Example usage for org.eclipse.jdt.core.dom AST JLS4

List of usage examples for org.eclipse.jdt.core.dom AST JLS4

Introduction

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

Prototype

int JLS4

To view the source code for org.eclipse.jdt.core.dom AST JLS4.

Click Source Link

Document

Constant for indicating the AST API that handles JLS4 (aka JLS7).

Usage

From source file:JavaCompleter.java

License:Apache License

public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    Scanner s = null;/* www .j  av a2  s .  c o  m*/
    for (String filename = in.readLine(); filename != null; filename = in.readLine()) {
        s = new Scanner(new File(filename));
        s.useDelimiter("\\Z");
        ASTParser parser = ASTParser.newParser(AST.JLS4);
        parser.setSource(s.next().toCharArray());
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        ASTNode file = parser.createAST(null);
        ASTNode range = NodeFinder.perform(file, 200, 201);
        System.out.println(range.getNodeType());
    }
}

From source file:byke.DependencyAnalysis.java

License:Open Source License

private void populateNodes(IProgressMonitor monitor) throws JavaModelException {
    if (monitor == null)
        monitor = new NullProgressMonitor();

    ASTParser parser = ASTParser.newParser(AST.JLS4);

    ASTVisitor visitor = _subject instanceof IType ? new TypeVisitor()
            : new PackageAnalyser(this, _subject.getElementName());

    List<ICompilationUnit> compilationUnits = compilationUnits();
    monitor.beginTask("dependency analysis", compilationUnits.size());

    for (ICompilationUnit each : compilationUnits) {
        if (monitor.isCanceled())
            break;
        populateNodes(monitor, parser, visitor, each);
    }/*from  w  ww .j  a  v a  2s .  com*/

}

From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java

License:Open Source License

private void processAnnotations(IJavaProject javaProject, Map<ICompilationUnit, BuildContext> fileMap) {
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setResolveBindings(true);//  ww w .  ja v a2  s  .c  o  m
    parser.setBindingsRecovery(true);
    parser.setProject(javaProject);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    ProjectContext projectContext = processingContext.get(javaProject);
    ProjectState state = projectContext.getState();

    parser.setIgnoreMethodBodies(state.getErrorLevel() == ValidationErrorLevel.none);

    ICompilationUnit[] cuArr = fileMap.keySet().toArray(new ICompilationUnit[fileMap.size()]);
    Map<ICompilationUnit, Collection<IDSModel>> models = new HashMap<ICompilationUnit, Collection<IDSModel>>();
    parser.createASTs(cuArr, new String[0], new AnnotationProcessor(models, fileMap, state.getErrorLevel()),
            null);

    Map<String, Collection<String>> cuMap = state.getMappings();
    Collection<String> unprocessed = projectContext.getUnprocessed();
    Collection<String> abandoned = projectContext.getAbandoned();

    IPath outputPath = new Path(state.getPath()).addTrailingSeparator();

    // save each model to a file; track changes to mappings
    for (Map.Entry<ICompilationUnit, Collection<IDSModel>> entry : models.entrySet()) {
        ICompilationUnit cu = entry.getKey();
        IType cuType = cu.findPrimaryType();
        if (cuType == null) {
            if (debug.isDebugging())
                debug.trace(String.format("CU %s has no primary type!", cu.getElementName())); //$NON-NLS-1$

            continue; // should never happen
        }

        String cuKey = cuType.getFullyQualifiedName();

        unprocessed.remove(cuKey);
        Collection<String> oldDSKeys = cuMap.remove(cuKey);
        Collection<String> dsKeys = new HashSet<String>();
        cuMap.put(cuKey, dsKeys);

        for (IDSModel model : entry.getValue()) {
            String compName = model.getDSComponent().getAttributeName();
            IPath filePath = outputPath.append(compName).addFileExtension("xml"); //$NON-NLS-1$
            String dsKey = filePath.toPortableString();

            // exclude file from garbage collection
            if (oldDSKeys != null)
                oldDSKeys.remove(dsKey);

            // add file to CU mapping
            dsKeys.add(dsKey);

            // actually save the file
            IFile compFile = PDEProject.getBundleRelativeFile(javaProject.getProject(), filePath);
            model.setUnderlyingResource(compFile);

            try {
                ensureDSProject(compFile.getProject());
            } catch (CoreException e) {
                Activator.getDefault().getLog().log(e.getStatus());
            }

            IPath parentPath = compFile.getParent().getProjectRelativePath();
            if (!parentPath.isEmpty()) {
                IFolder folder = javaProject.getProject().getFolder(parentPath);
                try {
                    ensureExists(folder);
                } catch (CoreException e) {
                    Activator.getDefault().getLog().log(e.getStatus());
                    model.dispose();
                    continue;
                }
            }

            if (debug.isDebugging())
                debug.trace(String.format("Saving model: %s", compFile.getFullPath())); //$NON-NLS-1$

            model.save();
            model.dispose();
        }

        // track abandoned files (may be garbage)
        if (oldDSKeys != null)
            abandoned.addAll(oldDSKeys);
    }
}

