org.eclipse.jdt.core.dom.IBinding Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.IBinding. 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: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {

	// 1: match types
	SimpleName name= token.getNode();
	ASTNode node= name.getParent();
	int nodeType= node.getNodeType();
	if (nodeType != ASTNode.METHOD_INVOCATION && nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME
			&& nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.ENUM_DECLARATION)
		return false;
	while (nodeType == ASTNode.QUALIFIED_NAME) {
		node= node.getParent();
		nodeType= node.getNodeType();
		if (nodeType == ASTNode.IMPORT_DECLARATION)
			return false;
	}

	// 2: match enums
	IBinding binding= token.getBinding();
	return binding instanceof ITypeBinding && ((ITypeBinding) binding).isEnum();
}
 
Example #2
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void qualifyMemberName(SimpleName memberName) {
	if (isStaticAccess(memberName)) {
		IBinding memberBinding= memberName.resolveBinding();

		if (memberBinding instanceof IVariableBinding || memberBinding instanceof IMethodBinding) {
			if (fStaticImportsInReference.contains(fNewLocation)) { // use static import if reference location used static import
				importStatically(memberName, memberBinding);
				return;
			} else if (fStaticImportsInInitializer2.contains(memberName)) { // use static import if already imported statically in initializer
				importStatically(memberName, memberBinding);
				return;
			}
		}
		qualifyToTopLevelClass(memberName); //otherwise: qualify and import non-static
	}
}
 
Example #3
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static Map<String, String> getCleanUpOptions(IBinding binding, boolean removeAll) {
	Map<String, String> result= new Hashtable<String, String>();

	result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS, CleanUpOptions.TRUE);
	switch (binding.getKind()) {
		case IBinding.TYPE:
			result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES, CleanUpOptions.TRUE);
			break;
		case IBinding.METHOD:
			if (((IMethodBinding) binding).isConstructor()) {
				result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS, CleanUpOptions.TRUE);
			} else {
				result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS, CleanUpOptions.TRUE);
			}
			break;
		case IBinding.VARIABLE:
			if (removeAll)
				return null;

			result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS, CleanUpOptions.TRUE);
			result.put(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES, CleanUpOptions.TRUE);
			break;
	}

	return result;
}
 
Example #4
Source File: GetterSetterCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean addGetterSetterProposal(IInvocationContext context, ASTNode coveringNode, Collection<ICommandAccess> proposals, int relevance) {
	if (!(coveringNode instanceof SimpleName)) {
		return false;
	}
	SimpleName sn= (SimpleName) coveringNode;

	IBinding binding= sn.resolveBinding();
	if (!(binding instanceof IVariableBinding))
		return false;
	IVariableBinding variableBinding= (IVariableBinding) binding;
	if (!variableBinding.isField())
		return false;

	if (proposals == null)
		return true;

	ChangeCorrectionProposal proposal= getProposal(context.getCompilationUnit(), sn, variableBinding, relevance);
	if (proposal != null)
		proposals.add(proposal);
	return true;
}
 
Example #5
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String getDisplayString(SimpleName simpleName, IBinding binding, boolean removeAllAssignements) {
	String name= BasicElementLabels.getJavaElementName(simpleName.getIdentifier());
	switch (binding.getKind()) {
		case IBinding.TYPE:
			return Messages.format(FixMessages.UnusedCodeFix_RemoveType_description, name);
		case IBinding.METHOD:
			if (((IMethodBinding) binding).isConstructor()) {
				return Messages.format(FixMessages.UnusedCodeFix_RemoveConstructor_description, name);
			} else {
				return Messages.format(FixMessages.UnusedCodeFix_RemoveMethod_description, name);
			}
		case IBinding.VARIABLE:
			if (removeAllAssignements) {
				return Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocalWithInitializer_description, name);
			} else {
				return Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_description, name);
			}
		default:
			return ""; //$NON-NLS-1$
	}
}
 
Example #6
Source File: VariableDeclarationFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
		boolean addFinalFields, boolean addFinalParameters, boolean addFinalLocals) {

	if (!addFinalFields && !addFinalParameters && !addFinalLocals)
		return null;

	HashMap<IBinding, List<SimpleName>> writtenNames= new HashMap<IBinding, List<SimpleName>>();
	WrittenNamesFinder finder= new WrittenNamesFinder(writtenNames);
	compilationUnit.accept(finder);

	List<ModifierChangeOperation> operations= new ArrayList<ModifierChangeOperation>();
	VariableDeclarationFinder visitor= new VariableDeclarationFinder(addFinalFields, addFinalParameters, addFinalLocals, operations, writtenNames);
	compilationUnit.accept(visitor);

	if (operations.isEmpty())
		return null;

	return new VariableDeclarationFix(FixMessages.VariableDeclarationFix_add_final_change_name, compilationUnit, operations.toArray(new CompilationUnitRewriteOperation[operations.size()]));
}
 
Example #7
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {

	// 1: match types
	SimpleName name= token.getNode();
	ASTNode node= name.getParent();
	int nodeType= node.getNodeType();
	if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.THIS_EXPRESSION && nodeType != ASTNode.QUALIFIED_TYPE  && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.TYPE_DECLARATION && nodeType != ASTNode.METHOD_INVOCATION)
		return false;
	while (nodeType == ASTNode.QUALIFIED_NAME) {
		node= node.getParent();
		nodeType= node.getNodeType();
		if (nodeType == ASTNode.IMPORT_DECLARATION)
			return false;
	}

	// 2: match classes
	IBinding binding= token.getBinding();
	return binding instanceof ITypeBinding && ((ITypeBinding) binding).isClass();
}
 
Example #8
Source File: MissingReturnTypeInLambdaCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) {
	ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
	IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);

	org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(root, returnOffset, 0);
	ASTNode varDeclFrag= ASTResolving.findAncestor(finder.getCoveringNode(), ASTNode.VARIABLE_DECLARATION_FRAGMENT);
	IVariableBinding varDeclFragBinding= null;
	if (varDeclFrag != null) {
		varDeclFragBinding= ((VariableDeclarationFragment) varDeclFrag).resolveBinding();
	}
	for (int i= 0; i < bindings.length; i++) {
		IVariableBinding curr= (IVariableBinding) bindings[i];
		ITypeBinding type= curr.getType();
		// Bindings are compared to make sure that a lambda does not return a variable which is yet to be initialised.
		if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr) && !Bindings.equals(curr, varDeclFragBinding)) {
			if (result == null) {
				result= ast.newSimpleName(curr.getName());
			}
			addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName());
		}
	}
	return result;
}
 
Example #9
Source File: FlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void endVisit(SimpleName node) {
	if (skipNode(node) || node.isDeclaration())
		return;
	IBinding binding= node.resolveBinding();
	if (binding instanceof IVariableBinding) {
		IVariableBinding variable= (IVariableBinding)binding;
		if (!variable.isField()) {
			setFlowInfo(node, new LocalFlowInfo(
				variable,
				FlowInfo.READ,
				fFlowContext));
		}
	} else if (binding instanceof ITypeBinding) {
		ITypeBinding type= (ITypeBinding)binding;
		if (type.isTypeVariable()) {
			setFlowInfo(node, new TypeVariableFlowInfo(type, fFlowContext));
		}
	}
}
 
Example #10
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IBinding[] getDeclarationsAfter(int offset, int flags) {
	try {
		org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0);
		ASTNode node= finder.getCoveringNode();
		if (node == null) {
			return null;
		}

		ASTNode declaration= ASTResolving.findParentStatement(node);
		while (declaration instanceof Statement && declaration.getNodeType() != ASTNode.BLOCK) {
			declaration= declaration.getParent();
		}

		if (declaration instanceof Block) {
			DefaultBindingRequestor requestor= new DefaultBindingRequestor();
			DeclarationsAfterVisitor visitor= new DeclarationsAfterVisitor(node.getStartPosition(), flags, requestor);
			declaration.accept(visitor);
			List<IBinding> result= requestor.getResult();
			return result.toArray(new IBinding[result.size()]);
		}
		return NO_BINDING;
	} finally {
		clearLists();
	}
}
 
