Example usage for org.eclipse.jdt.core.dom ASTRequestor ASTRequestor

List of usage examples for org.eclipse.jdt.core.dom ASTRequestor ASTRequestor

Introduction

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

Prototype

protected ASTRequestor() 

Source Link

Document

Creates a new instance.

Usage

From source file:ca.mcgill.cs.swevo.ppa.ui.PPAUtil.java

License:Open Source License

/**
 * <p>/*from  w  ww  .  j a v  a 2s . com*/
 * </p>
 * 
 * @param units
 * @return
 */
public List<CompilationUnit> getCUsWithOnePPAPass(List<ICompilationUnit> units) {

    if (units.size() == 0)
        return new ArrayList<CompilationUnit>();

    final List<CompilationUnit> astList = new ArrayList<CompilationUnit>();
    try {

        // FIXME a hack to get the current project.
        JavaProject jproject = (JavaProject) JavaCore.create(units.get(0).getUnderlyingResource().getProject());
        PPATypeRegistry registry = new PPATypeRegistry(jproject);
        final PPAEngine ppaEngine = new PPAEngine(registry, new PPAOptions());

        PPAASTParser parser2 = new PPAASTParser(AST.JLS3);
        parser2.setStatementsRecovery(true);
        parser2.setResolveBindings(true);
        parser2.setProject((IJavaProject) jproject);

        ASTRequestor requestor = new ASTRequestor() {

            @Override
            public void acceptAST(ICompilationUnit source, CompilationUnit ast) {
                astList.add(ast);
                ppaEngine.addUnitToProcess(ast);
            }
        };

        parser2.createASTs(units.toArray(new ICompilationUnit[units.size()]), new String[0], requestor, null);

        ppaEngine.doPPA();
        ppaEngine.reset();

    } catch (JavaModelException jme) {
        jme.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return astList;
}

From source file:com.google.gwt.eclipse.core.validators.java.JavaCompilationParticipant.java

License:Open Source License

private void handleBuildStarting(BuildContext[] files, final IProgressMonitor monitor) {
    UiBinderSubtypeToOwnerIndex prebuildOwnerIndex = new UiBinderSubtypeToOwnerIndex(
            UiBinderReferenceManager.INSTANCE.getSubtypeToOwnerIndex());
    final LinkedHashMap<ICompilationUnit, BuildContext> compilationUnitToBuildContext = new LinkedHashMap<ICompilationUnit, BuildContext>();

    for (BuildContext buildContext : files) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(buildContext.getFile());
        compilationUnitToBuildContext.put(cu, buildContext);
    }/* w  w w.  java  2  s .co m*/

    final Set<ICompilationUnit> validatedCompilationUnits = new HashSet<ICompilationUnit>();

    /*
     * ASTBatchParser processes the ICompilationUnits in batches based on the
     * available memory in the system. Note that we never cache the ASTs they
     * are only live for the duration of the callback below. Empirically, trying
     * to cache all ASTs for gwt-user project results in an OOM.
     */
    new ASTBatchParser().createASTs(compilationUnitToBuildContext.keySet().toArray(NO_UNITS), NO_STRINGS,
            new ASTRequestor() {
                @Override
                public void acceptAST(ICompilationUnit source, CompilationUnit ast) {
                    BuildContext buildContext = compilationUnitToBuildContext.get(source);
                    IFile file = buildContext.getFile();

                    if (monitor != null) {
                        // Return early if this is a canceled job. Note that the AST is
                        // still being built as there is no way to signal an abort.
                        if (monitor.isCanceled()) {
                            return;
                        }

                        // Update the progress monitor.
                        monitor.subTask(source.getElementName());
                        monitor.worked(1);
                    }

                    try {
                        ICompilationUnit cu = source;

                        validatedCompilationUnits.add(cu);

                        try {
                            /*
                             * Generally, the compilation unit will be consistent (the Java
                             * Model matches the .java file on disk). However, in certain
                             * cases, such as when the user undos a member rename
                             * refactoring, the two are out of sync when the build starts.
                             * In these cases, we have to explicitly reconcile the
                             * compilation unit with its underlying resource and use the AST
                             * we get back for validation.
                             */
                            if (!cu.isConsistent()) {
                                ast = cu.reconcile(AST.JLS4, true, null, null);
                                assert (cu.isConsistent());
                            }
                        } catch (JavaModelException e) {
                            GWTPluginLog.logError(e);
                            return;
                        }

                        // TODO: Merge this code with that of reconcile

                        // Validate the Java AST and record any GWT problems we find
                        JavaValidationResult result = validateCompilationUnit(ast);
                        List<CategorizedProblem> problems = new ArrayList<CategorizedProblem>(
                                result.getProblems());

                        RemoteServiceValidator rsv = new RemoteServiceValidator();
                        ValidationResult validationResult = rsv.validate(ast);
                        problems.addAll(validationResult.getProblems());

                        ClientBundleValidator cbv = new ClientBundleValidator();
                        ValidationResult cbvResult = cbv.validate(ast);
                        problems.addAll(cbvResult.getProblems());

                        ValidationResult uivResult;
                        if (UiBinderConstants.UI_BINDER_ENABLED) {
                            UiBinderJavaValidator uiv = new UiBinderJavaValidator(ast,
                                    UiBinderReferenceManager.INSTANCE.getSubtypeToOwnerIndex(),
                                    UiBinderReferenceManager.INSTANCE.getSubtypeToUiXmlIndex(),
                                    UiBinderReferenceManager.INSTANCE.getUiXmlReferencedFieldIndex(),
                                    UiBinderReferenceManager.INSTANCE.getReferenceManager());
                            uivResult = uiv.validate();
                            problems.addAll(uivResult.getProblems());
                        }

                        // Record the problems
                        buildContext.recordNewProblems(problems.toArray(EMPTY_PROBLEMS));

                        // Get all Java types references from JSNI blocks in this file
                        List<String> typeDependencies = new ArrayList<String>();
                        for (JsniJavaRef javaRef : result.getJavaRefs()) {
                            if (!typeDependencies.contains(javaRef.dottedClassName())) {
                                typeDependencies.add(javaRef.dottedClassName());
                            }
                        }

                        // Add the RPC dependencies
                        typeDependencies.addAll(validationResult.getTypeDependencies());

                        if (UiBinderConstants.UI_BINDER_ENABLED) {
                            // Add the UiBinder dependencies
                            typeDependencies.addAll(uivResult.getTypeDependencies());
                        }

                        // Record the JSNI dependencies so that changing any referenced
                        // types
                        // will automatically trigger a rebuild of this file
                        buildContext.recordDependencies(typeDependencies.toArray(Empty.STRINGS));
                    } catch (OperationCanceledException e) {
                        // Thrown by Eclipse to abort long-running processes
                        throw e;
                    } catch (Exception e) {
                        // Don't want to allow any unexpected exceptions to escape
                        GWTPluginLog.logError(e, "Unexpected error while validating {0}", file.getName());
                    }
                }
            }, null);

    if (UiBinderConstants.UI_BINDER_ENABLED) {
        revalidateOwnerTypes(prebuildOwnerIndex, validatedCompilationUnits);
    }
}

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

