Java Code Examples for com.sun.tools.javac.code.Symbol#ClassSymbol

The following examples show how to use com.sun.tools.javac.code.Symbol#ClassSymbol . 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: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
private boolean isExcludedClass(Symbol.ClassSymbol classSymbol) {
  String className = classSymbol.getQualifiedName().toString();
  if (config.isExcludedClass(className)) {
    return true;
  }
  if (!config.fromAnnotatedPackage(classSymbol)) {
    return true;
  }
  // check annotations
  ImmutableSet<String> excludedClassAnnotations = config.getExcludedClassAnnotations();
  return classSymbol
      .getAnnotationMirrors()
      .stream()
      .map(anno -> anno.getAnnotationType().toString())
      .anyMatch(excludedClassAnnotations::contains);
}
 
Example 2
Source File: SrcClassUtil.java    From manifold with Apache License 2.0 6 votes vote down vote up
private Symbol.MethodSymbol findConstructor( IModule module, String fqn, BasicJavacTask javacTask )
{
  manifold.rt.api.util.Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> classSymbol = ClassSymbols.instance( module ).getClassSymbol( javacTask, fqn );
  Symbol.ClassSymbol cs = classSymbol.getFirst();
  Symbol.MethodSymbol ctor = null;
  for( Symbol sym: cs.getEnclosedElements() )
  {
    if( sym instanceof Symbol.MethodSymbol && sym.flatName().toString().equals( "<init>" ) )
    {
      if( ctor == null )
      {
        ctor = (Symbol.MethodSymbol)sym;
      }
      else
      {
        ctor = mostAccessible( ctor, (Symbol.MethodSymbol)sym );
      }
      if( Modifier.isPublic( (int)ctor.flags() ) )
      {
        return ctor;
      }
    }
  }
  return ctor;
}
 
Example 3
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 4
Source File: AccessPathNullnessPropagation.java    From NullAway with MIT License 6 votes vote down vote up
@Nullable
private ClassTree findEnclosingLocalOrAnonymousClass(ClassTree classTree) {
  Symbol.ClassSymbol symbol = ASTHelpers.getSymbol(classTree);
  // we need this while loop since we can have a NestingKind.NESTED class (i.e., a nested
  // class declared at the top-level within its enclosing class) nested (possibly deeply)
  // within a NestingKind.ANONYMOUS or NestingKind.LOCAL class
  while (symbol.getNestingKind().isNested()) {
    if (symbol.getNestingKind().equals(NestingKind.ANONYMOUS)
        || symbol.getNestingKind().equals(NestingKind.LOCAL)) {
      return Trees.instance(JavacProcessingEnvironment.instance(context)).getTree(symbol);
    } else {
      // symbol.owner is the enclosing element, which could be a class or a method.
      // if it's a class, the enclClass() method will (surprisingly) return the class itself,
      // so this works
      symbol = symbol.owner.enclClass();
    }
  }
  return null;
}
 
Example 5
Source File: ApacheThriftIsSetHandler.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public void onMatchTopLevelClass(
    NullAway analysis, ClassTree tree, VisitorState state, Symbol.ClassSymbol classSymbol) {
  if (tbaseType == null) {
    tbaseType =
        Optional.ofNullable(state.getTypeFromString(TBASE_NAME)).map(state.getTypes()::erasure);
  }
}
 
Example 6
Source File: BaseProcessor.java    From WMRouter with Apache License 2.0 5 votes vote down vote up
/**
 * 创建Interceptors。格式:<code>, new Interceptor1(), new Interceptor2()</code>
 */
public CodeBlock buildInterceptors(List<? extends TypeMirror> interceptors) {
    CodeBlock.Builder b = CodeBlock.builder();
    if (interceptors != null && interceptors.size() > 0) {
        for (TypeMirror type : interceptors) {
            if (type instanceof Type.ClassType) {
                Symbol.TypeSymbol e = ((Type.ClassType) type).asElement();
                if (e instanceof Symbol.ClassSymbol && isInterceptor(e)) {
                    b.add(", new $T()", e);
                }
            }
        }
    }
    return b.build();
}
 
Example 7
Source File: BaseProcessor.java    From vertx-docgen with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve the coordinate of the type element, this method returns either:
 * <ul>
 * <li>a {@link io.vertx.docgen.Coordinate} object, the coordinate object can have null fields</li>
 * <li>{@code null} : the current element is being compiled, which likely means create a local link</li>
 * </ul>
 *
 * @param typeElt the type element to resolve
 * @return the resolved coordinate object or null if the element is locally compiled
 */
