Package org.eclipse.jdt.core.dom

Examples of org.eclipse.jdt.core.dom.AST


     @param prefix The prefix to be added to the beginning of the name (not
     *   including "." between the prefix and the name).
     *  @return The new AST name node.
     */
    private Name _addPrefix(Name name, String prefix) {
        AST ast = name.getAST();
        Name newName = null;

        while ((name != null)
                && name instanceof QualifiedName
                && !(((QualifiedName) name).getQualifier() instanceof SimpleName)) {
            name = ((QualifiedName) name).getQualifier();
        }

        int lastPosition = prefix.length() - 1;

        while (lastPosition >= 0) {
            int dotPosition = prefix.lastIndexOf('.', lastPosition);
            String part = (dotPosition == -1) ? prefix.substring(0,
                    lastPosition + 1) : prefix.substring(dotPosition + 1,
                    lastPosition + 1);
            lastPosition = dotPosition - 1;

            if (name == null) {
                name = ast.newSimpleName(part);
                newName = name;
            } else if (name instanceof SimpleName) {
                name = ast.newQualifiedName(ast.newSimpleName(part), ast
                        .newSimpleName(((SimpleName) name).getIdentifier()));
                newName = name;
            } else {
                QualifiedName qualifiedName = (QualifiedName) name;
                SimpleName leftPart = (SimpleName) qualifiedName.getQualifier();
                qualifiedName.setQualifier(ast.newQualifiedName(ast
                        .newSimpleName(part), ast.newSimpleName(leftPart
                        .getIdentifier())));
                name = qualifiedName.getQualifier();
            }
        }

View Full Code Here


        }

        // Sort all the importations.
        List imports = node.imports();
        int length = imports.size();
        AST ast = node.getAST();

        for (int i = 0; i < (length - 1); i++) {
            for (int j = i + 1; j < length; j++) {
                ImportDeclaration import1 = (ImportDeclaration) imports.get(i);
                ImportDeclaration import2 = (ImportDeclaration) imports.get(j);
View Full Code Here

                } catch (ClassNotFoundException e) {
                }
            }
        }

        AST ast = root.getAST();
        ImportDeclaration declaration = ast.newImportDeclaration();
        declaration.setName(createName(ast, name));
        root.imports().add(declaration);
        loader.importClass(name);
        return simpleName;
    }
