Java Code Examples for com.sun.tools.javac.tree.JCTree#JCExpression

The following examples show how to use com.sun.tools.javac.tree.JCTree#JCExpression . 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: ExtCodeGen.java    From manifold with Apache License 2.0 6 votes vote down vote up
private SrcClass makeStubFromSource()
{
  List<CompilationUnitTree> trees = new ArrayList<>();
  _model.getHost().getJavaParser().parseText( _existingSource, trees, null, null, null );
  JCTree.JCClassDecl classDecl = (JCTree.JCClassDecl)trees.get( 0 ).getTypeDecls().get( 0 );
  SrcClass srcExtended = new SrcClass( _fqn, classDecl.getKind() == Tree.Kind.CLASS ? SrcClass.Kind.Class : SrcClass.Kind.Interface )
    .modifiers( classDecl.getModifiers().getFlags() );
  if( classDecl.extending != null )
  {
    srcExtended.superClass( classDecl.extending.toString() );
  }
  for( JCTree.JCExpression iface : classDecl.implementing )
  {
    srcExtended.addInterface( iface.toString() );
  }
  return srcExtended;
}
 
Example 2
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
@Nonnull
private static java.util.List<String> getArgumentsType(
    SourceContext context, List<JCTree.JCExpression> arguments) throws IOException {

  SourceContext newContext = new SourceContext(context.source, context.endPosTable);
  newContext.setArgumentIndex(0);
  try {
    java.util.List<String> result = new ArrayList<>(arguments.size());
    for (JCTree.JCExpression expression : arguments) {
      newContext.argument = true;
      analyzeParsedTree(newContext, expression);
      newContext.incrArgumentIndex();
      newContext.argument = false;
      result.add(newContext.argumentFQCN);
    }
    return result;
  } finally {
    // reset
    context.setArgumentIndex(-1);
  }
}
 
Example 3
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private static MethodSymbol getMemberSymbol(JCTree.JCExpression node) {
  switch (node.getKind()) {
    case IDENTIFIER:
      return (MethodSymbol) ((JCTree.JCIdent) node).sym.baseSymbol();
    case MEMBER_SELECT:
      return (MethodSymbol) ((JCTree.JCFieldAccess) node).sym;
    default:
      throw new AssertionError("Unexpected tree kind: " + node.getKind());
  }
}
 
Example 4
Source File: BootstrapInserter.java    From manifold with Apache License 2.0 5 votes vote down vote up
private JCTree.JCExpression memberAccess( TreeMaker make, JavacElements node, String... components )
{
  JCTree.JCExpression expr = make.Ident( node.getName( components[0] ) );
  for( int i = 1; i < components.length; i++ )
  {
    expr = make.Select( expr, node.getName( components[i] ) );
  }
  return expr;
}
 
Example 5
Source File: Insertions.java    From annotation-tools with MIT License 5 votes vote down vote up
static TypeTree fromJCTree(JCTree jt) {
  if (jt != null) {
    Kind kind = jt.getKind();
    switch (kind) {
    case ANNOTATED_TYPE:
      return fromJCTree(
          ((JCTree.JCAnnotatedType) jt).getUnderlyingType());
    case IDENTIFIER:
      return new IdentifierTT(
          ((JCTree.JCIdent) jt).sym.getSimpleName().toString());
    case ARRAY_TYPE:
      return new ArrayTT(
          fromJCTree(((JCTree.JCArrayTypeTree) jt).getType()));
    case MEMBER_SELECT:
      return new MemberSelectTT(
          fromJCTree(((JCTree.JCFieldAccess) jt).getExpression()),
          ((JCTree.JCFieldAccess) jt).getIdentifier());
    case EXTENDS_WILDCARD:
    case SUPER_WILDCARD:
      return new WildcardTT(kind,
          fromJCTree(((JCTree.JCWildcard) jt).getBound()));
    case UNBOUNDED_WILDCARD:
      return new WildcardTT();
    case PARAMETERIZED_TYPE:
      com.sun.tools.javac.util.List<JCExpression> typeArgs =
        ((JCTree.JCTypeApply) jt).getTypeArguments();
      List<Tree> args = new ArrayList<>(typeArgs.size());
      for (JCTree.JCExpression typeArg : typeArgs) {
        args.add(fromJCTree(typeArg));
      }
      return new ParameterizedTypeTT(
          fromJCTree(((JCTree.JCTypeApply) jt).getType()),
          args);
    default:
      break;
    }
  }
  return null;
}
 
Example 6
Source File: Symbol.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public void setLazyConstValue(final Env<AttrContext> env,
                              final Attr attr,
                              final JCTree.JCExpression initializer)
{
    setData(new Callable<Object>() {
        public Object call() {
            return attr.attribLazyConstantValue(env, initializer, type);
        }
    });
}
 
