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

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCImport. 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: RemoveUnusedImports.java    From google-java-format with Apache License 2.0 7 votes vote down vote up
/** Construct replacements to fix unused imports. */
private static RangeMap<Integer, String> buildReplacements(
    String contents,
    JCCompilationUnit unit,
    Set<String> usedNames,
    Multimap<String, Range<Integer>> usedInJavadoc) {
  RangeMap<Integer, String> replacements = TreeRangeMap.create();
  for (JCImport importTree : unit.getImports()) {
    String simpleName = getSimpleName(importTree);
    if (!isUnused(unit, usedNames, usedInJavadoc, importTree, simpleName)) {
      continue;
    }
    // delete the import
    int endPosition = importTree.getEndPosition(unit.endPositions);
    endPosition = Math.max(CharMatcher.isNot(' ').indexIn(contents, endPosition), endPosition);
    String sep = Newlines.guessLineSeparator(contents);
    if (endPosition + sep.length() < contents.length()
        && contents.subSequence(endPosition, endPosition + sep.length()).toString().equals(sep)) {
      endPosition += sep.length();
    }
    replacements.put(Range.closedOpen(importTree.getStartPosition(), endPosition), "");
  }
  return replacements;
}
 
Example #2
Source File: TreePruner.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static boolean isUnused(
    JCCompilationUnit unit, Set<String> usedNames, JCImport importTree) {
  String simpleName =
      importTree.getQualifiedIdentifier() instanceof JCIdent
          ? ((JCIdent) importTree.getQualifiedIdentifier()).getName().toString()
          : ((JCFieldAccess) importTree.getQualifiedIdentifier()).getIdentifier().toString();
  String qualifier =
      ((JCFieldAccess) importTree.getQualifiedIdentifier()).getExpression().toString();
  if (qualifier.equals("java.lang")) {
    return true;
  }
  if (unit.getPackageName() != null && unit.getPackageName().toString().equals(qualifier)) {
    // remove imports of classes from the current package
    return true;
  }
  if (importTree.getQualifiedIdentifier() instanceof JCFieldAccess
      && ((JCFieldAccess) importTree.getQualifiedIdentifier())
          .getIdentifier()
          .contentEquals("*")) {
    return false;
  }
  if (usedNames.contains(simpleName)) {
    return false;
  }
  return true;
}
 
Example #3
Source File: TreePruner.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static void removeUnusedImports(JCCompilationUnit unit) {
  Set<String> usedNames = new HashSet<>();
  // TODO(cushon): consider folding this into PruningVisitor to avoid a second pass
  new TreePathScanner<Void, Void>() {
    @Override
    public Void visitImport(ImportTree importTree, Void usedSymbols) {
      return null;
    }

    @Override
    public Void visitIdentifier(IdentifierTree tree, Void unused) {
      if (tree == null) {
        return null;
      }
      usedNames.add(tree.getName().toString());
      return null;
    }
  }.scan(unit, null);
  com.sun.tools.javac.util.List<JCTree> replacements = com.sun.tools.javac.util.List.nil();
  for (JCTree def : unit.defs) {
    if (!def.hasTag(JCTree.Tag.IMPORT) || !isUnused(unit, usedNames, (JCImport) def)) {
      replacements = replacements.append(def);
    }
  }
  unit.defs = replacements;
}
 
Example #4
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 #5
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void checkImportsResolvable(final JCCompilationUnit toplevel) {
    for (final JCImport imp : toplevel.getImports()) {
        if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
            continue;
        final JCFieldAccess select = (JCFieldAccess) imp.qualid;
        final Symbol origin;
        if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
            continue;

        TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
        if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
            log.error(imp.pos(),
                      Errors.CantResolveLocation(KindName.STATIC,
                                                 select.name,
                                                 null,
                                                 null,
                                                 Fragments.Location(kindName(site),
                                                                    site,
                                                                    null)));
        }
    }
}
 
Example #6
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) {
    OUTER: for (JCImport imp : toplevel.getImports()) {
        if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk) {
            TypeSymbol tsym = ((JCFieldAccess)imp.qualid).selected.type.tsym;
            if (toplevel.modle.visiblePackages != null) {
                //TODO - unclear: selects like javax.* will get resolved from the current module
                //(as javax is not an exported package from any module). And as javax in the current
                //module typically does not contain any classes or subpackages, we need to go through
                //the visible packages to find a sub-package:
                for (PackageSymbol known : toplevel.modle.visiblePackages.values()) {
                    if (Convert.packagePart(known.fullname) == tsym.flatName())
                        continue OUTER;
                }
            }
            if (tsym.kind == PCK && tsym.members().isEmpty() && !tsym.exists()) {
                log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, Errors.DoesntExist(tsym));
            }
        }
    }
}
 
