Example usage for org.eclipse.jdt.internal.compiler.lookup TypeBinding readableName

List of usage examples for org.eclipse.jdt.internal.compiler.lookup TypeBinding readableName

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.lookup TypeBinding readableName.

Prototype

public abstract char[] readableName();

Source Link

Usage

From source file:com.android.build.gradle.tasks.annotations.Extractor.java

License:Apache License

@NonNull
private static String getParameterList(@NonNull MethodBinding binding, boolean isVarargs) {
    // Create compact type signature (no spaces around commas or generics arguments)
    StringBuilder sb = new StringBuilder();
    TypeBinding[] typeParameters = binding.parameters;
    if (typeParameters != null) {
        for (int i = 0, n = typeParameters.length; i < n; i++) {
            TypeBinding parameter = typeParameters[i];
            if (i > 0) {
                sb.append(',');
            }/*from  w  ww.j a v a  2 s  . co  m*/
            String str = fixParameterString(new String(parameter.readableName()));
            if (isVarargs && i == n - 1 && str.endsWith("[]")) {
                str = str.substring(0, str.length() - 2) + "...";
            }
            sb.append(str);
        }
    }
    return sb.toString();
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.PatternLocator.java

License:Open Source License

protected int resolveLevelForType(char[] simpleNamePattern, char[] qualificationPattern,
        char[][][] patternTypeArguments, int depth, TypeBinding type) {
    // standard search with no generic additional information must succeed
    int level = resolveLevelForType(simpleNamePattern, qualificationPattern, type);
    if (level == IMPOSSIBLE_MATCH)
        return IMPOSSIBLE_MATCH;
    if (type == null || patternTypeArguments == null || patternTypeArguments.length == 0
            || depth >= patternTypeArguments.length) {
        return level;
    }// www  . j  av a 2  s.c  om

    // if pattern is erasure match (see bug 79790), commute impossible to erasure
    int impossible = this.isErasureMatch ? ERASURE_MATCH : IMPOSSIBLE_MATCH;

    // pattern has type parameter(s) or type argument(s)
    if (type.isGenericType()) {
        // Binding is generic, get its type variable(s)
        TypeVariableBinding[] typeVariables = null;
        if (type instanceof SourceTypeBinding) {
            SourceTypeBinding sourceTypeBinding = (SourceTypeBinding) type;
            typeVariables = sourceTypeBinding.typeVariables;
        } else if (type instanceof BinaryTypeBinding) {
            BinaryTypeBinding binaryTypeBinding = (BinaryTypeBinding) type;
            if (this.mustResolve)
                typeVariables = binaryTypeBinding.typeVariables(); // TODO (frederic) verify performance
        }
        if (patternTypeArguments[depth] != null && patternTypeArguments[depth].length > 0
                && typeVariables != null && typeVariables.length > 0) {
            if (typeVariables.length != patternTypeArguments[depth].length)
                return IMPOSSIBLE_MATCH;
        }
        // TODO (frederic) do we need to verify each parameter?
        return level; // we can't do better
    }

    // raw type always match
    if (type.isRawType()) {
        return level;
    }

    // Standard types (i.e. neither generic nor parameterized nor raw types)
    // cannot match pattern with type parameters or arguments
    TypeBinding leafType = type.leafComponentType();
    if (!leafType.isParameterizedType()) {
        return (patternTypeArguments[depth] == null || patternTypeArguments[depth].length == 0) ? level
                : IMPOSSIBLE_MATCH;
    }

    // Parameterized type
    ParameterizedTypeBinding paramTypeBinding = (ParameterizedTypeBinding) leafType;

    // Compare arguments only if there ones on both sides
    if (patternTypeArguments[depth] != null && patternTypeArguments[depth].length > 0
            && paramTypeBinding.arguments != null && paramTypeBinding.arguments.length > 0) {

        // type parameters length must match at least specified type names length
        int length = patternTypeArguments[depth].length;
        if (paramTypeBinding.arguments.length != length)
            return IMPOSSIBLE_MATCH;

        // verify each pattern type parameter
        nextTypeArgument: for (int i = 0; i < length; i++) {
            char[] patternTypeArgument = patternTypeArguments[depth][i];
            TypeBinding argTypeBinding = paramTypeBinding.arguments[i];
            // get corresponding pattern wildcard
            switch (patternTypeArgument[0]) {
            case Signature.C_STAR: // unbound parameter always match
            case Signature.C_SUPER: // needs pattern type parameter binding
                // skip to next type argument as it will be resolved later
                continue nextTypeArgument;
            case Signature.C_EXTENDS:
                // remove wildcard from patter type argument
                patternTypeArgument = CharOperation.subarray(patternTypeArgument, 1,
                        patternTypeArgument.length);
                break;
            default:
                // no wildcard
                break;
            }
            // get pattern type argument from its signature
            patternTypeArgument = Signature.toCharArray(patternTypeArgument);
            if (!this.isCaseSensitive)
                patternTypeArgument = CharOperation.toLowerCase(patternTypeArgument);
            boolean patternTypeArgHasAnyChars = CharOperation.contains(new char[] { '*', '?' },
                    patternTypeArgument);

            // Verify that names match...
            // ...special case for wildcard
            if (argTypeBinding instanceof CaptureBinding) {
                WildcardBinding capturedWildcard = ((CaptureBinding) argTypeBinding).wildcard;
                if (capturedWildcard != null)
                    argTypeBinding = capturedWildcard;
            }
            if (argTypeBinding.isWildcard()) {
                WildcardBinding wildcardBinding = (WildcardBinding) argTypeBinding;
                switch (wildcardBinding.boundKind) {
                case Wildcard.EXTENDS:
                    // Invalid if type argument is not exact
                    if (patternTypeArgHasAnyChars)
                        return impossible;
                    continue nextTypeArgument;
                case Wildcard.UNBOUND:
                    // there's no bound name to match => valid
                    continue nextTypeArgument;
                }
                // Look if bound name match pattern type argument
                ReferenceBinding boundBinding = (ReferenceBinding) wildcardBinding.bound;
                if (CharOperation.match(patternTypeArgument, boundBinding.shortReadableName(),
                        this.isCaseSensitive)
                        || CharOperation.match(patternTypeArgument, boundBinding.readableName(),
                                this.isCaseSensitive)) {
                    // found name in hierarchy => match
                    continue nextTypeArgument;
                }

                // If pattern is not exact then match fails
                if (patternTypeArgHasAnyChars)
                    return impossible;

                // Look for bound name in type argument superclasses
                boundBinding = boundBinding.superclass();
                while (boundBinding != null) {
                    if (CharOperation.equals(patternTypeArgument, boundBinding.shortReadableName(),
                            this.isCaseSensitive)
                            || CharOperation.equals(patternTypeArgument, boundBinding.readableName(),
                                    this.isCaseSensitive)) {
                        // found name in hierarchy => match
                        continue nextTypeArgument;
                    } else if (boundBinding.isLocalType() || boundBinding.isMemberType()) {
                        // for local or member type, verify also source name (bug 81084)
                        if (CharOperation.match(patternTypeArgument, boundBinding.sourceName(),
                                this.isCaseSensitive))
                            continue nextTypeArgument;
                    }
                    boundBinding = boundBinding.superclass();
                }
                return impossible;
            }

            // See if names match
            if (CharOperation.match(patternTypeArgument, argTypeBinding.shortReadableName(),
                    this.isCaseSensitive)
                    || CharOperation.match(patternTypeArgument, argTypeBinding.readableName(),
                            this.isCaseSensitive)) {
                continue nextTypeArgument;
            } else if (argTypeBinding.isLocalType() || argTypeBinding.isMemberType()) {
                // for local or member type, verify also source name (bug 81084)
                if (CharOperation.match(patternTypeArgument, argTypeBinding.sourceName(), this.isCaseSensitive))
                    continue nextTypeArgument;
            }

            // If pattern is not exact then match fails
            if (patternTypeArgHasAnyChars)
                return impossible;

            // Scan hierarchy
            TypeBinding leafTypeBinding = argTypeBinding.leafComponentType();
            if (leafTypeBinding.isBaseType())
                return impossible;
            ReferenceBinding refBinding = ((ReferenceBinding) leafTypeBinding).superclass();
            while (refBinding != null) {
                if (CharOperation.equals(patternTypeArgument, refBinding.shortReadableName(),
                        this.isCaseSensitive)
                        || CharOperation.equals(patternTypeArgument, refBinding.readableName(),
                                this.isCaseSensitive)) {
                    // found name in hierarchy => match
                    continue nextTypeArgument;
                } else if (refBinding.isLocalType() || refBinding.isMemberType()) {
                    // for local or member type, verify also source name (bug 81084)
                    if (CharOperation.match(patternTypeArgument, refBinding.sourceName(), this.isCaseSensitive))
                        continue nextTypeArgument;
                }
                refBinding = refBinding.superclass();
            }
            return impossible;
        }
    }

    // Recurse on enclosing type
    TypeBinding enclosingType = paramTypeBinding.enclosingType();
    if (enclosingType != null && enclosingType.isParameterizedType() && depth < patternTypeArguments.length
            && qualificationPattern != null) {
        int lastDot = CharOperation.lastIndexOf('.', qualificationPattern);
        char[] enclosingQualificationPattern = lastDot == -1 ? null
                : CharOperation.subarray(qualificationPattern, 0, lastDot);
        char[] enclosingSimpleNamePattern = lastDot == -1 ? qualificationPattern
                : CharOperation.subarray(qualificationPattern, lastDot + 1, qualificationPattern.length);
        int enclosingLevel = resolveLevelForType(enclosingSimpleNamePattern, enclosingQualificationPattern,
                patternTypeArguments, depth + 1, enclosingType);
        if (enclosingLevel == impossible)
            return impossible;
        if (enclosingLevel == IMPOSSIBLE_MATCH)
            return IMPOSSIBLE_MATCH;
    }
    return level;
}

From source file:lombok.eclipse.agent.PatchDelegate.java

License:Open Source License

private static void failIfContainsAnnotation(TypeBinding parent, Binding[] bindings) throws DelegateRecursion {
    if (bindings == null)
        return;// ww w . j a v  a 2 s. c  o m

    for (Binding b : bindings) {
        AnnotationBinding[] anns = null;
        if (b instanceof MethodBinding)
            anns = ((MethodBinding) b).getAnnotations();
        if (b instanceof FieldBinding)
            anns = ((FieldBinding) b).getAnnotations();
        // anns = b.getAnnotations() would make a heck of a lot more sense, but that is a late addition to ecj, so would cause NoSuchMethodErrors! Don't use that!
        if (anns == null)
            continue;
        for (AnnotationBinding ann : anns) {
            char[][] name = null;
            try {
                name = ann.getAnnotationType().compoundName;
            } catch (Exception ignore) {
            }

            if (name == null || name.length < 2 || name.length > 3)
                continue;
            if (!Arrays.equals(STRING_LOMBOK, name[0]))
                continue;
            if (!Arrays.equals(STRING_DELEGATE, name[name.length - 1]))
                continue;
            if (name.length == 3 && !Arrays.equals(STRING_EXPERIMENTAL, name[1]))
                continue;

            throw new DelegateRecursion(parent.readableName(), b.readableName());
        }
    }
}

From source file:lombok.eclipse.agent.Patches.java

License:Open Source License

private static boolean matchesType(final Annotation ann, final Class<?> expectedType,
        final TypeDeclaration decl) {
    if (ann.type == null)
        return false;
    TypeBinding tb = ann.resolvedType;
    if ((tb == null) && (ann.type != null)) {
        try {//  www  .ja v a2s  . c o m
            tb = ann.type.resolveType(decl.initializerScope);
        } catch (final Exception ignore) {
            // completion nodes may throw an exception here
        }
    }
    if (tb == null)
        return false;
    return new String(tb.readableName()).equals(expectedType.getName());
}

From source file:lombok.eclipse.handlers.HandleListenerSupport.java

License:Open Source License

@Override
public void handle(final AnnotationValues<ListenerSupport> annotation, final Annotation source,
        final EclipseNode annotationNode) {
    EclipseType type = EclipseType.typeOf(annotationNode, source);
    if (type.isAnnotation() || type.isInterface()) {
        annotationNode.addError(canBeUsedOnClassAndEnumOnly(ListenerSupport.class));
        return;/*from w  ww  .  j a va2 s.c  o  m*/
    }

    List<Object> listenerInterfaces = annotation.getActualExpressions("value");
    if (listenerInterfaces.isEmpty()) {
        annotationNode.addError(String.format("@%s has no effect since no interface types were specified.",
                ListenerSupport.class.getName()));
        return;
    }
    for (Object listenerInterface : listenerInterfaces) {
        if (listenerInterface instanceof ClassLiteralAccess) {
            TypeBinding binding = ((ClassLiteralAccess) listenerInterface).type
                    .resolveType(type.get().initializerScope);
            if (binding == null)
                continue;
            if (!binding.isInterface()) {
                annotationNode.addWarning(String.format("@%s works only with interfaces. %s was skipped",
                        ListenerSupport.class.getName(), As.string(binding.readableName())));
                continue;
            }
            handler.addListenerField(type, binding);
            handler.addAddListenerMethod(type, binding);
            handler.addRemoveListenerMethod(type, binding);
            addFireListenerMethods(type, binding);
        }
    }

    type.editor().rebuild();
}

From source file:org.codehaus.jdt.groovy.internal.compiler.ast.JDTResolver.java

License:Open Source License

/**
 * Convert from a JDT Binding to a Groovy ClassNode
 *///w w w  .  j a  v  a  2s .co m
ClassNode convertToClassNode(TypeBinding jdtBinding) {
    if (inProgress.containsKey(jdtBinding)) {
        return inProgress.get(jdtBinding);
    }
    JDTClassNode existingNode = nodeCache.get(jdtBinding);
    if (existingNode != null) {
        if (debug) {
            log("Using cached JDTClassNode for binding " + new String(jdtBinding.readableName()));
        }
        return existingNode;
    }

    if (debug) {
        log("createJDTClassNode: Building new JDTClassNode for binding "
                + new String(jdtBinding.readableName()));
    }

    ClassNode jdtNode = createJDTClassNode(jdtBinding);
    return jdtNode;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.ast.CallinMappingDeclaration.java

License:Open Source License

/** Check whether the baseSpec has a result compatible via replace. */
public void checkResultForReplace(MethodSpec baseSpec) {
    boolean typeIdentityRequired = true; // default unless return is type variable
    // covariant return requires a fresh type parameter for the role's return type:
    if (baseSpec.covariantReturn && this.roleMethodSpec.returnType != null) {
        TypeBinding resolvedRoleReturn = this.roleMethodSpec.returnType.resolvedType;
        if (resolvedRoleReturn != null) {
            if (!resolvedRoleReturn.isTypeVariable()) {
                this.scope.problemReporter()
                        .covariantReturnRequiresTypeParameter(this.roleMethodSpec.returnType);
                this.binding.tagBits |= TagBits.HasMappingIncompatibility;
            } else {
                // is the type parameter "fresh"?
                for (Argument arg : this.roleMethodSpec.arguments) {
                    if (typeUsesTypeVariable(arg.type.resolvedType.leafComponentType(), resolvedRoleReturn)) {
                        this.scope.problemReporter().duplicateUseOfTypeVariableInCallin(
                                this.roleMethodSpec.returnType, resolvedRoleReturn);
                        this.binding.tagBits |= TagBits.HasMappingIncompatibility;
                        break;
                    }/*  ww  w .j  av  a2 s  .c  o m*/
                }
            }
        }
    }
    TypeVariableBinding returnVariable = MethodModel
            .checkedGetReturnTypeVariable(this.roleMethodSpec.resolvedMethod);
    if (returnVariable != null) {
        // unbounded type variable always matches:
        if (returnVariable.firstBound == null)
            return;
        // in case of type variable only one-way compatibility is needed even for replace:
        typeIdentityRequired = false;
    }

    // now go for the actual type checking:
    TypeBinding baseReturn = baseSpec.resolvedMethod.returnType;
    TypeBinding roleReturn = MethodModel.getReturnType(this.roleMethodSpec.resolvedMethod);
    TypeBinding roleReturnLeaf = roleReturn != null ? roleReturn.leafComponentType() : null;
    if (roleReturnLeaf instanceof ReferenceBinding && ((ReferenceBinding) roleReturnLeaf).isRole()) {
        // strengthen:
        roleReturnLeaf = TeamModel.strengthenRoleType(this.scope.enclosingSourceType(), roleReturnLeaf);
        if (roleReturnLeaf == null) { // FIXME(SH): testcase and better handling
            String roleReturnName = roleReturn != null ? new String(roleReturn.readableName())
                    : "null return type"; //$NON-NLS-1$
            throw new InternalCompilerError("role strengthening for " + roleReturnName + " -> null"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        // bound roles use their topmost bound super:
        if (((ReferenceBinding) roleReturnLeaf).baseclass() != null)
            roleReturnLeaf = RoleModel.getTopmostBoundRole(this.scope, (ReferenceBinding) roleReturnLeaf);

        // need the RTB:
        if (!(roleReturnLeaf instanceof DependentTypeBinding))
            roleReturnLeaf = RoleTypeCreator.maybeWrapUnqualifiedRoleType(roleReturnLeaf,
                    this.scope.enclosingSourceType());

        // array?
        int dims = roleReturn != null ? roleReturn.dimensions() : 0;
        if (dims == 0) {
            roleReturn = roleReturnLeaf;
            this.realRoleReturn = roleReturnLeaf;
        } else {
            roleReturn = ((DependentTypeBinding) roleReturnLeaf).getArrayType(dims);
            this.realRoleReturn = ((DependentTypeBinding) roleReturnLeaf).getArrayType(dims);
        }
    }
    if (baseReturn == null || baseReturn == TypeBinding.VOID) {
        // OTJLD 4.4(b): "A callin method bound with replace
        //                to a base method returning void
        //                must not declare a non-void result."
        if (!(roleReturn == null || roleReturn == TypeBinding.VOID)) {
            this.scope.problemReporter().callinIllegalRoleReturnReturn(baseSpec, this.roleMethodSpec);
            this.binding.tagBits |= TagBits.HasMappingIncompatibility;
        }
    } else {
        if (roleReturn == null || roleReturn == TypeBinding.VOID) {
            this.baseMethodNeedingResultFromBasecall = baseSpec;
            // will be reported in checkBaseResult().
            return;
        }

        TypeBinding baseLeaf = baseReturn.leafComponentType();
        if (baseLeaf instanceof DependentTypeBinding) {
            // instantiate relative to Role._OT$base:
            ReferenceBinding enclosingRole = this.scope.enclosingSourceType();
            FieldBinding baseField = enclosingRole.getField(IOTConstants._OT_BASE, true);
            if (baseField != null && baseField.isValidBinding())
                baseReturn = baseField.getRoleTypeBinding((ReferenceBinding) baseLeaf, baseReturn.dimensions());
        }

        // check auto(un)boxing:
        if (this.scope.isBoxingCompatibleWith(roleReturn, baseReturn))
            return;

        Config oldConfig = Config.createOrResetConfig(this);
        try {
            if (!roleReturn.isCompatibleWith(baseReturn)) {
                if (typeIdentityRequired) {
                    this.scope.problemReporter().callinIncompatibleReturnType(baseSpec, this.roleMethodSpec);
                    this.binding.tagBits |= TagBits.HasMappingIncompatibility;
                    return;
                }
                // else we still needed the lowering test
            }
            // callin replace requires two way compatibility:
            baseSpec.returnNeedsTranslation = Config.getLoweringRequired();

        } finally {
            Config.removeOrRestore(oldConfig, this);
        }
        // from now on don't bother with arrays any more (dimensions have been checked):
        roleReturn = roleReturn.leafComponentType();
        baseReturn = baseReturn.leafComponentType();
        TypeBinding translatedReturn = baseSpec.returnNeedsTranslation
                ? ((ReferenceBinding) roleReturn).baseclass()
                : roleReturn;
        if (translatedReturn.isTypeVariable()) {
            TypeBinding firstBound = ((TypeVariableBinding) translatedReturn).firstBound;
            if (firstBound != null)
                translatedReturn = firstBound;
        }
        if (!baseReturn.isCompatibleWith(translatedReturn)) {
            this.scope.problemReporter().callinIncompatibleReturnTypeBaseCall(baseSpec, this.roleMethodSpec);
            this.binding.tagBits |= TagBits.HasMappingIncompatibility;
        }
    }
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.mappings.CallinImplementor.java

License:Open Source License

/**
 *   gen:  if (result == null) throw new ResultNotProvidedException(..);
 *
 * @param roleName/*from www  .  j  a  v  a2 s  . c  o m*/
 * @param roleMethodBinding
 * @param baseTypeBinding
 * @param baseMethodSpec
 * @param gen
 * @return the assembled iff statement
 */
public static Statement genResultNotProvidedCheck(char[] teamName, char[] roleName,
        MethodBinding roleMethodBinding, TypeBinding baseTypeBinding, MethodSpec baseMethodSpec,
        AstGenerator gen) {

    String errMsg = Messages.bind("(team: {0}, role: {1}, method {2})\n" + //$NON-NLS-1$
            "Base call to {3}.{4} is missing", //$NON-NLS-1$
            new Object[] { new String(teamName), new String(roleName),
                    new String(roleMethodBinding.readableName()), new String(baseTypeBinding.readableName()),
                    new String(baseMethodSpec.resolvedMethod.readableName()) });

    return gen.ifStatement(
            new EqualExpression(gen.singleNameReference(IOTConstants.OT_RESULT), gen.nullLiteral(),
                    OperatorIds.EQUAL_EQUAL),
            gen.block(new Statement[] { gen.throwStatement(
                    gen.allocation(gen.qualifiedTypeReference(IOTConstants.ORG_OBJECTTEAMS_RESULT_NOT_PROVIDED),
                            new Expression[] { gen.stringLiteral(errMsg.toCharArray()) })) }));
}

From source file:spoon.support.compiler.jdt.ReferenceBuilder.java

License:Open Source License

/**
 * @param resolveGeneric if true then it never returns CtTypeParameterReference, but it's superClass instead
 *///from w w  w .  j a v  a2  s .  c o  m
<T> CtTypeReference<T> getTypeReference(TypeBinding binding, boolean resolveGeneric) {
    if (binding == null) {
        return null;
    }

    CtTypeReference<?> ref;

    if (binding instanceof RawTypeBinding) {
        ref = getTypeReference(((ParameterizedTypeBinding) binding).genericType());
    } else if (binding instanceof ParameterizedTypeBinding) {
        if (binding.actualType() != null && binding.actualType() instanceof LocalTypeBinding) {
            // When we define a nested class in a method and when the enclosing class of this method
            // is a parameterized type binding, JDT give a ParameterizedTypeBinding for the nested class
            // and hide the real class in actualType().
            ref = getTypeReference(binding.actualType());
        } else {
            ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
            this.exploringParameterizedBindings.put(binding, ref);
            if (binding.isAnonymousType()) {
                ref.setSimpleName("");
            } else {
                ref.setSimpleName(String.valueOf(binding.sourceName()));
                if (binding.enclosingType() != null) {
                    ref.setDeclaringType(getTypeReference(binding.enclosingType()));
                } else {
                    ref.setPackage(getPackageReference(binding.getPackage()));
                }
            }
        }
        if (binding.actualType() instanceof MissingTypeBinding) {
            ref = getTypeReference(binding.actualType());
        }

        if (((ParameterizedTypeBinding) binding).arguments != null) {
            for (TypeBinding b : ((ParameterizedTypeBinding) binding).arguments) {
                if (bindingCache.containsKey(b)) {
                    ref.addActualTypeArgument(getCtCircularTypeReference(b));
                } else {
                    if (!this.exploringParameterizedBindings.containsKey(b)) {
                        this.exploringParameterizedBindings.put(b, null);
                        CtTypeReference typeRefB = getTypeReference(b);
                        this.exploringParameterizedBindings.put(b, typeRefB);
                        ref.addActualTypeArgument(typeRefB);
                    } else {
                        CtTypeReference typeRefB = this.exploringParameterizedBindings.get(b);
                        if (typeRefB != null) {
                            ref.addActualTypeArgument(typeRefB.clone());
                        }
                    }
                }
            }
        }
    } else if (binding instanceof MissingTypeBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        ref.setSimpleName(new String(binding.sourceName()));
        ref.setPackage(getPackageReference(binding.getPackage()));
        if (!this.jdtTreeBuilder.getContextBuilder().ignoreComputeImports) {
            final CtReference declaring = this.getDeclaringReferenceFromImports(binding.sourceName());
            if (declaring instanceof CtPackageReference) {
                ref.setPackage((CtPackageReference) declaring);
            } else if (declaring instanceof CtTypeReference) {
                ref.setDeclaringType((CtTypeReference) declaring);
            }
        }
    } else if (binding instanceof BinaryTypeBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        if (binding.enclosingType() != null) {
            ref.setDeclaringType(getTypeReference(binding.enclosingType()));
        } else {
            ref.setPackage(getPackageReference(binding.getPackage()));
        }
        ref.setSimpleName(new String(binding.sourceName()));
    } else if (binding instanceof TypeVariableBinding) {
        boolean oldBounds = bounds;

        if (binding instanceof CaptureBinding) {
            ref = this.jdtTreeBuilder.getFactory().Core().createWildcardReference();
            bounds = true;
        } else {
            TypeVariableBinding typeParamBinding = (TypeVariableBinding) binding;
            if (resolveGeneric) {
                //it is called e.g. by ExecutableReference, which must not use CtParameterTypeReference
                //but it needs it's bounding type instead
                ReferenceBinding superClass = typeParamBinding.superclass;
                ReferenceBinding[] superInterfaces = typeParamBinding.superInterfaces();

                CtTypeReference refSuperClass = null;

                // if the type parameter has a super class other than java.lang.Object, we get it
                // superClass.superclass() is null if it's java.lang.Object
                if (superClass != null && !(superClass.superclass() == null)) {

                    // this case could happen with Enum<E extends Enum<E>> for example:
                    // in that case we only want to have E -> Enum -> E
                    // to conserve the same behavior as JavaReflectionTreeBuilder
                    if (!(superClass instanceof ParameterizedTypeBinding)
                            || !this.exploringParameterizedBindings.containsKey(superClass)) {
                        refSuperClass = this.getTypeReference(superClass, resolveGeneric);
                    }

                    // if the type parameter has a super interface, then we'll get it too, as a superclass
                    // type parameter can only extends an interface or a class, so we don't make the distinction
                    // in Spoon. Moreover we can only have one extends in a type parameter.
                } else if (superInterfaces != null && superInterfaces.length == 1) {
                    refSuperClass = this.getTypeReference(superInterfaces[0], resolveGeneric);
                }
                if (refSuperClass == null) {
                    refSuperClass = this.jdtTreeBuilder.getFactory().Type().getDefaultBoundingType();
                }
                ref = refSuperClass.clone();
            } else {
                ref = this.jdtTreeBuilder.getFactory().Core().createTypeParameterReference();
                ref.setSimpleName(new String(binding.sourceName()));
            }
        }
        TypeVariableBinding b = (TypeVariableBinding) binding;
        if (bounds) {
            if (b instanceof CaptureBinding && ((CaptureBinding) b).wildcard != null) {
                bounds = oldBounds;
                return getTypeReference(((CaptureBinding) b).wildcard, resolveGeneric);
            } else if (b.superclass != null && b.firstBound == b.superclass) {
                bounds = false;
                bindingCache.put(binding, ref);
                if (ref instanceof CtWildcardReference) {
                    ((CtWildcardReference) ref).setBoundingType(getTypeReference(b.superclass, resolveGeneric));
                }
                bounds = oldBounds;
            }
        }
        if (bounds && b.superInterfaces != null && b.superInterfaces != Binding.NO_SUPERINTERFACES) {
            bindingCache.put(binding, ref);
            List<CtTypeReference<?>> bounds = new ArrayList<>();
            CtTypeParameterReference typeParameterReference = (CtTypeParameterReference) ref;
            if (!(typeParameterReference.isDefaultBoundingType())) { // if it's object we can ignore it
                bounds.add(typeParameterReference.getBoundingType());
            }
            for (ReferenceBinding superInterface : b.superInterfaces) {
                bounds.add(getTypeReference(superInterface, resolveGeneric));
            }
            if (ref instanceof CtWildcardReference) {
                ((CtWildcardReference) ref).setBoundingType(this.jdtTreeBuilder.getFactory().Type()
                        .createIntersectionTypeReferenceWithBounds(bounds));
            }
        }
        if (binding instanceof CaptureBinding) {
            bounds = false;
        }
    } else if (binding instanceof BaseTypeBinding) {
        String name = new String(binding.sourceName());
        //always create new TypeReference, because clonning from a cache clones invalid SourcePosition
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        ref.setSimpleName(name);
    } else if (binding instanceof WildcardBinding) {
        WildcardBinding wildcardBinding = (WildcardBinding) binding;
        CtWildcardReference wref = this.jdtTreeBuilder.getFactory().Core().createWildcardReference();
        ref = wref;

        if (wildcardBinding.boundKind == Wildcard.SUPER) {
            wref.setUpper(false);
        }

        if (wildcardBinding.bound != null) {
            if (bindingCache.containsKey(wildcardBinding.bound)) {
                wref.setBoundingType(getCtCircularTypeReference(wildcardBinding.bound));
            } else {
                wref.setBoundingType(getTypeReference(((WildcardBinding) binding).bound));
            }
        }
    } else if (binding instanceof LocalTypeBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        if (binding.isAnonymousType()) {
            ref.setSimpleName(JDTTreeBuilderHelper
                    .computeAnonymousName(((SourceTypeBinding) binding).constantPoolName()));
            ref.setDeclaringType(getTypeReference(binding.enclosingType()));
        } else {
            ref.setSimpleName(new String(binding.sourceName()));
            if (((LocalTypeBinding) binding).enclosingMethod == null && binding.enclosingType() != null
                    && binding.enclosingType() instanceof LocalTypeBinding) {
                ref.setDeclaringType(getTypeReference(binding.enclosingType()));
            } else if (binding.enclosingMethod() != null) {
                ref.setSimpleName(JDTTreeBuilderHelper
                        .computeAnonymousName(((SourceTypeBinding) binding).constantPoolName()));
                ref.setDeclaringType(getTypeReference(binding.enclosingType()));
            }
        }
    } else if (binding instanceof SourceTypeBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        if (binding.isAnonymousType()) {
            ref.setSimpleName(JDTTreeBuilderHelper
                    .computeAnonymousName(((SourceTypeBinding) binding).constantPoolName()));
            ref.setDeclaringType(getTypeReference(binding.enclosingType()));
        } else {
            ref.setSimpleName(new String(binding.sourceName()));
            if (binding.enclosingType() != null) {
                ref.setDeclaringType(getTypeReference(binding.enclosingType()));
            } else {
                ref.setPackage(getPackageReference(binding.getPackage()));
            }
        }
    } else if (binding instanceof ArrayBinding) {
        CtArrayTypeReference<Object> arrayref;
        arrayref = this.jdtTreeBuilder.getFactory().Core().createArrayTypeReference();
        ref = arrayref;
        for (int i = 1; i < binding.dimensions(); i++) {
            CtArrayTypeReference<Object> tmp = this.jdtTreeBuilder.getFactory().Core()
                    .createArrayTypeReference();
            arrayref.setComponentType(tmp);
            arrayref = tmp;
        }
        arrayref.setComponentType(getTypeReference(binding.leafComponentType(), resolveGeneric));
    } else if (binding instanceof PolyTypeBinding) {
        // JDT can't resolve the type of this binding and we only have a string.
        // In this case, we return a type Object because we can't know more about it.
        ref = this.jdtTreeBuilder.getFactory().Type().objectType();
    } else if (binding instanceof ProblemReferenceBinding) {
        // Spoon is able to analyze also without the classpath
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        char[] readableName = binding.readableName();
        StringBuilder sb = new StringBuilder();
        for (int i = readableName.length - 1; i >= 0; i--) {
            char c = readableName[i];
            if (c == '.') {
                break;
            }
            sb.append(c);
        }
        sb.reverse();
        ref.setSimpleName(sb.toString());
        final CtReference declaring = this.getDeclaringReferenceFromImports(binding.sourceName());
        setPackageOrDeclaringType(ref, declaring);
    } else if (binding instanceof JDTTreeBuilder.SpoonReferenceBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        ref.setSimpleName(new String(binding.sourceName()));
        ref.setDeclaringType(getTypeReference(binding.enclosingType()));
    } else if (binding instanceof IntersectionTypeBinding18) {
        List<CtTypeReference<?>> bounds = new ArrayList<>();
        for (ReferenceBinding superInterface : binding.getIntersectingTypes()) {
            bounds.add(getTypeReference(superInterface));
        }
        ref = this.jdtTreeBuilder.getFactory().Type().createIntersectionTypeReferenceWithBounds(bounds);
    } else {
        throw new RuntimeException("Unknown TypeBinding: " + binding.getClass() + " " + binding);
    }
    bindingCache.remove(binding);
    this.exploringParameterizedBindings.remove(binding);
    return (CtTypeReference<T>) ref;
}

From source file:spoon.test.prettyprinter.testclasses.ComplexClass.java

License:Open Source License

@SuppressWarnings("unchecked")
<T> CtTypeReference<T> getTypeReference(TypeBinding binding) {
    if (binding == null) {
        return null;
    }//from  w w w  .  j  a v  a 2s.c o m

    CtTypeReference<?> ref = null;

    if (binding instanceof RawTypeBinding) {
        ref = getTypeReference(((ParameterizedTypeBinding) binding).genericType());
    } else if (binding instanceof ParameterizedTypeBinding) {
        if (binding.actualType() != null && binding.actualType() instanceof LocalTypeBinding) {
            // When we define a nested class in a method and when the enclosing class of this method
            // is a parameterized type binding, JDT give a ParameterizedTypeBinding for the nested class
            // and hide the real class in actualType().
            ref = getTypeReference(binding.actualType());
        } else {
            ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
            this.exploringParameterizedBindings.put(binding, ref);
            if (binding.isAnonymousType()) {
                ref.setSimpleName("");
            } else {
                ref.setSimpleName(String.valueOf(binding.sourceName()));
                if (binding.enclosingType() != null) {
                    ref.setDeclaringType(getTypeReference(binding.enclosingType()));
                } else {
                    ref.setPackage(getPackageReference(binding.getPackage()));
                }
            }
        }
        if (binding.actualType() instanceof MissingTypeBinding) {
            ref = getTypeReference(binding.actualType());
        }

        if (((ParameterizedTypeBinding) binding).arguments != null) {
            for (TypeBinding b : ((ParameterizedTypeBinding) binding).arguments) {
                if (bindingCache.containsKey(b)) {
                    ref.addActualTypeArgument(getCtCircularTypeReference(b));
                } else {
                    if (!this.exploringParameterizedBindings.containsKey(b)) {
                        this.exploringParameterizedBindings.put(b, null);
                        CtTypeReference typeRefB = getTypeReference(b);
                        this.exploringParameterizedBindings.put(b, typeRefB);
                        ref.addActualTypeArgument(typeRefB);
                    } else {
                        CtTypeReference typeRefB = this.exploringParameterizedBindings.get(b);
                        if (typeRefB != null) {
                            ref.addActualTypeArgument(typeRefB.clone());
                        }
                    }
                }
            }
        }
    } else if (binding instanceof MissingTypeBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        ref.setSimpleName(new String(binding.sourceName()));
        ref.setPackage(getPackageReference(binding.getPackage()));
        if (!this.jdtTreeBuilder.getContextBuilder().ignoreComputeImports) {
            final CtReference declaring = this.getDeclaringReferenceFromImports(binding.sourceName());
            if (declaring instanceof CtPackageReference) {
                ref.setPackage((CtPackageReference) declaring);
            } else if (declaring instanceof CtTypeReference) {
                ref.setDeclaringType((CtTypeReference) declaring);
            }
        }
    } else if (binding instanceof BinaryTypeBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        if (binding.enclosingType() != null) {
            ref.setDeclaringType(getTypeReference(binding.enclosingType()));
        } else {
            ref.setPackage(getPackageReference(binding.getPackage()));
        }
        ref.setSimpleName(new String(binding.sourceName()));
    } else if (binding instanceof TypeVariableBinding) {
        boolean oldBounds = bounds;

        if (binding instanceof CaptureBinding) {
            ref = this.jdtTreeBuilder.getFactory().Core().createWildcardReference();
            bounds = true;
        } else {
            TypeVariableBinding typeParamBinding = (TypeVariableBinding) binding;
            ReferenceBinding superClass = typeParamBinding.superclass;
            ReferenceBinding[] superInterfaces = typeParamBinding.superInterfaces();

            CtTypeReference refSuperClass = null;

            // if the type parameter has a super class other than java.lang.Object, we get it
            // superClass.superclass() is null if it's java.lang.Object
            if (superClass != null && !(superClass.superclass() == null)) {

                // this case could happen with Enum<E extends Enum<E>> for example:
                // in that case we only want to have E -> Enum -> E
                // to conserve the same behavior as JavaReflectionTreeBuilder
                if (!(superClass instanceof ParameterizedTypeBinding)
                        || !this.exploringParameterizedBindings.containsKey(superClass)) {
                    refSuperClass = this.getTypeReference(superClass);
                }

                // if the type parameter has a super interface, then we'll get it too, as a superclass
                // type parameter can only extends an interface or a class, so we don't make the distinction
                // in Spoon. Moreover we can only have one extends in a type parameter.
            } else if (superInterfaces != null && superInterfaces.length == 1) {
                refSuperClass = this.getTypeReference(superInterfaces[0]);
            }

            ref = this.jdtTreeBuilder.getFactory().Core().createTypeParameterReference();
            ref.setSimpleName(new String(binding.sourceName()));

            if (refSuperClass != null) {
                ((CtTypeParameterReference) ref).addBound(refSuperClass);
            }
        }
        TypeVariableBinding b = (TypeVariableBinding) binding;
        if (bounds) {
            if (b instanceof CaptureBinding && ((CaptureBinding) b).wildcard != null) {
                bounds = oldBounds;
                return getTypeReference(((CaptureBinding) b).wildcard);
            } else if (b.superclass != null && b.firstBound == b.superclass) {
                bounds = false;
                bindingCache.put(binding, ref);
                ((CtTypeParameterReference) ref).setBoundingType(getTypeReference(b.superclass));
                bounds = oldBounds;
            }
        }
        if (bounds && b.superInterfaces != null && b.superInterfaces != Binding.NO_SUPERINTERFACES) {
            bounds = false;
            bindingCache.put(binding, ref);
            List<CtTypeReference<?>> bounds = new ArrayList<>();
            CtTypeParameterReference typeParameterReference = (CtTypeParameterReference) ref;
            if (!(typeParameterReference.isDefaultBoundingType())) { // if it's object we can ignore it
                bounds.add(typeParameterReference.getBoundingType());
            }
            for (ReferenceBinding superInterface : b.superInterfaces) {
                bounds.add(getTypeReference(superInterface));
            }
            ((CtTypeParameterReference) ref).setBoundingType(
                    this.jdtTreeBuilder.getFactory().Type().createIntersectionTypeReferenceWithBounds(bounds));
        }
        if (binding instanceof CaptureBinding) {
            bounds = false;
        }
    } else if (binding instanceof BaseTypeBinding) {
        String name = new String(binding.sourceName());
        //always create new TypeReference, because clonning from a cache clones invalid SourcePosition
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        ref.setSimpleName(name);
    } else if (binding instanceof WildcardBinding) {
        WildcardBinding wildcardBinding = (WildcardBinding) binding;
        ref = this.jdtTreeBuilder.getFactory().Core().createWildcardReference();

        if (wildcardBinding.boundKind == Wildcard.SUPER && ref instanceof CtTypeParameterReference) {
            ((CtTypeParameterReference) ref).setUpper(false);
        }

        if (wildcardBinding.bound != null && ref instanceof CtTypeParameterReference) {
            if (bindingCache.containsKey(wildcardBinding.bound)) {
                ((CtTypeParameterReference) ref)
                        .setBoundingType(getCtCircularTypeReference(wildcardBinding.bound));
            } else {

                ((CtTypeParameterReference) ref)
                        .setBoundingType(getTypeReference(((WildcardBinding) binding).bound));
            }
        }
    } else if (binding instanceof LocalTypeBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        if (binding.isAnonymousType()) {
            ref.setSimpleName(JDTTreeBuilderHelper
                    .computeAnonymousName(((SourceTypeBinding) binding).constantPoolName()));
            ref.setDeclaringType(getTypeReference((binding.enclosingType())));
        } else {
            ref.setSimpleName(new String(binding.sourceName()));
            if (((LocalTypeBinding) binding).enclosingMethod == null && binding.enclosingType() != null
                    && binding.enclosingType() instanceof LocalTypeBinding) {
                ref.setDeclaringType(getTypeReference(binding.enclosingType()));
            } else if (binding.enclosingMethod() != null) {
                ref.setSimpleName(JDTTreeBuilderHelper
                        .computeAnonymousName(((SourceTypeBinding) binding).constantPoolName()));
                ref.setDeclaringType(getTypeReference(binding.enclosingType()));
            }
        }
    } else if (binding instanceof SourceTypeBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        if (binding.isAnonymousType()) {
            ref.setSimpleName(JDTTreeBuilderHelper
                    .computeAnonymousName(((SourceTypeBinding) binding).constantPoolName()));
            ref.setDeclaringType(getTypeReference((binding.enclosingType())));
        } else {
            ref.setSimpleName(new String(binding.sourceName()));
            if (binding.enclosingType() != null) {
                ref.setDeclaringType(getTypeReference(binding.enclosingType()));
            } else {
                ref.setPackage(getPackageReference(binding.getPackage()));
            }
            // if(((SourceTypeBinding) binding).typeVariables!=null &&
            // ((SourceTypeBinding) binding).typeVariables.length>0){
            // for (TypeBinding b : ((SourceTypeBinding)
            // binding).typeVariables) {
            // ref.getActualTypeArguments().add(getTypeReference(b));
            // }
            // }
        }
    } else if (binding instanceof ArrayBinding) {
        CtArrayTypeReference<Object> arrayref;
        arrayref = this.jdtTreeBuilder.getFactory().Core().createArrayTypeReference();
        ref = arrayref;
        for (int i = 1; i < binding.dimensions(); i++) {
            CtArrayTypeReference<Object> tmp = this.jdtTreeBuilder.getFactory().Core()
                    .createArrayTypeReference();
            arrayref.setComponentType(tmp);
            arrayref = tmp;
        }
        arrayref.setComponentType(getTypeReference(binding.leafComponentType()));
    } else if (binding instanceof PolyTypeBinding) {
        // JDT can't resolve the type of this binding and we only have a string.
        // In this case, we return a type Object because we can't know more about it.
        ref = this.jdtTreeBuilder.getFactory().Type().objectType();
    } else if (binding instanceof ProblemReferenceBinding) {
        // Spoon is able to analyze also without the classpath
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        ref.setSimpleName(new String(binding.readableName()));
        final CtReference declaring = this.getDeclaringReferenceFromImports(binding.sourceName());
        setPackageOrDeclaringType(ref, declaring);
    } else if (binding instanceof JDTTreeBuilder.SpoonReferenceBinding) {
        ref = this.jdtTreeBuilder.getFactory().Core().createTypeReference();
        ref.setSimpleName(new String(binding.sourceName()));
        ref.setDeclaringType(getTypeReference(binding.enclosingType()));
    } else if (binding instanceof IntersectionTypeBinding18) {
        List<CtTypeReference<?>> bounds = new ArrayList<>();
        for (ReferenceBinding superInterface : binding.getIntersectingTypes()) {
            bounds.add(getTypeReference(superInterface));
        }
        ref = this.jdtTreeBuilder.getFactory().Type().createIntersectionTypeReferenceWithBounds(bounds);
    } else {
        throw new RuntimeException("Unknown TypeBinding: " + binding.getClass() + " " + binding);
    }
    bindingCache.remove(binding);
    this.exploringParameterizedBindings.remove(binding);
    return (CtTypeReference<T>) ref;
}