Example usage for org.eclipse.jdt.core.dom Block statements

List of usage examples for org.eclipse.jdt.core.dom Block statements

Introduction

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

Prototype

ASTNode.NodeList statements

To view the source code for org.eclipse.jdt.core.dom Block statements.

Click Source Link

Document

The list of statements (element type: Statement ).

Usage

From source file:com.ashigeru.eclipse.util.jdt.internal.ui.handlers.InsertAssertionHandler.java

License:Apache License

private TextEdit createEdit(CompilationUnit ast, MethodDeclaration method, IDocument target) {
    assert ast != null;
    assert method != null;
    assert target != null;
    List<String> objectParams = new ArrayList<String>();
    for (Object o : method.parameters()) {
        SingleVariableDeclaration var = (SingleVariableDeclaration) o;
        if (var.getType().getNodeType() != ASTNode.PRIMITIVE_TYPE) {
            objectParams.add(var.getName().getIdentifier());
        }/*from ww  w.ja  v a  2 s . co m*/
    }
    if (objectParams.isEmpty()) {
        return null;
    }
    AST factory = ast.getAST();
    ast.recordModifications();
    List<Statement> toInsert = new ArrayList<Statement>();
    for (String name : objectParams) {
        AssertStatement assertion = createAssertion(factory, name);
        toInsert.add(assertion);
    }

    Block body = method.getBody();
    @SuppressWarnings("unchecked")
    List<Statement> statements = body.statements();

    int offset = 0;
    if (statements.isEmpty() == false) {
        Statement first = statements.get(0);
        int type = first.getNodeType();
        if (type == ASTNode.CONSTRUCTOR_INVOCATION || type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) {
            offset++;
        }
    }

    statements.addAll(offset, toInsert);

    return ast.rewrite(target, null);
}

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

License:Open Source License

@Override
public boolean visit(Block node) {
    if (this.options.keep_guardian_clause_on_one_line && this.tm.isGuardClause(node))
        return true;

    List<Statement> statements = node.statements();
    for (Statement statement : statements) {
        if (this.options.put_empty_statement_on_new_line || !(statement instanceof EmptyStatement))
            breakLineBefore(statement);//from   w ww .j av a  2  s . c o m
    }
    if (node.getParent().getLength() == 0)
        return true; // this is a fake block created by parsing in statements mode

    ASTNode parent = node.getParent();
    if (parent instanceof MethodDeclaration)
        return true; // braces have been handled in #visit(MethodDeclaration)

    String bracePosition = this.options.brace_position_for_block;
    if (parent instanceof SwitchStatement) {
        List<Statement> siblings = ((SwitchStatement) parent).statements();
        int blockPosition = siblings.indexOf(node);
        boolean isFirstInCase = blockPosition > 0 && (siblings.get(blockPosition - 1) instanceof SwitchCase);
        if (isFirstInCase)
            bracePosition = this.options.brace_position_for_block_in_case;
    } else if (parent instanceof LambdaExpression) {
        bracePosition = this.options.brace_position_for_lambda_body;
    }
    handleBracedCode(node, null, bracePosition, this.options.indent_statements_compare_to_block,
            this.options.insert_new_line_in_empty_block);

    return true;
}

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

License:Open Source License

public boolean isGuardClause(Block node) {
    if (node.statements().size() != 1)
        return false;
    ASTNode parent = node.getParent();// ww w .ja  va  2s  . c  o m
    if (!(parent instanceof IfStatement) || ((IfStatement) parent).getElseStatement() != null)
        return false;
    Object statement = node.statements().get(0);
    if (!(statement instanceof ReturnStatement) && !(statement instanceof ThrowStatement))
        return false;
    // guard clause cannot start with a comment
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=58565
    int openBraceIndex = firstIndexIn(node, TokenNameLBRACE);
    return !get(openBraceIndex + 1).isComment();
}

From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaAbstractAstNodeModelAdapter.java

License:Open Source License

/**
 * Creates a {@link Type} from the given name, owned by the given AST.
 *//*  w  w  w.ja va2  s. c om*/
protected Type getTypeFromString(AST ast, String name) {
    if (name == null) {
        return ast.newPrimitiveType(PrimitiveType.VOID);
    }
    PrimitiveType.Code primitiveTypeCode = PrimitiveType.toCode(name);
    if (primitiveTypeCode != null) {
        return ast.newPrimitiveType(primitiveTypeCode);
    }

    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_STATEMENTS);
    parser.setSource((name + " a;").toCharArray());

    Block block = (Block) parser.createAST(null);
    VariableDeclarationStatement declaration = (VariableDeclarationStatement) block.statements().get(0);
    return (Type) ASTNode.copySubtree(ast, declaration.getType());
}

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

License:Open Source License

