Search in sources :

Example 16 with List

use of com.sun.tools.javac.util.List in project ceylon-compiler by ceylon.

the class AbstractTransformer method makeReifiedTypeArgumentResolved.

private JCExpression makeReifiedTypeArgumentResolved(Type pt, boolean qualified) {
    if (pt.isUnion()) {
        // FIXME: refactor this shite
        List<JCExpression> typeTestArguments = List.nil();
        java.util.List<Type> typeParameters = pt.getCaseTypes();
        if (typeParameters.size() == 2) {
            Type alternative = null;
            if (typeParameters.get(0).isEmpty())
                alternative = typeParameters.get(1);
            else if (typeParameters.get(1).isEmpty())
                alternative = typeParameters.get(0);
            if (alternative != null && alternative.isTuple()) {
                JCExpression tupleType = makeTupleTypeDescriptor(alternative, true);
                if (tupleType != null)
                    return tupleType;
            }
        }
        for (int i = typeParameters.size() - 1; i >= 0; i--) {
            typeTestArguments = typeTestArguments.prepend(makeReifiedTypeArgument(typeParameters.get(i)));
        }
        return make().Apply(null, makeSelect(makeTypeDescriptorType(), "union"), typeTestArguments);
    } else if (pt.isIntersection()) {
        List<JCExpression> typeTestArguments = List.nil();
        java.util.List<Type> typeParameters = pt.getSatisfiedTypes();
        for (int i = typeParameters.size() - 1; i >= 0; i--) {
            typeTestArguments = typeTestArguments.prepend(makeReifiedTypeArgument(typeParameters.get(i)));
        }
        return make().Apply(null, makeSelect(makeTypeDescriptorType(), "intersection"), typeTestArguments);
    } else if (pt.isNothing()) {
        return makeNothingTypeDescriptor();
    }
    TypeDeclaration declaration = pt.getDeclaration();
    if (declaration instanceof Constructor) {
        pt = pt.getExtendedType();
        declaration = pt.getDeclaration();
    }
    if (pt.isClassOrInterface()) {
        if (declaration.isJavaEnum()) {
            pt = pt.getExtendedType();
            declaration = pt.getDeclaration();
        }
        // see if we have an alias for it
        if (supportsReifiedAlias((ClassOrInterface) declaration)) {
            JCExpression qualifier = naming.makeDeclarationName(declaration, DeclNameFlag.QUALIFIED);
            return makeSelect(qualifier, naming.getTypeDescriptorAliasName());
        }
        if (pt.isTuple()) {
            JCExpression tupleType = makeTupleTypeDescriptor(pt, false);
            if (tupleType != null)
                return tupleType;
        }
        // no alias, must build it
        List<JCExpression> typeTestArguments = makeReifiedTypeArgumentsResolved(pt.getTypeArgumentList(), qualified);
        JCExpression thisType = makeUnerasedClassLiteral(declaration);
        // do we have variance overrides?
        Map<TypeParameter, SiteVariance> varianceOverrides = pt.getVarianceOverrides();
        if (!varianceOverrides.isEmpty()) {
            // we need to pass them as second argument then, in an array
            ListBuffer<JCExpression> varianceElements = new ListBuffer<JCExpression>();
            for (TypeParameter typeParameter : declaration.getTypeParameters()) {
                SiteVariance useSiteVariance = varianceOverrides.get(typeParameter);
                String selector;
                if (useSiteVariance != null) {
                    switch(useSiteVariance) {
                        case IN:
                            selector = "IN";
                            break;
                        case OUT:
                            selector = "OUT";
                            break;
                        default:
                            selector = "NONE";
                            break;
                    }
                } else {
                    selector = "NONE";
                }
                JCExpression varianceElement = make().Select(makeIdent(syms().ceylonVarianceType), names().fromString(selector));
                varianceElements.append(varianceElement);
            }
            JCNewArray varianceArray = make().NewArray(makeIdent(syms().ceylonVarianceType), List.<JCExpression>nil(), varianceElements.toList());
            typeTestArguments = typeTestArguments.prepend(varianceArray);
        }
        typeTestArguments = typeTestArguments.prepend(thisType);
        JCExpression classDescriptor = make().Apply(null, makeSelect(makeTypeDescriptorType(), "klass"), typeTestArguments);
        Type qualifyingType = pt.getQualifyingType();
        JCExpression containerType = null;
        if (qualifyingType == null && // ignore qualifying types of static java declarations
        (Decl.isCeylon(declaration) || !declaration.isStaticallyImportable())) {
            // it may be contained in a function or value, and we want its type
            Declaration enclosingDeclaration = getDeclarationContainer(declaration);
            if (enclosingDeclaration instanceof TypedDeclaration)
                containerType = makeTypedDeclarationTypeDescriptorResolved((TypedDeclaration) enclosingDeclaration);
            else if (enclosingDeclaration instanceof TypeDeclaration) {
                qualifyingType = ((TypeDeclaration) enclosingDeclaration).getType();
            }
        }
        if (qualifyingType != null && qualifyingType.getDeclaration() instanceof Constructor) {
            qualifyingType = qualifyingType.getQualifyingType();
        }
        if (qualifyingType != null) {
            containerType = makeReifiedTypeArgumentResolved(qualifyingType, true);
        }
        if (containerType == null) {
            return classDescriptor;
        } else {
            return make().Apply(null, makeSelect(makeTypeDescriptorType(), "member"), List.of(containerType, classDescriptor));
        }
    } else if (pt.isTypeParameter()) {
        TypeParameter tp = (TypeParameter) declaration;
        String name = naming.getTypeArgumentDescriptorName(tp);
        if (!qualified || isTypeParameterSubstituted(tp))
            return makeUnquotedIdent(name);
        Scope container = tp.getContainer();
        JCExpression qualifier = null;
        if (container instanceof Class) {
            qualifier = naming.makeQualifiedThis(makeJavaType(((Class) container).getType(), JT_RAW));
        } else if (container instanceof Interface) {
            qualifier = naming.makeQualifiedThis(makeJavaType(((Interface) container).getType(), JT_COMPANION | JT_RAW));
        } else if (container instanceof Function) {
            // name must be a unique name, as returned by getTypeArgumentDescriptorName
            return makeUnquotedIdent(name);
        } else {
            throw BugException.unhandledCase(container);
        }
        return makeSelect(qualifier, name);
    } else {
        throw BugException.unhandledDeclarationCase(declaration);
    }
}
Also used : TypedDeclaration(com.redhat.ceylon.model.typechecker.model.TypedDeclaration) TypeParameter(com.redhat.ceylon.model.typechecker.model.TypeParameter) JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) Constructor(com.redhat.ceylon.model.typechecker.model.Constructor) ListBuffer(com.sun.tools.javac.util.ListBuffer) Function(com.redhat.ceylon.model.typechecker.model.Function) Type(com.redhat.ceylon.model.typechecker.model.Type) ModelUtil.appliedType(com.redhat.ceylon.model.typechecker.model.ModelUtil.appliedType) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) SiteVariance(com.redhat.ceylon.model.typechecker.model.SiteVariance) Scope(com.redhat.ceylon.model.typechecker.model.Scope) ArrayList(java.util.ArrayList) List(com.sun.tools.javac.util.List) LinkedList(java.util.LinkedList) ParameterList(com.redhat.ceylon.model.typechecker.model.ParameterList) Class(com.redhat.ceylon.model.typechecker.model.Class) TypedDeclaration(com.redhat.ceylon.model.typechecker.model.TypedDeclaration) Declaration(com.redhat.ceylon.model.typechecker.model.Declaration) TypeDeclaration(com.redhat.ceylon.model.typechecker.model.TypeDeclaration) TypeDeclaration(com.redhat.ceylon.model.typechecker.model.TypeDeclaration) JCNewArray(com.sun.tools.javac.tree.JCTree.JCNewArray) ClassOrInterface(com.redhat.ceylon.model.typechecker.model.ClassOrInterface) Interface(com.redhat.ceylon.model.typechecker.model.Interface)

