com.sun.source.tree.LineMap Java Examples
The following examples show how to use
com.sun.source.tree.LineMap.
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: PreferredCCParser.java From netbeans with Apache License 2.0 | 6 votes |
/** return the offset of the first non-whitespace character on the line, or -1 when the line does not exist */ private static int findLineOffset(LineMap lineMap, CharSequence text, int lineNumber) { int offset; try { offset = (int) lineMap.getStartPosition(lineNumber); int offset2 = (int) lineMap.getStartPosition(lineNumber + 1); CharSequence lineStr = text.subSequence(offset, offset2); for (int i = 0; i < lineStr.length(); i++) { if (!Character.isWhitespace(lineStr.charAt(i))) { offset += i; break; } } } catch (IndexOutOfBoundsException ioobex) { return -1; } return offset; }
Example #2
Source File: T4994049.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public boolean run(DocletEnvironment root) { DocTrees trees = root.getDocTrees(); SourcePositions sourcePositions = trees.getSourcePositions(); for (TypeElement klass : ElementFilter.typesIn(root.getIncludedElements())) { for (ExecutableElement method : getMethods(klass)) { if (method.getSimpleName().toString().equals("tabbedMethod")) { TreePath path = trees.getPath(method); CompilationUnitTree cu = path.getCompilationUnit(); long pos = sourcePositions.getStartPosition(cu, path.getLeaf()); LineMap lineMap = cu.getLineMap(); long columnNumber = lineMap.getColumnNumber(pos); if (columnNumber == 9) { System.out.println(columnNumber + ": OK!"); return true; } else { System.err.println(columnNumber + ": wrong tab expansion"); return false; } } } } return false; }
Example #3
Source File: TreeAnalyzer.java From meghanada-server with GNU General Public License v3.0 | 6 votes |
private static Source analyzeUnit(CompilationUnitTree cut, Set<File> errorFiles) throws IOException { LineMap lineMap = cut.getLineMap(); URI uri = cut.getSourceFile().toUri(); File file = new File(uri.normalize()); String path = file.getCanonicalPath(); Source source = new Source(path, lineMap); if (errorFiles.contains(file)) { source.hasCompileError = true; } SourceContext context = new SourceContext(source); analyzeCompilationUnitTree(context, cut); source.resetLineRange(); source.buildMethodCallsBF(); return source; }
Example #4
Source File: PartialReparseTest.java From netbeans with Apache License 2.0 | 5 votes |
private static List<Long> dumpLineMap(CompilationInfo info) { LineMap lm = info.getCompilationUnit().getLineMap(); int len = info.getText().length(); List<Long> dump = new ArrayList<>(); for (int p = 0; p <= len + 1; p++) { dump.add(lm.getLineNumber(p)); dump.add(lm.getColumnNumber(p)); dump.add(lm.getStartPosition(lm.getLineNumber(p))); dump.add(lm.getPosition(lm.getLineNumber(p), lm.getColumnNumber(p))); } return dump; }
Example #5
Source File: Utils.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public long getLineNumber(Element e) { TreePath path = getTreePath(e); if (path == null) { // maybe null if synthesized TypeElement encl = getEnclosingTypeElement(e); path = getTreePath(encl); } CompilationUnitTree cu = path.getCompilationUnit(); LineMap lineMap = cu.getLineMap(); DocSourcePositions spos = docTrees.getSourcePositions(); long pos = spos.getStartPosition(cu, path.getLeaf()); return lineMap.getLineNumber(pos); }
Example #6
Source File: CompletenessStressTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private boolean testStatement(StringWriter writer, SourcePositions sp, String text, CompilationUnitTree cut, Tree statement) { if (statement == null) { return true; } int start = (int) sp.getStartPosition(cut, statement); int end = (int) sp.getEndPosition(cut, statement); char ch = text.charAt(end - 1); SourceCodeAnalysis.Completeness expected = COMPLETE; LineMap lineMap = cut.getLineMap(); int row = (int) lineMap.getLineNumber(start); int column = (int) lineMap.getColumnNumber(start); switch (ch) { case ',': case ';': expected = (statement instanceof ExpressionStatementTree) ? COMPLETE : COMPLETE_WITH_SEMI; --end; break; case '}': break; default: writer.write(String.format("Unexpected end: row %d, column %d: '%c' -- %s\n", row, column, ch, text.substring(start, end))); return true; } String unit = text.substring(start, end); SourceCodeAnalysis.CompletionInfo ci = getAnalysis().analyzeCompletion(unit); if (ci.completeness() != expected) { if (expected == COMPLETE_WITH_SEMI && (ci.completeness() == CONSIDERED_INCOMPLETE || ci.completeness() == EMPTY)) { writer.write(String.format("Empty statement: row %d, column %d: -- %s\n", start, end, unit)); } else { writer.write(String.format("Expected %s got %s: '%s' row %d, column %d: -- %s\n", expected, ci.completeness(), unit, row, column, unit)); return false; } } return true; }
Example #7
Source File: JavaDocGenerator.java From vertx-docgen with Apache License 2.0 | 5 votes |
public String renderSource(TreePath path, List<? extends Tree> trees, String source) { CompilationUnitTree unit = path.getCompilationUnit(); int from = (int) docTrees.getSourcePositions().getStartPosition(unit, trees.get(0)); int to = (int) docTrees.getSourcePositions().getEndPosition(unit, trees.get(trees.size() - 1)); // Correct boundaries while (from > 1 && source.charAt(from - 1) != '\n') { from--; } while (to < source.length() && source.charAt(to) != '\n') { to++; } String block = source.substring(from, to); // Determine margin int blockMargin = Integer.MAX_VALUE; LineMap lineMap = unit.getLineMap(); for (Tree statement : trees) { int statementStart = (int) docTrees.getSourcePositions().getStartPosition(unit, statement); int lineStart = statementStart; while (lineMap.getLineNumber(statementStart) == lineMap.getLineNumber(lineStart - 1)) { lineStart--; } blockMargin = Math.min(blockMargin, statementStart - lineStart); } // Crop the fragment StringBuilder fragment = new StringBuilder(); for (Iterator<String> sc = new Scanner(block).useDelimiter("\n"); sc.hasNext(); ) { String line = sc.next(); int margin = Math.min(blockMargin, line.length()); line = line.substring(margin); fragment.append(line); if (sc.hasNext()) { fragment.append('\n'); } } return fragment.toString(); }
Example #8
Source File: OrganizeMembers.java From netbeans with Apache License 2.0 | 4 votes |
@TriggerTreeKind(Kind.CLASS) public static ErrorDescription checkMembers(final HintContext context) { for (Diagnostic<?> d : context.getInfo().getDiagnostics()) { if (Hacks.isSyntaxError(d)) { return null; } } Source source = context.getInfo().getSnapshot().getSource(); try { ModificationResult 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); doOrganizeMembers(copy, context.getPath()); } }); List<? extends Difference> diffs = result.getDifferences(source.getFileObject()); if (diffs != null && !diffs.isEmpty() && !checkGuarded(context.getInfo().getDocument(), diffs)) { Fix fix = new OrganizeMembersFix(context.getInfo(), context.getPath()).toEditorFix(); SourcePositions sp = context.getInfo().getTrees().getSourcePositions(); int offset = diffs.get(0).getStartPosition().getOffset(); LineMap lm = context.getInfo().getCompilationUnit().getLineMap(); long lno = lm.getLineNumber(offset); if (lno >= 1) { offset = (int)lm.getStartPosition(lno); } CompilationUnitTree cut = context.getPath().getCompilationUnit(); ClassTree clazz = (ClassTree) context.getPath().getLeaf(); for (Tree member : clazz.getMembers()) { if (context.getInfo().getTreeUtilities().isSynthetic(new TreePath(context.getPath(), member))) continue; if (sp.getStartPosition(cut, member) >= offset) { return ErrorDescriptionFactory.forTree(context, member, NbBundle.getMessage(OrganizeMembers.class, "MSG_OragnizeMembers"), fix); //NOI18N } } return ErrorDescriptionFactory.forTree(context, clazz, NbBundle.getMessage(OrganizeMembers.class, "MSG_OragnizeMembers"), fix); //NOI18N } } catch (Exception ex) { Exceptions.printStackTrace(ex); } return null; }
Example #9
Source File: Tiny.java From netbeans with Apache License 2.0 | 4 votes |
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.suggestions.Tiny.fillSwitch", description = "#DESC_org.netbeans.modules.java.hints.suggestions.Tiny.fillSwitch", category="suggestions", hintKind=Kind.ACTION, severity=Severity.HINT, customizerProvider=CustomizerProviderImpl.class) @TriggerPattern(value="switch ($expression) { case $cases$; }", constraints=@ConstraintVariableType(variable="$expression", type="java.lang.Enum")) public static ErrorDescription fillSwitch(HintContext ctx) { int caret = ctx.getCaretLocation(); SwitchTree st = (SwitchTree) ctx.getPath().getLeaf(); int switchStart = (int) ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getPath().getCompilationUnit(), st); LineMap lm = ctx.getPath().getCompilationUnit().getLineMap(); if (lm.getLineNumber(caret) != lm.getLineNumber(switchStart)) return null; TreePath expression = ctx.getVariables().get("$expression"); Element possibleEnumElement = ctx.getInfo().getTypes().asElement(ctx.getInfo().getTrees().getTypeMirror(expression)); if (possibleEnumElement == null || !possibleEnumElement.getKind().isClass()) return null; TypeElement enumType = (TypeElement) possibleEnumElement; List<VariableElement> enumConstants = new ArrayList<VariableElement>(enumType.getEnclosedElements().size()); for (Element e : enumType.getEnclosedElements()) { if (e.getKind() == ElementKind.ENUM_CONSTANT) { enumConstants.add((VariableElement) e); } } boolean hasDefault = false; for (TreePath casePath : ctx.getMultiVariables().get("$cases$")) { CaseTree ct = (CaseTree) casePath.getLeaf(); if (ct.getExpression() == null) { hasDefault = true; } else { enumConstants.remove(ctx.getInfo().getTrees().getElement(new TreePath(casePath, ct.getExpression()))); } } boolean generateDefault = ctx.getPreferences().getBoolean(KEY_DEFAULT_ENABLED, DEF_DEFAULT_ENABLED); if (enumConstants.isEmpty() && (hasDefault || !generateDefault)) return null; List<String> names = new ArrayList<String>(enumConstants.size()); for (VariableElement constant : enumConstants) { names.add(constant.getSimpleName().toString()); } String defaultTemplate = generateDefault ? ctx.getPreferences().get(KEY_DEFAULT_SNIPPET, DEF_DEFAULT_SNIPPET) : null; String errMessage = enumConstants.isEmpty() ? "ERR_Tiny.fillSwitchDefault" : !hasDefault && generateDefault ? "ERR_Tiny.fillSwitchCasesAndDefault" : "ERR_Tiny.fillSwitchCases"; String fixMessage = enumConstants.isEmpty() ? "FIX_Tiny.fillSwitchDefault" : !hasDefault && generateDefault ? "FIX_Tiny.fillSwitchCasesAndDefault" : "FIX_Tiny.fillSwitchCases"; return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), NbBundle.getMessage(Tiny.class, errMessage), new AddSwitchCasesImpl(ctx.getInfo(), ctx.getPath(), fixMessage, names, defaultTemplate).toEditorFix()); }
Example #10
Source File: TextDocumentServiceImpl.java From netbeans with Apache License 2.0 | 4 votes |
@Override public CompletableFuture<List<? extends Location>> definition(TextDocumentPositionParams params) { JavaSource js = getSource(params.getTextDocument().getUri()); GoToTarget[] target = new GoToTarget[1]; LineMap[] lm = new LineMap[1]; try { js.runUserActionTask(cc -> { cc.toPhase(JavaSource.Phase.RESOLVED); Document doc = cc.getSnapshot().getSource().getDocument(true); int offset = getOffset(doc, params.getPosition()); Context context = GoToSupport.resolveContext(cc, doc, offset, false, false); if (context == null) { return ; } target[0] = GoToSupport.computeGoToTarget(cc, context, offset); lm[0] = cc.getCompilationUnit().getLineMap(); }, true); } catch (IOException ex) { //TODO: include stack trace: client.logMessage(new MessageParams(MessageType.Error, ex.getMessage())); } List<Location> result = new ArrayList<>(); if (target[0] != null && target[0].success) { if (target[0].offsetToOpen < 0) { Object[] openInfo = ElementOpenAccessor.getInstance().getOpenInfo(target[0].cpInfo, target[0].elementToOpen, new AtomicBoolean()); if (openInfo != null) { FileObject file = (FileObject) openInfo[0]; int start = (int) openInfo[1]; int end = (int) openInfo[2]; result.add(new Location(toUri(file), new Range(createPosition(lm[0], start), createPosition(lm[0], end)))); } } else { Position pos = createPosition(js.getFileObjects().iterator().next(), target[0].offsetToOpen); result.add(new Location(params.getTextDocument().getUri(), new Range(pos, pos))); } } return CompletableFuture.completedFuture(result); }
Example #11
Source File: TextDocumentServiceImpl.java From netbeans with Apache License 2.0 | 4 votes |
public static Position createPosition(LineMap lm, int offset) { return new Position((int) lm.getLineNumber(offset) - 1, (int) lm.getColumnNumber(offset) - 1); }
Example #12
Source File: Source.java From meghanada-server with GNU General Public License v3.0 | 4 votes |
public Source(String filePath, LineMap lineMap) { this(filePath); this.lineMap = lineMap; }
Example #13
Source File: CompilationUnitTree.java From java-n-IDE-for-Android with Apache License 2.0 | 2 votes |
/** * Gets the line map for this compilation unit, if available. * Returns null if the line map is not available. * @return the line map for this compilation unit */ LineMap getLineMap();
Example #14
Source File: CompilationUnitTree.java From javaide with GNU General Public License v3.0 | 2 votes |
/** * Gets the line map for this compilation unit, if available. * Returns null if the line map is not available. * @return the line map for this compilation unit */ LineMap getLineMap();