/** * @param methodname * @return */ public FieldDeclaration getField( ) { ASTParser parser = ASTParser.newParser(AST.JLS8); String s = getStaticVariable ( ); if (s==null) return null; parser.setSource(s.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { public boolean visit(FieldDeclaration node) { field = node; return true; } }); return field; }
/** * @return */ public NormalAnnotation getGraphWalkerClassAnnotation() { String source = getSource (); if(source==null) return null; ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(source.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { public boolean visit(NormalAnnotation node) { annotation = node; return true; } }); if (this.generateAnnotation) return annotation; return null; }
private void analyzeCompilationUnit(CompilationUnit unit, ICompilationUnit compilationUnit) { Set<String> filters = loadFilters(); ASTVisitor importsVisitor = new ImportsVisitor(filters); unit.accept(importsVisitor); List types = unit.types(); for (Iterator iter = types.iterator(); iter.hasNext();) { Object next = iter.next(); if (next instanceof TypeDeclaration) { // declaration: Contains one file content at a time. TypeDeclaration declaration = (TypeDeclaration) next; // traverseType(declaration,true); } } }
private static String decideRuleKind(ReferencedClassesParser parser, Set<String> dependencies) { CompilationUnit cu = parser.compilationUnit; if (cu.types().isEmpty()) { return "java_library"; } AbstractTypeDeclaration topLevelClass = (AbstractTypeDeclaration) cu.types().get(0); if ((topLevelClass.getModifiers() & Modifier.ABSTRACT) != 0) { // Class is abstract, can't be a test. return "java_library"; } // JUnit 4 tests if (parser.className.endsWith("Test") && dependencies.contains("org.junit.Test")) { return "java_test"; } if (any( topLevelClass.bodyDeclarations(), d -> d instanceof MethodDeclaration && isMainMethod((MethodDeclaration) d))) { return "java_binary"; } return "java_library"; }
public NormalAnnotation getGeneratedClassAnnotation() { String source = getGeneratedAnnotationSource (); if(source==null) return null; ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(source.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { public boolean visit(NormalAnnotation node) { annotation = node; return true; } }); return annotation; }
/** * @param cu * @return */ public static String findPathGeneratorInGraphWalkerAnnotation(ICompilationUnit cu) { CompilationUnit ast = parse(cu); Map<String, String> ret = new HashMap<String, String>(); ast.accept(new ASTVisitor() { public boolean visit(MemberValuePair node) { String name = node.getName().getFullyQualifiedName(); if ("value".equals(name) && node.getParent() != null && node.getParent() instanceof NormalAnnotation) { IAnnotationBinding annoBinding = ((NormalAnnotation) node.getParent()).resolveAnnotationBinding(); String qname = annoBinding.getAnnotationType().getQualifiedName(); if (GraphWalker.class.getName().equals(qname)) { StringLiteral sl = (StringLiteral) node.getValue(); ret.put("ret", sl.getLiteralValue()); } } return true; } }); return ret.get("ret"); }
/** * Save the AST int he Compilation Unit * * @param testInterface * @param rewrite * @throws CoreException */ public static void save(CompilationUnit unit, ASTRewrite rewrite) throws CoreException { ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); IPath path = unit.getJavaElement().getPath(); try { bufferManager.connect(path, null); ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path); IDocument document = textFileBuffer.getDocument(); TextEdit edit = rewrite.rewriteAST(document, null); edit.apply(document); textFileBuffer.commit(null /* ProgressMonitor */, true /* Overwrite */); } catch (Exception e) { ResourceManager.logException(e); } finally { // disconnect the path bufferManager.disconnect(path, null); } }
public void parse() throws ParseException { ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(source.toCharArray()); Map<String, String> options = JavaCore.getOptions(); options.put("org.eclipse.jdt.core.compiler.source", "1.8"); parser.setCompilerOptions(options); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setUnitName("Program.java"); parser.setEnvironment(new String[] { classpath != null? classpath : "" }, new String[] { "" }, new String[] { "UTF-8" }, true); parser.setResolveBindings(true); cu = (CompilationUnit) parser.createAST(null); List<IProblem> problems = Arrays.stream(cu.getProblems()).filter(p -> p.isError() && p.getID() != IProblem.PublicClassMustMatchFileName && // we use "Program.java" p.getID() != IProblem.ParameterMismatch // Evidence varargs ).collect(Collectors.toList()); if (problems.size() > 0) throw new ParseException(problems); }
public TypeModel toGroovyTypeModel(String source) { source = source.replaceAll("//(?i)\\s*" + quote("given") + SEPARATOR, "givenBlockStart();"); source = source.replaceAll("//(?i)\\s*" + quote("when") + SEPARATOR, "whenBlockStart();"); source = source.replaceAll("//(?i)\\s*" + quote("then") + SEPARATOR, "thenBlockStart();"); ASTParser parser = ASTParser.newParser(JLS8); parser.setSource(source.toCharArray()); parser.setKind(K_COMPILATION_UNIT); parser.setCompilerOptions(compilerOptions()); CompilationUnit cu = (CompilationUnit) parser.createAST(null); astProxy.setTarget(cu.getAST()); TypeVisitor visitor = testClassVisitorSupplier.get(); cu.accept(visitor); return visitor.typeModel(); }
private void serializePosition(CompilationUnit cu, ASTNode node, JsonGenerator jG) throws IOException { final int startPosition = node.getStartPosition(); jG.writeFieldName("startPosition"); jG.writeNumber(startPosition); jG.writeFieldName("startLine"); jG.writeNumber(cu.getLineNumber(startPosition)); jG.writeFieldName("startColumn"); jG.writeNumber(cu.getColumnNumber(startPosition) + 1); // 1-based numbering final int endPosition = startPosition + node.getLength(); jG.writeFieldName("endPosition"); jG.writeNumber(endPosition); jG.writeFieldName("endLine"); jG.writeNumber(cu.getLineNumber(endPosition)); jG.writeFieldName("endColumn"); jG.writeNumber(cu.getColumnNumber(endPosition) + 1); // 1-based numbering }
@Override protected void addEdits(IDocument doc, TextEdit root) throws CoreException { super.addEdits(doc, root); // build a full AST CompilationUnit unit = SharedASTProvider.getInstance().getAST(getCompilationUnit(), null); ASTNode name= NodeFinder.perform(unit, fOffset, fLength); if (name instanceof SimpleName) { SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name); if (names != null) { for (int i= 0; i < names.length; i++) { SimpleName curr= names[i]; root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName)); } return; } } root.addChild(new ReplaceEdit(fOffset, fLength, fNewName)); }
/** * Evaluates fully qualified name of the TypeDeclaration object. */ public static String getFullName(TypeDeclaration decl) { String name = decl.getName().getIdentifier(); ASTNode parent = decl.getParent(); // resolve full name e.g.: A.B while (parent != null && parent.getClass() == TypeDeclaration.class) { name = ((TypeDeclaration) parent).getName().getIdentifier() + "." + name; parent = parent.getParent(); } // resolve fully qualified name e.g.: some.package.A.B if (decl.getRoot().getClass() == CompilationUnit.class) { CompilationUnit root = (CompilationUnit) decl.getRoot(); if (root.getPackage() != null) { PackageDeclaration pack = root.getPackage(); name = pack.getName().getFullyQualifiedName() + "." + name; } } return name; }
private Expression evaluateArgumentExpressions(AST ast, ITypeBinding requiredType, String key) { CompilationUnit root= (CompilationUnit) fCallerNode.getRoot(); int offset= fCallerNode.getStartPosition(); Expression best= null; ITypeBinding bestType= null; ScopeAnalyzer analyzer= new ScopeAnalyzer(root); IBinding[] bindings= analyzer.getDeclarationsInScope(offset, ScopeAnalyzer.VARIABLES); for (int i= 0; i < bindings.length; i++) { IVariableBinding curr= (IVariableBinding) bindings[i]; ITypeBinding type= curr.getType(); if (type != null && canAssign(type, requiredType) && testModifier(curr)) { if (best == null || isMoreSpecific(bestType, type)) { best= ast.newSimpleName(curr.getName()); bestType= type; } } } Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, requiredType); if (best == null) { best= defaultExpression; } return best; }
/** * Method to get class attributes and add them in a list. * @author Mariana Azevedo * @since 13/07/2014 * @param node */ @SuppressWarnings("unchecked") private void getClassAttributes(CompilationUnit node){ for (Object type : node.types()){ if (type instanceof TypeDeclaration){ FieldDeclaration [] attributes = ((TypeDeclaration) type).getFields(); for (FieldDeclaration attribute: attributes){ List<FieldDeclaration> fragments = attribute.fragments(); Object obj = fragments.get(0); if (obj instanceof VariableDeclarationFragment){ String str = ((VariableDeclarationFragment) obj).getName().toString(); this.listOfAttributes.add(str); } } } } }
public static void getAmbiguousTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); int offset= problem.getOffset(); int len= problem.getLength(); IJavaElement[] elements= cu.codeSelect(offset, len); for (int i= 0; i < elements.length; i++) { IJavaElement curr= elements[i]; if (curr instanceof IType) { String qualifiedTypeName= ((IType) curr).getFullyQualifiedName('.'); CompilationUnit root= context.getASTRoot(); String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importexplicit_description, BasicElementLabels.getJavaElementName(qualifiedTypeName)); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, ASTRewrite.create(root.getAST()), IProposalRelevance.IMPORT_EXPLICIT); ImportRewrite imports= proposal.createImportRewrite(root); imports.addImport(qualifiedTypeName); proposals.add(proposal); } } }
/** * Method to calculate the sum of the complexities of all class methods. * @author Mariana Azevedo * @since 13/07/2014 * @param node */ @SuppressWarnings("unchecked") private void calculateWeightMethods(CompilationUnit node){ for (Object type : node.types()){ if ((type instanceof TypeDeclaration) && !((TypeDeclaration) type).isInterface()){ List<TypeDeclaration> bodyDeclarationsList = ((TypeDeclaration) type). bodyDeclarations(); Iterator<TypeDeclaration> itBodyDeclaration = bodyDeclarationsList.iterator(); while (itBodyDeclaration.hasNext()){ Object itItem = itBodyDeclaration.next(); if (itItem instanceof MethodDeclaration){ checkStatementsInMethodsDeclaration(itItem); } } this.wmcIndex += this.visitor.getCyclomaticComplexityIndex(); } } }
@Override protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) { ScopeAnalyzer analyzer= new ScopeAnalyzer(root); IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(root, returnOffset, 0); ASTNode varDeclFrag= ASTResolving.findAncestor(finder.getCoveringNode(), ASTNode.VARIABLE_DECLARATION_FRAGMENT); IVariableBinding varDeclFragBinding= null; if (varDeclFrag != null) varDeclFragBinding= ((VariableDeclarationFragment) varDeclFrag).resolveBinding(); for (int i= 0; i < bindings.length; i++) { IVariableBinding curr= (IVariableBinding) bindings[i]; ITypeBinding type= curr.getType(); // Bindings are compared to make sure that a lambda does not return a variable which is yet to be initialised. if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr) && !Bindings.equals(curr, varDeclFragBinding)) { if (result == null) { result= ast.newSimpleName(curr.getName()); } addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName()); } } return result; }
private boolean hasImportDeclaration(CompilationUnit unit) { List imports = unit.imports(); for(Iterator iter = imports.iterator(); iter.hasNext() ; ) { Object next = iter.next(); if (next instanceof ImportDeclaration ) { ImportDeclaration importDecl = (ImportDeclaration)next; Name name = importDecl.getName(); if (name instanceof QualifiedName ) { QualifiedName qName = (QualifiedName)name; String qNameString = qName.getFullyQualifiedName(); if (qNameString.startsWith("edu.cmu.cs.aliasjava.annotations") ) { return true; } } } } return false; }
/** * Method that calculates the number of classes of * a specific project. * @author Mariana Azevedo * @since 13/07/2014 * @param unit */ @SuppressWarnings("unchecked") private void calculateNumberOfClasses(CompilationUnit unit) { numOfClassClasses++; for (Object type :unit.types()){ if ((type instanceof TypeDeclaration) && !((TypeDeclaration) type).isInterface()){ List<TypeDeclaration> bodyDeclarationsList = ((TypeDeclaration) type).bodyDeclarations(); Iterator<TypeDeclaration> itBodyDeclaration = bodyDeclarationsList.iterator(); while (itBodyDeclaration.hasNext()){ Object itItem = itBodyDeclaration.next(); if ((itItem instanceof TypeDeclaration) && !((TypeDeclaration) itItem).isInterface()){ numOfClassClasses++; } } } } }
private void run(){ Crystal crystal = Crystal.getInstance(); PrintWriter output = crystal.userOut(); crystal.scanWorkspace(); Iterator<ICompilationUnit> unitIterator = crystal.getCompilationUnitIterator(); ICompilationUnit compUnit = null; for (; unitIterator.hasNext();) { compUnit = unitIterator.next(); if (compUnit == null) { output.println("AbstractCompilationUnitAnalysis: null CompilationUnit"); continue; } // Obtain the AST for this CompilationUnit and analyze it ASTNode node = crystal.getASTNodeFromCompilationUnit(compUnit); if ((node != null) && (node instanceof CompilationUnit)) { analyzeCompilationUnit((CompilationUnit) node); } else { output.println("AbstractCompilationUnitAnalysis: Could not retrieve the ASTNode for CompilationUnit " + compUnit.getElementName()); } } }
/** * @see Measure#measure */ @Override public <T> void measure(T unit) { IType[] iTypes = null; try { iTypes = ((ICompilationUnit)unit).getTypes(); } catch (JavaModelException exception) { logger.error(exception); } CompilationUnit parse = parse(unit); CouplingBetweenObjectsVisitor visitor = CouplingBetweenObjectsVisitor.getInstance(); visitor.cleanArrayAndVariable(); visitor.addListOfTypes(iTypes); parse.accept(visitor); setCalculatedValue(getCouplingBetweenObjectsValue(visitor)); setMeanValue(getCalculatedValue()); setMaxValue(getCalculatedValue(), parse.getJavaElement().getElementName()); }
@Override public void endVisit(CompilationUnit node) { if (!hasSelectedNodes()) { super.endVisit(node); return; } ASTNode selectedNode = getFirstSelectedNode(); Selection selection = getSelection(); if (node != selectedNode) { ASTNode parent = selectedNode.getParent(); fStatus.merge(CommentAnalyzer.perform(selection, fScanner.getScanner(), parent.getStartPosition(), parent.getLength())); } if (!fStatus.hasFatalError()) { checkSelectedNodes(); } super.endVisit(node); }
/** * Goes through a list of compilation units and parses them. The act of parsing creates the AST structures from the * source code. * * @param compilationUnits the list of compilation units to parse * @return the mapping from compilation unit to the AST roots of each */ public static Map<ICompilationUnit, ASTNode> parseCompilationUnits(List<ICompilationUnit> compilationUnits) { if (compilationUnits == null) { throw new CrystalRuntimeException("null list of compilation units"); } ICompilationUnit[] compUnits = compilationUnits.toArray(new ICompilationUnit[0]); final Map<ICompilationUnit, ASTNode> parsedCompilationUnits = new HashMap<ICompilationUnit, ASTNode>(); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setResolveBindings(true); parser.setProject(WorkspaceUtilities.javaProject); parser.createASTs(compUnits, new String[0], new ASTRequestor() { @Override public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) { parsedCompilationUnits.put(unit, node); } @Override public final void acceptBinding(final String key, final IBinding binding) { // Do nothing } }, null); return parsedCompilationUnits; }
@Test public void testWhenPreviousBuilderRemovingFailsShouldShowDialog() throws Exception { // GIVEN BuilderRemover builderRemover = DiContainer.getDependency(BuilderRemover.class); willThrow(new RuntimeException("Cause")) .given(builderAstRemover) .removeBuilder(any(ASTRewrite.class), any(CompilationUnit.class)); super.setInput("class TestClass {}"); CompilationUnitModificationDomain dummyCompilationUnitModificationDomain = CompilationUnitModificationDomain.builder().build(); // WHEN builderRemover.removeExistingBuilderWhenNeeded(dummyCompilationUnitModificationDomain); // THEN verify(dialogWrapper).openInformationDialog("Error", "Error removing previous builder, skipping"); }
/** * What we're trying to do: * - traverse all CompilationUnits * - build some mappings */ private void populateTM(List<ICompilationUnit> allCompUnits){ // XXX. getReporter() still null here //PrintStream output = getReporter().userOut(); PrintStream output = System.err; for (ICompilationUnit compUnit : allCompUnits) { ASTNode node = parseCompilationUnits.get(compUnit); if ((node != null) && (node instanceof CompilationUnit)) { analyzeCompilationUnit((CompilationUnit) node, compUnit); } else { output.println("AbstractCompilationUnitAnalysis: Could not retrieve the ASTNode for CompilationUnit " + compUnit.getElementName()); } } // Create pair of overridden and overriding methods }
public CompilationUnit getAST(final ITypeRoot input, IProgressMonitor progressMonitor) { if (progressMonitor != null && progressMonitor.isCanceled()) { return null; } if (!shouldCache(input)) { JavaLanguageServerPlugin.logInfo("Creating uncached AST for " + input.getPath().toString()); return createAST(input, progressMonitor); } final String identifier = input.getHandleIdentifier(); return cache.computeIfAbsent(identifier, k -> { JavaLanguageServerPlugin.logInfo("Caching AST for " + input.getPath().toString()); CompilationUnit astRoot = createAST(input, progressMonitor); astCreationCount++; return astRoot; }); }
public static MethodDeclaration getMethodDeclaration(String methodName) { IJavaElement javaElem = EditorUtility.getActiveEditorJavaInput(); if (javaElem.getElementType() == IJavaElement.COMPILATION_UNIT) { ICompilationUnit iCompUnit = (ICompilationUnit) javaElem; ASTNode astNode = Crystal.getInstance() .getASTNodeFromCompilationUnit(iCompUnit); if (astNode != null && astNode.getNodeType() == ASTNode.COMPILATION_UNIT) { CompilationUnit compUnit = (CompilationUnit) astNode; for (Object declaration : compUnit.types()) { if (declaration instanceof TypeDeclaration) { for (MethodDeclaration method : ((TypeDeclaration) declaration) .getMethods()) { if (methodName.contentEquals(method.getName() .getFullyQualifiedName())) { return method; } } } } } } return null; }
public static UnusedCodeFix createUnusedMemberFix(CompilationUnit compilationUnit, IProblemLocation problem, boolean removeAllAssignements) { if (isUnusedMember(problem)) { SimpleName name= getUnusedName(compilationUnit, problem); if (name != null) { IBinding binding= name.resolveBinding(); if (binding != null) { if (isFormalParameterInEnhancedForStatement(name)) { return null; } String label= getDisplayString(name, binding, removeAllAssignements); RemoveUnusedMemberOperation operation= new RemoveUnusedMemberOperation(new SimpleName[] { name }, removeAllAssignements); return new UnusedCodeFix(label, compilationUnit, new CompilationUnitRewriteOperation[] { operation }, getCleanUpOptions(binding, removeAllAssignements)); } } } return null; }
/** * Returns the source of the given node from the location where it was parsed. * @param node the node to get the source from * @param extendedRange if set, the extended ranges of the nodes should ne used * @param removeIndent if set, the indentation is removed. * @return return the source for the given node or null if accessing the source failed. */ public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) { ASTNode root= node.getRoot(); if (root instanceof CompilationUnit) { CompilationUnit astRoot= (CompilationUnit) root; ITypeRoot typeRoot= astRoot.getTypeRoot(); try { if (typeRoot != null && typeRoot.getBuffer() != null) { IBuffer buffer= typeRoot.getBuffer(); int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition(); int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength(); String str= buffer.getText(offset, length); if (removeIndent) { IJavaProject project= typeRoot.getJavaProject(); int indent= getIndentUsed(buffer, node.getStartPosition(), project); str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator()); } return str; } } catch (JavaModelException e) { // ignore } } return null; }
@Override public boolean visit(MethodInvocation node) { visitExpressionIfName(node.getExpression()); if (node.getExpression() != null) { return true; } // node is of the form `methodName(...)`, and not eg., `Foo.methodName()`. org.eclipse.jdt.core.dom.SimpleName simpleName = node.getName(); if (compilationUnit.findDeclaringNode(simpleName.resolveBinding()) != null) { // simpleName is defined somewhere in this compilation unit - so no need to import it. return true; } // Do not report methods that appear in inner/anonymous classes that have a superclass: // Jade doesn't currently fetch inherited symbols for inner/anonymous classes, which // leads to inherited methods being imported. (b/35660499, b/35727475) // This isn't perfect because another class might call a same-named method; if this // becomes a problem, I'll use a blacklist. AbstractTypeDeclaration containingClass = getContainingClass(node); if (!(containingClass.getParent() instanceof CompilationUnit) && containingClass instanceof TypeDeclaration && ((TypeDeclaration) containingClass).getSuperclassType() != null) { return true; } if (isDescendantOfAnonymousClassDeclaration(node)) { return true; } // Work around Eclipse JDT Bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=462192, // where `simpleName.resolveBinding() == null` happens even though 'simpleName' is // defined in the current compilation unit. Set<String> methods = methodsOfClass.get(containingClass); if (methods.isEmpty()) { methods.addAll(getMethodDeclarations(containingClass)); } if (!methods.contains(simpleName.getIdentifier())) { int startPosition = simpleName.getStartPosition(); symbols.put( simpleName.getIdentifier(), Metadata.create( compilationUnit.getLineNumber(startPosition), compilationUnit.getColumnNumber(startPosition), true)); } return true; }
/** * Parse a source file, attempting to resolve references in the AST. Valid Java files will usually * have errors in the CompilationUnit returned by this method, because classes, imports and * methods will be undefined (because we're only looking at a single file from a whole project). * Consequently, do not assume the returned object's getProblems() is an empty list. On the other * hand, {@link @parseSource} returns a CompilationUnit fit for syntax checking purposes. */ private static CompilationUnit parseAndResolveSource(String source) { ASTParser parser = createCompilationUnitParser(); parser.setSource(source.toCharArray()); parser.setResolveBindings(true); parser.setBindingsRecovery(true); parser.setEnvironment( EMPTY_STRING_ARRAY, EMPTY_STRING_ARRAY, EMPTY_STRING_ARRAY, true /* includeRunningVMBootclasspath */); parser.setUnitName("dontCare"); return (CompilationUnit) parser.createAST(null); }
private static List<String> getCompilationMessages(String filename, String source) { CompilationUnit cu = parseSource(source); List<String> result = new ArrayList<>(); for (Message message : cu.getMessages()) { result.add( String.format( "%s:%d: %s", filename, cu.getLineNumber(message.getStartPosition()), message.getMessage())); } return result; }
/** * @param methodname * @return */ public ExpressionStatement getBodyMethod(String methodname) { ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(getBodyMethodSource (methodname).toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { public boolean visit(ExpressionStatement node) { expression = node; return true; } }); return expression; }
public static IPath guessPackageRootFragment(IProject project, boolean main) throws CoreException, FileNotFoundException { IPath folder = project.getFullPath() .append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), main)); IResource interfaceFolder = ResourceManager.toResource(folder); List<IPath> paths = new ArrayList<IPath>(); if (interfaceFolder != null) { interfaceFolder.accept(new IResourceVisitor() { @Override public boolean visit(IResource resource) throws CoreException { IJavaElement element = JavaCore.create(resource); if (element != null && element instanceof ICompilationUnit) { try { ICompilationUnit cu = (ICompilationUnit) element; CompilationUnit ast = parse(cu); ast.accept(new ASTVisitor() { public boolean visit(PackageDeclaration node) { PackageDeclaration decl = (PackageDeclaration) node; String pkgname = decl.getName().getFullyQualifiedName(); int sizePath = pkgname.split("\\.").length; paths.add(resource.getParent().getFullPath().removeLastSegments(sizePath)); return false; } }); } catch (Exception e) { ResourceManager.logException(e); } } return true; } }); } if (paths.size() == 0) return null; return paths.get(0); }
/** * @param project * @param itype * @return * @throws JavaModelException */ private static IPath findPathInStaticField(IProject project, IType itype) throws JavaModelException { List<IPath> wrapper = new ArrayList<IPath>(); ICompilationUnit cu = itype.getCompilationUnit(); CompilationUnit ast = parse(cu); ast.accept(new ASTVisitor() { public boolean visit(VariableDeclarationFragment node) { SimpleName simpleName = node.getName(); IBinding bding = simpleName.resolveBinding(); if (bding instanceof IVariableBinding) { IVariableBinding binding = (IVariableBinding) bding; String type = binding.getType().getBinaryName(); // String name = simpleName.getFullyQualifiedName(); if ("MODEL_PATH".equals(name) && "java.nio.file.Path".equals(type)) { Expression expression = node.getInitializer(); if (expression instanceof MethodInvocation) { MethodInvocation mi = (MethodInvocation) expression; if ("get".equals(mi.resolveMethodBinding().getName()) && "java.nio.file.Path".equals(mi.resolveTypeBinding().getBinaryName())) { StringLiteral sl = (StringLiteral) mi.arguments().get(0); String argument = sl.getLiteralValue(); try { IPath p = ResourceManager.find(project, argument); wrapper.add(p); } catch (CoreException e) { ResourceManager.logException(e); } } } } } return true; } }); if (wrapper.size() > 0) return wrapper.get(0); return null; }
/** * @param compilationUnit * @param progressMonitor * @return * @throws JavaModelException */ public static CompilationUnit parse(final ICompilationUnit cu) { ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(cu); parser.setResolveBindings(true); parser.setEnvironment(null, null, null, true); parser.setBindingsRecovery(true); final CompilationUnit ast = (CompilationUnit) parser.createAST(new NullProgressMonitor()); return ast; }
/** * @param cu * @param rewrite * @param ast * @param pkgDeclaration */ private static void addPackageDeclaration(CompilationUnit cu, ASTRewrite rewrite, AST ast, String[] pkgDeclaration) { PackageDeclaration packageDeclaration = ast.newPackageDeclaration(); Name name = ast.newName(pkgDeclaration); packageDeclaration.setName(name); rewrite.set(cu, CompilationUnit.PACKAGE_PROPERTY, packageDeclaration, null); }
/** * Rename a class name into another name * * @param file * @param oldClassname * @param newName * @param monitor * @return * @throws MalformedTreeException * @throws BadLocationException * @throws CoreException */ public static IFile renameClass(IFile file, String oldClassname, String newName, IProgressMonitor monitor) throws MalformedTreeException, BadLocationException, CoreException { Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file); CompilationUnit cu = parse(unit); AST ast = cu.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); String classname = file.getName(); classname = classname.substring(0, classname.indexOf(".")); final String clazz = classname; ASTVisitor visitor = new ASTVisitor() { public boolean visit(SimpleName node) { String s = node.getIdentifier(); if (oldClassname.equalsIgnoreCase(s)) { rewrite.replace(node, ast.newSimpleName(newName), null); } return true; } }; cu.accept(visitor); addPackageDeclarationIfNeeded(file, cu, rewrite, ast); file.refreshLocal(IResource.DEPTH_ZERO, monitor); cu = parse(JavaCore.createCompilationUnitFrom(file)); save(cu, rewrite); } catch (Exception e) { ResourceManager.logException(e); } } }); return file; }
@Test public void testParse() throws Exception { IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true); IFile impl = (IFile) ResourceManager .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString()); ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl); CompilationUnit cu = JDTManager.parse(compilationUnit); IProblem[] pbs = cu.getProblems(); assertEquals(0, pbs.length); }