com.sun.tools.javac.code.Types Java Examples

The following examples show how to use com.sun.tools.javac.code.Types. 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: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
/** Expand a boxing or unboxing conversion if needed. */
<T extends JCTree> T boxUnboxIfNeeded( Types types, TreeMaker make, Names names, T tree, Type type) {
  boolean havePrimitive = tree.type.isPrimitive();
  if (havePrimitive == type.isPrimitive())
    return tree;
  if (havePrimitive) {
    Type unboxedTarget = types.unboxedType(type);
    if (!unboxedTarget.hasTag(NONE)) {
      if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
        tree.type = unboxedTarget.constType(tree.type.constValue());
      return (T)boxPrimitive(types, make, names, (JCExpression)tree, type);
    } else {
      tree = (T)boxPrimitive(types, make, names, (JCExpression)tree);
    }
  } else {
    tree = (T)unbox(types, make, names, (JCExpression)tree, type);
  }
  return tree;
}
 
Example #2
Source File: MakeLiteralTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
void run() throws Exception {
    Context context = new Context();
    JavacFileManager.preRegister(context);
    Symtab syms = Symtab.instance(context);
    maker = TreeMaker.instance(context);
    types = Types.instance(context);

    test("abc",                     CLASS,      syms.stringType,    "abc");
    test(Boolean.FALSE,             BOOLEAN,    syms.booleanType,   Integer.valueOf(0));
    test(Boolean.TRUE,              BOOLEAN,    syms.booleanType,   Integer.valueOf(1));
    test(Byte.valueOf((byte) 1),    BYTE,       syms.byteType,      Byte.valueOf((byte) 1));
    test(Character.valueOf('a'),    CHAR,       syms.charType,      Integer.valueOf('a'));
    test(Double.valueOf(1d),        DOUBLE,     syms.doubleType,    Double.valueOf(1d));
    test(Float.valueOf(1f),         FLOAT,      syms.floatType,     Float.valueOf(1f));
    test(Integer.valueOf(1),        INT,        syms.intType,       Integer.valueOf(1));
    test(Long.valueOf(1),           LONG,       syms.longType,      Long.valueOf(1));
    test(Short.valueOf((short) 1),  SHORT,      syms.shortType,     Short.valueOf((short) 1));

    if (errors > 0)
        throw new Exception(errors + " errors found");
}
 
Example #3
Source File: Enter.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
protected Enter(Context context) {
    context.put(enterKey, this);

    log = Log.instance(context);
    reader = ClassReader.instance(context);
    make = TreeMaker.instance(context);
    syms = Symtab.instance(context);
    chk = Check.instance(context);
    memberEnter = MemberEnter.instance(context);
    types = Types.instance(context);
    annotate = Annotate.instance(context);
    lint = Lint.instance(context);
    names = Names.instance(context);

    predefClassDef = make.ClassDef(
        make.Modifiers(PUBLIC),
        syms.predefClass.name, null, null, null, null);
    predefClassDef.sym = syms.predefClass;
    todo = Todo.instance(context);
    fileManager = context.get(JavaFileManager.class);

    Options options = Options.instance(context);
    pkginfoOpt = PkgInfo.get(options);
}
 
Example #4
Source File: AccessPath.java    From NullAway with MIT License 6 votes vote down vote up
private static boolean isMapMethod(
    Symbol.MethodSymbol symbol, Types types, String methodName, int numParams) {
  if (!symbol.getSimpleName().toString().equals(methodName)) {
    return false;
  }
  if (symbol.getParameters().size() != numParams) {
    return false;
  }
  Symbol owner = symbol.owner;
  if (owner.getQualifiedName().toString().equals("java.util.Map")) {
    return true;
  }
  com.sun.tools.javac.util.List<Type> supertypes = types.closure(owner.type);
  for (Type t : supertypes) {
    if (t.asElement().getQualifiedName().toString().equals("java.util.Map")) {
      return true;
    }
  }
  return false;
}
 