Example 7
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
private static void parseUnionVariable(
    JCTree.JCVariableDecl vd,
    int preferredPos,
    Source src,
    JCTree typeTree,
    String vName,
    Range nameRange,
    JCTree.JCTypeUnion union) {

  for (JCTree.JCExpression expression : union.getTypeAlternatives()) {

    String type = expression.toString();
    Variable variable = new Variable(vName, preferredPos, nameRange);
    type = src.getImportedClassFQCN(type, type);

    if (vd.getTag().equals(JCTree.Tag.VARDEF)) {
      variable.isDef = true;
    }

    String typeSym = typeTree.toString();
    boolean markUnUse = requireImport(src, typeSym, type);
    log.trace("typeSym:{} type:{} markUnuse:{}", typeSym, type, markUnUse);

    if (nonNull(type)) {
      variable.fqcn = TreeAnalyzer.markFQCN(src, type, markUnUse);
      src.getCurrentScope()
          .ifPresent(
              scope -> {
                scope.addVariable(variable);
                addSymbolIndex(src, scope, variable);
              });
    }
  }
}
 
Example 8
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
private static void analyzeSimpleExpressions(
    SourceContext context, @Nullable List<JCTree.JCExpression> expressions) throws IOException {
  if (nonNull(expressions)) {
    for (JCTree.JCExpression expression : expressions) {
      analyzeParsedTree(context, expression);
    }
  }
}
 
Example 9
Source File: JavaParser.java    From manifold with Apache License 2.0 4 votes vote down vote up
public JCTree.JCExpression parseExpr( String expr, DiagnosticCollector<JavaFileObject> errorHandler )
{
  //!! Do not init() here; do not use _javac or _mfm for parseExpr() since this method is generally used
  //!! during the Parse phase, which happens earlier than the Enter phase where the plugin initializes much
  //!! of its state i.e., if parseExpr() is called before an Enter phase, it could use Manifold prematurely
  //!! and screw the pooch.  Also, we don't need Manifold for parsing expressions since it only produces a
  //!! simple AST with nothing resolved.
  // init();

  ArrayList<JavaFileObject> javaStringObjects = new ArrayList<>();
  String src =
    "class Sample {\n" +
    "  Object foo = " + expr + ";\n" +
    "}\n";
  javaStringObjects.add( new StringJavaFileObject( "sample", src ) );
  StringWriter errors = new StringWriter();
  BasicJavacTask javacTask = (BasicJavacTask)Objects.requireNonNull( _parserJavac.get() )
    .getTask( errors, null, errorHandler, Collections.singletonList( "-proc:none" ), null, javaStringObjects );
  try
  {
    initTypeProcessing( javacTask, Collections.singleton( "sample" ) );
    Iterable<? extends CompilationUnitTree> iterable = javacTask.parse();
    if( errors.getBuffer().length() > 0 )
    {
      System.err.println( errors.getBuffer() );
    }
    for( CompilationUnitTree x : iterable )
    {
      List<? extends Tree> typeDecls = x.getTypeDecls();
      if( !typeDecls.isEmpty() )
      {
        JCTree.JCClassDecl tree = (JCTree.JCClassDecl)typeDecls.get( 0 );
        JCTree.JCVariableDecl field = (JCTree.JCVariableDecl)tree.getMembers().get( 0 );
        return field.getInitializer();
      }
    }
    return null;
  }
  catch( Exception e )
  {
    return null;
  }
}
 
Example 10
Source File: JavaDynamicJdk_8.java    From manifold with Apache License 2.0 4 votes vote down vote up
@Override
public Symbol getOperator( JCTree.JCExpression tree )
{
  return tree instanceof JCTree.JCBinary ? ((JCTree.JCBinary)tree).operator : ((JCTree.JCUnary)tree).operator;
}
 
Example 11
Source File: CheckAttributedTree.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private boolean mandatoryType(JCTree that) {
    return that instanceof JCTree.JCExpression ||
            that.hasTag(VARDEF) ||
            that.hasTag(METHODDEF) ||
            that.hasTag(CLASSDEF);
}
 
Example 12
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 4 votes vote down vote up
public JCTree.JCExpression genericType(JavacNode node) {
  return func.call(node);
}
 
Example 13
Source File: BootstrapInserter.java    From manifold with Apache License 2.0 4 votes vote down vote up
private JCTree.JCExpression memberAccess( TreeMaker make, JavacElements javacElems, String path )
{
  return memberAccess( make, javacElems, path.split( "\\." ) );
}
 
