Java Code Examples for com.sun.tools.javac.code.Type#getTypeArguments()

The following examples show how to use com.sun.tools.javac.code.Type#getTypeArguments() . 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: JavacBinder.java    From manifold with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitClassType( Type.ClassType t, Type pt )
{
  if( _types.isSameType( t, pt ) )
  {
    return null;
  }

  List<Type> pt_params = pt.getTypeArguments();

  List<Type> t_params = t.getTypeArguments();
  for( int i = 0; i < t_params.size() && i < pt_params.size(); i++ )
  {
    fetchTypeVars( t_params.get( i ), pt_params.get( i ), _map );
  }

  return null;
}
 
Example 2
Source File: ClassReader.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Enter type variables of this classtype and all enclosing ones in
 *  `typevars'.
 */
protected void enterTypevars(Symbol sym, Type t) {
    if (t.getEnclosingType() != null) {
        if (!t.getEnclosingType().hasTag(TypeTag.NONE)) {
            enterTypevars(sym.owner, t.getEnclosingType());
        }
    } else if (sym.kind == MTH && !sym.isStatic()) {
        enterTypevars(sym.owner, sym.owner.type);
    }
    for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail) {
        typevars.enter(xs.head.tsym);
    }
}
 
Example 3
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Check that type is a class or interface type.
 *  @param pos           Position to be used for error reporting.
 *  @param t             The type to be checked.
 *  @param noBounds    True if type bounds are illegal here.
 */
Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
    t = checkClassType(pos, t);
    if (noBounds && t.isParameterized()) {
        List<Type> args = t.getTypeArguments();
        while (args.nonEmpty()) {
            if (args.head.hasTag(WILDCARD))
                return typeTagError(pos,
                                    diags.fragment(Fragments.TypeReqExact),
                                    args.head);
            args = args.tail;
        }
    }
    return t;
}
 
Example 4
Source File: IsSameTypeWildcardTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void runTest() {
    List<String> imports = new ArrayList<>();
    imports.add("java.util.*");
    strToTypeFactory = new StrToTypeFactory(null, imports, null);

    Type listOfWildcard = strToTypeFactory.getType("List<?>");
    com.sun.tools.javac.util.List<Type> arguments = listOfWildcard.getTypeArguments();
    Assert.check(!javacTypes.isSameType(arguments.head, arguments.head),
            "if any argument is a wildcard then result must be false");
}
 
Example 5
Source File: ManTypes.java    From manifold with Apache License 2.0 5 votes vote down vote up
private boolean hasSelfType( Type type )
{
  for( Attribute.TypeCompound anno: type.getAnnotationMirrors() )
  {
    if( anno.type.toString().equals( SELF_TYPE_NAME ) )
    {
      return true;
    }
  }

  if( type instanceof Type.ArrayType )
  {
    return hasSelfType( ((Type.ArrayType)type).getComponentType() );
  }

  for( Type typeParam: type.getTypeArguments() )
  {
    if( hasSelfType( typeParam ) )
    {
      return true;
    }
  }

  if( type instanceof Type.IntersectionClassType )
  {
    for( Type compType: ((Type.IntersectionClassType)type).getComponents() )
    {
      if( hasSelfType( compType ) )
      {
        return true;
      }
    }
  }

  return false;
}
 
Example 6
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 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<>();

    // 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 7
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/** Return the first method in t2 that conflicts with a method from t1. */
private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
    for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
        Type st1 = null;
        if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
                (s1.flags() & SYNTHETIC) != 0) continue;
        Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
        if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
        for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
            if (s1 == s2) continue;
            if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
                    (s2.flags() & SYNTHETIC) != 0) continue;
            if (st1 == null) st1 = types.memberType(t1, s1);
            Type st2 = types.memberType(t2, s2);
            if (types.overrideEquivalent(st1, st2)) {
                List<Type> tvars1 = st1.getTypeArguments();
                List<Type> tvars2 = st2.getTypeArguments();
                Type rt1 = st1.getReturnType();
                Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
                boolean compat =
                    types.isSameType(rt1, rt2) ||
                    !rt1.isPrimitiveOrVoid() &&
                    !rt2.isPrimitiveOrVoid() &&
                    (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
                     types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
                     checkCommonOverriderIn(s1,s2,site);
                if (!compat) {
                    log.error(pos, Errors.TypesIncompatibleDiffRet(t1, t2, s2.name +
                            "(" + types.memberType(t2, s2).getParameterTypes() + ")"));
                    return s2;
                }
            } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
                    !checkCommonOverriderIn(s1, s2, site)) {
                log.error(pos, Errors.NameClashSameErasureNoOverride(
                        s1.name, types.memberType(site, s1).asMethodType().getParameterTypes(), s1.location(),
                        s2.name, types.memberType(site, s2).asMethodType().getParameterTypes(), s2.location()));
                return s2;
            }
        }
    }
    return null;
}
 
Example 8
Source File: Infer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Generate constraints from the generic method's return type. If the method
 * call occurs in a context where a type T is expected, use the expected
 * type to derive more constraints on the generic method inference variables.
 */
Type generateReturnConstraints(JCTree tree, Attr.ResultInfo resultInfo,
        MethodType mt, InferenceContext inferenceContext) {
    InferenceContext rsInfoInfContext = resultInfo.checkContext.inferenceContext();
    Type from = mt.getReturnType();
    if (mt.getReturnType().containsAny(inferenceContext.inferencevars) &&
            rsInfoInfContext != emptyContext) {
        from = types.capture(from);
        //add synthetic captured ivars
        for (Type t : from.getTypeArguments()) {
            if (t.hasTag(TYPEVAR) && ((TypeVar)t).isCaptured()) {
                inferenceContext.addVar((TypeVar)t);
            }
        }
    }
    Type qtype = inferenceContext.asUndetVar(from);
    Type to = resultInfo.pt;

    if (qtype.hasTag(VOID)) {
        to = syms.voidType;
    } else if (to.hasTag(NONE)) {
        to = from.isPrimitive() ? from : syms.objectType;
    } else if (qtype.hasTag(UNDETVAR)) {
        if (needsEagerInstantiation((UndetVar)qtype, to, inferenceContext) &&
                (allowGraphInference || !to.isPrimitive())) {
            to = generateReferenceToTargetConstraint(tree, (UndetVar)qtype, to, resultInfo, inferenceContext);
        }
    } else if (rsInfoInfContext.free(resultInfo.pt)) {
        //propagation - cache captured vars
        qtype = inferenceContext.asUndetVar(rsInfoInfContext.cachedCapture(tree, from, !resultInfo.checkMode.updateTreeType()));
    }
    Assert.check(allowGraphInference || !rsInfoInfContext.free(to),
            "legacy inference engine cannot handle constraints on both sides of a subtyping assertion");
    //we need to skip capture?
    Warner retWarn = new Warner();
    if (!resultInfo.checkContext.compatible(qtype, rsInfoInfContext.asUndetVar(to), retWarn) ||
            //unchecked conversion is not allowed in source 7 mode
            (!allowGraphInference && retWarn.hasLint(Lint.LintCategory.UNCHECKED))) {
        throw inferenceException
                .setMessage("infer.no.conforming.instance.exists",
                inferenceContext.restvars(), mt.getReturnType(), to);
    }
    return from;
}
 
Example 9
Source File: Infer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
  * This method is used to infer a suitable target SAM in case the original
  * SAM type contains one or more wildcards. An inference process is applied
  * so that wildcard bounds, as well as explicit lambda/method ref parameters
  * (where applicable) are used to constraint the solution.
  */
public Type instantiateFunctionalInterface(DiagnosticPosition pos, Type funcInterface,
        List<Type> paramTypes, Check.CheckContext checkContext) {
    if (types.capture(funcInterface) == funcInterface) {
        //if capture doesn't change the type then return the target unchanged
        //(this means the target contains no wildcards!)
        return funcInterface;
    } else {
        Type formalInterface = funcInterface.tsym.type;
        InferenceContext funcInterfaceContext =
                new InferenceContext(this, funcInterface.tsym.type.getTypeArguments());

        Assert.check(paramTypes != null);
        //get constraints from explicit params (this is done by
        //checking that explicit param types are equal to the ones
        //in the functional interface descriptors)
        List<Type> descParameterTypes = types.findDescriptorType(formalInterface).getParameterTypes();
        if (descParameterTypes.size() != paramTypes.size()) {
            checkContext.report(pos, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
            return types.createErrorType(funcInterface);
        }
        for (Type p : descParameterTypes) {
            if (!types.isSameType(funcInterfaceContext.asUndetVar(p), paramTypes.head)) {
                checkContext.report(pos, diags.fragment(Fragments.NoSuitableFunctionalIntfInst(funcInterface)));
                return types.createErrorType(funcInterface);
            }
            paramTypes = paramTypes.tail;
        }

        List<Type> actualTypeargs = funcInterface.getTypeArguments();
        for (Type t : funcInterfaceContext.undetvars) {
            UndetVar uv = (UndetVar)t;
            Optional<Type> inst = StreamSupport.stream(uv.getBounds(InferenceBound.EQ))
                    .filter(b -> !b.containsAny(formalInterface.getTypeArguments())).findFirst();
            uv.setInst(inst.orElse(actualTypeargs.head));
            actualTypeargs = actualTypeargs.tail;
        }

        Type owntype = funcInterfaceContext.asInstType(formalInterface);
        if (!chk.checkValidGenericType(owntype)) {
            //if the inferred functional interface type is not well-formed,
            //or if it's not a subtype of the original target, issue an error
            checkContext.report(pos, diags.fragment(Fragments.NoSuitableFunctionalIntfInst(funcInterface)));
        }
        //propagate constraints as per JLS 18.2.1
        checkContext.compatible(owntype, funcInterface, types.noWarnings);
        return owntype;
    }
}
 
Example 10
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 11
Source File: JavacResolution.java    From EasyMPermission with MIT License 4 votes vote down vote up
private static JCExpression typeToJCTree0(Type type, JavacAST ast, boolean allowCompound, boolean allowVoid) throws TypeNotConvertibleException {
	// NB: There's such a thing as maker.Type(type), but this doesn't work very well; it screws up anonymous classes, captures, and adds an extra prefix dot for some reason too.
	//  -- so we write our own take on that here.
	
	JavacTreeMaker maker = ast.getTreeMaker();
	
	if (CTC_BOT.equals(typeTag(type))) return createJavaLangObject(ast);
	if (CTC_VOID.equals(typeTag(type))) return allowVoid ? primitiveToJCTree(type.getKind(), maker) : createJavaLangObject(ast);
	if (type.isPrimitive()) return primitiveToJCTree(type.getKind(), maker);
	if (type.isErroneous()) throw new TypeNotConvertibleException("Type cannot be resolved");
	
	TypeSymbol symbol = type.asElement();
	List<Type> generics = type.getTypeArguments();
	
	JCExpression replacement = null;
	
	if (symbol == null) throw new TypeNotConvertibleException("Null or compound type");
	
	if (symbol.name.length() == 0) {
		// Anonymous inner class
		if (type instanceof ClassType) {
			List<Type> ifaces = ((ClassType) type).interfaces_field;
			Type supertype = ((ClassType) type).supertype_field;
			if (ifaces != null && ifaces.length() == 1) {
				return typeToJCTree(ifaces.get(0), ast, allowCompound, allowVoid);
			}
			if (supertype != null) return typeToJCTree(supertype, ast, allowCompound, allowVoid);
		}
		throw new TypeNotConvertibleException("Anonymous inner class");
	}
	
	if (type instanceof CapturedType || type instanceof WildcardType) {
		Type lower, upper;
		if (type instanceof WildcardType) {
			upper = ((WildcardType)type).getExtendsBound();
			lower = ((WildcardType)type).getSuperBound();
		} else {
			lower = type.getLowerBound();
			upper = type.getUpperBound();
		}
		if (allowCompound) {
			if (lower == null || CTC_BOT.equals(typeTag(lower))) {
				if (upper == null || upper.toString().equals("java.lang.Object")) {
					return maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null);
				}
				if (upper.getTypeArguments().contains(type)) {
					return maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null);
				}
				return maker.Wildcard(maker.TypeBoundKind(BoundKind.EXTENDS), typeToJCTree(upper, ast, false, false));
			} else {
				return maker.Wildcard(maker.TypeBoundKind(BoundKind.SUPER), typeToJCTree(lower, ast, false, false));
			}
		}
		if (upper != null) {
			if (upper.getTypeArguments().contains(type)) {
				return maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null);
			}
			return typeToJCTree(upper, ast, allowCompound, allowVoid);
		}
		
		return createJavaLangObject(ast);
	}
	
	String qName;
	if (symbol.isLocal()) {
		qName = symbol.getSimpleName().toString();
	} else if (symbol.type != null && symbol.type.getEnclosingType() != null && typeTag(symbol.type.getEnclosingType()).equals(typeTag("CLASS"))) {
		replacement = typeToJCTree0(type.getEnclosingType(), ast, false, false);
		qName = symbol.getSimpleName().toString();
	} else {
		qName = symbol.getQualifiedName().toString();
	}
	
	if (qName.isEmpty()) throw new TypeNotConvertibleException("unknown type");
	if (qName.startsWith("<")) throw new TypeNotConvertibleException(qName);
	String[] baseNames = qName.split("\\.");
	int i = 0;
	
	if (replacement == null) {
		replacement = maker.Ident(ast.toName(baseNames[0]));
		i = 1;
	}
	for (; i < baseNames.length; i++) {
		replacement = maker.Select(replacement, ast.toName(baseNames[i]));
	}
	
	return genericsToJCTreeNodes(generics, ast, replacement);
}
 
Example 12
Source File: ASTPathCriterion.java    From annotation-tools with MIT License 4 votes vote down vote up
private boolean checkReceiverType(int i, Type t) {
    if (t == null) { return false; }
    while (++i < astPath.size()) {
        ASTPath.ASTEntry entry = astPath.get(i);
        switch (entry.getTreeKind()) {
        case ANNOTATED_TYPE:
          break;
        case ARRAY_TYPE:
          if (t.getKind() != TypeKind.ARRAY) { return false; }
          t = ((Type.ArrayType) t).getComponentType();
          break;
        case MEMBER_SELECT:
          // TODO
          break;
        case PARAMETERIZED_TYPE:
          if (entry.childSelectorIs(ASTPath.TYPE_PARAMETER)) {
            if (!t.isParameterized()) { return false; }
            List<Type> args = t.getTypeArguments();
            int a = entry.getArgument();
            if (a >= args.size()) { return false; }
            t = args.get(a);
          } // else TYPE -- stay?
          break;
        case TYPE_PARAMETER:
          if (t.getKind() != TypeKind.WILDCARD) { return false; }
          t = t.getLowerBound();
          break;
        case EXTENDS_WILDCARD:
          if (t.getKind() != TypeKind.WILDCARD) { return false; }
          t = ((Type.WildcardType) t).getExtendsBound();
          break;
        case SUPER_WILDCARD:
          if (t.getKind() != TypeKind.WILDCARD) { return false; }
          t = ((Type.WildcardType) t).getSuperBound();
          break;
        case UNBOUNDED_WILDCARD:
          if (t.getKind() != TypeKind.WILDCARD) { return false; }
          t = t.getLowerBound();
          break;
        default:
          return false;
        }
        if (t == null) { return false; }
    }
    return true;
}