Java 类org.eclipse.jdt.core.dom.IBinding 实例源码
项目:eclipse.jdt.ls
文件:CastCorrectionProposal.java
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
AST ast= rewrite.getAST();
ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);
if (fCastType != null) {
return importRewrite.addImport(fCastType, ast,context, TypeLocation.CAST);
}
ASTNode node= fNodeToCast;
ASTNode parent= node.getParent();
if (parent instanceof CastExpression) {
node= parent;
parent= parent.getParent();
}
while (parent instanceof ParenthesizedExpression) {
node= parent;
parent= parent.getParent();
}
if (parent instanceof MethodInvocation) {
MethodInvocation invocation= (MethodInvocation) node.getParent();
if (invocation.getExpression() == node) {
IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node);
ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
if (bindings.length > 0) {
ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());
Type newTypeNode= importRewrite.addImport(first, ast, context, TypeLocation.CAST);
return newTypeNode;
}
}
}
Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
return newCastType;
}
项目:che
文件:CodeStyleFix.java
private void handleSimpleName(SimpleName node) {
ASTNode firstExpression = node.getParent();
if (firstExpression instanceof FieldAccess) {
while (firstExpression instanceof FieldAccess) {
firstExpression = ((FieldAccess) firstExpression).getExpression();
}
if (!(firstExpression instanceof SimpleName)) return;
node = (SimpleName) firstExpression;
} else if (firstExpression instanceof SuperFieldAccess) return;
StructuralPropertyDescriptor parentDescription = node.getLocationInParent();
if (parentDescription == VariableDeclarationFragment.NAME_PROPERTY
|| parentDescription == SwitchCase.EXPRESSION_PROPERTY) return;
IBinding binding = node.resolveBinding();
if (!(binding instanceof IVariableBinding)) return;
handleVariable(node, (IVariableBinding) binding);
}
项目:che
文件:VariableDeclarationFix.java
private boolean handleFragments(List<VariableDeclarationFragment> list, ASTNode declaration) {
List<VariableDeclarationFragment> toChange = new ArrayList<VariableDeclarationFragment>();
for (Iterator<VariableDeclarationFragment> iter = list.iterator(); iter.hasNext(); ) {
VariableDeclarationFragment fragment = iter.next();
SimpleName name = fragment.getName();
IBinding resolveBinding = name.resolveBinding();
if (canAddFinal(resolveBinding, declaration)) {
IVariableBinding varbinding = (IVariableBinding) resolveBinding;
if (varbinding.isField()) {
if (fieldCanBeFinal(fragment, varbinding)) toChange.add(fragment);
} else {
if (!fWrittenVariables.containsKey(resolveBinding)) toChange.add(fragment);
}
}
}
if (toChange.size() == 0) return false;
ModifierChangeOperation op =
new ModifierChangeOperation(declaration, toChange, Modifier.FINAL, Modifier.NONE);
fResult.add(op);
return false;
}
项目:BUILD_file_generator
文件:ReferencedClassesParser.java
private void addType(IBinding binding, String type, int startPosition) {
if (type.isEmpty()) {
return;
}
// If 'binding' refers to anything defined in this compilationUnit, don't add it.
if (compilationUnit.findDeclaringNode(binding) != null) {
return;
}
symbols.put(
type,
Metadata.create(
compilationUnit.getLineNumber(startPosition),
compilationUnit.getColumnNumber(startPosition),
false));
}
项目:eclipse.jdt.ls
文件:BindingLabelProvider.java
/**
* Returns the label for a Java element with the flags as defined by {@link JavaElementLabels}.
* @param binding The binding to render.
* @param flags The text flags as defined in {@link JavaElementLabels}
* @return the label of the binding
*/
public static String getBindingLabel(IBinding binding, long flags) {
StringBuffer buffer= new StringBuffer(60);
if (binding instanceof ITypeBinding) {
getTypeLabel(((ITypeBinding) binding), flags, buffer);
} else if (binding instanceof IMethodBinding) {
getMethodLabel(((IMethodBinding) binding), flags, buffer);
} else if (binding instanceof IVariableBinding) {
final IVariableBinding variable= (IVariableBinding) binding;
if (variable.isField()) {
getFieldLabel(variable, flags, buffer);
} else {
getLocalVariableLabel(variable, flags, buffer);
}
}
return Strings.markLTR(buffer.toString());
}
项目:eclipse.jdt.ls
文件:Bindings.java
/**
* Checks if the two arrays of bindings have the same length and
* their elements are equal. Uses
* <code>Bindings.equals(IBinding, IBinding)</code> to compare.
* @param b1 the first array of bindings. Must not be <code>null</code>.
* @param b2 the second array of bindings.
* @return boolean
*/
public static boolean equals(IBinding[] b1, IBinding[] b2) {
Assert.isNotNull(b1);
if (b1 == b2) {
return true;
}
if (b2 == null) {
return false;
}
if (b1.length != b2.length) {
return false;
}
for (int i= 0; i < b1.length; i++) {
if (! Bindings.equals(b1[i], b2[i])) {
return false;
}
}
return true;
}
项目:eclipse.jdt.ls
文件:Bindings.java
public static String getImportName(IBinding binding) {
ITypeBinding declaring= null;
switch (binding.getKind()) {
case IBinding.TYPE:
return getRawQualifiedName((ITypeBinding) binding);
case IBinding.PACKAGE:
return binding.getName() + ".*"; //$NON-NLS-1$
case IBinding.METHOD:
declaring= ((IMethodBinding) binding).getDeclaringClass();
break;
case IBinding.VARIABLE:
declaring= ((IVariableBinding) binding).getDeclaringClass();
if (declaring == null) {
return binding.getName(); // array.length
}
break;
default:
return binding.getName();
}
return JavaModelUtil.concatenateName(getRawQualifiedName(declaring), binding.getName());
}
项目:eclipse.jdt.ls
文件:ASTNodes.java
public static IBinding getEnclosingDeclaration(ASTNode node) {
while(node != null) {
if (node instanceof AbstractTypeDeclaration) {
return ((AbstractTypeDeclaration)node).resolveBinding();
} else if (node instanceof AnonymousClassDeclaration) {
return ((AnonymousClassDeclaration)node).resolveBinding();
} else if (node instanceof MethodDeclaration) {
return ((MethodDeclaration)node).resolveBinding();
} else if (node instanceof FieldDeclaration) {
List<?> fragments= ((FieldDeclaration)node).fragments();
if (fragments.size() > 0) {
return ((VariableDeclarationFragment)fragments.get(0)).resolveBinding();
}
} else if (node instanceof VariableDeclarationFragment) {
IVariableBinding variableBinding= ((VariableDeclarationFragment)node).resolveBinding();
if (variableBinding.getDeclaringMethod() != null || variableBinding.getDeclaringClass() != null)
{
return variableBinding;
// workaround for incomplete wiring of DOM bindings: keep searching when variableBinding is unparented
}
}
node= node.getParent();
}
return null;
}
项目:eclipse.jdt.ls
文件:LinkedNodeFinder.java
/**
* Find all nodes connected to the given name node. If the node has a binding then all nodes connected
* to this binding are returned. If the node has no binding, then all nodes that also miss a binding and have
* the same name are returned.
* @param root The root of the AST tree to search
* @param name The node to find linked nodes for
* @return Return
*/
public static SimpleName[] findByNode(ASTNode root, SimpleName name) {
IBinding binding = name.resolveBinding();
if (binding != null) {
return findByBinding(root, binding);
}
SimpleName[] names= findByProblems(root, name);
if (names != null) {
return names;
}
int parentKind= name.getParent().getNodeType();
if (parentKind == ASTNode.LABELED_STATEMENT || parentKind == ASTNode.BREAK_STATEMENT || parentKind == ASTNode.CONTINUE_STATEMENT) {
ArrayList<SimpleName> res= new ArrayList<>();
LabelFinder nodeFinder= new LabelFinder(name, res);
root.accept(nodeFinder);
return res.toArray(new SimpleName[res.size()]);
}
return new SimpleName[] { name };
}
项目:eclipse.jdt.ls
文件:LinkedNodeFinder.java
@Override
public boolean visit(SimpleName node) {
IBinding binding= node.resolveBinding();
if (binding == null) {
return false;
}
binding= getDeclaration(binding);
if (fBinding == binding) {
fResult.add(node);
} else if (binding.getKind() != fBinding.getKind()) {
return false;
} else if (binding.getKind() == IBinding.METHOD) {
IMethodBinding curr= (IMethodBinding) binding;
IMethodBinding methodBinding= (IMethodBinding) fBinding;
if (methodBinding.overrides(curr) || curr.overrides(methodBinding)) {
fResult.add(node);
}
}
return false;
}
项目:eclipse.jdt.ls
文件:OrganizeImportsOperation.java
private void addStaticImports(
Collection<SimpleName> staticReferences,
ImportRewrite importRewrite,
UnresolvableImportMatcher unresolvableImportMatcher) {
for (SimpleName name : staticReferences) {
IBinding binding= name.resolveBinding();
if (binding != null) {
importRewrite.addStaticImport(binding);
} else {
// This could be an unresolvable reference to a static member.
String identifier= name.getIdentifier();
Set<String> unresolvableImports= unresolvableImportMatcher.matchStaticImports(identifier);
for (String unresolvableImport : unresolvableImports) {
int lastDotIndex= unresolvableImport.lastIndexOf('.');
// It's OK to skip invalid imports.
if (lastDotIndex != -1) {
String declaringTypeName= unresolvableImport.substring(0, lastDotIndex);
String simpleName= unresolvableImport.substring(lastDotIndex + 1);
// Whether name refers to a field or to a method is unknown.
boolean isField= false;
importRewrite.addStaticImport(declaringTypeName, simpleName, isField, UNRESOLVABLE_IMPORT_CONTEXT);
}
}
}
}
}
项目:eclipse.jdt.ls
文件:StubUtility.java
private static String[] getParameterTypeNamesForSeeTag(IMethod overridden) {
try {
ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
parser.setProject(overridden.getJavaProject());
IBinding[] bindings = parser.createBindings(new IJavaElement[] { overridden }, null);
if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) {
return getParameterTypeNamesForSeeTag((IMethodBinding) bindings[0]);
}
} catch (IllegalStateException e) {
// method does not exist
}
// fall back code. Not good for generic methods!
String[] paramTypes = overridden.getParameterTypes();
String[] paramTypeNames = new String[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
paramTypeNames[i] = Signature.toString(Signature.getTypeErasure(paramTypes[i]));
}
return paramTypeNames;
}
项目:eclipse.jdt.ls
文件:UnusedCodeFix.java
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException {
ASTRewrite rewrite= cuRewrite.getASTRewrite();
IBinding binding= fUnusedName.resolveBinding();
CompilationUnit root= (CompilationUnit) fUnusedName.getRoot();
String displayString= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description;
TextEditGroup group= createTextEditGroup(displayString, cuRewrite);
if (binding.getKind() == IBinding.TYPE) {
ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
ASTNode declaration= root.findDeclaringNode(decl);
if (declaration.getParent() instanceof TypeDeclarationStatement) {
declaration= declaration.getParent();
}
rewrite.remove(declaration, group);
}
}
项目:eclipse.jdt.ls
文件:UnusedCodeFix.java
private String getDisplayString(IBinding binding) {
switch (binding.getKind()) {
case IBinding.TYPE:
return FixMessages.UnusedCodeFix_RemoveUnusedType_description;
case IBinding.METHOD:
if (((IMethodBinding) binding).isConstructor()) {
return FixMessages.UnusedCodeFix_RemoveUnusedConstructor_description;
} else {
return FixMessages.UnusedCodeFix_RemoveUnusedPrivateMethod_description;
}
case IBinding.VARIABLE:
if (((IVariableBinding) binding).isField()) {
return FixMessages.UnusedCodeFix_RemoveUnusedField_description;
} else {
return FixMessages.UnusedCodeFix_RemoveUnusedVariabl_description;
}
default:
return ""; //$NON-NLS-1$
}
}
项目:eclipse.jdt.ls
文件:UnusedCodeFix.java
public static UnusedCodeFix createUnusedMemberFix(CompilationUnit compilationUnit, IProblemLocation problem, boolean removeAllAssignements) {
if (isUnusedMember(problem)) {
SimpleName name= getUnusedName(compilationUnit, problem);
if (name != null) {
IBinding binding= name.resolveBinding();
if (binding != null) {
if (isFormalParameterInEnhancedForStatement(name)) {
return null;
}
String label= getDisplayString(name, binding, removeAllAssignements);
RemoveUnusedMemberOperation operation= new RemoveUnusedMemberOperation(new SimpleName[] { name }, removeAllAssignements);
return new UnusedCodeFix(label, compilationUnit, new CompilationUnitRewriteOperation[] { operation }, getCleanUpOptions(binding, removeAllAssignements));
}
}
}
return null;
}
项目:eclipse.jdt.ls
文件:UnusedCodeFix.java
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$
}
}
项目:eclipse.jdt.ls
文件:ImportRemover.java
public IBinding[] getImportsToRemove() {
ArrayList<SimpleName> importNames= new ArrayList<>();
ArrayList<SimpleName> staticNames= new ArrayList<>();
ImportReferencesCollector.collect(fRoot, fProject, null, importNames, staticNames);
List<SimpleName> removedRefs= new ArrayList<>();
List<SimpleName> unremovedRefs= new ArrayList<>();
divideTypeRefs(importNames, staticNames, removedRefs, unremovedRefs);
if (removedRefs.size() == 0) {
return new IBinding[0];
}
HashMap<String, IBinding> potentialRemoves= getPotentialRemoves(removedRefs);
for (Iterator<SimpleName> iterator= unremovedRefs.iterator(); iterator.hasNext();) {
SimpleName name= iterator.next();
potentialRemoves.remove(name.getIdentifier());
}
Collection<IBinding> importsToRemove= potentialRemoves.values();
return importsToRemove.toArray(new IBinding[importsToRemove.size()]);
}
项目:eclipse.jdt.ls
文件:FlowAnalyzer.java
@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));
}
}
}
项目:eclipse.jdt.ls
文件:MissingReturnTypeInLambdaCorrectionProposal.java
@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;
}
项目:eclipse.jdt.ls
文件:AddArgumentCorrectionProposal.java
private Expression evaluateArgumentExpressions(AST ast, ITypeBinding requiredType, String key) {
CompilationUnit root= (CompilationUnit) fCallerNode.getRoot();
int offset= fCallerNode.getStartPosition();
Expression best= null;
ITypeBinding bestType= null;
ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
IBinding[] bindings= analyzer.getDeclarationsInScope(offset, ScopeAnalyzer.VARIABLES);
for (int i= 0; i < bindings.length; i++) {
IVariableBinding curr= (IVariableBinding) bindings[i];
ITypeBinding type= curr.getType();
if (type != null && canAssign(type, requiredType) && testModifier(curr)) {
if (best == null || isMoreSpecific(bestType, type)) {
best= ast.newSimpleName(curr.getName());
bestType= type;
}
}
}
Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, requiredType);
if (best == null) {
best= defaultExpression;
}
return best;
}
项目:eclipse.jdt.ls
文件:GetterSetterCorrectionSubProcessor.java
private static boolean addGetterSetterProposal(IInvocationContext context, ASTNode coveringNode, Collection<CUCorrectionProposal> proposals) {
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;
}
CUCorrectionProposal proposal = getProposal(context.getCompilationUnit(), sn, variableBinding);
if (proposal != null) {
proposals.add(proposal);
}
return true;
}
项目:eclipse.jdt.ls
文件:NewVariableCorrectionProposal.java
private Type evaluateVariableType(AST ast, ImportRewrite imports, ImportRewriteContext importRewriteContext, IBinding targetContext, TypeLocation location) {
if (fOriginalNode.getParent() instanceof MethodInvocation) {
MethodInvocation parent= (MethodInvocation) fOriginalNode.getParent();
if (parent.getExpression() == fOriginalNode) {
// _x_.foo() -> guess qualifier type by looking for a type with method 'foo'
ITypeBinding[] bindings= ASTResolving.getQualifierGuess(fOriginalNode.getRoot(), parent.getName().getIdentifier(), parent.arguments(), targetContext);
if (bindings.length > 0) {
return imports.addImport(bindings[0], ast, importRewriteContext, location);
}
}
}
ITypeBinding binding= ASTResolving.guessBindingForReference(fOriginalNode);
if (binding != null) {
if (binding.isWildcardType()) {
binding= ASTResolving.normalizeWildcardType(binding, isVariableAssigned(), ast);
if (binding == null) {
// only null binding applies
binding= ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
}
return imports.addImport(binding, ast, importRewriteContext, location);
}
// no binding, find type AST node instead -> ABC a= x-> use 'ABC' as is
Type type = ASTResolving.guessTypeForReference(ast, fOriginalNode);
if (type != null) {
return type;
}
if (fVariableKind == CONST_FIELD) {
return ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
}
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
项目:eclipse.jdt.ls
文件:UnresolvedElementsSubProcessor.java
private static String getExpressionBaseName(Expression expr) {
IBinding argBinding= Bindings.resolveExpressionBinding(expr, true);
if (argBinding instanceof IVariableBinding) {
IJavaProject project= null;
ASTNode root= expr.getRoot();
if (root instanceof CompilationUnit) {
ITypeRoot typeRoot= ((CompilationUnit) root).getTypeRoot();
if (typeRoot != null) {
project= typeRoot.getJavaProject();
}
}
return StubUtility.getBaseName((IVariableBinding)argBinding, project);
}
if (expr instanceof SimpleName) {
return ((SimpleName) expr).getIdentifier();
}
return null;
}
项目:eclipse.jdt.ls
文件:JavadocTagsSubProcessor.java
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocation problem,
Collection<CUCorrectionProposal> 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, context.getCompilationUnit(),
rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME);
proposals.add(proposal);
}
项目:code
文件:WorkspaceUtilities.java
/**
* Goes through a list of compilation units and parses them. The act of parsing creates the AST structures from the
* source code.
*
* @param compilationUnits the list of compilation units to parse
* @return the mapping from compilation unit to the AST roots of each
*/
public static Map<ICompilationUnit, ASTNode> parseCompilationUnits(List<ICompilationUnit> compilationUnits) {
if (compilationUnits == null) {
throw new CrystalRuntimeException("null list of compilation units");
}
ICompilationUnit[] compUnits = compilationUnits.toArray(new ICompilationUnit[0]);
final Map<ICompilationUnit, ASTNode> parsedCompilationUnits = new HashMap<ICompilationUnit, ASTNode>();
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
parser.setProject(WorkspaceUtilities.javaProject);
parser.createASTs(compUnits, new String[0], new ASTRequestor() {
@Override
public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
parsedCompilationUnits.put(unit, node);
}
@Override
public final void acceptBinding(final String key, final IBinding binding) {
// Do nothing
}
}, null);
return parsedCompilationUnits;
}
项目:code
文件:WorkspaceUtilities.java
/**
* Goes through a list of compilation units and parses them. The act of parsing creates the AST structures from the
* source code.
*
* @param compilationUnits the list of compilation units to parse
* @return the mapping from compilation unit to the AST roots of each
*/
public static Map<ICompilationUnit, ASTNode> parseCompilationUnits(List<ICompilationUnit> compilationUnits) {
if (compilationUnits == null) {
throw new CrystalRuntimeException("null list of compilation units");
}
ICompilationUnit[] compUnits = compilationUnits.toArray(new ICompilationUnit[0]);
final Map<ICompilationUnit, ASTNode> parsedCompilationUnits = new HashMap<ICompilationUnit, ASTNode>();
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
parser.setProject(WorkspaceUtilities.javaProject);
parser.createASTs(compUnits, new String[0], new ASTRequestor() {
@Override
public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
parsedCompilationUnits.put(unit, node);
}
@Override
public final void acceptBinding(final String key, final IBinding binding) {
// Do nothing
}
}, null);
return parsedCompilationUnits;
}
项目:code
文件:Utils.java
/**
* for an assignment x = y returns the variable binding of x
*
* @param varBinding
* @param assignment
* @return
*/
private static IVariableBinding getLeftHandSideVarBinding(Assignment assignment) {
Expression leftHnsd = assignment.getLeftHandSide();
if (leftHnsd instanceof SimpleName) {
IBinding bind = ((SimpleName) leftHnsd).resolveBinding();
if (bind instanceof IVariableBinding) {
return ((IVariableBinding) bind).getVariableDeclaration();
}
}
if (leftHnsd instanceof FieldAccess) {
FieldAccess fa = (FieldAccess) leftHnsd;
return fa.resolveFieldBinding();
}
// Leave it null - cannot determine actual domains for arrays
// workaround for bugs related to objects created in complex expression
// if (leftHnsd instanceof ArrayAccess) {
// ArrayAccess aa = (ArrayAccess) leftHnsd;
// return getArrayAccessVarBinding(aa);
// }
return null;
}
项目:code
文件:WorkspaceUtilities.java
/**
* Goes through a list of compilation units and parses them. The act of parsing creates the AST structures from the
* source code.
*
* @param compilationUnits the list of compilation units to parse
* @return the mapping from compilation unit to the AST roots of each
*/
public static Map<ICompilationUnit, ASTNode> parseCompilationUnits(List<ICompilationUnit> compilationUnits) {
if (compilationUnits == null) {
throw new CrystalRuntimeException("null list of compilation units");
}
ICompilationUnit[] compUnits = compilationUnits.toArray(new ICompilationUnit[0]);
final Map<ICompilationUnit, ASTNode> parsedCompilationUnits = new HashMap<ICompilationUnit, ASTNode>();
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
parser.setProject(WorkspaceUtilities.javaProject);
parser.createASTs(compUnits, new String[0], new ASTRequestor() {
@Override
public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
parsedCompilationUnits.put(unit, node);
}
@Override
public final void acceptBinding(final String key, final IBinding binding) {
// Do nothing
}
}, null);
return parsedCompilationUnits;
}
项目:Sparrow
文件:OutCodeVisitor.java
@Override
public boolean visit(MethodDeclaration methodDeclaration) {
IBinding binding = methodDeclaration.resolveBinding();
if (binding == null)
return false;
currentMethod = (IMethod) binding.getJavaElement();
if (currentMethod != null) {
methodDetails = new MethodDetails();
String handleIdentifier = currentMethod.getHandleIdentifier();
allDetails.put(handleIdentifier, methodDetails);
methodDetails.setModifiers(methodDeclaration.getModifiers());
methodDetails.setParameters(getParameters(methodDeclaration.parameters()));
Type returnType2 = methodDeclaration.getReturnType2();
if (returnType2 != null) {
ITypeBinding typeBinding = returnType2.resolveBinding();
IJavaElement returnType = typeBinding.getJavaElement();
if (returnType instanceof IType) {
methodDetails.setReturnType((IType) returnType);
}
}
}
return true;
}
项目:Sparrow
文件:OutCodeVisitor.java
@Override
public boolean visit(SimpleName node) {
if (currentMethod == null)
return false;
IBinding binding = node.resolveBinding();
if (binding == null)
return false;
if (node.isDeclaration())
return true;
if (node.resolveBinding() instanceof IVariableBinding) {
IVariableBinding iVariableBinding = (IVariableBinding) node.resolveBinding();
if (iVariableBinding.isField()) {
IVariableBinding variableDeclarationBinding = iVariableBinding.getVariableDeclaration();
if (variableDeclarationBinding.getDeclaringClass() != null) {
IJavaElement accessedField = variableDeclarationBinding.getJavaElement();
if (accessedField instanceof IField) {
if (!((IField) accessedField).isReadOnly())
methodDetails.addAccess((IField) accessedField);
}
}
}
}
return true;
}
项目:che
文件:SemanticHighlightings.java
@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();
}
项目:che
文件:NullAnnotationsRewriteOperations.java
boolean hasNonNullDefault(IBinding enclosingElement) {
if (!fRemoveIfNonNullByDefault) return false;
IAnnotationBinding[] annotations = enclosingElement.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
IAnnotationBinding annot = annotations[i];
if (annot.getAnnotationType().getQualifiedName().equals(fNonNullByDefaultName)) {
IMemberValuePairBinding[] pairs = annot.getDeclaredMemberValuePairs();
if (pairs.length > 0) {
// is default cancelled by "false" or "value=false" ?
for (int j = 0; j < pairs.length; j++)
if (pairs[j].getKey() == null || pairs[j].getKey().equals("value")) // $NON-NLS-1$
return (pairs[j].getValue() != Boolean.FALSE);
}
return true;
}
}
if (enclosingElement instanceof IMethodBinding) {
return hasNonNullDefault(((IMethodBinding) enclosingElement).getDeclaringClass());
} else if (enclosingElement instanceof ITypeBinding) {
ITypeBinding typeBinding = (ITypeBinding) enclosingElement;
if (typeBinding.isLocal()) return hasNonNullDefault(typeBinding.getDeclaringMethod());
else if (typeBinding.isMember()) return hasNonNullDefault(typeBinding.getDeclaringClass());
else return hasNonNullDefault(typeBinding.getPackage());
}
return false;
}
项目:che
文件:SnippetFinder.java
@Override
public boolean match(SimpleName candidate, Object s) {
if (!(s instanceof SimpleName)) return false;
SimpleName snippet = (SimpleName) s;
if (candidate.isDeclaration() != snippet.isDeclaration()) return false;
IBinding cb = candidate.resolveBinding();
IBinding sb = snippet.resolveBinding();
if (cb == null || sb == null) return false;
IVariableBinding vcb = ASTNodes.getVariableBinding(candidate);
IVariableBinding vsb = ASTNodes.getVariableBinding(snippet);
if (vcb == null || vsb == null) return Bindings.equals(cb, sb);
if (!vcb.isField() && !vsb.isField() && Bindings.equals(vcb.getType(), vsb.getType())) {
SimpleName mapped = fMatch.getMappedName(vsb);
if (mapped != null) {
IVariableBinding mappedBinding = ASTNodes.getVariableBinding(mapped);
if (!Bindings.equals(vcb, mappedBinding)) return false;
}
fMatch.addLocal(vsb, candidate);
return true;
}
return Bindings.equals(cb, sb);
}
项目:che
文件:ConvertAnonymousToNestedRefactoring.java
private boolean accessesAnonymousFields() {
List<IVariableBinding> anonymousInnerFieldTypes = getAllEnclosingAnonymousTypesField();
List<IBinding> accessedField = getAllAccessedFields();
final Iterator<IVariableBinding> it = anonymousInnerFieldTypes.iterator();
while (it.hasNext()) {
final IVariableBinding variableBinding = it.next();
final Iterator<IBinding> it2 = accessedField.iterator();
while (it2.hasNext()) {
IVariableBinding variableBinding2 = (IVariableBinding) it2.next();
if (Bindings.equals(variableBinding, variableBinding2)) {
return true;
}
}
}
return false;
}
项目:che
文件:SourceAnalyzer.java
@Override
public boolean visit(SimpleName node) {
addReferencesToName(node);
IBinding binding = node.resolveBinding();
if (binding instanceof ITypeBinding) {
ITypeBinding type = (ITypeBinding) binding;
if (type.isTypeVariable()) {
addTypeVariableReference(type, node);
}
} else if (binding instanceof IVariableBinding) {
IVariableBinding vb = (IVariableBinding) binding;
if (vb.isField() && !isStaticallyImported(node)) {
Name topName = ASTNodes.getTopMostName(node);
if (node == topName || node == ASTNodes.getLeftMostSimpleName(topName)) {
StructuralPropertyDescriptor location = node.getLocationInParent();
if (location != SingleVariableDeclaration.NAME_PROPERTY
&& location != VariableDeclarationFragment.NAME_PROPERTY) {
fImplicitReceivers.add(node);
}
}
} else if (!vb.isField()) {
// we have a local. Check if it is a parameter.
ParameterData data = fParameters.get(binding);
if (data != null) {
ASTNode parent = node.getParent();
if (parent instanceof Expression) {
int precedence = OperatorPrecedence.getExpressionPrecedence((Expression) parent);
if (precedence != Integer.MAX_VALUE) {
data.setOperatorPrecedence(precedence);
}
}
}
}
}
return true;
}
项目:che
文件:SemanticHighlightings.java
@Override
public boolean consumes(SemanticToken token) {
IBinding binding = getBinding(token);
if (binding != null) {
if (binding.isDeprecated()) return true;
if (binding instanceof IMethodBinding) {
IMethodBinding methodBinding = (IMethodBinding) binding;
if (methodBinding.isConstructor() && methodBinding.getJavaElement() == null) {
ITypeBinding declaringClass = methodBinding.getDeclaringClass();
if (declaringClass.isAnonymous()) {
ITypeBinding[] interfaces = declaringClass.getInterfaces();
if (interfaces.length > 0) return interfaces[0].isDeprecated();
else return declaringClass.getSuperclass().isDeprecated();
}
return declaringClass.isDeprecated();
}
}
}
return false;
}
项目:Slicer
文件:BDDSeedVisitor.java
/**
* Add the variable to the node aliases.
*/
public boolean visit(SimpleName node){
/* All we really need from this is the variable binding. */
IBinding binding = node.resolveBinding();
/* Since we already intercept method calls, we can be sure
* that this isn't part of a method call. */
if(binding == null){
if(!seedVariables.contains(node.getFullyQualifiedName()))
seedVariables.add(node.getFullyQualifiedName());
}
else if(binding instanceof IVariableBinding){
if(!seedVariables.contains(binding.getKey()))
seedVariables.add(binding.getKey());
}
return false;
}
项目:Slicer
文件:BDDSeedVisitor.java
/**
* Add the variable to the node aliases.
*/
public boolean visit(FieldAccess node){
/* All we really need from this is the variable binding. */
IBinding binding = node.resolveFieldBinding();
if(binding == null){
if(!seedVariables.contains(node.getName().toString()))
seedVariables.add(node.getName().toString());
}
else if(binding instanceof IVariableBinding){
if(!seedVariables.contains(binding.getKey()))
seedVariables.add(binding.getKey());
}
return false;
}
项目:che
文件:ImportRemover.java
public IBinding[] getImportsToRemove() {
ArrayList<SimpleName> importNames = new ArrayList<SimpleName>();
ArrayList<SimpleName> staticNames = new ArrayList<SimpleName>();
ImportReferencesCollector.collect(fRoot, fProject, null, importNames, staticNames);
List<SimpleName> removedRefs = new ArrayList<SimpleName>();
List<SimpleName> unremovedRefs = new ArrayList<SimpleName>();
divideTypeRefs(importNames, staticNames, removedRefs, unremovedRefs);
if (removedRefs.size() == 0) return new IBinding[0];
HashMap<String, IBinding> potentialRemoves = getPotentialRemoves(removedRefs);
for (Iterator<SimpleName> iterator = unremovedRefs.iterator(); iterator.hasNext(); ) {
SimpleName name = iterator.next();
potentialRemoves.remove(name.getIdentifier());
}
Collection<IBinding> importsToRemove = potentialRemoves.values();
return importsToRemove.toArray(new IBinding[importsToRemove.size()]);
}
项目:Slicer
文件:FDDVisitor.java
/**
* Add the variable to the node aliases.
*/
public boolean visit(QualifiedName node){
/* All we really need from this is the variable binding. */
IBinding binding = node.resolveBinding();
if(binding == null){
if(this.aliases.contains(node.getFullyQualifiedName())){
this.result = true;
return false;
}
}
else if(binding instanceof IVariableBinding){
if(this.aliases.contains(binding.getKey())){
this.result = true;
return false;
}
}
return true;
}