@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask(RefactoringCoreMessages.ExtractMethodRefactoring_checking_new_name, 2); pm.subTask(EMPTY); RefactoringStatus result = checkMethodName(); result.merge(checkParameterNames()); result.merge(checkVarargOrder()); pm.worked(1); if (pm.isCanceled()) { throw new OperationCanceledException(); } BodyDeclaration node = fAnalyzer.getEnclosingBodyDeclaration(); if (node != null) { fAnalyzer.checkInput(result, fMethodName, fDestination); pm.worked(1); } pm.done(); return result; }
private void initializeDestinations() { List<ASTNode> result = new ArrayList<>(); BodyDeclaration decl = fAnalyzer.getEnclosingBodyDeclaration(); ASTNode current = ASTResolving.findParentType(decl.getParent()); if (fAnalyzer.isValidDestination(current)) { result.add(current); } if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) { ITypeBinding binding = ASTNodes.getEnclosingType(current); ASTNode next = ASTResolving.findParentType(current.getParent()); while (next != null && binding != null && binding.isNested()) { if (fAnalyzer.isValidDestination(next)) { result.add(next); } current = next; binding = ASTNodes.getEnclosingType(current); next = ASTResolving.findParentType(next.getParent()); } } fDestinations = result.toArray(new ASTNode[result.size()]); fDestination = fDestinations[fDestinationIndex]; }
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 int getInterfaceMethodModifiers(ASTNode targetTypeDecl, boolean createAbstractMethod) { // for interface and annotation members copy the modifiers from an existing member if (targetTypeDecl instanceof TypeDeclaration) { TypeDeclaration type= (TypeDeclaration) targetTypeDecl; MethodDeclaration[] methodDecls= type.getMethods(); if (methodDecls.length > 0) { if (createAbstractMethod) { for (MethodDeclaration methodDeclaration : methodDecls) { IMethodBinding methodBinding= methodDeclaration.resolveBinding(); if (methodBinding != null && JdtFlags.isAbstract(methodBinding)) { return methodDeclaration.getModifiers(); } } } return methodDecls[0].getModifiers() & Modifier.PUBLIC; } List<BodyDeclaration> bodyDecls= type.bodyDeclarations(); if (bodyDecls.size() > 0) { return bodyDecls.get(0).getModifiers() & Modifier.PUBLIC; } } return 0; }
public static void assignModifiersForElementBasedOnDeclaration(NamedElement element, BodyDeclaration declaration) { int modifiers = declaration.getModifiers(); VisibilityKind visibility = VisibilityProvider.getVisibilityOfNamedElementFromModifiers(element, modifiers); element.setVisibility(visibility); boolean isAbstract = Modifier.isAbstract(modifiers); boolean isStatic = Modifier.isStatic(modifiers); if (element instanceof Classifier) { Classifier classifierElem = (Classifier) element; classifierElem.setIsAbstract(isAbstract); } if (element instanceof BehavioralFeature) { BehavioralFeature featureElem = (BehavioralFeature) element; featureElem.setIsStatic(isStatic); featureElem.setIsAbstract(isAbstract); } if (element instanceof Property) { Property propertyElem = (Property) element; propertyElem.setIsStatic(isStatic); } }
private static Java50Fix createFix( CompilationUnit compilationUnit, IProblemLocation problem, String annotation, String label) { ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement(); if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) return null; ASTNode selectedNode = problem.getCoveringNode(compilationUnit); if (selectedNode == null) return null; ASTNode declaringNode = getDeclaringNode(selectedNode); if (!(declaringNode instanceof BodyDeclaration)) return null; BodyDeclaration declaration = (BodyDeclaration) declaringNode; AnnotationRewriteOperation operation = new AnnotationRewriteOperation(declaration, annotation); return new Java50Fix(label, compilationUnit, new CompilationUnitRewriteOperation[] {operation}); }
private static void createAddDeprecatedAnnotationOperations( CompilationUnit compilationUnit, IProblemLocation[] locations, List<CompilationUnitRewriteOperation> result) { for (int i = 0; i < locations.length; i++) { IProblemLocation problem = locations[i]; if (isMissingDeprecationProblem(problem.getProblemId())) { ASTNode selectedNode = problem.getCoveringNode(compilationUnit); if (selectedNode != null) { ASTNode declaringNode = getDeclaringNode(selectedNode); if (declaringNode instanceof BodyDeclaration) { BodyDeclaration declaration = (BodyDeclaration) declaringNode; AnnotationRewriteOperation operation = new AnnotationRewriteOperation(declaration, DEPRECATED); result.add(operation); } } } } }
public static void checkModifiers(ProblemCollector collector, BodyDeclaration elem, Predicate<Modifier> allowSpecific) { for (Object obj : elem.modifiers()) { if (!(obj instanceof Modifier)) { continue; } Modifier modifier = (Modifier) obj; boolean valid; if (allowSpecific.test(modifier)) { valid = true; } else { valid = modifier.isPrivate() || modifier.isPublic() || modifier.isProtected() || modifier.isFinal(); } if (!valid) { collector.report(new InvalidModifier(collector.getSourceInfo(), modifier)); } } }
private TagElement getDelegateJavadocTag(BodyDeclaration declaration) throws JavaModelException { Assert.isNotNull(declaration); String msg = RefactoringCoreMessages.DelegateCreator_use_member_instead; int firstParam = msg.indexOf("{0}"); // $NON-NLS-1$ Assert.isTrue(firstParam != -1); List<ASTNode> fragments = new ArrayList<ASTNode>(); TextElement text = getAst().newTextElement(); text.setText(msg.substring(0, firstParam).trim()); fragments.add(text); fragments.add(createJavadocMemberReferenceTag(declaration, getAst())); text = getAst().newTextElement(); text.setText(msg.substring(firstParam + 3).trim()); fragments.add(text); final TagElement tag = getAst().newTagElement(); tag.setTagName(TagElement.TAG_DEPRECATED); tag.fragments().addAll(fragments); return tag; }
private void createFieldsForAccessedLocals( CompilationUnitRewrite rewrite, IVariableBinding[] varBindings, String[] fieldNames, List<BodyDeclaration> newBodyDeclarations) throws CoreException { final ImportRewrite importRewrite = rewrite.getImportRewrite(); final ASTRewrite astRewrite = rewrite.getASTRewrite(); final AST ast = astRewrite.getAST(); for (int i = 0; i < varBindings.length; i++) { VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); fragment.setInitializer(null); fragment.setName(ast.newSimpleName(fieldNames[i])); FieldDeclaration field = ast.newFieldDeclaration(fragment); ITypeBinding varType = varBindings[i].getType(); field.setType(importRewrite.addImport(varType, ast)); field.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.FINAL)); if (doAddComments()) { String string = CodeGeneration.getFieldComment( rewrite.getCu(), varType.getName(), fieldNames[i], StubUtility.getLineDelimiterUsed(fCu)); if (string != null) { Javadoc javadoc = (Javadoc) astRewrite.createStringPlaceholder(string, ASTNode.JAVADOC); field.setJavadoc(javadoc); } } newBodyDeclarations.add(field); addLinkedPosition(KEY_FIELD_NAME_EXT + i, fragment.getName(), astRewrite, false); } }
private List<VariableDeclarationFragment> getFieldsToInitializeInConstructor() { List<VariableDeclarationFragment> result = new ArrayList<VariableDeclarationFragment>(0); for (Iterator<BodyDeclaration> iter = fAnonymousInnerClassNode.bodyDeclarations().iterator(); iter.hasNext(); ) { Object element = iter.next(); if (element instanceof FieldDeclaration) { List<VariableDeclarationFragment> fragments = ((FieldDeclaration) element).fragments(); for (Iterator<VariableDeclarationFragment> fragmentIter = fragments.iterator(); fragmentIter.hasNext(); ) { VariableDeclarationFragment fragment = fragmentIter.next(); if (isToBeInitializerInConstructor(fragment, result)) result.add(fragment); } } } return result; }
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask(RefactoringCoreMessages.ExtractMethodRefactoring_checking_new_name, 2); pm.subTask(EMPTY); RefactoringStatus result = checkMethodName(); result.merge(checkParameterNames()); result.merge(checkVarargOrder()); pm.worked(1); if (pm.isCanceled()) throw new OperationCanceledException(); BodyDeclaration node = fAnalyzer.getEnclosingBodyDeclaration(); if (node != null) { fAnalyzer.checkInput(result, fMethodName, fDestination); pm.worked(1); } pm.done(); return result; }
private void initializeDestinations() { List<ASTNode> result = new ArrayList<ASTNode>(); BodyDeclaration decl = fAnalyzer.getEnclosingBodyDeclaration(); ASTNode current = ASTResolving.findParentType(decl.getParent()); if (fAnalyzer.isValidDestination(current)) { result.add(current); } if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) { ITypeBinding binding = ASTNodes.getEnclosingType(current); ASTNode next = ASTResolving.findParentType(current.getParent()); while (next != null && binding != null && binding.isNested()) { if (fAnalyzer.isValidDestination(next)) { result.add(next); } current = next; binding = ASTNodes.getEnclosingType(current); next = ASTResolving.findParentType(next.getParent()); } } fDestinations = result.toArray(new ASTNode[result.size()]); fDestination = fDestinations[fDestinationIndex]; }
private void computeConstantDeclarationLocation() throws JavaModelException { if (isDeclarationLocationComputed()) return; BodyDeclaration lastStaticDependency = null; Iterator<BodyDeclaration> decls = getContainingTypeDeclarationNode().bodyDeclarations().iterator(); while (decls.hasNext()) { BodyDeclaration decl = decls.next(); int modifiers; if (decl instanceof FieldDeclaration) modifiers = ((FieldDeclaration) decl).getModifiers(); else if (decl instanceof Initializer) modifiers = ((Initializer) decl).getModifiers(); else { continue; /* this declaration is not a field declaration or initializer, so the placement of the constant declaration relative to it does not matter */ } if (Modifier.isStatic(modifiers) && depends(getSelectedExpression(), decl)) lastStaticDependency = decl; } if (lastStaticDependency == null) fInsertFirst = true; else fToInsertAfter = lastStaticDependency; }
private static boolean depends(IExpressionFragment selected, BodyDeclaration bd) { /* We currently consider selected to depend on bd only if db includes a declaration * of a static field on which selected depends. * * A more accurate strategy might be to also check if bd contains (or is) a * static initializer containing code which changes the value of a static field on * which selected depends. However, if a static is written to multiple times within * during class initialization, it is difficult to predict which value should be used. * This would depend on which value is used by expressions instances for which the new * constant will be substituted, and there may be many of these; in each, the * static field in question may have taken on a different value (if some of these uses * occur within static initializers). */ if (bd instanceof FieldDeclaration) { FieldDeclaration fieldDecl = (FieldDeclaration) bd; for (Iterator<VariableDeclarationFragment> fragments = fieldDecl.fragments().iterator(); fragments.hasNext(); ) { VariableDeclarationFragment fragment = fragments.next(); SimpleName staticFieldName = fragment.getName(); if (selected.getSubFragmentsMatching( ASTFragmentFactory.createFragmentForFullSubtree(staticFieldName)) .length != 0) return true; } } return false; }
private static boolean isStaticFieldOrStaticInitializer(BodyDeclaration node) { if (node instanceof MethodDeclaration || node instanceof AbstractTypeDeclaration) return false; int modifiers; if (node instanceof FieldDeclaration) { modifiers = ((FieldDeclaration) node).getModifiers(); } else if (node instanceof Initializer) { modifiers = ((Initializer) node).getModifiers(); } else { Assert.isTrue(false); return false; } if (!Modifier.isStatic(modifiers)) return false; return true; }
public static ITypeBinding[] perform(BodyDeclaration enclosingNode, Selection selection) { ExceptionAnalyzer analyzer = new ExceptionAnalyzer(selection); enclosingNode.accept(analyzer); List<ITypeBinding> exceptions = analyzer.getCurrentExceptions(); if (enclosingNode.getNodeType() == ASTNode.METHOD_DECLARATION) { List<Type> thrownExceptions = ((MethodDeclaration) enclosingNode).thrownExceptionTypes(); for (Iterator<Type> thrown = thrownExceptions.iterator(); thrown.hasNext(); ) { ITypeBinding thrownException = thrown.next().resolveBinding(); if (thrownException != null) { for (Iterator<ITypeBinding> excep = exceptions.iterator(); excep.hasNext(); ) { ITypeBinding exception = excep.next(); if (exception.isAssignmentCompatible(thrownException)) excep.remove(); } } } } Collections.sort(exceptions, new ExceptionComparator()); return exceptions.toArray(new ITypeBinding[exceptions.size()]); }
public boolean resolveInMethodBody() { if (fInMethodBodyRequested) return fInMethodBody; fInMethodBodyRequested = true; resolveSelectedNodes(); ASTNode node = getStartNode(); if (node == null) { fInMethodBody = true; } else { while (node != null) { int nodeType = node.getNodeType(); if (nodeType == ASTNode.BLOCK && node.getParent() instanceof BodyDeclaration) { fInMethodBody = node.getParent().getNodeType() == ASTNode.METHOD_DECLARATION; break; } else if (nodeType == ASTNode.ANONYMOUS_CLASS_DECLARATION) { fInMethodBody = false; break; } node = node.getParent(); } } return fInMethodBody; }
@Override public int compare(BodyDeclaration o1, BodyDeclaration o2) { IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); String savedOrder = preferenceStore.getString(PreferenceConstants.P_ORDER); String[] order = OrderConverter.convert(savedOrder); boolean orderByName = preferenceStore.getBoolean(PreferenceConstants.P_ORDER_BY_NAME); Member member1 = _createMember(o1); Member member2 = _createMember(o2); int modifierOrder1 = _computeOrderByModifiers(member1.modifiers, order); int modifierOrder2 = _computeOrderByModifiers(member2.modifiers, order); // If they have the same modifiers then compare them by name if (modifierOrder1 == modifierOrder2) { return orderByName ? member1.name.compareTo(member2.name) : 0; } // Compare them by modifiers return (modifierOrder1 < modifierOrder2) ? -1 : 1; }
private ASTRewrite doAddField(CompilationUnit astRoot) { SimpleName node = fOriginalNode; boolean isInDifferentCU = false; ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding); if (newTypeDecl == null) { astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null); newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey()); isInDifferentCU = true; } ImportRewrite imports = createImportRewrite(astRoot); ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext( ASTResolving.findParentBodyDeclaration(node), imports); if (newTypeDecl != null) { AST ast = newTypeDecl.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(node.getIdentifier())); Type type = evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding); FieldDeclaration newDecl = ast.newFieldDeclaration(fragment); newDecl.setType(type); newDecl .modifiers() .addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl))); if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) { fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0)); } ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl); List<BodyDeclaration> decls = ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property); int maxOffset = isInDifferentCU ? -1 : node.getStartPosition(); int insertIndex = findFieldInsertIndex(decls, newDecl, maxOffset); ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property); listRewriter.insertAt(newDecl, insertIndex, null); ModifierCorrectionSubProcessor.installLinkedVisibilityProposals( getLinkedProposalModel(), rewrite, newDecl.modifiers(), fSenderBinding.isInterface()); addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE); if (!isInDifferentCU) { addLinkedPosition(rewrite.track(node), true, KEY_NAME); } addLinkedPosition(rewrite.track(fragment.getName()), false, KEY_NAME); if (fragment.getInitializer() != null) { addLinkedPosition(rewrite.track(fragment.getInitializer()), false, KEY_INITIALIZER); } return rewrite; } return null; }
private VariableDeclarationFragment addFieldDeclaration( ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression) { if (fExistingFragment != null) { return fExistingFragment; } ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl); List<BodyDeclaration> decls = ASTNodes.getBodyDeclarations(newTypeDecl); AST ast = newTypeDecl.getAST(); String[] varNames = suggestFieldNames(fTypeBinding, expression, modifiers); for (int i = 0; i < varNames.length; i++) { addLinkedPositionProposal(KEY_NAME, varNames[i], null); } String varName = varNames[0]; VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment(); newDeclFrag.setName(ast.newSimpleName(varName)); FieldDeclaration newDecl = ast.newFieldDeclaration(newDeclFrag); Type type = evaluateType(ast); newDecl.setType(type); newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers)); ModifierCorrectionSubProcessor.installLinkedVisibilityProposals( getLinkedProposalModel(), rewrite, newDecl.modifiers(), false); int insertIndex = findFieldInsertIndex(decls, fNodeToAssign.getStartPosition()); rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null); return newDeclFrag; }
private int findLastFieldIndex(TypeDeclaration newType) { return ((List<BodyDeclaration>) newType.bodyDeclarations()) .stream() .filter(element -> element instanceof FieldDeclaration) .collect(Collectors.toList()) .size(); }
private JavaVisibilityScopeModifier getFieldModifier(BodyDeclaration fieldDeclaration) { return ((List<IExtendedModifier>) fieldDeclaration.modifiers()) .stream() .filter(modifier -> modifier instanceof Modifier) .map(modifier -> ((Modifier) modifier).getKeyword().toString()) .filter(modifierKeyword -> JavaVisibilityScopeModifier.isValid(modifierKeyword)) .map(modifierKeyword -> JavaVisibilityScopeModifier.convert(modifierKeyword)) .filter(Optional::isPresent) .map(Optional::get) .findFirst() .orElse(JavaVisibilityScopeModifier.DEFAULT_MODIFIER); }
public boolean test(BodyDeclaration method, Predicate<IExtendedModifier> modifiedPredicate) { return ((List<IExtendedModifier>) method.modifiers()) .stream() .filter(modifier -> modifier instanceof Modifier) .filter(modifiedPredicate) .findFirst() .isPresent(); }
@Override public boolean test(BodyDeclaration bodyDeclaration) { return ((List<IExtendedModifier>) bodyDeclaration.modifiers()) .stream() .filter(modifier -> modifier instanceof SingleMemberAnnotation) .map(modifier -> (SingleMemberAnnotation) modifier) .filter(modifier -> isGeneratedAnnotation(modifier)) .filter(modifier -> modifier.getValue() instanceof StringLiteral) .filter(annotation -> ((StringLiteral) annotation.getValue()).getLiteralValue().equals(PLUGIN_GENERATED_ANNOTATION_NAME)) .findFirst() .isPresent(); }
public <T extends BodyDeclaration> List<T> extractBodyDeclaration(TypeDeclaration typeDeclaration, Class<T> expectedReturnType) { return ((List<BodyDeclaration>) typeDeclaration.bodyDeclarations()) .stream() .filter(value -> value.getClass().equals(expectedReturnType)) .map(value -> (T) value) .collect(Collectors.toList()); }
public static List<BodyDeclaration> getBodyDeclarations(ASTNode node) { if (node instanceof AbstractTypeDeclaration) { return ((AbstractTypeDeclaration)node).bodyDeclarations(); } else if (node instanceof AnonymousClassDeclaration) { return ((AnonymousClassDeclaration)node).bodyDeclarations(); } // should not happen. Assert.isTrue(false); return null; }
/** * Computes the maximum number of local variable declarations in the given * body declaration. * * @param declaration * the body declaration. Must either be a method declaration, or * an initializer, or a field declaration. * @return the maximum number of local variables */ public static int perform(BodyDeclaration declaration) { Assert.isTrue(declaration != null); switch (declaration.getNodeType()) { case ASTNode.METHOD_DECLARATION: case ASTNode.FIELD_DECLARATION: case ASTNode.INITIALIZER: return internalPerform(declaration); default: throw new IllegalArgumentException(declaration.toString()); } }
private static int getOrderPreference(BodyDeclaration member, MemberSortOrder sortOrder) { int memberType= member.getNodeType(); int modifiers= member.getModifiers(); switch (memberType) { case ASTNode.TYPE_DECLARATION: case ASTNode.ENUM_DECLARATION : case ASTNode.ANNOTATION_TYPE_DECLARATION : return sortOrder.getCategoryIndex(MemberSortOrder.TYPE_INDEX) * 2; case ASTNode.FIELD_DECLARATION: if (Modifier.isStatic(modifiers)) { int index = sortOrder.getCategoryIndex(MemberSortOrder.STATIC_FIELDS_INDEX) * 2; if (Modifier.isFinal(modifiers)) { return index; // first final static, then static } return index + 1; } return sortOrder.getCategoryIndex(MemberSortOrder.FIELDS_INDEX) * 2; case ASTNode.INITIALIZER: if (Modifier.isStatic(modifiers)) { return sortOrder.getCategoryIndex(MemberSortOrder.STATIC_INIT_INDEX) * 2; } return sortOrder.getCategoryIndex(MemberSortOrder.INIT_INDEX) * 2; case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: return sortOrder.getCategoryIndex(MemberSortOrder.METHOD_INDEX) * 2; case ASTNode.METHOD_DECLARATION: if (Modifier.isStatic(modifiers)) { return sortOrder.getCategoryIndex(MemberSortOrder.STATIC_METHODS_INDEX) * 2; } if (((MethodDeclaration) member).isConstructor()) { return sortOrder.getCategoryIndex(MemberSortOrder.CONSTRUCTORS_INDEX) * 2; } return sortOrder.getCategoryIndex(MemberSortOrder.METHOD_INDEX) * 2; default: return 100; } }
public static RefactoringStatus perform(BodyDeclaration declaration, Selection selection) { LocalTypeAnalyzer analyzer = new LocalTypeAnalyzer(selection); declaration.accept(analyzer); RefactoringStatus result = new RefactoringStatus(); analyzer.check(result); return result; }
private boolean matchesLocationInEnclosingBodyDecl(BodyDeclaration originalEnclosingBodyDeclaration, BodyDeclaration duplicateEnclosingBodyDeclaration, VariableDeclaration originalReturnNode, VariableDeclaration duplicateReturnNode) { boolean matches = true; ASTNode original = originalReturnNode; ASTNode dupliacte = duplicateReturnNode; // walk up the parent chains to check if the location of the return nodes in their respective parent chains is same do { ASTNode originalParent = original.getParent(); ASTNode duplicateParent = dupliacte.getParent(); StructuralPropertyDescriptor originalLoc = original.getLocationInParent(); StructuralPropertyDescriptor duplicateLoc = dupliacte.getLocationInParent(); if (originalParent != null && duplicateParent != null && originalLoc.getNodeClass().equals(duplicateLoc.getNodeClass()) && originalLoc.getId().equals(duplicateLoc.getId())) { if (originalLoc.isChildListProperty() && duplicateLoc.isChildListProperty()) { int indexOfOriginal = ((List<?>) originalParent.getStructuralProperty(originalLoc)).indexOf(original); int indexOfDuplicate = ((List<?>) duplicateParent.getStructuralProperty(duplicateLoc)).indexOf(dupliacte); if (indexOfOriginal != indexOfDuplicate) { matches = false; break; } } } else { matches = false; break; } original = originalParent; dupliacte = duplicateParent; if ((originalEnclosingBodyDeclaration.equals(original) && !duplicateEnclosingBodyDeclaration.equals(dupliacte)) || (!originalEnclosingBodyDeclaration.equals(original) && duplicateEnclosingBodyDeclaration.equals(dupliacte))) { matches = false; break; } } while (!originalEnclosingBodyDeclaration.equals(original) && !duplicateEnclosingBodyDeclaration.equals(dupliacte)); return matches; }
public BodyDeclaration getEnclosingBodyDeclaration() { ASTNode node = getFirstSelectedNode(); if (node == null) { return null; } return (BodyDeclaration) ASTNodes.getParent(node, BodyDeclaration.class); }
public static ASTNode getEnclosingNode(ASTNode firstSelectedNode) { ASTNode enclosingNode; if (firstSelectedNode instanceof MethodReference) { enclosingNode = firstSelectedNode; } else { enclosingNode = ASTResolving.findEnclosingLambdaExpression(firstSelectedNode); if (enclosingNode != null) { enclosingNode = ((LambdaExpression) enclosingNode).getBody(); } else { enclosingNode = ASTNodes.getParent(firstSelectedNode, BodyDeclaration.class); } } return enclosingNode; }
@Override protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(fNode); ASTNode typeDecl = astRoot.findDeclaringNode(fSenderBinding); ASTNode newTypeDecl = null; if (typeDecl != null) { newTypeDecl = typeDecl; } else { astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null); newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey()); } createImportRewrite(astRoot); if (newTypeDecl != null) { ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl); List<BodyDeclaration> members = ASTNodes.getBodyDeclarations(newTypeDecl); int insertIndex = members.size(); ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property); isGetter = true; MethodDeclaration newStub = getStub(rewrite, newTypeDecl); listRewriter.insertAt(newStub, insertIndex, null); isGetter = false; newStub = getStub(rewrite, newTypeDecl); listRewriter.insertAt(newStub, insertIndex + 1, null); return rewrite; } return null; }
private ASTRewrite doAddField(CompilationUnit astRoot) { SimpleName node= fOriginalNode; boolean isInDifferentCU= false; ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding); if (newTypeDecl == null) { astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null); newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey()); isInDifferentCU= true; } ImportRewrite imports= createImportRewrite(astRoot); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports); if (newTypeDecl != null) { AST ast= newTypeDecl.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(node.getIdentifier())); Type type= evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding, TypeLocation.FIELD); FieldDeclaration newDecl= ast.newFieldDeclaration(fragment); newDecl.setType(type); newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl))); if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) { fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0)); } ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl); List<BodyDeclaration> decls= ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property); int maxOffset= isInDifferentCU ? -1 : node.getStartPosition(); int insertIndex= findFieldInsertIndex(decls, newDecl, maxOffset); ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property); listRewriter.insertAt(newDecl, insertIndex, null); return rewrite; } return null; }
private int findFieldInsertIndex(List<BodyDeclaration> decls, FieldDeclaration newDecl, int maxOffset) { if (maxOffset != -1) { for (int i= decls.size() - 1; i >= 0; i--) { BodyDeclaration curr= decls.get(i); if (maxOffset > curr.getStartPosition() + curr.getLength()) { return BodyDeclarationRewrite.getInsertionIndex(newDecl, decls.subList(0, i + 1)); } } return 0; } return BodyDeclarationRewrite.getInsertionIndex(newDecl, decls); }
public static void getUnusedAndUndocumentedParameterOrExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) { ICompilationUnit cu= context.getCompilationUnit(); IJavaProject project= cu.getJavaProject(); if (!JavaCore.ENABLED.equals(project.getOption(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, true))) { return; } int problemId= problem.getProblemId(); boolean isUnusedTypeParam= problemId == IProblem.UnusedTypeParameter; boolean isUnusedParam= problemId == IProblem.ArgumentIsNeverUsed || isUnusedTypeParam; String key= isUnusedParam ? JavaCore.COMPILER_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE : JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_INCLUDE_DOC_COMMENT_REFERENCE; if (!JavaCore.ENABLED.equals(project.getOption(key, true))) { return; } ASTNode node= problem.getCoveringNode(context.getASTRoot()); if (node == null) { return; } BodyDeclaration bodyDecl= ASTResolving.findParentBodyDeclaration(node); if (bodyDecl == null || ASTResolving.getParentMethodOrTypeBinding(bodyDecl) == null) { return; } String label; if (isUnusedTypeParam) { label= CorrectionMessages.JavadocTagsSubProcessor_document_type_parameter_description; } else if (isUnusedParam) { label= CorrectionMessages.JavadocTagsSubProcessor_document_parameter_description; } else { node= ASTNodes.getNormalizedNode(node); label= CorrectionMessages.JavadocTagsSubProcessor_document_exception_description; } ASTRewriteCorrectionProposal proposal= new AddMissingJavadocTagProposal(label, context.getCompilationUnit(), bodyDecl, node, IProposalRelevance.DOCUMENT_UNUSED_ITEM); proposals.add(proposal); }
@Override protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fInvocationNode); ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding); ASTNode newTypeDecl= null; if (typeDecl != null) { newTypeDecl= typeDecl; } else { astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null); newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey()); } createImportRewrite(astRoot); if (newTypeDecl instanceof AnnotationTypeDeclaration) { AnnotationTypeDeclaration newAnnotationTypeDecl= (AnnotationTypeDeclaration) newTypeDecl; ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST()); AnnotationTypeMemberDeclaration newStub= getStub(rewrite, newAnnotationTypeDecl); List<BodyDeclaration> members= newAnnotationTypeDecl.bodyDeclarations(); int insertIndex= members.size(); ListRewrite listRewriter= rewrite.getListRewrite(newAnnotationTypeDecl, AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY); listRewriter.insertAt(newStub, insertIndex, null); return rewrite; } return null; }
private int evaluateModifiers(AnnotationTypeDeclaration targetTypeDecl) { List<BodyDeclaration> methodDecls= targetTypeDecl.bodyDeclarations(); for (int i= 0; i < methodDecls.size(); i++) { Object curr= methodDecls.get(i); if (curr instanceof AnnotationTypeMemberDeclaration) { return ((AnnotationTypeMemberDeclaration) curr).getModifiers(); } } return 0; }
@Override protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode); ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding); ASTNode newTypeDecl= null; boolean isInDifferentCU; if (typeDecl != null) { isInDifferentCU= false; newTypeDecl= typeDecl; } else { isInDifferentCU= true; astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null); newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey()); } createImportRewrite(astRoot); if (newTypeDecl != null) { ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST()); MethodDeclaration newStub= getStub(rewrite, newTypeDecl); ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl); List<BodyDeclaration> members= ASTNodes.getBodyDeclarations(newTypeDecl); int insertIndex; if (isConstructor()) { insertIndex= findConstructorInsertIndex(members); } else if (!isInDifferentCU) { insertIndex= findMethodInsertIndex(members, fNode.getStartPosition()); } else { insertIndex= members.size(); } ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property); listRewriter.insertAt(newStub, insertIndex, null); return rewrite; } return null; }