Example #7
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 6 votes vote down vote up
public static void deleteImportFromCompilationUnit(JavacNode node, String name) {
	if (inNetbeansEditor(node)) return;
	if (!node.shouldDeleteLombokAnnotations()) return;
	ListBuffer<JCTree> newDefs = new ListBuffer<JCTree>();
	
	JCCompilationUnit unit = (JCCompilationUnit) node.top().get();
	
	for (JCTree def : unit.defs) {
		boolean delete = false;
		if (def instanceof JCImport) {
			JCImport imp0rt = (JCImport)def;
			delete = (!imp0rt.staticImport && imp0rt.qualid.toString().equals(name));
		}
		if (!delete) newDefs.append(def);
	}
	unit.defs = newDefs.toList();
}
 
Example #8
Source File: Scope.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void importAll(Types types, Scope origin,
                      ImportFilter filter,
                      JCImport imp,
                      BiConsumer<JCImport, CompletionFailure> cfHandler) {
    for (Scope existing : subScopes) {
        Assert.check(existing instanceof FilterImportScope);
        FilterImportScope fis = (FilterImportScope) existing;
        if (fis.origin == origin && fis.filter == filter &&
            fis.imp.staticImport == imp.staticImport)
            return ; //avoid entering the same scope twice
    }
    prependSubScope(new FilterImportScope(types, origin, null, filter, imp, cfHandler));
}
 
Example #9
Source File: ImportStatementsTest.java    From Refaster with Apache License 2.0 5 votes vote down vote up
/**
 * Test empty initial import list. The output string should start and
 * end with newlines because it is intended to be inserted after the
 * package statement.
 */
@Test
public void addingToEmptyImportListOutputShouldStartAndEndWithNewlines() {
  ImportStatements imports = new ImportStatements(
      basePackage, new ArrayList<JCImport>(), FAKE_END_POS_MAP);
  imports.add("import org.joda.time.Interval");
  assertEquals("\n"
      + "import org.joda.time.Interval;\n",
      imports.toString());
}
 
Example #10
Source File: ImportStatementsTest.java    From Refaster with Apache License 2.0 5 votes vote down vote up
/**
 * Test empty initial import list. Positions should match package end
 * positions.
 */
@Test
public void emptyImportListShouldGivePositionOfPackageStmt() {
  ImportStatements imports = new ImportStatements(
      basePackage, new ArrayList<JCImport>(), FAKE_END_POS_MAP);
  assertEquals(81, imports.getStartPos());
  assertEquals(81, imports.getEndPos());
}
 
Example #11
Source File: ImportStatements.java    From Refaster with Apache License 2.0 5 votes vote down vote up
public ImportStatements(JCExpression packageTree, List<JCImport> importTrees,
    ErrorProneEndPosMap endPosMap) {
  
  // find start, end positions for current list of imports (for replacement)
  if (importTrees.isEmpty()) {
    // start/end positions are just after the package expression
    hasExistingImports = false;
    startPos = endPosMap.getEndPosition(packageTree) + 2;   // +2 for semicolon and newline
    endPos = startPos;
  } else {
    // process list of imports and find start/end positions
    hasExistingImports = true;
    for (JCImport importTree : importTrees) {
      int currStartPos = importTree.getStartPosition();
      int currEndPos = endPosMap.getEndPosition(importTree);
      
      startPos = Math.min(startPos, currStartPos);
      endPos = Math.max(endPos, currEndPos);
    }  
  }
  
  // sanity check for start/end positions
  Preconditions.checkState(startPos <= endPos);
  
  // convert list of JCImports to list of strings
  importStrings = new TreeSet<>(IMPORT_ORDERING);
  importStrings.addAll(Lists.transform(importTrees, new Function<JCImport, String>() {
    @Override
    public String apply(JCImport input) {
      String importExpr = input.toString();
      return importExpr.substring(0, importExpr.length() - 2); // snip trailing ";\n"
    }
  }));
}
 
