简体   繁体   English

更改Java.g4语法文件

[英]Change Java.g4 grammar file

I need to get parameters of method declaration of java file. 我需要获取Java文件的方法声明的参数。 I am using JavaBaseListener interface and those method : 我正在使用JavaBaseListener接口和那些方法:

 @Override public Object visitMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { TokenStream tokens = parser.getTokenStream(); String type = "void"; if(ctx.type() != null) { type = tokens.getText(ctx.type().getSourceInterval()); } String args = tokens.getText(ctx.formalParameters()); System.out.println("\\t" + type + " " + ctx.Identifier() + args + ";"); return super.visitMethodDeclaration(ctx); } 

The problem is, that there are no white spaces between method name and method classname. 问题是,方法名称和方法类名称之间没有空格。 Input : private void addLoan(Loan loan) 输入:private void addLoan(贷款贷款)

Output : void addLoan(Loanloan); 输出:void addLoan(Loanloan);

I tried to change java.g4 grammar file, and added whitespace there 我试图更改java.g4语法文件,并在其中添加空格

formalParameter : variableModifier* type " " variableDeclaratorId ; formalParameter:variableModifier *类型“” variableDeclaratorId;

But now i have a lot of errors such as : 但是现在我有很多错误,例如:

line 1:6 no viable alternative at input 'public ' line 1:12 extraneous input ' ' expecting Identifier line 1:20 extraneous input ' ' expecting {'extends', 'implements', '{', '<'} line 2:5 no viable alternative at input 'List ' ... 第1行:6行在输入'public'上没有可行的替代方法第1行,第12行外来输入''期望标识符第1行第20行,外来输入''期望{'extends','implements','{','<'}第2行:5输入'List'处没有可行的选择...

What is the best solution for my problem and how can i handle it? 解决我的问题的最佳方法是什么?如何解决? Thanks in forward 谢谢前进

In the java8 grammar found in this repository , the WS rule 此存储库中找到的java8语法WS规则

WS  :  [ \t\r\n\u000C]+ -> skip

throws the white space away ( -> skip ). 扔掉空白( -> skip )。

Using the small grammar in this answer , you can see the difference between -> skip and -> channel(HIDDEN) . 使用此答案中的小语法,您可以看到-> skip-> channel(HIDDEN)之间的区别。

With WS : [ \\t] -> channel(HIDDEN) ; 使用WS : [ \\t] -> channel(HIDDEN) ; the output is 输出是

Expression found : 3 + 4

With WS : [ \\t] -> skip ; 使用WS : [ \\t] -> skip ; the output is 输出是

Expression found : 3+4

Using the command 使用命令

$ grun Question question -tokens -diagnostics input.txt 

you can see that in the first case the WS tokens appear in the list of tokens, whereas they disappear in the second case. 您可以看到,在第一种情况下, WS令牌出现在令牌列表中,而在第二种情况下它们消失了。

This other example clearly shows that getText() depends on it : paydeltaco98 versus pay delta co 98 . 这个其他示例清楚地表明getText()依赖paydeltaco98paydeltaco98pay delta co 98

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM