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

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

Introduction

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

Prototype

ASTNode.NodeList thrownExceptionTypes

To view the source code for org.eclipse.jdt.core.dom MethodDeclaration thrownExceptionTypes.

Click Source Link

Document

The list of thrown exception Types (element type: Type ).

Usage

From source file:at.bestsolution.fxide.jdt.corext.dom.ASTFlattener.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration node) {
    if (node.getJavadoc() != null) {
        node.getJavadoc().accept(this);
    }//from   w ww  .j ava2  s .  c  om
    if (node.getAST().apiLevel() >= JLS3) {
        printModifiers(node.modifiers());
        if (!node.typeParameters().isEmpty()) {
            this.fBuffer.append("<");//$NON-NLS-1$
            for (Iterator<TypeParameter> it = node.typeParameters().iterator(); it.hasNext();) {
                TypeParameter t = it.next();
                t.accept(this);
                if (it.hasNext()) {
                    this.fBuffer.append(", ");//$NON-NLS-1$
                }
            }
            this.fBuffer.append("> ");//$NON-NLS-1$
        }
    }
    if (!node.isConstructor()) {
        if (node.getReturnType2() != null) {
            node.getReturnType2().accept(this);
        } else {
            // methods really ought to have a return type
            this.fBuffer.append("void");//$NON-NLS-1$
        }
        this.fBuffer.append(" ");//$NON-NLS-1$
    }
    node.getName().accept(this);
    this.fBuffer.append("(");//$NON-NLS-1$
    if (node.getAST().apiLevel() >= AST.JLS8) {
        Type receiverType = node.getReceiverType();
        if (receiverType != null) {
            receiverType.accept(this);
            this.fBuffer.append(' ');
            SimpleName qualifier = node.getReceiverQualifier();
            if (qualifier != null) {
                qualifier.accept(this);
                this.fBuffer.append('.');
            }
            this.fBuffer.append("this"); //$NON-NLS-1$
            if (node.parameters().size() > 0) {
                this.fBuffer.append(',');
            }
        }
    }
    for (Iterator<SingleVariableDeclaration> it = node.parameters().iterator(); it.hasNext();) {
        SingleVariableDeclaration v = it.next();
        v.accept(this);
        if (it.hasNext()) {
            this.fBuffer.append(", ");//$NON-NLS-1$
        }
    }
    this.fBuffer.append(")");//$NON-NLS-1$
    if (node.getAST().apiLevel() >= AST.JLS8) {
        List<Dimension> dimensions = node.extraDimensions();
        for (Iterator<Dimension> it = dimensions.iterator(); it.hasNext();) {
            Dimension e = it.next();
            e.accept(this);
        }
    } else {
        for (int i = 0; i < node.getExtraDimensions(); i++) {
            this.fBuffer.append("[]"); //$NON-NLS-1$
        }
    }
    List<? extends ASTNode> thrownExceptions = node.getAST().apiLevel() >= AST.JLS8
            ? node.thrownExceptionTypes()
            : getThrownExceptions(node);
    if (!thrownExceptions.isEmpty()) {
        this.fBuffer.append(" throws ");//$NON-NLS-1$
        for (Iterator<? extends ASTNode> it = thrownExceptions.iterator(); it.hasNext();) {
            ASTNode n = it.next();
            n.accept(this);
            if (it.hasNext()) {
                this.fBuffer.append(", ");//$NON-NLS-1$
            }
        }
        this.fBuffer.append(" ");//$NON-NLS-1$
    }
    if (node.getBody() == null) {
        this.fBuffer.append(";");//$NON-NLS-1$
    } else {
        node.getBody().accept(this);
    }
    return false;
}

From source file:boa.datagen.util.Java8Visitor.java

License:Apache License

@Override
public boolean visit(MethodDeclaration node) {
    List<boa.types.Ast.Method> list = methods.peek();
    Method.Builder b = Method.newBuilder();
    //      b.setPosition(pos.build());
    if (node.isConstructor())
        b.setName("<init>");
    else//from   w w  w .  ja v  a 2 s.  co  m
        b.setName(node.getName().getFullyQualifiedName());
    for (Object m : node.modifiers()) {
        if (((IExtendedModifier) m).isAnnotation())
            ((Annotation) m).accept(this);
        else
            ((org.eclipse.jdt.core.dom.Modifier) m).accept(this);
        b.addModifiers(modifiers.pop());
    }
    boa.types.Ast.Type.Builder tb = boa.types.Ast.Type.newBuilder();
    if (node.getReturnType2() != null) {
        String name = typeName(node.getReturnType2());
        // FIXME JLS8: Deprecated getExtraDimensions() and added extraDimensions()
        for (int i = 0; i < node.getExtraDimensions(); i++)
            name += "[]";
        tb.setName(getIndex(name));
        tb.setKind(boa.types.Ast.TypeKind.OTHER);
        b.setReturnType(tb.build());
    } else {
        tb.setName(getIndex("void"));
        tb.setKind(boa.types.Ast.TypeKind.OTHER);
        b.setReturnType(tb.build());
    }
    for (Object t : node.typeParameters()) {
        boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder();
        String name = ((TypeParameter) t).getName().getFullyQualifiedName();
        String bounds = "";
        for (Object o : ((TypeParameter) t).typeBounds()) {
            if (bounds.length() > 0)
                bounds += " & ";
            bounds += typeName((org.eclipse.jdt.core.dom.Type) o);
        }
        if (bounds.length() > 0)
            name = name + " extends " + bounds;
        tp.setName(getIndex(name));
        tp.setKind(boa.types.Ast.TypeKind.GENERIC);
        b.addGenericParameters(tp.build());
    }
    if (node.getReceiverType() != null) {
        Variable.Builder vb = Variable.newBuilder();
        //         vb.setPosition(pos.build()); // FIXME
        vb.setName("this");
        boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder();
        String name = typeName(node.getReceiverType());
        if (node.getReceiverQualifier() != null)
            name = node.getReceiverQualifier().getFullyQualifiedName() + "." + name;
        tp.setName(getIndex(name));
        tp.setKind(boa.types.Ast.TypeKind.OTHER); // FIXME change to receiver? or something?
        vb.setVariableType(tp.build());
        b.addArguments(vb.build());
    }
    for (Object o : node.parameters()) {
        SingleVariableDeclaration ex = (SingleVariableDeclaration) o;
        Variable.Builder vb = Variable.newBuilder();
        //         vb.setPosition(pos.build()); // FIXME
        vb.setName(ex.getName().getFullyQualifiedName());
        for (Object m : ex.modifiers()) {
            if (((IExtendedModifier) m).isAnnotation())
                ((Annotation) m).accept(this);
            else
                ((org.eclipse.jdt.core.dom.Modifier) m).accept(this);
            vb.addModifiers(modifiers.pop());
        }
        boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder();
        String name = typeName(ex.getType());
        // FIXME JLS8: Deprecated getExtraDimensions() and added extraDimensions()
        for (int i = 0; i < ex.getExtraDimensions(); i++)
            name += "[]";
        if (ex.isVarargs())
            name += "...";
        tp.setName(getIndex(name));
        tp.setKind(boa.types.Ast.TypeKind.OTHER);
        vb.setVariableType(tp.build());
        if (ex.getInitializer() != null) {
            ex.getInitializer().accept(this);
            vb.setInitializer(expressions.pop());
        }
        b.addArguments(vb.build());
    }
    for (Object o : node.thrownExceptionTypes()) {
        boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder();
        tb.setName(getIndex(typeName((org.eclipse.jdt.core.dom.Type) o)));
        tp.setKind(boa.types.Ast.TypeKind.CLASS);
        b.addExceptionTypes(tp.build());
    }
    if (node.getBody() != null) {
        statements.push(new ArrayList<boa.types.Ast.Statement>());
        node.getBody().accept(this);
        for (boa.types.Ast.Statement s : statements.pop())
            b.addStatements(s);
    }
    list.add(b.build());
    return false;
}

From source file:com.bsiag.eclipse.jdt.java.formatter.linewrap.WrapPreparator.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration node) {
    List<SingleVariableDeclaration> parameters = node.parameters();
    Type receiverType = node.getReceiverType();
    if (!parameters.isEmpty() || receiverType != null) {
        if (receiverType != null)
            this.wrapIndexes.add(this.tm.firstIndexIn(receiverType, -1));
        int wrappingOption = node.isConstructor()
                ? this.options.alignment_for_parameters_in_constructor_declaration
                : this.options.alignment_for_parameters_in_method_declaration;
        this.wrapGroupEnd = this.tm
                .lastIndexIn(parameters.isEmpty() ? receiverType : parameters.get(parameters.size() - 1), -1);
        handleArguments(parameters, wrappingOption);
    }/*  w  w  w.j  a  v a2 s. c  om*/

    List<Type> exceptionTypes = node.thrownExceptionTypes();
    if (!exceptionTypes.isEmpty()) {
        this.wrapParentIndex = this.tm.firstIndexBefore(exceptionTypes.get(0), TokenNameRPAREN);
        this.wrapGroupEnd = this.tm.lastIndexIn(exceptionTypes.get(exceptionTypes.size() - 1), -1);
        int wrappingOption = node.isConstructor()
                ? this.options.alignment_for_throws_clause_in_constructor_declaration
                : this.options.alignment_for_throws_clause_in_method_declaration;
        for (Type exceptionType : exceptionTypes)
            this.wrapIndexes.add(this.tm.firstIndexIn(exceptionType, -1));
        // instead of the first exception type, wrap the "throws" token
        this.wrapIndexes.set(0, this.tm.firstIndexBefore(exceptionTypes.get(0), TokenNamethrows));
        handleWrap(wrappingOption, 0.5f);
    }

    if (!node.isConstructor()) {
        this.wrapParentIndex = this.tm.findFirstTokenInLine(this.tm.firstIndexIn(node.getName(), -1));
        List<TypeParameter> typeParameters = node.typeParameters();
        if (!typeParameters.isEmpty())
            this.wrapIndexes.add(this.tm.firstIndexIn(typeParameters.get(0), -1));
        if (node.getReturnType2() != null) {
            int returTypeIndex = this.tm.firstIndexIn(node.getReturnType2(), -1);
            if (returTypeIndex != this.wrapParentIndex)
                this.wrapIndexes.add(returTypeIndex);
        }
        this.wrapIndexes.add(this.tm.firstIndexIn(node.getName(), -1));
        this.wrapGroupEnd = this.tm.lastIndexIn(node.getName(), -1);
        handleWrap(this.options.alignment_for_method_declaration);
    }
    return true;
}

From source file:com.bsiag.eclipse.jdt.java.formatter.SpacePreparator.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration node) {
    handleToken(node.getName(), TokenNameIdentifier, true, false);

    boolean spaceBeforeOpenParen = node.isConstructor()
            ? this.options.insert_space_before_opening_paren_in_constructor_declaration
            : this.options.insert_space_before_opening_paren_in_method_declaration;
    boolean spaceAfterOpenParen = node.isConstructor()
            ? this.options.insert_space_after_opening_paren_in_constructor_declaration
            : this.options.insert_space_after_opening_paren_in_method_declaration;
    boolean spaceBetweenEmptyParens = node.isConstructor()
            ? this.options.insert_space_between_empty_parens_in_constructor_declaration
            : this.options.insert_space_between_empty_parens_in_method_declaration;
    if (handleEmptyParens(node.getName(), spaceBetweenEmptyParens)) {
        handleToken(node.getName(), TokenNameLPAREN, spaceBeforeOpenParen, false);
    } else {//from  w w w  .  java 2  s. c om
        handleToken(node.getName(), TokenNameLPAREN, spaceBeforeOpenParen, spaceAfterOpenParen);

        boolean spaceBeforeCloseParen = node.isConstructor()
                ? this.options.insert_space_before_closing_paren_in_constructor_declaration
                : this.options.insert_space_before_closing_paren_in_method_declaration;
        handleTokenBefore(node.getBody(), TokenNameRPAREN, spaceBeforeCloseParen, false);
    }

    if ((node.isConstructor() ? this.options.insert_space_before_opening_brace_in_constructor_declaration
            : this.options.insert_space_before_opening_brace_in_method_declaration) && node.getBody() != null)
        this.tm.firstTokenIn(node.getBody(), TokenNameLBRACE).spaceBefore();

    boolean beforeComma = node.isConstructor()
            ? this.options.insert_space_before_comma_in_constructor_declaration_parameters
            : this.options.insert_space_before_comma_in_method_declaration_parameters;
    boolean afterComma = node.isConstructor()
            ? this.options.insert_space_after_comma_in_constructor_declaration_parameters
            : this.options.insert_space_after_comma_in_method_declaration_parameters;
    handleCommas(node.parameters(), beforeComma, afterComma);

    List<Type> thrownExceptionTypes = node.thrownExceptionTypes();
    if (!thrownExceptionTypes.isEmpty()) {
        this.tm.firstTokenBefore(thrownExceptionTypes.get(0), TokenNamethrows).spaceBefore();

        beforeComma = node.isConstructor()
                ? this.options.insert_space_before_comma_in_constructor_declaration_throws
                : this.options.insert_space_before_comma_in_method_declaration_throws;
        afterComma = node.isConstructor()
                ? this.options.insert_space_after_comma_in_constructor_declaration_throws
                : this.options.insert_space_after_comma_in_method_declaration_throws;
        handleCommas(thrownExceptionTypes, beforeComma, afterComma);
    }

    List<TypeParameter> typeParameters = node.typeParameters();
    if (!typeParameters.isEmpty()) {
        handleTypeParameters(typeParameters);
        handleTokenBefore(typeParameters.get(0), TokenNameLESS, true, false);
        handleTokenAfter(typeParameters.get(typeParameters.size() - 1), TokenNameGREATER, false, true);
    }
    return true;
}

From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java

License:Apache License

/** Visitor method for {@link MethodDeclaration}s. */
@Override//from   w w  w .ja  v  a  2s .  c o  m
public boolean visit(MethodDeclaration node) {
    sync(node);
    visitAndBreakModifiers(node.modifiers(), Direction.VERTICAL, Optional.<BreakTag>absent());

    builder.open(plusFour);
    {
        BreakTag breakBeforeName = genSym();
        BreakTag breakBeforeType = genSym();
        builder.open(ZERO);
        {
            boolean first = true;
            if (!node.typeParameters().isEmpty()) {
                visitTypeParameters(node.typeParameters(), ZERO, BreakOrNot.NO);
                first = false;
            }

            boolean openedNameAndTypeScope = false;
            // constructor-like declarations that don't match the name of the enclosing class are 
            // parsed as method declarations with a null return type
            if (!node.isConstructor() && node.getReturnType2() != null) {
                if (!first) {
                    builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO, Optional.of(breakBeforeType));
                } else {
                    first = false;
                }
                if (!openedNameAndTypeScope) {
                    builder.open(Indent.If.make(breakBeforeType, plusFour, ZERO));
                    openedNameAndTypeScope = true;
                }
                node.getReturnType2().accept(this);
            }
            if (!first) {
                builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO, Optional.of(breakBeforeName));
            } else {
                first = false;
            }
            if (!openedNameAndTypeScope) {
                builder.open(ZERO);
                openedNameAndTypeScope = true;
            }
            visit(node.getName());
            token("(");
            // end of name and type scope
            builder.close();
        }
        builder.close();

        builder.open(Indent.If.make(breakBeforeName, plusFour, ZERO));
        builder.open(Indent.If.make(breakBeforeType, plusFour, ZERO));
        builder.open(ZERO);
        {
            if (!node.parameters().isEmpty() || node.getReceiverType() != null) {
                // Break before args.
                builder.breakToFill("");
                visitFormals(node, Optional.fromNullable(node.getReceiverType()), node.getReceiverQualifier(),
                        node.parameters());
            }
            token(")");
            extraDimensions(plusFour, node.extraDimensions());
            if (!node.thrownExceptionTypes().isEmpty()) {
                builder.breakToFill(" ");
                builder.open(plusFour);
                {
                    visitThrowsClause(node.thrownExceptionTypes());
                }
                builder.close();
            }
        }
        builder.close();
        builder.close();
        builder.close();
    }
    builder.close();

    if (node.getBody() == null) {
        token(";");
    } else {
        builder.space();
        visitBlock(node.getBody(), CollapseEmptyOrNot.YES, AllowLeadingBlankLine.YES,
                AllowTrailingBlankLine.NO);
    }
    builder.guessToken(";");

    return false;
}

