ANTLR4 does not find grammar on import
Asked Answered
B

1

3

I am trying to split my ANTLR4 grammar in multiple files so i can test them more easily, i am using gradle as a build tool in a java project.

Both grammar compile correctly by separate but when i add the import to my main grammar i get the next compilation error

error(110): kanekotic/specflow/rider/SpecflowFeature.g4:3:7: can't find or load grammar SpecflowScenario

the inherited grammar looks like:

grammar SpecflowScenario;

@header {
    package kanekotic.specflow.rider;
}

scenario
    : 'Scenario: ';

and the main grammar looks like:

grammar SpecflowFeature;

import SpecflowScenario;

@header {
    package kanekotic.specflow.rider;
}

file returns [List<String> values]
    @init { $values = new ArrayList<String>(); }
    : 'Feature: ' EOF;

What am i doing wrong? is this not allowed?

edit:

the gradle.build looks like:

plugins {
    id "org.jetbrains.intellij" version "0.1.10"
}

apply plugin: 'org.jetbrains.intellij'
apply plugin: 'java'
apply plugin: 'antlr'

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8

intellij {
    version '143.2370.31'
    pluginName 'Specflow Rider'
}

group 'kanekotic.specflow.rider'
version '0.1'

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    antlr "org.antlr:antlr4:4.5"
    testCompile 'junit:junit:4.12'
    testCompile "org.mockito:mockito-core:2.+"
} 

all the code as it is open sourced is in this next link: https://github.com/kanekotic/Specflow.Rider/tree/antlr4_multiple_grammar

Butyrin answered 3/9, 2017 at 16:36 Comment(2)
Do you have the grammar in the file SpecflowScenario.g4 in the same folder? Maybe also post the part of your gradle file.Dust
@Dust thanks for your response, yes they are at the same directory and my gradle you can see on the edit. also added the repo as its open source.Butyrin
D
5

The Antlr plugin uses src/main/antlr as lib directory by default. As the grammar file to include is in kanekotic/specflow/rider, use the following code in your gradle file to include this location:

generateGrammarSource {
    arguments << "-lib" << "src/main/antlr/kanekotic/specflow/rider"
}

See also this gradle thread.

Dust answered 4/9, 2017 at 7:21 Comment(2)
thanks for actually pointing me towards the solution. I will accept it with a small change due files are not in src/main/antlr but in 'src/main/antlr/kanekotic/specflow/rider' so probably the answer should be 'src/main/antlr/<grammar path>', and also I believe that src/main/antlr is the default lib path as if moved to the root it actually worked.Butyrin
Thanks for pointing that out! I edited my answer accordingly.Dust

© 2022 - 2024 — McMap. All rights reserved.