From source file:ch.acanda.eclipse.pmd.java.resolution.ASTQuickFixTestCase.java

License:Open Source License

private CompilationUnit createAST(final org.eclipse.jface.text.Document document,
        final ASTQuickFix<ASTNode> quickFix) {
    final ASTParser astParser = ASTParser.newParser(AST.JLS4);
    astParser.setSource(document.get().toCharArray());
    astParser.setKind(ASTParser.K_COMPILATION_UNIT);
    astParser.setResolveBindings(quickFix.needsTypeResolution());
    astParser.setEnvironment(new String[0], new String[0], new String[0], true);
    final String name = last(params.pmdReferenceId.or("QuickFixTest").split("/"));
    astParser.setUnitName(format("{0}.java", name));
    final String version = last(params.language.or("java 1.7").split("\\s+"));
    astParser.setCompilerOptions(ImmutableMap.<String, String>builder().put(JavaCore.COMPILER_SOURCE, version)
            .put(JavaCore.COMPILER_COMPLIANCE, version).put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, version)
            .build());/* w w w  . ja v  a 2 s . c o  m*/
    final CompilationUnit ast = (CompilationUnit) astParser.createAST(null);
    ast.recordModifications();
    return ast;
}

From source file:ch.acanda.eclipse.pmd.java.resolution.JavaQuickFix.java

License:Open Source License

/**
 * Fixes all provided markers in a file.
 *
 * @param markers The markers to fix. There is at least one marker in this collection and all markers can be fixed
 *            by this quick fix./*w ww.  j a v a 2 s.  c o  m*/
 */
protected void fixMarkersInFile(final IFile file, final List<IMarker> markers, final IProgressMonitor monitor) {
    monitor.subTask(file.getFullPath().toOSString());

    final Optional<ICompilationUnit> optionalCompilationUnit = getCompilationUnit(file);

    if (!optionalCompilationUnit.isPresent()) {
        return;
    }

    final ICompilationUnit compilationUnit = optionalCompilationUnit.get();
    ITextFileBufferManager bufferManager = null;
    final IPath path = compilationUnit.getPath();

    try {
        bufferManager = FileBuffers.getTextFileBufferManager();
        bufferManager.connect(path, LocationKind.IFILE, null);

        final ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);

        final IDocument document = textFileBuffer.getDocument();
        final IAnnotationModel annotationModel = textFileBuffer.getAnnotationModel();

        final ASTParser astParser = ASTParser.newParser(AST.JLS4);
        astParser.setKind(ASTParser.K_COMPILATION_UNIT);
        astParser.setResolveBindings(needsTypeResolution());
        astParser.setSource(compilationUnit);

        final SubProgressMonitor parserMonitor = new SubProgressMonitor(monitor, 100);
        final CompilationUnit ast = (CompilationUnit) astParser.createAST(parserMonitor);
        parserMonitor.done();

        startFixingMarkers(ast);

        final Map<?, ?> options = compilationUnit.getJavaProject().getOptions(true);
        for (final IMarker marker : markers) {
            try {
                final MarkerAnnotation annotation = getMarkerAnnotation(annotationModel, marker);
                // if the annotation is null it means that is was deleted by a previous quick fix
                if (annotation != null) {
                    final Optional<T> node = getNodeFinder(annotationModel.getPosition(annotation))
                            .findNode(ast);
                    if (node.isPresent()) {
                        final boolean isSuccessful = fixMarker(node.get(), document, options);
                        if (isSuccessful) {
                            marker.delete();
                        }
                    }
                }
            } finally {
                monitor.worked(100);
            }
        }

        finishFixingMarkers(ast, document, options);

        // commit changes to underlying file if it is not opened in an editor
        if (!isEditorOpen(file)) {
            final SubProgressMonitor commitMonitor = new SubProgressMonitor(monitor, 100);
            textFileBuffer.commit(commitMonitor, false);
            commitMonitor.done();
        } else {
            monitor.worked(100);
        }

    } catch (CoreException | MalformedTreeException | BadLocationException e) {
        // TODO: log error
        // PMDPlugin.getDefault().error("Error processing quickfix", e);

    } finally {
        if (bufferManager != null) {
            try {
                bufferManager.disconnect(path, LocationKind.IFILE, null);
            } catch (final CoreException e) {
                // TODO: log error
                // PMDPlugin.getDefault().error("Error processing quickfix", e);
            }
        }
    }
}

