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

The following examples show how to use com.sun.tools.javac.code.Symbol#MethodSymbol . 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
private JCExpression classForNameCall( Type type, JCTree tree )
{
  TreeMaker make = _tp.getTreeMaker();
  JavacElements javacElems = _tp.getElementUtil();

  JCTree.JCMethodInvocation typeCall = make.Apply( List.nil(),
    memberAccess( make, javacElems, ReflectUtil.class.getName() + ".type" ),
    List.of( make.Literal( makeLiteralName( type ) ) ) );
  typeCall.setPos( Position.NOPOS );
  typeCall.type = _tp.getSymtab().classType;
  JCTree.JCFieldAccess newMethodSelect = (JCTree.JCFieldAccess)typeCall.getMethodSelect();

  Symbol.ClassSymbol reflectMethodClassSym =
    IDynamicJdk.instance().getTypeElement( _tp.getContext(), _tp.getCompilationUnit(), ReflectUtil.class.getName() );
  Symbol.MethodSymbol typeMethodSymbol = resolveMethod( tree.pos(),
    Names.instance( _tp.getContext() ).fromString( "type" ),
    reflectMethodClassSym.type, List.of( _tp.getSymtab().stringType ) );
  newMethodSelect.sym = typeMethodSymbol;
  newMethodSelect.type = typeMethodSymbol.type;
  newMethodSelect.pos = tree.pos;
  assignTypes( newMethodSelect.selected, reflectMethodClassSym );

  return typeCall;
}
 
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: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
private boolean isInitializerMethod(VisitorState state, Symbol.MethodSymbol symbol) {
  if (ASTHelpers.hasDirectAnnotationWithSimpleName(symbol, "Initializer")
      || config.isKnownInitializerMethod(symbol)) {
    return true;
  }
  for (AnnotationMirror anno : symbol.getAnnotationMirrors()) {
    String annoTypeStr = anno.getAnnotationType().toString();
    if (config.isInitializerMethodAnnotation(annoTypeStr)) {
      return true;
    }
  }
  Symbol.MethodSymbol closestOverriddenMethod =
      getClosestOverriddenMethod(symbol, state.getTypes());
  if (closestOverriddenMethod == null) {
    return false;
  }
  return isInitializerMethod(state, closestOverriddenMethod);
}
 
Example 4
Source File: OptionalEmptinessHandler.java    From NullAway with MIT License 6 votes vote down vote up
private void updateIfAssertIsPresentTrueOnOptional(
    MethodInvocationNode node, Types types, AccessPathNullnessPropagation.Updates bothUpdates) {
  Node receiver = node.getTarget().getReceiver();
  if (receiver instanceof MethodInvocationNode) {
    MethodInvocationNode receiverMethod = (MethodInvocationNode) receiver;
    Symbol.MethodSymbol receiverSymbol = ASTHelpers.getSymbol(receiverMethod.getTree());
    if (methodNameUtil.isMethodAssertThat(receiverSymbol)) {
      // assertThat will always have at least one argument, So safe to extract from the arguments
      Node arg = receiverMethod.getArgument(0);
      if (arg instanceof MethodInvocationNode) {
        // Since assertThat(a.isPresent()) changes to
        // Truth.assertThat(Boolean.valueOf(a.isPresent()))
        // need to be unwrapped from Boolean.valueOf
        Node unwrappedArg = ((MethodInvocationNode) arg).getArgument(0);
        if (unwrappedArg instanceof MethodInvocationNode) {
          MethodInvocationNode argMethod = (MethodInvocationNode) unwrappedArg;
          Symbol.MethodSymbol argSymbol = ASTHelpers.getSymbol(argMethod.getTree());
          if (optionalIsPresentCall(argSymbol, types)) {
            updateNonNullAPsForOptionalContent(bothUpdates, argMethod.getTarget().getReceiver());
          }
        }
      }
    }
  }
}
 
Example 5
Source File: RestrictiveAnnotationHandler.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public ImmutableSet<Integer> onUnannotatedInvocationGetNonNullPositions(
    NullAway analysis,
    VisitorState state,
    Symbol.MethodSymbol methodSymbol,
    List<? extends ExpressionTree> actualParams,
    ImmutableSet<Integer> nonNullPositions) {
  HashSet<Integer> positions = new HashSet<Integer>();
  positions.addAll(nonNullPositions);
  for (int i = 0; i < methodSymbol.getParameters().size(); ++i) {
    if (Nullness.paramHasNonNullAnnotation(methodSymbol, i, config)) {
      positions.add(i);
    }
  }
  return ImmutableSet.copyOf(positions);
}
 
