List of usage examples for org.eclipse.jdt.core.dom ASTParser createASTs
public void createASTs(ICompilationUnit[] compilationUnits, String[] bindingKeys, ASTRequestor requestor, IProgressMonitor monitor)
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);// w w w .ja va 2 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:cideplus.ui.astview.ASTView.java
License:Open Source License
protected void performParseBindingFromKey() { String msg = "Parse Binding from Key"; String key = askForKey(msg);/*from w w w.j a v a 2s . c o m*/ if (key == null) return; ASTParser parser = ASTParser.newParser(fCurrentASTLevel); parser.setResolveBindings(true); parser.setProject(fTypeRoot.getJavaProject()); class MyASTRequestor extends ASTRequestor { String fBindingKey; IBinding fBinding; @Override public void acceptBinding(String bindingKey, IBinding binding) { fBindingKey = bindingKey; fBinding = binding; } } MyASTRequestor requestor = new MyASTRequestor(); ASTAttribute item; Object viewerInput = fViewer.getInput(); try { parser.createASTs(new ICompilationUnit[0], new String[] { key }, requestor, null); if (requestor.fBindingKey != null) { String name = requestor.fBindingKey + ": " + Binding.getBindingLabel(requestor.fBinding); item = new Binding(viewerInput, name, requestor.fBinding, true); } else { item = new Error(viewerInput, "Key not resolved: " + key, null); } } catch (RuntimeException e) { item = new Error(viewerInput, "Error resolving key: " + key, e); } fViewer.add(viewerInput, item); fViewer.setSelection(new StructuredSelection(item), true); }
From source file:com.ibm.wala.cast.java.translator.jdt.JDTSourceModuleTranslator.java
License:Open Source License
@Override public void loadAllSources(Set<ModuleEntry> modules) { // TODO: we might need one AST (-> "Object" class) for all files. // TODO: group by project and send 'em in // sort files into projects Map<IProject, Map<ICompilationUnit, EclipseSourceFileModule>> projectsFiles = new HashMap<IProject, Map<ICompilationUnit, EclipseSourceFileModule>>(); for (ModuleEntry m : modules) { assert m instanceof EclipseSourceFileModule : "Expecing EclipseSourceFileModule, not " + m.getClass(); EclipseSourceFileModule entry = (EclipseSourceFileModule) m; IProject proj = entry.getIFile().getProject(); if (!projectsFiles.containsKey(proj)) { projectsFiles.put(proj, new HashMap<ICompilationUnit, EclipseSourceFileModule>()); }/*from w w w .jav a 2 s . co m*/ projectsFiles.get(proj).put(JavaCore.createCompilationUnitFrom(entry.getIFile()), entry); } final ASTParser parser = ASTParser.newParser(AST.JLS8); for (final Map.Entry<IProject, Map<ICompilationUnit, EclipseSourceFileModule>> proj : projectsFiles .entrySet()) { parser.setProject(JavaCore.create(proj.getKey())); parser.setResolveBindings(true); Set<ICompilationUnit> units = proj.getValue().keySet(); parser.createASTs(units.toArray(new ICompilationUnit[units.size()]), new String[0], new JdtAstToIR(proj), null); } }
From source file:net.rim.ejde.internal.builders.BBCompilationParticipant.java
License:Open Source License
@Override public void buildStarting(BuildContext[] files, boolean isBatch) { // _log.debug( "*********************************** BUILD STARTING ***********************************" ); // 5 files determined experimentally to be about the difference to make batch processing worth it. boolean runBatch = isBatch && (files.length > 5); // _log.trace( "Entering BBCompilationParticipant buildStarting();Running As Batch=" + runBatch ); //$NON-NLS-1$ // long start = System.currentTimeMillis(); if (files.length > 0) { // mark this project is built by the java builder IProject project = files[0].getFile().getProject(); // remove the packaging problems try {//from www . j a v a2s.c o m ResourceBuilderUtils.cleanProblemMarkers(project, new String[] { IRIMMarker.SIGNATURE_TOOL_PROBLEM_MARKER, IRIMMarker.PACKAGING_PROBLEM }, IResource.DEPTH_INFINITE); } catch (CoreException e) { _log.error(e.getMessage()); } PackagingJob.setBuiltByJavaBuilders(project, true); try { IJavaElement javaElem; Map<ICompilationUnit, BuildContext> buildContextMap = new HashMap<ICompilationUnit, BuildContext>(); IVMInstall vm = JavaRuntime.getVMInstall(_currentProject); if ((vm == null) || !VMUtils.isBlackBerryVM(vm)) { throw ProblemFactory.create_VM_MISSING_exception(_currentProject.getElementName()); } BBSigningKeys signingKeys = null; List<String> protectedClasses = null; boolean needParse = false; // No need to parse when there are no protected classes for (BuildContext file : files) { if (!NatureUtils.hasBBNature(file.getFile().getProject())) { continue; } // we only initialize these variables if there is any file in a BB project if ((signingKeys == null) || (protectedClasses == null)) { signingKeys = VMUtils.addSignKeysToCache(vm); protectedClasses = VMUtils.getHiddenClassesFilteredByPreferences(vm.getName()); needParse = protectedClasses.size() > 0; } IPath srcFilePath = file.getFile().getProjectRelativePath(); // For some odd reason we must remove the original pkg name or it won't be found. if (srcFilePath.segmentCount() > 1) { srcFilePath = srcFilePath.removeFirstSegments(1); } javaElem = _currentProject.findElement(srcFilePath); if ((javaElem != null) && (javaElem instanceof ICompilationUnit)) { ICompilationUnit cu = (ICompilationUnit) javaElem; CompilerToAppDescriptorManager.getInstance().onCompilationUnitCompile(cu); if (needParse) { if (runBatch) { buildContextMap.put(cu, file); } else { ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setResolveBindings(true); parser.setSource(cu); parser.setProject(_currentProject); CompilationUnit astRoot = (CompilationUnit) parser .createAST(new NullProgressMonitor()); BBASTVisitor visitor = new BBASTVisitor(cu, astRoot, signingKeys, protectedClasses); astRoot.accept(visitor); file.recordNewProblems(visitor.getProblems()); } } } else { // Will be the case for Resources // _log.error( "buildStarting: Error retrieving source to Parse for file " + file.getFile().getName() // ); } } if (needParse && runBatch) { ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setResolveBindings(true); parser.setProject(_currentProject); BBASTRequestor astRequestor = new BBASTRequestor(buildContextMap, signingKeys, protectedClasses); parser.createASTs( buildContextMap.keySet().toArray(new ICompilationUnit[buildContextMap.size()]), astRequestor.getKeys(), astRequestor, new NullProgressMonitor()); } } catch (JavaModelException jme) { _log.error("buildStarting: Error Parsing for Access Restrictions", jme); } catch (CoreException ce) { _log.error("buildStarting: " + ce.getMessage()); } // long stop = System.currentTimeMillis(); // long result = stop - start; // _totalTimeParsing += result; // _log.debug( _currentProject.getElementName() + " \t " + result + " \t Total \t " + _totalTimeParsing ); // _log.debug( "*******************************************************************************" ); // _log.trace( "Leaving BBCompilationParticipant buildStarting()" ); //$NON-NLS-1$ } }
From source file:org.assertj.eclipse.assertions.generator.internal.converter.util.ProjectBindings.java
License:Apache License
private ITypeBinding getTypeBinding(String typeName) { final ASTParser projectParser = AstParserFactory.astParserFor(project); String[] keys = new String[] { BindingKey.createTypeBindingKey(typeName) }; final ITypeBindingRequestor requestor = new ITypeBindingRequestor(); projectParser.createASTs(new ICompilationUnit[] {}, keys, requestor, null); return requestor.getITypeBinding(); }
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 ava 2 s .c o m * @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 w w . j av a 2 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; }
From source file:org.eclipse.pde.ds.internal.annotations.DSAnnotationCompilationParticipant.java
License:Open Source License
private void processAnnotations(IJavaProject javaProject, Map<ICompilationUnit, BuildContext> fileMap) { @SuppressWarnings("deprecation") ASTParser parser = ASTParser.newParser(AST.JLS4); parser.setResolveBindings(true);//from ww w .j ava 2 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.ignore); ICompilationUnit[] cuArr = fileMap.keySet().toArray(new ICompilationUnit[fileMap.size()]); parser.createASTs(cuArr, new String[0], new AnnotationProcessor(projectContext, fileMap), null); }