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

The following examples show how to use com.sun.tools.javac.tree.JCTree. These examples are extracted from open source projects. 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
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 2
Source Project: Refaster   Source File: ImportStatementsTest.java    License: 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 3
Source Project: openjdk-jdk9   Source File: JavacParserTest.java    License: 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 4
Source Project: manifold   Source File: ExtensionTransformer.java    License: 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
<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 6
Source Project: openjdk-jdk9   Source File: ReferenceParser.java    License: 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 7
@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 8
Source Project: netbeans   Source File: VeryPretty.java    License: 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 9
Source Project: openjdk-8-source   Source File: DPrinter.java    License: 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 10
Source Project: EasyMPermission   Source File: TreeMirrorMaker.java    License: 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 11
Source Project: jdk8u60   Source File: JavacTrees.java    License: 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 12
/** 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 13
Source Project: openjdk-jdk8u   Source File: Test.java    License: 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 14
Source Project: openjdk-8   Source File: JavacElements.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the tree node and compilation unit corresponding to this
 * element, or null if they can't be found.
 */
private Pair<JCTree, JCCompilationUnit> getTreeAndTopLevel(Element e) {
    Symbol sym = cast(Symbol.class, e);
    Env<AttrContext> enterEnv = getEnterEnv(sym);
    if (enterEnv == null)
        return null;
    JCTree tree = TreeInfo.declarationFor(sym, enterEnv.tree);
    if (tree == null || enterEnv.toplevel == null)
        return null;
    return new Pair<JCTree,JCCompilationUnit>(tree, enterEnv.toplevel);
}
 
Example 15
Source Project: netbeans   Source File: VeryPretty.java    License: 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 16
Source Project: netbeans   Source File: VeryPretty.java    License: 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 17
Source Project: openjdk-8   Source File: LVTRanges.java    License: GNU General Public License v2.0 5 votes vote down vote up
public List<VarSymbol> removeEntry(MethodSymbol method, JCTree tree) {
    Map<JCTree, List<VarSymbol>> varMap = aliveRangeClosingTrees.get(method);
    if (varMap != null) {
        List<VarSymbol> result = varMap.remove(tree);
        if (varMap.isEmpty()) {
            aliveRangeClosingTrees.remove(method);
        }
        return result;
    }
    return null;
}
 
Example 18
Source Project: jdk8u60   Source File: DPrinter.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void printSymbol(String label, Symbol sym, Details details) {
    if (sym == null) {
        printNull(label);
    } else {
        switch (details) {
        case SUMMARY:
            printString(label, toString(sym));
            break;

        case FULL:
            indent();
            out.print(label);
            out.println(": " +
                    info(sym.getClass(),
                        String.format("0x%x--%s", sym.kind, Kinds.kindName(sym)),
                        sym.getKind())
                    + " " + sym.name
                    + " " + hashString(sym));

            indent(+1);
            if (showSrc) {
                JCTree tree = (JCTree) trees.getTree(sym);
                if (tree != null)
                    printSource("src", tree);
            }
            printString("flags", String.format("0x%x--%s",
                    sym.flags_field, Flags.toString(sym.flags_field)));
            printObject("completer", sym.completer, Details.SUMMARY); // what if too long?
            printSymbol("owner", sym.owner, Details.SUMMARY);
            printType("type", sym.type, Details.SUMMARY);
            printType("erasure", sym.erasure_field, Details.SUMMARY);
            sym.accept(symVisitor, null);
            printAnnotations("annotations", sym.getAnnotations(), Details.SUMMARY);
            indent(-1);
        }
    }
}
 
Example 19
/** Visitor method: compute source positions for a single node.
 */
public SourceRange csp(JCTree tree) {
    if (tree == null) return null;
    tree.accept(this);
    if (result != null) {
        positions.put(tree, result);
    }
    return result;
}
 
Example 20
private void runField(String code) throws IOException {
    String src = prefix +
            code + "; }" +
            postfix;

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));

    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCVariableDecl var =
                (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
        checkMatch(code, var);
    }
}
 
Example 21
/** Get the line number for the primary position for a tree.
 * The code is intended to be simple, although not necessarily efficient.
 * However, note that a file manager such as JavacFileManager is likely
 * to cache the results of file.getCharContent, avoiding the need to read
 * the bits from disk each time this method is called.
 */
