Java Code Examples for org.eclipse.jdt.core.dom.CompilationUnit#getAST()

The following examples show how to use org.eclipse.jdt.core.dom.CompilationUnit#getAST() . 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: CopyResourceElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Updates the content of <code>cu</code>, modifying the type name and/or package
 * declaration as necessary.
 *
 * @return an AST rewrite or null if no rewrite needed
 */
private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName) throws JavaModelException {
	String[] currPackageName = ((PackageFragment) cu.getParent()).names;
	String[] destPackageName = dest.names;
	if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
		return null; //nothing to change
	} else {
		// ensure cu is consistent (noop if already consistent)
		cu.makeConsistent(this.progressMonitor);
		this.parser.setSource(cu);
		CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
		AST ast = astCU.getAST();
		ASTRewrite rewrite = ASTRewrite.create(ast);
		updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
		updatePackageStatement(astCU, destPackageName, rewrite, cu);
		return rewrite.rewriteAST();
	}
}
 
Example 2
Source File: CorrectMainTypeNameProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot= fContext.getASTRoot();

	AST ast= astRoot.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);

	AbstractTypeDeclaration decl= findTypeDeclaration(astRoot.types(), fOldName);
	if (decl != null) {
		ASTNode[] sameNodes= LinkedNodeFinder.findByNode(astRoot, decl.getName());
		for (int i= 0; i < sameNodes.length; i++) {
			rewrite.replace(sameNodes[i], ast.newSimpleName(fNewName), null);
		}
	}
	return rewrite;
}
 
Example 3
Source File: CorrectMainTypeNameProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot= fContext.getASTRoot();

	AST ast= astRoot.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);

	AbstractTypeDeclaration decl= findTypeDeclaration(astRoot.types(), fOldName);
	if (decl != null) {
		ASTNode[] sameNodes= LinkedNodeFinder.findByNode(astRoot, decl.getName());
		for (int i= 0; i < sameNodes.length; i++) {
			rewrite.replace(sameNodes[i], ast.newSimpleName(fNewName), null);
		}
	}
	return rewrite;
}
 
Example 4
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Perform the AST rewriting necessary on the given <code>CompilationUnit</code> to create the
 * factory method. The method will reside on the type identified by
 * <code>fFactoryOwningClass</code>.
 * 
 * @param unitRewriter the ASTRewrite to be used
 * @param unit the <code>CompilationUnit</code> where factory method will be created
 * @param gd the <code>GroupDescription</code> to associate with the changes made
 * @throws CoreException if an exception occurs while accessing its corresponding resource
 */
private void createFactoryChange(ASTRewrite unitRewriter, CompilationUnit unit, TextEditGroup gd) throws CoreException {
	// ================================================================================
	// First add the factory itself (method, class, and interface as needed/directed by user)
	AST				ast= unit.getAST();

	fFactoryMethod= createFactoryMethod(ast, fCtorBinding, unitRewriter);

	AbstractTypeDeclaration	factoryOwner= (AbstractTypeDeclaration) unit.findDeclaringNode(fFactoryOwningClass.resolveBinding().getKey());
	fImportRewriter.addImport(fCtorOwningClass.resolveBinding());

	int	idx= ASTNodes.getInsertionIndex(fFactoryMethod, factoryOwner.bodyDeclarations());

	if (idx < 0) idx= 0; // Guard against bug in getInsertionIndex()
	unitRewriter.getListRewrite(factoryOwner, factoryOwner.getBodyDeclarationsProperty()).insertAt(fFactoryMethod, idx, gd);
}
 