Example 6
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
private JCTree.JCMethodInvocation configMethod( JCTree.JCBinary tree, Symbol.MethodSymbol operatorMethod, JCTree.JCMethodInvocation methodCall )
{
  methodCall.setPos( tree.pos );
  methodCall.type = operatorMethod.getReturnType();

  // If methodCall is an extension method, rewrite it
  Symbol.MethodSymbol extMethod = findExtMethod( methodCall );
  if( extMethod != null )
  {
    // Replace with extension method call
    methodCall = replaceExtCall( methodCall, extMethod );
  }

  // Concrete type set in attr
  methodCall.type = tree.type;
  return methodCall;
}
 
Example 7
Source File: CompositeHandler.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public void onMatchMethodReference(
    NullAway analysis,
    MemberReferenceTree tree,
    VisitorState state,
    Symbol.MethodSymbol methodSymbol) {
  for (Handler h : handlers) {
    h.onMatchMethodReference(analysis, tree, state, methodSymbol);
  }
}
 
Example 8
Source File: StreamNullabilityPropagator.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public void onMatchMethod(
    NullAway analysis, MethodTree tree, VisitorState state, Symbol.MethodSymbol methodSymbol) {
  if (mapToFilterMap.containsKey(tree)) {
    bodyToMethodOrLambda.put(tree.getBody(), tree);
  }
}
 
Example 9
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
/**
 * Replace all extension method call-sites with static calls to extension methods
 */
@Override
public void visitApply( JCTree.JCMethodInvocation tree )
{
  super.visitApply( tree );

  eraseGenericStructuralVarargs( tree );

  if( _tp.isGenerate() &&
      // handle compiler-generated call to iterator(), sometimes a structural interface is involved here (lists in JSON)
      !isStructuralIteratorCall( tree ) )
  {
    // Don't process tree during GENERATE, unless the tree was generated e.g., a bridge method
    return;
  }

  Symbol.MethodSymbol method = findExtMethod( tree );
  if( method != null )
  {
    // Replace with extension method call
    result = replaceExtCall( tree, method );
  }
  else if( isStructuralMethod( tree ) )
  {
    // The structural interface method is implemented directly in the type or supertype hierarchy,
    // replace with proxy call
    result = replaceStructuralCall( tree );
  }
  else if( isJailbreakReceiver( tree ) )
  {
    result = replaceWithReflection( tree );
  }
  else
  {
    result = tree;
  }
}
 
Example 10
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
/**
 * If the binding expression is of the form `A b` where `A` is a Float or Double *literal* and `b` defines a
 * `R postfixBind(String)` where `R` is the same return type as the original binding expression, then get the
 * token that was parsed for the Float or Double literal and use the String version of `postfixBind()`. This has
 * the effect of preserving the value of the token, where otherwise it can be lost due to IEEE floating point
 * encoding.
 */
private Symbol.MethodSymbol favorStringsWithNumberCoercion( JCTree.JCBinary tree, Symbol.MethodSymbol operatorMethod )
{
  String operatorMethodName = operatorMethod.name.toString();
  if( !operatorMethodName.equals( "postfixBind" ) )
  {
    return operatorMethod;
  }

  if( tree.lhs instanceof JCTree.JCLiteral &&
      (tree.lhs.getKind() == Tree.Kind.FLOAT_LITERAL || tree.lhs.getKind() == Tree.Kind.DOUBLE_LITERAL) )
  {
    Type rhsType = tree.rhs.type;
    Symbol.MethodSymbol postfixBinding_string = ManAttr.getMethodSymbol(
      _tp.getTypes(), rhsType, _tp.getSymtab().stringType, operatorMethodName, (Symbol.ClassSymbol)rhsType.tsym, 1 );

    if( postfixBinding_string != null &&
        postfixBinding_string.getParameters().get( 0 ).type.tsym == _tp.getSymtab().stringType.tsym &&
        postfixBinding_string.getReturnType().equals( operatorMethod.getReturnType() ) )
    {
      // since the source may be preprocessed we attempt to get it in its preprocessed form
      CharSequence source = ManParserFactory.getSource( _tp.getCompilationUnit().getSourceFile() );
      int start = tree.lhs.pos;
      int end = tree.lhs.pos().getEndPosition( ((JCTree.JCCompilationUnit)_tp.getCompilationUnit()).endPositions );
      String token = source.subSequence( start, end ).toString();
      if( token.endsWith( "d" ) || token.endsWith( "f" ) )
      {
        token = token.substring( 0, token.length()-1 );
      }
      JCTree.JCLiteral temp = (JCTree.JCLiteral)tree.lhs;
      tree.lhs = _tp.getTreeMaker().Literal( token );
      tree.lhs.type = _tp.getSymtab().stringType;
      tree.lhs.pos = temp.pos;

      return postfixBinding_string;
    }
  }
  return operatorMethod;
}
 
