Search in sources :

Example 6 with CheASTParser

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

the class ASTProvider method createAST.

/**
     * Creates a new compilation unit AST.
     *
     * @param input the Java element for which to create the AST
     * @param progressMonitor the progress monitor
     * @return AST
     */
public static CompilationUnit createAST(final ITypeRoot input, final IProgressMonitor progressMonitor) {
    if (!hasSource(input))
        return null;
    if (progressMonitor != null && progressMonitor.isCanceled())
        return null;
    final CheASTParser parser = CheASTParser.newParser(SHARED_AST_LEVEL);
    parser.setResolveBindings(true);
    parser.setStatementsRecovery(SHARED_AST_STATEMENT_RECOVERY);
    parser.setBindingsRecovery(SHARED_BINDING_RECOVERY);
    parser.setSource(input);
    if (progressMonitor != null && progressMonitor.isCanceled())
        return null;
    final CompilationUnit[] root = new CompilationUnit[1];
    SafeRunner.run(new ISafeRunnable() {

        public void run() {
            try {
                if (progressMonitor != null && progressMonitor.isCanceled())
                    return;
                if (DEBUG)
                    System.err.println(getThreadName() + " - " + DEBUG_PREFIX + "creating AST for: " + //$NON-NLS-1$ //$NON-NLS-2$
                    input.getElementName());
                root[0] = (CompilationUnit) parser.createAST(progressMonitor);
                //mark as unmodifiable
                ASTNodes.setFlagsToAST(root[0], ASTNode.PROTECT);
            } catch (OperationCanceledException ex) {
                return;
            }
        }

        public void handleException(Throwable ex) {
            LOG.error(ex.getMessage(), ex);
        }
    });
    return root[0];
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ISafeRunnable(org.eclipse.core.runtime.ISafeRunnable) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser)

Example 7 with CheASTParser

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

the class AnonymousTypeCompletionProposal method createNewBody.

