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

The following examples show how to use com.sun.tools.javac.code.Symbol#VarSymbol . 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: PrivateStaticFinalLoggers.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchVariable(final VariableTree tree, final VisitorState state) {
  final Symbol.VarSymbol sym = ASTHelpers.getSymbol(tree);
  if (sym == null || sym.getKind() != ElementKind.FIELD) {
    return NO_MATCH;
  }
  if (sym.getModifiers()
      .containsAll(List.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))) {
    return NO_MATCH;
  }
  if (!isSubtype(
      getType(tree), state.getTypeFromString("org.apache.logging.log4j.Logger"), state)) {
    return NO_MATCH;
  }
  return buildDescription(tree)
      .addFix(addModifiers(tree, state, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))
      .build();
}
 
Example 2
Source File: GetTestClass.java    From Mockery with Apache License 2.0 6 votes vote down vote up
private List<Param> getParams(Symbol.MethodSymbol methodSymbol) {
  List<Param> params = new ArrayList<>();
  List<Symbol.VarSymbol> paramsSymbols = methodSymbol.getParameters();

  for (int position = 0; position < paramsSymbols.size(); position++) {
    Symbol.VarSymbol varSymbolParam = paramsSymbols.get(position);
    String name = varSymbolParam.getSimpleName().toString();
    TypeName type = TypeName.get(varSymbolParam.asType());

    boolean isOptional = true;
    Mockery mockery = getAnnotation(varSymbolParam, Mockery.class);

    if (mockery != null) {
      Mockery.Behaviour behaviour = getBehaviourMockery(mockery);
      isOptional = behaviour.isOptional();
    }

    params.add(new Param(name, varSymbolParam,
        position, type, mockery != null, isOptional));
  }

  return params;
}
 
Example 3
Source File: InferredJARModelsHandler.java    From NullAway with MIT License 6 votes vote down vote up
private String getMethodSignature(Symbol.MethodSymbol method) {
  // Generate method signature
  String methodSign =
      method.enclClass().getQualifiedName().toString()
          + ":"
          + (method.isStaticOrInstanceInit()
              ? ""
              : getSimpleTypeName(method.getReturnType()) + " ")
          + method.getSimpleName()
          + "(";
  if (!method.getParameters().isEmpty()) {
    for (Symbol.VarSymbol var : method.getParameters()) {
      methodSign += getSimpleTypeName(var.type) + ", ";
    }
    methodSign = methodSign.substring(0, methodSign.lastIndexOf(','));
  }
  methodSign += ")";
  LOG(DEBUG, "DEBUG", "@ method sign: " + methodSign);
  return methodSign;
}
 
Example 4
Source File: SrcClassUtil.java    From manifold with Apache License 2.0 6 votes vote down vote up
private String genSuperCtorCall( Symbol.MethodSymbol superCtor )
{
  String bodyStmt;
  StringBuilder sb = new StringBuilder( "super(" );
  List<Symbol.VarSymbol> parameters = superCtor.getParameters();
  for( int i = 0; i < parameters.size(); i++ )
  {
    Symbol.VarSymbol param = parameters.get( i );
    if( i > 0 )
    {
      sb.append( ", " );
    }
    sb.append( getValueForType( param.type ) );
  }
  sb.append( ");" );
  bodyStmt = sb.toString();
  return bodyStmt;
}
 
Example 5
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
private JCTree[] tempify( JCTree.JCBinary tree, TreeMaker make, JCExpression expr, Context ctx, Symbol owner, String varName )
{
  switch( expr.getTag() )
  {
    case LITERAL:
    case IDENT:
      return null;

    default:
      JCTree.JCVariableDecl tempVar = make.VarDef( make.Modifiers( FINAL | SYNTHETIC ),
        Names.instance( ctx ).fromString( varName + tempVarIndex ), make.Type( expr.type ), expr );
      tempVar.sym = new Symbol.VarSymbol( FINAL | SYNTHETIC, tempVar.name, expr.type, owner );
      tempVar.type = tempVar.sym.type;
      tempVar.pos = tree.pos;
      JCExpression ident = make.Ident( tempVar );
      ident.type = expr.type;
      ident.pos = tree.pos;
      return new JCTree[] {tempVar, ident};
  }
}
 