License:Open Source License

/**
 * Checks the conditions for a single {@link AJCompilationUnit}
 * @param ajUnit the unit to check// w w  w  .  j a va2 s.c  om
 * @param itdsForUnit all itds in this unit
 * @param imports a map from target {@link ICompilationUnit} to imports that need to be added
 * initially empty, but populated in this method
 * @param monitor
 * @return
 * @throws JavaModelException
 */
private RefactoringStatus checkFinalConditionsForITD(final ICompilationUnit ajUnit,
        final List<IMember> itdsForUnit, final Map<ICompilationUnit, PerUnitInformation> imports,
        final IProgressMonitor monitor) throws JavaModelException {

    final RefactoringStatus status = new RefactoringStatus();

    // group all of the ITD targets by the ICompilationUnit that they are in
    final Map<ICompilationUnit, Set<IMember>> unitsToTypes = getUnitTypeMap(getTargets(itdsForUnit));

    // group all of the ICompilationUnits by project
    final Map<IJavaProject, Collection<ICompilationUnit>> projects = new HashMap<IJavaProject, Collection<ICompilationUnit>>();
    for (ICompilationUnit targetUnit : unitsToTypes.keySet()) {
        IJavaProject project = targetUnit.getJavaProject();
        if (project != null) {
            Collection<ICompilationUnit> collection = projects.get(project);
            if (collection == null) {
                collection = new ArrayList<ICompilationUnit>();
                projects.put(project, collection);
            }
            collection.add(targetUnit);
        }
    }

    // also add the ajunit to the collection of affected units
    Collection<ICompilationUnit> units;
    IJavaProject aspectProject = ajUnit.getJavaProject();
    if (projects.containsKey(aspectProject)) {
        units = projects.get(aspectProject);
    } else {
        units = new ArrayList<ICompilationUnit>();
        projects.put(aspectProject, units);
    }
    units.add(ajUnit);

    // this requestor performs the real work
    ASTRequestor requestors = new ASTRequestor() {
        public void acceptAST(ICompilationUnit source, CompilationUnit ast) {
            try {

                // compute the imports that this itd adds to this unit
                PerUnitInformation holder;
                if (imports.containsKey(source)) {
                    holder = (PerUnitInformation) imports.get(source);
                } else {
                    holder = new PerUnitInformation(source);
                    imports.put(source, holder);
                }
                holder.computeImports(itdsForUnit, ajUnit, monitor);

                for (Entry<IType, Set<String>> entry : holder.declareParents.entrySet()) {
                    rewriteDeclareParents(entry.getKey(), ast, entry.getValue(), source);
                }

                // make the simplifying assumption that the CU that contains the
                // ITD does not also contain a target type
                // Bug 310020
                if (isCUnitContainingITD(source, (IMember) itdsForUnit.get(0))) {
                    // this is an AJCU.
                    rewriteAspectType(itdsForUnit, source, ast);
                } else {
                    // this is a regular CU

                    for (IMember itd : itdsForUnit) {

                        // filter out the types not affected by itd 
                        Collection<IMember> members = new ArrayList<IMember>();
                        members.addAll(unitsToTypes.get(source));
                        AJProjectModelFacade model = getModel(itd);
                        List<IJavaElement> realTargets;
                        if (itd instanceof IAspectJElement
                                && ((IAspectJElement) itd).getAJKind().isDeclareAnnotation()) {
                            realTargets = model.getRelationshipsForElement(itd,
                                    AJRelationshipManager.ANNOTATES);
                        } else {
                            // regular ITD or an ITIT
                            realTargets = model.getRelationshipsForElement(itd,
                                    AJRelationshipManager.DECLARED_ON);
                        }
                        for (Iterator<IMember> memberIter = members.iterator(); memberIter.hasNext();) {
                            IMember member = memberIter.next();
                            if (!realTargets.contains(member)) {
                                memberIter.remove();
                            }
                        }

                        if (members.size() > 0) {
                            // if declare parents, store until later
                            if (itd instanceof IAspectJElement
                                    && ((IAspectJElement) itd).getAJKind() == Kind.DECLARE_PARENTS) {
                                // already taken care of
                            }
                            applyTargetTypeEdits(itd, source, members);
                        }
                    } // for (Iterator itdIter = itdsForUnit.iterator(); itdIter.hasNext();) {
                }
            } catch (JavaModelException e) {
            } catch (CoreException e) {
            }
        }
    };
    IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1);
    try {
        try {
            final Set<IJavaProject> set = projects.keySet();
            subMonitor.beginTask("Compiling source...", set.size());
            for (IJavaProject project : projects.keySet()) {
                ASTParser parser = ASTParser.newParser(AST.JLS8);
                parser.setProject(project);
                parser.setResolveBindings(true);
                Collection<ICompilationUnit> collection = projects.get(project);
                parser.createASTs(
                        (ICompilationUnit[]) collection.toArray(new ICompilationUnit[collection.size()]),
                        new String[0], requestors, new SubProgressMonitor(subMonitor, 1));
            }

        } finally {
            subMonitor.done();
        }

    } finally {
        subMonitor.done();
    }
    return status;
}

From source file:org.eclipse.flux.jdt.services.CompletionProposalReplacementProvider.java

License:Open Source License

private ITypeBinding getExpectedTypeForGenericParameters() {
    char[][] chKeys = context.getExpectedTypesKeys();
    if (chKeys == null || chKeys.length == 0)
        return null;

    String[] keys = new String[chKeys.length];
    for (int i = 0; i < keys.length; i++) {
        keys[i] = String.valueOf(chKeys[0]);
    }//from w ww.jav  a2 s  . com

    final ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setProject(compilationUnit.getJavaProject());
    parser.setResolveBindings(true);
    parser.setStatementsRecovery(true);

    final Map<String, IBinding> bindings = new HashMap<String, IBinding>();
    ASTRequestor requestor = new ASTRequestor() {
        @Override
        public void acceptBinding(String bindingKey, IBinding binding) {
            bindings.put(bindingKey, binding);
        }
    };
    parser.createASTs(new ICompilationUnit[0], keys, requestor, null);

    if (bindings.size() > 0)
        return (ITypeBinding) bindings.get(keys[0]);

    return null;
}