private String createNewBody(ImportRewrite importRewrite) throws CoreException {
    if (importRewrite == null)
        return null;
    ICompilationUnit workingCopy = null;
    try {
        //$NON-NLS-1$
        String name = "Type" + System.currentTimeMillis();
        workingCopy = fCompilationUnit.getPrimary().getWorkingCopy(null);
        ISourceRange range = fSuperType.getSourceRange();
        boolean sameUnit = range != null && fCompilationUnit.equals(fSuperType.getCompilationUnit());
        // creates a type that extends the super type
        String dummyClassContent = createDummyType(name);
        StringBuffer workingCopyContents = new StringBuffer(fCompilationUnit.getSource());
        int insertPosition;
        if (sameUnit) {
            insertPosition = range.getOffset() + range.getLength();
        } else {
            ISourceRange firstTypeRange = fCompilationUnit.getTypes()[0].getSourceRange();
            insertPosition = firstTypeRange.getOffset();
        }
        if (fSuperType.isLocal()) {
            // add an extra block: helps the AST to recover
            workingCopyContents.insert(insertPosition, '{' + dummyClassContent + '}');
            insertPosition++;
        } else {
            /*
				 * The two empty lines are added because the trackedDeclaration uses the covered range
				 * and hence would also included comments that directly follow the dummy class.
				 */
            //$NON-NLS-1$
            workingCopyContents.insert(insertPosition, dummyClassContent + "\n\n");
        }
        workingCopy.getBuffer().setContents(workingCopyContents.toString());
        CheASTParser parser = CheASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setResolveBindings(true);
        parser.setStatementsRecovery(true);
        parser.setSource(workingCopy);
        CompilationUnit astRoot = (CompilationUnit) parser.createAST(new NullProgressMonitor());
        ASTNode newType = NodeFinder.perform(astRoot, insertPosition, dummyClassContent.length());
        if (!(newType instanceof AbstractTypeDeclaration))
            return null;
        AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) newType;
        ITypeBinding dummyTypeBinding = declaration.resolveBinding();
        if (dummyTypeBinding == null)
            return null;
        IMethodBinding[] bindings = StubUtility2.getOverridableMethods(astRoot.getAST(), dummyTypeBinding, true);
        if (fSuperType.isInterface()) {
            ITypeBinding[] dummySuperInterfaces = dummyTypeBinding.getInterfaces();
            if (dummySuperInterfaces.length == 0 || dummySuperInterfaces.length == 1 && dummySuperInterfaces[0].isRawType())
                bindings = new IMethodBinding[0];
        } else {
            ITypeBinding dummySuperclass = dummyTypeBinding.getSuperclass();
            if (dummySuperclass == null || dummySuperclass.isRawType())
                bindings = new IMethodBinding[0];
        }
        CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fSuperType.getJavaProject());
        IMethodBinding[] methodsToOverride = null;
        IType type = null;
        if (!fSuperType.isInterface() && !fSuperType.isAnnotation()) {
            IJavaElement typeElement = dummyTypeBinding.getJavaElement();
            // add extra checks here as the recovered code is fragile
            if (typeElement instanceof IType && name.equals(typeElement.getElementName()) && typeElement.exists()) {
                type = (IType) typeElement;
            }
        }
        if (type != null) {
            //TODO window
            throw new UnsupportedOperationException();
        } else {
            settings.createComments = false;
            List<IMethodBinding> result = new ArrayList<IMethodBinding>();
            for (int i = 0; i < bindings.length; i++) {
                IMethodBinding curr = bindings[i];
                if (Modifier.isAbstract(curr.getModifiers()))
                    result.add(curr);
            }
            methodsToOverride = result.toArray(new IMethodBinding[result.size()]);
        }
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        ITrackedNodePosition trackedDeclaration = rewrite.track(declaration);
        ListRewrite rewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
        for (int i = 0; i < methodsToOverride.length; i++) {
            IMethodBinding curr = methodsToOverride[i];
            MethodDeclaration stub = StubUtility2.createImplementationStub(workingCopy, rewrite, importRewrite, null, curr, dummyTypeBinding.getName(), settings, dummyTypeBinding.isInterface());
            rewriter.insertFirst(stub, null);
        }
        IDocument document = new Document(workingCopy.getSource());
        try {
            rewrite.rewriteAST().apply(document);
            int bodyStart = trackedDeclaration.getStartPosition() + dummyClassContent.indexOf('{');
            int bodyEnd = trackedDeclaration.getStartPosition() + trackedDeclaration.getLength();
            return document.get(bodyStart, bodyEnd - bodyStart);
        } catch (MalformedTreeException exception) {
            JavaPlugin.log(exception);
        } catch (BadLocationException exception) {
            JavaPlugin.log(exception);
        }
        return null;
    } finally {
        if (workingCopy != null)
            workingCopy.discardWorkingCopy();
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) ArrayList(java.util.ArrayList) StyledString(org.eclipse.jface.viewers.StyledString) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IType(org.eclipse.jdt.core.IType) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ITrackedNodePosition(org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition) ISourceRange(org.eclipse.jdt.core.ISourceRange) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 8 with CheASTParser

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

the class ASTNodeFactory method newTypeParameter.

public static TypeParameter newTypeParameter(AST ast, String content) {
    StringBuffer buffer = new StringBuffer(TYPEPARAM_HEADER);
    buffer.append(content);
    buffer.append(TYPEPARAM_FOOTER);
    CheASTParser p = CheASTParser.newParser(ast.apiLevel());
    p.setSource(buffer.toString().toCharArray());
    CompilationUnit root = (CompilationUnit) p.createAST(null);
    List<AbstractTypeDeclaration> list = root.types();
    TypeDeclaration typeDecl = (TypeDeclaration) list.get(0);
    MethodDeclaration methodDecl = typeDecl.getMethods()[0];
    TypeParameter tp = (TypeParameter) methodDecl.typeParameters().get(0);
    ASTNode result = ASTNode.copySubtree(ast, tp);
    result.accept(new PositionClearer());
    return (TypeParameter) result;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) TypeParameter(org.eclipse.jdt.core.dom.TypeParameter) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 9 with CheASTParser

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

the class ASTNodeFactory method newStatement.

public static ASTNode newStatement(AST ast, String content) {
    StringBuffer buffer = new StringBuffer(STATEMENT_HEADER);
    buffer.append(content);
    buffer.append(STATEMENT_FOOTER);
    CheASTParser p = CheASTParser.newParser(ast.apiLevel());
    p.setSource(buffer.toString().toCharArray());
    CompilationUnit root = (CompilationUnit) p.createAST(null);
    ASTNode result = ASTNode.copySubtree(ast, NodeFinder.perform(root, STATEMENT_HEADER.length(), content.length()));
    result.accept(new PositionClearer());
    return result;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser)

Example 10 with CheASTParser

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

the class StubUtility2 method getImplementationModifiers.

