Java Code Examples for com.sun.tools.javac.util.List#of()

The following examples show how to use com.sun.tools.javac.util.List#of() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Infer.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Computes a path that goes from a given node to the leafs in the graph.
 * Typically this will start from a node containing a variable in
 * {@code varsToSolve}. For any given path, the cost is computed as the total
 * number of type-variables that should be eagerly instantiated across that path.
 */
Pair<List<Node>, Integer> computeTreeToLeafs(Node n) {
    Pair<List<Node>, Integer> cachedPath = treeCache.get(n);
    if (cachedPath == null) {
        //cache miss
        if (n.isLeaf()) {
            //if leaf, stop
            cachedPath = new Pair<List<Node>, Integer>(List.of(n), n.data.length());
        } else {
            //if non-leaf, proceed recursively
            Pair<List<Node>, Integer> path = new Pair<List<Node>, Integer>(List.of(n), n.data.length());
            for (Node n2 : n.getAllDependencies()) {
                if (n2 == n) continue;
                Pair<List<Node>, Integer> subpath = computeTreeToLeafs(n2);
                path = new Pair<List<Node>, Integer>(
                        path.fst.prependList(subpath.fst),
                        path.snd + subpath.snd);
            }
            cachedPath = path;
        }
        //save results in cache
        treeCache.put(n, cachedPath);
    }
    return cachedPath;
}
 
Example 2
Source File: Symtab.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/** Enter a unary operation into symbol table.
 *  @param name     The name of the operator.
 *  @param arg      The type of the operand.
 *  @param res      The operation's result type.
 *  @param opcode   The operation's bytecode instruction.
 */
private OperatorSymbol enterUnop(String name,
                                 Type arg,
                                 Type res,
                                 int opcode) {
    OperatorSymbol sym =
        new OperatorSymbol(makeOperatorName(name),
                           new MethodType(List.of(arg),
                                          res,
                                          List.<Type>nil(),
                                          methodClass),
                           opcode,
                           predefClass);
    predefClass.members().enter(sym);
    return sym;
}
 
Example 3
Source File: Infer.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private List<Pair<Type, Type>> getParameterizedSupers(Type t, Type s) {
    Type lubResult = types.lub(t, s);
    if (lubResult == syms.errType || lubResult == syms.botType) {
        return List.nil();
    }
    List<Type> supertypesToCheck = lubResult.isIntersection() ?
            ((IntersectionClassType)lubResult).getComponents() :
            List.of(lubResult);
    ListBuffer<Pair<Type, Type>> commonSupertypes = new ListBuffer<>();
    for (Type sup : supertypesToCheck) {
        if (sup.isParameterized()) {
            Type asSuperOfT = asSuper(t, sup);
            Type asSuperOfS = asSuper(s, sup);
            commonSupertypes.add(new Pair<>(asSuperOfT, asSuperOfS));
        }
    }
    return commonSupertypes.toList();
}
 
Example 4
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void visitLambda(JCLambda tree) {
    if ((tree.type != null &&
            tree.type.isErroneous()) || inLambda) {
        return;
    }
    List<Type> prevCaught = caught;
    List<Type> prevThrown = thrown;
    ListBuffer<FlowPendingExit> prevPending = pendingExits;
    inLambda = true;
    try {
        pendingExits = new ListBuffer<>();
        caught = List.of(syms.throwableType);
        thrown = List.nil();
        scan(tree.body);
        inferredThrownTypes = thrown;
    } finally {
        pendingExits = prevPending;
        caught = prevCaught;
        thrown = prevThrown;
        inLambda = false;
    }
}
 
Example 5
Source File: Types.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Return list of bounds of the given type variable.
 */
public List<Type> getBounds(TypeVar t) {
    if (t.bound.isErroneous() || !t.bound.isCompound())
        return List.of(t.bound);
    else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
        return interfaces(t).prepend(supertype(t));
    else
        // No superclass was given in bounds.
        // In this case, supertype is Object, erasure is first interface.
        return interfaces(t);
}
 
Example 6
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	boolean mapMode = isMap();
	
	Name keyName = !mapMode ? data.getSingularName() : builderType.toName(data.getSingularName() + "$key");
	Name valueName = !mapMode ? null : builderType.toName(data.getSingularName() + "$value");
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, mapMode, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), mapMode ? "put" : "add");
	List<JCExpression> invokeAddExpr;
	if (mapMode) {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName), maker.Ident(valueName));
	} else {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName));
	}
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, invokeAddExpr);
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name methodName = data.getSingularName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(mapMode ? "put" : "add", methodName.toString()));
	List<JCVariableDecl> params;
	if (mapMode) {
		JCExpression keyType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		JCExpression valueType = cloneParamType(1, maker, data.getTypeArgs(), builderType, source);
		JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, keyType, null);
		JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, valueType, null);
		params = List.of(paramKey, paramValue);
	} else {
		JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		params = List.of(maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null));
	}
	JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null);
	injectMethod(builderType, method);
}
 
Example 7
Source File: StringConcat.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Produce the actual invokedynamic call to StringConcatFactory */
private void doCall(Type type, JCDiagnostic.DiagnosticPosition pos, List<Type> dynamicArgTypes) {
    Type.MethodType indyType = new Type.MethodType(dynamicArgTypes,
            type,
            List.nil(),
            syms.methodClass);

    int prevPos = make.pos;
    try {
        make.at(pos);

        List<Type> bsm_staticArgs = List.of(syms.methodHandleLookupType,
                syms.stringType,
                syms.methodTypeType);

        Symbol bsm = rs.resolveInternalMethod(pos,
                gen.getAttrEnv(),
                syms.stringConcatFactory,
                names.makeConcat,
                bsm_staticArgs,
                null);

        Symbol.DynamicMethodSymbol dynSym = new Symbol.DynamicMethodSymbol(names.makeConcat,
                syms.noSymbol,
                ClassFile.REF_invokeStatic,
                (Symbol.MethodSymbol)bsm,
                indyType,
                List.nil().toArray());

        Items.Item item = gen.getItems().makeDynamicItem(dynSym);
        item.invoke();
    } finally {
        make.at(prevPos);
    }
}
 
Example 8
Source File: Symtab.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void synthesizeBoxTypeIfMissing(final Type type) {
    ClassSymbol sym = reader.enterClass(boxedName[type.getTag().ordinal()]);
    final Completer completer = sym.completer;
    if (completer != null) {
        sym.completer = new Completer() {
            public void complete(Symbol sym) throws CompletionFailure {
                try {
                    completer.complete(sym);
                } catch (CompletionFailure e) {
                    sym.flags_field |= PUBLIC;
                    ((ClassType) sym.type).supertype_field = objectType;
                    Name n = target.boxWithConstructors() ? names.init : names.valueOf;
                    MethodSymbol boxMethod =
                        new MethodSymbol(PUBLIC | STATIC,
                            n,
                            new MethodType(List.of(type), sym.type,
                                List.<Type>nil(), methodClass),
                            sym);
                    sym.members().enter(boxMethod);
                    MethodSymbol unboxMethod =
                        new MethodSymbol(PUBLIC,
                            type.tsym.name.append(names.Value), // x.intValue()
                            new MethodType(List.<Type>nil(), type,
                                List.<Type>nil(), methodClass),
                            sym);
                    sym.members().enter(unboxMethod);
                }
            }
        };
    }

}
 
Example 9
Source File: LambdaToMethod.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private JCExpression deserTest(JCExpression prev, String func, String lit) {
    MethodType eqmt = new MethodType(List.of(syms.objectType), syms.booleanType, List.nil(), syms.methodClass);
    Symbol eqsym = rs.resolveQualifiedMethod(null, attrEnv, syms.objectType, names.equals, List.of(syms.objectType), List.nil());
    JCMethodInvocation eqtest = make.Apply(
            List.nil(),
            make.Select(deserGetter(func, syms.stringType), eqsym).setType(eqmt),
            List.of(make.Literal(lit)));
    eqtest.setType(syms.booleanType);
    JCBinary compound = make.Binary(JCTree.Tag.AND, prev, eqtest);
    compound.operator = operators.resolveBinary(compound, JCTree.Tag.AND, syms.booleanType, syms.booleanType);
    compound.setType(syms.booleanType);
    return compound;
}
 