private Coordinate resolveCoordinate(TypeElement typeElt) {
  try {
    Symbol.ClassSymbol cs = (Symbol.ClassSymbol) typeElt;
    if (cs.sourcefile != null && getURL(cs.sourcefile) != null) {
      // .java source we can link locally
      return null;
    }
    if (cs.classfile != null) {
      JavaFileObject cf = cs.classfile;
      URL classURL = getURL(cf);
      if (classURL != null && classURL.getFile().endsWith(".class")) {
        URL manifestURL = new URL(classURL.toString().substring(0, classURL.toString().length() - (typeElt.getQualifiedName().toString().length() + 6)) + "META-INF/MANIFEST.MF");
        InputStream manifestIs = manifestURL.openStream();
        if (manifestIs != null) {
          Manifest manifest = new Manifest(manifestIs);
          Attributes attributes = manifest.getMainAttributes();
          String groupId = attributes.getValue(new Attributes.Name("Maven-Group-Id"));
          String artifactId = attributes.getValue(new Attributes.Name("Maven-Artifact-Id"));
          String version = attributes.getValue(new Attributes.Name("Maven-Version"));
          return new Coordinate(groupId, artifactId, version);
        }
      }
    }
  } catch (Exception ignore) {
    //
  }
  return new Coordinate(null, null, null);
}
 
Example 8
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
private boolean isTreatmentGroupEnum(Symbol.ClassSymbol enumSym) {
  // Filter out some generic names, like CONTROL to make sure we don't match the wrong
  // TreatmentGroup
  if (COMMON_GROUP_NAMES.contains(treatmentGroup)) {
    return false;
  }
  for (Symbol fsym : enumSym.getEnclosedElements()) {
    if (fsym.getKind().equals(ElementKind.ENUM_CONSTANT)
        && fsym.name.toString().toLowerCase().equals(treatmentGroup)) {
      return true;
    }
  }
  return false;
}
 
Example 9
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * @param entities relevant entities from class
 * @param notInitializedInConstructors those fields not initialized in some constructor
 * @param state visitor state
 * @return those fields from notInitializedInConstructors that are not initialized in any
 *     initializer method
 */
private Set<Symbol> notAssignedInAnyInitializer(
    FieldInitEntities entities, Set<Symbol> notInitializedInConstructors, VisitorState state) {
  Trees trees = getTreesInstance(state);
  Symbol.ClassSymbol classSymbol = entities.classSymbol();
  ImmutableSet.Builder<Element> initInSomeInitializerBuilder = ImmutableSet.builder();
  for (MethodTree initMethodTree : entities.instanceInitializerMethods()) {
    if (initMethodTree.getBody() == null) {
      continue;
    }
    addInitializedFieldsForBlock(
        state,
        trees,
        classSymbol,
        initInSomeInitializerBuilder,
        initMethodTree.getBody(),
        new TreePath(state.getPath(), initMethodTree));
  }
  for (BlockTree block : entities.instanceInitializerBlocks()) {
    addInitializedFieldsForBlock(
        state,
        trees,
        classSymbol,
        initInSomeInitializerBuilder,
        block,
        new TreePath(state.getPath(), block));
  }
  Set<Symbol> result = new LinkedHashSet<>();
  ImmutableSet<Element> initInSomeInitializer = initInSomeInitializerBuilder.build();
  for (Symbol fieldSymbol : notInitializedInConstructors) {
    if (!initInSomeInitializer.contains(fieldSymbol)) {
      result.add(fieldSymbol);
    }
  }
  return result;
}
 
Example 10
Source File: VanillaPartialReparser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public BlockTree reattrMethodBody(Context context, Scope scope, MethodTree methodToReparse, BlockTree block) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Attr attr = Attr.instance(context);
//        assert ((JCTree.JCMethodDecl)methodToReparse).localEnv != null;
        JCTree.JCMethodDecl tree = (JCTree.JCMethodDecl) methodToReparse;
        final Names names = Names.instance(context);
        final Symtab syms = Symtab.instance(context);
        final TypeEnter typeEnter = TypeEnter.instance(context);
        final Log log = Log.instance(context);
        final TreeMaker make = TreeMaker.instance(context);
        final Env<AttrContext> env = ((JavacScope) scope).getEnv();//this is a copy anyway...
        final Symbol.ClassSymbol owner = env.enclClass.sym;
        if (tree.name == names.init && !owner.type.isErroneous() && owner.type != syms.objectType) {
            JCTree.JCBlock body = tree.body;
            if (body.stats.isEmpty() || !TreeInfo.isSelfCall(body.stats.head)) {
                body.stats = body.stats.
                prepend(make.at(body.pos).Exec(make.Apply(com.sun.tools.javac.util.List.nil(), make.Ident(names._super), com.sun.tools.javac.util.List.nil())));
            } else if ((env.enclClass.sym.flags() & Flags.ENUM) != 0 &&
                (tree.mods.flags & Flags.GENERATEDCONSTR) == 0 &&
                TreeInfo.isSuperCall(body.stats.head)) {
                // enum constructors are not allowed to call super
                // directly, so make sure there aren't any super calls
                // in enum constructors, except in the compiler
                // generated one.
                log.error(tree.body.stats.head.pos(),
                          new JCDiagnostic.Error("compiler",
                                    "call.to.super.not.allowed.in.enum.ctor",
                                    env.enclClass.sym));
                    }
        }
        attr.attribStat((JCTree.JCBlock)block, env);
        return block;
    }
 
