Java Code Examples for com.sun.source.tree.ExpressionTree#toString()

The following examples show how to use com.sun.source.tree.ExpressionTree#toString() . 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: BreadCrumbsNodeImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static String className(TreePath path) {
    ClassTree ct = (ClassTree) path.getLeaf();
    
    if (path.getParentPath().getLeaf().getKind() == Kind.NEW_CLASS) {
        NewClassTree nct = (NewClassTree) path.getParentPath().getLeaf();
        
        if (nct.getClassBody() == ct) {
            return simpleName(nct.getIdentifier());
        }
    } else if (path.getParentPath().getLeaf() == path.getCompilationUnit()) {
        ExpressionTree pkg = path.getCompilationUnit().getPackageName();
        String pkgName = pkg != null ? pkg.toString() : null;
        if (pkgName != null && !pkgName.contentEquals(ERR_NAME)) {
            return pkgName + '.' + ct.getSimpleName().toString();
        }
    }
    
    return ct.getSimpleName().toString();
}
 
Example 2
Source File: StringLiteralTemplateProcessor.java    From manifold with Apache License 2.0 6 votes vote down vote up
private boolean isTypeExcluded( JCTree.JCClassDecl classDef, CompilationUnitTree compilationUnit )
{
  if( _processorGates.isEmpty() )
  {
    return false;
  }

  ExpressionTree pkgName = compilationUnit.getPackageName();
  if( pkgName == null )
  {
    return false;
  }

  String simpleName = classDef.name.toString();
  String fqn = pkgName.toString() + '.' + simpleName;
  return _processorGates.stream().anyMatch( gate -> gate.exclude( fqn ) );
}
 
Example 3
Source File: JavacPlugin.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void addInputFile( TaskEvent e )
{
  if( !_initialized )
  {
    CompilationUnitTree compilationUnit = e.getCompilationUnit();
    ExpressionTree pkg = compilationUnit.getPackageName();
    String packageQualifier = pkg == null ? "" : (pkg.toString() + '.');
    for( Tree classDecl : compilationUnit.getTypeDecls() )
    {
      if( classDecl instanceof JCTree.JCClassDecl )
      {
        _javaInputFiles.add( new Pair<>( packageQualifier + ((JCTree.JCClassDecl)classDecl).getSimpleName(), compilationUnit.getSourceFile() ) );
      }
    }
  }
}
 
Example 4
Source File: IsSigMethodCriterion.java    From annotation-tools with MIT License 6 votes vote down vote up
private static Context initImports(TreePath path) {
  CompilationUnitTree topLevel = path.getCompilationUnit();
  Context result = contextCache.get(topLevel);
  if (result != null) {
    return result;
  }

  ExpressionTree packageTree = topLevel.getPackageName();
  String packageName;
  if (packageTree == null) {
    packageName = ""; // the default package
  } else {
    packageName = packageTree.toString();
  }

  List<String> imports = new ArrayList<>();
  for (ImportTree i : topLevel.getImports()) {
    String imported = i.getQualifiedIdentifier().toString();
    imports.add(imported);
  }

  result = new Context(packageName, imports);
  contextCache.put(topLevel, result);
  return result;
}
 
Example 5
Source File: PackageReferenceCollector.java    From deptective with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onEnteringCompilationUnit(CompilationUnitTree tree) {
    ExpressionTree packageNameTree = tree.getPackageName();

    // TODO deal with default package
    if (packageNameTree == null) {
        return false;
    }

    currentPackageName = packageNameTree.toString();
    packagesOfCurrentCompilation.add(currentPackageName);

    try {
        currentComponent = declaredComponents.getComponentByPackage(currentPackageName);
    }
    catch (PackageAssignedToMultipleComponentsException e) {
        log.report(
                ReportingPolicy.ERROR,
                DeptectiveMessages.PACKAGE_CONTAINED_IN_MULTIPLE_COMPONENTS,
                String.join(
                        ", ",
                        e.getMatchingComponents()
                                .stream()
                                .map(Component::getName)
                                .sorted()
                                .collect(Collectors.toList())
                ),
                currentPackageName
        );

        createOutputFile = false;
        return false;
    }

    if (currentComponent == null) {
        builder.addContains(currentPackageName, PackagePattern.getPattern(currentPackageName));
    }

    return true;
}
 
