com.sun.tools.javac.tree.JCTree Java Examples

The following examples show how to use com.sun.tools.javac.tree.JCTree. 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: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** The class in which an access method for given symbol goes.
 *  @param sym        The access symbol
 *  @param protAccess Is access to a protected symbol in another
 *                    package?
 */
ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
    if (protAccess) {
        Symbol qualifier = null;
        ClassSymbol c = currentClass;
        if (tree.hasTag(SELECT) && (sym.flags() & STATIC) == 0) {
            qualifier = ((JCFieldAccess) tree).selected.type.tsym;
            while (!qualifier.isSubClass(c, types)) {
                c = c.owner.enclClass();
            }
            return c;
        } else {
            while (!c.isSubClass(sym.owner, types)) {
                c = c.owner.enclClass();
            }
        }
        return c;
    } else {
        // the symbol is private
        return sym.owner.enclClass();
    }
}
 
Example #2
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private static void analyzeAnnotationTree(
    final Source src, final EndPosTable endPosTable, final AnnotationTree at) {
  if (at instanceof JCTree.JCAnnotation) {
    JCTree.JCAnnotation anno = (JCTree.JCAnnotation) at;
    int startPos = anno.getPreferredPosition();
    int endPos = anno.getEndPosition(endPosTable);
    JCTree annotationType = anno.getAnnotationType();
    int annotationTypeEndPosition = annotationType.getEndPosition(endPosTable);
    Range range;
    if (endPos != annotationTypeEndPosition) {
      startPos = annotationTypeEndPosition;
    }
    range = Range.create(src, startPos + 1, endPos);
    Type type = anno.type;
    Annotation annotation;
    if (nonNull(type)) {
      annotation = new Annotation(type.toString(), startPos, range);
    } else {
      annotation = new Annotation(annotationType.toString(), startPos, range);
    }
    src.annotationMap.put(range.begin.line, annotation);
  }
}
 
Example #3
Source File: ImportStatementsTest.java    From Refaster with Apache License 2.0 6 votes vote down vote up
/**
 * A helper method to create a JCImport stub.
 *
 * @param typeName the fully-qualified name of the type being imported
 * @param isStatic whether the import is static
 * @param startPos the start position of the import statement
 * @param endPos the end position of the import statement
 * @return a new JCImport stub
 */
private static JCImport stubImport(String typeName, boolean isStatic, int startPos, int endPos) {
  JCImport result = mock(JCImport.class);
  when(result.isStatic()).thenReturn(isStatic);
  when(result.getStartPosition()).thenReturn(startPos);
  when(result.getEndPosition(anyMapOf(JCTree.class, Integer.class))).thenReturn(endPos);

  // craft import string
  StringBuilder returnSB = new StringBuilder("import ");
  if (isStatic) {
    returnSB.append("static ");
  }
  returnSB.append(typeName);
  returnSB.append(";\n");
  when(result.toString()).thenReturn(returnSB.toString());
  return result;
}
 
Example #4
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
@Override
public void visitAnnotation( JCTree.JCAnnotation tree )
{
  super.visitAnnotation( tree );
  if( tree.getAnnotationType().type == null || !Self.class.getTypeName().equals( tree.getAnnotationType().type.tsym.toString() ) )
  {
    return;
  }

  if( !isSelfInMethodDeclOrFieldDecl( tree, tree ) )
  {
    _tp.report( tree, Diagnostic.Kind.ERROR, ExtIssueMsg.MSG_SELF_NOT_ALLOWED_HERE.get() );
  }
  else
  {
    verifySelfOnThis( tree, tree );
  }
}
 
Example #5
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVarPos() throws IOException {

    final String code = "package t; class Test { " +
            "{ java.io.InputStream in = null; } }";

    CompilationUnitTree cut = getCompilationUnitTree(code);

    new TreeScanner<Void, Void>() {

        @Override
        public Void visitVariable(VariableTree node, Void p) {
            if ("in".contentEquals(node.getName())) {
                JCTree.JCVariableDecl var = (JCTree.JCVariableDecl) node;
                assertEquals("testVarPos","in = null; } }",
                        code.substring(var.pos));
            }
            return super.visitVariable(node, p);
        }
    }.scan(cut, null);
}
 