View Full Code Here

            if (blockList != null) {
                Iterator nodesIter = blockList.iterator();

                while (nodesIter.hasNext()) {
                    Block body = (Block) nodesIter.next();
                    AST ast = body.getAST();
                    Statement invocation = _createSetCheckpointInvocation(ast);
                    List<Statement> statements = body.statements();
                    statements.add(statements.size() - 2, invocation);
                    nodesIter.remove();
                }
View Full Code Here

            }
        }

        if (needRefactor) {
            // Refactor the expression.
            AST ast = node.getAST();
            //CompilationUnit root = (CompilationUnit) node.getRoot();
            //String typeClassName = getClassName(typeName, state, root);

            int nIndices = 0;

            Expression nodeIterator = node;

            while (nodeIterator instanceof ParenthesizedExpression) {
                nodeIterator = ((ParenthesizedExpression) nodeIterator)
                        .getExpression();
            }

            List indices = new LinkedList();

            while (nodeIterator instanceof ArrayAccess) {
                nIndices++;

                ArrayAccess arrayAccess = (ArrayAccess) nodeIterator;
                indices
                        .add(0, ASTNode
                                .copySubtree(ast, arrayAccess.getIndex()));
                nodeIterator = arrayAccess.getArray();

                while (nodeIterator instanceof ParenthesizedExpression) {
                    nodeIterator = ((ParenthesizedExpression) nodeIterator)
                            .getExpression();
                }
            }

            Expression newObject = null;
            SimpleName name;

            if (nodeIterator instanceof FieldAccess) {
                Expression object = ((FieldAccess) nodeIterator)
                        .getExpression();
                name = ((FieldAccess) nodeIterator).getName();
                newObject = (Expression) ASTNode.copySubtree(ast, object);
            } else if (nodeIterator instanceof QualifiedName) {
                Name object = ((QualifiedName) nodeIterator).getQualifier();
                name = ((QualifiedName) nodeIterator).getName();
                newObject = (Expression) ASTNode.copySubtree(ast, object);
            } else if (nodeIterator instanceof SimpleName) {
                name = (SimpleName) nodeIterator;
            } else {
                return null;
            }

            // Get the class of the owner and test the modifiers of the field.
            Class ownerClass;
            boolean isStatic;

            try {
                ownerClass = owner.toClass(state.getClassLoader());

                Field field = ownerClass.getDeclaredField(name.getIdentifier());
                int modifiers = field.getModifiers();

                if (!java.lang.reflect.Modifier.isPrivate(modifiers)) {
                    return null; // Not handling non-private fields.
                }

                isStatic = java.lang.reflect.Modifier.isStatic(modifiers);
            } catch (ClassNotFoundException e) {
                throw new ASTClassNotFoundException(owner.getName());
            } catch (NoSuchFieldException e) {
                // The field is not defined in this class.
                return null;
            }

            if (isStatic && !HANDLE_STATIC_FIELDS) {
                return null;
            }

            MethodInvocation backup = ast.newMethodInvocation();

            if (newObject != null) {
                backup.setExpression(newObject);
            }

            SimpleName newName = ast.newSimpleName(_getBackupMethodName(name
                    .getIdentifier()));
            backup.setName(newName);

            // If the field is static, add the checkpoint object as the first
            // argument.
            if (isStatic) {
                backup.arguments().add(ast.newSimpleName(CHECKPOINT_NAME));
            }

            // Add all the indices into the argument list.
            backup.arguments().addAll(indices);
View Full Code Here

     *   following types: {@link Assignment}, {@link PostfixExpression}, and
     *   {@link PrefixExpression}.
     *  @param state The current state of the type analyzer.
     */
    private void _handleAssignment(ASTNode node, TypeAnalyzerState state) {
        AST ast = node.getAST();
        boolean isSpecial;

        if (node instanceof Assignment) {
            isSpecial = ((Assignment) node).getOperator() != Assignment.Operator.ASSIGN;
        } else {
            isSpecial = true;
        }

        // Get the left-hand side and right-hand side.
        Expression leftHand;

        // Get the left-hand side and right-hand side.
        Expression rightHand;

        if (node instanceof Assignment) {
            leftHand = ((Assignment) node).getLeftHandSide();
            rightHand = ((Assignment) node).getRightHandSide();
        } else if (node instanceof PrefixExpression) {
            leftHand = rightHand = ((PrefixExpression) node).getOperand();
        } else {
            leftHand = rightHand = ((PostfixExpression) node).getOperand();
        }

        while (leftHand instanceof ParenthesizedExpression) {
            leftHand = ((ParenthesizedExpression) leftHand).getExpression();
        }

        // If left-hand side is an array access, store the indices.
        List indices = new LinkedList();

        while (leftHand instanceof ArrayAccess) {
            ArrayAccess arrayAccess = (ArrayAccess) leftHand;
            indices.add(0, ASTNode.copySubtree(ast, arrayAccess.getIndex()));
            leftHand = arrayAccess.getArray();

            while (leftHand instanceof ParenthesizedExpression) {
                leftHand = ((ParenthesizedExpression) leftHand).getExpression();
            }
        }

        // For expression.name on the left-hand side, set newObject to be the
        // expression and name to be the name. newObject may be null.
        Expression newObject = null;
        SimpleName name;

        if (leftHand instanceof FieldAccess) {
            Expression object = ((FieldAccess) leftHand).getExpression();
            name = ((FieldAccess) leftHand).getName();

            Type type = Type.getType(object);

            if (!type.getName().equals(state.getCurrentClass().getName())) {
                return;
            }

            newObject = (Expression) ASTNode.copySubtree(ast, object);
        } else if (leftHand instanceof QualifiedName) {
            Name object = ((QualifiedName) leftHand).getQualifier();
            name = ((QualifiedName) leftHand).getName();

            Type type = Type.getType(object);

            if (!type.getName().equals(state.getCurrentClass().getName())) {
                return;
            }

            newObject = (Expression) ASTNode.copySubtree(ast, object);
        } else if (leftHand instanceof SimpleName) {
            name = (SimpleName) leftHand;
        } else {
            return; // Some unknown situation.
        }

        // Get the owner of the left-hand side, if it is a field.
        Type owner = Type.getOwner(leftHand);

        if (owner == null) { // Not a field.
            return;
        }

        // Get the class of the owner and test the modifiers of the field.
        Class ownerClass;
        boolean isStatic;

        try {
            ownerClass = owner.toClass(state.getClassLoader());

            Field field = ownerClass.getDeclaredField(name.getIdentifier());
            int modifiers = field.getModifiers();

            if (!java.lang.reflect.Modifier.isPrivate(modifiers)) {
                return; // Not handling non-private fields or final fields.
            }

            if (java.lang.reflect.Modifier.isFinal(modifiers)) {
                if (!field.getType().isArray()) {
                    return;
                }
            }

            isStatic = java.lang.reflect.Modifier.isStatic(modifiers);
        } catch (ClassNotFoundException e) {
            throw new ASTClassNotFoundException(owner.getName());
        } catch (NoSuchFieldException e) {
            // The field is not defined in this class.
            return;
        }

        if (isStatic && !HANDLE_STATIC_FIELDS) {
            return;
        }

        // The new method invocation to replace the assignment.
        MethodInvocation invocation = ast.newMethodInvocation();

        // Set the expression and name of the method invocation.
        if (newObject != null) {
            invocation.setExpression(newObject);
        }

        SimpleName newName = ast.newSimpleName(_getAssignMethodName(name
                .getIdentifier(), isSpecial));
        invocation.setName(newName);

        // If the field is static, add the checkpoint object as the first
        // argument.
        if (isStatic) {
            invocation.arguments().add(ast.newSimpleName(CHECKPOINT_NAME));
        }

        // Add an operator, if necessary.
        Type type = Type.getType(node);

        if (isSpecial && _assignOperators.containsKey(type.getName())) {
            int i = 0;
            String[] operators = _assignOperators.get(type.getName());

            String operator;

            if (node instanceof Assignment) {
                operator = ((Assignment) node).getOperator().toString();
            } else if (node instanceof PrefixExpression) {
                operator = ((PrefixExpression) node).getOperator().toString();
            } else {
                operator = ((PostfixExpression) node).getOperator().toString();
            }

            for (; i < operators.length; i++) {
                if (operators[i].equals(operator)) {
                    break;
                }
            }

            if (node instanceof PrefixExpression) {
                i += 2;
            }

            invocation.arguments().add(
                    ast.newNumberLiteral(Integer.toString(i)));
        }

        // Add all the indices into the argument list.
        invocation.arguments().addAll(indices);

        // Add the right-hand side expression to the argument list.
        Type rightHandType = Type.getType(rightHand);

        if (!isSpecial && type.isPrimitive() && !type.equals(rightHandType)) {
            // Require an explicit conversion.
            CastExpression castExpression = ast.newCastExpression();
            castExpression.setType(createType(ast, type.getName()));
            castExpression.setExpression((Expression) ASTNode.copySubtree(ast,
                    rightHand));
            rightHand = castExpression;
        } else {
            rightHand = (Expression) ASTNode.copySubtree(ast, rightHand);

            if (isSpecial && type.getName().equals(String.class.getName())
                    && !type.equals(rightHandType)) {
                InfixExpression extraPlus = ast.newInfixExpression();
                extraPlus.setLeftOperand(ast.newStringLiteral());
                extraPlus.setOperator(InfixExpression.Operator.PLUS);
                extraPlus.setRightOperand(rightHand);
                rightHand = extraPlus;
            }
        }
View Full Code Here

            TypeAnalyzerState state) {
        Class currentClass = state.getCurrentClass();
        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() == 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);
            }