Example 11
Source File: UsageCounter.java    From piranha with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitMethod(MethodTree tree, Void unused) {
  Symbol.MethodSymbol mSym = ASTHelpers.getSymbol(tree);
  if (ASTHelpers.hasAnnotation(mSym, "dagger.Provides", state)) {
    for (VariableTree vt : tree.getParameters()) {
      declaredParamVars.put(vt, mSym);
    }
  }
  return super.visitMethod(tree, null);
}
 
Example 12
Source File: StreamNullabilityPropagator.java    From NullAway with MIT License 5 votes vote down vote up
private void handleChainFromFilter(
    StreamTypeRecord streamType,
    MethodInvocationTree observableDotFilter,
    Tree filterMethodOrLambda,
    VisitorState state) {
  MethodInvocationTree outerCallInChain = observableDotFilter;
  if (outerCallInChain == null) {
    return;
  }
  // Traverse the observable call chain out through any pass-through methods
  do {
    outerCallInChain = observableOuterCallInChain.get(outerCallInChain);
    // Check for a map method (which might be a pass-through method or the first method after a
    // pass-through chain)
    if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) {
      // Update mapToFilterMap
      Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain);
      if (streamType.isMapMethod(mapMethod)) {
        MaplikeToFilterInstanceRecord record =
            new MaplikeToFilterInstanceRecord(
                streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda);
        mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record);
      }
    }
  } while (outerCallInChain != null
      && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state)
      && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain)));
}
 
Example 13
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 4 votes vote down vote up
@Override
public void visitUnary( JCTree.JCUnary tree )
{
  super.visitUnary( tree );

  if( _tp.isGenerate() && !shouldProcessForGeneration() )
  {
    // Don't process tree during GENERATE, unless the tree was generated e.g., a bridge method
    return;
  }

  Symbol op = IDynamicJdk.instance().getOperator( tree );
  if( op instanceof OverloadOperatorSymbol ) // handle negation overload
  {
    TreeMaker make = _tp.getTreeMaker();

    // Handle operator overload expressions

    Symbol.MethodSymbol operatorMethod = (Symbol.MethodSymbol)op;
    while( operatorMethod instanceof OverloadOperatorSymbol )
    {
      operatorMethod = ((OverloadOperatorSymbol)operatorMethod).getMethod();
    }

    if( operatorMethod != null )
    {
      JCTree.JCMethodInvocation methodCall;
      JCExpression receiver = tree.getExpression();
      methodCall = make.Apply( List.nil(), make.Select( receiver, operatorMethod ), List.nil() );
      methodCall.setPos( tree.pos );
      methodCall.type = operatorMethod.getReturnType();

      // If methodCall is an extension method, rewrite it accordingly
      Symbol.MethodSymbol extMethod = findExtMethod( methodCall );
      if( extMethod != null )
      {
        // Replace with extension method call
        methodCall = replaceExtCall( methodCall, extMethod );
      }

      result = methodCall;
    }
  }
  else if( isJailbreakReceiver( tree ) )
  {
    Tree.Kind kind = tree.getKind();
    if( kind == Tree.Kind.POSTFIX_INCREMENT || kind == Tree.Kind.POSTFIX_DECREMENT ||
        kind == Tree.Kind.PREFIX_INCREMENT || kind == Tree.Kind.PREFIX_DECREMENT )
    {
      // ++, -- operators not supported with jailbreak access to fields, only direct assignment
      _tp.report( tree, Diagnostic.Kind.ERROR, ExtIssueMsg.MSG_INCREMENT_OP_NOT_ALLOWED_REFLECTION.get() );
      Types types = Types.instance( ((BasicJavacTask)_tp.getJavacTask()).getContext() );
      tree.type = types.createErrorType( tree.type );
    }
    result = tree;
  }
  else
  {
    result = tree;
  }
}
 
