2
votes

I want to parse the sentence "i am looking for a java developer". The output I need is language=java.

I created a grammar file as follows.

grammar Job;

eval returns [String value]
    :    output=jobExp { $value = $output.text;}
    ;
jobExp returns [String value]
    :    ind=indro whitespace var1=language ' developer'  {$value = $var1.text;}
    ;

indro
    :
    'i am looking for a' |   'i am searching for a'
    ;

language :
    'java' | 'python' | 'cpp'
    ;

whitespace :
    (' '|'\t')+
    ;

Here, in rule language i am hard-coding a set of languages inside the grammar file itself. Is it possible to read the languages from a file and process the grammar accordingly ? Input file should be like this

languages.txt

 java
 python
 cpp

I am using antlr 4.5.1-1.

1
why would you want to do this in the grammar? why not parse language (in the example a single token as a string) and let the programme use the input file to check, if the language is supported or not? together with an action you can ensure this check from within your grammar.BeyelerStudios

1 Answers

1
votes

Not quite sure if this completely satisfies your question, but look into Composite Grammars:

https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Composite+Grammars

If you really need it to be in a file, consider creating a processing/build step from languages.txt to languages.grammar, and use languages.grammar as Composite.