0
votes

I need to get parameters of method declaration of java file. I am using JavaBaseListener interface and those method :

@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)

Output : void addLoan(Loanloan);

I tried to change java.g4 grammar file, and added whitespace there

formalParameter : variableModifier* type " " 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 ' ...

What is the best solution for my problem and how can i handle it? Thanks in forward

1
p.s. maybe someone has a good javabasevisitor usage example/tutorial, cause i didn't find anythingAnton Barinov
There is a visitor example in chapter 25-26 of The ANTLR mega tutorial.BernardK

1 Answers

0
votes

In the java8 grammar found in this repository, the WS rule

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

throws the white space away (-> skip).

Using the small grammar in this answer, you can see the difference between -> skip and -> channel(HIDDEN).

With WS : [ \t] -> channel(HIDDEN) ; the output is

Expression found : 3 + 4

With 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.

This other example clearly shows that getText() depends on it : paydeltaco98versus pay delta co 98.