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

The following examples show how to use com.sun.tools.javac.util.List#nonEmpty() . 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: InferenceContext.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/** Restore the state of this inference context to the previous known checkpoint.
*  Consider that the number of saved undetermined variables can be different to the current
*  amount. This is because new captured variables could have been added.
*/
public void rollback(List<Type> saved_undet) {
    Assert.check(saved_undet != null);
    //restore bounds (note: we need to preserve the old instances)
    ListBuffer<Type> newUndetVars = new ListBuffer<>();
    ListBuffer<Type> newInferenceVars = new ListBuffer<>();
    while (saved_undet.nonEmpty() && undetvars.nonEmpty()) {
        UndetVar uv = (UndetVar)undetvars.head;
        UndetVar uv_saved = (UndetVar)saved_undet.head;
        if (uv.qtype == uv_saved.qtype) {
            uv_saved.dupTo(uv, types);
            undetvars = undetvars.tail;
            saved_undet = saved_undet.tail;
            newUndetVars.add(uv);
            newInferenceVars.add(uv.qtype);
        } else {
            undetvars = undetvars.tail;
        }
    }
    undetvars = newUndetVars.toList();
    inferencevars = newInferenceVars.toList();
}
 
Example 2
Source File: TransTypes.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/** Translate method argument list, casting each argument
 *  to its corresponding type in a list of target types.
 *  @param _args            The method argument list.
 *  @param parameters       The list of target types.
 *  @param varargsElement   The erasure of the varargs element type,
 *  or null if translating a non-varargs invocation
 */
<T extends JCTree> List<T> translateArgs(List<T> _args,
                                       List<Type> parameters,
                                       Type varargsElement) {
    if (parameters.isEmpty()) return _args;
    List<T> args = _args;
    while (parameters.tail.nonEmpty()) {
        args.head = translate(args.head, parameters.head);
        args = args.tail;
        parameters = parameters.tail;
    }
    Type parameter = parameters.head;
    Assert.check(varargsElement != null || args.length() == 1);
    if (varargsElement != null) {
        while (args.nonEmpty()) {
            args.head = translate(args.head, varargsElement);
            args = args.tail;
        }
    } else {
        args.head = translate(args.head, parameter);
    }
    return _args;
}
 
Example 3
Source File: WildcardTypeImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the string form of a wildcard type ("?") along with any
 * "extends" or "super" clause.  Delimiting brackets are not
 * included.  Class names are qualified if "full" is true.
 */
static String wildcardTypeToString(DocEnv env,
                                   Type.WildcardType wildThing, boolean full) {
    if (env.legacyDoclet) {
        return TypeMaker.getTypeName(env.types.erasure(wildThing), full);
    }
    StringBuilder s = new StringBuilder("?");
    List<Type> bounds = getExtendsBounds(wildThing);
    if (bounds.nonEmpty()) {
        s.append(" extends ");
    } else {
        bounds = getSuperBounds(wildThing);
        if (bounds.nonEmpty()) {
            s.append(" super ");
        }
    }
    boolean first = true;   // currently only one bound is allowed
    for (Type b : bounds) {
        if (!first) {
            s.append(" & ");
        }
        s.append(TypeMaker.getTypeString(env, b, full));
        first = false;
    }
    return s.toString();
}
 
Example 4
Source File: CRTable.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Visitor method: compute source positions for
 * a list of case blocks of switch statements.
 */
public SourceRange cspCases(List<JCCase> trees) {
    if ((trees == null) || !(trees.nonEmpty())) return null;
    SourceRange list_sr = new SourceRange();
    for (List<JCCase> l = trees; l.nonEmpty(); l = l.tail) {
        list_sr.mergeWith(csp(l.head));
    }
    positions.put(trees, list_sr);
    return list_sr;
}
 
Example 5
Source File: TestProcessor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
String print(List<? extends JCTree> list, String sep) {
    StringBuilder sb = new StringBuilder();
    if (list.nonEmpty()) {
        sb.append(print(list.head));
        for (List<? extends JCTree> l = list.tail; l.nonEmpty(); l = l.tail) {
            sb.append(sep);
            sb.append(print(l.head));
        }
    }
    return sb.toString();
}
 
Example 6
Source File: Infer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
void apply(InferenceContext inferenceContext, Warner warn) {
    List<Type> boundList = StreamSupport.stream(uv.getBounds(InferenceBound.UPPER))
            .collect(types.closureCollector(true, types::isSameType));
    for (Type b2 : boundList) {
        if (t == b2) continue;
            /* This wildcard check is temporary workaround. This code may need to be
             * revisited once spec bug JDK-7034922 is fixed.
             */
        if (t != b2 && !t.hasTag(WILDCARD) && !b2.hasTag(WILDCARD)) {
            for (Pair<Type, Type> commonSupers : getParameterizedSupers(t, b2)) {
                List<Type> allParamsSuperBound1 = commonSupers.fst.allparams();
                List<Type> allParamsSuperBound2 = commonSupers.snd.allparams();
                while (allParamsSuperBound1.nonEmpty() && allParamsSuperBound2.nonEmpty()) {
                    //traverse the list of all params comparing them
                    if (!allParamsSuperBound1.head.hasTag(WILDCARD) &&
                            !allParamsSuperBound2.head.hasTag(WILDCARD)) {
                        if (!isSameType(inferenceContext.asUndetVar(allParamsSuperBound1.head),
                                inferenceContext.asUndetVar(allParamsSuperBound2.head))) {
                            reportBoundError(uv, InferenceBound.UPPER);
                        }
                    }
                    allParamsSuperBound1 = allParamsSuperBound1.tail;
                    allParamsSuperBound2 = allParamsSuperBound2.tail;
                }
                Assert.check(allParamsSuperBound1.isEmpty() && allParamsSuperBound2.isEmpty());
            }
        }
    }
}
 
Example 7
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) {
    if (!isAPISymbol(what) && !inSuperType) { //package private/private element
        log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
        return ;
    }

    PackageSymbol whatPackage = what.packge();
    ExportsDirective whatExport = findExport(whatPackage);
    ExportsDirective inExport = findExport(inPackage);

    if (whatExport == null) { //package not exported:
        log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
        return ;
    }

    if (whatExport.modules != null) {
        if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) {
            log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
        }
    }

    if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) {
        //check that relativeTo.modle requires transitive what.modle, somehow:
        List<ModuleSymbol> todo = List.of(inPackage.modle);

        while (todo.nonEmpty()) {
            ModuleSymbol current = todo.head;
            todo = todo.tail;
            if (current == whatPackage.modle)
                return ; //OK
            for (RequiresDirective req : current.requires) {
                if (req.isTransitive()) {
                    todo = todo.prepend(req.module);
                }
            }
        }

        log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
    }
}
 
Example 8
Source File: CRTable.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**  Visitor method: compute source positions for
 *    a list of case blocks of switch statements.
 */
public SourceRange cspCases(List<JCCase> trees) {
    if ((trees == null) || !(trees.nonEmpty())) return null;
    SourceRange list_sr = new SourceRange();
    for (List<JCCase> l = trees; l.nonEmpty(); l = l.tail) {
        list_sr.mergeWith(csp(l.head));
    }
    positions.put(trees, list_sr);
    return list_sr;
}
 
Example 9
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
    if ((c.flags_field & ACYCLIC) != 0)
        return;
    if (seenClasses.contains(c)) {
        errorFound = true;
        noteCyclic(pos, (ClassSymbol)c);
    } else if (!c.type.isErroneous()) {
        try {
            seenClasses = seenClasses.prepend(c);
            if (c.type.hasTag(CLASS)) {
                if (supertypes.nonEmpty()) {
                    scan(supertypes);
                }
                else {
                    ClassType ct = (ClassType)c.type;
                    if (ct.supertype_field == null ||
                            ct.interfaces_field == null) {
                        //not completed yet
                        partialCheck = true;
                        return;
                    }
                    checkSymbol(pos, ct.supertype_field.tsym);
                    for (Type intf : ct.interfaces_field) {
                        checkSymbol(pos, intf.tsym);
                    }
                }
                if (c.owner.kind == TYP) {
                    checkSymbol(pos, c.owner);
                }
            }
        } finally {
            seenClasses = seenClasses.tail;
        }
    }
}
 
Example 10
Source File: DocCommentParser.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
<T> T getFirst(List<T>... lists) {
    for (List<T> list: lists) {
        if (list.nonEmpty())
            return list.head;
    }
    return null;
}
 
Example 11
Source File: CRTable.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**  Visitor method: compute source positions for
 *   a list of catch clauses in try statements.
 */
public SourceRange cspCatchers(List<JCCatch> trees) {
    if ((trees == null) || !(trees.nonEmpty())) return null;
    SourceRange list_sr = new SourceRange();
    for (List<JCCatch> l = trees; l.nonEmpty(); l = l.tail) {
        list_sr.mergeWith(csp(l.head));
    }
    positions.put(trees, list_sr);
    return list_sr;
}
 
Example 12
Source File: BridgeHarness.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check that every bridge in the generated classfile has a matching bridge
 * annotation in the bridge map
 */
protected void checkBridges(JavaFileObject jfo) {
    try (InputStream is = jfo.openInputStream()) {
        ClassFile cf = ClassFile.read(is);
        System.err.println("checking: " + cf.getName());

        List<Bridge> bridgeList = bridgesMap.get(cf.getName());
        if (bridgeList == null) {
            //no bridges - nothing to check;
            bridgeList = List.nil();
        }

        for (Method m : cf.methods) {
            if (m.access_flags.is(AccessFlags.ACC_SYNTHETIC | AccessFlags.ACC_BRIDGE)) {
                //this is a bridge - see if there's a match in the bridge list
                Bridge match = null;
                for (Bridge b : bridgeList) {
                    if (b.value().equals(descriptor(m, cf.constant_pool))) {
                        match = b;
                        break;
                    }
                }
                if (match == null) {
                    error("No annotation for bridge method: " + descriptor(m, cf.constant_pool));
                } else {
                    bridgeList = drop(bridgeList, match);
                }
            }
        }
        if (bridgeList.nonEmpty()) {
            error("Redundant bridge annotation found: " + bridgeList.head.value());
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new Error("error reading " + jfo.toUri() +": " + e);
    }
}
 
Example 13
Source File: Attr.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/** Add any variables defined in stats to the switch scope. */
private static void addVars(List<JCStatement> stats, Scope switchScope) {
    for (;stats.nonEmpty(); stats = stats.tail) {
        JCTree stat = stats.head;
        if (stat.getTag() == JCTree.VARDEF)
            switchScope.enter(((JCVariableDecl) stat).sym);
    }
}
 
Example 14
Source File: JavacParser.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public JCExpression parseType(List<JCAnnotation> annotations) {
    JCExpression result = unannotatedType();

    if (annotations.nonEmpty()) {
        result = insertAnnotationsToMostInner(result, annotations, false);
    }

    return result;
}
 
Example 15
Source File: JavacParser.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public JCExpression parseType(List<JCAnnotation> annotations) {
    JCExpression result = unannotatedType();

    if (annotations.nonEmpty()) {
        result = insertAnnotationsToMostInner(result, annotations, false);
    }

    return result;
}
 
Example 16
Source File: JavacParser.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Inserts the annotations (and possibly a new array level)
 * to the left-most type in an array or nested type.
 *
 * When parsing a type like {@code @B Outer.Inner @A []}, the
 * {@code @A} annotation should target the array itself, while
 * {@code @B} targets the nested type {@code Outer}.
 *
 * Currently the parser parses the annotation first, then
 * the array, and then inserts the annotation to the left-most
 * nested type.
 *
 * When {@code createNewLevel} is true, then a new array
 * level is inserted as the most inner type, and have the
 * annotations target it.  This is useful in the case of
 * varargs, e.g. {@code String @A [] @B ...}, as the parser
 * first parses the type {@code String @A []} then inserts
 * a new array level with {@code @B} annotation.
 */
private JCExpression insertAnnotationsToMostInner(
        JCExpression type, List<JCAnnotation> annos,
        boolean createNewLevel) {
    int origEndPos = getEndPos(type);
    JCExpression mostInnerType = type;
    JCArrayTypeTree mostInnerArrayType = null;
    while (TreeInfo.typeIn(mostInnerType).hasTag(TYPEARRAY)) {
        mostInnerArrayType = (JCArrayTypeTree) TreeInfo.typeIn(mostInnerType);
        mostInnerType = mostInnerArrayType.elemtype;
    }

    if (createNewLevel) {
        mostInnerType = to(F.at(token.pos).TypeArray(mostInnerType));
    }

    JCExpression mostInnerTypeToReturn = mostInnerType;
    if (annos.nonEmpty()) {
        JCExpression lastToModify = mostInnerType;

        while (TreeInfo.typeIn(mostInnerType).hasTag(SELECT) ||
                TreeInfo.typeIn(mostInnerType).hasTag(TYPEAPPLY)) {
            while (TreeInfo.typeIn(mostInnerType).hasTag(SELECT)) {
                lastToModify = mostInnerType;
                mostInnerType = ((JCFieldAccess) TreeInfo.typeIn(mostInnerType)).getExpression();
            }
            while (TreeInfo.typeIn(mostInnerType).hasTag(TYPEAPPLY)) {
                lastToModify = mostInnerType;
                mostInnerType = ((JCTypeApply) TreeInfo.typeIn(mostInnerType)).clazz;
            }
        }

        mostInnerType = F.at(annos.head.pos).AnnotatedType(annos, mostInnerType);

        if (TreeInfo.typeIn(lastToModify).hasTag(TYPEAPPLY)) {
            ((JCTypeApply) TreeInfo.typeIn(lastToModify)).clazz = mostInnerType;
        } else if (TreeInfo.typeIn(lastToModify).hasTag(SELECT)) {
            ((JCFieldAccess) TreeInfo.typeIn(lastToModify)).selected = mostInnerType;
        } else {
            // We never saw a SELECT or TYPEAPPLY, return the annotated type.
            mostInnerTypeToReturn = mostInnerType;
        }
    }

    if (mostInnerArrayType == null) {
        return mostInnerTypeToReturn;
    } else {
        mostInnerArrayType.elemtype = mostInnerTypeToReturn;
        storeEnd(type, origEndPos);
        return type;
    }
}
 
Example 17
Source File: Check.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
  * Report warnings for potentially ambiguous method declarations. Two declarations
  * are potentially ambiguous if they feature two unrelated functional interface
  * in same argument position (in which case, a call site passing an implicit
  * lambda would be ambiguous).
  */
void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site,
        MethodSymbol msym1, MethodSymbol msym2) {
    if (msym1 != msym2 &&
            allowDefaultMethods &&
            lint.isEnabled(LintCategory.OVERLOADS) &&
            (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 &&
            (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) {
        Type mt1 = types.memberType(site, msym1);
        Type mt2 = types.memberType(site, msym2);
        //if both generic methods, adjust type variables
        if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
                types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
            mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
        }
        //expand varargs methods if needed
        int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
        List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
        List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
        //if arities don't match, exit
        if (args1.length() != args2.length()) return;
        boolean potentiallyAmbiguous = false;
        while (args1.nonEmpty() && args2.nonEmpty()) {
            Type s = args1.head;
            Type t = args2.head;
            if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
                if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
                        types.findDescriptorType(s).getParameterTypes().length() > 0 &&
                        types.findDescriptorType(s).getParameterTypes().length() ==
                        types.findDescriptorType(t).getParameterTypes().length()) {
                    potentiallyAmbiguous = true;
                } else {
                    break;
                }
            }
            args1 = args1.tail;
            args2 = args2.tail;
        }
        if (potentiallyAmbiguous) {
            //we found two incompatible functional interfaces with same arity
            //this means a call site passing an implicit lambda would be ambigiuous
            msym1.flags_field |= POTENTIALLY_AMBIGUOUS;
            msym2.flags_field |= POTENTIALLY_AMBIGUOUS;
            log.warning(LintCategory.OVERLOADS, pos, "potentially.ambiguous.overload",
                        msym1, msym1.location(),
                        msym2, msym2.location());
            return;
        }
    }
}
 
Example 18
Source File: Check.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private Type firstIncompatibleTypeArg(Type type) {
    List<Type> formals = type.tsym.type.allparams();
    List<Type> actuals = type.allparams();
    List<Type> args = type.getTypeArguments();
    List<Type> forms = type.tsym.type.getTypeArguments();
    ListBuffer<Type> bounds_buf = new ListBuffer<Type>();

    // For matching pairs of actual argument types `a' and
    // formal type parameters with declared bound `b' ...
    while (args.nonEmpty() && forms.nonEmpty()) {
        // exact type arguments needs to know their
        // bounds (for upper and lower bound
        // calculations).  So we create new bounds where
        // type-parameters are replaced with actuals argument types.
        bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
        args = args.tail;
        forms = forms.tail;
    }

    args = type.getTypeArguments();
    List<Type> tvars_cap = types.substBounds(formals,
                              formals,
                              types.capture(type).allparams());
    while (args.nonEmpty() && tvars_cap.nonEmpty()) {
        // Let the actual arguments know their bound
        args.head.withTypeVar((TypeVar)tvars_cap.head);
        args = args.tail;
        tvars_cap = tvars_cap.tail;
    }

    args = type.getTypeArguments();
    List<Type> bounds = bounds_buf.toList();

    while (args.nonEmpty() && bounds.nonEmpty()) {
        Type actual = args.head;
        if (!isTypeArgErroneous(actual) &&
                !bounds.head.isErroneous() &&
                !checkExtends(actual, bounds.head)) {
            return args.head;
        }
        args = args.tail;
        bounds = bounds.tail;
    }

    args = type.getTypeArguments();
    bounds = bounds_buf.toList();

    for (Type arg : types.capture(type).getTypeArguments()) {
        if (arg.hasTag(TYPEVAR) &&
                arg.getUpperBound().isErroneous() &&
                !bounds.head.isErroneous() &&
                !isTypeArgErroneous(args.head)) {
            return args.head;
        }
        bounds = bounds.tail;
        args = args.tail;
    }

    return null;
}
 