Example #6
Source File: DeferredAttr.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
<Z> JCTree attribSpeculative(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo, TreeCopier<Z> deferredCopier,
                             Function<JCTree, DeferredDiagnosticHandler> diagHandlerCreator,
                             LocalCacheContext localCache) {
    final JCTree newTree = deferredCopier.copy(tree);
    Env<AttrContext> speculativeEnv = env.dup(newTree, env.info.dup(env.info.scope.dupUnshared(env.info.scope.owner)));
    speculativeEnv.info.isSpeculative = true;
    Log.DeferredDiagnosticHandler deferredDiagnosticHandler = diagHandlerCreator.apply(newTree);
    try {
        attr.attribTree(newTree, speculativeEnv, resultInfo);
        return newTree;
    } finally {
        new UnenterScanner(env.toplevel.modle).scan(newTree);
        log.popDiagnosticHandler(deferredDiagnosticHandler);
        if (localCache != null) {
            localCache.leave();
        }
    }
}
 
Example #7
Source File: ReferenceParser.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private List<JCTree> parseParams(String s) throws ParseException {
    if (s.trim().isEmpty())
        return List.nil();

    JavacParser p = fac.newParser(s.replace("...", "[]"), false, false, false);
    ListBuffer<JCTree> paramTypes = new ListBuffer<>();
    paramTypes.add(p.parseType());

    if (p.token().kind == TokenKind.IDENTIFIER)
        p.nextToken();

    while (p.token().kind == TokenKind.COMMA) {
        p.nextToken();
        paramTypes.add(p.parseType());

        if (p.token().kind == TokenKind.IDENTIFIER)
            p.nextToken();
    }

    if (p.token().kind != TokenKind.EOF)
        throw new ParseException("dc.ref.unexpected.input");

    return paramTypes.toList();
}
 
Example #8
Source File: AbstractCodingRulesAnalyzer.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void finished(TaskEvent taskEvent) {
    if (taskEvent.getKind().equals(eventKind)) {
        TypeElement typeElem = taskEvent.getTypeElement();
        Tree tree = trees.getTree(typeElem);
        if (tree != null) {
            JavaFileObject prevSource = log.currentSourceFile();
            try {
                log.useSource(taskEvent.getCompilationUnit().getSourceFile());
                treeVisitor.scan((JCTree)tree);
            } finally {
                log.useSource(prevSource);
            }
        }
    }
}
 
Example #9
Source File: VeryPretty.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
   public void visitTry(JCTry tree) {
print("try");
       if (!tree.getResources().isEmpty()) {
           print(" ("); //XXX: space should be according to the code style!
           for (Iterator<? extends JCTree> it = tree.getResources().iterator(); it.hasNext();) {
               JCTree r = it.next();
               //XXX: disabling copying of original text, as the ending ';' needs to be removed in some cases.
               oldTrees.remove(r);
               printPrecedingComments(r, false);
               printExpr(r, 0);
               printTrailingComments(r, false);
               if (it.hasNext()) print(";");
           }
           print(") "); //XXX: space should be according to the code style!
       }
printBlock(tree.body, cs.getOtherBracePlacement(), cs.spaceBeforeTryLeftBrace());
for (List < JCCatch > l = tree.catchers; l.nonEmpty(); l = l.tail)
    printStat(l.head);
if (tree.finalizer != null) {
    printFinallyBlock(tree.finalizer);
}
   }
 
Example #10
Source File: DPrinter.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
protected void printObject(String label, Object item, Details details) {
    if (item == null) {
        printNull(label);
    } else if (item instanceof Attribute) {
        printAttribute(label, (Attribute) item);
    } else if (item instanceof Symbol) {
        printSymbol(label, (Symbol) item, details);
    } else if (item instanceof Type) {
        printType(label, (Type) item, details);
    } else if (item instanceof JCTree) {
        printTree(label, (JCTree) item);
    } else if (item instanceof List) {
        printList(label, (List) item);
    } else if (item instanceof Name) {
        printName(label, (Name) item);
    } else {
        printString(label, String.valueOf(item));
    }
}
 
Example #11
Source File: TreeMirrorMaker.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public JCTree visitVariable(VariableTree node, Void p) {
	JCVariableDecl original = node instanceof JCVariableDecl ? (JCVariableDecl) node : null;
	JCVariableDecl copy = (JCVariableDecl) super.visitVariable(node, p);
	if (original == null) return copy;
	
	copy.sym = original.sym;
	if (copy.sym != null) copy.type = original.type;
	if (copy.type != null) {
		boolean wipeSymAndType = copy.type.isErroneous();
		if (!wipeSymAndType) {
			TypeTag typeTag = TypeTag.typeTag(copy.type);
			wipeSymAndType = (CTC_NONE.equals(typeTag) || CTC_ERROR.equals(typeTag) || CTC_UNKNOWN.equals(typeTag) || CTC_UNDETVAR.equals(typeTag));
		}
		
		if (wipeSymAndType) {
			copy.sym = null;
			copy.type = null;
		}
	}
	
	return copy;
}
 
Example #12
Source File: JavacTrees.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public JCTree getTree(Element element) {
    Symbol symbol = (Symbol) element;
    TypeSymbol enclosing = symbol.enclClass();
    Env<AttrContext> env = enter.getEnv(enclosing);
    if (env == null)
        return null;
    JCClassDecl classNode = env.enclClass;
    if (classNode != null) {
        if (TreeInfo.symbolFor(classNode) == element)
            return classNode;
        for (JCTree node : classNode.getMembers())
            if (TreeInfo.symbolFor(node) == element)
                return node;
    }
    return null;
}
 
Example #13
Source File: VeryPretty.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isFirst(JCTree tree, List<? extends JCTree> list) {
    for (JCTree t : list) {
        if (!isSynthetic(t)) {
            return t == tree;
        }
    }
    return false;
}
 
Example #14
Source File: TypeAnnotationsPretty.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void checkMatch(String code, JCTree tree) {
    String expect = code.replace("\n", NL);
    String found = tree.toString();
    if (!expect.equals(found)) {
        mismatches.add("Expected: " + expect + NL +
                "Obtained: " + found);
    } else {
        matches.add("Passed: " + expect);
    }
}
 
Example #15
Source File: TransTypes.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Visitor method: perform a type translation on list of trees.
 */
public <T extends JCTree> List<T> translate(List<T> trees, Type pt) {
    Type prevPt = this.pt;
    List<T> res;
    try {
        this.pt = pt;
        res = translate(trees);
    } finally {
        this.pt = prevPt;
    }
    return res;
}
 
Example #16
Source File: VeryPretty.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void printStats(List < ? extends JCTree > trees, boolean members) {
       java.util.List<JCTree> filtered = CasualDiff.filterHidden(diffContext, trees);

       if (!filtered.isEmpty() && handlePossibleOldTrees(filtered, true)) return;

       boolean first = true;
for (JCTree t : filtered) {
     printStat(t, members, first, true, false, false);
           first = false;
}
   }
 
Example #17
Source File: CheckAttributedTree.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
Info(JCTree tree, EndPosTable endPosTable) {
    this.tree = tree;
    tag = tree.getTag();
    start = TreeInfo.getStartPos(tree);
    pos = tree.pos;
    end = TreeInfo.getEndPos(tree, endPosTable);
}
 