Example #5
Source File: LambdaToMethod.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private LambdaToMethod(Context context) {
    context.put(unlambdaKey, this);
    diags = JCDiagnostic.Factory.instance(context);
    log = Log.instance(context);
    lower = Lower.instance(context);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    rs = Resolve.instance(context);
    make = TreeMaker.instance(context);
    types = Types.instance(context);
    transTypes = TransTypes.instance(context);
    analyzer = new LambdaAnalyzerPreprocessor();
    Options options = Options.instance(context);
    dumpLambdaToMethodStats = options.isSet("dumpLambdaToMethodStats");
    attr = Attr.instance(context);
    forceSerializable = options.isSet("forceSerializable");
}
 
Example #6
Source File: ClassWriter.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static boolean isSameType(Type t1, Type t2, Types types) {
    if (t1 == null) { return t2 == null; }
    if (t2 == null) { return false; }

    if (isInt(t1) && isInt(t2)) { return true; }

    if (t1.hasTag(UNINITIALIZED_THIS)) {
        return t2.hasTag(UNINITIALIZED_THIS);
    } else if (t1.hasTag(UNINITIALIZED_OBJECT)) {
        if (t2.hasTag(UNINITIALIZED_OBJECT)) {
            return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset;
        } else {
            return false;
        }
    } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) {
        return false;
    }

    return types.isSameType(t1, t2);
}
 
Example #7
Source File: LambdaToMethod.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private LambdaToMethod(Context context) {
    context.put(unlambdaKey, this);
    diags = JCDiagnostic.Factory.instance(context);
    log = Log.instance(context);
    lower = Lower.instance(context);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    rs = Resolve.instance(context);
    make = TreeMaker.instance(context);
    types = Types.instance(context);
    transTypes = TransTypes.instance(context);
    analyzer = new LambdaAnalyzerPreprocessor();
    Options options = Options.instance(context);
    dumpLambdaToMethodStats = options.isSet("dumpLambdaToMethodStats");
    attr = Attr.instance(context);
    forceSerializable = options.isSet("forceSerializable");
}
 
Example #8
Source File: DynamicProxyFactory.java    From manifold with Apache License 2.0 6 votes vote down vote up
private static boolean hasCallHandlerFromExtension( Class rootClass )
{
  Boolean isCallHandler = ICALL_HANDLER_MAP.get( rootClass );
  if( isCallHandler != null )
  {
    return isCallHandler;
  }

  String fqn = rootClass.getCanonicalName();
  BasicJavacTask javacTask = RuntimeManifoldHost.get().getJavaParser().getJavacTask();
  Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> classSymbol = ClassSymbols.instance( RuntimeManifoldHost.get().getSingleModule() ).getClassSymbol( javacTask, fqn );
  Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> callHandlerSymbol = ClassSymbols.instance( RuntimeManifoldHost.get().getSingleModule() ).getClassSymbol( javacTask, ICallHandler.class.getCanonicalName() );
  if( Types.instance( javacTask.getContext() ).isAssignable( classSymbol.getFirst().asType(), callHandlerSymbol.getFirst().asType() ) )
  {
    // Nominally implements ICallHandler
    isCallHandler = true;
  }
  else
  {
    // Structurally implements ICallHandler
    isCallHandler = hasCallMethod( javacTask, classSymbol.getFirst() );
  }
  ICALL_HANDLER_MAP.put( rootClass, isCallHandler );
  return isCallHandler;
}
 
Example #9
Source File: LambdaToMethod.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private LambdaToMethod(Context context) {
    context.put(unlambdaKey, this);
    diags = JCDiagnostic.Factory.instance(context);
    log = Log.instance(context);
    lower = Lower.instance(context);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    rs = Resolve.instance(context);
    make = TreeMaker.instance(context);
    types = Types.instance(context);
    transTypes = TransTypes.instance(context);
    analyzer = new LambdaAnalyzerPreprocessor();
    Options options = Options.instance(context);
    dumpLambdaToMethodStats = options.isSet("dumpLambdaToMethodStats");
    attr = Attr.instance(context);
    forceSerializable = options.isSet("forceSerializable");
}
 
Example #10
Source File: TestInvokeDynamic.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
Object getValue(Symtab syms, Names names, Types types) {
    switch (this) {
        case STRING:
        case INTEGER:
        case LONG:
        case FLOAT:
        case DOUBLE:
            return value;
        case CLASS:
            return syms.stringType.tsym;
        case METHOD_HANDLE:
            return new Pool.MethodHandle(REF_invokeVirtual,
                    syms.arrayCloneMethod, types);
        case METHOD_TYPE:
            return syms.arrayCloneMethod.type;
        default:
            throw new AssertionError();
    }
}
 