Example 6
Source File: PackageReferenceValidator.java    From deptective with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onEnteringCompilationUnit(CompilationUnitTree tree) {
    ExpressionTree packageNameTree = tree.getPackageName();

    // TODO deal with default package
    if (packageNameTree == null) {
        return false;
    }

    String packageName = packageNameTree.toString();
    currentPackageName = packageName;

    try {
        currentComponent = allowedPackageDependencies.getComponentByPackage(packageName);

        if (currentComponent == null) {
            reportUnconfiguredPackageIfNeeded(tree, packageName);
        }
    }
    catch (PackageAssignedToMultipleComponentsException e) {
        log.report(
                ReportingPolicy.ERROR,
                DeptectiveMessages.PACKAGE_CONTAINED_IN_MULTIPLE_COMPONENTS,
                String.join(
                        ", ",
                        e.getMatchingComponents()
                                .stream()
                                .map(Component::getName)
                                .sorted()
                                .collect(Collectors.toList())
                ),
                packageName
        );

        createDotFile = false;
        return false;
    }

    return true;
}
 
Example 7
Source File: PackageReferenceCollector.java    From deptective with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onEnteringCompilationUnit(CompilationUnitTree tree) {
    ExpressionTree packageNameTree = tree.getPackageName();

    // TODO deal with default package
    if (packageNameTree == null) {
        return false;
    }

    currentPackageName = packageNameTree.toString();
    packagesOfCurrentCompilation.add(currentPackageName);

    try {
        currentComponent = declaredComponents.getComponentByPackage(currentPackageName);
    }
    catch (PackageAssignedToMultipleComponentsException e) {
        log.report(
                ReportingPolicy.ERROR,
                DeptectiveMessages.PACKAGE_CONTAINED_IN_MULTIPLE_COMPONENTS,
                String.join(
                        ", ",
                        e.getMatchingComponents()
                                .stream()
                                .map(Component::getName)
                                .sorted()
                                .collect(Collectors.toList())
                ),
                currentPackageName
        );

        createOutputFile = false;
        return false;
    }

    if (currentComponent == null) {
        builder.addContains(currentPackageName, PackagePattern.getPattern(currentPackageName));
    }

    return true;
}
 
Example 8
Source File: PackageReferenceValidator.java    From deptective with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onEnteringCompilationUnit(CompilationUnitTree tree) {
    ExpressionTree packageNameTree = tree.getPackageName();

    // TODO deal with default package
    if (packageNameTree == null) {
        return false;
    }

    String packageName = packageNameTree.toString();
    currentPackageName = packageName;

    try {
        currentComponent = allowedPackageDependencies.getComponentByPackage(packageName);

        if (currentComponent == null) {
            reportUnconfiguredPackageIfNeeded(tree, packageName);
        }
    }
    catch (PackageAssignedToMultipleComponentsException e) {
        log.report(
                ReportingPolicy.ERROR,
                DeptectiveMessages.PACKAGE_CONTAINED_IN_MULTIPLE_COMPONENTS,
                String.join(
                        ", ",
                        e.getMatchingComponents()
                                .stream()
                                .map(Component::getName)
                                .sorted()
                                .collect(Collectors.toList())
                ),
                packageName
        );

        createDotFile = false;
        return false;
    }

    return true;
}
 
Example 9
Source File: JavadocGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * computes name of throws clause to work around
 * <a href="http://www.netbeans.org/issues/show_bug.cgi?id=160414">issue 160414</a>.
 */
private static String resolveThrowsName(Element el, String fqn, ExpressionTree throwTree) {
    boolean nestedClass = ElementKind.CLASS == el.getKind()
            && NestingKind.TOP_LEVEL != ((TypeElement) el).getNestingKind();
    String insertName = nestedClass ? fqn : throwTree.toString();
    return insertName;
}
 
Example 10
Source File: JavacPlugin.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void process( TaskEvent e )
{
  Set<String> typesToProcess = new HashSet<>();
  ExpressionTree pkg = e.getCompilationUnit().getPackageName();
  String packageQualifier = pkg == null ? "" : (pkg.toString() + '.');
  for( Tree classDecl : e.getCompilationUnit().getTypeDecls() )
  {
    if( classDecl instanceof JCTree.JCClassDecl )
    {
      typesToProcess.add( packageQualifier + ((JCTree.JCClassDecl)classDecl).getSimpleName() );
      insertBootstrap( (JCTree.JCClassDecl)classDecl );
    }
  }
  _typeProcessor.addTypesToProcess( typesToProcess );
}
 
