Java Code Examples for org.eclipse.jdt.internal.corext.dom.ASTNodes#getNormalizedNode()

The following examples show how to use org.eclipse.jdt.internal.corext.dom.ASTNodes#getNormalizedNode() . 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: TypeArgumentMismatchSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void removeMismatchedArguments(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals){
	ICompilationUnit cu= context.getCompilationUnit();
	ASTNode selectedNode= problem.getCoveredNode(context.getASTRoot());
	if (!(selectedNode instanceof SimpleName)) {
		return;
	}

	ASTNode normalizedNode=ASTNodes.getNormalizedNode(selectedNode);
	if (normalizedNode instanceof ParameterizedType) {
		ASTRewrite rewrite = ASTRewrite.create(normalizedNode.getAST());
		ParameterizedType pt = (ParameterizedType) normalizedNode;
		ASTNode mt = rewrite.createMoveTarget(pt.getType());
		rewrite.replace(pt, mt, null);
		String label= CorrectionMessages.TypeArgumentMismatchSubProcessor_removeTypeArguments;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_TYPE_ARGUMENTS, image);
		proposals.add(proposal);
	}
}
 
Example 2
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addRedundantSuperInterfaceProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (!(selectedNode instanceof Name)) {
		return;
	}
	ASTNode node= ASTNodes.getNormalizedNode(selectedNode);

	ASTRewrite rewrite= ASTRewrite.create(node.getAST());
	rewrite.remove(node, null);

	String label= CorrectionMessages.LocalCorrectionsSubProcessor_remove_redundant_superinterface;
	Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);

	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_REDUNDANT_SUPER_INTERFACE, image);
	proposals.add(proposal);

}
 
Example 3
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IBinding resolveBinding(ASTNode node) {
	if (node instanceof SimpleName) {
		SimpleName simpleName= (SimpleName) node;
		// workaround for https://bugs.eclipse.org/62605 (constructor name resolves to type, not method)
		ASTNode normalized= ASTNodes.getNormalizedNode(simpleName);
		if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
			ClassInstanceCreation cic= (ClassInstanceCreation) normalized.getParent();
			IMethodBinding constructorBinding= cic.resolveConstructorBinding();
			if (constructorBinding == null)
				return null;
			ITypeBinding declaringClass= constructorBinding.getDeclaringClass();
			if (!declaringClass.isAnonymous())
				return constructorBinding;
			ITypeBinding superTypeDeclaration= declaringClass.getSuperclass().getTypeDeclaration();
			return resolveSuperclassConstructor(superTypeDeclaration, constructorBinding);
		}
		return simpleName.resolveBinding();
		
	} else if (node instanceof SuperConstructorInvocation) {
		return ((SuperConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof ConstructorInvocation) {
		return ((ConstructorInvocation) node).resolveConstructorBinding();
	} else {
		return null;
	}
}
 
Example 4
Source File: ImplementOccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public String initialize(CompilationUnit root, ASTNode node) {
	if (!(node instanceof Name))
		return SearchMessages.ImplementOccurrencesFinder_invalidTarget;

	fSelectedNode= ASTNodes.getNormalizedNode(node);
	if (!(fSelectedNode instanceof Type))
		return SearchMessages.ImplementOccurrencesFinder_invalidTarget;

	StructuralPropertyDescriptor location= fSelectedNode.getLocationInParent();
	if (location != TypeDeclaration.SUPERCLASS_TYPE_PROPERTY && location != TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY && location != EnumDeclaration.SUPER_INTERFACE_TYPES_PROPERTY)
		return SearchMessages.ImplementOccurrencesFinder_invalidTarget;

	fSelectedType= ((Type)fSelectedNode).resolveBinding();
	if (fSelectedType == null)
		return SearchMessages.ImplementOccurrencesFinder_invalidTarget;

	fStart= fSelectedNode.getParent(); // type declaration
	fASTRoot= root;
	fDescription= Messages.format(SearchMessages.ImplementOccurrencesFinder_occurrence_description, BasicElementLabels.getJavaElementName(fSelectedType.getName()));

	return null;
}
 
Example 5
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds and returns the <code>ASTNode</code> for the given source text
 * selection, if it is an entire constructor call or the class name portion
 * of a constructor call or constructor declaration, or null otherwise.
 * @param unit The compilation unit in which the selection was made
 * @param offset The textual offset of the start of the selection
 * @param length The length of the selection in characters
 * @return ClassInstanceCreation or MethodDeclaration
 */
private ASTNode getTargetNode(ICompilationUnit unit, int offset, int length) {
	ASTNode node= ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length));
	if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
		return node;
	if (node.getNodeType() == ASTNode.METHOD_DECLARATION && ((MethodDeclaration)node).isConstructor())
		return node;
	// we have some sub node. Make sure its the right child of the parent
	StructuralPropertyDescriptor location= node.getLocationInParent();
	ASTNode parent= node.getParent();
	if (location == ClassInstanceCreation.TYPE_PROPERTY) {
		return parent;
	} else if (location == MethodDeclaration.NAME_PROPERTY && ((MethodDeclaration)parent).isConstructor()) {
		return parent;
	}
	return null;
}
 