Example #11
Source File: OptionalEmptinessHandler.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public NullnessHint onDataflowVisitMethodInvocation(
    MethodInvocationNode node,
    Types types,
    Context context,
    AccessPathNullnessPropagation.SubNodeValues inputs,
    AccessPathNullnessPropagation.Updates thenUpdates,
    AccessPathNullnessPropagation.Updates elseUpdates,
    AccessPathNullnessPropagation.Updates bothUpdates) {
  Symbol.MethodSymbol symbol = ASTHelpers.getSymbol(node.getTree());

  if (optionalIsPresentCall(symbol, types)) {
    updateNonNullAPsForOptionalContent(thenUpdates, node.getTarget().getReceiver());
  } else if (config.handleTestAssertionLibraries() && methodNameUtil.isMethodIsTrue(symbol)) {
    // we check for instance of AssertThat(optionalFoo.isPresent()).isTrue()
    updateIfAssertIsPresentTrueOnOptional(node, types, bothUpdates);
  }
  return NullnessHint.UNKNOWN;
}
 
Example #12
Source File: Pool.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Place an object in the pool, unless it is already there.
 *  If object is a symbol also enter its owner unless the owner is a
 *  package.  Return the object's index in the pool.
 */
public int put(Object value) {
    value = makePoolValue(value);
    Assert.check(!(value instanceof Type.TypeVar));
    Assert.check(!(value instanceof Types.UniqueType &&
                   ((UniqueType) value).type instanceof Type.TypeVar));
    Integer index = indices.get(value);
    if (index == null) {
        index = pp;
        indices.put(value, index);
        pool = ArrayUtils.ensureCapacity(pool, pp);
        pool[pp++] = value;
        if (value instanceof Long || value instanceof Double) {
            pool = ArrayUtils.ensureCapacity(pool, pp);
            pool[pp++] = null;
        }
    }
    return index.intValue();
}
 
Example #13
Source File: LambdaToMethod.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private LambdaToMethod(Context context) {
    context.put(unlambdaKey, this);
    diags = JCDiagnostic.Factory.instance(context);
    log = Log.instance(context);
    lower = Lower.instance(context);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    rs = Resolve.instance(context);
    make = TreeMaker.instance(context);
    types = Types.instance(context);
    transTypes = TransTypes.instance(context);
    analyzer = new LambdaAnalyzerPreprocessor();
    Options options = Options.instance(context);
    dumpLambdaToMethodStats = options.isSet("dumpLambdaToMethodStats");
    attr = Attr.instance(context);
    forceSerializable = options.isSet("forceSerializable");
}
 
Example #14
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
/** Unbox an object to a primitive value. */
private JCExpression unbox( Types types, TreeMaker make, Names names, JCExpression tree, Type primitive ) {
  Type unboxedType = types.unboxedType(tree.type);
  if (unboxedType.hasTag(NONE)) {
    unboxedType = primitive;
    if (!unboxedType.isPrimitive())
      throw new AssertionError(unboxedType);
    make.at(tree.pos());
    tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
  } else {
    // There must be a conversion from unboxedType to primitive.
    if (!types.isSubtype(unboxedType, primitive))
      throw new AssertionError(tree);
  }
  make.at(tree.pos());
  Symbol valueSym = resolveMethod(tree.pos(),
    unboxedType.tsym.name.append(names.Value), // x.intValue()
    tree.type,
    List.<Type>nil());
  return make.App(make.Select(tree, valueSym));
}
 
Example #15
Source File: TreeConverter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private TreeNode convertFunctionalExpression(
    JCFunctionalExpression node, TreePath parent, FunctionalExpression newNode) {
  List<? extends TypeMirror> targets = getTargets(node, parent);
  for (TypeMirror type : targets) {
    newNode.addTargetType(type);
  }
  Types types =
      Types.instance(((com.sun.tools.javac.api.BasicJavacTask) env.task()).getContext());
  return newNode
      .setTypeMirror(targets.iterator().next())
      .setDescriptor(
          new ExecutablePair(
              (ExecutableElement) types
                  .findDescriptorSymbol(((com.sun.tools.javac.code.Type) targets.get(0)).tsym),
              (ExecutableType) node.getDescriptorType(types)));
}
 
