List of usage examples for org.eclipse.jdt.core.dom ASTParser setResolveBindings
public void setResolveBindings(boolean enabled)
From source file:ast.StructureParse.java
private void enclose(String body, DefaultMutableTreeNode parentNode) { ASTParser parser = ASTParser.newParser(AST.JLS2); /*//from w ww . j av a 2 s .co m * make parse result into OPP structure, because AST wanna be that. */ String setClass = "class fo{\nvoid foo(){ \n" + body + "\n}\n}"; parser.setSource(setClass.toCharArray()); //parser.setSource("/*abc*/".toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); //ASTNode node = parser.createAST(null); parser.setResolveBindings(true); try { final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { Set names2 = new HashSet(); @Override public boolean visit(SimpleName node) { if (this.names2.contains(node.getIdentifier())) { parentNode.add(new DefaultMutableTreeNode(node.toString())); System.out.println("SimpleNode : " + node.toString()); } return true; } @Override public boolean visit(EnhancedForStatement node) { _for = new DefaultMutableTreeNode( "for (" + node.getParameter() + " : " + node.getExpression() + ")"); parentNode.add(_for); System.out.println("for (" + node.getParameter() + " : " + node.getExpression() + ")"); enclose(node.getBody().toString(), _for); return false; } @Override public boolean visit(ForStatement node) { /* * because initial may more than 1. */ String initial = ""; for (int i = 0; i < node.initializers().size(); i++) { initial += node.initializers().get(i); if (node.initializers().size() - 1 != i) initial += ", "; } /* * because increment may more than 1 */ String inc = ""; for (int i = 0; i < node.updaters().size(); i++) { inc += node.updaters().get(i); if (node.updaters().size() - 1 != i) inc += ", "; } _for = new DefaultMutableTreeNode( "for (" + initial + "; " + node.getExpression() + "; " + inc + ")"); parentNode.add(_for); System.out.println("for (" + initial + "; " + node.getExpression() + "; " + inc + ")"); enclose(node.getBody().toString(), _for); return false; } @Override public boolean visit(IfStatement node) { String elseExist = ""; _if = new DefaultMutableTreeNode("if (" + node.getExpression() + ")"); System.out.println("if (+" + node.getExpression() + ")"); parentNode.add(_if); enclose(node.getThenStatement().toString(), _if); elseExist = node.getElseStatement() + ""; if (!(elseExist.equals("") || (elseExist.equals("null")))) { _else = new DefaultMutableTreeNode("else"); System.out.println("else"); parentNode.add(_else); enclose(node.getElseStatement().toString(), _else); } return false; } @Override public boolean visit(VariableDeclarationFragment node) { if (node.getParent() instanceof FieldDeclaration) { FieldDeclaration declaration = ((FieldDeclaration) node.getParent()); _class.add(new DefaultMutableTreeNode(declaration.getType().toString())); } else { System.out.println("VariableDeclarationFragment : " + node.toString()); parentNode.add(new DefaultMutableTreeNode(node.toString())); } return false; // do not continue to avoid usage info } @Override public boolean visit(ReturnStatement node) { parentNode.add(new DefaultMutableTreeNode(node.toString())); System.out.println("Return : " + node.toString()); return false; } @Override public boolean visit(SuperConstructorInvocation node) { _constructorCall = new DefaultMutableTreeNode(node); parentNode.add(_constructorCall); System.out.println("SuperConstructorInvocation : " + node); return false; } @Override public boolean visit(MethodInvocation node) { _methodCall = new DefaultMutableTreeNode(node); parentNode.add(_methodCall); System.out.println("MethodInvocation : " + node); return true; } @Override public boolean visit(SuperMethodInvocation node) { _methodCall = new DefaultMutableTreeNode(node); parentNode.add(_methodCall); System.out.println("SuperMethodInvocation : " + node); return false; } @Override public boolean visit(WhileStatement node) { _while = new DefaultMutableTreeNode("while " + node.getExpression()); parentNode.add(_while); System.out.println("WhileStatement : " + node.getExpression()); enclose(node.getBody().toString(), _while); return false; } @Override public boolean visit(DoStatement node) { _do = new DefaultMutableTreeNode("do"); parentNode.add(_do); System.out.println("do"); enclose(node.getBody().toString(), _do); _while = new DefaultMutableTreeNode("while(" + node.getExpression() + ")"); parentNode.add(_while); return false; } @Override public boolean visit(TryStatement node) { String ada = ""; _try = new DefaultMutableTreeNode("try"); parentNode.add(_try); System.out.println("try"); enclose(node.getBody().toString(), _try); ada = node.getFinally() + ""; if (!(ada.equals("") || (ada.equals("null")))) { _final = new DefaultMutableTreeNode("finally"); parentNode.add(_final); System.out.println("finally"); enclose(node.getFinally().toString(), _final); } return false; } @Override public boolean visit(CatchClause node) { _catch = new DefaultMutableTreeNode("catch (" + node.getException() + ")"); parentNode.add(_catch); System.out.println("catch : " + node.getException()); enclose(node.getBody().toString(), _catch); return false; } @Override public boolean visit(Assignment node) { _assignment = new DefaultMutableTreeNode(node.toString()); parentNode.add(_assignment); System.out.println("Assignment : " + node.toString()); return false; } @Override public boolean visit(ConstructorInvocation node) { _constructorCall = new DefaultMutableTreeNode(node.toString()); parentNode.add(_constructorCall); System.out.println(node.toString()); return false; } @Override public boolean visit(AnonymousClassDeclaration node) { _constructorCall = new DefaultMutableTreeNode(node.toString()); parentNode.add(_constructorCall); System.out.println("AnonymousClassDeclaration : " + node.toString()); return false; } @Override public boolean visit(ArrayAccess node) { _class = new DefaultMutableTreeNode(node.toString()); parentNode.add(_class); System.out.println("AbstrackTypeDeclaration : " + node.toString()); return false; } @Override public boolean visit(ArrayCreation node) { _array = new DefaultMutableTreeNode(node.toString()); _method.add(_array); System.out.println("ArrayCreation : " + node.toString()); return false; } @Override public boolean visit(ArrayInitializer node) { _array = new DefaultMutableTreeNode(node.toString()); System.out.println("ArrayInitialize : " + node.toString()); parentNode.add(_array); return false; } @Override public boolean visit(AssertStatement node) { _statement = new DefaultMutableTreeNode(node.toString()); System.out.println("AssertStatement : " + node.toString()); parentNode.add(_statement); return false; } @Override public boolean visit(ContinueStatement node) { _statement = new DefaultMutableTreeNode(node.toString()); System.out.println("ContinueStatement : " + node.toString()); parentNode.add(_statement); return false; } @Override public boolean visit(SwitchStatement node) { _switch = new DefaultMutableTreeNode("switch (" + node.getExpression() + ")"); System.out.println("switch (" + node.getExpression() + ")"); parentNode.add(_switch); List getStatement = node.statements(); for (Object st : getStatement) { Matcher _caseMatch = Pattern.compile("^case\\s+.+\\:").matcher(st.toString()); if (_caseMatch.find()) { _case = new DefaultMutableTreeNode(_caseMatch.group()); _switch.add(_case); } enclose(st.toString(), _case); Matcher _breakMatch = Pattern.compile("^break\\s*.*;").matcher(st.toString()); if (_breakMatch.find()) { _break = new DefaultMutableTreeNode(_breakMatch.group()); _case.add(_break); } } return false; } @Override public boolean visit(ClassInstanceCreation node) { _constructorCall = new DefaultMutableTreeNode(node.toString()); System.out.println("ClassInstanceCreation : " + node.toString()); parentNode.add(_constructorCall); return false; } }); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:boa.datagen.scm.AbstractCommit.java
License:Apache License
private boolean parseJavaScriptFile(final String path, final ChangedFile.Builder fb, final String content, final String compliance, final int astLevel, final boolean storeOnError, Writer astWriter, String key) { try {//from w w w . j a v a 2 s .c o m //System.out.println("parsing=" + (++count) + "\t" + path); final org.eclipse.wst.jsdt.core.dom.ASTParser parser = org.eclipse.wst.jsdt.core.dom.ASTParser .newParser(astLevel); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setResolveBindings(true); parser.setSource(content.toCharArray()); final Map options = JavaCore.getOptions(); JavaCore.setComplianceOptions(compliance, options); parser.setCompilerOptions(options); JavaScriptUnit cu; try { cu = (JavaScriptUnit) parser.createAST(null); } catch (java.lang.IllegalArgumentException ex) { return false; } final JavaScriptErrorCheckVisitor errorCheck = new JavaScriptErrorCheckVisitor(); cu.accept(errorCheck); if (!errorCheck.hasError || storeOnError) { final ASTRoot.Builder ast = ASTRoot.newBuilder(); // final CommentsRoot.Builder comments = // CommentsRoot.newBuilder(); final JavaScriptVisitor visitor = new JavaScriptVisitor(content); try { ast.addNamespaces(visitor.getNamespaces(cu)); // for (final String s : visitor.getImports()) // ast.addImports(s); /* * for (final Comment c : visitor.getComments()) * comments.addComments(c); */ } catch (final UnsupportedOperationException e) { return false; } catch (final Exception e) { if (debug) System.err.println("Error visiting: " + path); //e.printStackTrace(); return false; } if (astWriter != null) { try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new Text(key), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } } else fb.setAst(ast); // fb.setComments(comments); } return !errorCheck.hasError; } catch (final Exception e) { e.printStackTrace(); return false; } }
From source file:boa.datagen.scm.AbstractCommit.java
License:Apache License
private boolean parseJavaFile(final String path, final ChangedFile.Builder fb, final String content, final String compliance, final int astLevel, final boolean storeOnError, Writer astWriter, String key) { try {/*w w w . j a va2 s . c o m*/ final ASTParser parser = ASTParser.newParser(astLevel); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setResolveBindings(true); parser.setSource(content.toCharArray()); final Map options = JavaCore.getOptions(); JavaCore.setComplianceOptions(compliance, options); parser.setCompilerOptions(options); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); final JavaErrorCheckVisitor errorCheck = new JavaErrorCheckVisitor(); cu.accept(errorCheck); if (!errorCheck.hasError || storeOnError) { final ASTRoot.Builder ast = ASTRoot.newBuilder(); //final CommentsRoot.Builder comments = CommentsRoot.newBuilder(); final JavaVisitor visitor = new JavaVisitor(content, connector.nameIndices); try { ast.addNamespaces(visitor.getNamespaces(cu)); for (final String s : visitor.getImports()) ast.addImports(s); /*for (final Comment c : visitor.getComments()) comments.addComments(c);*/ } catch (final UnsupportedOperationException e) { return false; } catch (final Exception e) { if (debug) System.err.println("Error visiting: " + path); e.printStackTrace(); return false; } if (astWriter != null) { try { astWriter.append(new Text(key), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } } else fb.setAst(ast); //fb.setComments(comments); } return !errorCheck.hasError; } catch (final Exception e) { e.printStackTrace(); return false; } }
From source file:br.uff.ic.mergeguider.javaparser.JavaParser.java
private Storage generateASTs(String path) { ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setResolveBindings(true); parser.setBindingsRecovery(true);//from w w w .ja va 2 s . c om Map options = JavaCore.getOptions(); options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8); options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8); options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8); parser.setCompilerOptions(options); String[] srcDirs = FileUtils.getAllDirs(path); String[] javaFiles = FileUtils.getAllJavaFiles(path); parser.setEnvironment(null, srcDirs, null, true); Storage storage = new Storage(); parser.createASTs(javaFiles, null, new String[0], storage, null); return storage; }
From source file:byke.DependencyAnalysis.java
License:Open Source License
private void populateNodes(IProgressMonitor monitor, ASTParser parser, ASTVisitor visitor, ICompilationUnit each) {// w w w . j a v a 2s . c om monitor.subTask(each.getElementName()); parser.setResolveBindings(true); parser.setSource(each); CompilationUnit node = (CompilationUnit) parser.createAST(monitor); node.accept(visitor); monitor.worked(1); }
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); parser.setBindingsRecovery(true);/* w w w . j a v a2 s .c o m*/ 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:ca.mcgill.cs.swevo.jayfx.ASTCrawler.java
License:Open Source License
/** * Parsing a compilation unit. Starting point of the AST traversal. * // w w w. j av a 2 s . com * @param pCU */ public void analyze(final ICompilationUnit pCU, TimeCollector timeCollector) { if (timeCollector != null) timeCollector.start(); this.resetSpider(); this.extractTypes(pCU); final ASTParser lParser = ASTParser.newParser(AST.JLS8); // handles JLS8 // (J2SE // 1.8) lParser.setSource(pCU); lParser.setResolveBindings(true); final CompilationUnit lResult = (CompilationUnit) lParser.createAST(null); lResult.accept(this); if (timeCollector != null) timeCollector.stop(); }
From source file:cc.kave.eclipse.namefactory.astparser.PluginAstParser.java
License:Apache License
/** * Reads a ICompilationUnit and creates the AST DOM for manipulating the * Java source file/* ww w.j a va 2s . c o m*/ * * @param unit * @return */ private static CompilationUnit parse(ICompilationUnit unit) { ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(unit); parser.setResolveBindings(true); return (CompilationUnit) parser.createAST(null); // parse }
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());/*from w ww.ja v a 2 s .co 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./*from ww w . j av a2s . c om*/ */ 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); } } } }