Java Code Examples for org.eclipse.jdt.core.dom.Name#resolveBinding()

The following examples show how to use org.eclipse.jdt.core.dom.Name#resolveBinding() . 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: JavadocTagsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) {
	ASTNode node= problem.getCoveringNode(context.getASTRoot());
	if (!(node instanceof Name)) {
		return;
	}
	Name name= (Name) node;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof ITypeBinding)) {
		return;
	}
	ITypeBinding typeBinding= (ITypeBinding)binding;

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null);

	String label= CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description;
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(),
			rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME);

	proposals.add(proposal);
}
 
Example 2
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Name findConstantNameNode() {
	ASTNode node= NodeFinder.perform(fSelectionCuRewrite.getRoot(), fSelectionStart, fSelectionLength);
	if (node == null)
		return null;
	if (node instanceof FieldAccess)
		node= ((FieldAccess) node).getName();
	if (!(node instanceof Name))
		return null;
	Name name= (Name) node;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof IVariableBinding))
		return null;
	IVariableBinding variableBinding= (IVariableBinding) binding;
	if (!variableBinding.isField() || variableBinding.isEnumConstant())
		return null;
	int modifiers= binding.getModifiers();
	if (! (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)))
		return null;

	return name;
}
 
Example 3
Source File: StructCache.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Entry get(Name type) {
	IBinding b = type.resolveBinding();		
	if(b == null) {
		CompilerError.exec(CompilerError.TYPE_NOT_FOUND, type.toString() + ", " + type.getClass());
		return null;
	}
	if(b instanceof IPackageBinding) {
		return null;
	}
	if(b instanceof ITypeBinding) {
		return get((ITypeBinding)b);
	}
	if(b instanceof IVariableBinding) {
		IVariableBinding vb = (IVariableBinding)b;
		return get(vb.getType());		
	}
	Log.err("IGNORING BINFIND " + b + ", " + b.getClass());
	return null;
}
 
Example 4
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Is the specified name a target access?
 *
 * @param name
 *            the name to check
 * @return <code>true</code> if this name is a target access,
 *         <code>false</code> otherwise
 */
protected boolean isTargetAccess(final Name name) {
	Assert.isNotNull(name);
	final IBinding binding= name.resolveBinding();
	if (Bindings.equals(fTarget, binding))
		return true;
	if (name.getParent() instanceof FieldAccess) {
		final FieldAccess access= (FieldAccess) name.getParent();
		final Expression expression= access.getExpression();
		if (expression instanceof Name)
			return isTargetAccess((Name) expression);
	} else if (name instanceof QualifiedName) {
		final QualifiedName qualified= (QualifiedName) name;
		if (qualified.getQualifier() != null)
			return isTargetAccess(qualified.getQualifier());
	}
	return false;
}
 
Example 5
Source File: ConstantChecks.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private boolean checkName(Name name) {
	IBinding binding = name.resolveBinding();
	if (binding == null) {
		return true; /* If the binding is null because of compile errors etc.,
						    scenarios which may have been deemed unacceptable in
						    the presence of semantic information will be admitted. */
	}

	// If name represents a member:
	if (binding instanceof IVariableBinding || binding instanceof IMethodBinding) {
		return isMemberReferenceValidInClassInitialization(name);
	} else if (binding instanceof ITypeBinding) {
		return !((ITypeBinding) binding).isTypeVariable();
	} else {
		return true; // e.g. a NameQualifiedType's qualifier, which can be a package binding
	}
}
 
Example 6
Source File: ConstantChecks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean visitName(Name name) {
	IBinding binding= name.resolveBinding();
	if(binding == null) {
		/* If the binding is null because of compile errors etc.,
		   scenarios which may have been deemed unacceptable in
		   the presence of semantic information will be admitted.
		   Descend deeper.
		 */
		 return true;
	}

	int modifiers= binding.getModifiers();
	if(binding instanceof IVariableBinding) {
		if (!(Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers))) {
			fResult= false;
			return false;
		}
	} else if(binding instanceof IMethodBinding) {
		if (!Modifier.isStatic(modifiers)) {
			fResult= false;
			return false;
		}
	} else if(binding instanceof ITypeBinding) {
		return false; // It's o.k.  Don't descend deeper.

	} else {
		return false; // e.g. a NameQualifiedType's qualifier, which can be a package binding
	}

	//Descend deeper:
	return true;
}
 