Example 14
Source File: MethodNameUtil.java    From NullAway with MIT License 4 votes vote down vote up
boolean isMethodIsTrue(Symbol.MethodSymbol methodSymbol) {
  return matchesMethod(methodSymbol, isTrue, isTrueOwner);
}
 
Example 15
Source File: MethodNameUtil.java    From NullAway with MIT License 4 votes vote down vote up
boolean isMethodHamcrestAssertThat(Symbol.MethodSymbol methodSymbol) {
  return matchesMethod(methodSymbol, assertThat, hamcrestAssertClass);
}
 
Example 16
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 4 votes vote down vote up
private JCTree.JCMethodInvocation replaceWithReflection( JCTree.JCMethodInvocation tree )
{
  //## todo: maybe try to avoid reflection if the method is accessible -- at least check if the method and its enclosing nest of classes are all public

  Type type = tree.getMethodSelect().type;
  if( type instanceof Type.ErrorType )
  {
    // No such field/method or wrong params
    return tree;
  }

  TreeMaker make = _tp.getTreeMaker();
  JavacElements javacElems = _tp.getElementUtil();

  JCExpression methodSelect = tree.getMethodSelect();
  if( methodSelect instanceof JCTree.JCFieldAccess )
  {
    JCTree.JCFieldAccess m = (JCTree.JCFieldAccess)methodSelect;
    boolean isStatic = m.sym.getModifiers().contains( javax.lang.model.element.Modifier.STATIC );
    if( !(m.sym instanceof Symbol.MethodSymbol) )
    {
      return tree;
    }
    Type returnType = ((Symbol.MethodSymbol)m.sym).getReturnType();
    Symbol.MethodSymbol reflectMethodSym = findReflectUtilMethod( tree, returnType, isStatic );

    List<Symbol.VarSymbol> parameters = ((Symbol.MethodSymbol)m.sym).getParameters();
    ArrayList<JCExpression> paramTypes = new ArrayList<>();
    for( Symbol.VarSymbol param: parameters )
    {
      JCExpression classExpr = makeClassExpr( tree, param.type );
      paramTypes.add( classExpr );
    }
    Symtab symTab = _tp.getSymtab();
    JCTree.JCNewArray paramTypesArray = make.NewArray(
      make.Type( symTab.classType ), List.nil(), List.from( paramTypes ) );
    paramTypesArray.type = new Type.ArrayType( symTab.classType, symTab.arrayClass );

    JCTree.JCNewArray argsArray = make.NewArray(
      make.Type( symTab.objectType ), List.nil(), tree.getArguments() );
    argsArray.type = new Type.ArrayType( symTab.objectType, symTab.arrayClass );

    ArrayList<JCExpression> newArgs = new ArrayList<>();
    newArgs.add( isStatic ? makeClassExpr( tree, m.selected.type ) : m.selected ); // receiver or class
    newArgs.add( make.Literal( m.sym.flatName().toString() ) ); // method name
    newArgs.add( paramTypesArray ); // param types
    newArgs.add( argsArray ); // args

    Symbol.ClassSymbol reflectMethodClassSym =
      IDynamicJdk.instance().getTypeElement( _tp.getContext(), _tp.getCompilationUnit(), ReflectionRuntimeMethods.class.getName() );

    JCTree.JCMethodInvocation reflectCall =
      make.Apply( List.nil(),
        memberAccess( make, javacElems, ReflectionRuntimeMethods.class.getName() + "." + reflectMethodSym.flatName().toString() ),
        List.from( newArgs ) );
    reflectCall.setPos( tree.pos );
    reflectCall.type = returnType;
    reflectCall.pos = tree.pos;
    JCTree.JCFieldAccess newMethodSelect = (JCTree.JCFieldAccess)reflectCall.getMethodSelect();
    newMethodSelect.sym = reflectMethodSym;
    newMethodSelect.type = reflectMethodSym.type;
    assignTypes( newMethodSelect.selected, reflectMethodClassSym );
    newMethodSelect.pos = tree.pos;
    return reflectCall;
  }
  return tree;
}
 
