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; }
private static boolean isContext(ITypeBinding tbinding) { String executionContextClass = org.graphwalker.core.machine.ExecutionContext.class.getName(); String contextClass = org.graphwalker.core.machine.Context.class.getName(); while (tbinding != null) { String clazz = tbinding.getQualifiedName(); if (executionContextClass.equals(clazz)) return true; if (contextClass.equals(clazz)) return true; ITypeBinding[] interfaces = tbinding.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { ITypeBinding interf = interfaces[i]; if (contextClass.equals(interf.getQualifiedName())) return true; } tbinding = tbinding.getSuperclass(); } return false; }
private void handleTypeBinding(ASTNode node, ITypeBinding typeBinding, boolean includeTypeParameters) { if (typeBinding == null) { StructuralPropertyDescriptor locationInParent = node.getLocationInParent(); //System.out.println(locationInParent.getId() + " has no type binding"); } else { List<ITypeBinding> rawTypes = new ArrayList<ITypeBinding>(); Set<String> dejavu = new HashSet<String>(); this.appendRawTypes(rawTypes, dejavu, typeBinding, includeTypeParameters); for (ITypeBinding rawType : rawTypes) { if (!this.ignoreType(rawType)) { this.onTypeAccess(node, rawType); } } } }
public static String getKeyFromMethodBinding(IMethodBinding binding) { StringBuilder sb = new StringBuilder(); String className = binding.getDeclaringClass().getErasure().getQualifiedName(); sb.append(className); sb.append('.'); String methodName = binding.isConstructor() ? "" : binding.getName(); sb.append(methodName); //if (methodName.equals("allObjectsSorted")) { // System.out.println(); //} sb.append('('); ITypeBinding[] parameters = binding.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { if (i > 0) { sb.append(", "); } ITypeBinding type = parameters[i]; sb.append(type.getErasure().getName()); } sb.append(')'); return sb.toString(); }
public static String getKeyFromMethodBinding(IMethodBinding binding) { StringBuilder sb = new StringBuilder(); String className = binding.getDeclaringClass().getErasure().getQualifiedName(); sb.append(className); sb.append('#'); String methodName = binding.isConstructor() ? "" : binding.getName(); sb.append(methodName); //if (methodName.equals("allObjectsSorted")) { // System.out.println(); //} sb.append('('); ITypeBinding[] parameters = binding.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { if (i > 0) { sb.append(", "); } ITypeBinding type = parameters[i]; sb.append(type.getErasure().getName()); } sb.append(')'); return sb.toString(); }
public boolean visit(CastExpression node) { if (mtbStack.isEmpty()) // not part of a method return true; Expression expression = node.getExpression(); ITypeBinding type = node.getType().resolveBinding(); IMethodBinding mtb = mtbStack.peek(); String exprStr = expression.toString(); String typeStr = getQualifiedName(type); String methodStr = getQualifiedName(mtb); exprStr = edit_str(exprStr); facts.add(Fact.makeCastFact(exprStr, typeStr, methodStr)); return true; }
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); }
static void createName(ITypeBinding type, boolean includePackage, List<String> list) { ITypeBinding baseType = type; if (type.isArray()) { baseType = type.getElementType(); } if (!baseType.isPrimitive() && !baseType.isNullType()) { ITypeBinding declaringType = baseType.getDeclaringClass(); if (declaringType != null) { createName(declaringType, includePackage, list); } else if (includePackage && !baseType.getPackage().isUnnamed()) { String[] components = baseType.getPackage().getNameComponents(); for (int i = 0; i < components.length; i++) { list.add(components[i]); } } } if (!baseType.isAnonymous()) { list.add(type.getName()); } else { list.add("$local$"); //$NON-NLS-1$ } }
private static String getUniqueMethodName(ASTNode astNode, String suggestedName) throws JavaModelException { while (astNode != null && !(astNode instanceof TypeDeclaration)) { astNode = astNode.getParent(); } if (astNode instanceof TypeDeclaration) { ITypeBinding typeBinding = ((TypeDeclaration) astNode).resolveBinding(); if (typeBinding == null) { return suggestedName; } IType type = (IType) typeBinding.getJavaElement(); if (type == null) { return suggestedName; } IMethod[] methods = type.getMethods(); int suggestedPostfix = 2; String resultName = suggestedName; while (suggestedPostfix < 1000) { if (!hasMethod(methods, resultName)) { return resultName; } resultName = suggestedName + suggestedPostfix++; } } return suggestedName; }
private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List<IMethodBinding> similarElements, ASTNode invocationNode, List<Expression> arguments, Collection<CUCorrectionProposal> proposals) throws CoreException { int nSimilarElements= similarElements.size(); ITypeBinding[] argTypes= getArgumentTypes(arguments); if (argTypes == null || nSimilarElements == 0) { return; } for (int i= 0; i < nSimilarElements; i++) { IMethodBinding elem = similarElements.get(i); int diff= elem.getParameterTypes().length - argTypes.length; if (diff == 0) { int nProposals= proposals.size(); doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals); if (nProposals != proposals.size()) { return; // only suggest for one method (avoid duplicated proposals) } } else if (diff > 0) { doMoreParameters(context, invocationNode, argTypes, elem, proposals); } else { doMoreArguments(context, invocationNode, arguments, argTypes, elem, proposals); } } }
/** * Perform generic type substitution... * Currently, just uses string substitution. * Could be problematic (e.g., if it constructs invalid types). * * @return */ public static String typeFtoA(ITypeBinding typeBinding) { String formalType = ""; if(typeBinding.isParameterizedType()){ ITypeBinding genericTypeBinding = typeBinding.getTypeDeclaration(); ITypeBinding[] typeArguments = typeBinding.getTypeArguments(); ITypeBinding[] typeParameters = genericTypeBinding.getTypeParameters(); formalType = typeBinding.getQualifiedName(); int i =0; for (ITypeBinding iTypeBinding : typeParameters) { String typeParameterName = iTypeBinding.getQualifiedName(); String typeArgumentName = typeArguments[i].getQualifiedName(); formalType = formalType.replace(typeArgumentName, typeParameterName); } } else{ formalType = typeBinding.getQualifiedName(); } return formalType; }
public static boolean isMethodCompatible(MethodDeclaration methodDeclaration) { Crystal instance = Crystal.getInstance(); TypeDeclaration enclosingType = methodDeclaration.enclosingType; if(enclosingType!=null){ ITypeBinding typeBinding = instance .getTypeBindingFromName(enclosingType .getFullyQualifiedName()); for(IMethodBinding methodBinding : typeBinding.getDeclaredMethods()){ if(methodDeclaration.methodName.compareTo(methodBinding.getName()) == 0){ if(!isMethodCompatible(methodBinding)){ return false; } } } } return true; }
private static String asString(IMethodBinding method) { StringBuffer result= new StringBuffer(); result.append(method.getDeclaringClass().getName()); result.append(':'); result.append(method.getName()); result.append('('); ITypeBinding[] parameters= method.getParameterTypes(); int lastComma= parameters.length - 1; for (int i= 0; i < parameters.length; i++) { ITypeBinding parameter= parameters[i]; result.append(parameter.getName()); if (i < lastComma) { result.append(", "); //$NON-NLS-1$ } } result.append(')'); return result.toString(); }
public static ast.TypeDeclaration createFrom(ITypeBinding typeBinding){ ast.TypeDeclaration retNode = null; Adapter factory = Adapter.getInstance(); AstNode astNode = factory.get(typeBinding); if(astNode instanceof ast.TypeDeclaration){ retNode = (ast.TypeDeclaration)astNode; }else{ retNode = ast.TypeDeclaration.create(); retNode.type = TraceabilityFactory.getType(typeBinding); retNode.fields = TraceabilityFactory.getDeclaredFields(typeBinding); factory.map(typeBinding, retNode); // typeBinding.getQualifiedName() // XXX. Has the name been set yet? factory.mapTypeDeclaration(retNode); } return retNode; }
/** * A method to pin down inner of the qualifiers of a generic type * */ private void pinDownInner() { // TODO Auto-generated method stub TM tm = currentTM.copyTypeMapping(currentTM.getKey()); for (Variable var : tm.keySet()) { if(var instanceof TACNewExpr){ TACNewExpr newExprVar = (TACNewExpr)var; ITypeBinding instantiatedType = newExprVar.resolveType(); if(instantiatedType.isParameterizedType()){ Set<OType> varSet = new HashSet<OType>(tm.getAnalysisResult(var)); if(varSet.size()>1){ RankingStrategy ranking = RankingStrategy.getInstance(); OType highestQualifier = ranking.pickFromSet(varSet, null); varSet.clear(); varSet.add(highestQualifier); tm.putTypeMapping(var, varSet); TM newTM = runTFs(tm); if(!newTM.isDiscarded){ currentTM = newTM; } } } } } }
/** * Finds the method specified by <code>methodName</code> and <code>parameters</code> in * the given <code>type</code>. Returns <code>null</code> if no such method exists. * @param type The type to search the method in * @param methodName The name of the method to find * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only * the name is matched and parameters are ignored. * @return the method binding representing the method */ public static IMethodBinding findMethodInType(ITypeBinding type, String methodName, ITypeBinding[] parameters) { if (type.isPrimitive()) { return null; } IMethodBinding[] methods= type.getDeclaredMethods(); for (int i= 0; i < methods.length; i++) { if (parameters == null) { if (methodName.equals(methods[i].getName())) { return methods[i]; } } else { if (isEqualMethod(methods[i], methodName, parameters)) { return methods[i]; } } } return null; }
public static String getMethodSignature(String name, ITypeBinding[] params, boolean isVarArgs) { StringBuffer buf= new StringBuffer(); buf.append(name).append('('); for (int i= 0; i < params.length; i++) { if (i > 0) { buf.append(JavaElementLabels.COMMA_STRING); } if (isVarArgs && i == params.length - 1) { buf.append(getTypeSignature(params[i].getElementType())); buf.append("..."); //$NON-NLS-1$ } else { buf.append(getTypeSignature(params[i])); } } buf.append(')'); return BasicElementLabels.getJavaElementName(buf.toString()); }
private static void initTypeStructures() { TypeInfo typeInfo = TypeInfo.getInstance(); Crystal crystal = Crystal.getInstance(); // Create a copy, since we may discover additional types, from super classes, and super-interfaces // To avoid concurrent modification exception Set<Type> allTypes = new HashSet<Type>(); allTypes.addAll(typeInfo.getAllTypes()); for (Type type : allTypes) { String fullyQualifiedName = type.getFullyQualifiedName(); ITypeBinding typeBinding = crystal.getTypeBindingFromName(fullyQualifiedName); if (typeBinding != null) { typeInfo.reviveTypeFromBinding(type, typeBinding); } else { // HACK: Is it normal to not be able to resolve primitive types? // Cannot resolve typebinding: double[] System.err.println("Cannot resolve typebinding: " + fullyQualifiedName); } } }
public ITypeBinding getTypeBinding(AST ast) { boolean couldBeObject= false; for (int i= 0; i < fResult.size(); i++) { ReturnStatement node= fResult.get(i); Expression expr= node.getExpression(); if (expr != null) { ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding()); if (binding != null) { return binding; } else { couldBeObject= true; } } else { return ast.resolveWellKnownType("void"); //$NON-NLS-1$ } } if (couldBeObject) { return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } return ast.resolveWellKnownType("void"); //$NON-NLS-1$ }
private static Set<ITypeBinding> getTypeBoundsForSubsignature(ITypeBinding typeParameter) { ITypeBinding[] typeBounds= typeParameter.getTypeBounds(); int count= typeBounds.length; if (count == 0) { return Collections.emptySet(); } Set<ITypeBinding> result= new HashSet<>(typeBounds.length); for (int i= 0; i < typeBounds.length; i++) { ITypeBinding bound= typeBounds[i]; if ("java.lang.Object".equals(typeBounds[0].getQualifiedName())) { continue; } else if (containsTypeVariables(bound)) { result.add(bound.getErasure()); // try to achieve effect of "rename type variables" } else if (bound.isRawType()) { result.add(bound.getTypeDeclaration()); } else { result.add(bound); } } return result; }
protected void addNewTypeBinding(ITypeBinding typeBinding) { // Skip over primitive types, which includes void if (typeBinding == null || typeBinding.isPrimitive()) { return; } String key = typeBinding.getKey(); if (!mapKeyToType.containsKey(key)) { mapKeyToType.put(key, typeBinding); } String qualifiedName = typeBinding.getQualifiedName(); if (!mapNameToType.containsKey(qualifiedName)) { mapNameToType.put(qualifiedName, typeBinding); } // Add supertypes, and implemented interfaces as well! ITypeBinding superclassType = typeBinding.getSuperclass(); if ( superclassType != null ) { addNewTypeBinding(superclassType); } ITypeBinding[] interfaces = typeBinding.getInterfaces(); for(ITypeBinding itfBinding : interfaces) { addNewTypeBinding(itfBinding); } }
/** * Returns the type binding of the node's type context or null if the node is inside * an annotation, type parameter, super type declaration, or Javadoc of a top level type. * The result of this method is equal to the result of {@link #getBindingOfParentType(ASTNode)} for nodes in the type's body. * * @param node an AST node * @return the type binding of the node's parent type context, or <code>null</code> */ public static ITypeBinding getBindingOfParentTypeContext(ASTNode node) { StructuralPropertyDescriptor lastLocation= null; while (node != null) { if (node instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration decl= (AbstractTypeDeclaration) node; if (lastLocation == decl.getBodyDeclarationsProperty() || lastLocation == decl.getJavadocProperty()) { return decl.resolveBinding(); } else if (decl instanceof EnumDeclaration && lastLocation == EnumDeclaration.ENUM_CONSTANTS_PROPERTY) { return decl.resolveBinding(); } } else if (node instanceof AnonymousClassDeclaration) { return ((AnonymousClassDeclaration) node).resolveBinding(); } lastLocation= node.getLocationInParent(); node= node.getParent(); } return null; }
private void sortTypes(ITypeBinding[] typeProposals) { ITypeBinding oldType; if (fBinding instanceof IMethodBinding) { oldType= ((IMethodBinding) fBinding).getReturnType(); } else { oldType= ((IVariableBinding) fBinding).getType(); } if (! oldType.isParameterizedType()) { return; } final ITypeBinding oldTypeDeclaration= oldType.getTypeDeclaration(); Arrays.sort(typeProposals, new Comparator<ITypeBinding>() { @Override public int compare(ITypeBinding o1, ITypeBinding o2) { return rank(o2) - rank(o1); } private int rank(ITypeBinding type) { if (type.getTypeDeclaration().equals(oldTypeDeclaration)) { return 1; } return 0; } }); }
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$ }
private static boolean isAllOperandsHaveSameType(InfixExpression expression, ITypeBinding leftOperandType, ITypeBinding rightOperandType) { ITypeBinding binding= leftOperandType; if (binding == null) { return false; } ITypeBinding current= rightOperandType; if (binding != current) { return false; } for (Iterator<Expression> iterator= expression.extendedOperands().iterator(); iterator.hasNext();) { Expression operand= iterator.next(); current= operand.resolveTypeBinding(); if (binding != current) { return false; } } return true; }
private static Type newType(LambdaExpression lambdaExpression, VariableDeclarationFragment declaration, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { IMethodBinding method= lambdaExpression.resolveMethodBinding(); if (method != null) { ITypeBinding[] parameterTypes= method.getParameterTypes(); int index= lambdaExpression.parameters().indexOf(declaration); ITypeBinding typeBinding= parameterTypes[index]; if (importRewrite != null) { return importRewrite.addImport(typeBinding, ast, context); } else { String qualifiedName= typeBinding.getQualifiedName(); if (qualifiedName.length() > 0) { return newType(ast, qualifiedName); } } } // fall-back return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ }
/** * Returns the new type node representing the return type of <code>lambdaExpression</code> * including the extra dimensions. * * @param lambdaExpression the lambda expression * @param ast the AST to create the return type with * @param importRewrite the import rewrite to use, or <code>null</code> * @param context the import rewrite context, or <code>null</code> * @return a new type node created with the given AST representing the return type of * <code>lambdaExpression</code> * * @since 3.10 */ public static Type newReturnType(LambdaExpression lambdaExpression, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { IMethodBinding method= lambdaExpression.resolveMethodBinding(); if (method != null) { ITypeBinding returnTypeBinding= method.getReturnType(); if (importRewrite != null) { return importRewrite.addImport(returnTypeBinding, ast); } else { String qualifiedName= returnTypeBinding.getQualifiedName(); if (qualifiedName.length() > 0) { return newType(ast, qualifiedName); } } } // fall-back return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ }
/** * Return B <: C ? * @param typeB * @param typeC * @return */ public static boolean isSubtypeCompatible(Type typeB, Type typeC) { // return typeC.isSubtypeCompatible(typeB); String typeBName = typeB.getFullyQualifiedName(); Crystal crystal = Crystal.getInstance(); ITypeBinding typeBindingB = crystal.getTypeBindingFromName(typeBName); String typeCName = typeB.getFullyQualifiedName(); ITypeBinding typeBindingC = crystal.getTypeBindingFromName(typeCName); if (typeBindingB != null && typeBindingC != null ) { return typeBindingB.isSubTypeCompatible(typeBindingC); } return false; }
public static ast.TypeDeclaration createFrom(ASTNode node){ ast.TypeDeclaration retNode = null; if(node instanceof org.eclipse.jdt.core.dom.TypeDeclaration){ org.eclipse.jdt.core.dom.TypeDeclaration td = (org.eclipse.jdt.core.dom.TypeDeclaration)node; Adapter factory = Adapter.getInstance(); AstNode astNode = factory.get(node); if(astNode instanceof ast.TypeDeclaration){ retNode = (ast.TypeDeclaration)astNode; }else{ retNode = ast.TypeDeclaration.create(); ITypeBinding typeBinding = ((org.eclipse.jdt.core.dom.TypeDeclaration) node).resolveBinding(); retNode.type = TraceabilityFactory.getType(typeBinding); factory.map(node, retNode); factory.mapTypeDeclaration(retNode); retNode.fields = TraceabilityFactory.getDeclaredFields(td); } }else{ throw new IllegalArgumentException(); } return retNode; }
/** * Returns true iff 'methodDeclaration' represents a void static method named 'main' that takes a * single String[] parameter. */ private static boolean isMainMethod(MethodDeclaration methodDeclaration) { // Is it static? if ((methodDeclaration.getModifiers() & Modifier.STATIC) == 0) { return false; } // Does it return void? Type returnType = methodDeclaration.getReturnType2(); if (!returnType.isPrimitiveType()) { return false; } if (((PrimitiveType) returnType).getPrimitiveTypeCode() != PrimitiveType.VOID) { return false; } // Is it called 'main'? if (!"main".equals(methodDeclaration.getName().getIdentifier())) { return false; } // Does it have a single parameter? if (methodDeclaration.parameters().size() != 1) { return false; } // Is the parameter's type String[]? SingleVariableDeclaration pt = getOnlyElement((List<SingleVariableDeclaration>) methodDeclaration.parameters()); IVariableBinding vb = pt.resolveBinding(); if (vb == null) { return false; } ITypeBinding tb = vb.getType(); return tb != null && "java.lang.String[]".equals(tb.getQualifiedName()); }
/** * Extracts the fully qualified name and parameters from a method binding * and applies them to the name in a SourceCodeEntity. * @param binding The method binding. * @param sce SourceCodeEntity to which to apply changes. Name must be set * to the entity's unqualified name. */ private void extractDataFromMethodBinding(IMethodBinding binding, SourceCodeEntity sce) { if (binding != null) { //Get package and type name within which this method is declared. ITypeBinding type = binding.getDeclaringClass(); if (type != null) sce.name = type.getQualifiedName() + "." + sce.name; else sce.name = "?." + sce.name; //Get method parameter types String params = ""; for (ITypeBinding paramType : binding.getParameterTypes()) { if (paramType != null) params += paramType.getQualifiedName() + ","; } if (params.length() > 0) { sce.name += "(" + params.substring(0, params.length() - 1) + ")"; } else sce.name += "()"; } else { //If binding fails, mark the qualification as "?" to show it could //not be determined. sce.name = "?." + sce.name + "(?)"; } }
/** * Extracts the fully qualified name from a variable binding and applies * them to the name in a SourceCodeEntity. * @param binding The variable binding. * @param sce SourceCodeEntity to which to apply changes. Name must be set * to the entity's unqualified name. */ private static void extractDataFromVariableBinding( IVariableBinding binding, SourceCodeEntity sce) { if (binding != null) { //Type member variable. ITypeBinding type = binding.getDeclaringClass(); if (type != null) sce.name = type.getQualifiedName() + "." + sce.name; //Variable declared in method. else { IMethodBinding method = binding.getDeclaringMethod(); if (method != null) { type = method.getDeclaringClass(); if (type != null) { sce.name = type.getQualifiedName() + "." + method.getName() + "." + sce.name; } else sce.name = "?." + method.getName() + "." + sce.name; } else sce.name = "?." + sce.name; } } else { //If binding fails, mark the qualification as "?" to show it could //not be determined. sce.name = "?." + sce.name; } }
private boolean visitNameNode(Name node) { IBinding binding = node.resolveBinding(); if (binding instanceof IVariableBinding) { IVariableBinding variableBindig = (IVariableBinding) binding; if (variableBindig.isField()) { ITypeBinding declaringClass = variableBindig.getDeclaringClass(); handleTypeBinding(node, declaringClass, false); handleFieldBinding(node, variableBindig); } else if (!variableBindig.isEnumConstant()) { handleVariableBinding(node, variableBindig); } } return true; }
@Override public final boolean visit(VariableDeclarationStatement node) { ITypeBinding typeBinding = node.getType().resolveBinding(); handleTypeBinding(node, typeBinding, true); //typeBinding.get //supertypes return true; }
private void appendRawTypes(List<ITypeBinding> rawTypes, Set<String> dejavu, ITypeBinding typeBinding, boolean includeTypeParameters) { String key = typeBinding.getKey(); if (dejavu.contains(key)) { return; } dejavu.add(key); ITypeBinding erasure = typeBinding.getErasure(); rawTypes.add(erasure); if (!includeTypeParameters) { return; } ITypeBinding elementType = typeBinding.getElementType(); if (elementType != null) { this.appendRawTypes(rawTypes, dejavu, elementType, includeTypeParameters); } ITypeBinding[] typeArguments = typeBinding.getTypeArguments(); if (typeArguments != null) { for (ITypeBinding typeArgument : typeArguments) { this.appendRawTypes(rawTypes, dejavu, typeArgument, includeTypeParameters); } } ITypeBinding[] typeBounds = typeBinding.getTypeBounds(); if (typeBounds != null) { for (ITypeBinding typeBound : typeBounds) { this.appendRawTypes(rawTypes, dejavu, typeBound, includeTypeParameters); } } }
private void handleFieldBinding(ASTNode node, IVariableBinding variableBindig) { if (variableBindig == null) { StructuralPropertyDescriptor locationInParent = node.getLocationInParent(); //System.out.println(locationInParent.getId() + " has no field binding"); } else { ITypeBinding declaringClass = variableBindig.getDeclaringClass(); if (declaringClass != null && !this.ignoreType(declaringClass)) { this.onFieldAccess(node, variableBindig); } } }
private void handleMethodBinding(ASTNode node, IMethodBinding methodBinding) { if (methodBinding == null) { StructuralPropertyDescriptor locationInParent = node.getLocationInParent(); //System.out.println(locationInParent.getId() + " has no method binding"); } else { ITypeBinding declaringClass = methodBinding.getDeclaringClass(); if (declaringClass != null && !this.ignoreType(declaringClass)) { this.onMethodAccess(node, methodBinding); } } }
private RastNode visitTypeDeclaration(AbstractTypeDeclaration node, List<Type> supertypes, String nodeType) { RastNode type; String typeName = node.getName().getIdentifier(); if (node.isPackageMemberTypeDeclaration()) { type = model.createType(typeName, packageName, containerStack.peek(), sourceFilePath, node, nodeType); } else { type = model.createInnerType(typeName, containerStack.peek(), sourceFilePath, node, nodeType); } Set<String> annotations = extractAnnotationTypes(node.modifiers()); if (annotations.contains("Deprecated")) { type.addStereotypes(Stereotype.DEPRECATED); } for (Type superType : supertypes) { ITypeBinding superTypeBinding = superType.resolveBinding(); extractSupertypesForPostProcessing(type, superTypeBinding); } // final List<String> references = new ArrayList<String>(); // node.accept(new DependenciesAstVisitor(true) { // @Override // protected void onTypeAccess(ASTNode node, ITypeBinding binding) { // String typeKey = AstUtils.getKeyFromTypeBinding(binding); // references.add(typeKey); // } // }); // postProcessReferences.put(type, references); return type; }
private void extractSupertypesForPostProcessing(RastNode type, ITypeBinding superTypeBinding) { List<String> supertypes = postProcessSupertypes.get(type); if (supertypes == null) { supertypes = new ArrayList<String>(); postProcessSupertypes.put(type, supertypes); } while (superTypeBinding != null && superTypeBinding.isFromSource()) { String superTypeName = superTypeBinding.getErasure().getQualifiedName(); supertypes.add(superTypeName); superTypeBinding = superTypeBinding.getSuperclass(); } }