Example usage for org.eclipse.jdt.core.dom MethodDeclaration getRoot

List of usage examples for org.eclipse.jdt.core.dom MethodDeclaration getRoot

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom MethodDeclaration getRoot.

Prototype

public final ASTNode getRoot() 

Source Link

Document

Returns the root node at or above this node; returns this node if it is a root.

Usage

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.JavaSyncUtils.java

License:Open Source License

/**
 * Generates a body for method and inserts a comment at first line in the body content.
 * <p>/* www .  j a  v a  2s  .  co m*/
 * Comments aren't created as child nodes if we parse a block string that contains comment lines. <br>
 * Hack made : <br>
 * <ul>
 *    <li>a new {@link Statement} is created and added to block node. Because we can't create comments as {@link ASTNode}
 * the statement is created as a {@link ReturnStatement}.
 *    <li>the statement will contain the comment code
 *    <li>because the return statement node created must return our code (and not return;), 
 * it must be stored in NodeInfoStore class found as private field in InternalASTRewrite found as private field in the root AST class.    * 
 *    <li>when {@link JavaSyncUtils#writeJavafile(CompilationUnit, IFile)} is called at the end of forward mechanism 
 * it invokes {@link CompilationUnit#rewrite(org.eclipse.jface.text.IDocument, java.util.Map)} that will replace the 
 * return statement code with our code based on what it finds in NodeInfoStore list.
 * </ul>
 * @param md - the {@link MethodDeclaration} that requires a new body block. 
 * @param blockString - the {@link String} that will form the block content.
 * @param commentString - the {@link String} that will form the line comment.
 * 
 * @author Cristina
 */
@SuppressWarnings("unchecked")
public static void generateBodyWithCommentForMethod(MethodDeclaration md, String blockString,
        String commentString) {
    // generate body content without comments
    generateBodyForMethod(md, blockString);

    // insert comment on first line
    try {
        // get rewriter field from AST
        Object rewriter = FlowerMPUtils.getPrivateField(AST.class, "rewriter", md.getRoot().getAST());
        Class<?> thisClass = Class.forName("org.eclipse.jdt.core.dom.InternalASTRewrite");
        // get nodeStore field from InternalASTRewrite
        Object nodestore = FlowerMPUtils.getPrivateField(thisClass, "nodeStore", rewriter);
        Class<?> nodeInfoStore = Class.forName("org.eclipse.jdt.internal.core.dom.rewrite.NodeInfoStore");

        // nodeStore.newPlaceholderNode(ASTNode.RETURN_STATEMENT)         
        Method newPlaceholderNode = nodeInfoStore.getDeclaredMethod("newPlaceholderNode", int.class);
        ASTNode placeholder = (ASTNode) newPlaceholderNode.invoke(nodestore, ASTNode.RETURN_STATEMENT);

        // nodestore.markAsStringPlaceholder(placeholder, commentString)
        Method markAsStringPlaceholder = nodeInfoStore.getDeclaredMethod("markAsStringPlaceholder",
                ASTNode.class, String.class);
        markAsStringPlaceholder.invoke(nodestore, placeholder, commentString);
        // add comment to body content
        md.getBody().statements().add(0, placeholder);
    } catch (Exception e) {
        // swallowed
    }
}

From source file:net.sf.j2s.core.astvisitors.ASTScriptVisitor.java

License:Open Source License

public boolean visit(MethodDeclaration node) {
    //      methodBuffer = new StringBuffer();
    if (getJ2STag(node, "@j2sIgnore") != null) {
        return false;
    }/*from   w  w  w  . ja va 2 s  .  com*/

    IMethodBinding mBinding = node.resolveBinding();
    if (Bindings.isMethodInvoking(mBinding, "net.sf.j2s.ajax.SimpleRPCRunnable", "ajaxRun")) {
        if (getJ2STag(node, "@j2sKeep") == null) {
            return false;
        }
    }
    String[] pipeMethods = new String[] { "pipeSetup", "pipeThrough", "through", "pipeMonitoring",
            "pipeMonitoringInterval", "pipeWaitClosingInterval", "setPipeHelper" };
    for (int i = 0; i < pipeMethods.length; i++) {
        if (Bindings.isMethodInvoking(mBinding, "net.sf.j2s.ajax.SimplePipeRunnable", pipeMethods[i])) {
            if (getJ2STag(node, "@j2sKeep") == null) {
                return false;
            }
        }
    }
    if (Bindings.isMethodInvoking(mBinding, "net.sf.j2s.ajax.CompoundPipeSession", "convert")) {
        if (getJ2STag(node, "@j2sKeep") == null) {
            return false;
        }
    }
    if (mBinding != null) {
        methodDeclareStack.push(mBinding.getKey());
    }

    if (node.getBody() == null) {
        /*
         * Abstract or native method
         */
        if (isMethodNativeIgnored(node)) {
            return false;
        }
    }
    /*
     * To skip those methods or constructors which are just overriding with
     * default super methods or constructors. 
     */
    Block body = node.getBody();
    boolean needToCheckArgs = false;
    List argsList = null;
    if (body != null && containsOnlySuperCall(body)) {
        List sts = body.statements();
        Object statement = sts.get(sts.size() - 1);
        if (statement instanceof ReturnStatement) {
            ReturnStatement ret = (ReturnStatement) statement;
            Expression exp = ret.getExpression();
            if (exp instanceof SuperMethodInvocation) {
                SuperMethodInvocation superRet = (SuperMethodInvocation) exp;
                if (superRet.getName().toString().equals(node.getName().toString())) {
                    // same method name
                    needToCheckArgs = true;
                    argsList = superRet.arguments();
                }
            }
        } else if (statement instanceof ExpressionStatement) {
            ExpressionStatement sttmt = (ExpressionStatement) statement;
            Expression exp = sttmt.getExpression();
            if (exp instanceof SuperMethodInvocation) {
                SuperMethodInvocation superRet = (SuperMethodInvocation) exp;
                if (superRet.getName().toString().equals(node.getName().toString())) {
                    // same method name
                    needToCheckArgs = true;
                    argsList = superRet.arguments();
                }
            }
        } else if (statement instanceof SuperConstructorInvocation) {
            SuperConstructorInvocation superConstructor = (SuperConstructorInvocation) statement;
            needToCheckArgs = true;
            argsList = superConstructor.arguments();
            if (argsList.size() == 0) {
                IMethodBinding constructorBinding = superConstructor.resolveConstructorBinding();
                ITypeBinding declaringClass = constructorBinding.getDeclaringClass();
                if ("java.lang.Object".equals(declaringClass.getQualifiedName())) {
                    needToCheckArgs = false;
                }
            }
        }
        //      } else if (node.isConstructor() && (body != null && body.statements().size() == 0)) {
        //         IMethodBinding superConstructorExisted = Bindings.findConstructorInHierarchy(mBinding.getDeclaringClass(), mBinding);
        //         if (superConstructorExisted != null) {
        //            needToCheckArgs = true;
        //            argsList = new ArrayList();
        //         }
    }
    if (needToCheckArgs) {
        List params = node.parameters();
        if (params.size() == argsList.size()) {
            // same parameters count
            boolean isOnlySuper = true;
            for (Iterator iter = params.iterator(), itr = argsList.iterator(); iter.hasNext();) {
                ASTNode astNode = (ASTNode) iter.next();
                ASTNode argNode = (ASTNode) itr.next();
                if (astNode instanceof SingleVariableDeclaration && argNode instanceof SimpleName) {
                    SingleVariableDeclaration varDecl = (SingleVariableDeclaration) astNode;
                    String paramID = varDecl.getName().getIdentifier();
                    String argID = ((SimpleName) argNode).getIdentifier();
                    if (!paramID.equals(argID)) {
                        // not with the same order, break out
                        isOnlySuper = false;
                        break;
                    }
                } else {
                    isOnlySuper = false;
                    break;
                }
            }
            if (isOnlySuper && getJ2STag(node, "@j2sKeep") == null) {
                return false;
            }
        }
    }
    if ((node.getModifiers() & Modifier.PRIVATE) != 0) {
        if (mBinding != null) {
            boolean isReferenced = MethodReferenceASTVisitor.checkReference(node.getRoot(), mBinding.getKey());
            if (!isReferenced && getJ2STag(node, "@j2sKeep") == null) {
                return false;
            }
        }
    }

    if (node.isConstructor()) {
        if (getJ2STag(node, "@j2sOverride") != null) {
            buffer.append("Clazz.overrideConstructor (");
        } else {
            buffer.append("Clazz.makeConstructor (");
        }
    } else {
        if ((node.getModifiers() & Modifier.STATIC) != 0) {
            /* replace full class name with short variable name */
            buffer.append("cla$$");
            //buffer.append(fullClassName);
            buffer.append(".");
            //buffer.append(methods[i].getName());
            node.getName().accept(this);
            buffer.append(" = ");
        }
        if (getJ2STag(node, "@j2sOverride") != null) {
            buffer.append("Clazz.overrideMethod (");
        } else {
            boolean isOK2AutoOverriding = canAutoOverride(node);
            if (isOK2AutoOverriding) {
                buffer.append("Clazz.overrideMethod (");
            } else {
                buffer.append("Clazz.defineMethod (");
            }
        }
    }
    /* replace full class name with short variable name */
    buffer.append("cla$$");

    if (node.isConstructor()) {
        buffer.append(", ");
    } else {
        buffer.append(", \"");
        String identifier = getJ2SName(node.getName());
        if (checkKeyworkViolation(identifier)) {
            buffer.append('$');
        }
        buffer.append(identifier);
        buffer.append("\", ");
    }
    buffer.append("\r\n");
    boolean isPrivate = (node.getModifiers() & Modifier.PRIVATE) != 0;
    if (isPrivate) {
        buffer.append("($fz = ");
    }
    buffer.append("function (");
    List parameters = node.parameters();
    visitList(parameters, ", ");
    buffer.append(") ");
    if (node.isConstructor()) {
        boolean isSuperCalled = false;
        List statements = node.getBody().statements();
        if (statements.size() > 0) {
            ASTNode firstStatement = (ASTNode) statements.get(0);
            if (firstStatement instanceof SuperConstructorInvocation
                    || firstStatement instanceof ConstructorInvocation) {
                isSuperCalled = true;
            }
        }
        if (getJ2STag(node, "@j2sIgnoreSuperConstructor") != null) {
            isSuperCalled = true;
        }
        boolean existedSuperClass = false;
        IMethodBinding binding = node.resolveBinding();
        if (binding != null) {
            ITypeBinding declaringClass = binding.getDeclaringClass();
            ITypeBinding superclass = declaringClass.getSuperclass();
            String qualifiedName = discardGenericType(superclass.getQualifiedName());
            existedSuperClass = superclass != null && !"java.lang.Object".equals(qualifiedName)
                    && !"java.lang.Enum".equals(qualifiedName);
        }
        if (!isSuperCalled && existedSuperClass) {
            buffer.append("{\r\n");
            buffer.append("Clazz.superConstructor (this, ");
            buffer.append(assureQualifiedName(shortenQualifiedName(getFullClassName())));
            boolean constructorVarargs = isConstructorVarargs(binding, true);
            if (constructorVarargs) {
                buffer.append(", [[]]);\r\n");
            } else {
                buffer.append(", []);\r\n");
            }
            boolean read = checkJ2STags(node, false);
            if (!read) {
                blockLevel++;
                visitList(statements, "");
                //buffer.append("}");
                endVisit(node.getBody());
            } else {
                buffer.append("}");
            }
        } else {
            boolean read = checkJ2STags(node, true);
            if (!read) {
                node.getBody().accept(this);
            }
        }
    } else if (node.getBody() == null) {
        blockLevel++;
        boolean read = checkJ2STags(node, true);
        if (!read) {
            buffer.append("{\r\n");
            visitNativeJavadoc(node.getJavadoc(), null, false);
            buffer.append("}");
        }
        List normalVars = ((ASTVariableVisitor) getAdaptable(ASTVariableVisitor.class)).normalVars;
        for (int i = normalVars.size() - 1; i >= 0; i--) {
            ASTFinalVariable var = (ASTFinalVariable) normalVars.get(i);
            if (var.blockLevel >= blockLevel) {
                normalVars.remove(i);
            }
        }
        blockLevel--;
    } else {
        boolean read = checkJ2STags(node, true);
        if (!read) {
            node.getBody().accept(this);
        }
    }
    if (isPrivate) {
        buffer.append(", $fz.isPrivate = true, $fz)");
    }
    if (parameters.size() != 0) {
        buffer.append(", \"");
        for (Iterator iter = parameters.iterator(); iter.hasNext();) {
            SingleVariableDeclaration element = (SingleVariableDeclaration) iter.next();
            boolean isArray = false;
            IBinding resolveBinding = element.getName().resolveBinding();
            if (resolveBinding instanceof IVariableBinding) {
                IVariableBinding varBinding = (IVariableBinding) resolveBinding;
                if (varBinding != null) {
                    isArray = varBinding.getType().isArray();
                    if (isArray) {
                        //buffer.append("Array");
                        buffer.append("~A");
                    }
                }
            }
            if (!isArray) {
                Type type = element.getType();
                if (type.isPrimitiveType()) {
                    PrimitiveType pType = (PrimitiveType) type;
                    if (pType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) {
                        buffer.append("~B"); // Boolean
                    } else if (pType.getPrimitiveTypeCode() == PrimitiveType.CHAR) {
                        buffer.append("~S"); // String for char
                    } else {
                        buffer.append("~N"); // Number
                    }
                } else if (type.isArrayType()) {
                    buffer.append("~A"); // Array
                } else {
                    ITypeBinding binding = type.resolveBinding();
                    if (binding != null) {
                        if (binding.isTypeVariable()) {
                            buffer.append("~O");
                        } else {
                            String name = binding.getQualifiedName();
                            name = shortenQualifiedName(name);
                            if ("String".equals(name)) {
                                buffer.append("~S");
                            } else if ("Object".equals(name)) {
                                buffer.append("~O");
                            } else {
                                buffer.append(name);
                            }
                        }
                    } else {
                        buffer.append(type);
                    }
                }
            }
            if (iter.hasNext()) {
                buffer.append(",");
            }
        }
        buffer.append("\"");
    }
    buffer.append(");\r\n");
    return false;
}

From source file:org.eclipse.wb.internal.core.utils.ast.AstNodeUtils.java

License:Open Source License

/**
 * @return {@link List} of {@link ClassInstanceCreation}'s of given constructor in this
 *         {@link CompilationUnit}.//from ww w . ja  v a2s  .c  o  m
 */
public static List<ClassInstanceCreation> getClassInstanceCreations(MethodDeclaration constructor) {
    final List<ClassInstanceCreation> creations = Lists.newArrayList();
    final IMethodBinding constructorBinding = getMethodBinding(constructor);
    constructor.getRoot().accept(new ASTVisitor() {
        @Override
        public void endVisit(ClassInstanceCreation node) {
            IMethodBinding creationBinding = getCreationBinding(node);
            if (creationBinding == constructorBinding) {
                creations.add(node);
            }
        }
    });
    return creations;
}