Example 7
Source File: ConstantChecks.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isMemberReferenceValidInClassInitialization(Name name) {
	IBinding binding = name.resolveBinding();
	Assert.isTrue(binding instanceof IVariableBinding || binding instanceof IMethodBinding);

	if (name instanceof SimpleName) {
		return Modifier.isStatic(binding.getModifiers());
	} else {
		Assert.isTrue(name instanceof QualifiedName);
		return checkName(((QualifiedName) name).getQualifier());
	}
}
 
Example 8
Source File: ConstantChecks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isMemberReferenceValidInClassInitialization(Name name) {
	IBinding binding= name.resolveBinding();
	Assert.isTrue(binding instanceof IVariableBinding || binding instanceof IMethodBinding);

	if(name instanceof SimpleName)
		return Modifier.isStatic(binding.getModifiers());
	else {
		Assert.isTrue(name instanceof QualifiedName);
		return checkName(((QualifiedName) name).getQualifier());
	}
}
 
Example 9
Source File: ImportReferencesCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void possibleTypeRefFound(Name node) {
	while (node.isQualifiedName()) {
		node= ((QualifiedName) node).getQualifier();
	}
	IBinding binding= node.resolveBinding();
	if (binding == null || binding.getKind() == IBinding.TYPE) {
		// if the binding is null, we cannot determine if
		// we have a type binding or not, so we will assume
		// we do.
		addReference((SimpleName) node);
	}
}
 
Example 10
Source File: ImportRewriteUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Collects the necessary imports for an element represented by the specified AST node.
 *
 * @param project the java project containing the element
 * @param node the AST node specifying the element for which imports should be collected
 * @param typeBindings the set of type bindings (element type: Set <ITypeBinding>).
 * @param staticBindings the set of bindings (element type: Set <IBinding>).
 * @param excludeBindings the set of bindings to exclude (element type: Set <IBinding>).
 * @param declarations <code>true</code> if method declarations are treated as abstract, <code>false</code> otherwise
 */
public static void collectImports(final IJavaProject project, final ASTNode node, final Collection<ITypeBinding> typeBindings, final Collection<IBinding> staticBindings, final Collection<IBinding> excludeBindings, final boolean declarations) {
	Assert.isNotNull(project);
	Assert.isNotNull(node);
	Assert.isNotNull(typeBindings);
	Assert.isNotNull(staticBindings);
	final Set<SimpleName> types= new HashSet<>();
	final Set<SimpleName> members= new HashSet<>();

	ImportReferencesCollector.collect(node, project, null, declarations, types, members);

	Name name= null;
	IBinding binding= null;
	for (final Iterator<SimpleName> iterator= types.iterator(); iterator.hasNext();) {
		name= iterator.next();
		binding= name.resolveBinding();
		if (binding instanceof ITypeBinding) {
			final ITypeBinding type= (ITypeBinding) binding;
			if (excludeBindings == null || !excludeBindings.contains(type)) {
				typeBindings.add(type);
			}
		}
	}
	for (final Iterator<SimpleName> iterator= members.iterator(); iterator.hasNext();) {
		name= iterator.next();
		binding= name.resolveBinding();
		if (binding != null && (excludeBindings == null || !excludeBindings.contains(binding))) {
			staticBindings.add(binding);
		}
	}
}
 
Example 11
Source File: OrganizeImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addStaticImports(List<SimpleName> staticReferences, ImportRewrite importsStructure) {
	for (int i= 0; i < staticReferences.size(); i++) {
		Name name= staticReferences.get(i);
		IBinding binding= name.resolveBinding();
		if (binding != null) { // paranoia check
			importsStructure.addStaticImport(binding);
		}
	}
}
 
Example 12
Source File: ImportRewriteUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Collects the necessary imports for an element represented by the specified AST node.
 *
 * @param project the java project containing the element
 * @param node the AST node specifying the element for which imports should be collected
 * @param typeBindings the set of type bindings (element type: Set <ITypeBinding>).
 * @param staticBindings the set of bindings (element type: Set <IBinding>).
 * @param excludeBindings the set of bindings to exclude (element type: Set <IBinding>).
 * @param declarations <code>true</code> if method declarations are treated as abstract, <code>false</code> otherwise
 */
