diff --git a/tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg b/tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg index 2c62de203..02d8897e9 100644 --- a/tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg +++ b/tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg @@ -770,7 +770,7 @@ public \ T accept(ParseTreeVisitor\ visitor) { } >> -AttributeDecl(d) ::= " " +AttributeDecl(d) ::= " = " /** If we don't know location of label def x, use this template */ labelref(x) ::= "(()_localctx)." diff --git a/tool/src/org/antlr/v4/codegen/model/decl/AttributeDecl.java b/tool/src/org/antlr/v4/codegen/model/decl/AttributeDecl.java index 9732ab929..7b77ecd6e 100644 --- a/tool/src/org/antlr/v4/codegen/model/decl/AttributeDecl.java +++ b/tool/src/org/antlr/v4/codegen/model/decl/AttributeDecl.java @@ -36,8 +36,10 @@ import org.antlr.v4.tool.Attribute; /** */ public class AttributeDecl extends Decl { public String type; + public String initValue; public AttributeDecl(OutputModelFactory factory, Attribute a) { super(factory, a.name, a.decl); this.type = a.type; + this.initValue = a.initValue; } } diff --git a/tool/test/org/antlr/v4/test/TestParserExec.java b/tool/test/org/antlr/v4/test/TestParserExec.java index 21867a811..2102fd9bc 100644 --- a/tool/test/org/antlr/v4/test/TestParserExec.java +++ b/tool/test/org/antlr/v4/test/TestParserExec.java @@ -567,4 +567,31 @@ public class TestParserExec extends BaseTest { assertEquals("", found); assertNull(stderrDuringParse); } + + /** + * This is a regression test for antlr/antlr4#672 "Initialization failed in + * locals". + * https://github.com/antlr/antlr4/issues/672 + */ + @Test public void testAttributeValueInitialization() throws Exception { + String grammar = + "grammar Data; \n" + + "\n" + + "file : group+ EOF; \n" + + "\n" + + "group: INT sequence {System.out.println($sequence.values.size());} ; \n" + + "\n" + + "sequence returns [List values = new ArrayList()] \n" + + " locals[List localValues = new ArrayList()]\n" + + " : (INT {$localValues.add($INT.int);})* {$values.addAll($localValues);}\n" + + "; \n" + + "\n" + + "INT : [0-9]+ ; // match integers \n" + + "WS : [ \\t\\n\\r]+ -> skip ; // toss out all whitespace\n"; + + String input = "2 9 10 3 1 2 3"; + String found = execParser("Data.g4", grammar, "DataParser", "DataLexer", "file", input, false); + assertEquals("6\n", found); + assertNull(stderrDuringParse); + } }