Example #11
Source File: SemanticHighlightings.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {

	// 1: match types
	SimpleName name = token.getNode();
	ASTNode node = name.getParent();
	int nodeType = node.getNodeType();
	if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.TYPE_DECLARATION) {
		return false;
	}
	while (nodeType == ASTNode.QUALIFIED_NAME) {
		node = node.getParent();
		nodeType = node.getNodeType();
		if (nodeType == ASTNode.IMPORT_DECLARATION) {
			return false;
		}
	}

	// 2: match interfaces
	IBinding binding = token.getBinding();
	return binding instanceof ITypeBinding && ((ITypeBinding) binding).isInterface();
}
 
Example #12
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 6 votes vote down vote up
private Expression convert(org.eclipse.jdt.core.dom.QualifiedName expression) {
  IBinding binding = expression.resolveBinding();
  if (binding instanceof IVariableBinding) {
    IVariableBinding variableBinding = (IVariableBinding) binding;
    checkArgument(
        variableBinding.isField(),
        internalCompilerErrorMessage("Unexpected QualifiedName that is not a field"));

    Expression qualifier = convert(expression.getQualifier());
    return JdtUtils.createFieldAccess(qualifier, variableBinding);
  }

  if (binding instanceof ITypeBinding) {
    return null;
  }

  throw internalCompilerError(
      "Unexpected type for QualifiedName binding: %s ", binding.getClass().getName());
}
 
Example #13
Source File: SemanticHighlightings.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {

	// 1: match types
	SimpleName name = token.getNode();
	ASTNode node = name.getParent();
	int nodeType = node.getNodeType();
	if (nodeType != ASTNode.METHOD_INVOCATION && nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.QUALIFIED_NAME
			&& nodeType != ASTNode.ENUM_DECLARATION) {
		return false;
	}
	while (nodeType == ASTNode.QUALIFIED_NAME) {
		node = node.getParent();
		nodeType = node.getNodeType();
		if (nodeType == ASTNode.IMPORT_DECLARATION) {
			return false;
		}
	}

	// 2: match enums
	IBinding binding = token.getBinding();
	return binding instanceof ITypeBinding && ((ITypeBinding) binding).isEnum();
}
 
Example #14
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IBinding[] getDeclarationsInScope(int offset, int flags) {
	org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0);
	ASTNode node= finder.getCoveringNode();
	if (node == null) {
		return NO_BINDING;
	}

	if (node instanceof SimpleName) {
		return getDeclarationsInScope((SimpleName) node, flags);
	}

	try {
		ITypeBinding binding= Bindings.getBindingOfParentType(node);
		DefaultBindingRequestor requestor= new DefaultBindingRequestor(binding, flags);
		addLocalDeclarations(node, offset, flags, requestor);
		if (binding != null) {
			addTypeDeclarations(binding, flags, requestor);
		}
		List<IBinding> result= requestor.getResult();
		return result.toArray(new IBinding[result.size()]);
	} finally {
		clearLists();
	}
}
 
Example #15
Source File: SemanticHighlightings.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {
	SimpleName node = token.getNode();
	if (node.isDeclaration()) {
		return false;
	}

	IBinding binding = token.getBinding();
	if (binding == null || binding.getKind() != IBinding.METHOD) {
		return false;
	}

	ITypeBinding currentType = Bindings.getBindingOfParentType(node);
	ITypeBinding declaringType = ((IMethodBinding) binding).getDeclaringClass();
	if (currentType == declaringType || currentType == null) {
		return false;
	}

	return Bindings.isSuperType(declaringType, currentType);
}
 