Example 11
Source File: ASTIndex.java    From annotation-tools with MIT License 5 votes vote down vote up
public static Tree getNode(CompilationUnitTree cut, ASTRecord rec) {
  Map<Tree, ASTRecord> fwdIndex = ((ASTIndex) indexOf(cut)).back;
  Map<ASTRecord, Tree> revIndex =
      ((BiMap<Tree, ASTRecord>) fwdIndex).inverse();
  ExpressionTree et = cut.getPackageName();
  String pkg = et == null ? "" : et.toString();
  if (!pkg.isEmpty() && rec.className.indexOf('.') < 0) {
    rec = new ASTRecord(cut, pkg + "." + rec.className,
        rec.methodName, rec.varName, rec.astPath);
  }
  return revIndex.get(rec);
}
 
Example 12
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static String getMemberName(ExpressionTree node) {
  switch (node.getKind()) {
    case IDENTIFIER:
      return node.toString();
    case MEMBER_SELECT:
      return ((MemberSelectTree) node).getIdentifier().toString();
    default:
      return null;
  }
}
 
Example 13
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private PackageDeclaration convertPackage(TreePath parent) {
  ExpressionTree pkgName = unit.getPackageName();
  PackageElement pkg =
      pkgName != null
          ? env.elementUtilities().getPackageElement(pkgName.toString())
          : env.defaultPackage();
  PackageDeclaration newNode = null;
  if (pkg == null) {
    // Synthetic package, create from name.
    pkg = new GeneratedPackageElement(pkgName != null ? pkgName.toString() : "");
    newNode = new PackageDeclaration().setPackageElement(pkg);
    newNode.setName(new SimpleName(pkg, null));
  } else {
    Tree node = trees.getTree(pkg);
    newNode = new PackageDeclaration().setPackageElement(pkg);
    for (AnnotationTree pkgAnnotation : unit.getPackageAnnotations()) {
      newNode.addAnnotation((Annotation) convert(pkgAnnotation, parent));
    }
    if (unit.getSourceFile().toUri().getPath().endsWith("package-info.java")) {
      if (node == null) {
        // Java 8 javac bug, fixed in Java 9. Doc-comments in package-info.java
        // sources are keyed to their compilation unit, not their package node.
        node = unit;
      }
      newNode.setJavadoc((Javadoc) getAssociatedJavaDoc(node, getTreePath(parent, node)));
    }
    newNode.setName(newUnit.getEnv().elementUtil().getPackageName(pkg));
  }
  newNode.setPosition(SourcePosition.NO_POSITION);
  return newNode;
}
 
Example 14
Source File: JavaFixAllImports.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private ImportVisitor (CompilationInfo info) {
    this.info = info;
    ExpressionTree pkg = info.getCompilationUnit().getPackageName();
    currentPackage = pkg != null ? pkg.toString() : "";
    imports = new ArrayList<TreePathHandle>();
}
 