Example 6
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
private JCExpression getRelationalOpEnumConst( TreeMaker make, JCTree tree )
{
  Symbol.ClassSymbol opClassSym = IDynamicJdk.instance().getTypeElement( _tp.getContext(), _tp.getCompilationUnit(),
    ComparableUsing.Operator.class.getCanonicalName() );

  Names names = Names.instance( _tp.getContext() );
  Symbol.VarSymbol operatorSym = resolveField(
    tree.pos(), _tp.getContext(), names.fromString( tree.getTag().name() ), opClassSym.type );

  JCTree.JCFieldAccess opEnumConst = (JCTree.JCFieldAccess)memberAccess( make, _tp.getElementUtil(),
    ComparableUsing.Operator.class.getName() + "." + tree.getTag().name() );
  opEnumConst.type = operatorSym.type;
  opEnumConst.sym = operatorSym;
  opEnumConst.pos = tree.pos;
  assignTypes( opEnumConst.selected, opClassSym );
  opEnumConst.selected.pos = tree.pos;

  return opEnumConst;
}
 
Example 7
Source File: SrcClassUtil.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void addField( SrcClass srcClass, Symbol sym )
{
  Symbol.VarSymbol field = (Symbol.VarSymbol)sym;
  SrcField srcField = new SrcField( field.name.toString(), makeSrcType( field.type, sym, TargetType.FIELD, -1 ) );
  if( sym.isEnum() )
  {
    srcField.enumConst();
    srcClass.addEnumConst( srcField );
  }
  else
  {
    srcField.modifiers( field.getModifiers() );
    if( Modifier.isFinal( (int)srcField.getModifiers() ) )
    {
      srcField.initializer( new SrcRawExpression( getValueForType( sym.type ) ) );
    }
    srcClass.addField( srcField );
  }
}
 
Example 8
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
/**
 * Checks for {@link com.sun.tools.javac.code.Symbol.VarSymbol} and the flag name
 *
 * @param argSym a symbol
 * @return True if matches. Otherwise false
 */
private boolean isVarSymbolAndMatchesFlagName(Symbol argSym) {
  if (argSym instanceof Symbol.VarSymbol) {
    Object constantValue = ((Symbol.VarSymbol) argSym).getConstantValue();
    return constantValue != null && constantValue.equals(xpFlagName);
  }
  return false;
}
 
Example 9
Source File: JavaParserVisitor.java    From rewrite with Apache License 2.0 5 votes vote down vote up
@Nullable
private JavaType type(@Nullable Symbol symbol) {
    if (symbol instanceof Symbol.ClassSymbol || symbol instanceof Symbol.TypeVariableSymbol) {
        return type(symbol.type);
    } else if (symbol instanceof Symbol.VarSymbol) {
        return new JavaType.GenericTypeVariable(symbol.name.toString(), null);
    }
    return null;
}
 
Example 10
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Symbol.VarSymbol resolveField( JCDiagnostic.DiagnosticPosition pos, Context ctx, Name name, Type qual )
{
  Resolve rs = Resolve.instance( ctx );
  AttrContext attrContext = new AttrContext();
  Env<AttrContext> env = new AttrContextEnv( pos.getTree(), attrContext );
  env.toplevel = (JCTree.JCCompilationUnit)_tp.getCompilationUnit();
  return rs.resolveInternalField( pos, env, qual, name );
}
 
Example 11
Source File: NullabilityUtil.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * Works for method parameters defined either in source or in class files
 *
 * @param symbol the method symbol
 * @param paramInd index of the parameter
 * @return all declaration and type-use annotations for the parameter
 */