Example 11
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void make$name( Symbol.ClassSymbol sym, StringBuilder sb )
{
  Symbol enclosingElement = sym.getEnclosingElement();
  if( enclosingElement instanceof Symbol.ClassSymbol )
  {
    make$name( (Symbol.ClassSymbol)enclosingElement, sb );
    sb.append( '$' ).append( sym.getSimpleName() );
  }
  else
  {
    sb.append( sym.getQualifiedName().toString() );
  }
}
 
Example 12
Source File: AbstractConfig.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public boolean fromAnnotatedPackage(Symbol.ClassSymbol symbol) {
  String className = symbol.getQualifiedName().toString();
  return annotatedPackages.matcher(className).matches()
      && !unannotatedSubPackages.matcher(className).matches()
      && (!treatGeneratedAsUnannotated
          || !ASTHelpers.hasDirectAnnotationWithSimpleName(symbol, "Generated"));
}
 
Example 13
Source File: ManClassWriter.java    From manifold with Apache License 2.0 5 votes vote down vote up
@Override
public void writeClassFile( OutputStream out, Symbol.ClassSymbol c ) throws StringOverflow, IOException, PoolOverflow
{
  JavaFileObject sourceFile = c.sourcefile;
  if( sourceFile instanceof ISelfCompiledFile && ((ISelfCompiledFile)sourceFile).isSelfCompile( c.getQualifiedName().toString() ) )
  {
    out.write( ((ISelfCompiledFile)sourceFile).compile( c.getQualifiedName().toString() ) );
  }
  else
  {
    super.writeClassFile( out, c );
  }
}
 
Example 14
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * A safe init method is an instance method that is either private or final (so no overriding is
 * possible)
 *
 * @param stmt the statement
 * @param enclosingClassSymbol symbol for enclosing constructor / initializer
 * @param state visitor state
 * @return element of safe init function if stmt invokes that function; null otherwise
 */
@Nullable
private Element getInvokeOfSafeInitMethod(
    StatementTree stmt, final Symbol.ClassSymbol enclosingClassSymbol, VisitorState state) {
  Matcher<ExpressionTree> invokeMatcher =
      (expressionTree, s) -> {
        if (!(expressionTree instanceof MethodInvocationTree)) {
          return false;
        }
        MethodInvocationTree methodInvocationTree = (MethodInvocationTree) expressionTree;
        Symbol.MethodSymbol symbol = ASTHelpers.getSymbol(methodInvocationTree);
        Set<Modifier> modifiers = symbol.getModifiers();
        Set<Modifier> classModifiers = enclosingClassSymbol.getModifiers();
        if ((symbol.isPrivate()
                || modifiers.contains(Modifier.FINAL)
                || classModifiers.contains(Modifier.FINAL))
            && !symbol.isStatic()
            && !modifiers.contains(Modifier.NATIVE)) {
          // check it's the same class (could be an issue with inner classes)
          if (ASTHelpers.enclosingClass(symbol).equals(enclosingClassSymbol)) {
            // make sure the receiver is 'this'
            ExpressionTree receiver = ASTHelpers.getReceiver(expressionTree);
            return receiver == null || isThisIdentifier(receiver);
          }
        }
        return false;
      };
  if (stmt.getKind().equals(EXPRESSION_STATEMENT)) {
    ExpressionTree expression = ((ExpressionStatementTree) stmt).getExpression();
    if (invokeMatcher.matches(expression, state)) {
      return ASTHelpers.getSymbol(expression);
    }
  }
  return null;
}
 
Example 15
Source File: JavacBinder.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Symbol.MethodSymbol resolveBinderMethod( String name, Type left, Type right )
{
  if( !(left.tsym instanceof Symbol.ClassSymbol) )
  {
    return null;
  }

  return ManAttr.getMethodSymbol( _types, left, right, name, (Symbol.ClassSymbol)left.tsym, 1 );
}
 