Example 6
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IBinding resolveBinding(ASTNode node) {
	if (node instanceof SimpleName) {
		SimpleName simpleName = (SimpleName) node;
		// workaround for https://bugs.eclipse.org/62605 (constructor name resolves to type, not method)
		ASTNode normalized = ASTNodes.getNormalizedNode(simpleName);
		if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
			ClassInstanceCreation cic = (ClassInstanceCreation) normalized.getParent();
			IMethodBinding constructorBinding = cic.resolveConstructorBinding();
			if (constructorBinding == null) {
				return null;
			}
			ITypeBinding declaringClass = constructorBinding.getDeclaringClass();
			if (!declaringClass.isAnonymous()) {
				return constructorBinding;
			}
			ITypeBinding superTypeDeclaration = declaringClass.getSuperclass().getTypeDeclaration();
			return resolveSuperclassConstructor(superTypeDeclaration, constructorBinding);
		}
		return simpleName.resolveBinding();

	} else if (node instanceof SuperConstructorInvocation) {
		return ((SuperConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof ConstructorInvocation) {
		return ((ConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof LambdaExpression) {
		return ((LambdaExpression) node).resolveMethodBinding();
	} else {
		return null;
	}
}
 
Example 7
Source File: JavadocTagsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void getUnusedAndUndocumentedParameterOrExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	IJavaProject project= cu.getJavaProject();

	if (!JavaCore.ENABLED.equals(project.getOption(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, true))) {
		return;
	}

	int problemId= problem.getProblemId();
	boolean isUnusedTypeParam= problemId == IProblem.UnusedTypeParameter;
	boolean isUnusedParam= problemId == IProblem.ArgumentIsNeverUsed || isUnusedTypeParam;
	String key= isUnusedParam ? JavaCore.COMPILER_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE : JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_INCLUDE_DOC_COMMENT_REFERENCE;

	if (!JavaCore.ENABLED.equals(project.getOption(key, true))) {
		return;
	}

 	ASTNode node= problem.getCoveringNode(context.getASTRoot());
 	if (node == null) {
 		return;
 	}

	BodyDeclaration bodyDecl= ASTResolving.findParentBodyDeclaration(node);
	if (bodyDecl == null || ASTResolving.getParentMethodOrTypeBinding(bodyDecl) == null) {
		return;
	}

	String label;
	if (isUnusedTypeParam) {
		label= CorrectionMessages.JavadocTagsSubProcessor_document_type_parameter_description;
	} else if (isUnusedParam) {
		label= CorrectionMessages.JavadocTagsSubProcessor_document_parameter_description;
	} else {
		node= ASTNodes.getNormalizedNode(node);
		label= CorrectionMessages.JavadocTagsSubProcessor_document_exception_description;
	}
	ASTRewriteCorrectionProposal proposal= new AddMissingJavadocTagProposal(label, context.getCompilationUnit(), bodyDecl, node, IProposalRelevance.DOCUMENT_UNUSED_ITEM);
	proposals.add(proposal);
}
 
Example 8
Source File: CopyQualifiedNameAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether the given name belongs to a {@link ClassInstanceCreation} and if so, returns
 * its constructor binding.
 * 
 * @param nameNode the name node
 * @return the constructor binding or <code>null</code> if not found
 * @since 3.7
 */
private IBinding getConstructorBindingIfAvailable(Name nameNode) {
	ASTNode type= ASTNodes.getNormalizedNode(nameNode);
	StructuralPropertyDescriptor loc= type.getLocationInParent();
	if (loc == ClassInstanceCreation.TYPE_PROPERTY) {
		return ((ClassInstanceCreation) type.getParent()).resolveConstructorBinding();
	}
	return null;
}
 
Example 9
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Extracts the binding from the token's simple name.
 * Works around bug 62605 to return the correct constructor binding in a ClassInstanceCreation.
 *
 * @param token the token to extract the binding from
 * @return the token's binding, or <code>null</code>
 */
private static IBinding getBinding(SemanticToken token) {
	ASTNode node= token.getNode();
	ASTNode normalized= ASTNodes.getNormalizedNode(node);
	if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
		// work around: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62605
		return ((ClassInstanceCreation) normalized.getParent()).resolveConstructorBinding();
	}
	return token.getBinding();
}
 
Example 10
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isIntroduceFactoryAvailable(final JavaTextSelection selection) throws JavaModelException {
	final IJavaElement[] elements= selection.resolveElementAtOffset();
	if (elements.length == 1 && elements[0] instanceof IMethod)
		return isIntroduceFactoryAvailable((IMethod) elements[0]);

	// there's no IMethod for the default constructor
	if (!Checks.isAvailable(selection.resolveEnclosingElement()))
		return false;
	ASTNode node= selection.resolveCoveringNode();
	if (node == null) {
		ASTNode[] selectedNodes= selection.resolveSelectedNodes();
		if (selectedNodes != null && selectedNodes.length == 1) {
			node= selectedNodes[0];
			if (node == null)
				return false;
		} else {
			return false;
		}
	}

	if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
		return true;

	node= ASTNodes.getNormalizedNode(node);
	if (node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY)
		return true;

	return false;
}
 
Example 11
Source File: JavadocTagsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void getUnusedAndUndocumentedParameterOrExceptionProposals(IInvocationContext context,
		IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	IJavaProject project= cu.getJavaProject();

	if (!JavaCore.ENABLED.equals(project.getOption(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, true))) {
		return;
	}

	int problemId= problem.getProblemId();
	boolean isUnusedTypeParam= problemId == IProblem.UnusedTypeParameter;
	boolean isUnusedParam= problemId == IProblem.ArgumentIsNeverUsed || isUnusedTypeParam;
	String key= isUnusedParam ? JavaCore.COMPILER_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE : JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_INCLUDE_DOC_COMMENT_REFERENCE;

	if (!JavaCore.ENABLED.equals(project.getOption(key, true))) {
		return;
	}

	ASTNode node= problem.getCoveringNode(context.getASTRoot());
	if (node == null) {
		return;
	}

	BodyDeclaration bodyDecl= ASTResolving.findParentBodyDeclaration(node);
	if (bodyDecl == null || ASTResolving.getParentMethodOrTypeBinding(bodyDecl) == null) {
		return;
	}

	String label;
	if (isUnusedTypeParam) {
		label= CorrectionMessages.JavadocTagsSubProcessor_document_type_parameter_description;
	} else if (isUnusedParam) {
		label= CorrectionMessages.JavadocTagsSubProcessor_document_parameter_description;
	} else {
		node= ASTNodes.getNormalizedNode(node);
		label= CorrectionMessages.JavadocTagsSubProcessor_document_exception_description;
	}
	ASTRewriteCorrectionProposal proposal= new AddMissingJavadocTagProposal(label, context.getCompilationUnit(), bodyDecl, node, IProposalRelevance.DOCUMENT_UNUSED_ITEM);
	proposals.add(proposal);
}
 
Example 12
Source File: QuickAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean getAssignAllParamsToFieldsProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> resultingCollections) {
	node = ASTNodes.getNormalizedNode(node);
	ASTNode parent = node.getParent();
	if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
		return false;
	}
	MethodDeclaration methodDecl = (MethodDeclaration) parent.getParent();
	if (methodDecl.getBody() == null) {
		return false;
	}
	List<SingleVariableDeclaration> parameters = methodDecl.parameters();
	if (parameters.size() <= 1) {
		return false;
	}
	ITypeBinding parentType = Bindings.getBindingOfParentType(node);
	if (parentType == null || parentType.isInterface()) {
		return false;
	}
	for (SingleVariableDeclaration param : parameters) {
		IVariableBinding binding = param.resolveBinding();
		if (binding == null || binding.getType() == null) {
			return false;
		}
	}
	if (resultingCollections == null) {
		return true;
	}

	AssignToVariableAssistProposal fieldProposal = new AssignToVariableAssistProposal(context.getCompilationUnit(), parameters, IProposalRelevance.ASSIGN_ALL_PARAMS_TO_NEW_FIELDS);
	resultingCollections.add(fieldProposal);
	return true;
}
 
