Example usage for org.eclipse.jdt.core.dom Initializer setBody

List of usage examples for org.eclipse.jdt.core.dom Initializer setBody

Introduction

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

Prototype

public void setBody(Block body) 

Source Link

Document

Sets the body of this initializer declaration.

Usage

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

License:Open Source License

@Override
public boolean visit(FieldDeclaration node) {
    int mods = node.getModifiers();
    if (Modifier.isStatic(mods)) {
        ASTNode parent = node.getParent();
        @SuppressWarnings("unchecked")
        List<BodyDeclaration> classMembers = parent instanceof AbstractTypeDeclaration
                ? ((AbstractTypeDeclaration) parent).bodyDeclarations()
                : ((AnonymousClassDeclaration) parent).bodyDeclarations(); // safe by specification
        int indexOfNewMember = classMembers.indexOf(node) + 1;

        @SuppressWarnings("unchecked")
        List<VariableDeclarationFragment> fragments = node.fragments(); // safe by specification
        for (VariableDeclarationFragment var : fragments) {
            IVariableBinding binding = Types.getVariableBinding(var);
            if (Types.isPrimitiveConstant(binding) && Modifier.isPrivate(binding.getModifiers())) {
                // Don't define accessors for private constants, since they can be
                // directly referenced.
                continue;
            }/*w  ww  .j  a v a2  s .  com*/

            // rename varName to varName_, per Obj-C style guide
            SimpleName oldName = var.getName();
            ITypeBinding type = ((AbstractTypeDeclaration) node.getParent()).resolveBinding();
            String varName = NameTable.getStaticVarQualifiedName(type, oldName.getIdentifier());
            NameTable.rename(binding, varName);
            ITypeBinding typeBinding = binding.getType();
            var.setExtraDimensions(0); // if array, type was corrected above

            // add accessor(s)
            if (needsReader(var, classMembers)) {
                classMembers.add(indexOfNewMember++, makeStaticReader(var, mods));
            }
            if (!Modifier.isFinal(node.getModifiers()) && needsWriter(var, classMembers)) {
                classMembers.add(indexOfNewMember++,
                        makeStaticWriter(var, oldName.getIdentifier(), node.getType(), mods));
            }

            // move non-constant initialization to init block
            Expression initializer = var.getInitializer();
            if (initializer != null && initializer.resolveConstantExpressionValue() == null) {
                var.setInitializer(null);

                AST ast = var.getAST();
                SimpleName newName = ast.newSimpleName(varName);
                Types.addBinding(newName, binding);
                Assignment assign = ast.newAssignment();
                assign.setLeftHandSide(newName);
                Expression newInit = NodeCopier.copySubtree(ast, initializer);
                assign.setRightHandSide(newInit);
                Types.addBinding(assign, typeBinding);

                Block initBlock = ast.newBlock();
                @SuppressWarnings("unchecked")
                List<Statement> stmts = initBlock.statements(); // safe by definition
                stmts.add(ast.newExpressionStatement(assign));
                Initializer staticInitializer = ast.newInitializer();
                staticInitializer.setBody(initBlock);
                @SuppressWarnings("unchecked")
                List<IExtendedModifier> initMods = staticInitializer.modifiers(); // safe by definition
                initMods.add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
                classMembers.add(indexOfNewMember++, staticInitializer);
            }
        }
    }
    return true;
}

From source file:java5totext.input.JDTVisitor.java

License:Open Source License

@Override
public void endVisit(org.eclipse.jdt.core.dom.Initializer node) {
    Initializer element = (Initializer) this.binding.get(node);
    this.initializeNode(element, node);

    if (this.binding.get(node.getBody()) != null)
        element.setBody((Block) this.binding.get(node.getBody()));
    endVisitBD(node, element);//w ww  . ja v  a 2  s .c o  m

    this.localBindings.resolveBindings();
    // localBindings should be kept if initializer is declared in anonymous class declared in a method body
    if (!(node.getParent() instanceof org.eclipse.jdt.core.dom.AnonymousClassDeclaration
            || node.getParent().getParent() instanceof org.eclipse.jdt.core.dom.TypeDeclarationStatement))
        this.localBindings = null;
}