Example 14
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 4 votes vote down vote up
private static void analyzeNewClass(
    SourceContext context, JCTree.JCNewClass newClass, int preferredPos, int endPos)
    throws IOException {
  Source src = context.source;
  EndPosTable endPosTable = context.endPosTable;
  boolean isParameter = context.parameter;
  boolean isArgument = context.argument;
  int argumentIndex = context.argumentIndex;

  List<JCTree.JCExpression> argumentExpressions = newClass.getArguments();
  java.util.List<String> arguments = getArgumentsType(context, argumentExpressions);

  context.parameter = isParameter;
  context.argument = isArgument;
  context.setArgumentIndex(argumentIndex);

  JCTree.JCExpression identifier = newClass.getIdentifier();
  String name = identifier.toString();

  int start = identifier.getStartPosition();
  int end = identifier.getEndPosition(endPosTable);
  Range nameRange = Range.create(src, start, end);

  Range range = Range.create(src, preferredPos + 4, endPos);
  MethodCall methodCall = new MethodCall(name, preferredPos, nameRange, range, true);

  Type type = identifier.type;
  getTypeString(src, type)
      .ifPresent(
          fqcn -> {
            methodCall.declaringClass = TreeAnalyzer.markFQCN(src, fqcn);
            methodCall.returnType = fqcn;
            methodCall.argumentIndex = argumentIndex;
            context.setArgumentFQCN(fqcn);
          });

  if (isNull(type) || type instanceof Type.ErrorType) {
    // add className to unknown
    ClassName className = new ClassName(name);
    String simpleName = className.getName();
    if (!src.getImportedClassMap().containsKey(simpleName)
        && !CachedASMReflector.getInstance().getGlobalClassIndex().containsKey(simpleName)) {
      src.addUnknown(simpleName);
    }
  }

  JCTree.JCClassDecl classBody = newClass.getClassBody();
  analyzeParsedTree(context, classBody);

  src.getCurrentScope()
      .ifPresent(
          scope -> {
            if (nonNull(arguments)) {
              methodCall.setArguments(arguments);
            }
            scope.addMethodCall(methodCall);
            addUsageIndex(src, methodCall);
          });
}
 
Example 15
Source File: CheckAttributedTree.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private boolean mandatoryType(JCTree that) {
    return that instanceof JCTree.JCExpression ||
            that.hasTag(VARDEF) ||
            that.hasTag(METHODDEF) ||
            that.hasTag(CLASSDEF);
}
 
Example 16
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 4 votes vote down vote up
private static void analyzeImports(CompilationUnitTree cut, Source src, EndPosTable endPosTable) {
  CachedASMReflector cachedASMReflector = CachedASMReflector.getInstance();

  long firstLine = 0;

  for (ImportTree imp : cut.getImports()) {
    JCTree.JCImport jcImport = (JCTree.JCImport) imp;
    int startPos = jcImport.getPreferredPosition();
    int endPos = jcImport.getEndPosition(endPosTable);
    Range range = Range.create(src, startPos + 1, endPos);
    firstLine = range.begin.line;

    String importClass = imp.getQualifiedIdentifier().toString();
    String simpleName = ClassNameUtils.getSimpleName(importClass);

    if (imp.isStatic()) {
      // TODO static asterisk
      Tree tree = imp.getQualifiedIdentifier();
      if (tree instanceof JCTree.JCFieldAccess) {
        JCTree.JCFieldAccess fieldAccess = (JCTree.JCFieldAccess) tree;
        com.sun.tools.javac.util.Name name = fieldAccess.getIdentifier();
        JCTree.JCExpression expression = fieldAccess.getExpression();
        String methodName = name.toString();
        String decClazz = expression.toString();
        src.addStaticImport(methodName, decClazz);
      } else {
        log.warn("Not impl");
      }
    } else {
      if (simpleName.equals("*")) {
        // wild
        for (String s : cachedASMReflector.getPackageClasses(importClass).values()) {
          src.addImport(s);
        }
      } else {
        src.addImport(importClass);
      }
    }
  }
  src.setClassStartLine(firstLine);
}
 