public static Stream<? extends AnnotationMirror> getAllAnnotationsForParameter(
    Symbol.MethodSymbol symbol, int paramInd) {
  Symbol.VarSymbol varSymbol = symbol.getParameters().get(paramInd);
  return Stream.concat(
      varSymbol.getAnnotationMirrors().stream(),
      symbol
          .getRawTypeAttributes()
          .stream()
          .filter(
              t ->
                  t.position.type.equals(TargetType.METHOD_FORMAL_PARAMETER)
                      && t.position.parameter_index == paramInd));
}
 
Example 12
Source File: UsageCounter.java    From piranha with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitVariable(VariableTree tree, Void unused) {
  Symbol.VarSymbol vSym = ASTHelpers.getSymbol(tree);
  if (ASTHelpers.hasAnnotation(vSym, "javax.inject.Inject", state)) {
    declaredInjectVars.add(tree);
  }
  return super.visitVariable(tree, null);
}
 
Example 13
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 4 votes vote down vote up
private Symbol.MethodSymbol findExtMethod( JCTree.JCMethodInvocation tree )
{
  Symbol sym = null;
  if( tree.meth instanceof JCTree.JCFieldAccess )
  {
    sym = ((JCTree.JCFieldAccess)tree.meth).sym;
  }
  else if( tree.meth instanceof JCTree.JCIdent )
  {
    sym = ((JCTree.JCIdent)tree.meth).sym;
  }

  if( sym == null || !sym.hasAnnotations() )
  {
    return null;
  }

  for( Attribute.Compound annotation: sym.getAnnotationMirrors() )
  {
    if( annotation.type.toString().equals( ExtensionMethod.class.getName() ) )
    {
      String extensionClass = (String)annotation.values.get( 0 ).snd.getValue();
      boolean isStatic = (boolean)annotation.values.get( 1 ).snd.getValue();
      BasicJavacTask javacTask = (BasicJavacTask)_tp.getJavacTask(); //JavacHook.instance() != null ? (JavacTaskImpl)JavacHook.instance().getJavacTask_PlainFileMgr() : ClassSymbols.instance( _sp.getModule() ).getJavacTask_PlainFileMgr();
      Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> classSymbol = ClassSymbols.instance( _sp.getModule() ).getClassSymbol( javacTask, _tp, extensionClass );
      if( classSymbol == null )
      {
        // In module mode if a package in another module is not exported, classes in the package
        // will not be accessible to other modules, hence the null classSymbol
        continue;
      }

      Symbol.ClassSymbol extClassSym = classSymbol.getFirst();
      if( extClassSym == null )
      {
        // This can happen during bootstrapping with Dark Java classes from Manifold itself
        // So we short-circuit that here (ManClassFinder_9 or any other darkj class used during bootstrapping doesn't really need to use extensions)
        return null;
      }
      Types types = Types.instance( javacTask.getContext() );
      outer:
      for( Symbol elem: IDynamicJdk.instance().getMembers( extClassSym ) )
      {
        if( elem instanceof Symbol.MethodSymbol && elem.flatName().toString().equals( sym.name.toString() ) )
        {
          Symbol.MethodSymbol extMethodSym = (Symbol.MethodSymbol)elem;
          List<Symbol.VarSymbol> extParams = extMethodSym.getParameters();
          List<Symbol.VarSymbol> calledParams = ((Symbol.MethodSymbol)sym).getParameters();
          int thisOffset = isStatic ? 0 : 1;
          if( extParams.size() - thisOffset != calledParams.size() )
          {
            continue;
          }
          for( int i = thisOffset; i < extParams.size(); i++ )
          {
            Symbol.VarSymbol extParam = extParams.get( i );
            Symbol.VarSymbol calledParam = calledParams.get( i - thisOffset );
            if( !types.isSameType( types.erasure( extParam.type ), types.erasure( calledParam.type ) ) )
            {
              continue outer;
            }
          }
          return extMethodSym;
        }
      }
    }
  }
  return null;
}
 