Example #12
Source File: RemoveUnusedImports.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
private static boolean isUnused(
    JCCompilationUnit unit,
    Set<String> usedNames,
    Multimap<String, Range<Integer>> usedInJavadoc,
    JCImport importTree,
    String simpleName) {
  String qualifier =
      ((JCFieldAccess) importTree.getQualifiedIdentifier()).getExpression().toString();
  if (qualifier.equals("java.lang")) {
    return true;
  }
  if (unit.getPackageName() != null && unit.getPackageName().toString().equals(qualifier)) {
    return true;
  }
  if (importTree.getQualifiedIdentifier() instanceof JCFieldAccess
      && ((JCFieldAccess) importTree.getQualifiedIdentifier())
          .getIdentifier()
          .contentEquals("*")) {
    return false;
  }

  if (usedNames.contains(simpleName)) {
    return false;
  }
  if (usedInJavadoc.containsKey(simpleName)) {
    return false;
  }
  return true;
}
 
Example #13
Source File: JavacImportList.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public String getFullyQualifiedNameForSimpleName(String unqualified) {
	for (JCTree def : defs) {
		if (!(def instanceof JCImport)) continue;
		JCTree qual = ((JCImport) def).qualid;
		if (!(qual instanceof JCFieldAccess)) continue;
		String simpleName = ((JCFieldAccess) qual).name.toString();
		if (simpleName.equals(unqualified)) {
			return LombokInternalAliasing.processAliases(qual.toString());
		}
	}
	
	return null;
}
 
