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 IJavaCompletionProposal[] getImportStaticConstructsProposal( IInvocationContext context) { final ICompilationUnit unit = context.getCompilationUnit(); final IJavaProject project = unit.getJavaProject(); final ImportRewrite rewrite = getImportRewrite(context.getASTRoot(), "static apgas.Constructs.*"); final ArrayList<IJavaCompletionProposal> proposals = new ArrayList<IJavaCompletionProposal>(); proposals.add(new ConstructsImportProposal(project, rewrite)); final IJavaCompletionProposal[] propArr = new IJavaCompletionProposal[proposals .size()]; for (int i = 0; i < proposals.size(); i++) { propArr[i] = proposals.get(i); } return propArr; }
private IJavaCompletionProposal[] getAddAPGASToBuildPathProposals( IInvocationContext context) { final ICompilationUnit unit = context.getCompilationUnit(); final IJavaProject project = unit.getJavaProject(); final String name = "static apgas.Constructs.*"; final ClasspathFixProposal[] fixProposals = ClasspathFixProcessor .getContributedFixImportProposals(project, name, null); final List<ImportRewrite> importRewrites = new ArrayList<ImportRewrite>(); importRewrites.add(getImportRewrite(context.getASTRoot(), name)); importRewrites.add(getImportRewrite(context.getASTRoot(), "apgas.*")); final ArrayList<IJavaCompletionProposal> proposals = new ArrayList<IJavaCompletionProposal>(); for (final ClasspathFixProposal fixProposal : fixProposals) { proposals.add(new APGASClasspathFixCorrelationProposal(project, fixProposal, importRewrites)); } final IJavaCompletionProposal[] propArr = new IJavaCompletionProposal[proposals .size()]; for (int i = 0; i < proposals.size(); i++) { propArr[i] = proposals.get(i); } return propArr; }
/** * @param document * @param offset * @param importRewrite * @param completionSnippetsSupported * @return * @throws CoreException * @throws BadLocationException */ public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean completionSnippetsSupported) throws CoreException, BadLocationException { int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic); String stub; if (fIsGetter) { String getterName= GetterSetterUtil.getGetterName(fField, null); stub = GetterSetterUtil.getGetterStub(fField, getterName, true, flags); } else { String setterName= GetterSetterUtil.getSetterName(fField, null); stub = GetterSetterUtil.getSetterStub(fField, setterName, true, flags); } // use the code formatter String lineDelim= TextUtilities.getDefaultLineDelimiter(document); String replacement = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, 0, lineDelim, fField.getJavaProject()); if (replacement.endsWith(lineDelim)) { replacement = replacement.substring(0, replacement.length() - lineDelim.length()); } return replacement; }
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); } }
/** * Adds <code>@Override</code> annotation to <code>methodDecl</code> if not already present and * if requested by code style settings or compiler errors/warnings settings. * * @param settings the code generation style settings, may be <code>null</code> * @param project the Java project used to access the compiler settings * @param rewrite the ASTRewrite * @param imports the ImportRewrite * @param methodDecl the method declaration to add the annotation to * @param isDeclaringTypeInterface <code>true</code> if the type declaring the method overridden * by <code>methodDecl</code> is an interface * @param group the text edit group, may be <code>null</code> */ public static void addOverrideAnnotation(CodeGenerationSettings settings, IJavaProject project, ASTRewrite rewrite, ImportRewrite imports, MethodDeclaration methodDecl, boolean isDeclaringTypeInterface, TextEditGroup group) { if (!JavaModelUtil.is50OrHigher(project)) { return; } if (isDeclaringTypeInterface) { String version= project.getOption(JavaCore.COMPILER_COMPLIANCE, true); if (JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6)) { return; // not allowed in 1.5 } if (JavaCore.DISABLED.equals(project.getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION_FOR_INTERFACE_METHOD_IMPLEMENTATION, true))) { return; // user doesn't want to use 1.6 style } } if ((settings != null && settings.overrideAnnotation) || !JavaCore.IGNORE.equals(project.getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION, true))) { createOverrideAnnotation(rewrite, imports, methodDecl, group); } }
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); } }
public TypeReferenceProcessor(Set<String> oldSingleImports, Set<String> oldDemandImports, CompilationUnit root, ImportRewrite impStructure, boolean ignoreLowerCaseNames, UnresolvableImportMatcher unresolvableImportMatcher) { fOldSingleImports= oldSingleImports; fOldDemandImports= oldDemandImports; fImpStructure= impStructure; fDoIgnoreLowerCaseNames= ignoreLowerCaseNames; fUnresolvableImportMatcher= unresolvableImportMatcher; ICompilationUnit cu= impStructure.getCompilationUnit(); fImplicitImports= new HashSet<>(3); fImplicitImports.add(""); //$NON-NLS-1$ fImplicitImports.add("java.lang"); //$NON-NLS-1$ fImplicitImports.add(cu.getParent().getElementName()); fAnalyzer= new ScopeAnalyzer(root); fCurrPackage= (IPackageFragment) cu.getParent(); fAllowDefaultPackageImports= cu.getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true).equals(JavaCore.VERSION_1_3); fImportsAdded= new HashSet<>(); fUnresolvedTypes= new HashMap<>(); }
private void addStaticImports( Collection<SimpleName> staticReferences, ImportRewrite importRewrite, UnresolvableImportMatcher unresolvableImportMatcher) { for (SimpleName name : staticReferences) { IBinding binding= name.resolveBinding(); if (binding != null) { importRewrite.addStaticImport(binding); } else { // This could be an unresolvable reference to a static member. String identifier= name.getIdentifier(); Set<String> unresolvableImports= unresolvableImportMatcher.matchStaticImports(identifier); for (String unresolvableImport : unresolvableImports) { int lastDotIndex= unresolvableImport.lastIndexOf('.'); // It's OK to skip invalid imports. if (lastDotIndex != -1) { String declaringTypeName= unresolvableImport.substring(0, lastDotIndex); String simpleName= unresolvableImport.substring(lastDotIndex + 1); // Whether name refers to a field or to a method is unknown. boolean isField= false; importRewrite.addStaticImport(declaringTypeName, simpleName, isField, UNRESOLVABLE_IMPORT_CONTEXT); } } } } }
public ImportRewrite getImportRewrite() { if (fImportRewrite == null) { // lazily initialized to avoid lengthy processing in checkInitialConditions(..) try { /* If bindings are to be resolved, then create the AST, so that * ImportRewrite#setUseContextToFilterImplicitImports(boolean) will be set to true * and ContextSensitiveImportRewriteContext etc. can be used. */ if (fRoot == null && ! fResolveBindings) { fImportRewrite= StubUtility.createImportRewrite(fCu, true); } else { fImportRewrite= StubUtility.createImportRewrite(getRoot(), true); } } catch (CoreException e) { JavaLanguageServerPlugin.log(e); throw new IllegalStateException(e.getMessage()); // like ASTParser#createAST(..) does } } return fImportRewrite; }
@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$ }
public static void getAmbiguousTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); int offset= problem.getOffset(); int len= problem.getLength(); IJavaElement[] elements= cu.codeSelect(offset, len); for (int i= 0; i < elements.length; i++) { IJavaElement curr= elements[i]; if (curr instanceof IType) { String qualifiedTypeName= ((IType) curr).getFullyQualifiedName('.'); CompilationUnit root= context.getASTRoot(); String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importexplicit_description, BasicElementLabels.getJavaElementName(qualifiedTypeName)); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, ASTRewrite.create(root.getAST()), IProposalRelevance.IMPORT_EXPLICIT); ImportRewrite imports= proposal.createImportRewrite(root); imports.addImport(qualifiedTypeName); proposals.add(proposal); } } }
private RefactoringStatus rewriteInfixExpression(ASTRewrite astRewrite, ImportRewrite importRewrite, InfixExpression ie, String fullyQualifiedTypeName) { final RefactoringStatus status = new RefactoringStatus(); final AST ast = ie.getAST(); final Expression leftExpCopy = (Expression) ASTNode.copySubtree(ast, ie.getLeftOperand()); final Expression rightExpCopy = (Expression) ASTNode.copySubtree(ast, ie.getRightOperand()); final NumberLiteral zero = ast.newNumberLiteral(); astRewrite.replace(ie.getRightOperand(), zero, null); final MethodInvocation newInvocation = ast.newMethodInvocation(); newInvocation.setExpression(leftExpCopy); newInvocation.setName(ast.newSimpleName("compareTo")); //$NON-NLS-1$ newInvocation.arguments().add(rightExpCopy); astRewrite.replace(ie.getLeftOperand(), newInvocation, null); if (((ASTNode) newInvocation.arguments().get(0)).getNodeType() == ASTNode.SIMPLE_NAME && this.fieldsToRefactor.contains(((SimpleName) ie .getRightOperand()).resolveBinding().getJavaElement())) this.rewriteReference(astRewrite, importRewrite, (SimpleName) newInvocation.arguments().get(0), fullyQualifiedTypeName); if (((ASTNode) newInvocation.getExpression()).getNodeType() == ASTNode.SIMPLE_NAME && this.fieldsToRefactor.contains(((SimpleName) ie .getLeftOperand()).resolveBinding().getJavaElement())) this.rewriteReference(astRewrite, importRewrite, (SimpleName) newInvocation.getExpression(), fullyQualifiedTypeName); return status; }
protected void rewriteCompilationUnit(ICompilationUnit unit, Collection matches, CompilationUnit node, RefactoringStatus status, IProgressMonitor monitor) throws CoreException { final ASTRewrite astRewrite = ASTRewrite.create(node.getAST()); final ImportRewrite importRewrite = ImportRewrite.create(node, true); for (final Iterator it = matches.iterator(); it.hasNext();) { final SearchMatch match = (SearchMatch) it.next(); if (match.getAccuracy() == SearchMatch.A_ACCURATE && !match.isInsideDocComment()) if (this.matchToPurposeMap.get(match) == SearchMatchPurpose.ALTER_TYPE_DECLARATION || this.matchToPurposeMap.get(match) == SearchMatchPurpose.ALTER_NAMESPACE_PREFIX) this.rewriteDeclarationsAndNamespaces(node, match, status, astRewrite, importRewrite); else if (this.matchToPurposeMap.get(match) == SearchMatchPurpose.ALTER_INFIX_EXPRESSION) this.rewriteExpressions(node, match, status, astRewrite, importRewrite); } this.rewriteAST(unit, astRewrite, importRewrite); }
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$ }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fBodyDeclaration, fBodyDeclaration.getModifiersProperty()); TextEditGroup group = createTextEditGroup(fMessage, cuRewrite); if (!checkExisting(fBodyDeclaration.modifiers(), listRewrite, group)) return; if (hasNonNullDefault(fBodyDeclaration.resolveBinding())) return; // should be safe, as in this case checkExisting() should've already produced a // change (remove existing // annotation). Annotation newAnnotation = ast.newMarkerAnnotation(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); String resolvableName = importRewrite.addImport(fAnnotationToAdd); newAnnotation.setTypeName(ast.newName(resolvableName)); listRewrite.insertLast( newAnnotation, group); // null annotation is last modifier, directly preceding the return type }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fArgument, SingleVariableDeclaration.MODIFIERS2_PROPERTY); TextEditGroup group = createTextEditGroup(fMessage, cuRewrite); if (!checkExisting(fArgument.modifiers(), listRewrite, group)) return; Annotation newAnnotation = ast.newMarkerAnnotation(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); String resolvableName = importRewrite.addImport(fAnnotationToAdd); newAnnotation.setTypeName(ast.newName(resolvableName)); listRewrite.insertLast( newAnnotation, group); // null annotation is last modifier, directly preceding the type }
public ImportRewrite getImportRewrite() { if (fImportRewrite == null) { // lazily initialized to avoid lengthy processing in checkInitialConditions(..) try { /* If bindings are to be resolved, then create the AST, so that * ImportRewrite#setUseContextToFilterImplicitImports(boolean) will be set to true * and ContextSensitiveImportRewriteContext etc. can be used. */ if (fRoot == null && !fResolveBindings) { fImportRewrite = StubUtility.createImportRewrite(fCu, true); } else { fImportRewrite = StubUtility.createImportRewrite(getRoot(), true); } } catch (CoreException e) { JavaPlugin.log(e); throw new IllegalStateException(e.getMessage()); // like ASTParser#createAST(..) does } } return fImportRewrite; }
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 void addStaticImport( ICompilationUnit movedUnit, IImportDeclaration importDecl, ImportRewrite rewrite) { String old = importDecl.getElementName(); int oldPackLength = movedUnit.getParent().getElementName().length(); StringBuffer result = new StringBuffer(fDestination.getElementName()); if (oldPackLength == 0) // move FROM default package result.append('.').append(old); else if (result.length() == 0) // move TO default package result.append(old.substring(oldPackLength + 1)); // cut "." else result.append(old.substring(oldPackLength)); int index = result.lastIndexOf("."); // $NON-NLS-1$ if (index > 0 && index < result.length() - 1) rewrite.addStaticImport( result.substring(0, index), result.substring(index + 1, result.length()), true); }
private void addImportToSourcePackageTypes(ICompilationUnit movedUnit, IProgressMonitor pm) throws CoreException { List<ICompilationUnit> cuList = Arrays.asList(fCus); IType[] allCuTypes = movedUnit.getAllTypes(); IType[] referencedTypes = ReferenceFinderUtil.getTypesReferencedIn(allCuTypes, pm); ImportRewrite importEdit = getImportRewrite(movedUnit); importEdit.setFilterImplicitImports(false); IPackageFragment srcPack = (IPackageFragment) movedUnit.getParent(); for (int i = 0; i < referencedTypes.length; i++) { IType iType = referencedTypes[i]; if (!iType.exists()) continue; if (!JavaModelUtil.isSamePackage(iType.getPackageFragment(), srcPack)) continue; if (cuList.contains(iType.getCompilationUnit())) continue; importEdit.addImport(iType.getFullyQualifiedName('.')); } }
/** * Updates the replacement string. * * @param document the document * @param trigger the trigger * @param offset the offset * @param impRewrite the import rewrite * @return <code>true</code> if the cursor position should be updated, <code>false</code> * otherwise * @throws org.eclipse.jface.text.BadLocationException if accessing the document fails * @throws org.eclipse.core.runtime.CoreException if something else fails */ protected boolean updateReplacementString( IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException { // avoid adding imports when inside imports container if (impRewrite != null && fFullyQualifiedTypeName != null) { String replacementString = getReplacementString(); String qualifiedType = fFullyQualifiedTypeName; if (qualifiedType.indexOf('.') != -1 && replacementString.startsWith(qualifiedType) && !replacementString.endsWith(String.valueOf(';'))) { IType[] types = impRewrite.getCompilationUnit().getTypes(); if (types.length > 0 && types[0].getSourceRange().getOffset() <= offset) { // ignore positions above type. setReplacementString(impRewrite.addImport(getReplacementString())); return true; } } } return false; }
static CompilationUnitChange createAddImportChange( ICompilationUnit cu, Name name, String fullyQualifiedName) throws CoreException { String[] args = { BasicElementLabels.getJavaElementName(Signature.getSimpleName(fullyQualifiedName)), BasicElementLabels.getJavaElementName(Signature.getQualifier(fullyQualifiedName)) }; String label = Messages.format( CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, args); CompilationUnitChange cuChange = new CompilationUnitChange(label, cu); ImportRewrite importRewrite = StubUtility.createImportRewrite((CompilationUnit) name.getRoot(), true); importRewrite.addImport(fullyQualifiedName); cuChange.setEdit(importRewrite.rewriteImports(null)); return cuChange; }
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; }
/** * Generates the normalized form and adds the required imports for a given * {@link Type}. */ public static Type normalizeTypeAndAddImport(AST ast, Type type, ImportRewrite imports) { ITypeBinding binding = type.resolveBinding(); // Eliminate type variables in the generated type // TODO(): maybe leave the type variables, if we can verify that the type // parameters on the target type are exactly the same as those on the source // type (all names and type bounds are identical) if (JavaASTUtils.containsTypeVariable(type)) { binding = binding.getErasure(); } // Report the type binding to the import rewriter, which will record the // import and give us either a SimpleType or a QualifiedType to use. return imports.addImport(binding, ast); }
private ImportRewrite getImportRewrite(CompilationUnit astRoot, String typeToImport) { if (typeToImport != null) { final ImportRewrite importRewrite = CodeStyleConfiguration .createImportRewrite(astRoot, true); importRewrite.addImport(typeToImport); return importRewrite; } return null; }
public APGASClasspathFixCorrelationProposal(IJavaProject project, ClasspathFixProposal classpathFixProposal, List<ImportRewrite> importRewrites) { fJavaProject = project; fClasspathFixProposal = classpathFixProposal; fImportRewrites = importRewrites; }
protected Change createChange() throws CoreException { final Change change = fClasspathFixProposal.createChange(null); if (fImportRewrites != null) { final CompositeChange composite = new CompositeChange(getDisplayString()); composite.add(change); for (final ImportRewrite ir : fImportRewrites) { final TextFileChange cuChange = new TextFileChange("Add import", //$NON-NLS-1$ (IFile) ir.getCompilationUnit().getResource()); cuChange.setEdit(ir.rewriteImports(null)); composite.add(cuChange); } return composite; } return change; }
static ImportRewrite createImportRewrite(ICompilationUnit compilationUnit) { try { ImportRewrite rewrite = ImportRewrite.create(compilationUnit, true); rewrite.setImportOrder(IMPORTS_ORDER); rewrite.setOnDemandImportThreshold(IMPORTS_THRESHOLD); rewrite.setStaticOnDemandImportThreshold(IMPORTS_THRESHOLD); return rewrite; } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
public String updateReplacementString(IDocument document, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException { String newBody = createNewBody(impRewrite); if (newBody == null) { return null; } StringBuffer buf = new StringBuffer("new A()"); //$NON-NLS-1$ buf.append(newBody); // use the code formatter String lineDelim = TextUtilities.getDefaultLineDelimiter(document); final IJavaProject project = fCompilationUnit.getJavaProject(); IRegion lineInfo = document.getLineInformationOfOffset(fReplacementOffset); Map<String, String> options = project != null ? project.getOptions(true) : JavaCore.getOptions(); String replacementString = CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, lineDelim, options); int lineEndOffset = lineInfo.getOffset() + lineInfo.getLength(); int p = offset; if (p < document.getLength()) { char ch = document.getChar(p); while (p < lineEndOffset) { if (ch == '(' || ch == ')' || ch == ';' || ch == ',') { break; } ch = document.getChar(++p); } if (ch != ';' && ch != ',' && ch != ')') { replacementString = replacementString + ';'; } } int beginIndex = replacementString.indexOf('('); replacementString = replacementString.substring(beginIndex); return replacementString; }
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 ContextSensitiveImportRewriteContext(CompilationUnit compilationUnit, int position, ImportRewrite importRewrite, RedundantNullnessTypeAnnotationsFilter redundantNullnessTypeAnnotationsFilter) { fCompilationUnit= compilationUnit; fPosition= position; fImportRewrite= importRewrite; fDeclarationsInScope= null; fImportedNames= null; fRedundantTypeAnnotationsFilter= redundantNullnessTypeAnnotationsFilter; }
@Override public TextEdit computeEdits(int offset, LinkedPosition position, char trigger, int stateMask, LinkedModeModel model) throws CoreException { ImportRewrite impRewrite= StubUtility.createImportRewrite(fCompilationUnit, true); String replaceString= impRewrite.addImport(fTypeProposal); MultiTextEdit composedEdit= new MultiTextEdit(); composedEdit.addChild(new ReplaceEdit(position.getOffset(), position.getLength(), replaceString)); composedEdit.addChild(impRewrite.rewriteImports(null)); return composedEdit; }
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; }
static CompilationUnitChange createAddImportChange(ICompilationUnit cu, Name name, String fullyQualifiedName) throws CoreException { String[] args= { BasicElementLabels.getJavaElementName(Signature.getSimpleName(fullyQualifiedName)), BasicElementLabels.getJavaElementName(Signature.getQualifier(fullyQualifiedName)) }; String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, args); CompilationUnitChange cuChange= new CompilationUnitChange(label, cu); ImportRewrite importRewrite= StubUtility.createImportRewrite((CompilationUnit) name.getRoot(), true); importRewrite.addImport(fullyQualifiedName); cuChange.setEdit(importRewrite.rewriteImports(null)); return cuChange; }