antlr / antlr4

ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.
http://antlr.org
BSD 3-Clause "New" or "Revised" License
17.22k stars 3.29k forks source link

javscript target: actions - non-local attribute references - wrong code generated #1744

Open v-leon opened 7 years ago

v-leon commented 7 years ago

When referencing non-local attributes within an action, the generated code is wrong. The getInvokingContext method is called without "this." in front.

Here is an example grammar:

start
    locals [ Object all]
:a b;
a: 'a' {$start::all = [];};
b: 'b' {$start::all.push(1);};
v-leon commented 7 years ago

Proposed solution - add "this." in front of getInvokingContext.

diff --git a/tool/resources/org/antlr/v4/tool/templates/codegen/JavaScript/JavaScript.stg b/tool/resources/org/antlr/v4/tool/templates/codegen/JavaScript/JavaScript.stg
index 2e10728..2bac718 100644
--- a/tool/resources/org/antlr/v4/tool/templates/codegen/JavaScript/JavaScript.stg
+++ b/tool/resources/org/antlr/v4/tool/templates/codegen/JavaScript/JavaScript.stg
@@ -597,8 +597,8 @@ ThisRulePropertyRef_text(r)  ::= "this._input.getText(new antlr4.Interval(localc
 ThisRulePropertyRef_ctx(r)      ::= "localctx"
 ThisRulePropertyRef_parser(r)   ::= "this"

-NonLocalAttrRef(s)                      ::= "getInvokingContext(<s.ruleIndex>).<s.name>"
-SetNonLocalAttr(s, rhsChunks)  ::= "getInvokingContext(<s.ruleIndex>).<s.name> = <rhsChunks>"
+NonLocalAttrRef(s)                      ::= "this.getInvokingContext(<s.ruleIndex>).<s.name>"
+SetNonLocalAttr(s, rhsChunks)  ::= "this.getInvokingContext(<s.ruleIndex>).<s.name> = <rhsChunks>"

 AddToLabelList(a) ::= "<ctx(a.label)>.<a.listName>.push(<labelref(a.label)>);"
ericvergnaud commented 7 years ago

Hi, thanks for this. Can you submit a PR so we can understand how this would behave? Eric