Skip to content

Commit

Permalink
Added AST and parser support for types on variable declarations
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidTimms committed Jul 12, 2020
1 parent 2fc046c commit 8f78320
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 11 deletions.
4 changes: 3 additions & 1 deletion src/Parser.ts
Expand Up @@ -210,11 +210,13 @@ export default class Parser {
private varDeclaration(): Stmt {
const name = this.consume("IDENTIFIER", "Expect variable name.");

const type = this.match("COLON") ? this.typeExpr() : null;

const initializer = this.match("EQUAL") ? this.expression() : null;

this.consume("SEMICOLON", "Expect ';' after variable declaration");

return new VarStmt(name, initializer);
return new VarStmt(name, type, initializer);
}

private whileStatement(): Stmt {
Expand Down
1 change: 1 addition & 0 deletions src/Stmt.ts
Expand Up @@ -87,6 +87,7 @@ export class ReturnStmt {
export class VarStmt {
constructor(
readonly name: Token,
readonly type: TypeExpr | null,
readonly initializer: Expr | null,
) {}

Expand Down
28 changes: 18 additions & 10 deletions src/tool/generateAst.ts
Expand Up @@ -35,17 +35,25 @@ function main(args: string[]): void {

defineAst(outputDir, "Stmt", [
"Block -> statements: Stmt[]",
"Class -> name: Token, superclass: VariableExpr | null, " +
" methods: FunctionStmt[]",
`Class -> name: Token,
superclass: VariableExpr | null,
methods: FunctionStmt[]`,
"Expression -> expression: Expr",
"Function -> name: Token, params: Parameter[], " +
" returnType: TypeExpr | null, body: Stmt[]",
"If -> condition: Expr, thenBranch: Stmt, " +
" elseBranch: Stmt | null",
`Function -> name: Token,
params: Parameter[],
returnType: TypeExpr | null,
body: Stmt[]`,
`If -> condition: Expr,
thenBranch: Stmt,
elseBranch: Stmt | null`,
"Print -> expression: Expr",
"Return -> keyword: Token, value: Expr | null",
"Var -> name: Token, initializer: Expr | null",
"While -> condition: Expr, body: Stmt",
`Return -> keyword: Token,
value: Expr | null`,
`Var -> name: Token,
type: TypeExpr | null,
initializer: Expr | null`,
`While -> condition: Expr,
body: Stmt`,
]);

defineAst(outputDir, "TypeExpr", [
Expand Down Expand Up @@ -134,7 +142,7 @@ function parseClassDefinition(
): ClassDefinition {
const [classPrefix, fieldList] = definition.split("->").map(s => s.trim());
const className = classPrefix + baseName;
const fields = fieldList.split(", ").map(field => {
const fields = fieldList.split(",").map(field => {
const [name, typeList] = field.split(":").map(s => s.trim());
return {name, types: typeList.split("|").map(s => s.trim())};
});
Expand Down
1 change: 1 addition & 0 deletions tests/variablesAndScope/variableWithType.lox
@@ -0,0 +1 @@
var x: Number = 123;

0 comments on commit 8f78320

Please sign in to comment.