From source file:ch.acanda.eclipse.pmd.java.resolution.TextEditQuickFixTestCase.java

License:Open Source License

private CompilationUnit createAST(final org.eclipse.jface.text.Document document) {
    final ASTParser astParser = ASTParser.newParser(AST.JLS4);
    astParser.setKind(ASTParser.K_COMPILATION_UNIT);
    astParser.setSource(document.get().toCharArray());
    astParser.setCompilerOptions(// w ww  . j a  v a2 s  .c  o m
            ImmutableMap.<String, String>builder().put(JavaCore.COMPILER_SOURCE, "1.7").build());
    final CompilationUnit ast = (CompilationUnit) astParser.createAST(null);
    ast.recordModifications();
    return ast;
}

From source file:com.alex.example.fixlicense.actions.SampleAction.java

License:Open Source License

private CompilationUnit getAST(IDocument doc) {
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(doc.get().toCharArray());
    parser.setResolveBindings(true);/*from   w ww . j  a v a 2 s. co m*/
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    return cu;
}

From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaAbstractAstNodeModelAdapter.java

License:Open Source License

protected void setJavaDoc(Object element, Object docComment) {
    if (element instanceof BodyDeclaration) {
        BodyDeclaration node = (BodyDeclaration) element;
        ASTParser parser = ASTParser.newParser(AST.JLS4);
        parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
        parser.setSource(("/** " + docComment + "*/ int x;").toCharArray());
        TypeDeclaration type = (TypeDeclaration) parser.createAST(null);
        BodyDeclaration x = (BodyDeclaration) type.bodyDeclarations().get(0);
        Javadoc javadoc = x.getJavadoc();
        node.setJavadoc((Javadoc) ASTNode.copySubtree(node.getAST(), javadoc));
    }//from  w  w w  .j  a  v a  2  s . c  o m
}

From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaAbstractAstNodeModelAdapter.java

License:Open Source License

/**
 * Creates an {@link Expression} from the given string, owned by the given AST. 
 *//*from   w w  w.ja  va  2s.  c  om*/
protected Expression getExpressionFromString(AST ast, String expression) {
    if (expression == null) {
        return null;
    }
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_EXPRESSION);
    parser.setSource(expression.toCharArray());
    ASTNode node = parser.createAST(null);
    return (Expression) ASTNode.copySubtree(ast, node);
}

From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaAbstractAstNodeModelAdapter.java

License:Open Source License

/**
 * Creates a {@link Type} from the given name, owned by the given AST.
 *//*  w  ww .  j  a v  a2s  .co  m*/
protected Type getTypeFromString(AST ast, String name) {
    if (name == null) {
        return ast.newPrimitiveType(PrimitiveType.VOID);
    }
    PrimitiveType.Code primitiveTypeCode = PrimitiveType.toCode(name);
    if (primitiveTypeCode != null) {
        return ast.newPrimitiveType(primitiveTypeCode);
    }

    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_STATEMENTS);
    parser.setSource((name + " a;").toCharArray());

    Block block = (Block) parser.createAST(null);
    VariableDeclarationStatement declaration = (VariableDeclarationStatement) block.statements().get(0);
    return (Type) ASTNode.copySubtree(ast, declaration.getType());
}