Example 19
Source File: SrcClassUtil.java    From manifold with Apache License 2.0 4 votes vote down vote up
private String typeNoAnnotations( Type type )
{
  if( isJava8() )
  {
    return type.toString();
  }

  StringBuilder sb = new StringBuilder();
  if( type instanceof Type.ClassType )
  {
    if( type.getEnclosingType().hasTag( CLASS ) &&
        ReflectUtil.field( type.tsym.owner, "kind" ).get() == ReflectUtil.field( "com.sun.tools.javac.code.Kinds$Kind", "TYP" ).getStatic() )
    {
      sb.append( typeNoAnnotations( type.getEnclosingType() ) );
      sb.append( "." );
      sb.append( ReflectUtil.method( type, "className", Symbol.class, boolean.class ).invoke( type.tsym, false ) );
    }
    else
    {
      sb.append( ReflectUtil.method( type, "className", Symbol.class, boolean.class ).invoke( type.tsym, true ) );
    }

    List<Type> typeArgs = type.getTypeArguments();
    if( typeArgs.nonEmpty() )
    {
      sb.append( '<' );
      for( int i = 0; i < typeArgs.size(); i++ )
      {
        if( i > 0 )
        {
          sb.append( ", " );
        }
        Type typeArg = typeArgs.get( i );
        sb.append( typeNoAnnotations( typeArg ) );
      }
      sb.append( ">" );
    }
  }
  else if( type instanceof Type.ArrayType )
  {
    sb.append( typeNoAnnotations( ((Type.ArrayType)type).getComponentType() ) ).append( "[]" );
  }
  else if( type instanceof Type.WildcardType )
  {
    Type.WildcardType wildcardType = (Type.WildcardType)type;
    BoundKind kind = wildcardType.kind;
    sb.append( kind.toString() );
    if( kind != BoundKind.UNBOUND )
    {
      sb.append( typeNoAnnotations( wildcardType.type ) );
    }
  }
  else
  {
    sb.append( type.toString() );
  }
  return sb.toString();
}
 
Example 20
Source File: MemberEnter.java    From java-n-IDE-for-Android with Apache License 2.0 3 votes vote down vote up
/** Generate call to superclass constructor. This is:
 *
 *    super(id_0, ..., id_n)
 *
 * or, if based == true
 *
 *    id_0.super(id_1,...,id_n)
 *
 *  where id_0, ..., id_n are the names of the given parameters.
 *
 *  @param make    The tree factory
 *  @param params  The parameters that need to be passed to super
 *  @param typarams  The type parameters that need to be passed to super
 *  @param based   Is first parameter a this$n?
 */
JCExpressionStatement SuperCall(TreeMaker make,
               List<Type> typarams,
               List<JCVariableDecl> params,
               boolean based) {
    JCExpression meth;
    if (based) {
        meth = make.Select(make.Ident(params.head), names._super);
        params = params.tail;
    } else {
        meth = make.Ident(names._super);
    }
    List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
    return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));
}