Example usage for org.eclipse.jdt.core.dom ASTParser createAST

List of usage examples for org.eclipse.jdt.core.dom ASTParser createAST

Introduction

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

Prototype

public ASTNode createAST(IProgressMonitor monitor) 

Source Link

Document

Creates an abstract syntax tree.

Usage

From source file:org.eclipse.ajdt.core.tests.codeconversion.AspectsConvertingParserTest.java

License:Open Source License

/**
 * test that '?' in type parameters are converted correctly
 *///  www.  jav  a 2 s. c  o  m
public void testBug282948() throws Exception {
    IProject bug282948 = createPredefinedProject("Bug282948");
    IFile file = bug282948.getFile("src/RR.aj");
    String source = getContents(file);

    ConversionOptions conversionOptions = ConversionOptions.STANDARD;
    AspectsConvertingParser conv = new AspectsConvertingParser(source.toCharArray());
    conv.convert(conversionOptions);
    String converted = new String(conv.content);

    // now convert using a regular Java parser:
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(converted.toCharArray());
    CompilationUnit result = (CompilationUnit) parser.createAST(null);
    if (result.getProblems().length > 0) {
        fail("Improperly converted.  Original:\n" + source + "\nConverted:\n" + converted); //$NON-NLS-1$
    }
}

From source file:org.eclipse.ajdt.internal.debug.ui.actions.ToggleBreakpointAdapter.java

License:Open Source License

