Search in sources :

Example 91 with AbstractTypeDeclaration

use of org.eclipse.jdt.core.dom.AbstractTypeDeclaration in project che by eclipse.

the class StubUtility method getCatchBodyContent.

public static String getCatchBodyContent(ICompilationUnit cu, String exceptionType, String variableName, ASTNode locationInAST, String lineDelimiter) throws CoreException {
    //$NON-NLS-1$
    String enclosingType = "";
    //$NON-NLS-1$
    String enclosingMethod = "";
    if (locationInAST != null) {
        MethodDeclaration parentMethod = ASTResolving.findParentMethodDeclaration(locationInAST);
        if (parentMethod != null) {
            enclosingMethod = parentMethod.getName().getIdentifier();
            locationInAST = parentMethod;
        }
        ASTNode parentType = ASTResolving.findParentType(locationInAST);
        if (parentType instanceof AbstractTypeDeclaration) {
            enclosingType = ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
        }
    }
    return getCatchBodyContent(cu, exceptionType, variableName, enclosingType, enclosingMethod, lineDelimiter);
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 92 with AbstractTypeDeclaration

use of org.eclipse.jdt.core.dom.AbstractTypeDeclaration in project che by eclipse.

the class AssignToVariableAssistProposal method doAddField.

private ASTRewrite doAddField() {
    boolean isParamToField = fNodeToAssign.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION;
    ASTNode newTypeDecl = ASTResolving.findParentType(fNodeToAssign);
    if (newTypeDecl == null) {
        return null;
    }
    Expression expression = isParamToField ? ((SingleVariableDeclaration) fNodeToAssign).getName() : ((ExpressionStatement) fNodeToAssign).getExpression();
    AST ast = newTypeDecl.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    createImportRewrite((CompilationUnit) fNodeToAssign.getRoot());
    BodyDeclaration bodyDecl = ASTResolving.findParentBodyDeclaration(fNodeToAssign);
    Block body;
    if (bodyDecl instanceof MethodDeclaration) {
        body = ((MethodDeclaration) bodyDecl).getBody();
    } else if (bodyDecl instanceof Initializer) {
        body = ((Initializer) bodyDecl).getBody();
    } else {
        return null;
    }
    IJavaProject project = getCompilationUnit().getJavaProject();
    boolean isAnonymous = newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
    boolean isStatic = Modifier.isStatic(bodyDecl.getModifiers()) && !isAnonymous;
    boolean isConstructorParam = isParamToField && fNodeToAssign.getParent() instanceof MethodDeclaration && ((MethodDeclaration) fNodeToAssign.getParent()).isConstructor();
    int modifiers = Modifier.PRIVATE;
    if (isStatic) {
        modifiers |= Modifier.STATIC;
    } else if (isConstructorParam) {
    //			String saveActionsKey= AbstractSaveParticipantPreferenceConfiguration.EDITOR_SAVE_PARTICIPANT_PREFIX + CleanUpPostSaveListener.POSTSAVELISTENER_ID;
    //			IScopeContext[] scopes= { InstanceScope.INSTANCE, new ProjectScope(project.getProject()) };
    //			boolean safeActionsEnabled= Platform.getPreferencesService().getBoolean(JavaPlugin.getPluginId(), saveActionsKey, false, scopes);
    }
    if (/*CleanUpOptions.TRUE.equals(PreferenceConstants.getPreference(
					CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + CleanUpConstants.CLEANUP_ON_SAVE_ADDITIONAL_OPTIONS, project))
			&&*/
    CleanUpOptions.TRUE.equals(PreferenceConstants.getPreference(CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL, project)) && CleanUpOptions.TRUE.equals(PreferenceConstants.getPreference(CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, project))) {
        int constructors = 0;
        if (newTypeDecl instanceof AbstractTypeDeclaration) {
            List<BodyDeclaration> bodyDeclarations = ((AbstractTypeDeclaration) newTypeDecl).bodyDeclarations();
            for (BodyDeclaration decl : bodyDeclarations) {
                if (decl instanceof MethodDeclaration && ((MethodDeclaration) decl).isConstructor()) {
                    constructors++;
                }
            }
        }
        if (constructors == 1) {
            modifiers |= Modifier.FINAL;
        }
    }
    VariableDeclarationFragment newDeclFrag = addFieldDeclaration(rewrite, newTypeDecl, modifiers, expression);
    String varName = newDeclFrag.getName().getIdentifier();
    Assignment assignment = ast.newAssignment();
    assignment.setRightHandSide((Expression) rewrite.createCopyTarget(expression));
    boolean needsThis = StubUtility.useThisForFieldAccess(project);
    if (isParamToField) {
        needsThis |= varName.equals(((SimpleName) expression).getIdentifier());
    }
    SimpleName accessName = ast.newSimpleName(varName);
    if (needsThis) {
        FieldAccess fieldAccess = ast.newFieldAccess();
        fieldAccess.setName(accessName);
        if (isStatic) {
            String typeName = ((AbstractTypeDeclaration) newTypeDecl).getName().getIdentifier();
            fieldAccess.setExpression(ast.newSimpleName(typeName));
        } else {
            fieldAccess.setExpression(ast.newThisExpression());
        }
        assignment.setLeftHandSide(fieldAccess);
    } else {
        assignment.setLeftHandSide(accessName);
    }
    ASTNode selectionNode;
    if (isParamToField) {
        // assign parameter to field
        ExpressionStatement statement = ast.newExpressionStatement(assignment);
        int insertIdx = findAssignmentInsertIndex(body.statements());
        rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY).insertAt(statement, insertIdx, null);
        selectionNode = statement;
    } else {
        if (needsSemicolon(expression)) {
            rewrite.replace(expression, ast.newExpressionStatement(assignment), null);
        } else {
            rewrite.replace(expression, assignment, null);
        }
        selectionNode = fNodeToAssign;
    }
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
    if (!isParamToField) {
        FieldDeclaration fieldDeclaration = (FieldDeclaration) newDeclFrag.getParent();
        addLinkedPosition(rewrite.track(fieldDeclaration.getType()), false, KEY_TYPE);
    }
    addLinkedPosition(rewrite.track(accessName), true, KEY_NAME);
    IVariableBinding variableBinding = newDeclFrag.resolveBinding();
    if (variableBinding != null) {
        SimpleName[] linkedNodes = LinkedNodeFinder.findByBinding(fNodeToAssign.getRoot(), variableBinding);
        for (int i = 0; i < linkedNodes.length; i++) {
            addLinkedPosition(rewrite.track(linkedNodes[i]), false, KEY_NAME);
        }
    }
    setEndPosition(rewrite.track(selectionNode));
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) Assignment(org.eclipse.jdt.core.dom.Assignment) IJavaProject(org.eclipse.jdt.core.IJavaProject) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) Initializer(org.eclipse.jdt.core.dom.Initializer) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 93 with AbstractTypeDeclaration