From source file:ctrus.pa.bow.java.token.MethodTokens.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void addTokens(ASTNode node) {
    // Check if the node is a MethodDeclaration 
    if (!(node instanceof MethodDeclaration))
        throw new IllegalArgumentException(
                "Expecting method declaration but found " + node.getClass().getName());

    MethodDeclaration mth = (MethodDeclaration) node;

    // Add method name
    String methodName = mth.getName().getFullyQualifiedName();
    addInterfaceToken(methodName);/*from ww  w. ja  va  2s .c  o m*/

    // Add method declaration parameters and create unique method name
    String uniqueMethodName = "";
    uniqueMethodName = methodName;

    for (SingleVariableDeclaration param : (List<SingleVariableDeclaration>) mth.parameters()) {
        if (!_stateAnalysis) {
            addInterfaceToken(param.getName().getIdentifier());
            addInterfaceToken(param.getType().toString());
        }
        uniqueMethodName = uniqueMethodName + " " + param.getType().toString();
    }

    // Set the identifier of this token-set
    setIdentifier(uniqueMethodName);

    // Add return type
    if (!mth.isConstructor()) {
        boolean skipReturn = false;
        Type mthReturn = mth.getReturnType2();
        if (mthReturn == null) {
            skipReturn = true;
        } else if (mthReturn.isPrimitiveType()) {
            if (PrimitiveType.VOID.equals(((PrimitiveType) mthReturn).getPrimitiveTypeCode()))
                skipReturn = true;
        }
        if (!skipReturn)
            addInterfaceToken(mthReturn.toString());
    }

    // update method identifier position in the Java source text
    updateIdentifierPosition(mth);

    // Add exceptions thrown by method
    if (!_stateAnalysis) {
        for (Object exception : mth.thrownExceptionTypes()) {
            addInterfaceToken(((SimpleType) exception).getName().getFullyQualifiedName());
        }
    }

    // Visit the method body to collect terms           
    Block block = mth.getBody();
    if (_hasBody && block != null) { // Found method body
        block.accept(new ASTVisitor() {
            public boolean visit(StringLiteral node) {
                if (!_stateAnalysis) {
                    addToken(node.toString());
                }
                return true;
            }

            public boolean visit(SimpleName node) {
                addToken(node.toString());
                return true;
            }
        });
    }

    // Add java doc comment found for the method
    if (!_ignoreComments && !_stateAnalysis && mth.getJavadoc() != null) {
        List<TagElement> jDocComments = (List<TagElement>) mth.getJavadoc().tags();
        for (TagElement jDocComment : jDocComments) {
            addCommentToken(jDocComment.toString());
        }
    }
}

From source file:edu.uci.ics.sourcerer.tools.java.extractor.eclipse.ReferenceExtractorVisitor.java

License:Open Source License