Example #16
Source File: LambdaToMethod.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private LambdaToMethod(Context context) {
    context.put(unlambdaKey, this);
    diags = JCDiagnostic.Factory.instance(context);
    log = Log.instance(context);
    lower = Lower.instance(context);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    rs = Resolve.instance(context);
    make = TreeMaker.instance(context);
    types = Types.instance(context);
    transTypes = TransTypes.instance(context);
    analyzer = new LambdaAnalyzerPreprocessor();
    Options options = Options.instance(context);
    dumpLambdaToMethodStats = options.isSet("dumpLambdaToMethodStats");
    attr = Attr.instance(context);
}
 
Example #17
Source File: TypeHarness.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
protected TypeHarness() {
    Context ctx = new Context();
    JavacFileManager.preRegister(ctx);
    types = Types.instance(ctx);
    chk = Check.instance(ctx);
    predef = Symtab.instance(ctx);
    names = Names.instance(ctx);
    fac = new Factory();
}
 
Example #18
Source File: Pool.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Object[] getUniqueTypeArray(Object[] objects, Types types) {
    Object[] result = new Object[objects.length];
    for (int i = 0; i < objects.length; i++) {
        if (objects[i] instanceof Type) {
            result[i] = new UniqueType((Type)objects[i], types);
        } else {
            result[i] = objects[i];
        }
    }
    return result;
}
 
Example #19
Source File: ClassReader.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Construct a new class reader. */
protected ClassReader(Context context) {
    context.put(classReaderKey, this);
    annotate = Annotate.instance(context);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    types = Types.instance(context);
    fileManager = context.get(JavaFileManager.class);
    if (fileManager == null)
        throw new AssertionError("FileManager initialization error");
    diagFactory = JCDiagnostic.Factory.instance(context);

    log = Log.instance(context);

    Options options = Options.instance(context);
    verbose         = options.isSet(Option.VERBOSE);

    Source source = Source.instance(context);
    allowSimplifiedVarargs = source.allowSimplifiedVarargs();
    allowModules     = source.allowModules();

    saveParameterNames = options.isSet(PARAMETERS);

    profile = Profile.instance(context);

    typevars = WriteableScope.create(syms.noSymbol);

    lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);

    initAttributeReaders();
}
 
Example #20
Source File: StringConcat.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected StringConcat(Context context) {
    context.put(concatKey, this);
    gen = Gen.instance(context);
    syms = Symtab.instance(context);
    types = Types.instance(context);
    names = Names.instance(context);
    make = TreeMaker.instance(context);
    rs = Resolve.instance(context);
    sbAppends = new HashMap<>();
}
 
Example #21
Source File: TypeHarness.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected TypeHarness() {
    Context ctx = new Context();
    JavacFileManager.preRegister(ctx);
    types = Types.instance(ctx);
    chk = Check.instance(ctx);
    predef = Symtab.instance(ctx);
    names = Names.instance(ctx);
    fac = new Factory();
}
 
Example #22
Source File: Pool.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/** Construct a pool with given number of elements and element array.
 */
public Pool(int pp, Object[] pool, Types types) {
    this.pp = pp;
    this.pool = pool;
    this.types = types;
    this.indices = new HashMap<Object,Integer>(pool.length);
    for (int i = 1; i < pp; i++) {
        if (pool[i] != null) indices.put(pool[i], i);
    }
}
 
Example #23
Source File: AccessPathNullnessPropagation.java    From NullAway with MIT License 5 votes vote down vote up
AccessPathNullnessPropagation(
    Nullness defaultAssumption,
    Predicate<MethodInvocationNode> methodReturnsNonNull,
    Context context,
    Config config,
    Handler handler) {
  this.defaultAssumption = defaultAssumption;
  this.methodReturnsNonNull = methodReturnsNonNull;
  this.context = context;
  this.types = Types.instance(context);
  this.config = config;
  this.handler = handler;
}
 
Example #24
Source File: AccessPath.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * Gets corresponding AccessPath for node, if it exists. Handles calls to <code>Map.get()
 * </code>
 *
 * @param node AST node
 * @param types javac {@link Types}
 * @return corresponding AccessPath if it exists; <code>null</code> otherwise
 */