Example #16
Source File: ExpressionVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static IBinding resolveBinding(Expression expression){
	if (expression instanceof Name)
		return ((Name)expression).resolveBinding();
	if (expression instanceof ParenthesizedExpression)
		return resolveBinding(((ParenthesizedExpression)expression).getExpression());
	else if (expression instanceof Assignment)
		return resolveBinding(((Assignment)expression).getLeftHandSide());//TODO ???
	else if (expression instanceof MethodInvocation)
		return ((MethodInvocation)expression).resolveMethodBinding();
	else if (expression instanceof SuperMethodInvocation)
		return ((SuperMethodInvocation)expression).resolveMethodBinding();
	else if (expression instanceof FieldAccess)
		return ((FieldAccess)expression).resolveFieldBinding();
	else if (expression instanceof SuperFieldAccess)
		return ((SuperFieldAccess)expression).resolveFieldBinding();
	else if (expression instanceof ConditionalExpression)
		return resolveBinding(((ConditionalExpression)expression).getThenExpression());
	return null;
}
 
Example #17
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 #18
Source File: ReorgCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean canModifyAccessRules(IBinding binding) {
	IJavaElement element= binding.getJavaElement();
	if (element == null)
		return false;

	IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(element);
	if (root == null)
		return false;

	try {
		IClasspathEntry classpathEntry= root.getRawClasspathEntry();
		if (classpathEntry == null)
			return false;
		if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
			return true;
		if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
			ClasspathContainerInitializer classpathContainerInitializer= JavaCore.getClasspathContainerInitializer(classpathEntry.getPath().segment(0));
			IStatus status= classpathContainerInitializer.getAccessRulesStatus(classpathEntry.getPath(), root.getJavaProject());
			return status.isOK();
		}
	} catch (JavaModelException e) {
		return false;
	}
	return false;
}
 
Example #19
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 #20
Source File: RenameTypeParameterProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(SimpleName node) {
	IBinding binding= node.resolveBinding();
	if (fBinding == binding) {
		String groupDescription= null;
		if (node != fName) {
			if (fUpdateReferences) {
				groupDescription= RefactoringCoreMessages.RenameTypeParameterRefactoring_update_type_parameter_reference;
			}
		} else {
			groupDescription= RefactoringCoreMessages.RenameTypeParameterRefactoring_update_type_parameter_declaration;
		}
		if (groupDescription != null) {
			fRewrite.getASTRewrite().set(node, SimpleName.IDENTIFIER_PROPERTY, getNewElementName(), fRewrite.createGroupDescription(groupDescription));
		}
	}
	return true;
}
 
Example #21
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(SimpleName node) {
	ITypeBinding typeBinding= node.resolveTypeBinding();
	if (typeBinding != null && typeBinding.isLocal()) {
		if (node.isDeclaration()) {
			fLocalDefinitions.add(typeBinding);
		} else if (! fLocalDefinitions.contains(typeBinding)) {
			fLocalReferencesToEnclosing.add(node);
		}
	}
	if (typeBinding != null && typeBinding.isTypeVariable()) {
		if (node.isDeclaration()) {
			fLocalDefinitions.add(typeBinding);
		} else if (! fLocalDefinitions.contains(typeBinding)) {
			if (fMethodTypeVariables.contains(typeBinding)) {
				fLocalReferencesToEnclosing.add(node);
			} else {
				fClassTypeVariablesUsed= true;
			}
		}
	}
	IBinding binding= node.resolveBinding();
	if (binding != null && binding.getKind() == IBinding.VARIABLE && ! ((IVariableBinding)binding).isField()) {
		if (node.isDeclaration()) {
			fLocalDefinitions.add(binding);
		} else if (! fLocalDefinitions.contains(binding)) {
			fLocalReferencesToEnclosing.add(node);
		}
	}
	return super.visit(node);
}
 
Example #22
Source File: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final void endVisit(final SimpleName node) {
	final ASTNode parent= node.getParent();
	if (!(parent instanceof ImportDeclaration) && !(parent instanceof PackageDeclaration) && !(parent instanceof AbstractTypeDeclaration)) {
		final IBinding binding= node.resolveBinding();
		if (binding instanceof IVariableBinding && !(parent instanceof MethodDeclaration))
			endVisit((IVariableBinding) binding, null, node);
		else if (binding instanceof ITypeBinding && parent instanceof MethodDeclaration)
			endVisit((ITypeBinding) binding, node);
	}
}
 
