Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix circular grammar import stack overflow #3771

Merged
merged 2 commits into from
Jul 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,26 @@ public void testImportLeftRecursiveGrammar(@TempDir Path tempDir) {
assertEquals("", executedState.errors);
}

// ISSUE: https://github.com/antlr/antlr4/issues/2296
@Test
public void testCircularGrammarInclusion(@TempDir Path tempDir) {
String tempDirPath = tempDir.toString();
String g1 =
"grammar G1;\n" +
"import G2;\n" +
"r : 'R1';";

String g2 =
"grammar G2;\n" +
"import G1;\n" +
"r : 'R2';";

FileUtils.mkdir(tempDirPath);
writeFile(tempDirPath, "G1.g4", g1);
ExecutedState executedState = execParser("G2.g4", g2, "G2Parser", "G2Lexer", "r", "R2", debug, tempDir);
assertEquals("", executedState.errors);
}

private static void checkGrammarSemanticsWarning(ErrorQueue equeue, GrammarSemanticsMessage expectedMessage) {
ANTLRMessage foundMsg = null;
for (int i = 0; i < equeue.warnings.size(); i++) {
Expand Down
10 changes: 7 additions & 3 deletions tool/src/org/antlr/v4/tool/Grammar.java
Original file line number Diff line number Diff line change
Expand Up @@ -371,11 +371,15 @@ protected void initTokenSymbolTables() {
typeToTokenList.add(null);
}

public void loadImportedGrammars() {

public void loadImportedGrammars() {
this.loadImportedGrammars(new HashSet<>());
}

private void loadImportedGrammars(Set<String> visited) {
if ( ast==null ) return;
GrammarAST i = (GrammarAST)ast.getFirstChildWithType(ANTLRParser.IMPORT);
if ( i==null ) return;
Set<String> visited = new HashSet<>();
visited.add(this.name);
importedGrammars = new ArrayList<Grammar>();
for (Object c : i.getChildren()) {
Expand Down Expand Up @@ -407,7 +411,7 @@ else if ( t.getType()==ANTLRParser.ID ) {
if ( g == null ) continue;
g.parent = this;
importedGrammars.add(g);
g.loadImportedGrammars(); // recursively pursue any imports in this import
g.loadImportedGrammars(visited); // recursively pursue any imports in this import
}
}

Expand Down