Example 10
Source File: Lower.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private JCBlock makeTwrFinallyClause(Symbol primaryException, JCExpression resource) {
    // primaryException.addSuppressed(catchException);
    VarSymbol catchException =
        new VarSymbol(SYNTHETIC, make.paramName(2),
                      syms.throwableType,
                      currentMethodSym);
    JCStatement addSuppressionStatement =
        make.Exec(makeCall(make.Ident(primaryException),
                           names.addSuppressed,
                           List.<JCExpression>of(make.Ident(catchException))));

    // try { resource.close(); } catch (e) { primaryException.addSuppressed(e); }
    JCBlock tryBlock =
        make.Block(0L, List.<JCStatement>of(makeResourceCloseInvocation(resource)));
    JCVariableDecl catchExceptionDecl = make.VarDef(catchException, null);
    JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(addSuppressionStatement));
    List<JCCatch> catchClauses = List.<JCCatch>of(make.Catch(catchExceptionDecl, catchBlock));
    JCTry tryTree = make.Try(tryBlock, catchClauses, null);
    tryTree.finallyCanCompleteNormally = true;

    // if (primaryException != null) {try...} else resourceClose;
    JCIf closeIfStatement = make.If(makeNonNullCheck(make.Ident(primaryException)),
                                    tryTree,
                                    makeResourceCloseInvocation(resource));

    // if (#resource != null) { if (primaryException ...  }
    return make.Block(0L,
                      List.<JCStatement>of(make.If(makeNonNullCheck(resource),
                                                   closeIfStatement,
                                                   null)));
}
 
Example 11
Source File: Symtab.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void synthesizeBoxTypeIfMissing(final Type type) {
    ClassSymbol sym = reader.enterClass(boxedName[type.getTag().ordinal()]);
    final Completer completer = sym.completer;
    if (completer != null) {
        sym.completer = new Completer() {
            public void complete(Symbol sym) throws CompletionFailure {
                try {
                    completer.complete(sym);
                } catch (CompletionFailure e) {
                    sym.flags_field |= PUBLIC;
                    ((ClassType) sym.type).supertype_field = objectType;
                    Name n = target.boxWithConstructors() ? names.init : names.valueOf;
                    MethodSymbol boxMethod =
                        new MethodSymbol(PUBLIC | STATIC,
                            n,
                            new MethodType(List.of(type), sym.type,
                                List.<Type>nil(), methodClass),
                            sym);
                    sym.members().enter(boxMethod);
                    MethodSymbol unboxMethod =
                        new MethodSymbol(PUBLIC,
                            type.tsym.name.append(names.Value), // x.intValue()
                            new MethodType(List.<Type>nil(), type,
                                List.<Type>nil(), methodClass),
                            sym);
                    sym.members().enter(unboxMethod);
                }
            }
        };
    }

}
 
Example 12
Source File: Lower.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private JCBlock makeTwrFinallyClause(Symbol primaryException, JCExpression resource) {
    // primaryException.addSuppressed(catchException);
    VarSymbol catchException =
        new VarSymbol(SYNTHETIC, make.paramName(2),
                      syms.throwableType,
                      currentMethodSym);
    JCStatement addSuppressionStatement =
        make.Exec(makeCall(make.Ident(primaryException),
                           names.addSuppressed,
                           List.<JCExpression>of(make.Ident(catchException))));

    // try { resource.close(); } catch (e) { primaryException.addSuppressed(e); }
    JCBlock tryBlock =
        make.Block(0L, List.<JCStatement>of(makeResourceCloseInvocation(resource)));
    JCVariableDecl catchExceptionDecl = make.VarDef(catchException, null);
    JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(addSuppressionStatement));
    List<JCCatch> catchClauses = List.<JCCatch>of(make.Catch(catchExceptionDecl, catchBlock));
    JCTry tryTree = make.Try(tryBlock, catchClauses, null);
    tryTree.finallyCanCompleteNormally = true;

    // if (primaryException != null) {try...} else resourceClose;
    JCIf closeIfStatement = make.If(makeNonNullCheck(make.Ident(primaryException)),
                                    tryTree,
                                    makeResourceCloseInvocation(resource));

    // if (#resource != null) { if (primaryException ...  }
    return make.Block(0L,
                      List.<JCStatement>of(make.If(makeNonNullCheck(resource),
                                                   closeIfStatement,
                                                   null)));
}
 
