From 4e6e7edf0ddb06523391c3e644a5c6cfb507518d Mon Sep 17 00:00:00 2001 From: parrt Date: Mon, 21 Nov 2016 13:45:05 -0800 Subject: [PATCH] Fixes #1317 --- .../antlr/v4/test/tool/TestCompositeGrammars.java | 14 +++++++++++++- tool/src/org/antlr/v4/tool/Grammar.java | 5 +++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/tool-testsuite/test/org/antlr/v4/test/tool/TestCompositeGrammars.java b/tool-testsuite/test/org/antlr/v4/test/tool/TestCompositeGrammars.java index 709be7a8a..b096ebad3 100644 --- a/tool-testsuite/test/org/antlr/v4/test/tool/TestCompositeGrammars.java +++ b/tool-testsuite/test/org/antlr/v4/test/tool/TestCompositeGrammars.java @@ -69,7 +69,19 @@ public class TestCompositeGrammars extends BaseJavaTest { "WS : (' '|'\\n') -> skip ;\n" ; writeFile(tmpdir, "M.g4", master); ErrorQueue equeue = antlr("M.g4", false, "-lib", subdir); - assertEquals(equeue.size(), 0); + assertEquals(0, equeue.size()); + } + + // Test for https://github.com/antlr/antlr4/issues/1317 + @Test public void testImportSelfLoop() throws Exception { + mkdir(tmpdir); + String master = + "grammar M;\n" + + "import M;\n" + + "s : 'a' ;\n"; + writeFile(tmpdir, "M.g4", master); + ErrorQueue equeue = antlr("M.g4", false, "-lib", tmpdir); + assertEquals(0, equeue.size()); } @Test public void testDelegatesSeeSameTokenType() throws Exception { diff --git a/tool/src/org/antlr/v4/tool/Grammar.java b/tool/src/org/antlr/v4/tool/Grammar.java index 4aec8ad05..65e736152 100644 --- a/tool/src/org/antlr/v4/tool/Grammar.java +++ b/tool/src/org/antlr/v4/tool/Grammar.java @@ -392,6 +392,8 @@ public class Grammar implements AttributeResolver { if ( ast==null ) return; GrammarAST i = (GrammarAST)ast.getFirstChildWithType(ANTLRParser.IMPORT); if ( i==null ) return; + Set visited = new HashSet<>(); + visited.add(this.name); importedGrammars = new ArrayList(); for (Object c : i.getChildren()) { GrammarAST t = (GrammarAST)c; @@ -403,6 +405,9 @@ public class Grammar implements AttributeResolver { else if ( t.getType()==ANTLRParser.ID ) { importedGrammarName = t.getText(); } + if ( visited.contains(importedGrammarName) ) { // ignore circular refs + continue; + } Grammar g; try { g = tool.loadImportedGrammar(this, t);