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"; }
/** * Returns the type binding of the node's type context or null if the node is inside * an annotation, type parameter, super type declaration, or Javadoc of a top level type. * The result of this method is equal to the result of {@link #getBindingOfParentType(ASTNode)} for nodes in the type's body. * * @param node an AST node * @return the type binding of the node's parent type context, or <code>null</code> */ public static ITypeBinding getBindingOfParentTypeContext(ASTNode node) { StructuralPropertyDescriptor lastLocation= null; while (node != null) { if (node instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration decl= (AbstractTypeDeclaration) node; if (lastLocation == decl.getBodyDeclarationsProperty() || lastLocation == decl.getJavadocProperty()) { return decl.resolveBinding(); } else if (decl instanceof EnumDeclaration && lastLocation == EnumDeclaration.ENUM_CONSTANTS_PROPERTY) { return decl.resolveBinding(); } } else if (node instanceof AnonymousClassDeclaration) { return ((AnonymousClassDeclaration) node).resolveBinding(); } lastLocation= node.getLocationInParent(); node= node.getParent(); } return null; }
/** * Returns the receiver's type binding of the given method invocation. * * @param invocation method invocation to resolve type of * @return the type binding of the receiver */ public static ITypeBinding getReceiverTypeBinding(MethodInvocation invocation) { ITypeBinding result= null; Expression exp= invocation.getExpression(); if(exp != null) { return exp.resolveTypeBinding(); } else { AbstractTypeDeclaration type= (AbstractTypeDeclaration)getParent(invocation, AbstractTypeDeclaration.class); if (type != null) { return type.resolveBinding(); } } return result; }
public static IBinding getEnclosingDeclaration(ASTNode node) { while(node != null) { if (node instanceof AbstractTypeDeclaration) { return ((AbstractTypeDeclaration)node).resolveBinding(); } else if (node instanceof AnonymousClassDeclaration) { return ((AnonymousClassDeclaration)node).resolveBinding(); } else if (node instanceof MethodDeclaration) { return ((MethodDeclaration)node).resolveBinding(); } else if (node instanceof FieldDeclaration) { List<?> fragments= ((FieldDeclaration)node).fragments(); if (fragments.size() > 0) { return ((VariableDeclarationFragment)fragments.get(0)).resolveBinding(); } } else if (node instanceof VariableDeclarationFragment) { IVariableBinding variableBinding= ((VariableDeclarationFragment)node).resolveBinding(); if (variableBinding.getDeclaringMethod() != null || variableBinding.getDeclaringClass() != null) { return variableBinding; // workaround for incomplete wiring of DOM bindings: keep searching when variableBinding is unparented } } node= node.getParent(); } 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 declaration node for the originally selected node. * * @param name * the name of the node * * @return the declaration node */ private static ASTNode getDeclarationNode(SimpleName name) { ASTNode parent = name.getParent(); if (!(parent instanceof AbstractTypeDeclaration)) { parent = parent.getParent(); if (parent instanceof ParameterizedType || parent instanceof Type) { parent = parent.getParent(); } if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; parent = creation.getAnonymousClassDeclaration(); } } return parent; }
private static boolean isTypeBindingNull(ASTNode typeNode) { if (typeNode instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration abstractTypeDeclaration= (AbstractTypeDeclaration) typeNode; if (abstractTypeDeclaration.resolveBinding() == null) { return true; } return false; } else if (typeNode instanceof AnonymousClassDeclaration) { AnonymousClassDeclaration anonymousClassDeclaration= (AnonymousClassDeclaration) typeNode; if (anonymousClassDeclaration.resolveBinding() == null) { return true; } return false; } else if (typeNode instanceof EnumConstantDeclaration) { return false; } else { return true; } }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) { continue; } if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) { rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup); } else if (node instanceof AnonymousClassDeclaration) { rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) { rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } } } else { Assert.isTrue(false); } addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, "\n" /* StubUtility.getLineDelimiterUsed(fUnit) */); if (comment != null && comment.length() > 0 && !"/**\n *\n */\n".equals(comment)) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) { return; } positionGroups.setEndPosition(rewrite.track(fragment)); }
public static List<Match> perform(ASTNode start, ASTNode[] snippet) { Assert.isTrue(start instanceof AbstractTypeDeclaration || start instanceof AnonymousClassDeclaration); SnippetFinder finder = new SnippetFinder(snippet); start.accept(finder); for (Iterator<Match> iter = finder.fResult.iterator(); iter.hasNext();) { Match match = iter.next(); ASTNode[] nodes = match.getNodes(); // doesn't match if the candidate is the left hand side of an // assignment and the snippet consists of a single node. // Otherwise y= i; i= z; results in y= e(); e()= z; if (nodes.length == 1 && isLeftHandSideOfAssignment(nodes[0])) { iter.remove(); } } return finder.fResult; }
@Override protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= fContext.getASTRoot(); AST ast= astRoot.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); AbstractTypeDeclaration decl= findTypeDeclaration(astRoot.types(), fOldName); if (decl != null) { ASTNode[] sameNodes= LinkedNodeFinder.findByNode(astRoot, decl.getName()); for (int i= 0; i < sameNodes.length; i++) { rewrite.replace(sameNodes[i], ast.newSimpleName(fNewName), null); } } return rewrite; }
/** * Returns the type binding of the node's type context or null if the node is inside an * annotation, type parameter, super type declaration, or Javadoc of a top level type. The result * of this method is equal to the result of {@link #getBindingOfParentType(ASTNode)} for nodes in * the type's body. * * @param node an AST node * @return the type binding of the node's parent type context, or <code>null</code> */ public static ITypeBinding getBindingOfParentTypeContext(ASTNode node) { StructuralPropertyDescriptor lastLocation = null; while (node != null) { if (node instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration decl = (AbstractTypeDeclaration) node; if (lastLocation == decl.getBodyDeclarationsProperty() || lastLocation == decl.getJavadocProperty()) { return decl.resolveBinding(); } else if (decl instanceof EnumDeclaration && lastLocation == EnumDeclaration.ENUM_CONSTANTS_PROPERTY) { return decl.resolveBinding(); } } else if (node instanceof AnonymousClassDeclaration) { return ((AnonymousClassDeclaration) node).resolveBinding(); } lastLocation = node.getLocationInParent(); node = node.getParent(); } return null; }
private boolean addOuterDeclarationsForLocalType( ITypeBinding localBinding, int flags, IBindingRequestor requestor) { ASTNode node = fRoot.findDeclaringNode(localBinding); if (node == null) { return false; } if (node instanceof AbstractTypeDeclaration || node instanceof AnonymousClassDeclaration) { if (addLocalDeclarations(node.getParent(), flags, requestor)) return true; ITypeBinding parentTypeBinding = Bindings.getBindingOfParentType(node.getParent()); if (parentTypeBinding != null) { if (addTypeDeclarations(parentTypeBinding, flags, requestor)) return true; } } return false; }
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 declaration node for the originally selected node. * * @param name the name of the node * @return the declaration node */ private static ASTNode getDeclarationNode(SimpleName name) { ASTNode parent = name.getParent(); if (!(parent instanceof AbstractTypeDeclaration)) { parent = parent.getParent(); if (parent instanceof ParameterizedType || parent instanceof Type) parent = parent.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; parent = creation.getAnonymousClassDeclaration(); } } return parent; }
public static ASTNode getSelectedTypeNode(CompilationUnit root, IProblemLocation problem) { ASTNode selectedNode = problem.getCoveringNode(root); if (selectedNode == null) return null; if (selectedNode.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION) { // bug 200016 selectedNode = selectedNode.getParent(); } if (selectedNode.getLocationInParent() == EnumConstantDeclaration.NAME_PROPERTY) { selectedNode = selectedNode.getParent(); } if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent() instanceof AbstractTypeDeclaration) { return selectedNode.getParent(); } else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) { return ((ClassInstanceCreation) selectedNode).getAnonymousClassDeclaration(); } else if (selectedNode.getNodeType() == ASTNode.ENUM_CONSTANT_DECLARATION) { EnumConstantDeclaration enumConst = (EnumConstantDeclaration) selectedNode; if (enumConst.getAnonymousClassDeclaration() != null) return enumConst.getAnonymousClassDeclaration(); return enumConst; } else { return null; } }
private static boolean isTypeBindingNull(ASTNode typeNode) { if (typeNode instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration abstractTypeDeclaration = (AbstractTypeDeclaration) typeNode; if (abstractTypeDeclaration.resolveBinding() == null) return true; return false; } else if (typeNode instanceof AnonymousClassDeclaration) { AnonymousClassDeclaration anonymousClassDeclaration = (AnonymousClassDeclaration) typeNode; if (anonymousClassDeclaration.resolveBinding() == null) return true; return false; } else if (typeNode instanceof EnumConstantDeclaration) { return false; } else { return true; } }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration .modifiers() .addAll( ASTNodeFactory.newModifiers( ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) continue; if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) rewrite .getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()) .insertAt(declaration, 0, editGroup); else if (node instanceof AnonymousClassDeclaration) rewrite .getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) rewrite .getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); } } else Assert.isTrue(false); addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment( fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit)); if (comment != null && comment.length() > 0) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) return; positionGroups.setEndPosition(rewrite.track(fragment)); }
private void addNewConstructorToSubclass( AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) { AST ast = subclass.getAST(); MethodDeclaration newConstructor = ast.newMethodDeclaration(); newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier())); newConstructor.setConstructor(true); newConstructor.setJavadoc(null); newConstructor .modifiers() .addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass))); newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); Block body = ast.newBlock(); newConstructor.setBody(body); SuperConstructorInvocation superCall = ast.newSuperConstructorInvocation(); addArgumentsToNewSuperConstructorCall(superCall, cuRewrite); body.statements().add(superCall); String msg = RefactoringCoreMessages.ChangeSignatureRefactoring_add_constructor; TextEditGroup description = cuRewrite.createGroupDescription(msg); cuRewrite .getASTRewrite() .getListRewrite(subclass, subclass.getBodyDeclarationsProperty()) .insertFirst(newConstructor, description); // TODO use AbstractTypeDeclaration }
protected String getFullTypeName() { ASTNode node = getNode(); while (true) { node = node.getParent(); if (node instanceof AbstractTypeDeclaration) { String typeName = ((AbstractTypeDeclaration) node).getName().getIdentifier(); if (getNode() instanceof LambdaExpression) { return Messages.format( RefactoringCoreMessages.ChangeSignatureRefactoring_lambda_expression, typeName); } return typeName; } else if (node instanceof ClassInstanceCreation) { ClassInstanceCreation cic = (ClassInstanceCreation) node; return Messages.format( RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(cic.getType()))); } else if (node instanceof EnumConstantDeclaration) { EnumDeclaration ed = (EnumDeclaration) node.getParent(); return Messages.format( RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(ed.getName()))); } } }
@Override public boolean visit(AbstractTypeDeclaration node) { String name = node.getName().getIdentifier(); if (name.equals(getNewElementName())) { fStatus.addError( Messages.format( RefactoringCoreMessages .RenameTypeParameterRefactoring_type_parameter_inner_class_clash, new String[] {name}), JavaStatusContext.create( fTypeParameter.getDeclaringMember().getCompilationUnit(), SourceRangeFactory.create(node))); return true; } return true; }
private void initAST(IProgressMonitor pm) { if (fCompilationUnitNode == null) { fCompilationUnitNode = RefactoringASTParser.parseWithASTProvider(fCu, true, pm); } if (fAnonymousInnerClassNode == null) { fAnonymousInnerClassNode = getAnonymousInnerClass( NodeFinder.perform(fCompilationUnitNode, fSelectionStart, fSelectionLength)); } if (fAnonymousInnerClassNode != null) { final AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class); if (declaration instanceof TypeDeclaration) { final AbstractTypeDeclaration[] nested = ((TypeDeclaration) declaration).getTypes(); fClassNamesUsed = new HashSet<String>(nested.length); for (int index = 0; index < nested.length; index++) fClassNamesUsed.add(nested[index].getName().getIdentifier()); } else fClassNamesUsed = Collections.emptySet(); } }
private String[] getNamesOfFieldsInDeclaringType() { final AbstractTypeDeclaration type = getEnclosingType(); if (type instanceof TypeDeclaration) { FieldDeclaration[] fields = ((TypeDeclaration) type).getFields(); List<String> result = new ArrayList<String>(fields.length); for (int i = 0; i < fields.length; i++) { for (Iterator<VariableDeclarationFragment> iter = fields[i].fragments().iterator(); iter.hasNext(); ) { VariableDeclarationFragment field = iter.next(); result.add(field.getName().getIdentifier()); } } return result.toArray(new String[result.size()]); } return new String[] {}; }
public static Match[] perform(ASTNode start, ASTNode[] snippet) { Assert.isTrue( start instanceof AbstractTypeDeclaration || start instanceof AnonymousClassDeclaration); SnippetFinder finder = new SnippetFinder(snippet); start.accept(finder); for (Iterator<Match> iter = finder.fResult.iterator(); iter.hasNext(); ) { Match match = iter.next(); ASTNode[] nodes = match.getNodes(); // doesn't match if the candidate is the left hand side of an // assignment and the snippet consists of a single node. // Otherwise y= i; i= z; results in y= e(); e()= z; if (nodes.length == 1 && isLeftHandSideOfAssignment(nodes[0])) { iter.remove(); } } return finder.fResult.toArray(new Match[finder.fResult.size()]); }
private MethodDeclaration createNewMethod( ASTNode[] selectedNodes, String lineDelimiter, TextEditGroup substitute) throws CoreException { MethodDeclaration result = createNewMethodDeclaration(); result.setBody(createMethodBody(selectedNodes, substitute, result.getModifiers())); if (fGenerateJavadoc) { AbstractTypeDeclaration enclosingType = (AbstractTypeDeclaration) ASTNodes.getParent( fAnalyzer.getEnclosingBodyDeclaration(), AbstractTypeDeclaration.class); String string = CodeGeneration.getMethodComment( fCUnit, enclosingType.getName().getIdentifier(), result, null, lineDelimiter); if (string != null) { Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC); result.setJavadoc(javadoc); } } return result; }
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; }
/** * Perform the AST rewriting necessary on the given <code>CompilationUnit</code> to create the * factory method. The method will reside on the type identified by <code>fFactoryOwningClass * </code>. * * @param unitRewriter the ASTRewrite to be used * @param unit the <code>CompilationUnit</code> where factory method will be created * @param gd the <code>GroupDescription</code> to associate with the changes made * @throws CoreException if an exception occurs while accessing its corresponding resource */ private void createFactoryChange(ASTRewrite unitRewriter, CompilationUnit unit, TextEditGroup gd) throws CoreException { // ================================================================================ // First add the factory itself (method, class, and interface as needed/directed by user) AST ast = unit.getAST(); fFactoryMethod = createFactoryMethod(ast, fCtorBinding, unitRewriter); AbstractTypeDeclaration factoryOwner = (AbstractTypeDeclaration) unit.findDeclaringNode(fFactoryOwningClass.resolveBinding().getKey()); fImportRewriter.addImport(fCtorOwningClass.resolveBinding()); int idx = ASTNodes.getInsertionIndex(fFactoryMethod, factoryOwner.bodyDeclarations()); if (idx < 0) idx = 0; // Guard against bug in getInsertionIndex() unitRewriter .getListRewrite(factoryOwner, factoryOwner.getBodyDeclarationsProperty()) .insertAt(fFactoryMethod, idx, gd); }
private void copyTypeToDestination( IType type, CompilationUnitRewrite targetRewriter, CompilationUnit sourceCuNode, CompilationUnit targetCuNode) throws JavaModelException { AbstractTypeDeclaration newType = (AbstractTypeDeclaration) targetRewriter .getASTRewrite() .createStringPlaceholder(getUnindentedSource(type), ASTNode.TYPE_DECLARATION); IType enclosingType = getEnclosingType(getJavaElementDestination()); if (enclosingType != null) { copyMemberToDestination(type, targetRewriter, sourceCuNode, targetCuNode, newType); } else { targetRewriter .getASTRewrite() .getListRewrite(targetCuNode, CompilationUnit.TYPES_PROPERTY) .insertLast(newType, null); } }
private boolean considerBinding(IBinding binding, ASTNode node) { if (!(binding instanceof IVariableBinding)) return false; boolean result = Bindings.equals(fFieldBinding, ((IVariableBinding) binding).getVariableDeclaration()); if (!result || fEncapsulateDeclaringClass) return result; if (binding instanceof IVariableBinding) { AbstractTypeDeclaration type = (AbstractTypeDeclaration) ASTNodes.getParent(node, AbstractTypeDeclaration.class); if (type != null) { ITypeBinding declaringType = type.resolveBinding(); return !Bindings.equals(fDeclaringClassBinding, declaringType); } } return true; }
private void checkInHierarchy( RefactoringStatus status, boolean usingLocalGetter, boolean usingLocalSetter) { AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class); ITypeBinding type = declaration.resolveBinding(); if (type != null) { ITypeBinding fieldType = fFieldDeclaration.resolveBinding().getType(); checkMethodInHierarchy( type, fGetterName, fieldType, new ITypeBinding[0], status, usingLocalGetter); checkMethodInHierarchy( type, fSetterName, fFieldDeclaration.getAST().resolveWellKnownType("void"), // $NON-NLS-1$ new ITypeBinding[] {fieldType}, status, usingLocalSetter); } }
public boolean resolveInClassInitializer() { if (fInClassInitializerRequested) return fInClassInitializer; fInClassInitializerRequested = true; resolveSelectedNodes(); ASTNode node = getStartNode(); if (node == null) { fInClassInitializer = true; } else { while (node != null) { int nodeType = node.getNodeType(); if (node instanceof AbstractTypeDeclaration) { fInClassInitializer = false; break; } else if (nodeType == ASTNode.ANONYMOUS_CLASS_DECLARATION) { fInClassInitializer = false; break; } else if (nodeType == ASTNode.INITIALIZER) { fInClassInitializer = true; break; } node = node.getParent(); } } return fInClassInitializer; }
@Override protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot = fContext.getASTRoot(); AST ast = astRoot.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); AbstractTypeDeclaration decl = findTypeDeclaration(astRoot.types(), fOldName); if (decl != null) { ASTNode[] sameNodes = LinkedNodeFinder.findByNode(astRoot, decl.getName()); for (int i = 0; i < sameNodes.length; i++) { rewrite.replace(sameNodes[i], ast.newSimpleName(fNewName), null); } } return rewrite; }
private static int getNodeStartPosition(final ASTNode node) { if (node instanceof MethodDeclaration) { MethodDeclaration decl = (MethodDeclaration) node; return decl.isConstructor() ? decl.getName().getStartPosition() : decl.getReturnType2().getStartPosition(); } else if (node instanceof FieldDeclaration) { return ((FieldDeclaration) node).getType().getStartPosition(); } else if (node instanceof AbstractTypeDeclaration) { return ((AbstractTypeDeclaration) node).getName().getStartPosition(); } else if (node instanceof AnnotationTypeMemberDeclaration) { return ((AnnotationTypeMemberDeclaration) node).getName().getStartPosition(); } else if (node instanceof EnumConstantDeclaration) { return ((EnumConstantDeclaration) node).getName().getStartPosition(); } else if (node instanceof PackageDeclaration) { return ((PackageDeclaration) node).getName().getStartPosition(); } /* TODO: Initializer */ return node.getStartPosition(); }
public boolean resolveInClassInitializer() { if (fInClassInitializerRequested) return fInClassInitializer; fInClassInitializerRequested= true; resolveSelectedNodes(); ASTNode node= getStartNode(); if (node == null) { fInClassInitializer= true; } else { while (node != null) { int nodeType= node.getNodeType(); if (node instanceof AbstractTypeDeclaration) { fInClassInitializer= false; break; } else if (nodeType == ASTNode.ANONYMOUS_CLASS_DECLARATION) { fInClassInitializer= false; break; } else if (nodeType == ASTNode.INITIALIZER) { fInClassInitializer= true; break; } node= node.getParent(); } } return fInClassInitializer; }
private void addEnclosingInstanceDeclaration(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException { Assert.isNotNull(declaration); Assert.isNotNull(rewrite); final AST ast= declaration.getAST(); final VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(fEnclosingInstanceFieldName)); final FieldDeclaration newField= ast.newFieldDeclaration(fragment); newField.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getEnclosingInstanceAccessModifiers())); newField.setType(createEnclosingType(ast)); final String comment= CodeGeneration.getFieldComment(fType.getCompilationUnit(), declaration.getName().getIdentifier(), fEnclosingInstanceFieldName, StubUtility.getLineDelimiterUsed(fType.getJavaProject())); if (comment != null && comment.length() > 0) { final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); newField.setJavadoc(doc); } rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(newField, null); }
/** * Creates a new add unimplemented constructors operation. * * @param astRoot the compilation unit AST node * @param type the type to add the methods to * @param constructorsToImplement the method binding keys to implement * @param insertPos the insertion point, or <code>-1</code> * @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise */ public AddUnimplementedConstructorsOperation(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] constructorsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) { if (astRoot == null || !(astRoot.getJavaElement() instanceof ICompilationUnit)) { throw new IllegalArgumentException("AST must not be null and has to be created from a ICompilationUnit"); //$NON-NLS-1$ } if (type == null) { throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$ } ASTNode node= astRoot.findDeclaringNode(type); if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) { throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$ } fType= type; fInsertPos= insertPos; fASTRoot= astRoot; fConstructorsToImplement= constructorsToImplement; fSave= save; fApply= apply; fImports= imports; fCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaProject()); fVisibility= Modifier.PUBLIC; fOmitSuper= false; }
private String getLabel(ASTNode node) { if (node instanceof AbstractTypeDeclaration) { return ((AbstractTypeDeclaration)node).getName().getIdentifier(); } else if (node instanceof AnonymousClassDeclaration) { if (node.getLocationInParent() == ClassInstanceCreation.ANONYMOUS_CLASS_DECLARATION_PROPERTY) { ClassInstanceCreation creation= (ClassInstanceCreation)node.getParent(); return Messages.format( RefactoringMessages.ExtractMethodInputPage_anonymous_type_label, BasicElementLabels.getJavaElementName(ASTNodes.asString(creation.getType()))); } else if (node.getLocationInParent() == EnumConstantDeclaration.ANONYMOUS_CLASS_DECLARATION_PROPERTY) { EnumConstantDeclaration decl= (EnumConstantDeclaration)node.getParent(); return decl.getName().getIdentifier(); } } return "UNKNOWN"; //$NON-NLS-1$ }
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; }
private void modifyAccessToFieldsFromEnclosingInstance(CompilationUnitRewrite targetRewrite, SimpleName[] simpleNames, AbstractTypeDeclaration declaration) { IBinding binding= null; SimpleName simpleName= null; IVariableBinding variable= null; for (int index= 0; index < simpleNames.length; index++) { simpleName= simpleNames[index]; binding= simpleName.resolveBinding(); if (binding != null && binding instanceof IVariableBinding && !(simpleName.getParent() instanceof FieldAccess)) { variable= (IVariableBinding) binding; final FieldAccess access= simpleName.getAST().newFieldAccess(); access.setExpression(createAccessExpressionToEnclosingInstanceFieldText(simpleName, variable, declaration)); access.setName(simpleName.getAST().newSimpleName(simpleName.getIdentifier())); targetRewrite.getASTRewrite().replace(simpleName, access, null); targetRewrite.getImportRemover().registerRemovedNode(simpleName); } } }
private void modifyAccessToMethodsFromEnclosingInstance(CompilationUnitRewrite targetRewrite, MethodInvocation[] methodInvocations, AbstractTypeDeclaration declaration) { IMethodBinding binding= null; MethodInvocation invocation= null; for (int index= 0; index < methodInvocations.length; index++) { invocation= methodInvocations[index]; binding= invocation.resolveMethodBinding(); if (binding != null) { final Expression target= invocation.getExpression(); if (target == null) { final Expression expression= createAccessExpressionToEnclosingInstanceFieldText(invocation, binding, declaration); targetRewrite.getASTRewrite().set(invocation, MethodInvocation.EXPRESSION_PROPERTY, expression, null); } else { if (!(invocation.getExpression() instanceof ThisExpression) || !(((ThisExpression) invocation.getExpression()).getQualifier() != null)) continue; targetRewrite.getASTRewrite().replace(target, createAccessExpressionToEnclosingInstanceFieldText(invocation, binding, declaration), null); targetRewrite.getImportRemover().registerRemovedNode(target); } } } }
/** * Creates a new add unimplemented methods operation. * * @param astRoot the compilation unit AST node * @param type the type to add the methods to * @param methodsToImplement the method bindings to implement or <code>null</code> to implement all unimplemented methods * @param insertPos the insertion point, or <code>-1</code> * @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise */ public AddUnimplementedMethodsOperation(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] methodsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) { if (astRoot == null || !(astRoot.getJavaElement() instanceof ICompilationUnit)) { throw new IllegalArgumentException("AST must not be null and has to be created from a ICompilationUnit"); //$NON-NLS-1$ } if (type == null) { throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$ } ASTNode node= astRoot.findDeclaringNode(type); if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) { throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$ } fType= type; fInsertPos= insertPos; fASTRoot= astRoot; fMethodsToImplement= methodsToImplement; fSave= save; fApply= apply; fImports= imports; fDoCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaProject()); }