Java Code Examples for com.sun.source.tree.LineMap#getLineNumber()

The following examples show how to use com.sun.source.tree.LineMap#getLineNumber() . 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: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 2
Source File: CompletenessStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 3
Source File: JavaDocGenerator.java    From vertx-docgen with Apache License 2.0 5 votes vote down vote up
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 4
Source File: OrganizeMembers.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@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 5
Source File: Tiny.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@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 6
Source File: TextDocumentServiceImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static Position createPosition(LineMap lm, int offset) {
    return new Position((int) lm.getLineNumber(offset) - 1,
                        (int) lm.getColumnNumber(offset) - 1);
}