Example 17
Source File: StringLiteralTemplateProcessor.java    From manifold with Apache License 2.0 4 votes vote down vote up
public List<JCTree.JCExpression> parse( String stringValue, int literalOffset )
{
  List<StringLiteralTemplateParser.Expr> comps =
    StringLiteralTemplateParser.parse( new EscapeMatcher( _manDiagnosticHandler, literalOffset+1 ), stringValue );
  if( comps.isEmpty() )
  {
    return Collections.emptyList();
  }

  TreeMaker maker = TreeMaker.instance( _javacTask.getContext() );
  Names names = Names.instance( _javacTask.getContext() );

  List<JCTree.JCExpression> exprs = new ArrayList<>();
  StringLiteralTemplateParser.Expr prev = null;
  for( StringLiteralTemplateParser.Expr comp : comps )
  {
    JCTree.JCExpression expr;
    if( comp.isVerbatim() )
    {
      expr = maker.Literal( comp.getExpr() );
    }
    else
    {
      if( prev != null && !prev.isVerbatim() )
      {
        // enforce concatenation
        exprs.add( maker.Literal( "" ) );
      }

      int exprPos = literalOffset + 1 + comp.getOffset();

      if( comp.isIdentifier() )
      {
        JCTree.JCIdent ident = maker.Ident( names.fromString( comp.getExpr() ) );
        ident.pos = exprPos;
        expr = ident;
      }
      else
      {
        DiagnosticCollector<JavaFileObject> errorHandler = new DiagnosticCollector<>();
        expr = _tp.getHost().getJavaParser().parseExpr( comp.getExpr(), errorHandler );
        if( transferParseErrors( literalOffset, comp, expr, errorHandler ) )
        {
          return Collections.emptyList();
        }
        replaceNames( expr, exprPos );
      }
    }
    prev = comp;
    exprs.add( expr );
  }

  if( exprs.size() == 1 )
  {
    // insert an empty string so concat will make the expr a string
    exprs.add( 0, maker.Literal( "" ) );
  }

  return exprs;
}
 
Example 18
Source File: CheckAttributedTree.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private boolean mandatoryType(JCTree that) {
    return that instanceof JCTree.JCExpression ||
            that.hasTag(VARDEF) ||
            that.hasTag(METHODDEF) ||
            that.hasTag(CLASSDEF);
}
 
Example 19
Source File: HandleRuntimePermission.java    From EasyMPermission with MIT License 4 votes vote down vote up
private JCMethodDecl createIsPermissionGrantedMethod(JavacNode typeNode) {
    JavacTreeMaker treeMaker = typeNode.getTreeMaker();

    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();

    statements.append(Variable(typeNode)
            .modifiers(0)
            .name("ok")
            .type(treeMaker.TypeIdent(CTC_BOOLEAN))
            .value(treeMaker.Literal(CTC_BOOLEAN, 1))
            .build());

    statements.append(Variable(typeNode)
            .modifiers(0)
            .name("failed")
            .type(treeMaker.TypeIdent(CTC_BOOLEAN))
            .value(treeMaker.Literal(CTC_BOOLEAN, 0))
            .build());

    JCTree.JCExpression returnType = treeMaker.TypeIdent(CTC_BOOLEAN);

    List<JCTypeParameter> typleList = List.nil();

    List<JCVariableDecl> paramList = List.of(
            Variable(typeNode)
                    .modifiers(Flags.PARAMETER)
                    .name("permissions")
                    .type(treeMaker.TypeArray(genJavaLangTypeRef(typeNode, "String")))
                    .value(null)
                    .build()
    );

    JCVariableDecl v = Variable(typeNode)
            .modifiers(Flags.PARAMETER)
            .name("permission")
            .type(genJavaLangTypeRef(typeNode, "String"))
            .value(null)
            .build();

    JCExpression checkMethod = JavacHandlerUtil.chainDots(typeNode, "this", "checkSelfPermission");
    List<JCExpression> checkArgs = List.<JCExpression>of(treeMaker.Ident(typeNode.toName("permission")));
    JCMethodInvocation checkInvocation = treeMaker.Apply(List.<JCExpression>nil(), checkMethod, checkArgs);
    JCExpression cmp = treeMaker.Binary(CTC_NOT_EQUAL,
            checkInvocation,
            JavacHandlerUtil.chainDots(typeNode, "android", "content", "pm", "PackageManager", "PERMISSION_GRANTED"));

    JCBlock body = Block(typeNode)
            .last(treeMaker.Return(treeMaker.Ident(typeNode.toName("failed"))))
            .build();

    JCIf jcIf = If(typeNode)
            .condition(cmp)
            .onlyThen(body)
            .build();

    JCEnhancedForLoop block = treeMaker.ForeachLoop(v,
            treeMaker.Ident(typeNode.toName("permissions")),
            jcIf);
    statements.append(block);

    statements.append(treeMaker.Return(treeMaker.Ident(typeNode.toName("ok"))));

    body = Block(typeNode)
            .last(statements.toList())
            .build();

    return Method(typeNode)
            .modifiers(Flags.PRIVATE)
            .returnType(returnType)
            .name(IS_PERMISSION_GRANTED_METHOD)
            .paramType(typleList)
            .parameters(paramList)
            .thrown()
            .body(body)
            .build();
}
 
Example 20
Source File: IDynamicJdk.java    From manifold with Apache License 2.0 votes vote down vote up
Symbol getOperator( JCTree.JCExpression tree );