Example 17
Source File: JavaParserVisitor.java    From rewrite with Apache License 2.0 4 votes vote down vote up
@Override
public J visitMethodInvocation(MethodInvocationTree node, Formatting fmt) {
    var jcSelect = ((JCTree.JCMethodInvocation) node).getMethodSelect();

    Expression select = null;
    if (jcSelect instanceof JCFieldAccess) {
        select = convert(((JCFieldAccess) jcSelect).selected, t -> sourceBefore("."));
    } else if (!(jcSelect instanceof JCIdent)) {
        throw new IllegalStateException("Unexpected method select type " + jcSelect.getClass().getSimpleName());
    }

    // generic type parameters can only exist on qualified targets
    J.MethodInvocation.TypeParameters typeParams = null;
    if (!node.getTypeArguments().isEmpty()) {
        var genericPrefix = sourceBefore("<");
        List<Expression> genericParams = convertAll(node.getTypeArguments(), commaDelim, t -> sourceBefore(">"));
        typeParams = new J.TypeParameters(randomId(), genericParams.stream()
                .map(gp -> new J.TypeParameter(randomId(), emptyList(), gp.withFormatting(EMPTY), null, gp.getFormatting()))
                .collect(toList()),
                format(genericPrefix));
    }

    J.Ident name;
    if (jcSelect instanceof JCFieldAccess) {
        String selectName = ((JCFieldAccess) jcSelect).name.toString();
        name = J.Ident.build(randomId(), selectName, null, format(sourceBefore(selectName)));
    } else {
        name = convert(jcSelect);
    }

    var argsPrefix = sourceBefore("(");
    var args = new J.MethodInvocation.Arguments(randomId(),
            node.getArguments().isEmpty() ?
                    singletonList(new J.Empty(randomId(), format(sourceBefore(")")))) :
                    convertAll(node.getArguments(), commaDelim, t -> sourceBefore(")")),
            format(argsPrefix)
    );

    var genericSymbolAny = (jcSelect instanceof JCFieldAccess) ? ((JCFieldAccess) jcSelect).sym : ((JCIdent) jcSelect).sym;

    // if the symbol is not a method symbol, there is a parser error in play
    Symbol.MethodSymbol genericSymbol = genericSymbolAny instanceof Symbol.MethodSymbol ? (Symbol.MethodSymbol) genericSymbolAny : null;

    JavaType.Method type = null;
    if (genericSymbol != null && jcSelect.type != null) {
        Function<com.sun.tools.javac.code.Type, JavaType.Method.Signature> signature = t -> {
            if (t instanceof com.sun.tools.javac.code.Type.MethodType) {
                com.sun.tools.javac.code.Type.MethodType mt = (com.sun.tools.javac.code.Type.MethodType) t;
                return new JavaType.Method.Signature(type(mt.restype), mt.argtypes.stream().filter(Objects::nonNull)
                        .map(this::type).collect(toList()));
            }
            return null;
        };

        JavaType.Method.Signature genericSignature;
        if (genericSymbol.type instanceof com.sun.tools.javac.code.Type.ForAll) {
            genericSignature = signature.apply(((com.sun.tools.javac.code.Type.ForAll) genericSymbol.type).qtype);
        } else {
            genericSignature = signature.apply(genericSymbol.type);
        }

        type = JavaType.Method.build(
                TypeUtils.asClass(type(genericSymbol.owner)),
                name.getSimpleName(),
                genericSignature,
                signature.apply(jcSelect.type),
                genericSymbol.params().stream().map(p -> p.name.toString()).collect(toList()),
                filteredFlags(genericSymbol)
        );
    }

    return new J.MethodInvocation(randomId(), select, typeParams, name, args, type, fmt);
}
 
Example 18
Source File: StreamTypeRecord.java    From NullAway with MIT License 4 votes vote down vote up
public boolean isPassthroughMethod(Symbol.MethodSymbol methodSymbol) {
  return passthroughMethodSigs.contains(methodSymbol.toString())
      || passthroughMethodSimpleNames.contains(methodSymbol.getQualifiedName().toString());
}
 
Example 19
Source File: Handler.java    From NullAway with MIT License 2 votes vote down vote up
/**
 * Called when NullAway first matches a particular method reference expression
 *
 * @param analysis A reference to the running NullAway analysis.
 * @param tree The AST node for the method reference expression being matched.
 * @param state The current visitor state.
 * @param methodSymbol The method symbol for the reference being matched.
 */
void onMatchMethodReference(
    NullAway analysis,
    MemberReferenceTree tree,
    VisitorState state,
    Symbol.MethodSymbol methodSymbol);
 
Example 20
Source File: Config.java    From NullAway with MIT License 2 votes vote down vote up
/**
 * Checks if a method is a known initializer.
 *
 * @param methodSymbol the method
 * @return true if the method is a known initializer
 */
boolean isKnownInitializerMethod(Symbol.MethodSymbol methodSymbol);