From source file:org.eclipse.jdt.core.dom.ASTConverter.java

License:Open Source License

protected void checkAndAddMultipleFieldDeclaration(
        org.eclipse.jdt.internal.compiler.ast.FieldDeclaration[] fields, int index, List bodyDeclarations) {
    if (fields[index] instanceof org.eclipse.jdt.internal.compiler.ast.Initializer) {
        org.eclipse.jdt.internal.compiler.ast.Initializer oldInitializer = (org.eclipse.jdt.internal.compiler.ast.Initializer) fields[index];
        Initializer initializer = new Initializer(this.ast);
        initializer.setBody(convert(oldInitializer.block));
        setModifiers(initializer, oldInitializer);
        initializer.setSourceRange(oldInitializer.declarationSourceStart,
                oldInitializer.sourceEnd - oldInitializer.declarationSourceStart + 1);
        // The javadoc comment is now got from list store in compilation unit declaration
        convert(oldInitializer.javadoc, initializer);
        bodyDeclarations.add(initializer);
        return;//  ww  w  .  j  a  v a 2 s .c o  m
    }
    if (index > 0 && fields[index - 1].declarationSourceStart == fields[index].declarationSourceStart) {
        // we have a multiple field declaration
        // We retrieve the existing fieldDeclaration to add the new VariableDeclarationFragment
        FieldDeclaration fieldDeclaration = (FieldDeclaration) bodyDeclarations
                .get(bodyDeclarations.size() - 1);
        fieldDeclaration.fragments().add(convertToVariableDeclarationFragment(fields[index]));
    } else {
        // we can create a new FieldDeclaration
        bodyDeclarations.add(convertToFieldDeclaration(fields[index]));
    }
}

From source file:org.eclipse.jdt.core.dom.ASTConverter.java

License:Open Source License

public TypeDeclaration convert(org.eclipse.jdt.internal.compiler.ast.ASTNode[] nodes) {
    final TypeDeclaration typeDecl = new TypeDeclaration(this.ast);
    typeDecl.setInterface(false);//from  w  w w.j a v a 2s.  co  m
    int nodesLength = nodes.length;
    for (int i = 0; i < nodesLength; i++) {
        org.eclipse.jdt.internal.compiler.ast.ASTNode node = nodes[i];
        if (node instanceof org.eclipse.jdt.internal.compiler.ast.Initializer) {
            org.eclipse.jdt.internal.compiler.ast.Initializer oldInitializer = (org.eclipse.jdt.internal.compiler.ast.Initializer) node;
            Initializer initializer = new Initializer(this.ast);
            initializer.setBody(convert(oldInitializer.block));
            setModifiers(initializer, oldInitializer);
            initializer.setSourceRange(oldInitializer.declarationSourceStart,
                    oldInitializer.sourceEnd - oldInitializer.declarationSourceStart + 1);
            //            setJavaDocComment(initializer);
            //            initializer.setJavadoc(convert(oldInitializer.javadoc));
            convert(oldInitializer.javadoc, initializer);
            typeDecl.bodyDeclarations().add(initializer);
        } else if (node instanceof org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) {
            org.eclipse.jdt.internal.compiler.ast.FieldDeclaration fieldDeclaration = (org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) node;
            if (i > 0 && (nodes[i - 1] instanceof org.eclipse.jdt.internal.compiler.ast.FieldDeclaration)
                    && ((org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) nodes[i
                            - 1]).declarationSourceStart == fieldDeclaration.declarationSourceStart) {
                // we have a multiple field declaration
                // We retrieve the existing fieldDeclaration to add the new VariableDeclarationFragment
                FieldDeclaration currentFieldDeclaration = (FieldDeclaration) typeDecl.bodyDeclarations()
                        .get(typeDecl.bodyDeclarations().size() - 1);
                currentFieldDeclaration.fragments().add(convertToVariableDeclarationFragment(fieldDeclaration));
            } else {
                // we can create a new FieldDeclaration
                typeDecl.bodyDeclarations().add(convertToFieldDeclaration(fieldDeclaration));
            }
        } else if (node instanceof org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration) {
            AbstractMethodDeclaration nextMethodDeclaration = (AbstractMethodDeclaration) node;
            if (!nextMethodDeclaration.isDefaultConstructor() && !nextMethodDeclaration.isClinit()) {
                typeDecl.bodyDeclarations().add(convert(false, nextMethodDeclaration));
            }
        } else if (node instanceof org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) {
            org.eclipse.jdt.internal.compiler.ast.TypeDeclaration nextMemberDeclaration = (org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) node;
            ASTNode nextMemberDeclarationNode = convert(nextMemberDeclaration);
            if (nextMemberDeclarationNode == null) {
                typeDecl.setFlags(typeDecl.getFlags() | ASTNode.MALFORMED);
            } else {
                typeDecl.bodyDeclarations().add(nextMemberDeclarationNode);
            }
        }
    }
    return typeDecl;
}