Example 15
Source File: Analyzer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
    public Void visitThrows(ThrowsTree tree, List<ErrorDescription> errors) {
        boolean oldInheritDoc = foundInheritDoc;
        ReferenceTree exName = tree.getExceptionName();
        DocTreePath refPath = new DocTreePath(getCurrentPath(), tree.getExceptionName());
        Element ex = javac.getDocTrees().getElement(refPath);
        Types types = javac.getTypes();
        Elements elements = javac.getElements();
        final TypeElement throwableEl = elements.getTypeElement("java.lang.Throwable");
        final TypeElement errorEl = elements.getTypeElement("java.lang.Error");
        final TypeElement runtimeEl = elements.getTypeElement("java.lang.RuntimeException");
        if(throwableEl == null || errorEl == null || runtimeEl == null) {
            LOG.warning("Broken java-platform, cannot resolve " + throwableEl == null? "java.lang.Throwable" : errorEl == null? "java.lang.Error" : "java.lang.RuntimeException"); //NOI18N
            return null;
        }
        TypeMirror throwable = throwableEl.asType();
        TypeMirror error = errorEl.asType();
        TypeMirror runtime = runtimeEl.asType();
        DocTreePath currentDocPath = getCurrentPath();
        DocTreePathHandle dtph = DocTreePathHandle.create(currentDocPath, javac);
        if(dtph == null) {
            return null;
        }
        DocSourcePositions sp = (DocSourcePositions) javac.getTrees().getSourcePositions();
        int start = (int) sp.getStartPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), tree);
        int end = (int) sp.getEndPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), tree);
        if (ex == null || (ex.asType().getKind() == TypeKind.DECLARED
                && types.isAssignable(ex.asType(), throwable))) {
            switch (currentElement.getKind()) {
                case CONSTRUCTOR:
                case METHOD:
                    if (ex == null || !(types.isAssignable(ex.asType(), error)
                            || types.isAssignable(ex.asType(), runtime))) {
                        ExecutableElement ee = (ExecutableElement) currentElement;
                        String fqn;
                        if (ex != null) {
                            fqn = ((TypeElement) ex).getQualifiedName().toString();
                        } else {
                            ExpressionTree referenceClass = javac.getTreeUtilities().getReferenceClass(new DocTreePath(currentDocPath, exName));
                            if(referenceClass == null) break;
                            fqn = referenceClass.toString();
                        }
                        checkThrowsDeclared(tree, ex, fqn, ee.getThrownTypes(), dtph, start, end, errors);
                    }
                    break;
                default:
//                        env.messages.error(REFERENCE, tree, "dc.invalid.throws");
            }
        } else {
//                env.messages.error(REFERENCE, tree, "dc.invalid.throws");
        }
        warnIfEmpty(tree, tree.getDescription());
        super.visitThrows(tree, errors);
        foundInheritDoc = oldInheritDoc;
        return null;
    }
 
Example 16
Source File: Eval.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private List<Snippet> processExpression(String userSource, String compileSource) {
    String name = null;
    ExpressionInfo ei = ExpressionToTypeInfo.expressionInfo(compileSource, state);
    ExpressionTree assignVar;
    Wrap guts;
    Snippet snip;
    if (ei != null && ei.isNonVoid) {
        String typeName = ei.typeName;
        SubKind subkind;
        if (ei.tree instanceof IdentifierTree) {
            IdentifierTree id = (IdentifierTree) ei.tree;
            name = id.getName().toString();
            subkind = SubKind.VAR_VALUE_SUBKIND;

        } else if (ei.tree instanceof AssignmentTree
                && (assignVar = ((AssignmentTree) ei.tree).getVariable()) instanceof IdentifierTree) {
            name = assignVar.toString();
            subkind = SubKind.ASSIGNMENT_SUBKIND;
        } else {
            subkind = SubKind.OTHER_EXPRESSION_SUBKIND;
        }
        if (shouldGenTempVar(subkind)) {
            if (state.tempVariableNameGenerator != null) {
                name = state.tempVariableNameGenerator.get();
            }
            while (name == null || state.keyMap.doesVariableNameExist(name)) {
                name = "$" + ++varNumber;
            }
            guts = Wrap.tempVarWrap(compileSource, typeName, name);
            Collection<String> declareReferences = null; //TODO
            snip = new VarSnippet(state.keyMap.keyForVariable(name), userSource, guts,
                    name, SubKind.TEMP_VAR_EXPRESSION_SUBKIND, typeName, declareReferences, null);
        } else {
            guts = Wrap.methodReturnWrap(compileSource);
            snip = new ExpressionSnippet(state.keyMap.keyForExpression(name, typeName), userSource, guts,
                    name, subkind);
        }
    } else {
        guts = Wrap.methodWrap(compileSource);
        if (ei == null) {
            // We got no type info, check for not a statement by trying
            AnalyzeTask at = trialCompile(guts);
            if (at.getDiagnostics().hasNotStatement()) {
                guts = Wrap.methodReturnWrap(compileSource);
                at = trialCompile(guts);
            }
            if (at.hasErrors()) {
                return compileFailResult(at, userSource, Kind.EXPRESSION);
            }
        }
        snip = new StatementSnippet(state.keyMap.keyForStatement(), userSource, guts);
    }
    return singletonList(snip);
}