1

I am trying to find hardcoded string assignment statements in Java. I am trying to use antlr or javaparser but am not getting how to find assignment statements?

Javaparser seems a good way to go. It has support for declarations etc. I am trying to find variable declarations etc but not assignment statements. How can I use that to find assignment statement where a string literal is assigned to a variable.

user3565529
  • 1,317
  • 2
  • 14
  • 24

2 Answers2

1

Here's an approach I used.

  • Generate a visual AST of a sample Java file, e.g., one with the hard-coded expression you're looking for. JavaParser can output DOT files (e.g., blog entry) and that's a great way to spot the nodes in the AST you're interested in.
  • I saw from my visualization that the nodes I was interested in were VariableDeclarator with an initializer, so I followed the example of using the VoidVisitorAdapter and overrode the corresponding visit method. A good IDE (IntelliJ) helped me with the rest:

    public void visit(VariableDeclarator variableDeclarator, Void arg) {
        super.visit(variableDeclarator, arg);
        variableDeclarator.getInitializer().ifPresent(expression -> {
            expression.ifStringLiteralExpr(stringLiteralExpr -> {/* do something */})
    }
    
Fuhrmanator
  • 11,459
  • 6
  • 62
  • 111
0

I would try create a listener; listen to the assignment statement (line 1196 in Java8.g4) by overwriting the appropriate method, e.g.:

    public override void ExitAssignment(Java8Parser.AssignmentContext context);  // C#

Check the context passed whether
• the assignmentOperator is something that could apply to strings (=, +=)
• and if expression resolves to something like CharacterLiteral or StringLiteral

You get the information via the methods context.assignmentOperator() and context.expression().