Java Code Examples for com.sun.source.tree.Tree.Kind#COMPILATION_UNIT
The following examples show how to use
com.sun.source.tree.Tree.Kind#COMPILATION_UNIT .
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: ErrorDescriptionFactory.java From netbeans with Apache License 2.0 | 6 votes |
/** Creates a fix, which when invoked adds @SuppresWarnings(keys) to * nearest declaration. * @param compilationInfo CompilationInfo to work on * @param treePath TreePath to a tree. The method will find nearest outer * declaration. (type, method, field or local variable) * @param keys keys to be contained in the SuppresWarnings annotation. E.g. * @SuppresWarnings( "key" ) or @SuppresWarnings( {"key1", "key2", ..., "keyN" } ). * @throws IllegalArgumentException if keys are null or empty or id no suitable element * to put the annotation on is found (e.g. if TreePath to CompilationUnit is given") */ static Fix createSuppressWarningsFix(CompilationInfo compilationInfo, TreePath treePath, String... keys ) { Parameters.notNull("compilationInfo", compilationInfo); Parameters.notNull("treePath", treePath); Parameters.notNull("keys", keys); if (keys.length == 0) { throw new IllegalArgumentException("key must not be empty"); // NOI18N } if (!isSuppressWarningsSupported(compilationInfo)) { return null; } while (treePath.getLeaf().getKind() != Kind.COMPILATION_UNIT && !DECLARATION.contains(treePath.getLeaf().getKind())) { treePath = treePath.getParentPath(); } if (treePath.getLeaf().getKind() != Kind.COMPILATION_UNIT) { return new FixImpl(TreePathHandle.create(treePath, compilationInfo), compilationInfo.getFileObject(), keys); } else { return null; } }
Example 2
Source File: UncaughtException.java From netbeans with Apache License 2.0 | 6 votes |
/** * Detects if we are parameter of this() or super() call * @return true if yes */ private boolean isThisParameter(TreePath path) { //anonymous class must not be on the path to top while(!TreeUtilities.CLASS_TREE_KINDS.contains(path.getLeaf().getKind()) && path.getLeaf().getKind() != Kind.COMPILATION_UNIT) { if (path.getParentPath().getLeaf().getKind() == Kind.METHOD_INVOCATION) { MethodInvocationTree mi = (MethodInvocationTree) path.getParentPath().getLeaf(); if(mi.getMethodSelect().getKind() == Kind.IDENTIFIER) { String id = ((IdentifierTree) mi.getMethodSelect()).getName().toString(); if ("super".equals(id) || "this".equals(id)) return true; } } path = path.getParentPath(); } return false; }
Example 3
Source File: ClassStructure.java From netbeans with Apache License 2.0 | 6 votes |
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.multipleTopLevelClassesInFile", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.multipleTopLevelClassesInFile", category = "class_structure", enabled = false, suppressWarnings = {"MultipleTopLevelClassesInFile"}, options=Options.QUERY) //NOI18N @TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE}) public static ErrorDescription multipleTopLevelClassesInFile(HintContext context) { final ClassTree cls = (ClassTree) context.getPath().getLeaf(); final Tree parent = context.getPath().getParentPath().getLeaf(); if (parent.getKind() == Kind.COMPILATION_UNIT) { final List<? extends Tree> typeDecls = new ArrayList<Tree>(((CompilationUnitTree) parent).getTypeDecls()); for (Iterator<? extends Tree> it = typeDecls.iterator(); it.hasNext();) { if (it.next().getKind() == Kind.EMPTY_STATEMENT) it.remove(); } if (typeDecls.size() > 1 && typeDecls.get(0) != cls) { return ErrorDescriptionFactory.forName(context, cls, NbBundle.getMessage(ClassStructure.class, "MSG_MultipleTopLevelClassesInFile")); //NOI18N } } return null; }
Example 4
Source File: TreePathHandle.java From netbeans with Apache License 2.0 | 5 votes |
public Kind getKind() { switch (el.getKind()) { case PACKAGE: return Kind.COMPILATION_UNIT; case ENUM: case CLASS: case ANNOTATION_TYPE: case INTERFACE: return Kind.CLASS; case ENUM_CONSTANT: case FIELD: case PARAMETER: case LOCAL_VARIABLE: case RESOURCE_VARIABLE: case EXCEPTION_PARAMETER: return Kind.VARIABLE; case METHOD: case CONSTRUCTOR: return Kind.METHOD; case STATIC_INIT: case INSTANCE_INIT: return Kind.BLOCK; case TYPE_PARAMETER: return Kind.TYPE_PARAMETER; case OTHER: default: return Kind.OTHER; } }
Example 5
Source File: JavadocCompletionUtils.java From netbeans with Apache License 2.0 | 5 votes |
public static TreePath findJavadoc(CompilationInfo javac, int offset) { TokenSequence<JavaTokenId> ts = SourceUtils.getJavaTokenSequence(javac.getTokenHierarchy(), offset); if (ts == null || !movedToJavadocToken(ts, offset)) { return null; } int offsetBehindJavadoc = ts.offset() + ts.token().length(); while (ts.moveNext()) { TokenId tid = ts.token().id(); if (tid == JavaTokenId.BLOCK_COMMENT) { if ("/**/".contentEquals(ts.token().text())) { // NOI18N // see #147533 return null; } } else if (tid == JavaTokenId.JAVADOC_COMMENT) { if (ts.token().partType() == PartType.COMPLETE) { return null; } } else if (!IGNORE_TOKES.contains(tid)) { offsetBehindJavadoc = ts.offset(); // it is magic for TreeUtilities.pathFor ++offsetBehindJavadoc; break; } } TreePath tp = javac.getTreeUtilities().pathFor(offsetBehindJavadoc); while (!TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind()) && tp.getLeaf().getKind() != Kind.METHOD && tp.getLeaf().getKind() != Kind.VARIABLE && tp.getLeaf().getKind() != Kind.COMPILATION_UNIT) { tp = tp.getParentPath(); if (tp == null) { break; } } return tp; }
Example 6
Source File: OrganizeImports.java From netbeans with Apache License 2.0 | 5 votes |
@TriggerTreeKind(Kind.COMPILATION_UNIT) public static ErrorDescription checkImports(final HintContext context) { Source source = context.getInfo().getSnapshot().getSource(); ModificationResult result = null; try { result = ModificationResult.runModificationTask(Collections.singleton(source), new UserTask() { @Override public void run(ResultIterator resultIterator) throws Exception { WorkingCopy copy = WorkingCopy.get(resultIterator.getParserResult()); copy.toPhase(Phase.RESOLVED); doOrganizeImports(copy, context.isBulkMode()); } }); } catch (ParseException ex) { Exceptions.printStackTrace(ex); } List<? extends Difference> diffs = result != null ? result.getDifferences(source.getFileObject()) : null; if (diffs != null && !diffs.isEmpty()) { Fix fix = new OrganizeImportsFix(context.getInfo(), context.getPath(), context.isBulkMode()).toEditorFix(); SourcePositions sp = context.getInfo().getTrees().getSourcePositions(); int offset = diffs.get(0).getStartPosition().getOffset(); CompilationUnitTree cu = context.getInfo().getCompilationUnit(); for (ImportTree imp : cu.getImports()) { if (sp.getEndPosition(cu, imp) >= offset) return ErrorDescriptionFactory.forTree(context, imp, NbBundle.getMessage(OrganizeImports.class, "MSG_OragnizeImports"), fix); //NOI18N } return ErrorDescriptionFactory.forTree(context, context.getInfo().getCompilationUnit().getImports().get(0), NbBundle.getMessage(OrganizeImports.class, "MSG_OragnizeImports"), fix); //NOI18N } return null; }
Example 7
Source File: AddParameterOrLocalFix.java From netbeans with Apache License 2.0 | 5 votes |
private TreePath findStatement(TreePath tp) { TreePath statement = tp; while (statement.getLeaf().getKind() != Kind.COMPILATION_UNIT) { if (isStatement(statement.getLeaf())) { return statement; } statement = statement.getParentPath(); } return null; }
Example 8
Source File: TagOrderHint.java From netbeans with Apache License 2.0 | 5 votes |
@TriggerTreeKind(Kind.COMPILATION_UNIT) @Messages("ERR_TagOrderHint=Incorrect tag order") public static ErrorDescription computeWarning(HintContext ctx) { Result tags = TagParser.parseTags(ctx.getInfo()); List<Tag> sorted = sortTags(tags); if (!tags.getTags().equals(sorted)) { ErrorDescription idealED = ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_TagOrderHint(), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix()); List<Tag> test = tags.getName2Tag().get("test"); return org.netbeans.spi.editor.hints.ErrorDescriptionFactory.createErrorDescription(idealED.getSeverity(), idealED.getDescription(), idealED.getFixes(), ctx.getInfo().getFileObject(), test.get(0).getTagStart(), test.get(0).getTagEnd()); } return null; }
Example 9
Source File: WrongSourceVersion.java From netbeans with Apache License 2.0 | 5 votes |
@TriggerTreeKind(Kind.COMPILATION_UNIT) @Messages({ "ERR_HardcodedSource=Hardcoded source version, should use ${jdk.version}" }) public static List<ErrorDescription> computeWarning(HintContext ctx) { Result tags = TagParser.parseTags(ctx.getInfo()); List<ErrorDescription> result = new ArrayList<>(); for (Tag tag : tags.getTags()) { if (!"compile".equals(tag.getName())) { continue; } String[] params = tag.getValue().split("[\\s]+"); boolean hasEnablePreview = Arrays.stream(params).anyMatch(s -> "--enable-preview".equals(s)); if (hasEnablePreview) { for (int i = 0; i < params.length; i++) { if ((params[i].equals("-source") || params[i].equals("--source")) && i + 1 < params.length) { try { Integer.parseInt(params[i + 1]); int pos = tag.getValue().indexOf(params[i]); int start = tag.getValue().indexOf(params[i + 1], pos) + tag.getTagEnd(); int end = start + params[i + 1].length(); ErrorDescription idealED = ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_HardcodedSource(), new UseJdkSource(ctx.getInfo(), ctx.getPath(), start, end).toEditorFix()); result.add(org.netbeans.spi.editor.hints.ErrorDescriptionFactory.createErrorDescription(idealED.getSeverity(), idealED.getDescription(), idealED.getFixes(), ctx.getInfo().getFileObject(), start, end)); } catch (NumberFormatException ex) { //OK } } } } } return result; }
Example 10
Source File: ModulesHint.java From netbeans with Apache License 2.0 | 5 votes |
@TriggerTreeKind(Kind.COMPILATION_UNIT) @Messages("ERR_ModulesHint=Incorrect @modules tag") public static ErrorDescription computeWarning(final HintContext ctx) { Pair<Fix, int[]> fix = computeChange(ctx.getInfo()); if (fix == null) return null; ErrorDescription idealED = ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ModulesHint(), fix.first()); return org.netbeans.spi.editor.hints.ErrorDescriptionFactory.createErrorDescription(idealED.getSeverity(), idealED.getDescription(), idealED.getFixes(), ctx.getInfo().getFileObject(), fix.second()[0], fix.second()[1]); }
Example 11
Source File: GeneratorUtilities.java From netbeans with Apache License 2.0 | 4 votes |
static <T extends Tree> T importComments(CompilationInfo info, T original, CompilationUnitTree cut) { try { CommentSetImpl comments = CommentHandlerService.instance(info.impl.getJavacTask().getContext()).getComments(original); if (comments.areCommentsMapped()) { //optimalization, if comments are already mapped, do not even try to //map them again, would not be attached anyway: return original; } JCTree.JCCompilationUnit unit = (JCCompilationUnit) cut; TokenHierarchy<?> tokens = unit.getSourceFile() instanceof AbstractSourceFileObject ? ((AbstractSourceFileObject) unit.getSourceFile()).getTokenHierarchy() : TokenHierarchy.create(unit.getSourceFile().getCharContent(true), JavaTokenId.language()); TokenSequence<JavaTokenId> seq = tokens.tokenSequence(JavaTokenId.language()); TreePath tp = TreePath.getPath(cut, original); Tree toMap = original; Tree mapTarget = null; if (tp != null && original.getKind() != Kind.COMPILATION_UNIT) { // find some 'nice' place like method/class/field so the comments get an appropriate contents // Javadocs or other comments may be assigned inappropriately with wider surrounding contents. TreePath p2 = tp; boolean first = true; B: while (p2 != null) { Tree.Kind k = p2.getLeaf().getKind(); if (StatementTree.class.isAssignableFrom(k.asInterface())) { mapTarget = p2.getLeaf(); p2 = p2.getParentPath(); break; } switch (p2.getLeaf().getKind()) { case CLASS: case INTERFACE: case ENUM: case METHOD: case BLOCK: case VARIABLE: if (mapTarget == null) { mapTarget = p2.getLeaf(); } if (first) { p2 = p2 = p2.getParentPath(); } break B; } first = false; p2 = p2.getParentPath(); } if (p2 != null) { toMap = p2.getLeaf(); } if (toMap == tp.getLeaf()) { // go at least one level up in a hope it's sufficient. toMap = tp.getParentPath().getLeaf(); } } if (mapTarget == null) { mapTarget = original; } AssignComments translator = new AssignComments(info, mapTarget, seq, unit); translator.scan(toMap, null); return original; } catch (IOException ex) { Exceptions.printStackTrace(ex); } return original; }
Example 12
Source File: Imports.java From netbeans with Apache License 2.0 | 4 votes |
@Hint(displayName = "#DN_Imports_DEFAULT_PACKAGE", description = "#DESC_Imports_DEFAULT_PACKAGE", category="imports", id="Imports_DEFAULT_PACKAGE", suppressWarnings={"", "JavaLangImport"}) @TriggerTreeKind(Kind.COMPILATION_UNIT) public static List<ErrorDescription> defaultImport(HintContext ctx) { return importMultiHint(ctx, ImportHintKind.DEFAULT_PACKAGE, getAllImportsOfKind(ctx.getInfo(), ImportHintKind.DEFAULT_PACKAGE)); }
Example 13
Source File: Imports.java From netbeans with Apache License 2.0 | 4 votes |
@Hint(displayName = "#DN_Imports_UNUSED", description = "#DESC_Imports_UNUSED", category="imports", id="Imports_UNUSED", suppressWarnings={"", "UnusedImport", "UNUSED_IMPORT"}) @TriggerTreeKind(Kind.COMPILATION_UNIT) public static List<ErrorDescription> unusedImport(HintContext ctx) throws IOException { return importMultiHint(ctx, ImportHintKind.UNUSED, UnusedImports.computeUnusedImports(ctx.getInfo())); }
Example 14
Source File: Imports.java From netbeans with Apache License 2.0 | 4 votes |
@Hint(displayName = "#DN_Imports_SAME_PACKAGE", description = "#DESC_Imports_SAME_PACKAGE", category="imports", id="Imports_SAME_PACKAGE", suppressWarnings={"", "SamePackageImport"}) @TriggerTreeKind(Kind.COMPILATION_UNIT) public static List<ErrorDescription> samePackage(HintContext ctx) throws IOException { return importMultiHint(ctx, ImportHintKind.SAME_PACKAGE, getAllImportsOfKind(ctx.getInfo(), ImportHintKind.SAME_PACKAGE)); }
Example 15
Source File: HintsInvoker.java From netbeans with Apache License 2.0 | 2 votes |
private Map<HintDescription, List<ErrorDescription>> computeHintsInSpan(CompilationInfo info, Map<Class, List<HintDescription>> triggerKind2Hints, Collection<? super MessageImpl> problems) { TreePath path = info.getTreeUtilities().pathFor((from + to) / 2); while (path.getLeaf().getKind() != Kind.COMPILATION_UNIT) { int start = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), path.getLeaf()); int end = (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), path.getLeaf()); if (start <= from && end >= to) { break; } path = path.getParentPath(); } Map<HintDescription, List<ErrorDescription>> errors = new HashMap<HintDescription, List<ErrorDescription>>(); List<HintDescription> kindBasedHints = triggerKind2Hints.get(Kinds.class); if (!kindBasedHints.isEmpty()) { long kindStart = System.currentTimeMillis(); new ScannerImpl(info, cancel, sortByKinds(kindBasedHints), problems).scan(path, errors); long kindEnd = System.currentTimeMillis(); timeLog.put("Kind Based Hints", kindEnd - kindStart); } List<HintDescription> patternBasedHints = triggerKind2Hints.get(PatternDescription.class); if (!patternBasedHints.isEmpty()) { long patternStart = System.currentTimeMillis(); Map<PatternDescription, List<HintDescription>> patternHints = sortByPatterns(patternBasedHints); Map<String, List<PatternDescription>> patternTests = computePatternTests(patternHints); long bulkStart = System.currentTimeMillis(); BulkPattern bulkPattern = BulkSearch.getDefault().create(info, cancel, patternTests.keySet()); if (bulkPattern == null || cancel.get()) return null; Map<String, Collection<TreePath>> occurringPatterns = BulkSearch.getDefault().match(info, cancel, path, bulkPattern, timeLog); if (occurringPatterns == null || cancel.get()) return null; long bulkEnd = System.currentTimeMillis(); timeLog.put("Bulk Search", bulkEnd - bulkStart); Map<HintDescription, List<ErrorDescription>> computedHints = doComputeHints(info, occurringPatterns, patternTests, patternHints, problems); if (computedHints == null || cancel.get()) return null; mergeAll(errors, computedHints); long patternEnd = System.currentTimeMillis(); timeLog.put("Pattern Based Hints", patternEnd - patternStart); } if (path != null) { Map<HintDescription, List<ErrorDescription>> suggestions = computeSuggestions(info, path, true, triggerKind2Hints, problems); if (suggestions == null || cancel.get()) return null; mergeAll(errors, suggestions); } return errors; }