Example 17 with List

use of com.sun.tools.javac.util.List in project glide by bumptech.

the class RootModuleGenerator method getExcludedGlideModuleClassNames.

private static Set<String> getExcludedGlideModuleClassNames(ProcessingEnvironment processingEnv, String rootGlideModuleClassName) {
    TypeElement rootGlideModule = processingEnv.getElementUtils().getTypeElement(rootGlideModuleClassName);
    String excludedModulesName = Excludes.class.getName();
    AnnotationValue excludedModuleAnnotationValue = null;
    for (AnnotationMirror annotationMirror : rootGlideModule.getAnnotationMirrors()) {
        // instead. This check is necessary because a given class may have multiple Annotations.
        if (!excludedModulesName.equals(annotationMirror.getAnnotationType().toString())) {
            continue;
        }
        Set<? extends Map.Entry<? extends ExecutableElement, ? extends AnnotationValue>> values = annotationMirror.getElementValues().entrySet();
        // (usually value).
        if (values.size() != 1) {
            throw new IllegalArgumentException("Expected single value, but found: " + values);
        }
        excludedModuleAnnotationValue = values.iterator().next().getValue();
        if (excludedModuleAnnotationValue == null) {
            throw new NullPointerException("Failed to find Excludes#value");
        }
    }
    // If the RootGlideModule class is not annotated, then there are no classes to exclude.
    if (excludedModuleAnnotationValue == null) {
        return Collections.emptySet();
    }
    List values = (List) excludedModuleAnnotationValue.getValue();
    Set<String> result = new HashSet<>(values.size());
    for (Object value : values) {
        Attribute.Class clazz = (Attribute.Class) value;
        result.add(clazz.getValue().toString());
    }
    return result;
}
Also used : Attribute(com.sun.tools.javac.code.Attribute) TypeElement(javax.lang.model.element.TypeElement) AnnotationMirror(javax.lang.model.element.AnnotationMirror) AnnotationValue(javax.lang.model.element.AnnotationValue) List(com.sun.tools.javac.util.List) Map(java.util.Map) HashSet(java.util.HashSet)

