Java Code Examples for org.eclipse.jdt.core.dom.rewrite.ASTRewrite#create()
The following examples show how to use
org.eclipse.jdt.core.dom.rewrite.ASTRewrite#create() .
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: MissingAnnotationAttributesProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
@Override protected ASTRewrite getRewrite() throws CoreException { AST ast= fAnnotation.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); createImportRewrite((CompilationUnit) fAnnotation.getRoot()); ListRewrite listRewrite; if (fAnnotation instanceof NormalAnnotation) { listRewrite= rewrite.getListRewrite(fAnnotation, NormalAnnotation.VALUES_PROPERTY); } else { NormalAnnotation newAnnotation= ast.newNormalAnnotation(); newAnnotation.setTypeName((Name) rewrite.createMoveTarget(fAnnotation.getTypeName())); rewrite.replace(fAnnotation, newAnnotation, null); listRewrite= rewrite.getListRewrite(newAnnotation, NormalAnnotation.VALUES_PROPERTY); } addMissingAtributes(fAnnotation.resolveTypeBinding(), listRewrite); return rewrite; }
Example 2
Source File: MoveMethodRefactoring.java From JDeodorant with MIT License | 6 votes |
private void removeSourceMethod() { ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST()); ListRewrite classBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); classBodyRewrite.remove(sourceMethod, null); Set<MethodDeclaration> methodsToBeMoved = new LinkedHashSet<MethodDeclaration>(additionalMethodsToBeMoved.values()); for(MethodDeclaration methodDeclaration : methodsToBeMoved) { classBodyRewrite.remove(methodDeclaration, null); } try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); sourceMultiTextEdit.addChild(sourceEdit); sourceCompilationUnitChange.addTextEditGroup(new TextEditGroup("Remove moved method", new TextEdit[] {sourceEdit})); } catch(JavaModelException javaModelException) { javaModelException.printStackTrace(); } }
Example 3
Source File: ReplaceTypeCodeWithStateStrategy.java From JDeodorant with MIT License | 6 votes |
private void createStateField() { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); AST contextAST = sourceTypeDeclaration.getAST(); ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST); FieldDeclaration typeFieldDeclaration = contextAST.newFieldDeclaration(typeFragment); sourceRewriter.set(typeFieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null); ListRewrite typeFieldDeclarationModifiersRewrite = sourceRewriter.getListRewrite(typeFieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); typeFieldDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD), null); contextBodyRewrite.insertBefore(typeFieldDeclaration, typeCheckElimination.getTypeField().getParent(), null); try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Create field holding the current state", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } }
Example 4
Source File: AbstractCreateMethodProposal.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
@Override protected ASTRewrite getRewrite() { CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST( getCompilationUnit(), null); createImportRewrite(targetAstRoot); // Find the target type declaration TypeDeclaration typeDecl = JavaASTUtils.findTypeDeclaration(targetAstRoot, targetQualifiedTypeName); if (typeDecl == null) { return null; } ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST()); // Generate the new method declaration MethodDeclaration methodDecl = createMethodDeclaration(rewrite.getAST()); // Add the new method declaration to the interface ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(typeDecl); ListRewrite listRewriter = rewrite.getListRewrite(typeDecl, property); listRewriter.insertLast(methodDecl, null); return rewrite; }
Example 5
Source File: ChangeUtil.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private static void convertMoveCompilationUnitChange(WorkspaceEdit edit, MoveCompilationUnitChange change) throws JavaModelException { IPackageFragment newPackage = change.getDestinationPackage(); ICompilationUnit unit = change.getCu(); CompilationUnit astCU = RefactoringASTParser.parseWithASTProvider(unit, true, new NullProgressMonitor()); ASTRewrite rewrite = ASTRewrite.create(astCU.getAST()); IPackageDeclaration[] packDecls = unit.getPackageDeclarations(); String oldPackageName = packDecls.length > 0 ? packDecls[0].getElementName() : ""; if (!Objects.equals(oldPackageName, newPackage.getElementName())) { // update the package declaration if (updatePackageStatement(astCU, newPackage.getElementName(), rewrite, unit)) { convertTextEdit(edit, unit, rewrite.rewriteAST()); } } RenameFile cuResourceChange = new RenameFile(); cuResourceChange.setOldUri(JDTUtils.toURI(unit)); IPath newCUPath = newPackage.getResource().getLocation().append(unit.getPath().lastSegment()); String newUri = ResourceUtils.fixURI(newCUPath.toFile().toURI()); cuResourceChange.setNewUri(newUri); edit.getDocumentChanges().add(Either.forRight(cuResourceChange)); }
Example 6
Source File: LocalCorrectionsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (!(selectedNode instanceof Name)) { return; } Name name= (Name) selectedNode; IBinding binding= name.resolveBinding(); if (!(binding instanceof IVariableBinding)) { return; } IVariableBinding varBinding= (IVariableBinding) binding; CompilationUnit astRoot= context.getASTRoot(); ASTNode node= astRoot.findDeclaringNode(binding); if (node instanceof VariableDeclarationFragment) { ASTRewrite rewrite= ASTRewrite.create(node.getAST()); VariableDeclarationFragment fragment= (VariableDeclarationFragment) node; if (fragment.getInitializer() != null) { return; } Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType()); if (expression == null) { return; } rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null); String label= CorrectionMessages.LocalCorrectionsSubProcessor_uninitializedvariable_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.INITIALIZE_VARIABLE, image); proposal.addLinkedPosition(rewrite.track(expression), false, "initializer"); //$NON-NLS-1$ proposals.add(proposal); } }
Example 7
Source File: GenerateForLoopAssistProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Helper to generate an iterator based <code>for</code> loop to iterate over an * {@link Iterable}. * * @param ast the {@link AST} instance to rewrite the loop to * @return the complete {@link ASTRewrite} object */ private ASTRewrite generateIteratorBasedForRewrite(AST ast) { ASTRewrite rewrite= ASTRewrite.create(ast); ForStatement loopStatement= ast.newForStatement(); ITypeBinding loopOverType= extractElementType(ast); SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "iterator", null, true); //$NON-NLS-1$ loopStatement.initializers().add(getIteratorBasedForInitializer(rewrite, loopVariableName)); MethodInvocation loopExpression= ast.newMethodInvocation(); loopExpression.setName(ast.newSimpleName("hasNext")); //$NON-NLS-1$ SimpleName expressionName= ast.newSimpleName(loopVariableName.getIdentifier()); addLinkedPosition(rewrite.track(expressionName), LinkedPositionGroup.NO_STOP, expressionName.getIdentifier()); loopExpression.setExpression(expressionName); loopStatement.setExpression(loopExpression); Block forLoopBody= ast.newBlock(); Assignment assignResolvedVariable= getIteratorBasedForBodyAssignment(rewrite, loopOverType, loopVariableName); forLoopBody.statements().add(ast.newExpressionStatement(assignResolvedVariable)); forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite)); loopStatement.setBody(forLoopBody); rewrite.replace(fCurrentNode, loopStatement, null); return rewrite; }
Example 8
Source File: SuppressWarningsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Adds a proposal to correct the name of the SuppressWarning annotation * @param context the context * @param problem the problem * @param proposals the resulting proposals */ public static void addUnknownSuppressWarningProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ASTNode coveringNode= context.getCoveringNode(); if (!(coveringNode instanceof StringLiteral)) return; AST ast= coveringNode.getAST(); StringLiteral literal= (StringLiteral) coveringNode; String literalValue= literal.getLiteralValue(); String[] allWarningTokens= CorrectionEngine.getAllWarningTokens(); for (int i= 0; i < allWarningTokens.length; i++) { String curr= allWarningTokens[i]; if (NameMatcher.isSimilarName(literalValue, curr)) { StringLiteral newLiteral= ast.newStringLiteral(); newLiteral.setLiteralValue(curr); ASTRewrite rewrite= ASTRewrite.create(ast); rewrite.replace(literal, newLiteral, null); String label= Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_fix_suppress_token_label, new String[] { curr }); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.FIX_SUPPRESS_TOKEN, image); proposals.add(proposal); } } addRemoveUnusedSuppressWarningProposals(context, problem, proposals); }
Example 9
Source File: GenerateBuilderExecutorImpl.java From SparkBuilderGenerator with MIT License | 5 votes |
private void addBuilder(ICompilationUnit iCompilationUnit, BuilderType builderType) { CompilationUnit compilationUnit = compilationUnitParser.parse(iCompilationUnit); AST ast = compilationUnit.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); CompilationUnitModificationDomain compilationUnitModificationDomain = builderOwnerClassFinder.provideBuilderOwnerClass(compilationUnit, ast, rewriter, iCompilationUnit); builderGenerators.stream() .filter(builderGenerator -> builderGenerator.canHandle(builderType)) .findFirst() .orElseThrow(() -> new IllegalStateException("No builder generator can handle " + builderType)) .generateBuilder(compilationUnitModificationDomain); compilationUnitSourceSetter.commitCodeChange(iCompilationUnit, rewriter); }
Example 10
Source File: ReplaceTypeCodeWithStateStrategy.java From JDeodorant with MIT License | 5 votes |
private void removePrimitiveStateField() { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); AST contextAST = sourceTypeDeclaration.getAST(); ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); FieldDeclaration[] fieldDeclarations = sourceTypeDeclaration.getFields(); for(FieldDeclaration fieldDeclaration : fieldDeclarations) { List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); for(VariableDeclarationFragment fragment : fragments) { if(fragment.equals(typeCheckElimination.getTypeField())) { if(fragments.size() == 1) { contextBodyRewrite.remove(fragment.getParent(), null); } else { ListRewrite fragmentRewrite = sourceRewriter.getListRewrite(fragment.getParent(), FieldDeclaration.FRAGMENTS_PROPERTY); fragmentRewrite.remove(fragment, null); } } } } try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Remove primitive field holding the current state", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } }
Example 11
Source File: JavadocTagsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Override protected ASTRewrite getRewrite() throws CoreException { AST ast= fBodyDecl.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); insertMissingJavadocTag(rewrite, fMissingNode, fBodyDecl); return rewrite; }
Example 12
Source File: JavadocTagsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@Override protected ASTRewrite getRewrite() throws CoreException { AST ast= fBodyDecl.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); insertMissingJavadocTag(rewrite, fMissingNode, fBodyDecl); return rewrite; }
Example 13
Source File: AddImportCorrectionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
public AddImportCorrectionProposal(String name, ICompilationUnit cu, int relevance, String qualifierName, String typeName, SimpleName node) { super(name, CodeActionKind.QuickFix, cu, ASTRewrite.create(node.getAST()), relevance); fTypeName= typeName; fQualifierName= qualifierName; }
Example 14
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 15
Source File: UnresolvedElementsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private static void addStaticImportFavoriteProposals(IInvocationContext context, SimpleName node, boolean isMethod, Collection<ICommandAccess> proposals) throws JavaModelException { IJavaProject project= context.getCompilationUnit().getJavaProject(); if (JavaModelUtil.is50OrHigher(project)) { String pref= PreferenceConstants.getPreference(PreferenceConstants.CODEASSIST_FAVORITE_STATIC_MEMBERS, project); String[] favourites= pref.split(";"); //$NON-NLS-1$ if (favourites.length == 0) { return; } CompilationUnit root= context.getASTRoot(); AST ast= root.getAST(); String name= node.getIdentifier(); String[] staticImports= SimilarElementsRequestor.getStaticImportFavorites(context.getCompilationUnit(), name, isMethod, favourites); for (int i= 0; i < staticImports.length; i++) { String curr= staticImports[i]; ImportRewrite importRewrite= StubUtility.createImportRewrite(root, true); ASTRewrite astRewrite= ASTRewrite.create(ast); String label; String qualifiedTypeName= Signature.getQualifier(curr); String elementLabel= BasicElementLabels.getJavaElementName(JavaModelUtil.concatenateName(Signature.getSimpleName(qualifiedTypeName), name)); 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); label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_change_to_static_import_description, elementLabel); } else { label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_add_static_import_description, elementLabel); } Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_STATIC_IMPORT, image); proposal.setImportRewrite(importRewrite); proposals.add(proposal); } } }
Example 16
Source File: SelfEncapsulateFieldRefactoring.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask(NO_NAME, 12); pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions); RefactoringStatus result = new RefactoringStatus(); fRewriter = ASTRewrite.create(fRoot.getAST()); fChangeManager.clear(); boolean usingLocalGetter = isUsingLocalGetter(); boolean usingLocalSetter = isUsingLocalSetter(); result.merge(checkMethodNames(usingLocalGetter, usingLocalSetter)); pm.worked(1); if (result.hasFatalError()) { return result; } pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits); final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5); ICompilationUnit[] affectedCUs = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(fField, fConsiderVisibility), subPm, result, true); checkInHierarchy(result, usingLocalGetter, usingLocalSetter); if (result.hasFatalError()) { return result; } pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing); IProgressMonitor sub = new SubProgressMonitor(pm, 5); sub.beginTask(NO_NAME, affectedCUs.length); IVariableBinding fieldIdentifier = fFieldDeclaration.resolveBinding(); ITypeBinding declaringClass = ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class).resolveBinding(); List<TextEditGroup> ownerDescriptions = new ArrayList<>(); ICompilationUnit owner = fField.getCompilationUnit(); fImportRewrite = StubUtility.createImportRewrite(fRoot, true); for (int i = 0; i < affectedCUs.length; i++) { ICompilationUnit unit = affectedCUs[i]; sub.subTask(BasicElementLabels.getFileName(unit)); CompilationUnit root = null; ASTRewrite rewriter = null; ImportRewrite importRewrite; List<TextEditGroup> descriptions; if (owner.equals(unit)) { root = fRoot; rewriter = fRewriter; importRewrite = fImportRewrite; descriptions = ownerDescriptions; } else { root = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(unit, true); rewriter = ASTRewrite.create(root.getAST()); descriptions = new ArrayList<>(); importRewrite = StubUtility.createImportRewrite(root, true); } checkCompileErrors(result, root, unit); AccessAnalyzer analyzer = new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite); root.accept(analyzer); result.merge(analyzer.getStatus()); if (!fSetterMustReturnValue) { fSetterMustReturnValue= analyzer.getSetterMustReturnValue(); } if (result.hasFatalError()) { fChangeManager.clear(); return result; } descriptions.addAll(analyzer.getGroupDescriptions()); if (!owner.equals(unit)) { createEdits(unit, rewriter, descriptions, importRewrite); } sub.worked(1); if (pm.isCanceled()) { throw new OperationCanceledException(); } } ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(), usingLocalSetter, usingLocalGetter)); createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite); sub.done(); IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()); result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext(), pm)); if (result.hasFatalError()) { return result; } ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)); return result; }
Example 17
Source File: UnresolvedElementsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection<ChangeCorrectionProposal> proposals) { ITypeBinding castType= expression.getType().resolveBinding(); if (castType == null) { return false; } if (paramTypes != null) { if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) { return false; } } else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) { return false; } ITypeBinding bindingToCast= accessExpression.resolveTypeBinding(); if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) { return false; } IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes); if (res != null) { AST ast= expression.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); CastExpression newCast= ast.newCastExpression(); newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType())); newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression)); ParenthesizedExpression parents= ast.newParenthesizedExpression(); parents.setExpression(newCast); ASTNode node= rewrite.createCopyTarget(expression.getExpression()); rewrite.replace(expression, node, null); rewrite.replace(accessExpression, parents, null); String label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description; ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, rewrite, IProposalRelevance.ADD_PARENTHESES_AROUND_CAST); proposals.add(proposal); return true; } return false; }
Example 18
Source File: ChangeAsyncMethodReturnTypeProposal.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 4 votes |
@Override protected ASTRewrite getRewrite() throws CoreException { CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST( getCompilationUnit(), null); AST ast = targetAstRoot.getAST(); createImportRewrite(targetAstRoot); ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST()); // Find the method declaration in the AST we just generated (the one that // the AST rewriter is hooked up to). MethodDeclaration rewriterAstMethodDecl = JavaASTUtils.findMethodDeclaration( targetAstRoot, methodDecl.resolveBinding().getKey()); if (rewriterAstMethodDecl == null) { return null; } // Set up the list of valid return types List<ITypeBinding> validReturnTypeBindings = new ArrayList<ITypeBinding>(); validReturnTypeBindings.add(ast.resolveWellKnownType("void")); IJavaProject javaProject = getCompilationUnit().getJavaProject(); ITypeBinding requestBinding = JavaASTUtils.resolveType(javaProject, "com.google.gwt.http.client.Request"); if (requestBinding != null) { validReturnTypeBindings.add(requestBinding); } ITypeBinding requestBuilderBinding = JavaASTUtils.resolveType(javaProject, "com.google.gwt.http.client.RequestBuilder"); if (requestBuilderBinding != null) { validReturnTypeBindings.add(requestBuilderBinding); } // Set default proposal return type Type newReturnType = getImportRewrite().addImport( validReturnTypeBindings.get(0), ast); rewrite.replace(rewriterAstMethodDecl.getReturnType2(), newReturnType, null); // Use linked mode to choose from one of the other valid return types String key = "return_type"; addLinkedPosition(rewrite.track(newReturnType), true, key); for (ITypeBinding binding : validReturnTypeBindings) { addLinkedPositionProposal(key, binding); } return rewrite; }
Example 19
Source File: OrganizeImportsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
public static TextEdit wrapStaticImports(TextEdit edit, CompilationUnit root, ICompilationUnit unit) throws MalformedTreeException, CoreException { String[] favourites = PreferenceManager.getPrefs(unit.getResource()).getJavaCompletionFavoriteMembers(); if (favourites.length == 0) { return edit; } IJavaProject project = unit.getJavaProject(); if (JavaModelUtil.is50OrHigher(project)) { List<SimpleName> typeReferences = new ArrayList<>(); List<SimpleName> staticReferences = new ArrayList<>(); ImportReferencesCollector.collect(root, project, null, typeReferences, staticReferences); if (staticReferences.isEmpty()) { return edit; } ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(root, true); AST ast = root.getAST(); ASTRewrite astRewrite = ASTRewrite.create(ast); for (SimpleName node : staticReferences) { addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, true); addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, false); } TextEdit staticEdit = importRewrite.rewriteImports(null); if (staticEdit != null && staticEdit.getChildrenSize() > 0) { TextEdit lastStatic = staticEdit.getChildren()[staticEdit.getChildrenSize() - 1]; if (lastStatic instanceof DeleteEdit) { if (edit.getChildrenSize() > 0) { TextEdit last = edit.getChildren()[edit.getChildrenSize() - 1]; if (last instanceof DeleteEdit && lastStatic.getOffset() == last.getOffset() && lastStatic.getLength() == last.getLength()) { edit.removeChild(last); } } } TextEdit firstStatic = staticEdit.getChildren()[0]; if (firstStatic instanceof InsertEdit) { if (edit.getChildrenSize() > 0) { TextEdit firstEdit = edit.getChildren()[0]; if (firstEdit instanceof InsertEdit) { if (areEqual((InsertEdit) firstEdit, (InsertEdit) firstStatic)) { edit.removeChild(firstEdit); } } } } try { staticEdit.addChild(edit); return staticEdit; } catch (MalformedTreeException e) { JavaLanguageServerPlugin.logException("Failed to resolve static organize imports source action", e); } } } return edit; }
Example 20
Source File: NewVariableCorrectionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
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; }