I would have this problem :
Given this rules
defField: type VAR ( ',' VAR)* SEP ;
VAR : ('a'..'z'|'A'..'Z')+ ;
type: 'Number'|'String' ;
SEP : '\n'|';' ;
where I have to do is to associate a template with a rule “defField”, that returns the string that represents the xml-schema for the field, that is:
Number a,b,c ;-> "<xs:element name="a" type = "xs:Number"\>" ,also for b and c.
my problem is in * of Kleene, that is, how do I write the template to do what I described above in the light of the ‘*’ ??
Thanks you!!!
Collect all
VARtokens in ajava.util.Listby using the+=operator:Now
v(a List) contains allVAR‘s.Then pass
tandvas a parameter to a method in your StringTemplateGroup:where
defFieldSchema(...)must be declared in your StringTemplateGroup, which might look like (file: T.stg):The syntax for iterating over a collection is as follows:
Ans since
varsis aListcontainingCommonTokens‘s, I grabbed its.textattribute instead of relying on itstoString()method.Demo
Take the following grammar (file T.g):
which can be tested with the following class (file: Main.java):
As you will see when you run this class, it parses the input
"Number a,b,c;"and produces the following output:EDIT
To run the demo, make sure you have all of the following files in the same directory:
T.g(the combined grammar file)T.stg(the StringTemplateGroup file)antlr-3.3.jar(the latest stable ANTLR build as of this writing)Main.java(the test class)then execute to following commands from your OS’s shell/prompt (from the same directory all the files are in):
java -cp antlr-3.3.jar org.antlr.Tool T.g # generate the lexer & parser javac -cp antlr-3.3.jar *.java # compile all .java source files java -cp .:antlr-3.3.jar Main # run the main class (*nix) # or java -cp .;antlr-3.3.jar Main # run the main class (Windows)Probably not necessary to mention, but the
#including the text after it should not be a part of the commands: these are only comments to indicate what these commands are for.