From source file:org.eclipse.modisco.java.discoverer.internal.io.java.JDTVisitor.java

License:Open Source License

@Override
public void endVisit(final org.eclipse.jdt.core.dom.Initializer node) {
    if (!this.isFULLLEVELANALYSIS) {
        return;/*from w w  w  . j a  va 2 s  .c  om*/
    }

    Initializer element = (Initializer) this.binding.get(node);
    initializeNode(element, node);

    if (this.binding.get(node.getBody()) != null) {
        element.setBody((Block) this.binding.get(node.getBody()));
    }

    endVisitBD(node, element);

    // long debut = System.currentTimeMillis();

    getLocalBindings().resolveBindings();

    // long fin = System.currentTimeMillis();
    // TimeResults.resolveBindings += fin - debut;

    // localBindings should be kept if initializer is declared in anonymous
    // class declared in a method body
    if (!(node.getParent() instanceof org.eclipse.jdt.core.dom.AnonymousClassDeclaration
            || node.getParent().getParent() instanceof org.eclipse.jdt.core.dom.TypeDeclarationStatement)) {
        setLocalBindings(null);
    }
}

From source file:org.whole.lang.java.util.JDTTransformerVisitor.java

License:Open Source License

@Override
public boolean visit(Initializer node) {
    org.whole.lang.java.model.Initializer initializer;
    appendBodyDeclaration(initializer = lf.create(JavaEntityDescriptorEnum.Initializer));

    if (acceptChild(node.getJavadoc()))
        initializer.setJavadoc(this.javadoc);

    List<?> modifiers = node.modifiers();
    if (!modifiers.isEmpty()) {
        initializer.setModifiers(lf.create(JavaEntityDescriptorEnum.ExtendedModifiers));
        setExtendedModifiers(initializer.getModifiers(), modifiers);
    }/*  w ww  .j  a  v  a 2s  .  c  o  m*/

    acceptChild(node.getBody());
    initializer.setBody((org.whole.lang.java.model.Block) stm);

    return false;
}

From source file:ptolemy.backtrack.eclipse.ast.transform.AssignmentTransformer.java

License:Open Source License

/** Handle a class declaration or anonymous class declaration. Records and
 *  assignment methods are added to the declaration.
 *
 *  @param node The AST node of class declaration or anonymous class
 *   declaration./*from w  ww  .j  ava2  s . c o  m*/
 *  @param bodyDeclarations The list of body declarations in the class.
 *  @param state The current state of the type analyzer.
 */
