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.12k stars 3.28k forks source link

problem in access to variable with same name in Semantic actions #2692

Open mmasomi73 opened 4 years ago

mmasomi73 commented 4 years ago

Hi i have a problem in access to variable that have same name, for example:

term: term ('*'|'/')factor {print($term.text);}| factor;

take this error missing attribute access on rule reference term in $term how to fix this problem?

ericvergnaud commented 4 years ago

Hi the place for support is the google discussion group

Le 30 nov. 2019 à 01:24, meysam notifications@github.com a écrit :

Hi i have a problem in access to variable that have same name, for example:

term: term ('*'|'/')factor {print($term.text);}| factor;

take this error missing attribute access on rule reference term in $term how to fix this problem?

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/antlr/antlr4/issues/2692?email_source=notifications&email_token=AAZNQJGNPAWRCUSWTU2WZULQWFF6HA5CNFSM4JTCAGFKYY3PNVWWK3TUL52HS4DFUVEXG43VMWVGG33NNVSW45C7NFSM4H454XLQ, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAZNQJHIE5ZTQ4KC7AXNIU3QWFF6HANCNFSM4JTCAGFA.

sharwell commented 4 years ago

I would have expected this to be fixed by #630 for ANTLR 4.3.

@mmasomi73 do you know what version you are using?

mmasomi73 commented 4 years ago

ANTRL 4.7.2

sharwell commented 4 years ago

@mmasomi73 Can you post a complete grammar that produces this result? If your full grammar cannot be public, then a constructed sample grammar would work.

mmasomi73 commented 4 years ago

if this sample code has work, my main grammar can work,

`grammar Expr;

@parser::members{ int temp = 0; String newTemp(){ return "t"+ ++temp; } void print(String s){ System.out.println(s); } }

prog: ID '=' expr EOF;

expr returns [String t,String op]: e=expr ('+'{$op = "+";}|'-'{$op = "-";}) term { print($expr.text+"|"+$e.text);} | term; term returns [String t,String op]: term ('*'|'/')factor | factor; factor:'('expr')'|ID|NUM;

NUM : [0-9]+ ; ID: [a-zA-Z]+ ; WS : [ \t\r\n]+ -> skip;`

i need to access left and right value of expr

sharwell commented 4 years ago

The issue occurs in this line:

{ print($expr.text+"|"+$e.text);} | term;

You cannot reference the containing rule by its name (it has a special reserved name $ctx), so you need to change this action to the following:

-{ print($expr.text+"|"+$e.text);} | term;
+{ print($ctx.text+"|"+$e.text);} | term;