/**
 * This method writes://  w ww.jav a 2s  .co  m
 * <ul>
 *   <li>Constructor entity to <code>IEntityWriter</code>.
 *   <ul>
 *     <li>Inside relation to <code>IRelationWriter</code>.</li>
 *     <li>Throws relation to <code>IRelationWriter</code>.</li>
 *     
 *   </ul></li>
 *   <li>Method entity to <code>IEntityWriter</code>.
 *   <ul>
 *     <li>Inside relation to <code>IRelationWriter</code>.</li>
 *     <li>Returns relation to <code>IRelationWriter</code>.</li>
 *     <li>Throws relation to <code>IRelationWriter</code>.</li>
 *   </ul></li>
 *   <li>Default constructor call relation to <code>IRelationWriter</code>.</li>
 * </ul>
 * 
 * Method fully qualified names (FQNs) adhere to the following format:<br> 
 * parent fqn + . + simple name + ( + parameter list + )
 * <p>
 * Constructor FQNs adhere to the following format:<br>
 * parent fqn + . + <init> + ( + parameter list + )
 */
@SuppressWarnings("unchecked")
@Override
public boolean visit(MethodDeclaration node) {
    // Build the fqn and type
    String fqn = null;
    String fullFqn = null;
    Entity type = null;

    String parentFqn = fqnStack.getFqn();
    String signature = getMethodParams(node.parameters());
    String rawSignature = getErasedMethodParams(node.parameters());
    if (node.isConstructor()) {
        type = Entity.CONSTRUCTOR;
        fqn = parentFqn + ".<init>";
        fullFqn = fqn + signature;
    } else {
        type = Entity.METHOD;
        fqn = parentFqn + '.' + node.getName().getIdentifier();
        fullFqn = fqn + signature;

        // Write the returns relation
        Type returnType = node.getReturnType2();
        if (returnType == null) {
            logger.severe("Null return type for " + fullFqn);
        } else {
            relationWriter.writeRelation(Relation.RETURNS, fullFqn, getTypeFqn(returnType),
                    createLocation(returnType));
        }
    }

    fqnStack.push(fullFqn, type);

    // Explore the children
    accept(node.getJavadoc());
    accept(node.modifiers());
    accept(node.typeParameters());
    accept(node.getReturnType2());
    accept(node.getName());
    accept(node.parameters());
    accept(node.thrownExceptionTypes());
    accept(node.getBody());

    // Write the entity
    if (signature.equals(rawSignature)) {
        entityWriter.writeEntity(type, fqn, signature, null, node.getModifiers(), createMetrics(node),
                createLocation(node));
    } else {
        entityWriter.writeEntity(type, fqn, signature, rawSignature, node.getModifiers(), createMetrics(node),
                createLocation(node));
    }

    // Write the contains relation
    relationWriter.writeRelation(Relation.CONTAINS, parentFqn, fullFqn, createUnknownLocation());

    // Write the throws relation
    for (SimpleType name : (List<SimpleType>) node.thrownExceptionTypes()) {
        ITypeBinding exceptionBinding = name.getName().resolveTypeBinding();
        if (exceptionBinding == null) {
            relationWriter.writeRelation(Relation.THROWS, fullFqn,
                    createUnknownFqn(name.getName().getFullyQualifiedName()), createLocation(node));
        } else {
            relationWriter.writeRelation(Relation.THROWS, fullFqn, getTypeFqn(exceptionBinding),
                    createLocation(name));
        }
    }

    // Write the default constructor call if needed
    if (node.isConstructor() && !fqnStack.peek(EnclosingConstructor.class).wasSuperInvoked()) {
        IMethodBinding binding = node.resolveBinding();
        if (binding != null) {
            ITypeBinding declaring = binding.getDeclaringClass();
            if (declaring != null) {
                if (declaring.isEnum()) {
                    relationWriter.writeRelation(Relation.CALLS, fqnStack.getFqn(),
                            "java.lang.Enum.<init>(java.lang.String,int)", createUnknownLocation());
                } else {
                    ITypeBinding parent = declaring.getSuperclass();
                    if (parent == null) {
                        relationWriter.writeRelation(Relation.CALLS, fqnStack.getFqn(),
                                "java.lang.Object.<init>()", createUnknownLocation());
                    } else {
                        relationWriter.writeRelation(Relation.CALLS, fqnStack.getFqn(),
                                getErasedTypeFqn(parent) + ".<init>()", createUnknownLocation());
                    }
                }
            }
        }
    }

    fqnStack.pop();
    return false;
}

