How to create FunctionCall statement with arguments and add in function

133 views Asked by At

I need to create FunctionCall statement like Utiliy.initialize("value") and add this in first line of every function of js file.

Below is the code using which I am trying to create FunctionCall

private FunctionCall getFunctionCall() {
        FunctionCall functionCall = new FunctionCall();
        Name name =  new Name();
        name.setIdentifier("initialize");
        functionCall.setTarget(name);
}

below is the code I am using to add in every functionNode

class FunctionVisitor implements NodeVisitor {
        @Override
        public boolean visit(AstNode node) {
             if (node.getClass() == FunctionNode.class) {
                FunctionNode fun = (FunctionNode) node;
                fun.addChildrenToFront(getFunctionCall());
            }
            return true;
        }

    }

Please suggest how I can create FunctionCall with arguments and how I can print created FunctionCall statement to test. Is there any tool available to view javascript nodes like java ASTVIEW viewer?

1

There are 1 answers

4
Dominik Kunicki On BEST ANSWER

You have to create StringLiteral as a argument and add it to functionCall, in othere case it could be NumberLiteral, ArrrayLiteral etc. (see: http://javadox.com/org.mozilla/rhino/1.7R4/org/mozilla/javascript/ast/AstNode.html)

private FunctionCall getFunctionCall() {
        FunctionCall functionCall = new FunctionCall();
        Name name =  new Name();
        name.setIdentifier("initialize");
        functionCall.setTarget(name);
        StringLiteral arg = new StringLiteral();
        arg.setValue("value");
        arg.setQuoteCharacter('"');
        functionCall.addArgument(arg);
        return functionCall;
}

class FunctionVisitor implements NodeVisitor {
        @Override
        public boolean visit(AstNode node) {
             if (node.getClass() == FunctionNode.class) {
                FunctionNode fun = (FunctionNode) node;
                if(fun.getName().equals("initialize")) //prevents infinit loop
                {
                     return true;
                }
                fun.getBody().addChildrenToFront(new EmptyStatement()); // adds ';', I don't know if required
                fun.getBody().addChildrenToFront(getFunctionCall());//no fun.addChildrenToFront
            }
            return true;
        }

    }

You can print every corect AstNode by toSource() method. I hope this will help.