Example #18
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Symbol getEnclosingSymbol( Tree tree, Context ctx )
{
  if( tree == null )
  {
    return null;
  }
  if( tree instanceof JCTree.JCClassDecl )
  {
    // should not really get here, but should be static block scope if possible
    return new Symbol.MethodSymbol( STATIC | BLOCK,
      Names.instance( ctx ).empty, null, ((JCTree.JCClassDecl)tree).sym );
  }
  if( tree instanceof JCTree.JCMethodDecl )
  {
    return ((JCTree.JCMethodDecl)tree).sym;
  }
  if( tree instanceof JCTree.JCVariableDecl )
  {
    Tree parent = _tp.getParent( tree );
    if( parent instanceof JCTree.JCClassDecl )
    {
      // field initializers have a block scope
      return new Symbol.MethodSymbol( (((JCTree.JCVariableDecl)tree).mods.flags & STATIC) | BLOCK,
        Names.instance( ctx ).empty, null, ((JCTree.JCClassDecl)parent).sym );
    }
  }
  return getEnclosingSymbol( _tp.getParent( tree ), ctx );
}
 
Example #19
Source File: CheckAttributedTree.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void test(List<Pair<JCCompilationUnit, JCTree>> trees) {
    for (Pair<JCCompilationUnit, JCTree> p : trees) {
        sourcefile = p.fst.sourcefile;
        endPosTable = p.fst.endPositions;
        encl = new Info(p.snd, endPosTable);
        p.snd.accept(this);
    }
}
 
Example #20
Source File: ManResolve.java    From manifold with Apache License 2.0 5 votes vote down vote up
private boolean isJailbreakOnType()
{
  JCTree.JCAnnotatedType annotatedType = ((ManAttr)_attr).peekAnnotatedType();
  if( annotatedType != null )
  {
    return annotatedType.toString().contains( "@Jailbreak" );
  }
  return false;
}
 
Example #21
Source File: JavaUtil.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public static String findImportedClassName(@NonNull JCTree.JCCompilationUnit mUnit,
                                           @NonNull String className) {
    List<JCTree.JCImport> imports = mUnit.getImports();
    for (JCTree.JCImport jcImport : imports) {
        String fullName = jcImport.getQualifiedIdentifier().toString();
        if (fullName.equals(className) || fullName.endsWith("." + className)) {
            return fullName;
        }
    }
    return className;
}
 
Example #22
Source File: TreeFinder.java    From annotation-tools with MIT License 5 votes vote down vote up
private void addNewType(TreePath path, NewInsertion neu,
    NewArrayTree newArray) {
  DeclaredType baseType = neu.getBaseType();
  if (baseType.getName().isEmpty()) {
    List<String> annotations = neu.getType().getAnnotations();
    Type newType = Insertions.TypeTree.javacTypeToType(
        ((JCTree.JCNewArray) newArray).type);
    for (String ann : annotations) {
      newType.addAnnotation(ann);
    }
    neu.setType(newType);
  }
  Insertion.decorateType(neu.getInnerTypeInsertions(), neu.getType(),
      neu.getCriteria().getASTPath());
}
 
Example #23
Source File: Test.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void checkEndPos(CompilationUnitTree unit, Tree tree) {
    long sp = srcPosns.getStartPosition(unit, tree);
    long ep = srcPosns.getEndPosition(unit, tree);
    if (sp >= 0 && ep == Position.NOPOS) {
        error("endpos not set for " + tree.getKind()
                + " " + Pretty.toSimpleString(((JCTree) tree))
                +", start:" + sp);
    }
}
 
Example #24
Source File: TestLog.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void visitIf(JCTree.JCIf tree) {
    JCDiagnostic.DiagnosticPosition nil = null;
    // generate dummy messages to exercise the log API
    log.error("not.stmt");
    log.error(tree.pos, "not.stmt");
    log.error(tree.pos(), "not.stmt");
    log.error(nil, "not.stmt");

    log.warning("div.zero");
    log.warning(tree.pos, "div.zero");
    log.warning(tree.pos(), "div.zero");
    log.warning(nil, "div.zero");
}
 