From source file:org.autorefactor.refactoring.rules.ImplicitDefaultConstructorRatherThanWrittenOneRefactoring.java

License:Open Source License

private boolean isCheckedExceptionThrown(final MethodDeclaration uniqueConstructor) {
    if (uniqueConstructor.thrownExceptionTypes() != null) {
        for (final Object type : uniqueConstructor.thrownExceptionTypes()) {
            if (isChecked((Type) type)) {
                return true;
            }/*from  w  w w.ja  v a  2 s.  co  m*/
        }
    }
    return false;
}

From source file:org.codemucker.jmutate.ast.JAstFlattener.java

License:Open Source License

public boolean visit(MethodDeclaration node) {
    if (node.getJavadoc() != null) {
        node.getJavadoc().accept(this);
    }//from www.j  a v  a  2s .co m
    printIndent();
    if (node.getAST().apiLevel() == JLS2) {
        printModifiers(node.getModifiers());
    }
    if (node.getAST().apiLevel() >= JLS3) {
        printModifiers(node.modifiers());
        if (!node.typeParameters().isEmpty()) {
            this.buffer.append("<");//$NON-NLS-1$
            for (Iterator it = node.typeParameters().iterator(); it.hasNext();) {
                TypeParameter t = (TypeParameter) it.next();
                t.accept(this);
                if (it.hasNext()) {
                    this.buffer.append(",");//$NON-NLS-1$
                }
            }
            this.buffer.append(">");//$NON-NLS-1$
        }
    }
    if (!node.isConstructor()) {
        if (node.getAST().apiLevel() == JLS2) {
            getReturnType(node).accept(this);
        } else {
            if (node.getReturnType2() != null) {
                node.getReturnType2().accept(this);
            } else {
                // methods really ought to have a return type
                this.buffer.append("void");//$NON-NLS-1$
            }
        }
        this.buffer.append(" ");//$NON-NLS-1$
    }
    node.getName().accept(this);
    this.buffer.append("(");//$NON-NLS-1$
    if (node.getAST().apiLevel() >= AST.JLS8) {
        Type receiverType = node.getReceiverType();
        if (receiverType != null) {
            receiverType.accept(this);
            this.buffer.append(' ');
            SimpleName qualifier = node.getReceiverQualifier();
            if (qualifier != null) {
                qualifier.accept(this);
                this.buffer.append('.');
            }
            this.buffer.append("this"); //$NON-NLS-1$
            if (node.parameters().size() > 0) {
                this.buffer.append(',');
            }
        }
    }
    for (Iterator it = node.parameters().iterator(); it.hasNext();) {
        SingleVariableDeclaration v = (SingleVariableDeclaration) it.next();
        v.accept(this);
        if (it.hasNext()) {
            this.buffer.append(",");//$NON-NLS-1$
        }
    }
    this.buffer.append(")");//$NON-NLS-1$
    int size = node.getExtraDimensions();
    if (node.getAST().apiLevel() >= AST.JLS8) {
        List dimensions = node.extraDimensions();
        for (int i = 0; i < size; i++) {
            visit((Dimension) dimensions.get(i));
        }
    } else {
        for (int i = 0; i < size; i++) {
            this.buffer.append("[]"); //$NON-NLS-1$
        }
    }
    if (node.getAST().apiLevel() < AST.JLS8) {
        if (!thrownExceptions(node).isEmpty()) {
            this.buffer.append(" throws ");//$NON-NLS-1$
            for (Iterator it = thrownExceptions(node).iterator(); it.hasNext();) {
                Name n = (Name) it.next();
                n.accept(this);
                if (it.hasNext()) {
                    this.buffer.append(", ");//$NON-NLS-1$
                }
            }
            this.buffer.append(" ");//$NON-NLS-1$
        }
    } else {
        if (!node.thrownExceptionTypes().isEmpty()) {
            this.buffer.append(" throws ");//$NON-NLS-1$
            for (Iterator it = node.thrownExceptionTypes().iterator(); it.hasNext();) {
                Type n = (Type) it.next();
                n.accept(this);
                if (it.hasNext()) {
                    this.buffer.append(", ");//$NON-NLS-1$
                }
            }
            this.buffer.append(" ");//$NON-NLS-1$               
        }
    }
    if (node.getBody() == null) {
        this.buffer.append(";\n");//$NON-NLS-1$
    } else {
        node.getBody().accept(this);
    }
    return false;
}

