Java Code Examples for org.eclipse.jdt.core.dom.rewrite.ImportRewrite#addImport()
The following examples show how to use
org.eclipse.jdt.core.dom.rewrite.ImportRewrite#addImport() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeParametersFix.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { TextEditGroup group= createTextEditGroup(FixMessages.TypeParametersFix_insert_inferred_type_arguments_description, cuRewrite); ASTRewrite rewrite= cuRewrite.getASTRewrite(); ImportRewrite importRewrite= cuRewrite.getImportRewrite(); AST ast= cuRewrite.getRoot().getAST(); for (int i= 0; i < fCreatedTypes.length; i++) { ParameterizedType createdType= fCreatedTypes[i]; ITypeBinding[] typeArguments= createdType.resolveBinding().getTypeArguments(); ContextSensitiveImportRewriteContext importContext= new ContextSensitiveImportRewriteContext(cuRewrite.getRoot(), createdType.getStartPosition(), importRewrite); ListRewrite argumentsRewrite= rewrite.getListRewrite(createdType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY); for (int j= 0; j < typeArguments.length; j++) { ITypeBinding typeArgument= typeArguments[j]; Type argumentNode= importRewrite.addImport(typeArgument, ast, importContext); argumentsRewrite.insertLast(argumentNode, group); } } }
Example 2
Source File: SourceProvider.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void updateTypeReferences(ASTRewrite rewriter, CallContext context) { ImportRewrite importer= context.importer; for (Iterator<SimpleName> iter= fAnalyzer.getTypesToImport().iterator(); iter.hasNext();) { Name element= iter.next(); ITypeBinding binding= ASTNodes.getTypeBinding(element); if (binding != null && !binding.isLocal()) { // We have collected names not types. So we have to import // the declaration type if we reference a parameterized type // since we have an entry for every name node (e.g. one for // Vector and one for Integer in Vector<Integer>. if (binding.isParameterizedType()) { binding= binding.getTypeDeclaration(); } String s= importer.addImport(binding); if (!ASTNodes.asString(element).equals(s)) { rewriter.replace(element, rewriter.createStringPlaceholder(s, ASTNode.SIMPLE_NAME), null); } } } }
Example 3
Source File: ASTNodeFactory.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * 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$ }
Example 4
Source File: MoveCuUpdateCreator.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
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('.')); } }
Example 5
Source File: OrganizeImportsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private static void addImports(CompilationUnit root, ICompilationUnit unit, String[] favourites, ImportRewrite importRewrite, AST ast, ASTRewrite astRewrite, SimpleName node, boolean isMethod) throws JavaModelException { String name = node.getIdentifier(); String[] imports = SimilarElementsRequestor.getStaticImportFavorites(unit, name, isMethod, favourites); if (imports.length > 1) { // See https://github.com/redhat-developer/vscode-java/issues/1472 return; } for (int i = 0; i < imports.length; i++) { String curr = imports[i]; String qualifiedTypeName = Signature.getQualifier(curr); String res = importRewrite.addStaticImport(qualifiedTypeName, name, isMethod, new ContextSensitiveImportRewriteContext(root, node.getStartPosition(), importRewrite)); int dot = res.lastIndexOf('.'); if (dot != -1) { String usedTypeName = importRewrite.addImport(qualifiedTypeName); Name newName = ast.newQualifiedName(ast.newName(usedTypeName), ast.newSimpleName(name)); astRewrite.replace(node, newName, null); } } }
Example 6
Source File: ChangeTypeRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * update a CompilationUnit's imports after changing the type of declarations * @param astRoot the AST * @param rootEdit the resulting edit * @return the type name to use * @throws CoreException */ private String updateImports(CompilationUnit astRoot, MultiTextEdit rootEdit) throws CoreException{ ImportRewrite rewrite= StubUtility.createImportRewrite(astRoot, true); ContextSensitiveImportRewriteContext context= new ContextSensitiveImportRewriteContext(astRoot, fSelectionStart, rewrite); String typeName= rewrite.addImport(fSelectedType.getQualifiedName(), context); rootEdit.addChild(rewrite.rewriteImports(null)); return typeName; }
Example 7
Source File: UnresolvedElementsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
static CUCorrectionProposal createTypeRefChangeFullProposal(ICompilationUnit cu, ITypeBinding binding, ASTNode node, int relevance) { ASTRewrite rewrite= ASTRewrite.create(node.getAST()); String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_change_full_type_description, BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_DEFAULT)); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, relevance, image); ImportRewrite imports= proposal.createImportRewrite((CompilationUnit) node.getRoot()); Type type= imports.addImport(binding, node.getAST()); rewrite.replace(node, type, null); return proposal; }
Example 8
Source File: MoveCuUpdateCreator.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private void addReferenceUpdates(TextChangeManager changeManager, ICompilationUnit movedUnit, IProgressMonitor pm, RefactoringStatus status) throws JavaModelException, CoreException { List<ICompilationUnit> cuList = Arrays.asList(fCus); SearchResultGroup[] references = getReferences(movedUnit, pm, status); for (int i = 0; i < references.length; i++) { SearchResultGroup searchResultGroup = references[i]; ICompilationUnit referencingCu = searchResultGroup.getCompilationUnit(); if (referencingCu == null) { continue; } boolean simpleReferencesNeedNewImport = simpleReferencesNeedNewImport(movedUnit, referencingCu, cuList); SearchMatch[] results = searchResultGroup.getSearchResults(); for (int j = 0; j < results.length; j++) { // TODO: should update type references with results from addImport TypeReference reference = (TypeReference) results[j]; if (reference.isImportDeclaration()) { ImportRewrite rewrite = getImportRewrite(referencingCu); IImportDeclaration importDecl = (IImportDeclaration) SearchUtils.getEnclosingJavaElement(results[j]); if (Flags.isStatic(importDecl.getFlags())) { rewrite.removeStaticImport(importDecl.getElementName()); addStaticImport(movedUnit, importDecl, rewrite); } else { rewrite.removeImport(importDecl.getElementName()); rewrite.addImport(createStringForNewImport(movedUnit, importDecl)); } } else if (reference.isQualified()) { TextChange textChange = changeManager.get(referencingCu); String changeName = RefactoringCoreMessages.MoveCuUpdateCreator_update_references; TextEdit replaceEdit = new ReplaceEdit(reference.getOffset(), reference.getSimpleNameStart() - reference.getOffset(), fNewPackage); TextChangeCompatibility.addTextEdit(textChange, changeName, replaceEdit); } else if (simpleReferencesNeedNewImport) { ImportRewrite importEdit = getImportRewrite(referencingCu); String typeName = reference.getSimpleName(); importEdit.addImport(getQualifiedType(fDestination.getElementName(), typeName)); } } } }
Example 9
Source File: ImplementInterfaceProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@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); ListRewrite listRewrite= rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY); listRewrite.insertLast(newInterface, null); // set up linked mode final String KEY_TYPE= "type"; //$NON-NLS-1$ addLinkedPosition(rewrite.track(newInterface), true, KEY_TYPE); return rewrite; } return null; }
Example 10
Source File: LinkedProposalPositionGroup.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@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; }
Example 11
Source File: ClientBundleResource.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
public MethodDeclaration createMethodDeclaration(IType clientBundle, ASTRewrite astRewrite, ImportRewrite importRewrite, boolean addComments) throws CoreException { AST ast = astRewrite.getAST(); MethodDeclaration methodDecl = ast.newMethodDeclaration(); // Method is named after the resource it accesses methodDecl.setName(ast.newSimpleName(getMethodName())); // Method return type is a ResourcePrototype subtype ITypeBinding resourceTypeBinding = JavaASTUtils.resolveType(clientBundle.getJavaProject(), getReturnTypeName()); Type resourceType = importRewrite.addImport(resourceTypeBinding, ast); methodDecl.setReturnType2(resourceType); // Add @Source annotation if necessary String sourceAnnotationValue = getSourceAnnotationValue(clientBundle); if (sourceAnnotationValue != null) { // Build the annotation SingleMemberAnnotation sourceAnnotation = ast.newSingleMemberAnnotation(); sourceAnnotation.setTypeName(ast.newName("Source")); StringLiteral annotationValue = ast.newStringLiteral(); annotationValue.setLiteralValue(sourceAnnotationValue); sourceAnnotation.setValue(annotationValue); // Add the annotation to the method ChildListPropertyDescriptor modifiers = methodDecl.getModifiersProperty(); ListRewrite modifiersRewriter = astRewrite.getListRewrite(methodDecl, modifiers); modifiersRewriter.insertFirst(sourceAnnotation, null); } return methodDecl; }
Example 12
Source File: ExtractConstantRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private Type getConstantType() throws JavaModelException { if (fConstantTypeCache == null) { IExpressionFragment fragment= getSelectedExpression(); ITypeBinding typeBinding= guessBindingForReference(fragment.getAssociatedExpression()); AST ast= fCuRewrite.getAST(); typeBinding= Bindings.normalizeForDeclarationUse(typeBinding, ast); ImportRewrite importRewrite= fCuRewrite.getImportRewrite(); ImportRewriteContext context= new ContextSensitiveImportRewriteContext(fCuRewrite.getRoot(), fSelectionStart, importRewrite); fConstantTypeCache= importRewrite.addImport(typeBinding, ast, context); } return fConstantTypeCache; }
Example 13
Source File: UnresolvedElementsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
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 = CodeStyleConfiguration.createImportRewrite((CompilationUnit) name.getRoot(), true); importRewrite.addImport(fullyQualifiedName); cuChange.setEdit(importRewrite.rewriteImports(null)); return cuChange; }
Example 14
Source File: ConvertAnonymousToNestedRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void addExceptionsToNewConstructor(MethodDeclaration newConstructor, ImportRewrite importRewrite) { IMethodBinding constructorBinding= getSuperConstructorBinding(); if (constructorBinding == null) return; ITypeBinding[] exceptions= constructorBinding.getExceptionTypes(); for (int i= 0; i < exceptions.length; i++) { Type exceptionType= importRewrite.addImport(exceptions[i], fAnonymousInnerClassNode.getAST()); newConstructor.thrownExceptionTypes().add(exceptionType); } }
Example 15
Source File: AccessorClassCreator.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void addImportsToAccessorCu(ICompilationUnit newCu, IProgressMonitor pm) throws CoreException { ImportRewrite is= StubUtility.createImportRewrite(newCu, true); if (fIsEclipseNLS) { is.addImport("org.eclipse.osgi.util.NLS"); //$NON-NLS-1$ } else { is.addImport("java.util.MissingResourceException"); //$NON-NLS-1$ is.addImport("java.util.ResourceBundle"); //$NON-NLS-1$ } TextEdit edit= is.rewriteImports(pm); JavaModelUtil.applyEdit(newCu, edit, false, null); }
Example 16
Source File: LocalCorrectionsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode instanceof Name) { IBinding binding= ((Name) selectedNode).resolveBinding(); if (binding instanceof IVariableBinding) { IVariableBinding variableBinding= (IVariableBinding) binding; if (variableBinding.isField()) { String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName(); String fieldName= variableBinding.getName(); String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName)); if (methodName != null) { AST ast= selectedNode.getAST(); ASTRewrite astRewrite= ASTRewrite.create(ast); ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true); MethodInvocation method= ast.newMethodInvocation(); String qfn= importRewrite.addImport(methodName[0]); method.setExpression(ast.newName(qfn)); method.setName(ast.newSimpleName(methodName[1])); ASTNode parent= selectedNode.getParent(); ICompilationUnit cu= context.getCompilationUnit(); // add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works): if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is18OrHigher(cu.getJavaProject())) { IMethodBinding methodBinding= Invocations.resolveBinding(parent); if (methodBinding != null) { ITypeBinding[] parameterTypes= methodBinding.getParameterTypes(); int i= Invocations.getArguments(parent).indexOf(selectedNode); if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) { ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments(); for (int j= 0; j < typeArguments.length; j++) { ITypeBinding typeArgument= typeArguments[j]; typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast); if (! TypeRules.isJavaLangObject(typeArgument)) { // add all type arguments if at least one is found to be necessary: List<Type> typeArgumentsList= method.typeArguments(); for (int k= 0; k < typeArguments.length; k++) { typeArgument= typeArguments[k]; typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast); typeArgumentsList.add(importRewrite.addImport(typeArgument, ast)); } break; } } } } } astRewrite.replace(selectedNode, method, null); String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(method))); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image); proposal.setImportRewrite(importRewrite); proposals.add(proposal); } } } } }
Example 17
Source File: UnresolvedElementsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection<ICommandAccess> proposals) { ITypeBinding declaringType= binding.getDeclaringClass(); ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode); ITypeBinding currType= parentType; boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers()); while (currType != null && !Bindings.isSuperType(declaringType, currType)) { if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) { return; } currType= currType.getDeclaringClass(); } if (currType == null || currType == parentType) { return; } ASTRewrite rewrite= ASTRewrite.create(invocationNode.getAST()); String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetoouter_description, ASTResolving.getTypeSignature(currType)); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_WITH_ENCLOSING_TYPE, image); ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot()); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(invocationNode, imports); AST ast= invocationNode.getAST(); String qualifier= imports.addImport(currType, importRewriteContext); Name name= ASTNodeFactory.newName(ast, qualifier); Expression newExpression; if (isInstanceMethod) { ThisExpression expr= ast.newThisExpression(); expr.setQualifier(name); newExpression= expr; } else { newExpression= name; } rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null); proposals.add(proposal); }
Example 18
Source File: LambdaExpressionsFix.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
/** * {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { ASTRewrite rewrite= cuRewrite.getASTRewrite(); ImportRemover importRemover= cuRewrite.getImportRemover(); AST ast= rewrite.getAST(); HashMap<ClassInstanceCreation, HashSet<String>> cicToNewNames= new HashMap<ClassInstanceCreation, HashSet<String>>(); for (int i= 0; i < fExpressions.size(); i++) { ClassInstanceCreation classInstanceCreation= fExpressions.get(i); TextEditGroup group= createTextEditGroup(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, cuRewrite); AnonymousClassDeclaration anonymTypeDecl= classInstanceCreation.getAnonymousClassDeclaration(); List<BodyDeclaration> bodyDeclarations= anonymTypeDecl.bodyDeclarations(); Object object= bodyDeclarations.get(0); if (!(object instanceof MethodDeclaration)) continue; MethodDeclaration methodDeclaration= (MethodDeclaration) object; HashSet<String> excludedNames= new HashSet<String>(); if (i != 0) { for (ClassInstanceCreation convertedCic : fExpressions.subList(0, i)) { if (ASTNodes.isParent(classInstanceCreation, convertedCic)) { excludedNames.addAll(cicToNewNames.get(convertedCic)); } } } HashSet<String> newNames= makeNamesUnique(excludedNames, methodDeclaration, rewrite, group); cicToNewNames.put(classInstanceCreation, new HashSet<String>(newNames)); List<SingleVariableDeclaration> methodParameters= methodDeclaration.parameters(); // use short form with inferred parameter types and without parentheses if possible LambdaExpression lambdaExpression= ast.newLambdaExpression(); List<VariableDeclaration> lambdaParameters= lambdaExpression.parameters(); lambdaExpression.setParentheses(methodParameters.size() != 1); for (SingleVariableDeclaration methodParameter : methodParameters) { VariableDeclarationFragment lambdaParameter= ast.newVariableDeclarationFragment(); lambdaParameter.setName((SimpleName) rewrite.createCopyTarget(methodParameter.getName())); lambdaParameters.add(lambdaParameter); } Block body= methodDeclaration.getBody(); List<Statement> statements= body.statements(); ASTNode lambdaBody= body; if (statements.size() == 1) { // use short form with just an expression body if possible Statement statement= statements.get(0); if (statement instanceof ExpressionStatement) { lambdaBody= ((ExpressionStatement) statement).getExpression(); } else if (statement instanceof ReturnStatement) { Expression returnExpression= ((ReturnStatement) statement).getExpression(); if (returnExpression != null) { lambdaBody= returnExpression; } } } //TODO: Bug 421479: [1.8][clean up][quick assist] convert anonymous to lambda must consider lost scope of interface // lambdaBody.accept(new InterfaceAccessQualifier(rewrite, classInstanceCreation.getType().resolveBinding())); //TODO: maybe need a separate ASTRewrite and string placeholder lambdaExpression.setBody(rewrite.createCopyTarget(lambdaBody)); Expression replacement= lambdaExpression; if (ASTNodes.isTargetAmbiguous(classInstanceCreation, lambdaParameters.isEmpty())) { CastExpression cast= ast.newCastExpression(); cast.setExpression(lambdaExpression); ImportRewrite importRewrite= cuRewrite.getImportRewrite(); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(classInstanceCreation, importRewrite); Type castType= importRewrite.addImport(classInstanceCreation.getType().resolveBinding(), ast, importRewriteContext); cast.setType(castType); importRemover.registerAddedImports(castType); replacement= cast; } rewrite.replace(classInstanceCreation, replacement, group); importRemover.registerRemovedNode(classInstanceCreation); importRemover.registerRetainedNode(lambdaBody); } }
Example 19
Source File: NewVariableCorrectionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private Type evaluateVariableType(AST ast, ImportRewrite imports, ImportRewriteContext importRewriteContext, IBinding targetContext) { 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) { for (int i= 0; i < bindings.length; i++) { addLinkedPositionProposal(KEY_TYPE, bindings[i]); } return imports.addImport(bindings[0], ast, importRewriteContext); } } } 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$ } } if (isVariableAssigned()) { ITypeBinding[] typeProposals= ASTResolving.getRelaxingTypes(ast, binding); for (int i= 0; i < typeProposals.length; i++) { addLinkedPositionProposal(KEY_TYPE, typeProposals[i]); } } return imports.addImport(binding, ast, importRewriteContext); } // 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$ }
Example 20
Source File: ExtractMethodAnalyzer.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
private void initReturnType(ImportRewrite rewriter) { AST ast = fEnclosingBodyDeclaration.getAST(); fReturnType = null; fReturnTypeBinding = null; switch (fReturnKind) { case ACCESS_TO_LOCAL: VariableDeclaration declaration = ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration); fReturnType = ASTNodeFactory.newType(ast, declaration, rewriter, new ContextSensitiveImportRewriteContext(declaration, rewriter)); if (declaration.resolveBinding() != null) { fReturnTypeBinding = declaration.resolveBinding().getType(); } break; case EXPRESSION: Expression expression = (Expression) getFirstSelectedNode(); if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) { fExpressionBinding = ((ClassInstanceCreation) expression).getType().resolveBinding(); } else { fExpressionBinding = expression.resolveTypeBinding(); } if (fExpressionBinding != null) { if (fExpressionBinding.isNullType()) { getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression)); } else { ITypeBinding normalizedBinding = Bindings.normalizeForDeclarationUse(fExpressionBinding, ast); if (normalizedBinding != null) { ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter); fReturnType = rewriter.addImport(normalizedBinding, ast, context, TypeLocation.RETURN_TYPE); fReturnTypeBinding = normalizedBinding; } } } else { fReturnType = ast.newPrimitiveType(PrimitiveType.VOID); fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$ getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression)); } break; case RETURN_STATEMENT_VALUE: LambdaExpression enclosingLambdaExpr = ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode()); if (enclosingLambdaExpr != null) { fReturnType = ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null); IMethodBinding methodBinding = enclosingLambdaExpr.resolveMethodBinding(); fReturnTypeBinding = methodBinding != null ? methodBinding.getReturnType() : null; } else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) { fReturnType = ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2(); fReturnTypeBinding = fReturnType != null ? fReturnType.resolveBinding() : null; } break; default: fReturnType = ast.newPrimitiveType(PrimitiveType.VOID); fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$ } if (fReturnType == null) { fReturnType = ast.newPrimitiveType(PrimitiveType.VOID); fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$ } }