is it possible to invoke a rule from a different grammar?
the purpose is to have two languages in the same file, the second language starting by an (begin ...) where ... is in the second language. the grammar should invoke another grammar to parse that second language.
for example:
grammar A;
start_rule
: '(' 'begin' B.program ')' //or something like that
;
grammar B;
program
: something* EOF
;
something
: ...
;
Your question could be interpreted in (at least) two ways:
I assume it's the first, in which case you can import grammars.
A demo for option 1:
file: L.g
file: Sub.g
file: Root.g
file: Main.java
Run the demo:
which will print:
to the console.
More info, see: http://www.antlr.org/wiki/display/ANTLR3/Composite+Grammars
A demo for option 2:
A nice example of a language inside a language is regex. You have the "normal" regex language with its meta characters, but there's another one in it: the language that describes a character set (or character class).
Instead of accounting for the meta characters of a character set (range
-
, negation^
, etc.) inside your regex-grammar, you could simply consider a character set as a single token consisting of a[
and then everything up to and including]
(with possibly\]
in it!) inside your regex-grammar. When you then stumble upon aCharSet
token in one of your parser rules, you invoke the CharSet-parser.file: Regex.g
file: CharSet.g
file: Main.java
And if you run the main class, you will see the DOT output for the regex
((xyz)*[^\\da-f])foo
which is the following tree:The magic is inside the
Regex.g
grammar in theatom
rule where I inserted a tree node in a rewrite rule by invoking the staticast
method from theCharSetParser
class:Note that inside such rewrite rules, there must not be a semi colon! So, this would be wrong:
{CharSetParser.ast($CharSet.text);}
.EDIT
And here's how to create tree walkers for both grammars:
file: RegexWalker.g
file: CharSetWalker.g
Main.java
To run the demo, do:
which will print: