Skip to content

Commit

Permalink
perf(lexer): generate if statement instead of switch
Browse files Browse the repository at this point in the history
In itself, this won't make the lexer faster, but it is a precondition
for implementing subsequent optimization ideas listed in:

- #207
  • Loading branch information
wincent committed Aug 4, 2023
1 parent 7e70569 commit 68e72e8
Show file tree
Hide file tree
Showing 5 changed files with 1,003 additions and 1,075 deletions.
45 changes: 31 additions & 14 deletions packages/codegen/src/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,23 @@ type AssignmentStatement = {
type BinaryExpression = {
kind: 'BinaryExpression';
lexpr: Expression;
operator:
| '!='
| '!=='
| '&&'
| '<'
| '<='
| '=='
| '==='
| '>'
| '>='
| '||'
| '+';
operator: BinaryOperator;
rexpr: Expression;
};

type BinaryOperator =
| '!='
| '!=='
| '&&'
| '<'
| '<='
| '=='
| '==='
| '>'
| '>='
| '||'
| '+';

type BooleanValue = {
kind: 'BooleanValue';
value: boolean;
Expand All @@ -55,7 +57,14 @@ type ClassDeclaration = {
body: Array<MethodDefinition | PropertyDeclaration>;
};

type Consequent = {
// Better AST might be
// IfStatement
// Condition
// Consequent (Array<Statement>)
// Alternate (can be another IfStatement, for `else if`, or Array<Statement>,
// for `else`)
// The name "Consequent" sucks.
export type Consequent = {
kind: 'Consequent';
condition: Expression;
block: Array<Statement>;
Expand Down Expand Up @@ -325,7 +334,11 @@ const ast = {
}
},

binop(lexpr: Expression, operator: '<', rexpr: Expression): BinaryExpression {
binop(
lexpr: Expression,
operator: BinaryOperator,
rexpr: Expression,
): BinaryExpression {
return {
kind: 'BinaryExpression',
lexpr,
Expand Down Expand Up @@ -382,6 +395,10 @@ const ast = {
};
},

equals(lexpr: Expression, rexpr: Expression): BinaryExpression {
return ast.binop(lexpr, '===', rexpr);
},

expression(template: string): Expression {
if (/^\d+$/.test(template)) {
return ast.number(parseInt(template));
Expand Down
1 change: 1 addition & 0 deletions packages/codegen/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export {default as print} from './print';
export {default as quote} from './quote';

export type {
Consequent,
Expression,
IfStatement,
Program,
Expand Down
Loading

0 comments on commit 68e72e8

Please sign in to comment.