tunnelvisionlabs / antlr4ts

Optimized TypeScript target for ANTLR 4
Other
624 stars 106 forks source link

Rule numbers: constants vs static members #472

Open BurtHarris opened 4 years ago

BurtHarris commented 4 years ago

In ActionExpr.g4, I've got the following:

expr
    returns[v: number]:
    a = expr op = ('*' | '/') b = expr {
                                   if ( $op.type==MUL ) $v = $a.v * $b.v;
                                   else $v = $a.v / $b.v;
                                   }
    | a = expr op = ('+' | '-') b = expr {
                                   if ( $op.type==ADD ) $v = $a.v + $b.v;
                                   else $v = $a.v - $b.v;
                                   }
    | INT {$v = Number.parseInt($INT.text,10);}
    | ID {$v = this.memory[$ID.text];}
    | '(' e = expr ')' {$v = $e.v;};

MUL: '*'; // assigns token name to '*' used above in grammar
DIV: '/';
ADD: '+';
SUB: '-';

The generated code from is flagged by Typescript on the naked MULand ADDin the actions, suggesting "Cannot find name 'ADD'. Did you mean the static member 'ActionExprParser.ADD'?"

We might make actions including this sort of code work by declaring constants for ADD and MUL in the outermost scope of the generated parser, or perhaps even a const enum (with a consistant name!)

BurtHarris commented 4 years ago

Workaround in .g4 file:

stat:
    expr NEWLINE {console.log($expr.v);}
    | ID '=' expr NEWLINE { this.memory[$ID.text as string] = $expr.v; }
    | NEWLINE;