int getLine(JavaFileObject file, JCTree tree) {
    try {
        CharSequence cs = file.getCharContent(true);
        int line = 1;
        for (int i = 0; i < tree.pos; i++) {
            if (cs.charAt(i) == '\n') // jtreg tests always use Unix line endings
                line++;
        }
        return line;
    } catch (IOException e) {
        return -1;
    }
}
 
Example 22
Source Project: openjdk-jdk9   Source File: StringConcat.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Item makeConcat(JCTree.JCAssignOp tree) {
    List<JCTree> args = collectAll(tree.lhs, tree.rhs);
    Item l = gen.genExpr(tree.lhs, tree.lhs.type);
    emit(args, tree.type, tree.pos());
    return l;
}
 
Example 23
/**
 * Get the set of fields for a tree node that may contain child tree nodes.
 * These are the fields that are subtypes of JCTree or List.
 * The results are cached, based on the tree's tag.
 */
Set<Field> getFields(JCTree tree) {
    Set<Field> fields = map.get(tree.getTag());
    if (fields == null) {
        fields = new HashSet<Field>();
        for (Field f: tree.getClass().getFields()) {
            Class<?> fc = f.getType();
            if (JCTree.class.isAssignableFrom(fc) || List.class.isAssignableFrom(fc))
                fields.add(f);
        }
        map.put(tree.getTag(), fields);
    }
    return fields;
}
 
Example 24
Source Project: openjdk-jdk9   Source File: TypeAnnotations.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void scan(JCTree tree) {
    push(tree);
    try {
        super.scan(tree);
    } finally {
        pop();
    }
}
 
Example 25
/**
 * Returns the tree node and compilation unit corresponding to this
 * element, or null if they can't be found.
 */
private Pair<JCTree, JCCompilationUnit> getTreeAndTopLevel(Element e) {
    Symbol sym = cast(Symbol.class, e);
    Env<AttrContext> enterEnv = getEnterEnv(sym);
    if (enterEnv == null)
        return null;
    JCTree tree = TreeInfo.declarationFor(sym, enterEnv.tree);
    if (tree == null || enterEnv.toplevel == null)
        return null;
    return new Pair<JCTree,JCCompilationUnit>(tree, enterEnv.toplevel);
}
 
Example 26
Source Project: openjdk-jdk9   Source File: Annotate.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Enqueue tree for scanning of type annotations, attaching to the Symbol sym.
 */
public void queueScanTreeAndTypeAnnotate(JCTree tree, Env<AttrContext> env, Symbol sym,
        DiagnosticPosition deferPos)
{
    Assert.checkNonNull(sym);
    normal(() -> tree.accept(new TypeAnnotate(env, sym, deferPos)));
}
 
Example 27
Source Project: jdk8u60   Source File: JavacTrees.java    License: GNU General Public License v2.0 5 votes vote down vote up
public DocCommentTree getDocCommentTree(TreePath path) {
    CompilationUnitTree t = path.getCompilationUnit();
    Tree leaf = path.getLeaf();
    if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
        JCCompilationUnit cu = (JCCompilationUnit) t;
        if (cu.docComments != null) {
            return cu.docComments.getCommentTree((JCTree) leaf);
        }
    }
    return null;
}
 
Example 28
private Type generateReferenceToTargetConstraint(JCTree tree, UndetVar from,
        Type to, Attr.ResultInfo resultInfo,
        InferenceContext inferenceContext) {
    inferenceContext.solve(List.of(from.qtype), new Warner());
    inferenceContext.notifyChange();
    Type capturedType = resultInfo.checkContext.inferenceContext()
            .cachedCapture(tree, from.getInst(), !resultInfo.checkMode.updateTreeType());
    if (types.isConvertible(capturedType,
            resultInfo.checkContext.inferenceContext().asUndetVar(to))) {
        //effectively skip additional return-type constraint generation (compatibility)
        return syms.objectType;
    }
    return to;
}
 
Example 29
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 Project: javaide   Source File: ExpressionResolver.java    License: GNU General Public License v3.0 5 votes vote down vote up
private boolean isCursorInsideTree(JCTree tree) {
    if (tree == null) {
        return false;
    }
    int startPosition = tree.getStartPosition();
    int endPosition = tree.getEndPosition(mEndPositions);
    return startPosition <= mCursor && mCursor <= endPosition;
}