Example #23
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the field binding associated with this expression.
 *
 * @param expression
 *            the expression to get the field binding for
 * @return the field binding, if the expression denotes a field access
 *         or a field name, <code>null</code> otherwise
 */
protected static IVariableBinding getFieldBinding(final Expression expression) {
	Assert.isNotNull(expression);
	if (expression instanceof FieldAccess)
		return (IVariableBinding) ((FieldAccess) expression).getName().resolveBinding();
	if (expression instanceof Name) {
		final IBinding binding= ((Name) expression).resolveBinding();
		if (binding instanceof IVariableBinding) {
			final IVariableBinding variable= (IVariableBinding) binding;
			if (variable.isField())
				return variable;
		}
	}
	return null;
}
 
Example #24
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String[] getExcludedVariableNames() {
	if (fExcludedVariableNames == null) {
		try {
			IBinding[] bindings= new ScopeAnalyzer(fCompilationUnitNode).getDeclarationsInScope(getSelectedExpression().getStartPosition(), ScopeAnalyzer.VARIABLES
					| ScopeAnalyzer.CHECK_VISIBILITY);
			fExcludedVariableNames= new String[bindings.length];
			for (int i= 0; i < bindings.length; i++) {
				fExcludedVariableNames[i]= bindings[i].getName();
			}
		} catch (JavaModelException e) {
			fExcludedVariableNames= new String[0];
		}
	}
	return fExcludedVariableNames;
}
 
Example #25
Source File: ConstantChecks.java    From eclipse.jdt.ls with Eclipse Public License 2.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 #26
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 #27
Source File: CompletionProposalReplacementProvider.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private ITypeBinding getExpectedTypeForGenericParameters() {
	char[][] chKeys= context.getExpectedTypesKeys();
	if (chKeys == null || chKeys.length == 0) {
		return null;
	}

	String[] keys= new String[chKeys.length];
	for (int i= 0; i < keys.length; i++) {
		keys[i]= String.valueOf(chKeys[0]);
	}

	final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setProject(compilationUnit.getJavaProject());
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);

	final Map<String, IBinding> bindings= new HashMap<>();
	ASTRequestor requestor= new ASTRequestor() {
		@Override
		public void acceptBinding(String bindingKey, IBinding binding) {
			bindings.put(bindingKey, binding);
		}
	};
	parser.createASTs(new ICompilationUnit[0], keys, requestor, null);

	if (bindings.size() > 0) {
		return (ITypeBinding) bindings.get(keys[0]);
	}

	return null;
}
 
Example #28
Source File: MoveStaticMembersProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(SimpleName node) {
	IBinding binding= node.resolveBinding();
	if (!(binding instanceof ITypeBinding))
		return true;
	if (!fDefined.contains(binding))
		fResult.add(binding);
	return true;
}
 
Example #29
Source File: SwitchControlCase.java    From JDeodorant with MIT License 5 votes vote down vote up
private String getConstantValue(Name name)
{
	IBinding nameBinding = name.resolveBinding();
	if (nameBinding.getKind() == IBinding.VARIABLE)
	{
		IVariableBinding nameVariableBinding = (IVariableBinding)nameBinding;
		Object valueObject = nameVariableBinding.getConstantValue();
		if (valueObject instanceof Integer || valueObject instanceof Byte || valueObject instanceof Character || valueObject instanceof String)
		{
			return valueObject.toString();
		}
	}
	return null;
}
 
Example #30
Source File: RefactoringUtility.java    From JDeodorant with MIT License 5 votes vote down vote up
private static boolean isEnumConstantInSwitchCaseExpression(SimpleName simpleName) {
	IBinding binding = simpleName.resolveBinding();
	if(binding != null && binding.getKind() == IBinding.VARIABLE) {
		IVariableBinding variableBinding = (IVariableBinding)binding;
		if(variableBinding.isField()) {
			return simpleName.getParent() instanceof SwitchCase && variableBinding.getDeclaringClass().isEnum();
		}
	}
	return false;
}