Example 13
Source File: NewCUUsingWizardProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ITypeBinding getPossibleSuperTypeBinding(ASTNode node) {
	if (fTypeKind == K_ANNOTATION) {
		return null;
	}

	AST ast= node.getAST();
	node= ASTNodes.getNormalizedNode(node);
	ASTNode parent= node.getParent();
	switch (parent.getNodeType()) {
		case ASTNode.METHOD_DECLARATION:
			if (node.getLocationInParent() == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) {
				return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
			}
			break;
		case ASTNode.THROW_STATEMENT :
			return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
		case ASTNode.SINGLE_VARIABLE_DECLARATION:
			if (parent.getLocationInParent() == CatchClause.EXCEPTION_PROPERTY) {
				return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
			}
			break;
		case ASTNode.VARIABLE_DECLARATION_STATEMENT:
		case ASTNode.FIELD_DECLARATION:
			return null; // no guessing for LHS types, cannot be a supertype of a known type
		case ASTNode.PARAMETERIZED_TYPE:
			return null; // Inheritance doesn't help: A<X> z= new A<String>(); ->
	}
	ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
	if (binding != null && !binding.isRecovered()) {
		return binding;
	}
	return null;
}
 
Example 14
Source File: SemanticHighlightings.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Extracts the binding from the token's simple name. Works around bug 62605 to
 * return the correct constructor binding in a ClassInstanceCreation.
 *
 * @param token
 *            the token to extract the binding from
 * @return the token's binding, or <code>null</code>
 */