Example 16
Source File: ClassSymbols.java    From manifold with Apache License 2.0 4 votes vote down vote up
public Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> getClassSymbol( BasicJavacTask javacTask, String fqn )
{
  return getClassSymbol( javacTask, (TypeProcessor)null, fqn );
}
 
Example 17
Source File: SrcClassUtil.java    From manifold with Apache License 2.0 4 votes vote down vote up
public SrcClass makeStub( String fqn, Symbol.ClassSymbol classSymbol, CompilationUnitTree compilationUnit, BasicJavacTask javacTask, IModule module, JavaFileManager.Location location, DiagnosticListener<JavaFileObject> errorHandler,
                          boolean withMembers )
{
  return makeSrcClass( fqn, null, classSymbol, compilationUnit, javacTask, module, location, errorHandler, withMembers );
}
 
Example 18
Source File: ClassSymbols.java    From manifold with Apache License 2.0 4 votes vote down vote up
public Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> getClassSymbol( BasicJavacTask javacTask, Object moduleSymbol, String fqn )
{
  return getClassSymbol( javacTask.getContext(), moduleSymbol, fqn );
}
 
Example 19
Source File: NullAway.java    From NullAway with MIT License 4 votes vote down vote up
private FieldInitEntities collectEntities(ClassTree tree, VisitorState state) {
  Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol(tree);
  Set<Symbol> nonnullInstanceFields = new LinkedHashSet<>();
  Set<Symbol> nonnullStaticFields = new LinkedHashSet<>();
  List<BlockTree> instanceInitializerBlocks = new ArrayList<>();
  List<BlockTree> staticInitializerBlocks = new ArrayList<>();
  Set<MethodTree> constructors = new LinkedHashSet<>();
  Set<MethodTree> instanceInitializerMethods = new LinkedHashSet<>();
  Set<MethodTree> staticInitializerMethods = new LinkedHashSet<>();

  // we assume getMembers() returns members in the same order as the declarations
  for (Tree memberTree : tree.getMembers()) {
    switch (memberTree.getKind()) {
      case METHOD:
        // check if it is a constructor or an @Initializer method
        MethodTree methodTree = (MethodTree) memberTree;
        Symbol.MethodSymbol symbol = ASTHelpers.getSymbol(methodTree);
        if (isConstructor(methodTree)) {
          constructors.add(methodTree);
        } else if (isInitializerMethod(state, symbol)) {
          if (symbol.isStatic()) {
            staticInitializerMethods.add(methodTree);
          } else {
            instanceInitializerMethods.add(methodTree);
          }
        }
        break;
      case VARIABLE:
        // field declaration
        VariableTree varTree = (VariableTree) memberTree;
        Symbol fieldSymbol = ASTHelpers.getSymbol(varTree);
        if (fieldSymbol.type.isPrimitive() || skipDueToFieldAnnotation(fieldSymbol)) {
          continue;
        }
        if (varTree.getInitializer() != null) {
          // note that we check that the initializer does the right thing in
          // matchVariable()
          continue;
        }
        if (fieldSymbol.isStatic()) {
          nonnullStaticFields.add(fieldSymbol);
        } else {
          nonnullInstanceFields.add(fieldSymbol);
        }
        break;
      case BLOCK:
        // initializer block
        BlockTree blockTree = (BlockTree) memberTree;
        if (blockTree.isStatic()) {
          staticInitializerBlocks.add(blockTree);
        } else {
          instanceInitializerBlocks.add(blockTree);
        }
        break;
      case ENUM:
      case CLASS:
      case INTERFACE:
      case ANNOTATION_TYPE:
        // do nothing
        break;
      default:
        throw new RuntimeException(
            memberTree.getKind().toString() + " " + state.getSourceForNode(memberTree));
    }
  }

  return FieldInitEntities.create(
      classSymbol,
      ImmutableSet.copyOf(nonnullInstanceFields),
      ImmutableSet.copyOf(nonnullStaticFields),
      ImmutableList.copyOf(instanceInitializerBlocks),
      ImmutableList.copyOf(staticInitializerBlocks),
      ImmutableSet.copyOf(constructors),
      ImmutableSet.copyOf(instanceInitializerMethods),
      ImmutableSet.copyOf(staticInitializerMethods));
}
 
Example 20
Source File: IDynamicJdk.java    From manifold with Apache License 2.0 votes vote down vote up
Iterable<Symbol> getMembers( Symbol.ClassSymbol members );