Example 14
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 4 votes vote down vote up
private JCTree replaceWithReflection( JCTree.JCNewClass tree )
{
  if( tree.constructor == null )
  {
    return tree;
  }

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

  Type type = ((JCTree.JCAnnotatedType)tree.clazz).underlyingType.type;

  if( tree.constructor instanceof Symbol.ClassSymbol )
  {
    //assert tree.constructor.kind == com.sun.tools.javac.code.Kinds.ERR;
    return tree;
  }

  List<Symbol.VarSymbol> parameters = ((Symbol.MethodSymbol)tree.constructor).getParameters();
  ArrayList<JCExpression> paramTypes = new ArrayList<>();
  for( Symbol.VarSymbol param: parameters )
  {
    paramTypes.add( makeClassExpr( tree, param.type ) );
  }
  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( makeClassExpr( tree, type ) ); // the class
  newArgs.add( paramTypesArray ); // param types
  newArgs.add( argsArray ); // args


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

  Symbol.MethodSymbol reflectMethodSym = findReflectUtilConstructor( tree );
  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 = type;
  JCTree.JCFieldAccess newMethodSelect = (JCTree.JCFieldAccess)reflectCall.getMethodSelect();
  newMethodSelect.sym = reflectMethodSym;
  newMethodSelect.type = reflectMethodSym.type;
  assignTypes( newMethodSelect.selected, reflectMethodClassSym );

  return reflectCall;
}
 
Example 15
Source File: DynamicProxyFactory.java    From manifold with Apache License 2.0 4 votes vote down vote up
private static boolean hasCallMethod( BasicJavacTask javacTask, Symbol.ClassSymbol classSymbol )
{
  Name call = Names.instance( javacTask.getContext() ).fromString( "call" );
  Iterable<Symbol> elems = IDynamicJdk.instance().getMembersByName( classSymbol, call );
  for( Symbol s : elems )
  {
    if( s instanceof Symbol.MethodSymbol )
    {
      List<Symbol.VarSymbol> parameters = ((Symbol.MethodSymbol)s).getParameters();
      if( parameters.size() != 6 )
      {
        return false;
      }

      Symtab symbols = Symtab.instance( javacTask.getContext() );
      Types types = Types.instance( javacTask.getContext() );
      return types.erasure( parameters.get( 0 ).asType() ).equals( types.erasure( symbols.classType ) ) &&
             parameters.get( 1 ).asType().equals( symbols.stringType ) &&
             parameters.get( 2 ).asType().equals( symbols.stringType ) &&
             types.erasure( parameters.get( 3 ).asType() ).equals( types.erasure( symbols.classType ) ) &&
             parameters.get( 4 ).asType() instanceof Type.ArrayType && types.erasure( ((Type.ArrayType)parameters.get( 4 ).asType()).getComponentType() ).equals( types.erasure( symbols.classType ) ) &&
             parameters.get( 5 ).asType() instanceof Type.ArrayType && ((Type.ArrayType)parameters.get( 5 ).asType()).getComponentType().equals( symbols.objectType );
    }
  }
  Type superclass = classSymbol.getSuperclass();
  if( !(superclass instanceof NoType) )
  {
    if( hasCallMethod( javacTask, (Symbol.ClassSymbol)superclass.tsym ) )
    {
      return true;
    }
  }
  for( Type iface : classSymbol.getInterfaces() )
  {
    if( hasCallMethod( javacTask, (Symbol.ClassSymbol)iface.tsym ) )
    {
      return true;
    }
  }
  return false;
}
 