Example 5
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void updateType(CompilationUnit cu, Type oldType, CompilationUnitChange unitChange,
						ASTRewrite unitRewriter, String typeName) {

	String oldName= fSelectionTypeBinding.getName();
	String[] keys= { BasicElementLabels.getJavaElementName(oldName), BasicElementLabels.getJavaElementName(typeName)};
	String description= Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_typeChange, keys);
	TextEditGroup gd= new TextEditGroup(description);
	AST	ast= cu.getAST();

	ASTNode nodeToReplace= oldType;
	if (fSelectionTypeBinding.isParameterizedType() && !fSelectionTypeBinding.isRawType()){
		if (oldType.isSimpleType()){
			nodeToReplace= oldType.getParent();
		}
	}

    //TODO handle types other than simple & parameterized (e.g., arrays)
	Assert.isTrue(fSelectedType.isClass() || fSelectedType.isInterface());

	Type newType= null;
	if (!fSelectedType.isParameterizedType()){
		newType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeName));
	} else {
		newType= createParameterizedType(ast, fSelectedType);
	}

	unitRewriter.replace(nodeToReplace, newType, gd);
	unitChange.addTextEditGroup(gd);
}
 
Example 6
Source File: CopyResourceElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Renames the main type in <code>cu</code>.
 */
private void updateTypeName(ICompilationUnit cu, CompilationUnit astCU, String oldName, String newName, ASTRewrite rewriter) throws JavaModelException {
	if (newName != null) {
		String oldTypeName= Util.getNameWithoutJavaLikeExtension(oldName);
		String newTypeName= Util.getNameWithoutJavaLikeExtension(newName);
		AST ast = astCU.getAST();
		// update main type name
		IType[] types = cu.getTypes();
		for (int i = 0, max = types.length; i < max; i++) {
			IType currentType = types[i];
			if (currentType.getElementName().equals(oldTypeName)) {
				AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) ((JavaElement) currentType).findNode(astCU);
				if (typeNode != null) {
					// rename type
					rewriter.replace(typeNode.getName(), ast.newSimpleName(newTypeName), null);
					// rename constructors
					Iterator bodyDeclarations = typeNode.bodyDeclarations().iterator();
					while (bodyDeclarations.hasNext()) {
						Object bodyDeclaration = bodyDeclarations.next();
						if (bodyDeclaration instanceof MethodDeclaration) {
							MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
							if (methodDeclaration.isConstructor()) {
								SimpleName methodName = methodDeclaration.getName();
								if (methodName.getIdentifier().equals(oldTypeName)) {
									rewriter.replace(methodName, ast.newSimpleName(newTypeName), null);
								}
							}
						}
					}
				}
			}
		}
	}
}
 
Example 7
Source File: DeleteElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void deleteElement(IJavaElement elementToRemove, ICompilationUnit cu) throws JavaModelException {
	// ensure cu is consistent (noop if already consistent)
	cu.makeConsistent(this.progressMonitor);
	this.parser.setSource(cu);
	CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
	ASTNode node = ((JavaElement) elementToRemove).findNode(astCU);
	if (node == null)
		Assert.isTrue(false, "Failed to locate " + elementToRemove.getElementName() + " in " + cu.getElementName()); //$NON-NLS-1$//$NON-NLS-2$
	AST ast = astCU.getAST();
	ASTRewrite rewriter = ASTRewrite.create(ast);
	rewriter.remove(node, null);
		TextEdit edits = rewriter.rewriteAST();
		applyTextEdit(cu, edits);
}
 
Example 8
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private SingleVariableDeclaration createParameterDeclaration(String parameterName, VariableDeclarationFragment fragement, Expression arrayAccess, ForStatement statement, ImportRewrite importRewrite, ASTRewrite rewrite, TextEditGroup group, LinkedProposalPositionGroup pg, boolean makeFinal) {
	CompilationUnit compilationUnit= (CompilationUnit)arrayAccess.getRoot();
	AST ast= compilationUnit.getAST();

	SingleVariableDeclaration result= ast.newSingleVariableDeclaration();

	SimpleName name= ast.newSimpleName(parameterName);
	pg.addPosition(rewrite.track(name), true);
	result.setName(name);

	ITypeBinding arrayTypeBinding= arrayAccess.resolveTypeBinding();
	Type type= importType(arrayTypeBinding.getElementType(), statement, importRewrite, compilationUnit);
	if (arrayTypeBinding.getDimensions() != 1) {
		type= ast.newArrayType(type, arrayTypeBinding.getDimensions() - 1);
	}
	result.setType(type);

	if (fragement != null) {
		VariableDeclarationStatement declaration= (VariableDeclarationStatement)fragement.getParent();
		ModifierRewrite.create(rewrite, result).copyAllModifiers(declaration, group);
	}
	if (makeFinal && (fragement == null || ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(fragement)) == null)) {
		ModifierRewrite.create(rewrite, result).setModifiers(Modifier.FINAL, 0, group);
	}

	return result;
}
 
