@Override public boolean visit(VariableDeclarationFragment param) { ASTNode parent = param.getParent(); if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement statement = (VariableDeclarationStatement) parent; ASTNode annotation = getAnnotation(statement.modifiers(), "Domain"); if (annotation != null) { ListRewrite paramRewrite = rewrite.getListRewrite(statement, VariableDeclarationStatement.MODIFIERS2_PROPERTY); paramRewrite.remove(annotation, null); } } return super.visit(param); }
ClassModel(ASTNodeFactory astNodeFactory, String className, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<TypeModel> innerTypes, List<ASTNode> modifiers) { groovism = provide(); this.className = className; this.packageDeclaration = packageDeclaration; this.fields = fieldDeclarations(fields); this.methods = unmodifiableList(new LinkedList<>(methods)); this.modifiers = unmodifiableList(new LinkedList<>(modifiers)); this.imports = imports; this.innerTypes = unmodifiableList(new LinkedList<>(innerTypes)); if (isTestClass(methods)) { this.superClassType = Optional.of(astNodeFactory.simpleType(Specification.class.getSimpleName())); imports.add(0, astNodeFactory.importDeclaration(Specification.class)); } else { this.superClassType = Optional.ofNullable(superClassType); } }
InterfaceModel(String typeName, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<ASTNode> modifiers) { groovism = provide(); LinkedList<ImportDeclaration> importDeclarations = new LinkedList<>(imports); this.superClassType = Optional.ofNullable(superClassType).map(Object::toString); this.typeName = typeName; this.packageDeclaration = packageDeclaration; this.fields = unmodifiableList(new LinkedList<>(fields)); this.methods = unmodifiableList(new LinkedList<>(methods)); this.imports = unmodifiableList(importDeclarations); this.modifiers = unmodifiableList(modifiers); }
private void handleTypeBinding(ASTNode node, ITypeBinding typeBinding, boolean includeTypeParameters) { if (typeBinding == null) { StructuralPropertyDescriptor locationInParent = node.getLocationInParent(); //System.out.println(locationInParent.getId() + " has no type binding"); } else { List<ITypeBinding> rawTypes = new ArrayList<ITypeBinding>(); Set<String> dejavu = new HashSet<String>(); this.appendRawTypes(rawTypes, dejavu, typeBinding, includeTypeParameters); for (ITypeBinding rawType : rawTypes) { if (!this.ignoreType(rawType)) { this.onTypeAccess(node, rawType); } } } }
private BlockInfo.Type getBlockType(ASTNode node) { if(node instanceof TypeDeclaration) return BlockInfo.Type.TYPE; else if(node instanceof MethodDeclaration) return BlockInfo.Type.METHOD; else if(node instanceof WhileStatement) return BlockInfo.Type.WHILE; else if(node instanceof ForStatement) return BlockInfo.Type.FOR; else if(node instanceof IfStatement) return BlockInfo.Type.IF; else return BlockInfo.Type.OTHER; }
@Override public boolean visit(FieldDeclaration node) { List fragments = node.fragments(); for(Object o : fragments) { VariableDeclarationFragment frag = (VariableDeclarationFragment) o; String varName = frag.getName().getIdentifier(); int line = cunit.getLineNumber(frag.getStartPosition()); ASTNode parent = node.getParent(); Scope scope = new Scope(cunit.getLineNumber(parent.getStartPosition()), getEndLine(parent, cunit)); TypeDeclaration dec = (TypeDeclaration) node.getParent(); String qName = dec.getName().getFullyQualifiedName(); PackageDeclaration packageDec = cunit.getPackage(); if(packageDec != null) qName = packageDec.getName().getFullyQualifiedName() + "." + qName; String type = !Modifier.isStatic(node.getModifiers()) ? qName : null; VariableTags tags = new VariableTags(varName, type, line, scope, true); variables.add(tags); } return false; }
@Override public boolean visit(ArrayAccess node) { String arrayName = node.getArray().toString(); List<String> iterators = iteratorsByArray.get(arrayName); if(iterators == null) { iterators= new ArrayList<>(); } String iteratorName = node.getIndex().getNodeType() == ASTNode.INFIX_EXPRESSION ? filterIteratorName((InfixExpression) node.getIndex()) : node.getIndex().toString(); if(!iterators.contains(iteratorName)) { isArrayPrimitiveFigure = true; iterators.add(iteratorName); allIterators.add(iteratorName); iteratorsByArray.put(arrayName, iterators); System.out.println("A variavel " + iteratorName + " est� a iterar sobre a array: " + node.getArray().toString()); } return super.visit(node); }
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 }
private static List<String> structuralPropertyNamesOf(final List<Class<? extends ASTNode>> nodes) { final List<String> names = new ArrayList<>(); for (final Class<? extends ASTNode> node : nodes) { try { final Method m = node.getDeclaredMethod("propertyDescriptors", int.class); final List l = (List) m.invoke(null, AST.JLS8); for (final Object o : l) { final StructuralPropertyDescriptor d = (StructuralPropertyDescriptor) o; names.add(d.getId()); } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { throw new RuntimeException("unexpected exception", ex); } } return names; }
/** * Creates a new EclipseParser * * @param sourceFile String of source file to read * @param outJ JSON parsed out * @throws IOException when file can't be opened or errors in reading/writing */ public EclipseParser(String sourceFile, PrintStream outJ, boolean prettyprint) throws IOException { File file = new File(sourceFile); final BufferedReader reader = new BufferedReader(new FileReader(file)); char[] source = IOUtils.toCharArray(reader); reader.close(); this.parser = ASTParser.newParser(AST.JLS8); parser.setSource(source); parser.setKind(ASTParser.K_COMPILATION_UNIT); final JsonFactory jsonF = new JsonFactory(); jG = jsonF.createGenerator(outJ); if (prettyprint) { jG.setPrettyPrinter(new DefaultPrettyPrinter()); mapper.enable(SerializationFeature.INDENT_OUTPUT); } mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); SimpleModule module = new SimpleModule(); module.addSerializer(ASTNode.class, new NodeSerializer()); mapper.registerModule(module); }
@Override public void serialize(ASTNode node, JsonGenerator jG, SerializerProvider provider) throws IOException { List<StructuralPropertyDescriptor> descriptorList = node.structuralPropertiesForType(); nCount++; jG.writeStartObject(); for (StructuralPropertyDescriptor descriptor : descriptorList) { Object child = node.getStructuralProperty(descriptor); if (child instanceof List) { serializeChildList((List<ASTNode>) child, descriptor, provider); } else if (child instanceof ASTNode) { serializeChild((ASTNode) child, descriptor, provider); } else if (child != null) { jG.writeFieldName(descriptor.getId()); jG.writeString(child.toString()); } } jG.writeEndObject(); }
@Override public void endVisit(CompilationUnit node) { ASTNode enclosingNode = null; if (!getStatus().hasFatalError() && hasSelectedNodes()) { enclosingNode= getEnclosingNode(getFirstSelectedNode()); } super.endVisit(node); if (enclosingNode != null && !getStatus().hasFatalError()) { fExceptions = ExceptionAnalyzer.perform(enclosingNode, getSelection()); if (fExceptions == null || fExceptions.length == 0) { if (enclosingNode instanceof MethodReference) { invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_doesNotContain); } else { fExceptions = new ITypeBinding[] { node.getAST().resolveWellKnownType("java.lang.Exception") }; //$NON-NLS-1$ } } } }
public static LoadLiteral createFrom(ASTNode node) { LoadLiteral retNode = null; Adapter factory = Adapter.getInstance(); // XXX. Check compatible types AstNode astNode = factory.get(node); if ( astNode instanceof LoadLiteral ) { retNode = (LoadLiteral)astNode; } else { retNode = LoadLiteral.create(); retNode.complexExpression = node.toString(); factory.map(node, retNode); } return retNode; }
/** * Evaluates the insertion position of a new node. * * @param listRewrite The list rewriter to which the new node will be added * @param sibling The Java element before which the new element should be added. * @return the AST node of the list to insert before or null to insert as last. * @throws JavaModelException thrown if accessing the Java element failed */ public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElement sibling) throws JavaModelException { if (sibling instanceof IMember) { ISourceRange sourceRange= ((IMember) sibling).getSourceRange(); if (sourceRange == null) { return null; } int insertPos= sourceRange.getOffset(); List<? extends ASTNode> members= listRewrite.getOriginalList(); for (int i= 0; i < members.size(); i++) { ASTNode curr= members.get(i); if (curr.getStartPosition() >= insertPos) { return curr; } } } return null; }
@Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (selection instanceof ITextSelection) { ASTNode node = ASTUtils.getASTNode((ITextSelection) selection); if (node != null) { String string = node.toString(); CharSequence subSequence = string.subSequence(0, string.length() > 100 ? 100 : string.length()); RelatedObjectsEdges.this.setContentDescription(subSequence.toString() .trim()); RelatedObjectsEdges.this.fTreeViewer.setInput(node); RelatedObjectsEdges.this.fTreeViewer.expandAll(); RelatedObjectsEdges.this.tableViewer.setInput(null); } } }
private ASTNode getAnnotation(List paramModifiers, String annotation) { ASTNode found = null; for (Iterator itParamModifiers = paramModifiers.iterator(); itParamModifiers.hasNext();) { IExtendedModifier o = (IExtendedModifier) itParamModifiers.next(); if (o instanceof SingleMemberAnnotation) { SingleMemberAnnotation annot = (SingleMemberAnnotation) o; String name = annot.getTypeName().toString(); if (name.compareTo(annotation) == 0) { found = annot; break; } } } return found; }
/** * Collects all top level methods from CompilationUnits. (Embedded Methods are currently not collected.) * * @param compilationUnitToASTNode the mapping of CompilationUnits to preparsed ASTNodes * @return the list of all top level methods within the CompilationUnits */ public static List<MethodDeclaration> scanForMethodDeclarations( Map<ICompilationUnit, ASTNode> compilationUnitToASTNode) { if (compilationUnitToASTNode == null) { throw new CrystalRuntimeException("null map of compilation units to ASTNodes"); } // Create an empty list List<MethodDeclaration> methodList = new LinkedList<MethodDeclaration>(); List<MethodDeclaration> tempMethodList; // Get all CompilationUnits and look for MethodDeclarations in each Set<Entry<ICompilationUnit, ASTNode>> entrySet = compilationUnitToASTNode.entrySet(); Iterator<Entry<ICompilationUnit, ASTNode>> iterator = entrySet.iterator(); while(iterator.hasNext()) { Entry<ICompilationUnit, ASTNode> entry = iterator.next(); ICompilationUnit icu = entry.getKey(); tempMethodList = WorkspaceUtilities.scanForMethodDeclarationsFromAST(compilationUnitToASTNode.get(icu)); methodList.addAll(tempMethodList); } return methodList; }
public static void addMethodWithConstrNameProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode instanceof MethodDeclaration) { MethodDeclaration declaration= (MethodDeclaration) selectedNode; ASTRewrite rewrite= ASTRewrite.create(declaration.getAST()); rewrite.set(declaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.TRUE, null); String label= CorrectionMessages.ReturnTypeSubProcessor_constrnamemethod_description; ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_CONSTRUCTOR); proposals.add(proposal); } }
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<CUCorrectionProposal> proposals) { if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) { ASTNode type= selectedNode.getParent(); if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) { SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent(); if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) { if (svd.getName().getLength() == 0) { SimpleName simpleName= (SimpleName) selectedNode; String name= simpleName.getIdentifier(); int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7; String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name)); proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance)); } } } } }
/** * Returns the binding of the variable written in an Assignment. * @param assignment The assignment * @return The binding or <code>null</code> if no bindings are available. */ public static IVariableBinding getAssignedVariable(Assignment assignment) { Expression leftHand = assignment.getLeftHandSide(); switch (leftHand.getNodeType()) { case ASTNode.SIMPLE_NAME: return (IVariableBinding) ((SimpleName) leftHand).resolveBinding(); case ASTNode.QUALIFIED_NAME: return (IVariableBinding) ((QualifiedName) leftHand).getName().resolveBinding(); case ASTNode.FIELD_ACCESS: return ((FieldAccess) leftHand).resolveFieldBinding(); case ASTNode.SUPER_FIELD_ACCESS: return ((SuperFieldAccess) leftHand).resolveFieldBinding(); default: return null; } }
public static String getCatchBodyContent(ICompilationUnit cu, String exceptionType, String variableName, ASTNode locationInAST, String lineDelimiter) throws CoreException { String enclosingType = ""; //$NON-NLS-1$ String enclosingMethod = ""; //$NON-NLS-1$ if (locationInAST != null) { MethodDeclaration parentMethod = ASTResolving.findParentMethodDeclaration(locationInAST); if (parentMethod != null) { enclosingMethod = parentMethod.getName().getIdentifier(); locationInAST = parentMethod; } ASTNode parentType = ASTResolving.findParentType(locationInAST); if (parentType instanceof AbstractTypeDeclaration) { enclosingType = ((AbstractTypeDeclaration) parentType).getName().getIdentifier(); } } return getCatchBodyContent(cu, exceptionType, variableName, enclosingType, enclosingMethod, lineDelimiter); }
/** * returns the name associated with an assignment instruction * * @param instr * @return */ public static String getSimpleAssignName(AssignmentInstruction instr) { if (instr instanceof LoadLiteralInstruction) return ((LoadLiteralInstruction) instr).getLiteral().toString(); ASTNode parentInstr = instr.getNode().getParent(); if (parentInstr instanceof VariableDeclarationFragment) { return ((VariableDeclarationFragment) parentInstr).getName().getFullyQualifiedName(); } if (parentInstr instanceof Assignment) { Expression leftHnsd = ((Assignment) parentInstr).getLeftHandSide(); if (leftHnsd instanceof SimpleName) { return ((SimpleName) leftHnsd).getFullyQualifiedName(); } else if (leftHnsd instanceof FieldAccess) { return ((FieldAccess) leftHnsd).getName().getFullyQualifiedName(); } } throw new IllegalStateException("cannot find local variable associated with " + instr); }
static boolean isLeftHandSideOfAssignment(ASTNode node) { Assignment assignment = (Assignment) ASTNodes.getParent(node, ASTNode.ASSIGNMENT); if (assignment != null) { Expression leftHandSide = assignment.getLeftHandSide(); if (leftHandSide == node) { return true; } if (ASTNodes.isParent(node, leftHandSide)) { switch (leftHandSide.getNodeType()) { case ASTNode.SIMPLE_NAME: return true; case ASTNode.FIELD_ACCESS: return node == ((FieldAccess) leftHandSide).getName(); case ASTNode.QUALIFIED_NAME: return node == ((QualifiedName) leftHandSide).getName(); case ASTNode.SUPER_FIELD_ACCESS: return node == ((SuperFieldAccess) leftHandSide).getName(); default: return false; } } } return false; }
@Override protected boolean addInitializer(final VariableDeclarationFragment fragment, final ASTNode declarationNode) { Assert.isNotNull(fragment); final Expression expression= fragment.getAST().newNumberLiteral(DEFAULT_EXPRESSION); if (expression != null) { fragment.setInitializer(expression); } return true; }
private ASTRewrite doAddEnumConst(CompilationUnit astRoot) { SimpleName node= fOriginalNode; ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding); if (newTypeDecl == null) { astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null); newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey()); } if (newTypeDecl != null) { AST ast= newTypeDecl.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); EnumConstantDeclaration constDecl= ast.newEnumConstantDeclaration(); constDecl.setName(ast.newSimpleName(node.getIdentifier())); ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, EnumDeclaration.ENUM_CONSTANTS_PROPERTY); listRewriter.insertLast(constDecl, null); return rewrite; } return null; }
/** * 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; }
private static String getArgument(TagElement curr) { List<? extends ASTNode> fragments= curr.fragments(); if (!fragments.isEmpty()) { Object first= fragments.get(0); if (first instanceof Name) { return ASTNodes.getSimpleNameIdentifier((Name) first); } else if (first instanceof TextElement && TagElement.TAG_PARAM.equals(curr.getTagName())) { String text= ((TextElement) first).getText(); if ("<".equals(text) && fragments.size() >= 3) { //$NON-NLS-1$ Object second= fragments.get(1); Object third= fragments.get(2); if (second instanceof Name && third instanceof TextElement && ">".equals(((TextElement) third).getText())) { //$NON-NLS-1$ return '<' + ASTNodes.getSimpleNameIdentifier((Name) second) + '>'; } } else if (text.startsWith(String.valueOf('<')) && text.endsWith(String.valueOf('>')) && text.length() > 2) { return text.substring(1, text.length() - 1); } } } return null; }
public static ClassInstanceCreation createFrom(ASTNode node) { ClassInstanceCreation retNode = null; Adapter factory = Adapter.getInstance(); AstNode astNode = factory.get(node); if ( astNode instanceof ClassInstanceCreation ) { retNode = (ClassInstanceCreation)astNode; } else { retNode = ClassInstanceCreation.create(); retNode.complexExpression = node.toString(); factory.map(node, retNode); } return retNode; }
public static void addMethodReturnsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) throws JavaModelException { CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof ReturnStatement)) { return; } ReturnStatement returnStatement= (ReturnStatement) selectedNode; Expression expression= returnStatement.getExpression(); if (expression == null) { return; } BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { MethodDeclaration methDecl= (MethodDeclaration) decl; Type retType= methDecl.getReturnType2(); if (retType == null || retType.resolveBinding() == null) { return; } TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals); } }
private void addNewJavadoc(ASTRewrite rewrite, MethodDeclaration decl, ImportRewriteContext context) throws CoreException { IType parentType = fField.getDeclaringType(); String typeName = Signature.toString(fField.getTypeSignature()); String accessorName = StubUtility.getBaseName(fField); String lineDelim = "\n"; String comment = null; String name = getFunctionName(); if (isGetter) { comment = CodeGeneration.getGetterComment(fField.getCompilationUnit(), parentType.getTypeQualifiedName('.'), name, fField.getElementName(), typeName, accessorName, lineDelim); } else { String argname = getArgumentName(); comment = CodeGeneration.getSetterComment(fField.getCompilationUnit(), parentType.getTypeQualifiedName('.'), name, fField.getElementName(), typeName, argname, accessorName, lineDelim); } comment = comment.substring(0, comment.lastIndexOf(lineDelim)); if (comment != null) { Javadoc javadoc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); decl.setJavadoc(javadoc); } }
public boolean isLiteralNodeSelected() { ASTNode[] nodes = getSelectedNodes(); if (nodes.length != 1) { return false; } ASTNode node = nodes[0]; switch (node.getNodeType()) { case ASTNode.BOOLEAN_LITERAL: case ASTNode.CHARACTER_LITERAL: case ASTNode.NULL_LITERAL: case ASTNode.NUMBER_LITERAL: return true; default: return false; } }
/** * 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 static void highlightInEditor(ASTNode enclosingDeclaration , ASTNode expressionNode){ if(TraceToCodeUIAction.highlightCode){ IJavaElement javaElement = getIJavaElement(enclosingDeclaration); if (javaElement != null) { try { EditorUtility.openInEditor(javaElement); IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); if (part instanceof ITextEditor) { ((ITextEditor) part).selectAndReveal(expressionNode.getStartPosition(), expressionNode.getLength()); } } catch (PartInitException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
/** * Removes all {@link Annotation} whose only {@link Target} is {@link ElementType#TYPE_USE} from * <code>node</code>'s <code>childListProperty</code>. * <p> * In a combination of {@link ElementType#TYPE_USE} and {@link ElementType#TYPE_PARAMETER} * the latter is ignored, because this is implied by the former and creates no ambiguity.</p> * * @param node ASTNode * @param childListProperty child list property * @param rewrite rewrite that removes the nodes * @param editGroup the edit group in which to collect the corresponding text edits, or null if * ungrouped */ public static void removePureTypeAnnotations(ASTNode node, ChildListPropertyDescriptor childListProperty, ASTRewrite rewrite, TextEditGroup editGroup) { CompilationUnit root= (CompilationUnit) node.getRoot(); if (!JavaModelUtil.is18OrHigher(root.getJavaElement().getJavaProject())) { return; } ListRewrite listRewrite= rewrite.getListRewrite(node, childListProperty); @SuppressWarnings("unchecked") List<? extends ASTNode> children= (List<? extends ASTNode>) node.getStructuralProperty(childListProperty); for (ASTNode child : children) { if (child instanceof Annotation) { Annotation annotation= (Annotation) child; if (isPureTypeAnnotation(annotation)) { listRewrite.remove(child, editGroup); } } } }
public void run() { List<ICompilationUnit> allCompilationUnits = WorkspaceUtilities.scanForCompilationUnits(); for (ICompilationUnit compUnit : allCompilationUnits) { if (compUnit == null) { System.err.println("AbstractCompilationUnitAnalysis: null CompilationUnit"); continue; } // Obtain the AST for this CompilationUnit and analyze it ASTNode node = WorkspaceUtilities.getASTNodeFromCompilationUnit(compUnit); if ((node != null) && (node instanceof CompilationUnit)) { analyzeCompilationUnit((CompilationUnit) node, compUnit); } else { System.err.println("AbstractCompilationUnitAnalysis: Could not retrieve the ASTNode for CompilationUnit " + compUnit.getElementName()); } } }
@Override public boolean visit(org.eclipse.jdt.core.dom.QualifiedName node) { if (node.getParent().getNodeType() != ASTNode.IMPORT_DECLARATION) { visitExpressionIfName(node.getQualifier()); } return false; }
private static AbstractTypeDeclaration getContainingClass(ASTNode node) { while (node != null) { if (node instanceof AbstractTypeDeclaration) { return (AbstractTypeDeclaration) node; } node = node.getParent(); } return null; }
private static boolean isDescendantOfAnonymousClassDeclaration(ASTNode node) { while (node != null) { if (node instanceof AnonymousClassDeclaration) { return true; } node = node.getParent(); } return false; }