private static IBinding getBinding(SemanticToken token) {
	ASTNode node = token.getNode();
	ASTNode normalized = ASTNodes.getNormalizedNode(node);
	if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
		// work around: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62605
		return ((ClassInstanceCreation) normalized.getParent()).resolveConstructorBinding();
	}
	return token.getBinding();
}
 
Example 15
Source File: JavadocTagsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static void getMissingJavadocTagProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	ASTNode node= problem.getCoveringNode(context.getASTRoot());
	if (node == null) {
		return;
	}
	node= ASTNodes.getNormalizedNode(node);

	BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
	if (bodyDeclaration == null) {
		return;
	}
	Javadoc javadoc= bodyDeclaration.getJavadoc();
	if (javadoc == null) {
		return;
	}

	String label;
	StructuralPropertyDescriptor location= node.getLocationInParent();
	if (location == SingleVariableDeclaration.NAME_PROPERTY) {
		label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_paramtag_description;
		if (node.getParent().getLocationInParent() != MethodDeclaration.PARAMETERS_PROPERTY) {
			return; // paranoia checks
		}
	} else if (location == TypeParameter.NAME_PROPERTY) {
		label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_paramtag_description;
		StructuralPropertyDescriptor parentLocation= node.getParent().getLocationInParent();
		if (parentLocation != MethodDeclaration.TYPE_PARAMETERS_PROPERTY && parentLocation != TypeDeclaration.TYPE_PARAMETERS_PROPERTY) {
			return; // paranoia checks
		}
	} else if (location == MethodDeclaration.RETURN_TYPE2_PROPERTY) {
		label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_returntag_description;
	} else if (location == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) {
		label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_throwstag_description;
	} else {
		return;
	}
	ASTRewriteCorrectionProposal proposal= new AddMissingJavadocTagProposal(label, context.getCompilationUnit(), bodyDeclaration, node, IProposalRelevance.ADD_MISSING_TAG);
	proposals.add(proposal);

	String label2= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_allmissing_description;
	ASTRewriteCorrectionProposal addAllMissing= new AddAllMissingJavadocTagsProposal(label2, context.getCompilationUnit(), bodyDeclaration, IProposalRelevance.ADD_ALL_MISSING_TAGS);
	proposals.add(addAllMissing);
}
 