protected CompilationUnit parseCompilationUnit(ITextEditor editor) throws CoreException {
    IEditorInput editorInput = editor.getEditorInput();
    IDocumentProvider documentProvider = editor.getDocumentProvider();
    if (documentProvider == null) {
        throw new CoreException(Status.CANCEL_STATUS);
    }/*from ww  w .  j a  v a 2 s. c  o m*/
    IDocument document = documentProvider.getDocument(editorInput);
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(document.get().toCharArray());
    return (CompilationUnit) parser.createAST(null);
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.ITDRenameRefactoringProvider.java

License:Open Source License

public CompilationUnit createASTForRefactoring(ITypeRoot root) {
    if (root instanceof AJCompilationUnit) {
        AJCompilationUnit ajUnit = (AJCompilationUnit) root;

        // create a clone of the original ajUnit so that 
        // an ast and its bindings can be created on the constant sized source 
        // code//  w w  w.  j av  a2  s  . c om
        try {
            ajUnit.requestOriginalContentMode();
            char[] contents = ((AJCompilationUnit) root).getContents();
            ajUnit.discardOriginalContentMode();
            AspectsConvertingParser acp = new AspectsConvertingParser(contents);
            acp.convert(ConversionOptions.CONSTANT_SIZE);
            AJCompilationUnit clone = ajUnit.ajCloneCachingContents(acp.content);
            ASTParser parser = ASTParser.newParser(AST.JLS8);
            parser.setBindingsRecovery(true);
            parser.setResolveBindings(true);
            parser.setSource(clone);
            ASTNode result = parser.createAST(null);
            return result instanceof CompilationUnit ? (CompilationUnit) result : null;
        } catch (JavaModelException e) {
        }
    }
    return null;
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.ITDRenameRefactoringProvider.java

License:Open Source License

/**
 * Creates an AST for the given compilation unit with translated code.
 * The source locations of the created AST have been converted back so that they reflect the source locations
 * of the original, non-translated source.
 *//*from   ww  w  . j  a v  a 2s  .com*/
public CompilationUnit createSourceConvertedAST(String contents, ICompilationUnit unit, boolean resolveBindings,
        boolean statementsRecovery, boolean bindingsRecovery, IProgressMonitor monitor) {
    AspectsConvertingParser converter = new AspectsConvertingParser(contents.toCharArray());
    converter.setUnit(unit);
    final ArrayList<Replacement> replacements = converter.convert(ConversionOptions.CODE_COMPLETION);

    ASTParser fParser = ASTParser.newParser(AST.JLS4);
    fParser.setResolveBindings(resolveBindings);
    fParser.setStatementsRecovery(statementsRecovery);
    fParser.setBindingsRecovery(bindingsRecovery);
    fParser.setProject(unit.getJavaProject());
    fParser.setSource(converter.content);
    fParser.setUnitName(unit.getElementName());
    if (unit.getOwner() != null) {
        fParser.setWorkingCopyOwner(unit.getOwner());
    }
    CompilationUnit result = (CompilationUnit) fParser.createAST(monitor);
    result.accept(new ASTVisitor() {
        @Override
        public void preVisit(ASTNode node) {
            int newStart = AspectsConvertingParser.translatePositionToBeforeChanges(node.getStartPosition(),
                    replacements);
            int newEnd = AspectsConvertingParser
                    .translatePositionToBeforeChanges(node.getStartPosition() + node.getLength(), replacements);
            node.setSourceRange(newStart, newEnd - newStart);
        }
    });
    return result;
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.pullout.PullOutRefactoring.java

License:Open Source License

@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
        throws CoreException, OperationCanceledException {
    RefactoringStatus status = new RefactoringStatus();
    SubProgressMonitor submonitor = new SubProgressMonitor(pm, memberMap.keySet().size());
    submonitor.beginTask("Checking preconditions...", memberMap.keySet().size());
    try {// w w w  . j  ava 2s  .c o m
        aspectChanges = new AspectRewrite();
        // For a more predictable and orderly outcome, sort by the name of the CU
        ICompilationUnit[] cus = memberMap.keySet().toArray(new ICompilationUnit[0]);
        Arrays.sort(cus, CompilationUnitComparator.the);
        for (ICompilationUnit cu : cus) {
            ASTParser parser = ASTParser.newParser(AST.JLS8);
            parser.setSource(cu);
            parser.setResolveBindings(true);
            ASTNode cuNode = parser.createAST(pm);
            for (IMember member : memberMap.get(cu)) {
                BodyDeclaration memberNode = (BodyDeclaration) findASTNode(cuNode, member);
                ITDCreator itd = new ITDCreator(member, memberNode);
                if (member.getDeclaringType().isInterface()) {
                    // No need to check "isAllowMakePublic" since technically it was already public.
                    itd.addModifier(Modifier.PUBLIC);
                }
                if (itd.wasProtected()) {
                    if (isAllowDeleteProtected()) {
                        itd.removeModifier(Modifier.PROTECTED);
                    } else {
                        status.addWarning("moved member '" + member.getElementName() + "' is protected\n"
                                + "protected ITDs are not allowed by AspectJ.\n", makeContext(member));
                    }
                }
                if (itd.wasAbstract()) {
                    if (isGenerateAbstractMethodStubs()) {
                        itd.removeModifier(Modifier.ABSTRACT);
                        itd.setBody(getAbstractMethodStubBody(member));
                    } else {
                        status.addWarning("moved member '" + member.getElementName() + "' is abstract.\n"
                                + "abstract ITDs are not allowed by AspectJ.\n"
                                + "You can enable the 'convert abstract methods' option to avoid this error.",
                                makeContext(member));
                        //If you choose to ignore this error and perform refactoring anyway...
                        // We make sure the abstract keyword is added to the itd, so you will get a compile error
                        // and be forced to deal with that error.
                        itd.addModifier(Modifier.ABSTRACT);
                    }
                }
                checkOutgoingReferences(itd, status);
                checkIncomingReferences(itd, status);
                checkConctructorThisCall(itd, status);
                aspectChanges.addITD(itd, status);
            }
            submonitor.worked(1);
        }
    } catch (BadLocationException e) {
        status.merge(RefactoringStatus.createFatalErrorStatus("Internal error:" + e.getMessage()));
    } finally {
        submonitor.done();
    }
    return status;
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.pullout.PullOutRefactoring.java

License:Open Source License

@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    try {// w  ww .j  a  va2s .  c  o  m
        pm.beginTask("Creating changes...", memberMap.keySet().size());
        CompositeChange allChanges = new CompositeChange("PullOut ITDs");
        for (ICompilationUnit cu : memberMap.keySet()) {

            // Prepare an ASTRewriter for this compilation unit
            ASTParser parser = ASTParser.newParser(AST.JLS8);
            parser.setSource(cu);
            ASTNode cuNode = parser.createAST(pm);
            MultiTextEdit cuEdits = new MultiTextEdit();

            // Apply all operations to the AST rewriter
            for (IMember member : getMembers(cu)) {
                ISourceRange range = member.getSourceRange();
                range = grabSpaceBefore(cu, range);
                cuEdits.addChild(new DeleteEdit(range.getOffset(), range.getLength()));
            }

            // Create CUChange object with the accumulated deletion edits.
            CompilationUnitChange cuChanges = newCompilationUnitChange(cu);
            cuChanges.setEdit(cuEdits);

            // Add changes for this compilation unit.
            allChanges.add(cuChanges);

            pm.worked(1);
        }
        aspectChanges.rewriteAspect(pm, allChanges);
        return allChanges;
    } finally {
        pm.done();
    }
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.PushInRefactoring.java

License:Open Source License

private Type createTypeAST(String newSuper, AST ast) {
    String toParse = newSuper + " t;";
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource((toParse).toCharArray());
    parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
    ASTNode astNode = parser.createAST(null);
    Type t = null;/* w ww  . ja  v a2s.c  om*/
    if (astNode instanceof TypeDeclaration) {
        Object object = ((TypeDeclaration) astNode).bodyDeclarations().get(0);
        if (object instanceof FieldDeclaration) {
            t = ((FieldDeclaration) object).getType();
            t = (Type) ASTNode.copySubtree(ast, t);
        }
    }
    if (t == null) {
        t = ast.newSimpleType(ast.newSimpleName("MISSING"));
    }
    return t;
}

From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java

License:Open Source License

/**
 * Hook method that gets called when the type name has changed. The method validates the 
 * type name and returns the status of the validation.
 * <p>/*from ww  w .j a  v a 2s.  c o m*/
 * Subclasses may extend this method to perform their own validation.
 * </p>
 * 
 * @return the status of the validation
 */
protected IStatus typeNameChanged() {
    StatusInfo status = new StatusInfo();
    fCurrType = null;
    String typeNameWithParameters = getTypeName();
    // must not be empty
    if (typeNameWithParameters.length() == 0) {
        status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
        return status;
    }

    String typeName = getTypeNameWithoutParameters();
    if (typeName.indexOf('.') != -1) {
        status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
        return status;
    }

    IJavaProject project = getJavaProject();
    IStatus val = validateJavaTypeName(typeName, project);
    if (val.getSeverity() == IStatus.ERROR) {
        status.setError(
                Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
        return status;
    } else if (val.getSeverity() == IStatus.WARNING) {
        status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged,
                val.getMessage()));
        // continue checking
    }

    // must not exist
    if (!isEnclosingTypeSelected()) {
        IPackageFragment pack = getPackageFragment();
        if (pack != null) {
            ICompilationUnit cu = pack.getCompilationUnit(getCompilationUnitName(typeName));
            fCurrType = cu.getType(typeName);
            IResource resource = cu.getResource();

            if (resource.exists()) {
                status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
                return status;
            }
            URI location = resource.getLocationURI();
            if (location != null) {
                try {
                    IFileStore store = EFS.getStore(location);
                    if (store.fetchInfo().exists()) {
                        status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
                        return status;
                    }
                } catch (CoreException e) {
                    status.setError(
                            Messages.format(NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown,
                                    BasicElementLabels.getURLPart(Resources.getLocationString(resource))));
                }
            }
        }
    } else {
        IType type = getEnclosingType();
        if (type != null) {
            fCurrType = type.getType(typeName);
            if (fCurrType.exists()) {
                status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
                return status;
            }
        }
    }

    if (!typeNameWithParameters.equals(typeName) && project != null) {
        if (!JavaModelUtil.is50OrHigher(project)) {
            status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
            return status;
        }
        String typeDeclaration = "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$
        ASTParser parser = ASTParser.newParser(AST.JLS8);
        parser.setSource(typeDeclaration.toCharArray());
        parser.setProject(project);
        CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
        IProblem[] problems = compilationUnit.getProblems();
        if (problems.length > 0) {
            status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName,
                    problems[0].getMessage()));
            return status;
        }
    }
    return status;
}

From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java

License:Open Source License

private CompilationUnit createASTForImports(ICompilationUnit cu) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(cu);/*  w w w  .ja  v a 2 s  .  c  o m*/
    parser.setResolveBindings(false);
    parser.setFocalPosition(0);
    return (CompilationUnit) parser.createAST(null);
}