Example 18 with List

use of com.sun.tools.javac.util.List in project error-prone by google.

the class Template method callCheckMethod.

/**
   * Reflectively invoke Resolve.checkMethod(), which despite being package-private is apparently
   * the only useful entry-point into javac8's type inference implementation.
   */
private MethodType callCheckMethod(Warner warner, Inliner inliner, Object resultInfo, List<Type> actualArgTypes, MethodSymbol methodSymbol, Type site, Env<AttrContext> env) throws InferException {
    try {
        Method checkMethod;
        checkMethod = Resolve.class.getDeclaredMethod("checkMethod", Env.class, Type.class, Symbol.class, // ResultInfo is package-private
        Class.forName("com.sun.tools.javac.comp.Attr$ResultInfo"), List.class, List.class, Warner.class);
        checkMethod.setAccessible(true);
        return (MethodType) checkMethod.invoke(Resolve.instance(inliner.getContext()), env, site, methodSymbol, resultInfo, actualArgTypes, /*freeTypeVariables=*/
        List.<Type>nil(), warner);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof Resolve.InapplicableMethodException) {
            throw new InferException(ImmutableList.of(((Resolve.InapplicableMethodException) e.getTargetException()).getDiagnostic()));
        }
        throw new LinkageError(e.getMessage(), e.getCause());
    } catch (ReflectiveOperationException e) {
        throw new LinkageError(e.getMessage(), e);
    }
}
Also used : MethodType(com.sun.tools.javac.code.Type.MethodType) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) Symbol(com.sun.tools.javac.code.Symbol) Method(java.lang.reflect.Method) Env(com.sun.tools.javac.comp.Env) Resolve(com.sun.tools.javac.comp.Resolve) InvocationTargetException(java.lang.reflect.InvocationTargetException) Warner(com.sun.tools.javac.util.Warner) MethodType(com.sun.tools.javac.code.Type.MethodType) Type(com.sun.tools.javac.code.Type) List(com.sun.tools.javac.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList)

Example 19 with List

use of com.sun.tools.javac.util.List in project error-prone by google.

the class UPlaceholderStatement method apply.

