Antlr中StringTemplate的使用
我会遇到这个问题: 给定这个规则
defField: type VAR ( ',' VAR)* SEP ;
VAR : ('a'..'z'|'A'..'Z')+ ;
type: 'Number'|'String' ;
SEP : '\n'|';' ;
,我要做的就是将模板与规则“defField”关联起来,该规则返回表示该字段的 xml 模式的字符串,即:
Number a,b,c ;-> "<xs:element name="a" type = "xs:Number"\>" ,also for b and c.
我的问题是在 Kleene 的 * 中,即如何做我编写模板是为了根据“*”执行上面描述的操作?
感谢您!!!
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!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
+=
运算符收集java.util.List
中的所有VAR
标记:现在
v
( List) 包含所有VAR
。然后将
t
和v
作为参数传递给 StringTemplateGroup 中的方法:其中必须在 StringTemplateGroup 中声明
defFieldSchema(...)
,可能看起来像(文件:T.stg):迭代集合的语法如下:
Ans,因为
vars
是一个List
包含CommonTokens
的,我获取了它的.text
属性,而不是依赖它的toString()
方法。演示
采用以下语法(文件Tg):
可以使用以下类进行测试(文件:Main.java):
正如您在运行此类时看到的那样,它解析输入
“Number a,b,c;”
并生成以下输出:编辑
要运行演示,请确保同一目录中具有以下所有文件:
Tg
(组合语法文件)T.stg
(StringTemplateGroup 文件)antlr-3.3.jar
(撰写本文时最新的稳定 ANTLR 版本)Main.java
(测试类)然后从操作系统的 shell/提示符(所有文件都在同一目录中)执行以下命令:
可能没有必要提及,但是
# 后面包含的文本不应成为命令的一部分:这些只是注释,用于指示这些命令的用途。
Collect all
VAR
tokens in ajava.util.List
by using the+=
operator:Now
v
(a List) contains allVAR
's.Then pass
t
andv
as 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
vars
is aList
containingCommonTokens
's, I grabbed its.text
attribute 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):
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.