Example 16
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance,
		Collection<ChangeCorrectionProposal> proposals) throws CoreException {
	SimilarElement[] elements = SimilarElementsRequestor.findSimilarElement(cu, node, kind);

	// try to resolve type in context -> highest severity
	String resolvedTypeName= null;
	ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
	if (binding != null) {
		ITypeBinding simpleBinding= binding;
		if (simpleBinding.isArray()) {
			simpleBinding= simpleBinding.getElementType();
		}
		simpleBinding= simpleBinding.getTypeDeclaration();

		if (!simpleBinding.isRecovered()) {
			resolvedTypeName= simpleBinding.getQualifiedName();
			CUCorrectionProposal proposal= createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2, elements.length);
			proposals.add(proposal);
			if (proposal instanceof AddImportCorrectionProposal) {
				proposal.setRelevance(relevance + elements.length + 2);
			}

			if (binding.isParameterizedType()
					&& (node.getParent() instanceof SimpleType || node.getParent() instanceof NameQualifiedType)
					&& !(node.getParent().getParent() instanceof Type)) {
				proposals.add(createTypeRefChangeFullProposal(cu, binding, node, relevance + 5));
			}
		}
	} else {
		ASTNode normalizedNode= ASTNodes.getNormalizedNode(node);
		if (!(normalizedNode.getParent() instanceof Type) && node.getParent() != normalizedNode) {
			ITypeBinding normBinding= ASTResolving.guessBindingForTypeReference(normalizedNode);
			if (normBinding != null && !normBinding.isRecovered()) {
				proposals.add(createTypeRefChangeFullProposal(cu, normBinding, normalizedNode, relevance + 5));
			}
		}
	}

	// add all similar elements
	for (int i= 0; i < elements.length; i++) {
		SimilarElement elem= elements[i];
		if ((elem.getKind() & TypeKinds.ALL_TYPES) != 0) {
			String fullName= elem.getName();
			if (!fullName.equals(resolvedTypeName)) {
				proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance, elements.length));
			}
		}
	}
}
 