@Override
public Choice<UnifierWithUnconsumedStatements> apply(final UnifierWithUnconsumedStatements initState) {
    final PlaceholderUnificationVisitor visitor = PlaceholderUnificationVisitor.create(TreeMaker.instance(initState.unifier().getContext()), arguments());
    PlaceholderVerificationVisitor verification = new PlaceholderVerificationVisitor(Collections2.transform(placeholder().requiredParameters(), Functions.forMap(arguments())), arguments().values());
    // The choices where we might conceivably have a completed placeholder match.
    Choice<State<ConsumptionState>> realOptions = Choice.none();
    // The choice of consumption states to this point in the block. 
    Choice<State<ConsumptionState>> choiceToHere = Choice.of(State.create(List.<UVariableDecl>nil(), initState.unifier(), ConsumptionState.empty()));
    if (verification.allRequiredMatched()) {
        realOptions = choiceToHere.or(realOptions);
    }
    for (final StatementTree targetStatement : initState.unconsumedStatements()) {
        if (!verification.scan(targetStatement, initState.unifier())) {
            // we saw a variable that's not allowed to be referenced
            break;
        }
        // Consume another statement, or if that fails, fall back to the previous choices...
        choiceToHere = choiceToHere.thenChoose(new Function<State<ConsumptionState>, Choice<State<ConsumptionState>>>() {

            @Override
            public Choice<State<ConsumptionState>> apply(final State<ConsumptionState> consumptionState) {
                return visitor.unifyStatement(targetStatement, consumptionState).transform(new Function<State<? extends JCStatement>, State<ConsumptionState>>() {

                    @Override
                    public State<ConsumptionState> apply(State<? extends JCStatement> stmtState) {
                        return stmtState.withResult(consumptionState.result().consume(stmtState.result()));
                    }
                });
            }
        });
        if (verification.allRequiredMatched()) {
            realOptions = choiceToHere.or(realOptions);
        }
    }
    return realOptions.thenOption(new Function<State<ConsumptionState>, Optional<UnifierWithUnconsumedStatements>>() {

        @Override
        public Optional<UnifierWithUnconsumedStatements> apply(State<ConsumptionState> consumptionState) {
            if (ImmutableSet.copyOf(consumptionState.seenParameters()).containsAll(placeholder().requiredParameters())) {
                Unifier resultUnifier = consumptionState.unifier().fork();
                int nConsumedStatements = consumptionState.result().consumedStatements();
                java.util.List<? extends StatementTree> remainingStatements = initState.unconsumedStatements().subList(nConsumedStatements, initState.unconsumedStatements().size());
                UnifierWithUnconsumedStatements result = UnifierWithUnconsumedStatements.create(resultUnifier, remainingStatements);
                List<JCStatement> impl = consumptionState.result().placeholderImplInReverseOrder().reverse();
                ControlFlowVisitor.Result implFlow = ControlFlowVisitor.INSTANCE.visitStatements(impl);
                if (implFlow == implementationFlow()) {
                    List<JCStatement> prevBinding = resultUnifier.getBinding(placeholder().blockKey());
                    if (prevBinding != null && prevBinding.toString().equals(impl.toString())) {
                        return Optional.of(result);
                    } else if (prevBinding == null) {
                        resultUnifier.putBinding(placeholder().blockKey(), impl);
                        return Optional.of(result);
                    }
                }
            }
            return Optional.absent();
        }
    });
}
Also used : Optional(com.google.common.base.Optional) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) StatementTree(com.sun.source.tree.StatementTree) Function(com.google.common.base.Function) State(com.google.errorprone.refaster.PlaceholderUnificationVisitor.State) List(com.sun.tools.javac.util.List) ImmutableList(com.google.common.collect.ImmutableList)

Example 20 with List

use of com.sun.tools.javac.util.List in project lombok by rzwitserloot.

the class JavacJavaUtilSingularizer method createJavaUtilSimpleCreationAndFillStatements.