/**
 * Creates a new appropriate {@link Type} from the given <code>value</code>.
 * <p>/*  w w  w . j  a va  2  s  . c o m*/
 * Note that if <code>value</code> is <code>null</code> returns
 * {@link PrimitiveType#VOID}.
 * 
 * @param ast
 *            {@link AST} of the {@link ASTNode ASTElement} needing a new
 *            Type
 * @param value
 *            the name of the {@link Type} to be created.
 * @param canBePrimitiveType
 *            if <code>true</code> try to create a primitive from the
 *            given <code>value</code> if possible, otherwise create a new
 *            Type without checking primitives
 * @author Luiza
 * 
 * @flowerModelElementId _zVs8hZiOEd6aNMdNFvR5WQ
 */
public static Type getJavaTypeFromString(AST ast, String value, boolean canBePrimitiveType) {
    if (canBePrimitiveType) {
        PrimitiveType.Code primitiveTypeCode = null;
        if (value == null)
            primitiveTypeCode = PrimitiveType.VOID;
        else {
            primitiveTypeCode = PrimitiveType.toCode(value);
        }
        if (primitiveTypeCode != null)
            return ast.newPrimitiveType(primitiveTypeCode);
    }

    // not a primitive
    ASTParser statementParser = ASTParser.newParser(AST.JLS3);
    statementParser.setKind(ASTParser.K_STATEMENTS);
    statementParser.setSource((value + " a;").toCharArray()); // try to parse a variable declaration

    Block block = (Block) statementParser.createAST(null);
    VariableDeclarationStatement declaration = (VariableDeclarationStatement) block.statements().get(0);
    return (Type) ASTNode.copySubtree(ast, declaration.getType()); // detach the type from the parent node
}

From source file:com.dforensic.plugin.manal.parser.SuspectSearch.java

License:Open Source License

private void extractStatements(CompilationUnit cu, MethodDeclaration method, ApiDescriptor methodSearched) {
    String methodName = methodSearched.getMethodNameFromSoot();
    if (methodName == null) {
        System.err.println("Can't search a method. Method name is NULL.");
        return;/*ww  w .  j  av  a 2 s .  co m*/
    }
    Block body = method.getBody();
    if (body != null) {
        for (Statement smt : (List<Statement>) body.statements()) {
            if (smt instanceof ExpressionStatement) {
                Expression esn = ((ExpressionStatement) smt).getExpression();
                if (esn instanceof MethodInvocation) {
                    // TODO when refactoring
                    // go deeper to statements (not only MethodInvoke)
                    MethodInvocation inv = (MethodInvocation) esn;
                    if (methodName.equals(inv.getName())) {
                        methodSearched.setCompilationUnit(cu);
                        return;
                    }
                    // filterMethod(cu, inv);

                    // SimpleName name = inv.getName();
                    // ApiDescriptor apiDesc = new ApiDescriptor();
                    // apiDesc.setMethodName(name.getIdentifier());
                    // apiDesc.setReturnType(method.getReturnType());
                    // apiDesc.setSignature(method.getSignature());
                    // mMethodDetails.add(apiDesc);
                }
            }
        }
    } else {
        System.out.print(">>warning: the method doesn't have a body.");
    }
}

From source file:com.google.devtools.j2cpp.gen.CppStatementGenerator.java

License:Open Source License

@Override
public boolean visit(Block node) {
    buffer.append("{\n");
    List<?> stmts = node.statements();
    printStatements(stmts);/* w w w . j a  v a 2s . c  o  m*/
    buffer.append("}\n");
    return false;
}

From source file:com.google.devtools.j2cpp.translate.ClassConverter.java

License:Open Source License

protected void addInnerParameters(MethodDeclaration constructor, GeneratedMethodBinding binding,
        List<IVariableBinding> innerFields, AST ast, boolean methodVars) {
    // Add parameters and initializers for each field.
    @SuppressWarnings("unchecked") // safe by definition
    List<SingleVariableDeclaration> parameters = constructor.parameters();
    List<SingleVariableDeclaration> newParams = createConstructorArguments(innerFields,
            Types.getMethodBinding(constructor), ast, "outer$");
    Block body = constructor.getBody();
    @SuppressWarnings("unchecked") // safe by definition
    List<Statement> statements = body.statements();
    Statement first = statements.size() > 0 ? statements.get(0) : null;
    int offset = first != null
            && (first instanceof SuperConstructorInvocation || first instanceof ConstructorInvocation) ? 1 : 0;
    boolean firstIsThisCall = first != null && first instanceof ConstructorInvocation;

    // If superclass constructor takes an outer$ parameter, create or edit
    // an invocation for it first
    if (!innerFields.isEmpty() && !methodVars) {
        if (firstIsThisCall) {
            ConstructorInvocation thisCall = (ConstructorInvocation) first;
            IMethodBinding cons = Types.getMethodBinding(thisCall);
            GeneratedMethodBinding newCons = new GeneratedMethodBinding(cons.getMethodDeclaration());
            // Create a new this invocation to the updated constructor.
            @SuppressWarnings("unchecked")
            List<Expression> args = ((ConstructorInvocation) first).arguments();
            int index = 0;
            for (SingleVariableDeclaration param : newParams) {
                IVariableBinding paramBinding = Types.getVariableBinding(param);
                newCons.addParameter(index, Types.getTypeBinding(param));
                args.add(index++, makeFieldRef(paramBinding, ast));
            }/*from  ww  w. ja  v a2 s. co m*/
            Types.addBinding(thisCall, newCons);
        } else {
            ITypeBinding superType = binding.getDeclaringClass().getSuperclass().getTypeDeclaration();
            if ((superType.getDeclaringClass() != null || superType.getDeclaringMethod() != null)
                    && (superType.getModifiers() & Modifier.STATIC) == 0) {

                // There may be more than one outer var supplied, find the right one.
                IVariableBinding outerVar = null;
                for (SingleVariableDeclaration param : newParams) {
                    IVariableBinding paramBinding = Types.getVariableBinding(param);
                    if (paramBinding.getType().isAssignmentCompatible(superType.getDeclaringClass())) {
                        outerVar = paramBinding;
                    }
                }
                assert outerVar != null;

                IMethodBinding cons = null;
                if (offset > 0) {
                    cons = Types.getMethodBinding(statements.get(0));
                } else {
                    for (IMethodBinding method : superType.getDeclaredMethods()) {
                        // The super class's constructor may or may not have been already
                        // modified.
                        if (method.isConstructor()) {
                            if (method.getParameterTypes().length == 0) {
                                cons = method;
                                break;
                            } else if (method.getParameterTypes().length == 1
                                    && outerVar.getType().isAssignmentCompatible(method.getParameterTypes()[0])
                                    && method instanceof GeneratedMethodBinding) {
                                cons = method;
                                break;
                            }
                        }
                    }
                }

                assert cons != null;

                if (!updatedConstructors.contains(cons)) {
                    GeneratedMethodBinding newSuperCons = new GeneratedMethodBinding(
                            cons.getMethodDeclaration());
                    newSuperCons.addParameter(0, superType.getDeclaringClass());
                    cons = newSuperCons;
                }

                SimpleName outerRef = makeFieldRef(outerVar, ast);
                SuperConstructorInvocation superInvocation = offset == 0 ? ast.newSuperConstructorInvocation()
                        : (SuperConstructorInvocation) statements.get(0);
                @SuppressWarnings("unchecked")
                List<Expression> args = superInvocation.arguments(); // safe by definition
                args.add(0, outerRef);
                if (offset == 0) {
                    statements.add(0, superInvocation);
                    offset = 1;
                }
                Types.addBinding(superInvocation, cons);
            }
        }
    }

    for (int i = 0; i < newParams.size(); i++) {
        SingleVariableDeclaration parameter = newParams.get(i);

        // Only add an assignment statement for fields.
        if (innerFields.get(i).isField()) {
            statements.add(i + offset,
                    createAssignment(innerFields.get(i), Types.getVariableBinding(parameter), ast));
        }

        // Add methodVars at the end of the method invocation.
        if (methodVars) {
            parameters.add(parameter);
            binding.addParameter(Types.getVariableBinding(parameter));
        } else {
            parameters.add(i, parameter);
            binding.addParameter(i, Types.getVariableBinding(parameter));
        }
    }

    Symbols.scanAST(constructor);
    updatedConstructors.add(binding);
    assert constructor.parameters().size() == binding.getParameterTypes().length;
}

From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java

License:Open Source License

/**
 * Add a thrown AssertionError statement to a block.
 *//*  w ww  .  j  a v  a  2  s . c  om*/
@SuppressWarnings("unchecked")
private void addAssertionError(Block block) {
    AST ast = block.getAST();

    ThrowStatement throwStatement = ast.newThrowStatement();
    block.statements().add(throwStatement);

    ClassInstanceCreation newException = ast.newClassInstanceCreation();
    throwStatement.setExpression(newException);

    Type assertionError = ast.newSimpleType(ast.newSimpleName("AssertionError"));
    newException.setType(assertionError);

    StringLiteral assertionDescription = ast.newStringLiteral();
    assertionDescription.setLiteralValue("Cannot invoke dead method");
    newException.arguments().add(assertionDescription);
}

From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java

License:Open Source License

/**
 * Adds a nullary constructor that invokes a superclass constructor with
 * default arguments./*w w w. j a  v a  2 s  . c om*/
 */
@SuppressWarnings("unchecked")
private void generateConstructor(TypeDeclaration node) {
    ITypeBinding clazz = node.resolveBinding();
    IMethodBinding superConstructor = getVisible(getConstructors(clazz.getSuperclass())).next();

    // Add an explicit constructor that calls super with suitable default arguments.
    AST ast = node.getAST();
    MethodDeclaration constructor = ast.newMethodDeclaration();
    constructor.setConstructor(true);
    constructor.setName(ast.newSimpleName(node.getName().getIdentifier()));
    constructor.modifiers().add(ast.newModifier(ModifierKeyword.PROTECTED_KEYWORD));
    node.bodyDeclarations().add(constructor);

    Block block = ast.newBlock();
    constructor.setBody(block);
    SuperConstructorInvocation invocation = ast.newSuperConstructorInvocation();
    block.statements().add(invocation);
    addAssertionError(block);

    for (ITypeBinding type : superConstructor.getParameterTypes()) {
        Expression value = getDefaultValue(ast, type);
        CastExpression cast = ast.newCastExpression();
        cast.setExpression(value);
        cast.setType(createType(ast, clazz, type));
        invocation.arguments().add(cast);
    }
}