private void _handleDeclaration(ASTNode node, List bodyDeclarations, TypeAnalyzerState state) {
    Class currentClass = state.getCurrentClass();
    @SuppressWarnings("unused")
    Class parent = currentClass.getSuperclass();
    List newMethods = new LinkedList();
    List newFields = new LinkedList();
    AST ast = node.getAST();
    CompilationUnit root = (CompilationUnit) node.getRoot();

    List fieldNames = new LinkedList();
    List fieldTypes = new LinkedList();

    // Iterate over all the body declarations.
    Iterator bodyIter = bodyDeclarations.iterator();

    while (bodyIter.hasNext()) {
        Object nextDeclaration = bodyIter.next();

        // Handle only field declarations.
        if (nextDeclaration instanceof FieldDeclaration) {
            FieldDeclaration fieldDecl = (FieldDeclaration) nextDeclaration;
            boolean isStatic = Modifier.isStatic(fieldDecl.getModifiers());

            // If HANDLE_STATIC_FIELDS is set to false, do not refactor
            // static fields.
            if (isStatic && (HANDLE_STATIC_FIELDS != true)) {
                continue;
            }

            // Handle only private fields or the $CHECKPOINT special field.
            if (Modifier.isPrivate(fieldDecl.getModifiers())) {
                Type type = Type.getType(fieldDecl);

                // Iterate over all the fragments in the field declaration.
                Iterator fragmentIter = fieldDecl.fragments().iterator();

                while (fragmentIter.hasNext()) {
                    VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragmentIter.next();
                    String fieldName = fragment.getName().getIdentifier();

                    // Get the list of numbers of indices.
                    Hashtable[] tables = new Hashtable[] { _accessedFields, _specialAccessedFields,
                            _backupFields };

                    for (int i = 0; i < tables.length; i++) {
                        List indicesList = _getAccessedField(tables[i], currentClass.getName(), fieldName);

                        if (indicesList == null) {
                            continue;
                        }

                        // Iterate over all the numbers of indices.
                        Iterator indicesIter = indicesList.iterator();

                        while (indicesIter.hasNext()) {
                            int indices = ((Integer) indicesIter.next()).intValue();

                            // Create an extra method for every different
                            // number of indices.
                            if (tables[i] == _backupFields) {
                                newMethods.add(_createBackupMethod(ast, root, state, fieldName, type, indices,
                                        isStatic));
                            } else {
                                newMethods.add(_createAssignMethod(ast, root, state, fieldName, type, indices,
                                        tables[i] == _specialAccessedFields, isStatic));
                            }
                        }
                    }

                    fieldNames.add(fieldName);
                    fieldTypes.add(type);

                    // Create a record field.
                    FieldDeclaration field = _createFieldRecord(ast, root, state, fieldName, type.dimensions(),
                            isStatic);

                    if (field != null) {
                        newFields.add(field);
                    }
                }
            }
        }
    }

    boolean isInterface = node instanceof TypeDeclaration && ((TypeDeclaration) node).isInterface();

    boolean isAnonymous = node instanceof AnonymousClassDeclaration;

    if (isAnonymous) {
        Class[] interfaces = currentClass.getInterfaces();

        for (int i = 0; i < interfaces.length; i++) {
            if (state.getCrossAnalyzedTypes().contains(interfaces[i].getName())) {
                isAnonymous = false;
            }
        }
    }

    RehandleDeclarationRecord declarationRecord = null;

    if (isAnonymous) {
        Class[] interfaces = currentClass.getInterfaces();

        if (interfaces.length == 1) {
            declarationRecord = new RehandleDeclarationRecord(bodyDeclarations);
            addToLists(_rehandleDeclaration, interfaces[0].getName(), declarationRecord);
        }
    }

    // Do not handle anonymous class declarations in a static method.
    boolean ignore = !_isInStatic.isEmpty() && (_isInStatic.peek().equals(Boolean.TRUE)) && isAnonymous;

    // Add an array of all the records.
    if (!isInterface && !ignore) {
        newFields.add(_createRecordArray(ast, root, state, fieldNames));
    }

    // Add a commit method.
    MethodDeclaration commitMethod = null;

    if (!ignore) {
        commitMethod = _createCommitMethod(ast, root, state, fieldNames, fieldTypes, isAnonymous, isInterface);
        newMethods.add(commitMethod);
    }

    if (declarationRecord != null) {
        if (!ignore) {
            declarationRecord._addExtendedDeclaration(commitMethod);
        }

        MethodDeclaration fixedCommitMethod = _createCommitMethod(ast, root, state, fieldNames, fieldTypes,
                false, isInterface);
        declarationRecord._addFixedDeclaration(fixedCommitMethod);
    }

    // Add a restore method.
    MethodDeclaration restoreMethod = null;

    if (!ignore) {
        restoreMethod = _createRestoreMethod(ast, root, state, fieldNames, fieldTypes, isAnonymous,
                isInterface);
        newMethods.add(restoreMethod);
    }

    if (declarationRecord != null) {
        if (!ignore) {
            declarationRecord._addExtendedDeclaration(restoreMethod);
        }

        MethodDeclaration fixedRestoreMethod = _createRestoreMethod(ast, root, state, fieldNames, fieldTypes,
                false, isInterface);
        declarationRecord._addFixedDeclaration(fixedRestoreMethod);
    }

    // Get checkpoint method.
    MethodDeclaration getCheckpoint = null;

    if (!ignore) {
        getCheckpoint = _createGetCheckpointMethod(ast, root, state, isAnonymous, isInterface);

        if (getCheckpoint != null) {
            newMethods.add(getCheckpoint);
        }
    }

    if (declarationRecord != null) {
        if (!ignore) {
            declarationRecord._addExtendedDeclaration(getCheckpoint);
        }

        MethodDeclaration fixedGetCheckpoint = _createGetCheckpointMethod(ast, root, state, false, isInterface);
        declarationRecord._addFixedDeclaration(fixedGetCheckpoint);
    }

    // Set checkpoint method.
    MethodDeclaration setCheckpoint = null;

    if (!ignore) {
        setCheckpoint = _createSetCheckpointMethod(ast, root, state, isAnonymous, isInterface);

        if (setCheckpoint != null) {
            newMethods.add(setCheckpoint);
        }
    }

    if (declarationRecord != null) {
        if (!ignore) {
            declarationRecord._addExtendedDeclaration(setCheckpoint);
        }

        MethodDeclaration fixedSetCheckpoint = _createSetCheckpointMethod(ast, root, state, false, isInterface);
        declarationRecord._addFixedDeclaration(fixedSetCheckpoint);
    }

    // Add an interface.
    if (!ignore) {
        if (isAnonymous) {
            TypeDeclaration proxy = _createProxyClass(ast, root, state);
            bodyDeclarations.add(proxy);

            if (declarationRecord != null) {
                declarationRecord._addExtendedDeclaration(proxy);
            }
        } else {
            // Set the class to implement Rollbackable.
            if (node instanceof TypeDeclaration) {
                String rollbackType = getClassName(Rollbackable.class, state, root);
                ((TypeDeclaration) node).superInterfaceTypes()
                        .add(ast.newSimpleType(createName(ast, rollbackType)));
            }

            if (!isInterface) {
                // Create a checkpoint field.
                FieldDeclaration checkpointField = _createCheckpointField(ast, root, state);

                if (checkpointField != null) {
                    bodyDeclarations.add(0, checkpointField);
                }

                // Create a record for the checkpoint field.
                FieldDeclaration record = _createCheckpointRecord(ast, root, state);

                if (record != null) {
                    newFields.add(0, record);
                }
            }
        }
    }

    // Add all the methods and then all the fields.
    if (!ignore) {
        bodyDeclarations.addAll(newMethods);
        bodyDeclarations.addAll(newFields);
    } else {
        if (declarationRecord != null) {
            declarationRecord._addFixedDeclarations(newMethods);
            declarationRecord._addFixedDeclarations(newFields);
        }
    }

    if (isAnonymous && !ignore) {
        // Create a simple initializer.
        Initializer initializer = ast.newInitializer();
        Block body = ast.newBlock();
        initializer.setBody(body);

        MethodInvocation addInvocation = ast.newMethodInvocation();
        addInvocation.setExpression(ast.newSimpleName(CHECKPOINT_NAME));
        addInvocation.setName(ast.newSimpleName("addObject"));

        ClassInstanceCreation proxy = ast.newClassInstanceCreation();
        proxy.setType(ast.newSimpleType(ast.newSimpleName(_getProxyName())));
        addInvocation.arguments().add(proxy);
        body.statements().add(ast.newExpressionStatement(addInvocation));
        bodyDeclarations.add(initializer);

        if (declarationRecord != null) {
            declarationRecord._addExtendedDeclaration(initializer);
        }
    }
}