@Nullable
public static AccessPath getAccessPathForNodeWithMapGet(Node node, @Nullable Types types) {
  if (node instanceof LocalVariableNode) {
    return fromLocal((LocalVariableNode) node);
  } else if (node instanceof FieldAccessNode) {
    return fromFieldAccess((FieldAccessNode) node);
  } else if (node instanceof MethodInvocationNode) {
    return fromMethodCall((MethodInvocationNode) node, types);
  } else {
    return null;
  }
}
 
Example #25
Source File: NullabilityUtil.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * finds the corresponding functional interface method for a lambda expression or method reference
 *
 * @param tree the lambda expression or method reference
 * @return the functional interface method
 */
public static Symbol.MethodSymbol getFunctionalInterfaceMethod(ExpressionTree tree, Types types) {
  Preconditions.checkArgument(
      (tree instanceof LambdaExpressionTree) || (tree instanceof MemberReferenceTree));
  Type funcInterfaceType = ((JCTree.JCFunctionalExpression) tree).type;
  return (Symbol.MethodSymbol) types.findDescriptorSymbol(funcInterfaceType.tsym);
}
 
Example #26
Source File: Pool.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/** Construct a pool with given number of elements and element array.
 */
public Pool(int pp, Object[] pool, Types types) {
    this.pp = pp;
    this.pool = pool;
    this.types = types;
    this.indices = new HashMap<Object,Integer>(pool.length);
    for (int i = 1; i < pp; i++) {
        if (pool[i] != null) indices.put(pool[i], i);
    }
}
 
Example #27
Source File: TypeHarness.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
protected TypeHarness() {
    Context ctx = new Context();
    JavacFileManager.preRegister(ctx);
    types = Types.instance(ctx);
    chk = Check.instance(ctx);
    predef = Symtab.instance(ctx);
    names = Names.instance(ctx);
    fac = new Factory();
}
 
Example #28
Source File: ManAttr.java    From manifold with Apache License 2.0 5 votes vote down vote up
static boolean isAssignableWithGenerics( Types types, Type t1, Type t2 )
{
  if( t2 instanceof Type.TypeVar )
  {
    Type parameterizedParamType = types.asSuper( t1, t2.getUpperBound().tsym );
    return parameterizedParamType != null;
  }
  return false;
}
 
Example #29
Source File: ManAttr.java    From manifold with Apache License 2.0 5 votes vote down vote up
static Symbol.MethodSymbol resolveOperatorMethod( Types types, Tag tag, Type left, Type right )
{
  String opName = BINARY_OP_TO_NAME.get( tag );
  if( opName == null )
  {
    if( isComparableOperator( tag ) )
    {
      opName = COMPARE_TO_USING;
    }
    else
    {
      return null;
    }
  }

  if( left instanceof Type.TypeVar )
  {
    left = types.erasure( left );
  }

  if( !(left.tsym instanceof Symbol.ClassSymbol) )
  {
    return null;
  }

  int paramCount = opName.equals( COMPARE_TO_USING ) ? 2 : 1;
  Symbol.MethodSymbol methodSymbol = getMethodSymbol( types, left, right, opName, (Symbol.ClassSymbol)left.tsym, paramCount );
  if( methodSymbol == null && paramCount == 2 && !left.isPrimitive() && isRelationalOperator( tag ) )
  {
    // Support > >= < <= on any Comparable implementor
    methodSymbol = getMethodSymbol( types, left, right, COMPARE_TO, (Symbol.ClassSymbol)left.tsym, 1 );

  }
  return methodSymbol;
}
 
Example #30
Source File: RichDiagnosticFormatter.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
protected RichDiagnosticFormatter(Context context) {
    super((AbstractDiagnosticFormatter) Log.instance(context).getDiagnosticFormatter());
    setRichPrinter(new RichPrinter());
    this.syms = Symtab.instance(context);
    this.diags = JCDiagnostic.Factory.instance(context);
    this.types = Types.instance(context);
    this.messages = JavacMessages.instance(context);
    whereClauses = new LinkedHashMap<WhereClauseKind, Map<Type, JCDiagnostic>>();
    configuration = new RichConfiguration(Options.instance(context), formatter);
    for (WhereClauseKind kind : WhereClauseKind.values())
        whereClauses.put(kind, new LinkedHashMap<Type, JCDiagnostic>());
}