use of org.eclipse.jdt.core.dom.AbstractTypeDeclaration in project che by eclipse.

the class SelfEncapsulateFieldRefactoring method checkFinalConditions.

@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
    pm.beginTask(NO_NAME, 12);
    pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions);
    RefactoringStatus result = new RefactoringStatus();
    fRewriter = ASTRewrite.create(fRoot.getAST());
    fChangeManager.clear();
    boolean usingLocalGetter = isUsingLocalGetter();
    boolean usingLocalSetter = isUsingLocalSetter();
    result.merge(checkMethodNames(usingLocalGetter, usingLocalSetter));
    pm.worked(1);
    if (result.hasFatalError())
        return result;
    pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits);
    final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5);
    ICompilationUnit[] affectedCUs = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(fField, fConsiderVisibility), subPm, result, true);
    checkInHierarchy(result, usingLocalGetter, usingLocalSetter);
    if (result.hasFatalError())
        return result;
    pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing);
    IProgressMonitor sub = new SubProgressMonitor(pm, 5);
    sub.beginTask(NO_NAME, affectedCUs.length);
    IVariableBinding fieldIdentifier = fFieldDeclaration.resolveBinding();
    ITypeBinding declaringClass = ((AbstractTypeDeclaration) ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class)).resolveBinding();
    List<TextEditGroup> ownerDescriptions = new ArrayList<TextEditGroup>();
    ICompilationUnit owner = fField.getCompilationUnit();
    fImportRewrite = StubUtility.createImportRewrite(fRoot, true);
    for (int i = 0; i < affectedCUs.length; i++) {
        ICompilationUnit unit = affectedCUs[i];
        sub.subTask(BasicElementLabels.getFileName(unit));
        CompilationUnit root = null;
        ASTRewrite rewriter = null;
        ImportRewrite importRewrite;
        List<TextEditGroup> descriptions;
        if (owner.equals(unit)) {
            root = fRoot;
            rewriter = fRewriter;
            importRewrite = fImportRewrite;
            descriptions = ownerDescriptions;
        } else {
            root = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(unit, true);
            rewriter = ASTRewrite.create(root.getAST());
            descriptions = new ArrayList<TextEditGroup>();
            importRewrite = StubUtility.createImportRewrite(root, true);
        }
        checkCompileErrors(result, root, unit);
        AccessAnalyzer analyzer = new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite);
        root.accept(analyzer);
        result.merge(analyzer.getStatus());
        if (!fSetterMustReturnValue)
            fSetterMustReturnValue = analyzer.getSetterMustReturnValue();
        if (result.hasFatalError()) {
            fChangeManager.clear();
            return result;
        }
        descriptions.addAll(analyzer.getGroupDescriptions());
        if (!owner.equals(unit))
            createEdits(unit, rewriter, descriptions, importRewrite);
        sub.worked(1);
        if (pm.isCanceled())
            throw new OperationCanceledException();
    }
    ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(), usingLocalSetter, usingLocalGetter));
    createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite);
    sub.done();
    IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
    result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
    if (result.hasFatalError())
        return result;
    ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IFile(org.eclipse.core.resources.IFile) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TextEditGroup(org.eclipse.text.edits.TextEditGroup) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 94 with AbstractTypeDeclaration