Example 16
Source File: SrcClassUtil.java    From manifold with Apache License 2.0 4 votes vote down vote up
private SrcClass makeSrcClass( String fqn, SrcClass enclosing, Symbol.ClassSymbol classSymbol, CompilationUnitTree compilationUnit, BasicJavacTask javacTask, IModule module, JavaFileManager.Location location, DiagnosticListener<JavaFileObject> errorHandler, boolean withMembers )
  {
    SrcClass srcClass;
    if( enclosing == null )
    {
      srcClass = new SrcClass( fqn, SrcClass.Kind.from( classSymbol.getKind() ), location, module, errorHandler )
        .modifiers( classSymbol.getModifiers() );
    }
    else
    {
      srcClass = new SrcClass( fqn, enclosing, SrcClass.Kind.from( classSymbol.getKind() ) )
        .modifiers( classSymbol.getModifiers() );
    }
    if( classSymbol.getEnclosingElement() instanceof Symbol.PackageSymbol && compilationUnit != null )
    {
      for( ImportTree imp: compilationUnit.getImports() )
      {
        if( imp.isStatic() )
        {
          srcClass.addStaticImport( imp.getQualifiedIdentifier().toString() );
        }
        else
        {
          srcClass.addImport( imp.getQualifiedIdentifier().toString() );
        }
      }
    }
    addAnnotations( srcClass, classSymbol );
    for( Symbol.TypeVariableSymbol typeVar: classSymbol.getTypeParameters() )
    {
      srcClass.addTypeVar( makeTypeVarType( typeVar ) );
    }
    Type superclass = classSymbol.getSuperclass();
    if( !(superclass instanceof NoType) )
    {
      srcClass.superClass( makeNestedType( superclass ) );
    }
    for( Type iface: classSymbol.getInterfaces() )
    {
      srcClass.addInterface( makeNestedType( iface ) );
    }
    if( withMembers )
    {
      java.util.List<Symbol> members = classSymbol.getEnclosedElements();
      for( Symbol sym: members )
      {
// include private members because:
// 1. @Jailbreak can expose private members
// 2. Compiler error messages are better when referencing an inaccessible method vs. a non-existent one
//        long modifiers = SrcAnnotated.modifiersFrom( sym.getModifiers() );
//        if( Modifier.isPrivate( (int)modifiers ) )
//        {
//          continue;
//        }

        if( sym instanceof Symbol.ClassSymbol )
        {
          addInnerClass( module, srcClass, sym, javacTask );
        }
        else if( sym instanceof Symbol.VarSymbol )
        {
          addField( srcClass, sym );
        }
        else if( sym instanceof Symbol.MethodSymbol )
        {
          if( !isEnumMethod( sym ) )
          {
            addMethod( module, srcClass, (Symbol.MethodSymbol)sym, javacTask );
          }
        }
      }

      addDefaultCtorForEnum( classSymbol, srcClass, members );
    }
    return srcClass;
  }
 