Example 13
Source File: Lower.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/** Return access symbol for a private or protected symbol from an inner class.
 *  @param sym        The accessed private symbol.
 *  @param tree       The accessing tree.
 *  @param enclOp     The closest enclosing operation node of tree,
 *                    null if tree is not a subtree of an operation.
 *  @param protAccess Is access to a protected symbol in another
 *                    package?
 *  @param refSuper   Is access via a (qualified) C.super?
 */
MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
                          boolean protAccess, boolean refSuper) {
    ClassSymbol accOwner = refSuper && protAccess
        // For access via qualified super (T.super.x), place the
        // access symbol on T.
        ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
        // Otherwise pretend that the owner of an accessed
        // protected symbol is the enclosing class of the current
        // class which is a subclass of the symbol's owner.
        : accessClass(sym, protAccess, tree);

    Symbol vsym = sym;
    if (sym.owner != accOwner) {
        vsym = sym.clone(accOwner);
        actualSymbols.put(vsym, sym);
    }

    Integer anum              // The access number of the access method.
        = accessNums.get(vsym);
    if (anum == null) {
        anum = accessed.length();
        accessNums.put(vsym, anum);
        accessSyms.put(vsym, new MethodSymbol[NCODES]);
        accessed.append(vsym);
        // System.out.println("accessing " + vsym + " in " + vsym.location());
    }

    int acode;                // The access code of the access method.
    List<Type> argtypes;      // The argument types of the access method.
    Type restype;             // The result type of the access method.
    List<Type> thrown;        // The thrown exceptions of the access method.
    switch (vsym.kind) {
    case VAR:
        acode = accessCode(tree, enclOp);
        if (acode >= FIRSTASGOPcode) {
            OperatorSymbol operator = binaryAccessOperator(acode);
            if (operator.opcode == string_add)
                argtypes = List.of(syms.objectType);
            else
                argtypes = operator.type.getParameterTypes().tail;
        } else if (acode == ASSIGNcode)
            argtypes = List.of(vsym.erasure(types));
        else
            argtypes = List.nil();
        restype = vsym.erasure(types);
        thrown = List.nil();
        break;
    case MTH:
        acode = DEREFcode;
        argtypes = vsym.erasure(types).getParameterTypes();
        restype = vsym.erasure(types).getReturnType();
        thrown = vsym.type.getThrownTypes();
        break;
    default:
        throw new AssertionError();
    }

    // For references via qualified super, increment acode by one,
    // making it odd.
    if (protAccess && refSuper) acode++;

    // Instance access methods get instance as first parameter.
    // For protected symbols this needs to be the instance as a member
    // of the type containing the accessed symbol, not the class
    // containing the access method.
    if ((vsym.flags() & STATIC) == 0) {
        argtypes = argtypes.prepend(vsym.owner.erasure(types));
    }
    MethodSymbol[] accessors = accessSyms.get(vsym);
    MethodSymbol accessor = accessors[acode];
    if (accessor == null) {
        accessor = new MethodSymbol(
            STATIC | SYNTHETIC,
            accessName(anum.intValue(), acode),
            new MethodType(argtypes, restype, thrown, syms.methodClass),
            accOwner);
        enterSynthetic(tree.pos(), accessor, accOwner.members());
        accessors[acode] = accessor;
    }
    return accessor;
}
 