Example 9
Source File: NewCUProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private TextEdit constructEnclosingTypeEdit(ICompilationUnit icu) throws CoreException {
	ASTParser astParser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	astParser.setSource(icu);
	CompilationUnit cu = (CompilationUnit) astParser.createAST(null);
	TypeDeclaration enclosingDecl = findEnclosingTypeDeclaration(cu, fTypeContainer.getElementName());
	AST ast = cu.getAST();
	ASTRewrite rewrite = ASTRewrite.create(ast);
	final AbstractTypeDeclaration newDeclaration;
	switch (fTypeKind) {
		case K_CLASS:
			newDeclaration = ast.newTypeDeclaration();
			((TypeDeclaration) newDeclaration).setInterface(false);
			break;
		case K_INTERFACE:
			newDeclaration = ast.newTypeDeclaration();
			((TypeDeclaration) newDeclaration).setInterface(true);
			break;
		case K_ENUM:
			newDeclaration = ast.newEnumDeclaration();
			break;
		case K_ANNOTATION:
			newDeclaration = ast.newAnnotationTypeDeclaration();
			break;
		default:
			return null;
	}
	newDeclaration.setJavadoc(null);
	newDeclaration.setName(ast.newSimpleName(ASTNodes.getSimpleNameIdentifier(fNode)));
	newDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
	if (isParameterizedType(fTypeKind, fNode)) {
		addTypeParameters((TypeDeclaration) newDeclaration);
	}

	ListRewrite lrw = rewrite.getListRewrite(enclosingDecl, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	lrw.insertLast(newDeclaration, null);
	return rewrite.rewriteAST();
}
 
Example 10
Source File: GenerateBuilderExecutorImpl.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
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 11
Source File: ChangeAsyncMethodReturnTypeProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@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 12
Source File: BaseTranslator.java    From junion with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public BaseTranslator(CompilationUnit cu, Document doc, String sourceFileName) {
	this.cu = cu;
	this.doc = doc;
	this.sourceFileName = sourceFileName;
	this.ast = cu.getAST();
}
 
Example 13
Source File: OrganizeImportsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
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 14
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addStaticImportFavoriteProposals(IInvocationContext context, SimpleName node, boolean isMethod,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	IJavaProject project= context.getCompilationUnit().getJavaProject();
	if (JavaModelUtil.is50OrHigher(project)) {
		String[] favourites = PreferenceManager.getPrefs(context.getCompilationUnit().getResource())
				.getJavaCompletionFavoriteMembers();
		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 = CodeStyleConfiguration.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);
			}

			ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix,
					context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_STATIC_IMPORT);
			proposal.setImportRewrite(importRewrite);
			proposals.add(proposal);
		}
	}
}
 