public static void collectImports(final IJavaProject project, final ASTNode node, final Collection<ITypeBinding> typeBindings, final Collection<IBinding> staticBindings, final Collection<IBinding> excludeBindings, final boolean declarations) {
	Assert.isNotNull(project);
	Assert.isNotNull(node);
	Assert.isNotNull(typeBindings);
	Assert.isNotNull(staticBindings);
	final Set<SimpleName> types= new HashSet<SimpleName>();
	final Set<SimpleName> members= new HashSet<SimpleName>();

	ImportReferencesCollector.collect(node, project, null, declarations, types, members);

	Name name= null;
	IBinding binding= null;
	for (final Iterator<SimpleName> iterator= types.iterator(); iterator.hasNext();) {
		name= iterator.next();
		binding= name.resolveBinding();
		if (binding instanceof ITypeBinding) {
			final ITypeBinding type= (ITypeBinding) binding;
			if (excludeBindings == null || !excludeBindings.contains(type))
				typeBindings.add(type);
		}
	}
	for (final Iterator<SimpleName> iterator= members.iterator(); iterator.hasNext();) {
		name= iterator.next();
		binding= name.resolveBinding();
		if (binding != null && (excludeBindings == null || !excludeBindings.contains(binding)))
			staticBindings.add(binding);
	}
}
 
Example 13
Source File: TempDeclarationFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return <code>null</code> if the selection is invalid or does not cover a temp
 * declaration or reference.
 */
public static VariableDeclaration findTempDeclaration(CompilationUnit cu, int selectionOffset, int selectionLength) {
	TempSelectionAnalyzer analyzer= new TempSelectionAnalyzer(selectionOffset, selectionLength);
	cu.accept(analyzer);

	ASTNode[] selected= analyzer.getSelectedNodes();
	if (selected == null || selected.length != 1)
		return null;

	ASTNode selectedNode= selected[0];
	if (selectedNode instanceof VariableDeclaration)
		return (VariableDeclaration)selectedNode;

	if (selectedNode instanceof Name){
		Name reference= (Name)selectedNode;
		IBinding binding= reference.resolveBinding();
		if (binding == null)
			return null;
		ASTNode declaringNode= cu.findDeclaringNode(binding);
		if (declaringNode instanceof VariableDeclaration)
			return (VariableDeclaration)declaringNode;
		else
			return null;
	} else if (selectedNode instanceof VariableDeclarationStatement){
		VariableDeclarationStatement vds= (VariableDeclarationStatement)selectedNode;
		if (vds.fragments().size() != 1)
			return null;
		return (VariableDeclaration)vds.fragments().get(0);
	}
	return null;
}
 
Example 14
Source File: OccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public String initialize(CompilationUnit root, ASTNode node) {
	if (!(node instanceof Name))
		return SearchMessages.OccurrencesFinder_no_element;
	fRoot= root;
	fSelectedNode= (Name)node;
	fTarget= fSelectedNode.resolveBinding();
	if (fTarget == null)
		return SearchMessages.OccurrencesFinder_no_binding;
	fTarget= getBindingDeclaration(fTarget);

	fTargetIsStaticMethodImport= isStaticImport(fSelectedNode.getParent());
	fReadDescription= Messages.format(SearchMessages.OccurrencesFinder_occurrence_description, BasicElementLabels.getJavaElementName(fTarget.getName()));
	fWriteDescription= Messages.format(SearchMessages.OccurrencesFinder_occurrence_write_description, BasicElementLabels.getJavaElementName(fTarget.getName()));
	return null;
}
 
Example 15
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isEnumCase(ASTNode node) {
	if (node instanceof SwitchCase) {
		final SwitchCase caze= (SwitchCase) node;
		final Expression expression= caze.getExpression();
		if (expression instanceof Name) {
			final Name name= (Name) expression;
			final IBinding binding= name.resolveBinding();
			if (binding instanceof IVariableBinding) {
				IVariableBinding variableBinding= (IVariableBinding) binding;
				return variableBinding.isEnumConstant();
			}
		}
	}
	return false;
}
 