Example 14
Source File: Lower.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * A statement of the form
 *
 * <pre>
 *     for ( T v : arrayexpr ) stmt;
 * </pre>
 *
 * (where arrayexpr is of an array type) gets translated to
 *
 * <pre>{@code
 *     for ( { arraytype #arr = arrayexpr;
 *             int #len = array.length;
 *             int #i = 0; };
 *           #i < #len; i$++ ) {
 *         T v = arr$[#i];
 *         stmt;
 *     }
 * }</pre>
 *
 * where #arr, #len, and #i are freshly named synthetic local variables.
 */
private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
    make_at(tree.expr.pos());
    VarSymbol arraycache = new VarSymbol(SYNTHETIC,
                                         names.fromString("arr" + target.syntheticNameChar()),
                                         tree.expr.type,
                                         currentMethodSym);
    JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
    VarSymbol lencache = new VarSymbol(SYNTHETIC,
                                       names.fromString("len" + target.syntheticNameChar()),
                                       syms.intType,
                                       currentMethodSym);
    JCStatement lencachedef = make.
        VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
    VarSymbol index = new VarSymbol(SYNTHETIC,
                                    names.fromString("i" + target.syntheticNameChar()),
                                    syms.intType,
                                    currentMethodSym);

    JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
    indexdef.init.type = indexdef.type = syms.intType.constType(0);

    List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
    JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));

    JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));

    Type elemtype = types.elemtype(tree.expr.type);
    JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
                                            make.Ident(index)).setType(elemtype);
    JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
                                          tree.var.name,
                                          tree.var.vartype,
                                          loopvarinit).setType(tree.var.type);
    loopvardef.sym = tree.var.sym;
    JCBlock body = make.
        Block(0, List.of(loopvardef, tree.body));

    result = translate(make.
                       ForLoop(loopinit,
                               cond,
                               List.of(step),
                               body));
    patchTargets(body, tree, result);
}
 
Example 15
Source File: Lower.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * A statement of the form
 *
 * <pre>
 *     for ( T v : arrayexpr ) stmt;
 * </pre>
 *
 * (where arrayexpr is of an array type) gets translated to
 *
 * <pre>{@code
 *     for ( { arraytype #arr = arrayexpr;
 *             int #len = array.length;
 *             int #i = 0; };
 *           #i < #len; i$++ ) {
 *         T v = arr$[#i];
 *         stmt;
 *     }
 * }</pre>
 *
 * where #arr, #len, and #i are freshly named synthetic local variables.
 */
private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
    make_at(tree.expr.pos());
    VarSymbol arraycache = new VarSymbol(SYNTHETIC,
                                         names.fromString("arr" + target.syntheticNameChar()),
                                         tree.expr.type,
                                         currentMethodSym);
    JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
    VarSymbol lencache = new VarSymbol(SYNTHETIC,
                                       names.fromString("len" + target.syntheticNameChar()),
                                       syms.intType,
                                       currentMethodSym);
    JCStatement lencachedef = make.
        VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
    VarSymbol index = new VarSymbol(SYNTHETIC,
                                    names.fromString("i" + target.syntheticNameChar()),
                                    syms.intType,
                                    currentMethodSym);

    JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
    indexdef.init.type = indexdef.type = syms.intType.constType(0);

    List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
    JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));

    JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));

    Type elemtype = types.elemtype(tree.expr.type);
    JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
                                            make.Ident(index)).setType(elemtype);
    JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
                                          tree.var.name,
                                          tree.var.vartype,
                                          loopvarinit).setType(tree.var.type);
    loopvardef.sym = tree.var.sym;
    JCBlock body = make.
        Block(0, List.of(loopvardef, tree.body));

    result = translate(make.
                       ForLoop(loopinit,
                               cond,
                               List.of(step),
                               body));
    patchTargets(body, tree, result);
}
 
Example 16
Source File: Gen.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotations(JCCatch tree) {
    return TreeInfo.isMultiCatch(tree) ?
            catchTypesWithAnnotationsFromMulticatch((JCTypeUnion)tree.param.vartype, tree.param.sym.getRawTypeAttributes()) :
            List.of(new Pair<>(tree.param.sym.getRawTypeAttributes(), tree.param.vartype));
}
 
Example 17
Source File: Analyzer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
List<JCVariableDecl> rewrite(JCVariableDecl oldTree) {
    return List.of(rewriteVarType(oldTree));
}
 
Example 18
Source File: Infer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Compute a synthetic method type corresponding to the requested polymorphic
 * method signature. The target return type is computed from the immediately
 * enclosing scope surrounding the polymorphic-signature call.
 */
Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env,
                                        MethodSymbol spMethod,  // sig. poly. method or null if none
                                        Resolve.MethodResolutionContext resolveContext,
                                        List<Type> argtypes) {
    final Type restype;

    if (spMethod == null || types.isSameType(spMethod.getReturnType(), syms.objectType, true)) {
        // The return type of the polymorphic signature is polymorphic,
        // and is computed from the enclosing tree E, as follows:
        // if E is a cast, then use the target type of the cast expression
        // as a return type; if E is an expression statement, the return
        // type is 'void'; otherwise
        // the return type is simply 'Object'. A correctness check ensures
        // that env.next refers to the lexically enclosing environment in
        // which the polymorphic signature call environment is nested.

        switch (env.next.tree.getTag()) {
            case TYPECAST:
                JCTypeCast castTree = (JCTypeCast)env.next.tree;
                restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ?
                          castTree.clazz.type :
                          syms.objectType;
                break;
            case EXEC:
                JCTree.JCExpressionStatement execTree =
                        (JCTree.JCExpressionStatement)env.next.tree;
                restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ?
                          syms.voidType :
                          syms.objectType;
                break;
            default:
                restype = syms.objectType;
        }
    } else {
        // The return type of the polymorphic signature is fixed
        // (not polymorphic)
        restype = spMethod.getReturnType();
    }

    List<Type> paramtypes = argtypes.map(new ImplicitArgType(spMethod, resolveContext.step));
    List<Type> exType = spMethod != null ?
        spMethod.getThrownTypes() :
        List.of(syms.throwableType); // make it throw all exceptions

    MethodType mtype = new MethodType(paramtypes,
                                      restype,
                                      exType,
                                      syms.methodClass);
    return mtype;
}
 
Example 19
Source File: HandleSetter.java    From EasyMPermission with MIT License 4 votes vote down vote up
public static JCMethodDecl createSetter(long access, JavacNode field, JavacTreeMaker treeMaker, String setterName, boolean shouldReturnThis, JavacNode source, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) {
	if (setterName == null) return null;
	
	JCVariableDecl fieldDecl = (JCVariableDecl) field.get();
	
	JCExpression fieldRef = createFieldAccessor(treeMaker, field, FieldAccess.ALWAYS_FIELD);
	JCAssign assign = treeMaker.Assign(fieldRef, treeMaker.Ident(fieldDecl.name));
	
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	List<JCAnnotation> nonNulls = findAnnotations(field, NON_NULL_PATTERN);
	List<JCAnnotation> nullables = findAnnotations(field, NULLABLE_PATTERN);
	
	Name methodName = field.toName(setterName);
	List<JCAnnotation> annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables);
	
	long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext());
	JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null);
	
	if (nonNulls.isEmpty()) {
		statements.append(treeMaker.Exec(assign));
	} else {
		JCStatement nullCheck = generateNullCheck(treeMaker, field, source);
		if (nullCheck != null) statements.append(nullCheck);
		statements.append(treeMaker.Exec(assign));
	}
	
	JCExpression methodType = null;
	if (shouldReturnThis) {
		methodType = cloneSelfType(field);
	}
	
	if (methodType == null) {
		//WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6.
		methodType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID));
		shouldReturnThis = false;
	}
	
	if (shouldReturnThis) {
		JCReturn returnStatement = treeMaker.Return(treeMaker.Ident(field.toName("this")));
		statements.append(returnStatement);
	}
	
	JCBlock methodBody = treeMaker.Block(0, statements.toList());
	List<JCTypeParameter> methodGenericParams = List.nil();
	List<JCVariableDecl> parameters = List.of(param);
	List<JCExpression> throwsClauses = List.nil();
	JCExpression annotationMethodDefaultValue = null;
	
	List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod);
	if (isFieldDeprecated(field)) {
		annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.<JCExpression>nil()));
	}
	
	JCMethodDecl decl = recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType,
			methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext());
	copyJavadoc(field, decl, CopyJavadoc.SETTER);
	return decl;
}
 
Example 20
Source File: WildcardTypeImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private static List<Type> getSuperBounds(Type.WildcardType wild) {
    return wild.isExtendsBound()
            ? List.<Type>nil()
            : List.of(wild.type);
}