Example 15
Source File: ReturnTypeSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addMissingReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();

	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (selectedNode == null) {
		return;
	}
	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methodDeclaration= (MethodDeclaration) decl;

		ReturnStatementCollector eval= new ReturnStatementCollector();
		decl.accept(eval);

		AST ast= astRoot.getAST();

		ITypeBinding typeBinding= eval.getTypeBinding(decl.getAST());
		typeBinding= Bindings.normalizeTypeBinding(typeBinding);
		if (typeBinding == null) {
			typeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
		}
		if (typeBinding.isWildcardType()) {
			typeBinding= ASTResolving.normalizeWildcardType(typeBinding, true, ast);
		}

		ASTRewrite rewrite= ASTRewrite.create(ast);

		String label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_missingreturntype_description, BindingLabelProvider.getBindingLabel(typeBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.MISSING_RETURN_TYPE, image);

		ImportRewrite imports= proposal.createImportRewrite(astRoot);
		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports);
		Type type= imports.addImport(typeBinding, ast, importRewriteContext);

		rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, type, null);
		rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);

		Javadoc javadoc= methodDeclaration.getJavadoc();
		if (javadoc != null && typeBinding != null) {
			TagElement newTag= ast.newTagElement();
			newTag.setTagName(TagElement.TAG_RETURN);
			TextElement commentStart= ast.newTextElement();
			newTag.fragments().add(commentStart);

			JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
			proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); //$NON-NLS-1$
		}

		String key= "return_type"; //$NON-NLS-1$
		proposal.addLinkedPosition(rewrite.track(type), true, key);
		if (typeBinding != null) {
			ITypeBinding[] bindings= ASTResolving.getRelaxingTypes(ast, typeBinding);
			for (int i= 0; i < bindings.length; i++) {
				proposal.addLinkedPositionProposal(key, bindings[i]);
			}
		}

		proposals.add(proposal);

		// change to constructor
		ASTNode parentType= ASTResolving.findParentType(decl);
		if (parentType instanceof AbstractTypeDeclaration) {
			boolean isInterface= parentType instanceof TypeDeclaration && ((TypeDeclaration) parentType).isInterface();
			if (!isInterface) {
				String constructorName= ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
				ASTNode nameNode= methodDeclaration.getName();
				label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_wrongconstructorname_description, BasicElementLabels.getJavaElementName(constructorName));
				proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, IProposalRelevance.CHANGE_TO_CONSTRUCTOR));
			}
		}
	}
}
 
Example 16
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
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 17
Source File: NewVariableCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTRewrite doAddParam(CompilationUnit cu) {
	AST ast= cu.getAST();
	SimpleName node= fOriginalNode;

	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methodDeclaration= (MethodDeclaration) decl;

		ASTRewrite rewrite= ASTRewrite.create(ast);

		ImportRewrite imports= createImportRewrite((CompilationUnit) decl.getRoot());
		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports);

		SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration();
		newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, methodDeclaration.resolveBinding()));
		newDecl.setName(ast.newSimpleName(node.getIdentifier()));

		ListRewrite listRewriter= rewrite.getListRewrite(decl, MethodDeclaration.PARAMETERS_PROPERTY);
		listRewriter.insertLast(newDecl, null);

		addLinkedPosition(rewrite.track(node), true, KEY_NAME);

		// add javadoc tag
		Javadoc javadoc= methodDeclaration.getJavadoc();
		if (javadoc != null) {
			HashSet<String> leadingNames= new HashSet<String>();
			for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
				SingleVariableDeclaration curr= iter.next();
				leadingNames.add(curr.getName().getIdentifier());
			}
			SimpleName newTagRef= ast.newSimpleName(node.getIdentifier());

			TagElement newTagElement= ast.newTagElement();
			newTagElement.setTagName(TagElement.TAG_PARAM);
			newTagElement.fragments().add(newTagRef);
			TextElement commentStart= ast.newTextElement();
			newTagElement.fragments().add(commentStart);

			addLinkedPosition(rewrite.track(newTagRef), false, KEY_NAME);
			addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); //$NON-NLS-1$

			ListRewrite tagsRewriter= rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
			JavadocTagsSubProcessor.insertTag(tagsRewriter, newTagElement, leadingNames);
		}
		
		addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
		addLinkedPosition(rewrite.track(newDecl.getName()), false, KEY_NAME);

		return rewrite;
	}
	return null;
}
 