Example 17
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, Collection<ICommandAccess> proposals) throws CoreException {
	SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind);

	// try to resolve type in context -> highest severity
	String resolvedTypeName= null;
	ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
	if (binding != null) {
		ITypeBinding simpleBinding= binding;
		if (simpleBinding.isArray()) {
			simpleBinding= simpleBinding.getElementType();
		}
		simpleBinding= simpleBinding.getTypeDeclaration();

		if (!simpleBinding.isRecovered()) {
			resolvedTypeName= simpleBinding.getQualifiedName();
			CUCorrectionProposal proposal= createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2, elements.length);
			proposals.add(proposal);
			if (proposal instanceof AddImportCorrectionProposal)
				proposal.setRelevance(relevance + elements.length + 2);

			if (binding.isParameterizedType()
					&& (node.getParent() instanceof SimpleType || node.getParent() instanceof NameQualifiedType)
					&& !(node.getParent().getParent() instanceof Type)) {
				proposals.add(createTypeRefChangeFullProposal(cu, binding, node, relevance + 5));
			}
		}
	} else {
		ASTNode normalizedNode= ASTNodes.getNormalizedNode(node);
		if (!(normalizedNode.getParent() instanceof Type) && node.getParent() != normalizedNode) {
			ITypeBinding normBinding= ASTResolving.guessBindingForTypeReference(normalizedNode);
			if (normBinding != null && !normBinding.isRecovered()) {
				proposals.add(createTypeRefChangeFullProposal(cu, normBinding, normalizedNode, relevance + 5));
			}
		}
	}

	// add all similar elements
	for (int i= 0; i < elements.length; i++) {
		SimilarElement elem= elements[i];
		if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) {
			String fullName= elem.getName();
			if (!fullName.equals(resolvedTypeName)) {
				proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance, elements.length));
			}
		}
	}
}
 
Example 18
Source File: RefactorProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static RefactoringCorrectionProposal getConvertAnonymousToNestedProposal(CodeActionParams params, IInvocationContext context, final ASTNode node, boolean returnAsCommand) throws CoreException {
	String label = CorrectionMessages.QuickAssistProcessor_convert_anonym_to_nested;
	ASTNode normalized = ASTNodes.getNormalizedNode(node);
	if (normalized.getLocationInParent() != ClassInstanceCreation.TYPE_PROPERTY) {
		return null;
	}

	final AnonymousClassDeclaration anonymTypeDecl = ((ClassInstanceCreation) normalized.getParent()).getAnonymousClassDeclaration();
	if (anonymTypeDecl == null || anonymTypeDecl.resolveBinding() == null) {
		return null;
	}

	final ConvertAnonymousToNestedRefactoring refactoring = new ConvertAnonymousToNestedRefactoring(anonymTypeDecl);
	if (!refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
		return null;
	}

	if (returnAsCommand) {
		return new RefactoringCorrectionCommandProposal(label, CodeActionKind.Refactor, context.getCompilationUnit(), IProposalRelevance.CONVERT_ANONYMOUS_TO_NESTED, RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID,
				Arrays.asList(CONVERT_ANONYMOUS_CLASS_TO_NESTED_COMMAND, params));
	}

	String extTypeName = ASTNodes.getSimpleNameIdentifier((Name) node);
	ITypeBinding anonymTypeBinding = anonymTypeDecl.resolveBinding();
	String className;
	if (anonymTypeBinding.getInterfaces().length == 0) {
		className = Messages.format(CorrectionMessages.QuickAssistProcessor_name_extension_from_interface, extTypeName);
	} else {
		className = Messages.format(CorrectionMessages.QuickAssistProcessor_name_extension_from_class, extTypeName);
	}
	String[][] existingTypes = ((IType) anonymTypeBinding.getJavaElement()).resolveType(className);
	int i = 1;
	while (existingTypes != null) {
		i++;
		existingTypes = ((IType) anonymTypeBinding.getJavaElement()).resolveType(className + i);
	}
	refactoring.setClassName(i == 1 ? className : className + i);

	LinkedProposalModelCore linkedProposalModel = new LinkedProposalModelCore();
	refactoring.setLinkedProposalModel(linkedProposalModel);

	final ICompilationUnit cu = context.getCompilationUnit();
	RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, CodeActionKind.Refactor, cu, refactoring, IProposalRelevance.CONVERT_ANONYMOUS_TO_NESTED);
	proposal.setLinkedProposalModel(linkedProposalModel);
	return proposal;

}
 