From source file:org.decojer.cavaj.transformers.TrOutline.java

License:Open Source License

/**
 * Decompile method parameters (parameter types, return type, exception types, annotations,
 * names)./*from  w w w . j a va 2s .com*/
 *
 * @param m
 *            method declaration
 */
@SuppressWarnings("deprecation")
private static void decompileMethodParams(final M m) {
    // method type parameters (full signature only):
    // <T:Ljava/lang/Integer;U:Ljava/lang/Long;>(TT;TU;)V
    // <U:TT;>(TT;TU;)V
    final Object astNode = m.getAstNode();
    if (!(astNode instanceof MethodDeclaration)) {
        assert false;
        return;
    }
    final MethodDeclaration methodDeclaration = (MethodDeclaration) astNode;
    final T t = m.getT();
    assert t != null : "decompile method cannot be dynamic";
    final AST ast = t.getCu().getAst();

    final T[] paramTs = m.getParamTs();
    final T receiverT = m.getReceiverT();
    if (receiverT != null) {
        methodDeclaration.setReceiverType(newType(receiverT, t));
    }
    final A[][] paramAss = m.getParamAss();
    for (int i = 0; i < paramTs.length; ++i) {
        if (m.isConstructor()) {
            if (i <= 1 && t.isEnum() && !t.getCu().check(DFlag.IGNORE_ENUM)) {
                // enum constructors have two leading synthetic parameters,
                // enum classes are static and can not be anonymous or inner method
                if (i == 0 && m.getParamTs()[0].is(String.class)) {
                    continue;
                }
                if (i == 1 && m.getParamTs()[1] == T.INT) {
                    continue;
                }
            }
            if (i == 0 && t.isInner() && !t.getCu().check(DFlag.IGNORE_CONSTRUCTOR_THIS)) {
                // inner class constructor has synthetic this reference as first argument: skip
                if (m.getParamTs()[0].is(t.getEnclosingT())) {
                    continue;
                }
                log.warn(m + ": Inner class constructor has no synthetic this reference as first argument!");
            }
            // anonymous inner classes cannot have visible Java constructors, don't handle
            // here but ignore in merge all

            // method inner classes have extra trailing parameters for visible outer finals,
            // that are used in other methods

            // static inner classes can only have top-level or static outer,
            // anonymous inner classes are static if context is static,
            // enums are static and can not be anonymous or inner method
        }
        methodDeclaration.parameters().add(newSingleVariableDeclaration(m, paramTs, paramAss, i, t));
    }
    // decompile return type
    methodDeclaration.setReturnType2(newType(m.getReturnT(), t));
    // decompile exceptions
    for (final T throwT : m.getThrowsTs()) {
        assert throwT != null;
        // Eclipse AST expects a List<Name> for thrownExceptions, not a List<Type>:
        // is OK - thrownExceptions cannot be generic
        if (ast.apiLevel() <= AST.JLS4) {
            methodDeclaration.thrownExceptions().add(newTypeName(throwT, t));
        } else {
            methodDeclaration.thrownExceptionTypes().add(newType(throwT, t));
        }
    }
}