Example 18
Source File: NewVariableCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ASTRewrite doAddParam(CompilationUnit cu) {
	AST ast= cu.getAST();
	SimpleName node= fOriginalNode;

	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methodDeclaration= (MethodDeclaration) decl;

		ASTRewrite rewrite= ASTRewrite.create(ast);

		ImportRewrite imports= createImportRewrite((CompilationUnit) decl.getRoot());
		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports);

		SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration();
		newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, methodDeclaration.resolveBinding(), TypeLocation.PARAMETER));
		newDecl.setName(ast.newSimpleName(node.getIdentifier()));

		ListRewrite listRewriter= rewrite.getListRewrite(decl, MethodDeclaration.PARAMETERS_PROPERTY);
		listRewriter.insertLast(newDecl, null);

		// add javadoc tag
		Javadoc javadoc= methodDeclaration.getJavadoc();
		if (javadoc != null) {
			HashSet<String> leadingNames= new HashSet<>();
			for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
				SingleVariableDeclaration curr= iter.next();
				leadingNames.add(curr.getName().getIdentifier());
			}
			SimpleName newTagRef= ast.newSimpleName(node.getIdentifier());

			TagElement newTagElement= ast.newTagElement();
			newTagElement.setTagName(TagElement.TAG_PARAM);
			newTagElement.fragments().add(newTagRef);
			TextElement commentStart= ast.newTextElement();
			newTagElement.fragments().add(commentStart);

			ListRewrite tagsRewriter= rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
			JavadocTagsSubProcessor.insertTag(tagsRewriter, newTagElement, leadingNames);
		}

		return rewrite;
	}
	return null;
}
 
Example 19
Source File: ReturnTypeSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static void addMissingReturnTypeProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();

	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (selectedNode == null) {
		return;
	}
	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methodDeclaration= (MethodDeclaration) decl;

		ReturnStatementCollector eval= new ReturnStatementCollector();
		decl.accept(eval);

		AST ast= astRoot.getAST();

		ITypeBinding typeBinding= eval.getTypeBinding(decl.getAST());
		typeBinding= Bindings.normalizeTypeBinding(typeBinding);
		if (typeBinding == null) {
			typeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
		}
		if (typeBinding.isWildcardType()) {
			typeBinding= ASTResolving.normalizeWildcardType(typeBinding, true, ast);
		}

		ASTRewrite rewrite= ASTRewrite.create(ast);

		String label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_missingreturntype_description, BindingLabelProviderCore.getBindingLabel(typeBinding, BindingLabelProviderCore.DEFAULT_TEXTFLAGS));
		LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, CodeActionKind.QuickFix, cu, rewrite, IProposalRelevance.MISSING_RETURN_TYPE);

		ImportRewrite imports= proposal.createImportRewrite(astRoot);
		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports);
		Type type= imports.addImport(typeBinding, ast, importRewriteContext, TypeLocation.RETURN_TYPE);

		rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, type, null);
		rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);

		Javadoc javadoc= methodDeclaration.getJavadoc();
		if (javadoc != null && typeBinding != null) {
			TagElement newTag= ast.newTagElement();
			newTag.setTagName(TagElement.TAG_RETURN);
			TextElement commentStart= ast.newTextElement();
			newTag.fragments().add(commentStart);

			JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
			proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); //$NON-NLS-1$
		}

		String key= "return_type"; //$NON-NLS-1$
		proposal.addLinkedPosition(rewrite.track(type), true, key);
		if (typeBinding != null) {
			ITypeBinding[] bindings= ASTResolving.getRelaxingTypes(ast, typeBinding);
			for (int i= 0; i < bindings.length; i++) {
				proposal.addLinkedPositionProposal(key, bindings[i]);
			}
		}

		proposals.add(proposal);

		// change to constructor
		ASTNode parentType= ASTResolving.findParentType(decl);
		if (parentType instanceof AbstractTypeDeclaration) {
			boolean isInterface= parentType instanceof TypeDeclaration && ((TypeDeclaration) parentType).isInterface();
			if (!isInterface) {
				String constructorName= ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
				ASTNode nameNode= methodDeclaration.getName();
				label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_wrongconstructorname_description, BasicElementLabels.getJavaElementName(constructorName));
				proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, IProposalRelevance.CHANGE_TO_CONSTRUCTOR));
			}
		}
	}
}