Example 17
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 18
Source File: SrcClassUtil.java    From manifold with Apache License 2.0 4 votes vote down vote up
private void addMethod( IModule module, SrcClass srcClass, Symbol.MethodSymbol method, BasicJavacTask javacTask )
{
  String name = method.flatName().toString();
  SrcMethod srcMethod = new SrcMethod( srcClass, name.equals( "<init>" ) );
  addAnnotations( srcMethod, method );
  srcMethod.modifiers( method.getModifiers() );
  if( (method.flags() & Flags.VARARGS) != 0 )
  {
    srcMethod.modifiers( srcMethod.getModifiers() | 0x00000080 ); // Modifier.VARARGS
  }
  if( name.equals( "<clinit>" ) )
  {
    return;
  }
  if( !srcMethod.isConstructor() )
  {
    srcMethod.name( name );
    srcMethod.returns( makeSrcType( method.getReturnType(), method, TargetType.METHOD_RETURN, -1 ) );
  }
  for( Symbol.TypeVariableSymbol typeVar: method.getTypeParameters() )
  {
    srcMethod.addTypeVar( makeTypeVarType( typeVar ) );
  }
  List<Symbol.VarSymbol> parameters = method.getParameters();
  for( int i = 0; i < parameters.size(); i++ )
  {
    Symbol.VarSymbol param = parameters.get( i );
    SrcParameter srcParam = new SrcParameter( param.flatName().toString(), makeSrcType( param.type, method, TargetType.METHOD_FORMAL_PARAMETER, i ) );
    srcMethod.addParam( srcParam );
    addAnnotations( srcParam, param );
  }
  List<Type> thrownTypes = method.getThrownTypes();
  for( int i = 0; i < thrownTypes.size(); i++ )
  {
    Type throwType = thrownTypes.get( i );
    srcMethod.addThrowType( makeSrcType( throwType, method, TargetType.THROWS, i ) );
  }
  String bodyStmt;
  if( srcMethod.isConstructor() && !srcClass.isEnum() )
  {
    // Note we can't just throw an exception for the ctor body, the compiler will
    // still complain about the missing super() call if the super class does not have
    // an accessible default ctor. To appease the compiler we generate a super(...)
    // call to the first accessible constructor we can find in the super class.
    bodyStmt = genSuperCtorCall( module, srcClass, javacTask );
  }
  else
  {
    bodyStmt = "throw new RuntimeException();";
  }
  srcMethod.body( new SrcStatementBlock()
    .addStatement(
      new SrcRawStatement()
        .rawText( bodyStmt ) ) );
  srcClass.addMethod( srcMethod );
}
 
Example 19
Source File: AccessPathNullnessPropagation.java    From NullAway with MIT License 4 votes vote down vote up
private NullnessStore lambdaInitialStore(
    UnderlyingAST.CFGLambda underlyingAST, List<LocalVariableNode> parameters) {
  // include nullness info for locals from enclosing environment
  EnclosingEnvironmentNullness environmentNullness =
      EnclosingEnvironmentNullness.instance(context);
  NullnessStore environmentMapping =
      Objects.requireNonNull(
          environmentNullness.getEnvironmentMapping(underlyingAST.getLambdaTree()),
          "no environment stored for lambda");
  NullnessStore.Builder result = environmentMapping.toBuilder();
  LambdaExpressionTree code = underlyingAST.getLambdaTree();
  // need to check annotation for i'th parameter of functional interface declaration
  Symbol.MethodSymbol fiMethodSymbol = NullabilityUtil.getFunctionalInterfaceMethod(code, types);
  com.sun.tools.javac.util.List<Symbol.VarSymbol> fiMethodParameters =
      fiMethodSymbol.getParameters();
  ImmutableSet<Integer> nullableParamsFromHandler =
      handler.onUnannotatedInvocationGetExplicitlyNullablePositions(
          context, fiMethodSymbol, ImmutableSet.of());

  for (int i = 0; i < parameters.size(); i++) {
    LocalVariableNode param = parameters.get(i);
    VariableTree variableTree = code.getParameters().get(i);
    Element element = param.getElement();
    Nullness assumed;
    // we treat lambda parameters differently; they "inherit" the nullability of the
    // corresponding functional interface parameter, unless they are explicitly annotated
    if (Nullness.hasNullableAnnotation((Symbol) element, config)) {
      assumed = NULLABLE;
    } else if (!NullabilityUtil.lambdaParamIsImplicitlyTyped(variableTree)) {
      // the parameter has a declared type with no @Nullable annotation
      // treat as non-null
      assumed = NONNULL;
    } else {
      if (NullabilityUtil.isUnannotated(fiMethodSymbol, config)) {
        // assume parameter is non-null unless handler tells us otherwise
        assumed = nullableParamsFromHandler.contains(i) ? NULLABLE : NONNULL;
      } else {
        assumed =
            Nullness.hasNullableAnnotation(fiMethodParameters.get(i), config)
                ? NULLABLE
                : NONNULL;
      }
    }
    result.setInformation(AccessPath.fromLocal(param), assumed);
  }
  result = handler.onDataflowInitialStore(underlyingAST, parameters, result);
  return result.build();
}