Example #25
Source File: Test.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void checkEndPos(CompilationUnitTree unit, Tree tree) {
    long sp = srcPosns.getStartPosition(unit, tree);
    long ep = srcPosns.getEndPosition(unit, tree);
    if (sp >= 0 && ep == Position.NOPOS) {
        error("endpos not set for " + tree.getKind()
                + " " + Pretty.toSimpleString(((JCTree) tree))
                +", start:" + sp);
    }
}
 
Example #26
Source File: ArgumentAttr.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Process a method argument; this method takes care of performing a speculative pass over the
 * argument tree and calling a well-defined entry point to build the argument type associated
 * with such tree.
 */
@SuppressWarnings("unchecked")
<T extends JCExpression, Z extends ArgumentType<T>> void processArg(T that, Function<T, Z> argumentTypeFactory) {
    UniquePos pos = new UniquePos(that);
    processArg(that, () -> {
        T speculativeTree = (T)deferredAttr.attribSpeculative(that, env, attr.new MethodAttrInfo() {
            @Override
            protected boolean needsArgumentAttr(JCTree tree) {
                return !new UniquePos(tree).equals(pos);
            }
        });
        return argumentTypeFactory.apply(speculativeTree);
    });
}
 
Example #27
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
@Override
public MethodModel visitMethod(MethodTree node, VisitContext p) {
  List<TypeInfo> parameterTypes = new ArrayList<>();
  for (VariableTree var : node.getParameters()) {
    JCTree.JCVariableDecl decl = (JCTree.JCVariableDecl) var;
    TypeInfo parameterType = factory.create(decl.sym.asType());
    parameterTypes.add(parameterType);
  }
  TypeInfo returnType = VoidTypeInfo.INSTANCE;
  if (node.getReturnType() instanceof JCTree) {
    returnType = factory.create(((JCTree)node.getReturnType()).type);
  }
  return new MethodModel("" + typeElt.getQualifiedName(), scan(node.getBody(), p), new MethodSignature(node.getName().toString(), parameterTypes, false, returnType), node.getParameters().stream().map(param -> param.getName().toString()).collect(Collectors.toList()));
}
 
Example #28
Source File: Operators.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Entry point for resolving a unary operator given an operator tag and an argument type.
 */
OperatorSymbol resolveUnary(DiagnosticPosition pos, JCTree.Tag tag, Type op) {
    return resolve(tag,
            unaryOperators,
            unop -> unop.test(op),
            unop -> unop.resolve(op),
            () -> reportErrorIfNeeded(pos, tag, op));
}
 
Example #29
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) {
    if (warnOnAnyAccessToMembers ||
        (lint.isEnabled(LintCategory.SERIAL) &&
        !lint.isSuppressed(LintCategory.SERIAL) &&
        isLambda)) {
        Symbol sym = TreeInfo.symbol(tree);
        if (!sym.kind.matches(KindSelector.VAL_MTH)) {
            return;
        }

        if (sym.kind == VAR) {
            if ((sym.flags() & PARAMETER) != 0 ||
                sym.isLocal() ||
                sym.name == names._this ||
                sym.name == names._super) {
                return;
            }
        }

        if (!types.isSubtype(sym.owner.type, syms.serializableType) &&
            isEffectivelyNonPublic(sym)) {
            if (isLambda) {
                if (belongsToRestrictedPackage(sym)) {
                    log.warning(LintCategory.SERIAL, tree.pos(),
                                Warnings.AccessToMemberFromSerializableLambda(sym));
                }
            } else {
                log.warning(tree.pos(),
                            Warnings.AccessToMemberFromSerializableElement(sym));
            }
        }
    }
}
 
Example #30
Source File: VeryPretty.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private int getOldPos(JCTree oldT) {
    if (overrideStartPositions != null) {
        Integer i = overrideStartPositions.get(oldT);
        if (i != null) {
            return i;
        }
    }
    return TreeInfo.getStartPos(oldT);
}