private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) { AST ast= rewrite.getAST(); ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite); if (fCastType != null) { return importRewrite.addImport(fCastType, ast,context, TypeLocation.CAST); } ASTNode node= fNodeToCast; ASTNode parent= node.getParent(); if (parent instanceof CastExpression) { node= parent; parent= parent.getParent(); } while (parent instanceof ParenthesizedExpression) { node= parent; parent= parent.getParent(); } if (parent instanceof MethodInvocation) { MethodInvocation invocation= (MethodInvocation) node.getParent(); if (invocation.getExpression() == node) { IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node); ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext); if (bindings.length > 0) { ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding()); Type newTypeNode= importRewrite.addImport(first, ast, context, TypeLocation.CAST); return newTypeNode; } } } Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ return newCastType; }
private static void createTypeParameters( ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) { ITypeBinding[] typeParams = binding.getTypeParameters(); List<TypeParameter> typeParameters = decl.typeParameters(); for (int i = 0; i < typeParams.length; i++) { ITypeBinding curr = typeParams[i]; TypeParameter newTypeParam = ast.newTypeParameter(); newTypeParam.setName(ast.newSimpleName(curr.getName())); ITypeBinding[] typeBounds = curr.getTypeBounds(); if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) { // $NON-NLS-1$ List<Type> newTypeBounds = newTypeParam.typeBounds(); for (int k = 0; k < typeBounds.length; k++) { newTypeBounds.add(imports.addImport(typeBounds[k], ast, context)); } } typeParameters.add(newTypeParam); } }
private static Type newType(LambdaExpression lambdaExpression, VariableDeclarationFragment declaration, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { IMethodBinding method= lambdaExpression.resolveMethodBinding(); if (method != null) { ITypeBinding[] parameterTypes= method.getParameterTypes(); int index= lambdaExpression.parameters().indexOf(declaration); ITypeBinding typeBinding= parameterTypes[index]; if (importRewrite != null) { return importRewrite.addImport(typeBinding, ast, context); } else { String qualifiedName= typeBinding.getQualifiedName(); if (qualifiedName.length() > 0) { return newType(ast, qualifiedName); } } } // fall-back return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ }
/** * Returns the new type node representing the return type of <code>lambdaExpression</code> * including the extra dimensions. * * @param lambdaExpression the lambda expression * @param ast the AST to create the return type with * @param importRewrite the import rewrite to use, or <code>null</code> * @param context the import rewrite context, or <code>null</code> * @return a new type node created with the given AST representing the return type of * <code>lambdaExpression</code> * * @since 3.10 */ public static Type newReturnType(LambdaExpression lambdaExpression, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { IMethodBinding method= lambdaExpression.resolveMethodBinding(); if (method != null) { ITypeBinding returnTypeBinding= method.getReturnType(); if (importRewrite != null) { return importRewrite.addImport(returnTypeBinding, ast); } else { String qualifiedName= returnTypeBinding.getQualifiedName(); if (qualifiedName.length() > 0) { return newType(ast, qualifiedName); } } } // fall-back return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ }
/** * Create a Type suitable as the creationType in a ClassInstanceCreation expression. * @param ast The AST to create the nodes for. * @param typeBinding binding representing the given class type * @param importRewrite the import rewrite to use * @param importContext the import context used to determine which (null) annotations to consider * @return a Type suitable as the creationType in a ClassInstanceCreation expression. */ public static Type newCreationType(AST ast, ITypeBinding typeBinding, ImportRewrite importRewrite, ImportRewriteContext importContext) { if (typeBinding.isParameterizedType()) { Type baseType= newCreationType(ast, typeBinding.getTypeDeclaration(), importRewrite, importContext); IAnnotationBinding[] typeAnnotations= importContext.removeRedundantTypeAnnotations(typeBinding.getTypeAnnotations(), TypeLocation.NEW, typeBinding); for (IAnnotationBinding typeAnnotation : typeAnnotations) { ((AnnotatableType)baseType).annotations().add(importRewrite.addAnnotation(typeAnnotation, ast, importContext)); } ParameterizedType parameterizedType= ast.newParameterizedType(baseType); for (ITypeBinding typeArgument : typeBinding.getTypeArguments()) { typeArgument= StubUtility2.replaceWildcardsAndCaptures(typeArgument); parameterizedType.typeArguments().add(importRewrite.addImport(typeArgument, ast, importContext, TypeLocation.TYPE_ARGUMENT)); } return parameterizedType; } else { return importRewrite.addImport(typeBinding, ast, importContext, TypeLocation.NEW); } }
private static void createTypeParameters(ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) { ITypeBinding[] typeParams= binding.getTypeParameters(); List<TypeParameter> typeParameters= decl.typeParameters(); for (int i= 0; i < typeParams.length; i++) { ITypeBinding curr= typeParams[i]; TypeParameter newTypeParam= ast.newTypeParameter(); newTypeParam.setName(ast.newSimpleName(curr.getName())); ITypeBinding[] typeBounds= curr.getTypeBounds(); if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$ List<Type> newTypeBounds= newTypeParam.typeBounds(); for (int k= 0; k < typeBounds.length; k++) { newTypeBounds.add(imports.addImport(typeBounds[k], ast, context, TypeLocation.TYPE_BOUND)); } } typeParameters.add(newTypeParam); } }
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); } }
@Override protected ASTRewrite getRewrite() throws CoreException { ASTNode boundNode= fAstRoot.findDeclaringNode(fBinding); ASTNode declNode= null; CompilationUnit newRoot= fAstRoot; if (boundNode != null) { declNode= boundNode; // is same CU } else { newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null); declNode= newRoot.findDeclaringNode(fBinding.getKey()); } ImportRewrite imports= createImportRewrite(newRoot); if (declNode instanceof TypeDeclaration) { AST ast= declNode.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(declNode, imports); Type newInterface= imports.addImport(fNewInterface, ast, importRewriteContext, TypeLocation.OTHER); ListRewrite listRewrite= rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY); listRewrite.insertLast(newInterface, null); return rewrite; } return null; }
private Type evaluateVariableType(AST ast, ImportRewrite imports, ImportRewriteContext importRewriteContext, IBinding targetContext, TypeLocation location) { if (fOriginalNode.getParent() instanceof MethodInvocation) { MethodInvocation parent= (MethodInvocation) fOriginalNode.getParent(); if (parent.getExpression() == fOriginalNode) { // _x_.foo() -> guess qualifier type by looking for a type with method 'foo' ITypeBinding[] bindings= ASTResolving.getQualifierGuess(fOriginalNode.getRoot(), parent.getName().getIdentifier(), parent.arguments(), targetContext); if (bindings.length > 0) { return imports.addImport(bindings[0], ast, importRewriteContext, location); } } } ITypeBinding binding= ASTResolving.guessBindingForReference(fOriginalNode); if (binding != null) { if (binding.isWildcardType()) { binding= ASTResolving.normalizeWildcardType(binding, isVariableAssigned(), ast); if (binding == null) { // only null binding applies binding= ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } } return imports.addImport(binding, ast, importRewriteContext, location); } // no binding, find type AST node instead -> ABC a= x-> use 'ABC' as is Type type = ASTResolving.guessTypeForReference(ast, fOriginalNode); if (type != null) { return type; } if (fVariableKind == CONST_FIELD) { return ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$ } return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ }
private Type getNewType(ASTRewrite rewrite) { AST ast= rewrite.getAST(); Type newTypeNode= null; ITypeBinding binding= null; if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) { Expression value= ((MemberValuePair) fInvocationNode.getParent()).getValue(); binding= value.resolveTypeBinding(); } else if (fInvocationNode instanceof Expression) { binding= ((Expression) fInvocationNode).resolveTypeBinding(); } if (binding != null) { ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite()); newTypeNode= getImportRewrite().addImport(binding, ast, importRewriteContext); } if (newTypeNode == null) { newTypeNode= ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$ } return newTypeNode; }
@Override protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException { AST ast= rewrite.getAST(); List<Expression> arguments= fArguments; for (int i= 0; i < arguments.size(); i++) { Expression elem= arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); // argument type String argTypeKey= "arg_type_" + i; //$NON-NLS-1$ Type type= evaluateParameterType(ast, elem, argTypeKey, context); param.setType(type); // argument name String argNameKey= "arg_name_" + i; //$NON-NLS-1$ String name= evaluateParameterName(takenNames, elem, type, argNameKey); param.setName(ast.newSimpleName(name)); params.add(param); } }
private static Type newType( LambdaExpression lambdaExpression, VariableDeclarationFragment declaration, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { IMethodBinding method = lambdaExpression.resolveMethodBinding(); if (method != null) { ITypeBinding[] parameterTypes = method.getParameterTypes(); int index = lambdaExpression.parameters().indexOf(declaration); ITypeBinding typeBinding = parameterTypes[index]; if (importRewrite != null) { return importRewrite.addImport(typeBinding, ast, context); } else { String qualifiedName = typeBinding.getQualifiedName(); if (qualifiedName.length() > 0) { return newType(ast, qualifiedName); } } } // fall-back return ast.newSimpleType(ast.newSimpleName("Object")); // $NON-NLS-1$ }
/** * Returns the new type node representing the return type of <code>lambdaExpression</code> * including the extra dimensions. * * @param lambdaExpression the lambda expression * @param ast the AST to create the return type with * @param importRewrite the import rewrite to use, or <code>null</code> * @param context the import rewrite context, or <code>null</code> * @return a new type node created with the given AST representing the return type of <code> * lambdaExpression</code> * @since 3.10 */ public static Type newReturnType( LambdaExpression lambdaExpression, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { IMethodBinding method = lambdaExpression.resolveMethodBinding(); if (method != null) { ITypeBinding returnTypeBinding = method.getReturnType(); if (importRewrite != null) { return importRewrite.addImport(returnTypeBinding, ast); } else { String qualifiedName = returnTypeBinding.getQualifiedName(); if (qualifiedName.length() > 0) { return newType(ast, qualifiedName); } } } // fall-back return ast.newSimpleType(ast.newSimpleName("Object")); // $NON-NLS-1$ }
private String getReceiver( CallContext context, int modifiers, ImportRewriteContext importRewriteContext) { String receiver = context.receiver; ITypeBinding invocationType = ASTNodes.getEnclosingType(context.invocation); ITypeBinding sourceType = fDeclaration.resolveBinding().getDeclaringClass(); if (!context.receiverIsStatic && Modifier.isStatic(modifiers)) { if ("this".equals(receiver) && invocationType != null && Bindings.equals(invocationType, sourceType)) { // $NON-NLS-1$ receiver = null; } else { receiver = context.importer.addImport(sourceType, importRewriteContext); } } return receiver; }
private Expression newDefaultExpression( AST ast, ITypeBinding type, ImportRewriteContext context) { if (type.isPrimitive()) { String name = type.getName(); if ("boolean".equals(name)) { // $NON-NLS-1$ return ast.newBooleanLiteral(false); } else { return ast.newNumberLiteral("0"); // $NON-NLS-1$ } } if (type == ast.resolveWellKnownType("java.lang.String")) { // $NON-NLS-1$ return ast.newStringLiteral(); } if (type.isArray()) { ArrayInitializer initializer = ast.newArrayInitializer(); initializer.expressions().add(newDefaultExpression(ast, type.getElementType(), context)); return initializer; } if (type.isAnnotation()) { MarkerAnnotation annotation = ast.newMarkerAnnotation(); annotation.setTypeName(ast.newName(getImportRewrite().addImport(type, context))); return annotation; } return ast.newNullLiteral(); }
@Override protected ASTRewrite getRewrite() throws CoreException { AST ast = fTypeNode.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); createImportRewrite((CompilationUnit) fTypeNode.getRoot()); CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaProject()); if (!settings.createComments) { settings = null; } ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(fTypeNode, getImportRewrite()); MethodDeclaration newMethodDecl = createNewMethodDeclaration(ast, fSuperConstructor, rewrite, importRewriteContext, settings); rewrite .getListRewrite(fTypeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY) .insertFirst(newMethodDecl, null); addLinkedRanges(rewrite, newMethodDecl); return rewrite; }
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 Type getNewType(ASTRewrite rewrite) { AST ast = rewrite.getAST(); Type newTypeNode = null; ITypeBinding binding = null; if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) { Expression value = ((MemberValuePair) fInvocationNode.getParent()).getValue(); binding = value.resolveTypeBinding(); } else if (fInvocationNode instanceof Expression) { binding = ((Expression) fInvocationNode).resolveTypeBinding(); } if (binding != null) { ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite()); newTypeNode = getImportRewrite().addImport(binding, ast, importRewriteContext); } if (newTypeNode == null) { newTypeNode = ast.newSimpleType(ast.newSimpleName("String")); // $NON-NLS-1$ } addLinkedPosition(rewrite.track(newTypeNode), false, KEY_TYPE); return newTypeNode; }
protected void rewrite(FieldAccess node, ITypeBinding type) { Expression exp= node.getExpression(); if (exp == null) { ImportRewriteContext context= new ContextSensitiveImportRewriteContext(node, fCuRewrite.getImportRewrite()); Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST(), context); fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName()); exp= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result)); fCuRewrite.getASTRewrite().set(node, FieldAccess.EXPRESSION_PROPERTY, exp, fCuRewrite.createGroupDescription(REFERENCE_UPDATE)); fNeedsImport= true; } else if (exp instanceof Name) { rewriteName((Name)exp, type); } else { rewriteExpression(node, exp, type); } fProcessed.add(node.getName()); }
protected void rewrite(MethodInvocation node, ITypeBinding type) { Expression exp= node.getExpression(); if (exp == null) { ImportRewriteContext context= new ContextSensitiveImportRewriteContext(node, fCuRewrite.getImportRewrite()); Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST(), context); fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName()); exp= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result)); fCuRewrite.getASTRewrite().set(node, MethodInvocation.EXPRESSION_PROPERTY, exp, fCuRewrite.createGroupDescription(REFERENCE_UPDATE)); fNeedsImport= true; } else if (exp instanceof Name) { rewriteName((Name)exp, type); } else { rewriteExpression(node, exp, type); } fProcessed.add(node.getName()); }
ContextSensitiveImportRewriteContext createParameterClassAwareContext(final boolean asTopLevelClass, final CompilationUnitRewrite cuRewrite, int position) { ContextSensitiveImportRewriteContext context= new ContextSensitiveImportRewriteContext(cuRewrite.getRoot(), position, cuRewrite.getImportRewrite()) { @Override public int findInContext(String qualifier, String name, int kind) { String parameterClassName= getClassName(); if (kind == ImportRewriteContext.KIND_TYPE && parameterClassName.equals(name)) { String parameterClassQualifier= asTopLevelClass ? getPackage() : getEnclosingType(); if (super.findInContext(qualifier, "", kind) == ImportRewriteContext.RES_NAME_FOUND) { //$NON-NLS-1$ // TODO: should be "*", not " "! if (parameterClassQualifier.equals(qualifier)) { return ImportRewriteContext.RES_NAME_FOUND; } else { return ImportRewriteContext.RES_NAME_CONFLICT; } } } return super.findInContext(qualifier, name, kind); } }; return context; }
private void addMethodStubForAbstractMethod(final IMethod sourceMethod, final CompilationUnit declaringCuNode, final AbstractTypeDeclaration typeToCreateStubIn, final ICompilationUnit newCu, final CompilationUnitRewrite rewriter, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException { final MethodDeclaration methodToCreateStubFor= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode); final AST ast= rewriter.getRoot().getAST(); final MethodDeclaration newMethod= ast.newMethodDeclaration(); newMethod.setBody(createMethodStub(methodToCreateStubFor, ast)); newMethod.setConstructor(false); copyExtraDimensions(methodToCreateStubFor, newMethod); newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiersWithUpdatedVisibility(sourceMethod, JdtFlags.clearFlag(Modifier.NATIVE | Modifier.ABSTRACT, methodToCreateStubFor.getModifiers()), adjustments, new SubProgressMonitor(monitor, 1), false, status))); newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, methodToCreateStubFor.getName()))); final TypeVariableMaplet[] mapping= TypeVariableUtil.composeMappings(TypeVariableUtil.subTypeToSuperType(getDeclaringType(), getDestinationType()), TypeVariableUtil.superTypeToInheritedType(getDestinationType(), ((IType) typeToCreateStubIn.resolveBinding().getJavaElement()))); copyReturnType(rewriter.getASTRewrite(), getDeclaringType().getCompilationUnit(), methodToCreateStubFor, newMethod, mapping); copyParameters(rewriter.getASTRewrite(), getDeclaringType().getCompilationUnit(), methodToCreateStubFor, newMethod, mapping); copyThrownExceptions(methodToCreateStubFor, newMethod); newMethod.setJavadoc(createJavadocForStub(typeToCreateStubIn.getName().getIdentifier(), methodToCreateStubFor, newMethod, newCu, rewriter.getASTRewrite())); ImportRewriteContext context= new ContextSensitiveImportRewriteContext(typeToCreateStubIn, rewriter.getImportRewrite()); ImportRewriteUtil.addImports(rewriter, context, newMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false); rewriter.getASTRewrite().getListRewrite(typeToCreateStubIn, typeToCreateStubIn.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, typeToCreateStubIn.bodyDeclarations()), rewriter.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_method_stub, SET_PULL_UP)); }
private void createAbstractMethod(final IMethod sourceMethod, final CompilationUnitRewrite sourceRewriter, final CompilationUnit declaringCuNode, final AbstractTypeDeclaration destination, final TypeVariableMaplet[] mapping, final CompilationUnitRewrite targetRewrite, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException { final MethodDeclaration oldMethod= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode); if (JavaModelUtil.is50OrHigher(sourceMethod.getJavaProject()) && (fSettings.overrideAnnotation || JavaCore.ERROR.equals(sourceMethod.getJavaProject().getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION, true)))) { final MarkerAnnotation annotation= sourceRewriter.getAST().newMarkerAnnotation(); annotation.setTypeName(sourceRewriter.getAST().newSimpleName("Override")); //$NON-NLS-1$ sourceRewriter.getASTRewrite().getListRewrite(oldMethod, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(annotation, sourceRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_override_annotation, SET_PULL_UP)); } final MethodDeclaration newMethod= targetRewrite.getAST().newMethodDeclaration(); newMethod.setBody(null); newMethod.setConstructor(false); copyExtraDimensions(oldMethod, newMethod); newMethod.setJavadoc(null); int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, Modifier.ABSTRACT | JdtFlags.clearFlag(Modifier.NATIVE | Modifier.FINAL, sourceMethod.getFlags()), adjustments, monitor, false, status); if (oldMethod.isVarargs()) modifiers&= ~Flags.AccVarargs; newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(targetRewrite.getAST(), modifiers)); newMethod.setName(((SimpleName) ASTNode.copySubtree(targetRewrite.getAST(), oldMethod.getName()))); copyReturnType(targetRewrite.getASTRewrite(), getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping); copyParameters(targetRewrite.getASTRewrite(), getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping); copyThrownExceptions(oldMethod, newMethod); copyTypeParameters(oldMethod, newMethod); ImportRewriteContext context= new ContextSensitiveImportRewriteContext(destination, targetRewrite.getImportRewrite()); ImportRewriteUtil.addImports(targetRewrite, context, oldMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false); targetRewrite.getASTRewrite().getListRewrite(destination, destination.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, destination.bodyDeclarations()), targetRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_abstract_method, SET_PULL_UP)); }
private Expression newDefaultExpression(AST ast, ITypeBinding type, ImportRewriteContext context) { if (type.isPrimitive()) { String name= type.getName(); if ("boolean".equals(name)) { //$NON-NLS-1$ return ast.newBooleanLiteral(false); } else { return ast.newNumberLiteral("0"); //$NON-NLS-1$ } } if (type == ast.resolveWellKnownType("java.lang.String")) { //$NON-NLS-1$ return ast.newStringLiteral(); } if (type.isArray()) { ArrayInitializer initializer= ast.newArrayInitializer(); initializer.expressions().add(newDefaultExpression(ast, type.getElementType(), context)); return initializer; } if (type.isAnnotation()) { MarkerAnnotation annotation= ast.newMarkerAnnotation(); annotation.setTypeName(ast.newName(getImportRewrite().addImport(type, context))); return annotation; } return ast.newNullLiteral(); }
private static void createTypeParameters(ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) { ITypeBinding[] typeParams= binding.getTypeParameters(); List<TypeParameter> typeParameters= decl.typeParameters(); for (int i= 0; i < typeParams.length; i++) { ITypeBinding curr= typeParams[i]; TypeParameter newTypeParam= ast.newTypeParameter(); newTypeParam.setName(ast.newSimpleName(curr.getName())); ITypeBinding[] typeBounds= curr.getTypeBounds(); if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$ List<Type> newTypeBounds= newTypeParam.typeBounds(); for (int k= 0; k < typeBounds.length; k++) { newTypeBounds.add(imports.addImport(typeBounds[k], ast, context)); } } typeParameters.add(newTypeParam); } }
private void qualifyThisExpressions(ASTNode node, final ASTRewrite rewrite, final ImportRewrite importRewrite, final ImportRewriteContext importRewriteContext) { node.accept(new GenericVisitor() { /** * {@inheritDoc} */ @Override public boolean visit(ThisExpression thisExpr) { if (thisExpr.getQualifier() == null) { ITypeBinding typeBinding= thisExpr.resolveTypeBinding(); if (typeBinding != null) { String typeName= importRewrite.addImport(typeBinding.getTypeDeclaration(), importRewriteContext); SimpleName simpleName= thisExpr.getAST().newSimpleName(typeName); rewrite.set(thisExpr, ThisExpression.QUALIFIER_PROPERTY, simpleName, null); } } return super.visit(thisExpr); } }); }
private Type getNewType(ASTRewrite rewrite) { AST ast= rewrite.getAST(); Type newTypeNode= null; ITypeBinding binding= null; if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) { Expression value= ((MemberValuePair) fInvocationNode.getParent()).getValue(); binding= value.resolveTypeBinding(); } else if (fInvocationNode instanceof Expression) { binding= ((Expression) fInvocationNode).resolveTypeBinding(); } if (binding != null) { ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite()); newTypeNode= getImportRewrite().addImport(binding, ast, importRewriteContext); } if (newTypeNode == null) { newTypeNode= ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$ } addLinkedPosition(rewrite.track(newTypeNode), false, KEY_TYPE); return newTypeNode; }
private void addMethodStubForAbstractMethod(final IMethod sourceMethod, final CompilationUnit declaringCuNode, final AbstractTypeDeclaration typeToCreateStubIn, final ICompilationUnit newCu, final CompilationUnitRewrite rewriter, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException { final MethodDeclaration methodToCreateStubFor= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode); final AST ast= rewriter.getRoot().getAST(); final MethodDeclaration newMethod= ast.newMethodDeclaration(); newMethod.setBody(createMethodStub(methodToCreateStubFor, ast)); newMethod.setConstructor(false); newMethod.setExtraDimensions(methodToCreateStubFor.getExtraDimensions()); newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiersWithUpdatedVisibility(sourceMethod, JdtFlags.clearFlag(Modifier.NATIVE | Modifier.ABSTRACT, methodToCreateStubFor.getModifiers()), adjustments, new SubProgressMonitor(monitor, 1), false, status))); newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, methodToCreateStubFor.getName()))); final TypeVariableMaplet[] mapping= TypeVariableUtil.composeMappings(TypeVariableUtil.subTypeToSuperType(getDeclaringType(), getDestinationType()), TypeVariableUtil.superTypeToInheritedType(getDestinationType(), ((IType) typeToCreateStubIn.resolveBinding().getJavaElement()))); copyReturnType(rewriter.getASTRewrite(), getDeclaringType().getCompilationUnit(), methodToCreateStubFor, newMethod, mapping); copyParameters(rewriter.getASTRewrite(), getDeclaringType().getCompilationUnit(), methodToCreateStubFor, newMethod, mapping); copyThrownExceptions(methodToCreateStubFor, newMethod); newMethod.setJavadoc(createJavadocForStub(typeToCreateStubIn.getName().getIdentifier(), methodToCreateStubFor, newMethod, newCu, rewriter.getASTRewrite())); ImportRewriteContext context= new ContextSensitiveImportRewriteContext(typeToCreateStubIn, rewriter.getImportRewrite()); ImportRewriteUtil.addImports(rewriter, context, newMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false); rewriter.getASTRewrite().getListRewrite(typeToCreateStubIn, typeToCreateStubIn.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, typeToCreateStubIn.bodyDeclarations()), rewriter.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_method_stub, SET_PULL_UP)); }
private void createAbstractMethod(final IMethod sourceMethod, final CompilationUnitRewrite sourceRewriter, final CompilationUnit declaringCuNode, final AbstractTypeDeclaration destination, final TypeVariableMaplet[] mapping, final CompilationUnitRewrite targetRewrite, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException { final MethodDeclaration oldMethod= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode); if (JavaModelUtil.is50OrHigher(sourceMethod.getJavaProject()) && (fSettings.overrideAnnotation || JavaCore.ERROR.equals(sourceMethod.getJavaProject().getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION, true)))) { final MarkerAnnotation annotation= sourceRewriter.getAST().newMarkerAnnotation(); annotation.setTypeName(sourceRewriter.getAST().newSimpleName("Override")); //$NON-NLS-1$ sourceRewriter.getASTRewrite().getListRewrite(oldMethod, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(annotation, sourceRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_override_annotation, SET_PULL_UP)); } final MethodDeclaration newMethod= targetRewrite.getAST().newMethodDeclaration(); newMethod.setBody(null); newMethod.setConstructor(false); newMethod.setExtraDimensions(oldMethod.getExtraDimensions()); newMethod.setJavadoc(null); int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, Modifier.ABSTRACT | JdtFlags.clearFlag(Modifier.NATIVE | Modifier.FINAL, sourceMethod.getFlags()), adjustments, monitor, false, status); if (oldMethod.isVarargs()) modifiers&= ~Flags.AccVarargs; newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(targetRewrite.getAST(), modifiers)); newMethod.setName(((SimpleName) ASTNode.copySubtree(targetRewrite.getAST(), oldMethod.getName()))); copyReturnType(targetRewrite.getASTRewrite(), getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping); copyParameters(targetRewrite.getASTRewrite(), getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping); copyThrownExceptions(oldMethod, newMethod); ImportRewriteContext context= new ContextSensitiveImportRewriteContext(destination, targetRewrite.getImportRewrite()); ImportRewriteUtil.addImports(targetRewrite, context, newMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false); targetRewrite.getASTRewrite().getListRewrite(destination, destination.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, destination.bodyDeclarations()), targetRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_abstract_method, SET_PULL_UP)); }
public static void createOverrideAnnotation(ASTRewrite rewrite, ImportRewrite imports, MethodDeclaration decl, TextEditGroup group) { if (findAnnotation("java.lang.Override", decl.modifiers()) != null) { //$NON-NLS-1$ return; // No need to add duplicate annotation } AST ast= rewrite.getAST(); ASTNode root= decl.getRoot(); ImportRewriteContext context= null; if (root instanceof CompilationUnit) { context= new ContextSensitiveImportRewriteContext((CompilationUnit) root, decl.getStartPosition(), imports); } Annotation marker= ast.newMarkerAnnotation(); marker.setTypeName(ast.newName(imports.addImport("java.lang.Override", context))); //$NON-NLS-1$ rewrite.getListRewrite(decl, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(marker, group); }
private void addNewParameters(ASTRewrite rewrite, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException { if (!isGetter) { AST ast = rewrite.getAST(); SingleVariableDeclaration param = ast.newSingleVariableDeclaration(); Type type = getImportRewrite().addImport(fVariableBinding.getType(), ast, context, TypeLocation.PARAMETER); param.setType(type); param.setName(ast.newSimpleName(getArgumentName())); params.add(param); } }
private Type getNewMethodType(ASTRewrite rewrite, ImportRewriteContext context) throws CoreException { AST ast = rewrite.getAST(); Type newTypeNode = null; if (isGetter) { newTypeNode = getImportRewrite().addImport(fVariableBinding.getType(), ast, context, TypeLocation.RETURN_TYPE); } else { newTypeNode = ast.newPrimitiveType(PrimitiveType.VOID); } return newTypeNode; }
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; }