Search in sources :

Example 1 with PackageFactory

use of spoon.reflect.factory.PackageFactory in project spoon by INRIA.

the class ReferenceBuilder method getTypeReference.

/**
 * JDT doesn't return a correct AST with the resolved type of the reference.
 * This method try to build a correct Spoon AST from the name of the JDT
 * reference, thanks to the parsing of the string, the name parameterized from
 * the JDT reference and java convention.
 * Returns a complete Spoon AST when the name is correct, otherwise a spoon type
 * reference with a name that correspond to the name of the JDT type reference.
 */
<T> CtTypeReference<T> getTypeReference(TypeReference ref) {
    CtTypeReference<T> res = null;
    CtTypeReference inner = null;
    final String[] namesParameterized = CharOperation.charArrayToStringArray(ref.getParameterizedTypeName());
    String nameParameterized = CharOperation.toString(ref.getParameterizedTypeName());
    String typeName = CharOperation.toString(ref.getTypeName());
    int index = namesParameterized.length - 1;
    for (; index >= 0; index--) {
        // Start at the end to get the class name first.
        CtTypeReference main = getTypeReference(namesParameterized[index]);
        if (main == null) {
            break;
        }
        if (res == null) {
            res = (CtTypeReference<T>) main;
        } else {
            inner.setDeclaringType((CtTypeReference<?>) main);
        }
        inner = main;
    }
    if (res == null) {
        return this.jdtTreeBuilder.getFactory().Type().createReference(nameParameterized);
    }
    if (inner.getPackage() == null) {
        PackageFactory packageFactory = this.jdtTreeBuilder.getFactory().Package();
        CtPackageReference packageReference = index >= 0 ? packageFactory.getOrCreate(concatSubArray(namesParameterized, index)).getReference() : packageFactory.topLevel();
        inner.setPackage(packageReference);
    }
    if (!res.toString().replace(", ?", ",?").endsWith(nameParameterized)) {
        // verify that we did not match a class that have the same name in a different package
        return this.jdtTreeBuilder.getFactory().Type().createReference(typeName);
    }
    return res;
}
Also used : PackageFactory(spoon.reflect.factory.PackageFactory) CtPackageReference(spoon.reflect.reference.CtPackageReference) CtTypeReference(spoon.reflect.reference.CtTypeReference)

Aggregations

PackageFactory (spoon.reflect.factory.PackageFactory)1 CtPackageReference (spoon.reflect.reference.CtPackageReference)1 CtTypeReference (spoon.reflect.reference.CtTypeReference)1