Example #14
Source File: PrettyCommentsPrinter.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void visitImport(JCImport tree) {
	try {
		print("import ");
		if (tree.staticImport) print("static ");
		printExpr(tree.qualid);
		print(";");
		println();
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
 
Example #15
Source File: PrettyCommentsPrinter.java    From EasyMPermission with MIT License 5 votes vote down vote up
/** Print unit consisting of package clause and import statements in toplevel,
 *  followed by class definition. if class definition == null,
 *  print all definitions in toplevel.
 *  @param tree	 The toplevel tree
 *  @param cdef	 The class definition, which is assumed to be part of the
 *				  toplevel tree.
 */
public void printUnit(JCCompilationUnit tree, JCClassDecl cdef) throws IOException {
	Object dc = getDocComments(tree);
	loadDocCommentsTable(dc);
	printDocComment(tree);
	if (tree.pid != null) {
		consumeComments(tree.pos, tree);
		print("package ");
		printExpr(tree.pid);
		print(";");
		println();
	}
	boolean firstImport = true;
	for (List<JCTree> l = tree.defs;
	l.nonEmpty() && (cdef == null || IMPORT.equals(treeTag(l.head)));
	l = l.tail) {
		if (IMPORT.equals(treeTag(l.head))) {
			JCImport imp = (JCImport)l.head;
			Name name = TreeInfo.name(imp.qualid);
			if (name == name.table.fromChars(new char[] {'*'}, 0, 1) ||
					cdef == null ||
					isUsed(TreeInfo.symbol(imp.qualid), cdef)) {
				if (firstImport) {
					firstImport = false;
					println();
				}
				printStat(imp);
			}
		} else {
			printStat(l.head);
		}
	}
	if (cdef != null) {
		printStat(cdef);
		println();
	}
}
 
Example #16
Source File: Scope.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public FilterImportScope(Types types,
                         Scope origin,
                         Name  filterName,
                         ImportFilter filter,
                         JCImport imp,
                         BiConsumer<JCImport, CompletionFailure> cfHandler) {
    super(origin.owner);
    this.types = types;
    this.origin = origin;
    this.filterName = filterName;
    this.filter = filter;
    this.imp = imp;
    this.cfHandler = cfHandler;
}
 
Example #17
Source File: Scope.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void importAll(Types types, Scope origin,
                      ImportFilter filter,
                      JCImport imp,
                      BiConsumer<JCImport, CompletionFailure> cfHandler) {
    for (Scope existing : subScopes) {
        Assert.check(existing instanceof FilterImportScope);
        FilterImportScope fis = (FilterImportScope) existing;
        if (fis.origin == origin && fis.filter == filter &&
            fis.imp.staticImport == imp.staticImport)
            return ; //avoid entering the same scope twice
    }
    prependSubScope(new FilterImportScope(types, origin, null, filter, imp, cfHandler));
}
 
Example #18
Source File: TypeEnter.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Import all static members of a class or package on demand.
 *  @param imp           The import that is being handled.
 *  @param tsym          The class or package the members of which are imported.
 *  @param env           The env in which the imported classes will be entered.
 */
private void importStaticAll(JCImport imp,
                             final TypeSymbol tsym,
                             Env<AttrContext> env) {
    final StarImportScope toScope = env.toplevel.starImportScope;
    final TypeSymbol origin = tsym;

    toScope.importAll(types, origin.members(), staticImportFilter, imp, cfHandler);
}
 
Example #19
Source File: Scope.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public FilterImportScope(Types types,
                         Scope origin,
                         Name  filterName,
                         ImportFilter filter,
                         JCImport imp,
                         BiConsumer<JCImport, CompletionFailure> cfHandler) {
    super(origin.owner);
    this.types = types;
    this.origin = origin;
    this.filterName = filterName;
    this.filter = filter;
    this.imp = imp;
    this.cfHandler = cfHandler;
}
 
Example #20
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**Check that types imported through the ordinary imports don't clash with types imported
 * by other (static or ordinary) imports. Note that two static imports may import two clashing
 * types without an error on the imports.
 * @param toplevel       The toplevel tree for which the test should be performed.
 */
void checkImportsUnique(JCCompilationUnit toplevel) {
    WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
    WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
    WriteableScope topLevelScope = toplevel.toplevelScope;

    for (JCTree def : toplevel.defs) {
        if (!def.hasTag(IMPORT))
            continue;

        JCImport imp = (JCImport) def;

        if (imp.importScope == null)
            continue;

        for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
            if (imp.isStatic()) {
                checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
                staticallyImportedSoFar.enter(sym);
            } else {
                checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
                ordinallyImportedSoFar.enter(sym);
            }
        }

        imp.importScope = null;
    }
}
 
Example #21
Source File: TypeEnter.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void doImport(JCImport tree) {
    JCFieldAccess imp = (JCFieldAccess)tree.qualid;
    Name name = TreeInfo.name(imp);

    // Create a local environment pointing to this tree to disable
    // effects of other imports in Resolve.findGlobalType
    Env<AttrContext> localEnv = env.dup(tree);

    TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
    if (name == names.asterisk) {
        // Import on demand.
        chk.checkCanonical(imp.selected);
        if (tree.staticImport)
            importStaticAll(tree, p, env);
        else
            importAll(tree, p, env);
    } else {
        // Named type import.
        if (tree.staticImport) {
            importNamedStatic(tree, p, name, localEnv);
            chk.checkCanonical(imp.selected);
        } else {
            Type importedType = attribImportType(imp, localEnv);
            Type originalType = importedType.getOriginalType();
            TypeSymbol c = originalType.hasTag(CLASS) ? originalType.tsym : importedType.tsym;
            chk.checkCanonical(imp);
            importNamed(tree.pos(), c, env, tree);
        }
    }
}
 
Example #22
Source File: TypeEnter.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Import statics types of a given name.  Non-types are handled in Attr.
 *  @param imp           The import that is being handled.
 *  @param tsym          The class from which the name is imported.
 *  @param name          The (simple) name being imported.
 *  @param env           The environment containing the named import
 *                  scope to add to.
 */
private void importNamedStatic(final JCImport imp,
                               final TypeSymbol tsym,
                               final Name name,
                               final Env<AttrContext> env) {
    if (tsym.kind != TYP) {
        log.error(DiagnosticFlag.RECOVERABLE, imp.pos(), Errors.StaticImpOnlyClassesAndInterfaces);
        return;
    }

    final NamedImportScope toScope = env.toplevel.namedImportScope;
    final Scope originMembers = tsym.members();

    imp.importScope = toScope.importByName(types, originMembers, name, staticImportFilter, imp, cfHandler);
}
 
Example #23
Source File: CheckAttributedTree.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visitImport(JCImport tree) { }
 
Example #24
Source File: CheckAttributedTree.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visitImport(JCImport tree) { }
 
Example #25
Source File: GenStubs.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visitImport(JCImport tree) { }
 
Example #26
Source File: CheckAttributedTree.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visitImport(JCImport tree) { }
 
Example #27
Source File: GenStubs.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visitImport(JCImport tree) { }
 
Example #28
Source File: CheckAttributedTree.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visitImport(JCImport tree) { }
 
Example #29
Source File: Scope.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Scope importByName(Types types, Scope origin, Name name, ImportFilter filter, JCImport imp, BiConsumer<JCImport, CompletionFailure> cfHandler) {
    return appendScope(new FilterImportScope(types, origin, name, filter, imp, cfHandler));
}
 
Example #30
Source File: RemoveUnusedImports.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
private static String getSimpleName(JCImport importTree) {
  return importTree.getQualifiedIdentifier() instanceof JCIdent
      ? ((JCIdent) importTree.getQualifiedIdentifier()).getName().toString()
      : ((JCFieldAccess) importTree.getQualifiedIdentifier()).getIdentifier().toString();
}