View Full Code Here

   * @param classToImport The fully qualified name of the class to import
   * @param compilationUnit The compilation unit to add the import to
   */
  void addImportToCompilationUnit(String classToImport, CompilationUnit compilationUnit) {
    if (!isClassImported(classToImport, compilationUnit)) {
      AST ast = compilationUnit.getAST();

      Name name = createQualifiedName(ast, classToImport);
      ImportDeclaration importDeclaration = ast.newImportDeclaration();
      importDeclaration.setName(name);
      importDeclaration.setOnDemand(false);
      importDeclaration.setStatic(false);

      compilationUnit.imports().add(importDeclaration);
View Full Code Here

   * @throws JavaModelException
   */
  private Expression createAnnotationPropertyValueExpression(CompilationUnit cu, Class<?> type, Object value) throws JavaModelException {
    Expression expression = null;

    AST ast = cu.getAST();

    if (type.isAnnotation() && (value instanceof Map)) {
      return createModifier(ast, type, (Map) value, cu);
    } else if (value.getClass().isArray()) {
      Object[] objects = (Object[]) value;

      expression = ast.newArrayInitializer();

      for (Object object : objects) {
        Expression objExpr = createAnnotationPropertyValueExpression(cu, type.getComponentType(), object);
        ((ArrayInitializer) expression).expressions().add(objExpr);
      }
    } else if ((value instanceof String) && (type == Class.class)) {
      expression = ast.newTypeLiteral();
      SimpleType newSimpleType = ast.newSimpleType(ast.newName((String) value));
      ((TypeLiteral) expression).setType(newSimpleType);

      addImportToCompilationUnit((String) value, cu);
    } else if (value instanceof String) {
      expression = ast.newStringLiteral();
      ((StringLiteral) expression).setLiteralValue(value.toString());
    } else if (value.getClass().isEnum()) {
      String enumClass = value.getClass().getSimpleName();
      String enumVal = value.toString();
      expression = ast.newQualifiedName(ast.newSimpleName(enumClass), ast.newSimpleName(enumVal));

      addImportToCompilationUnit(value.getClass().getCanonicalName(), cu);
    }

    return expression;
View Full Code Here

    try {
      CompilationUnit cu = compilationUnitCache.getCompilationUnit(targetClass);
      addImportToCompilationUnit(interfaceClass, cu);

      TypeDeclaration typeDeclaration = compilationUnitCache.getTypeDeclaration(targetClass);
      AST ast = cu.getAST();
      SimpleType interfaceType = ast.newSimpleType(createQualifiedName(ast, interfaceClass));

      typeDeclaration.superInterfaceTypes().add(interfaceType);
    } catch (Exception e) {
      warnings.add(String.format(Messages.getString("org.apache.openejb.helper.annotation.warnings.12"), interfaceClass, targetClass)); //$NON-NLS-1$
    }
View Full Code Here

TOP

Related Classes of org.eclipse.jdt.core.dom.AST

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.