use of org.eclipse.jdt.core.dom.AbstractTypeDeclaration in project che by eclipse.

the class SelfEncapsulateFieldRefactoring method checkInHierarchy.

private void checkInHierarchy(RefactoringStatus status, boolean usingLocalGetter, boolean usingLocalSetter) {
    AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class);
    ITypeBinding type = declaration.resolveBinding();
    if (type != null) {
        ITypeBinding fieldType = fFieldDeclaration.resolveBinding().getType();
        checkMethodInHierarchy(type, fGetterName, fieldType, new ITypeBinding[0], status, usingLocalGetter);
        checkMethodInHierarchy(//$NON-NLS-1$
        type, //$NON-NLS-1$
        fSetterName, //$NON-NLS-1$
        fFieldDeclaration.getAST().resolveWellKnownType("void"), new ITypeBinding[] { fieldType }, status, usingLocalSetter);
    }
}
Also used : ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 95 with AbstractTypeDeclaration

use of org.eclipse.jdt.core.dom.AbstractTypeDeclaration in project AutoRefactor by JnRouvignac.

the class RemoveSemiColonRefactoring method visit.

private boolean visit(BodyDeclaration node) {
    final BodyDeclaration nextSibling = getNextSibling(node);
    final ASTNode parent = node.getParent();
    if (nextSibling != null) {
        return removeSuperfluousSemiColons(node, getEndPosition(node), nextSibling.getStartPosition());
    } else if (parent instanceof AbstractTypeDeclaration) {
        final AbstractTypeDeclaration typeDecl = (AbstractTypeDeclaration) parent;
        return removeSuperfluousSemiColons(node, getEndPosition(node), getEndPosition(typeDecl) - 1);
    } else if (parent instanceof AnonymousClassDeclaration) {
        final AnonymousClassDeclaration classDecl = (AnonymousClassDeclaration) parent;
        return removeSuperfluousSemiColons(node, getEndPosition(node), getEndPosition(classDecl) - 1);
    } else if (parent instanceof CompilationUnit) {
        final CompilationUnit cu = (CompilationUnit) parent;
        return removeSuperfluousSemiColons(node, getEndPosition(node), getEndPosition(cu) - 1);
    } else if (parent instanceof TypeDeclarationStatement) {
        return VISIT_SUBTREE;
    }
    throw new NotImplementedException(node, "for a parent of type " + (parent != null ? parent.getClass().getSimpleName() : null));
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) TypeDeclarationStatement(org.eclipse.jdt.core.dom.TypeDeclarationStatement) NotImplementedException(org.autorefactor.util.NotImplementedException) ASTNode(org.eclipse.jdt.core.dom.ASTNode) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Aggregations

AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)124 ASTNode (org.eclipse.jdt.core.dom.ASTNode)71 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)51 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)39 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)39 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)34 AnonymousClassDeclaration (org.eclipse.jdt.core.dom.AnonymousClassDeclaration)33 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)28 ArrayList (java.util.ArrayList)25 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)25 AST (org.eclipse.jdt.core.dom.AST)24 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)24 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)23 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)21 Type (org.eclipse.jdt.core.dom.Type)19 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)19 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)17 IType (org.eclipse.jdt.core.IType)16 Javadoc (org.eclipse.jdt.core.dom.Javadoc)13 SimpleName (org.eclipse.jdt.core.dom.SimpleName)13