Example 19
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getConvertAnonymousToNestedProposal(IInvocationContext context, final ASTNode node, Collection<ICommandAccess> proposals) throws CoreException {
	if (!(node instanceof Name))
		return false;

	ASTNode normalized= ASTNodes.getNormalizedNode(node);
	if (normalized.getLocationInParent() != ClassInstanceCreation.TYPE_PROPERTY)
		return false;

	final AnonymousClassDeclaration anonymTypeDecl= ((ClassInstanceCreation) normalized.getParent()).getAnonymousClassDeclaration();
	if (anonymTypeDecl == null || anonymTypeDecl.resolveBinding() == null) {
		return false;
	}

	if (proposals == null) {
		return true;
	}

	final ICompilationUnit cu= context.getCompilationUnit();
	final ConvertAnonymousToNestedRefactoring refactoring= new ConvertAnonymousToNestedRefactoring(anonymTypeDecl);
	
	String extTypeName= ASTNodes.getSimpleNameIdentifier((Name) node);
	ITypeBinding anonymTypeBinding= anonymTypeDecl.resolveBinding();
	String className;
	if (anonymTypeBinding.getInterfaces().length == 0) {
		className= Messages.format(CorrectionMessages.QuickAssistProcessor_name_extension_from_interface, extTypeName);
	} else {
		className= Messages.format(CorrectionMessages.QuickAssistProcessor_name_extension_from_class, extTypeName);
	}
	String[][] existingTypes= ((IType) anonymTypeBinding.getJavaElement()).resolveType(className);
	int i= 1;
	while (existingTypes != null) {
		i++;
		existingTypes= ((IType) anonymTypeBinding.getJavaElement()).resolveType(className + i);
	}
	refactoring.setClassName(i == 1 ? className : className + i);

	if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
		LinkedProposalModel linkedProposalModel= new LinkedProposalModel();
		refactoring.setLinkedProposalModel(linkedProposalModel);

		String label= CorrectionMessages.QuickAssistProcessor_convert_anonym_to_nested;
		Image image= JavaPlugin.getImageDescriptorRegistry().get(JavaElementImageProvider.getTypeImageDescriptor(true, false, Flags.AccPrivate, false));
		RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.CONVERT_ANONYMOUS_TO_NESTED, image);
		proposal.setLinkedProposalModel(linkedProposalModel);
		proposal.setCommandId(CONVERT_ANONYMOUS_TO_LOCAL_ID);
		proposals.add(proposal);
	}
	return false;
}
 
Example 20
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getAssignParamToFieldProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	node= ASTNodes.getNormalizedNode(node);
	ASTNode parent= node.getParent();
	if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
		return false;
	}
	SingleVariableDeclaration paramDecl= (SingleVariableDeclaration) parent;
	IVariableBinding binding= paramDecl.resolveBinding();

	MethodDeclaration methodDecl= (MethodDeclaration) parent.getParent();
	if (binding == null || methodDecl.getBody() == null) {
		return false;
	}
	ITypeBinding typeBinding= binding.getType();
	if (typeBinding == null) {
		return false;
	}

	if (resultingCollections == null) {
		return true;
	}

	ITypeBinding parentType= Bindings.getBindingOfParentType(node);
	if (parentType != null) {
		if (parentType.isInterface()) {
			return false;
		}
		// assign to existing fields
		CompilationUnit root= context.getASTRoot();
		IVariableBinding[] declaredFields= parentType.getDeclaredFields();
		boolean isStaticContext= ASTResolving.isInStaticContext(node);
		for (int i= 0; i < declaredFields.length; i++) {
			IVariableBinding curr= declaredFields[i];
			if (isStaticContext == Modifier.isStatic(curr.getModifiers()) && typeBinding.isAssignmentCompatible(curr.getType())) {
				ASTNode fieldDeclFrag= root.findDeclaringNode(curr);
				if (fieldDeclFrag instanceof VariableDeclarationFragment) {
					VariableDeclarationFragment fragment= (VariableDeclarationFragment) fieldDeclFrag;
					if (fragment.getInitializer() == null) {
						resultingCollections.add(new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, fragment, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_EXISTING_FIELD));
					}
				}
			}
		}
	}

	AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, null, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_NEW_FIELD);
	fieldProposal.setCommandId(ASSIGN_PARAM_TO_FIELD_ID);
	resultingCollections.add(fieldProposal);
	return true;
}