From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java

License:Open Source License

private void removeUnusedImports(ICompilationUnit cu, Set existingImports, boolean needsSave)
        throws CoreException {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(cu);// w  ww  .  j a va  2 s  .  c  o  m
    parser.setResolveBindings(true);

    CompilationUnit root = (CompilationUnit) parser.createAST(null);
    if (root.getProblems().length == 0) {
        return;
    }

    List importsDecls = root.imports();
    if (importsDecls.isEmpty()) {
        return;
    }
    ImportsManager imports = new ImportsManager(root);

    int importsEnd = ASTNodes.getExclusiveEnd((ASTNode) importsDecls.get(importsDecls.size() - 1));
    IProblem[] problems = root.getProblems();
    for (int i = 0; i < problems.length; i++) {
        IProblem curr = problems[i];
        if (curr.getSourceEnd() < importsEnd) {
            int id = curr.getID();
            if (id == IProblem.UnusedImport || id == IProblem.NotVisibleType) { // not visible problems hide unused -> remove both
                int pos = curr.getSourceStart();
                for (int k = 0; k < importsDecls.size(); k++) {
                    ImportDeclaration decl = (ImportDeclaration) importsDecls.get(k);
                    if (decl.getStartPosition() <= pos && pos < decl.getStartPosition() + decl.getLength()) {
                        if (existingImports.isEmpty() || !existingImports.contains(ASTNodes.asString(decl))) {
                            String name = decl.getName().getFullyQualifiedName();
                            if (decl.isOnDemand()) {
                                name += ".*"; //$NON-NLS-1$
                            }
                            if (decl.isStatic()) {
                                imports.removeStaticImport(name);
                            } else {
                                imports.removeImport(name);
                            }
                        }
                        break;
                    }
                }
            }
        }
    }
    imports.create(needsSave, null);
}