private static List<IExtendedModifier> getImplementationModifiers(AST ast, IMethodBinding method, boolean inInterface, ImportRewrite importRewrite, ImportRewriteContext context) throws JavaModelException {
    IJavaProject javaProject = importRewrite.getCompilationUnit().getJavaProject();
    int modifiers = method.getModifiers() & ~Modifier.ABSTRACT & ~Modifier.NATIVE & ~Modifier.PRIVATE;
    if (inInterface) {
        modifiers = modifiers & ~Modifier.PROTECTED;
        if (!method.getDeclaringClass().isInterface()) {
            modifiers = modifiers | Modifier.PUBLIC;
        }
    } else {
        modifiers = modifiers & ~Modifier.DEFAULT;
    }
    IAnnotationBinding[] annotations = method.getAnnotations();
    if (modifiers != Modifier.NONE && annotations.length > 0) {
        // need an AST of the source method to preserve order of modifiers
        IMethod iMethod = (IMethod) method.getJavaElement();
        if (iMethod != null && JavaElementUtil.isSourceAvailable(iMethod)) {
            CheASTParser parser = CheASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(iMethod.getTypeRoot());
            parser.setIgnoreMethodBodies(true);
            CompilationUnit otherCU = (CompilationUnit) parser.createAST(null);
            ASTNode otherMethod = NodeFinder.perform(otherCU, iMethod.getSourceRange());
            if (otherMethod instanceof MethodDeclaration) {
                MethodDeclaration otherMD = (MethodDeclaration) otherMethod;
                ArrayList<IExtendedModifier> result = new ArrayList<IExtendedModifier>();
                List<IExtendedModifier> otherModifiers = otherMD.modifiers();
                for (IExtendedModifier otherModifier : otherModifiers) {
                    if (otherModifier instanceof Modifier) {
                        int otherFlag = ((Modifier) otherModifier).getKeyword().toFlagValue();
                        if ((otherFlag & modifiers) != 0) {
                            modifiers = ~otherFlag & modifiers;
                            result.addAll(ast.newModifiers(otherFlag));
                        }
                    } else {
                        Annotation otherAnnotation = (Annotation) otherModifier;
                        String n = otherAnnotation.getTypeName().getFullyQualifiedName();
                        for (IAnnotationBinding annotation : annotations) {
                            ITypeBinding otherAnnotationType = annotation.getAnnotationType();
                            String qn = otherAnnotationType.getQualifiedName();
                            if (qn.endsWith(n) && (qn.length() == n.length() || qn.charAt(qn.length() - n.length() - 1) == '.')) {
                                if (StubUtility2.isCopyOnInheritAnnotation(otherAnnotationType, javaProject))
                                    result.add(importRewrite.addAnnotation(annotation, ast, context));
                                break;
                            }
                        }
                    }
                }
                result.addAll(ASTNodeFactory.newModifiers(ast, modifiers));
                return result;
            }
        }
    }
    ArrayList<IExtendedModifier> result = new ArrayList<IExtendedModifier>();
    for (IAnnotationBinding annotation : annotations) {
        if (StubUtility2.isCopyOnInheritAnnotation(annotation.getAnnotationType(), javaProject))
            result.add(importRewrite.addAnnotation(annotation, ast, context));
    }
    result.addAll(ASTNodeFactory.newModifiers(ast, modifiers));
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ArrayList(java.util.ArrayList) Annotation(org.eclipse.jdt.core.dom.Annotation) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) IJavaProject(org.eclipse.jdt.core.IJavaProject) IAnnotationBinding(org.eclipse.jdt.core.dom.IAnnotationBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) IMethod(org.eclipse.jdt.core.IMethod) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) Modifier(org.eclipse.jdt.core.dom.Modifier)

Aggregations

CheASTParser (org.eclipse.jdt.core.dom.CheASTParser)10 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)8 ASTNode (org.eclipse.jdt.core.dom.ASTNode)5 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)4 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)3 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)3 ArrayList (java.util.ArrayList)2 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 IJavaProject (org.eclipse.jdt.core.IJavaProject)2 IBinding (org.eclipse.jdt.core.dom.IBinding)2 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)2 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)2 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)2 StyledString (org.eclipse.jface.viewers.StyledString)2 HashMap (java.util.HashMap)1 ISafeRunnable (org.eclipse.core.runtime.ISafeRunnable)1 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)1 IJavaElement (org.eclipse.jdt.core.IJavaElement)1 IMethod (org.eclipse.jdt.core.IMethod)1 ISourceRange (org.eclipse.jdt.core.ISourceRange)1