Example 16
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 17
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void endVisit(CompilationUnit node) {
	RefactoringStatus status= getStatus();
	superCall: {
		if (status.hasFatalError())
			break superCall;
		if (!hasSelectedNodes()) {
			ASTNode coveringNode= getLastCoveringNode();
			if (coveringNode instanceof Block && coveringNode.getParent() instanceof MethodDeclaration) {
				MethodDeclaration methodDecl= (MethodDeclaration)coveringNode.getParent();
				Message[] messages= ASTNodes.getMessages(methodDecl, ASTNodes.NODE_ONLY);
				if (messages.length > 0) {
					status.addFatalError(Messages.format(
						RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors,
						BasicElementLabels.getJavaElementName(methodDecl.getName().getIdentifier())), JavaStatusContext.create(fCUnit, methodDecl));
					break superCall;
				}
			}
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection);
			break superCall;
		}
		fEnclosingBodyDeclaration= (BodyDeclaration)ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class);
		if (fEnclosingBodyDeclaration == null ||
				(fEnclosingBodyDeclaration.getNodeType() != ASTNode.METHOD_DECLARATION &&
				 fEnclosingBodyDeclaration.getNodeType() != ASTNode.FIELD_DECLARATION &&
				 fEnclosingBodyDeclaration.getNodeType() != ASTNode.INITIALIZER)) {
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection);
			break superCall;
		} else if (ASTNodes.getEnclosingType(fEnclosingBodyDeclaration) == null) {
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors_no_parent_binding);
			break superCall;
		} else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
			fEnclosingMethodBinding= ((MethodDeclaration)fEnclosingBodyDeclaration).resolveBinding();
		}
		if (!isSingleExpressionOrStatementSet()) {
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_single_expression_or_set);
			break superCall;
		}
		if (isExpressionSelected()) {
			ASTNode expression= getFirstSelectedNode();
			if (expression instanceof Name) {
				Name name= (Name)expression;
				if (name.resolveBinding() instanceof ITypeBinding) {
					status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference);
					break superCall;
				}
				if (name.resolveBinding() instanceof IMethodBinding) {
					status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_method_name_reference);
					break superCall;
				}
				if (name.resolveBinding() instanceof IVariableBinding) {
					StructuralPropertyDescriptor locationInParent= name.getLocationInParent();
					if (locationInParent == QualifiedName.NAME_PROPERTY || (locationInParent == FieldAccess.NAME_PROPERTY && !(((FieldAccess) name.getParent()).getExpression() instanceof ThisExpression)))  {
						status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_part_of_qualified_name);
						break superCall;
					}
				}
				if (name.isSimpleName() && ((SimpleName)name).isDeclaration()) {
					status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_name_in_declaration);
					break superCall;
				}
			}
			fForceStatic=
				ASTNodes.getParent(expression, ASTNode.SUPER_CONSTRUCTOR_INVOCATION) != null ||
				ASTNodes.getParent(expression, ASTNode.CONSTRUCTOR_INVOCATION) != null;
		}
		status.merge(LocalTypeAnalyzer.perform(fEnclosingBodyDeclaration, getSelection()));
		computeLastStatementSelected();
	}
	super.endVisit(node);
}
 
Example 18
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static IMethodBinding getMethodBinding(Name node) {
	IBinding binding= node.resolveBinding();
	if (binding instanceof IMethodBinding)
		return (IMethodBinding)binding;
	return null;
}
 
Example 19
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static IVariableBinding getVariableBinding(Name node) {
	IBinding binding= node.resolveBinding();
	if (binding instanceof IVariableBinding)
		return (IVariableBinding)binding;
	return null;
}
 
Example 20
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean visit(final FieldAccess node) {
	if (!fRemoveFieldQualifiers)
		return true;

	Expression expression= node.getExpression();
	if (!(expression instanceof ThisExpression))
		return true;

	final SimpleName name= node.getName();
	if (hasConflict(expression.getStartPosition(), name, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY))
		return true;

	Name qualifier= ((ThisExpression) expression).getQualifier();
	if (qualifier != null) {
		ITypeBinding outerClass= (ITypeBinding) qualifier.resolveBinding();
		if (outerClass == null)
			return true;

		IVariableBinding nameBinding= (IVariableBinding) name.resolveBinding();
		if (nameBinding == null)
			return true;

		ITypeBinding variablesDeclaringClass= nameBinding.getDeclaringClass();
		if (outerClass != variablesDeclaringClass)
			//be conservative: We have a reference to a field of an outer type, and this type inherited
			//the field. It's possible that the inner type inherits the same field. We must not remove
			//the qualifier in this case.
			return true;
		
		ITypeBinding enclosingTypeBinding= Bindings.getBindingOfParentType(node);
		if (enclosingTypeBinding == null || Bindings.isSuperType(variablesDeclaringClass, enclosingTypeBinding))
			//We have a reference to a field of an outer type, and this type inherited
			//the field. The inner type inherits the same field. We must not remove
			//the qualifier in this case.
			return true;
	}

	fOperations.add(new CompilationUnitRewriteOperation() {
		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			TextEditGroup group= createTextEditGroup(FixMessages.CodeStyleFix_removeThis_groupDescription, cuRewrite);
			rewrite.replace(node, rewrite.createCopyTarget(name), group);
		}
	});
	return super.visit(node);
}