protected List<JCStatement> createJavaUtilSimpleCreationAndFillStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, boolean defineVar, boolean addInitialCapacityArg, boolean nullGuard, String targetType, JCTree source) {
    List<JCExpression> jceBlank = List.nil();
    Name thisName = builderType.toName("this");
    JCStatement createStat;
    {
        // pluralName = new java.util.TargetType(initialCap);
        List<JCExpression> constructorArgs = List.nil();
        if (addInitialCapacityArg) {
            Name varName = mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName();
            // this.varName.size() < MAX_POWER_OF_2 ? 1 + this.varName.size() + (this.varName.size() - 3) / 3 : Integer.MAX_VALUE;
            // lessThanCutOff = this.varName.size() < MAX_POWER_OF_2
            JCExpression lessThanCutoff = maker.Binary(CTC_LESS_THAN, getSize(maker, builderType, varName, nullGuard, true), maker.Literal(CTC_INT, 0x40000000));
            JCExpression integerMaxValue = genJavaLangTypeRef(builderType, "Integer", "MAX_VALUE");
            JCExpression sizeFormulaLeft = maker.Binary(CTC_PLUS, maker.Literal(CTC_INT, 1), getSize(maker, builderType, varName, nullGuard, true));
            JCExpression sizeFormulaRightLeft = maker.Parens(maker.Binary(CTC_MINUS, getSize(maker, builderType, varName, nullGuard, true), maker.Literal(CTC_INT, 3)));
            JCExpression sizeFormulaRight = maker.Binary(CTC_DIV, sizeFormulaRightLeft, maker.Literal(CTC_INT, 3));
            JCExpression sizeFormula = maker.Binary(CTC_PLUS, sizeFormulaLeft, sizeFormulaRight);
            constructorArgs = List.<JCExpression>of(maker.Conditional(lessThanCutoff, sizeFormula, integerMaxValue));
        }
        JCExpression targetTypeExpr = chainDots(builderType, "java", "util", targetType);
        targetTypeExpr = addTypeArgs(mapMode ? 2 : 1, false, builderType, targetTypeExpr, data.getTypeArgs(), source);
        JCExpression constructorCall = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null);
        if (defineVar) {
            JCExpression localShadowerType = chainDotsString(builderType, data.getTargetFqn());
            localShadowerType = addTypeArgs(mapMode ? 2 : 1, false, builderType, localShadowerType, data.getTypeArgs(), source);
            createStat = maker.VarDef(maker.Modifiers(0), data.getPluralName(), localShadowerType, constructorCall);
        } else {
            createStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), constructorCall));
        }
    }
    JCStatement fillStat;
    {
        if (mapMode) {
            // for (int $i = 0; $i < this.pluralname$key.size(); i++) pluralname.put(this.pluralname$key.get($i), this.pluralname$value.get($i));
            Name ivar = builderType.toName("$i");
            Name keyVarName = builderType.toName(data.getPluralName() + "$key");
            JCExpression pluralnameDotPut = maker.Select(maker.Ident(data.getPluralName()), builderType.toName("put"));
            JCExpression arg1 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$key", "get"), List.<JCExpression>of(maker.Ident(ivar)));
            JCExpression arg2 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$value", "get"), List.<JCExpression>of(maker.Ident(ivar)));
            JCStatement putStatement = maker.Exec(maker.Apply(jceBlank, pluralnameDotPut, List.of(arg1, arg2)));
            JCStatement forInit = maker.VarDef(maker.Modifiers(0), ivar, maker.TypeIdent(CTC_INT), maker.Literal(CTC_INT, 0));
            JCExpression checkExpr = maker.Binary(CTC_LESS_THAN, maker.Ident(ivar), getSize(maker, builderType, keyVarName, nullGuard, true));
            JCExpression incrementExpr = maker.Unary(CTC_POSTINC, maker.Ident(ivar));
            fillStat = maker.ForLoop(List.of(forInit), checkExpr, List.of(maker.Exec(incrementExpr)), putStatement);
        } else {
            // pluralname.addAll(this.pluralname);
            JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName());
            fillStat = maker.Exec(maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("addAll")), List.of(thisDotPluralName)));
        }
        if (nullGuard) {
            JCExpression thisDotField = maker.Select(maker.Ident(thisName), mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName());
            JCExpression nullCheck = maker.Binary(CTC_NOT_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
            fillStat = maker.If(nullCheck, fillStat, null);
        }
    }
    JCStatement unmodifiableStat;
    {
        // pluralname = Collections.unmodifiableInterfaceType(pluralname);
        JCExpression arg = maker.Ident(data.getPluralName());
        JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiable" + data.getTargetSimpleType()), List.of(arg));
        unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke));
    }
    return List.of(createStat, fillStat, unmodifiableStat);
}
Also used : JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) List(com.sun.tools.javac.util.List) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) Name(com.sun.tools.javac.util.Name)

Aggregations

List (com.sun.tools.javac.util.List)25 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)16 ArrayList (java.util.ArrayList)11 JCStatement (com.sun.tools.javac.tree.JCTree.JCStatement)9 ListBuffer (com.sun.tools.javac.util.ListBuffer)7 ParameterList (com.redhat.ceylon.model.typechecker.model.ParameterList)5 TypeDeclaration (com.redhat.ceylon.model.typechecker.model.TypeDeclaration)5 TypedDeclaration (com.redhat.ceylon.model.typechecker.model.TypedDeclaration)5 JCTree (com.sun.tools.javac.tree.JCTree)5 ImmutableList (com.google.common.collect.ImmutableList)4 Tree (com.redhat.ceylon.compiler.typechecker.tree.Tree)4 Class (com.redhat.ceylon.model.typechecker.model.Class)4 Declaration (com.redhat.ceylon.model.typechecker.model.Declaration)4 Value (com.redhat.ceylon.model.typechecker.model.Value)4 LombokImmutableList (lombok.core.LombokImmutableList)4 ClassOrInterface (com.redhat.ceylon.model.typechecker.model.ClassOrInterface)3 Function (com.redhat.ceylon.model.typechecker.model.Function)3 FunctionOrValue (com.redhat.ceylon.model.typechecker.model.FunctionOrValue)3 Interface (com.redhat.ceylon.model.typechecker.model.Interface)3 Parameter (com.redhat.ceylon.model.typechecker.model.Parameter)3