Java Code Examples for com.sun.source.util.SourcePositions#getEndPosition()

The following examples show how to use com.sun.source.util.SourcePositions#getEndPosition() . 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: AssignResultToVariable.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StatementTree findExactStatement(CompilationInfo info, BlockTree block, int offset, boolean start) {
    if (offset == (-1)) return null;
    
    SourcePositions sp = info.getTrees().getSourcePositions();
    CompilationUnitTree cut = info.getCompilationUnit();
    
    for (StatementTree t : block.getStatements()) {
        long pos = start ? sp.getStartPosition(info.getCompilationUnit(), t) : sp.getEndPosition( cut, t);

        if (offset == pos) {
            return t;
        }
    }

    return null;
}
 
Example 2
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Token<JavaTokenId> findIdentifierSpanImpl(CompilationInfo info, IdentifierTree tree, CompilationUnitTree cu, SourcePositions positions) {
    int start = (int)positions.getStartPosition(cu, tree);
    int endPosition = (int)positions.getEndPosition(cu, tree);
    
    if (start == (-1) || endPosition == (-1))
        return null;

    TokenHierarchy<?> th = info.getTokenHierarchy();
    TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language());

    if (ts.move(start) == Integer.MAX_VALUE) {
        return null;
    }

    if (ts.moveNext()) {
        if (ts.offset() >= start) {
            Token<JavaTokenId> t = ts.token();
            return t;
        }
    }
    
    return null;
}
 
Example 3
Source File: OpenTestAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 */
public void run(CompilationController controller) throws IOException {
    try {
        controller.toPhase(Phase.RESOLVED);     //cursor position needed
    } catch (IOException ex) {
        Logger.getLogger("global").log(Level.SEVERE, null, ex); //NOI18N
    }
    if (cancelled) {
        return;
    }
    
    Element element = elemHandle.resolve(controller);
    if (cancelled || (element == null)) {
        return;
    }

    Trees trees = controller.getTrees();
    CompilationUnitTree compUnit = controller.getCompilationUnit();
    DeclarationTreeFinder treeFinder = new DeclarationTreeFinder(
                                                element, trees);
    treeFinder.scan(compUnit, null);
    Tree tree = treeFinder.getDeclarationTree();

    if (tree != null) {
        SourcePositions srcPositions = trees.getSourcePositions();
        long startPos = srcPositions.getStartPosition(compUnit, tree);
        long endPos = srcPositions.getEndPosition(compUnit, tree);
        
        if ((startPos >= 0) && (startPos <= (long) Integer.MAX_VALUE)
             && (endPos >= 0) && (endPos <= (long) Integer.MAX_VALUE)) {
            positionRange = new int[2];
            positionRange[0] = (int) startPos;
            positionRange[1] = (int) endPos;
        }
    }
}
 
Example 4
Source File: SourceUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all elements of the given scope that are declared after given position in a source.
 * @param path to the given search scope
 * @param pos position in the source
 * @param sourcePositions
 * @param trees
 * @return collection of forward references
 * 
 * @since 0.136
 */
public static Collection<? extends Element> getForwardReferences(TreePath path, int pos, SourcePositions sourcePositions, Trees trees) {
    HashSet<Element> refs = new HashSet<>();
    Element el;
    
    while(path != null) {
        switch(path.getLeaf().getKind()) {
            case VARIABLE:
                el = trees.getElement(path);
                if (el != null) {
                    refs.add(el);
                }
                TreePath parent = path.getParentPath();
                if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getLeaf().getKind())) {
                    boolean isStatic = ((VariableTree)path.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC);
                    for(Tree member : ((ClassTree)parent.getLeaf()).getMembers()) {
                        if (member.getKind() == Tree.Kind.VARIABLE && sourcePositions.getStartPosition(path.getCompilationUnit(), member) >= pos &&
                                (isStatic || !((VariableTree)member).getModifiers().getFlags().contains(Modifier.STATIC))) {
                            el = trees.getElement(new TreePath(parent, member));
                            if (el != null) {
                                refs.add(el);
                            }
                        }
                    }
                }
                break;
            case ENHANCED_FOR_LOOP:
                EnhancedForLoopTree efl = (EnhancedForLoopTree)path.getLeaf();
                if (sourcePositions.getEndPosition(path.getCompilationUnit(), efl.getExpression()) >= pos) {
                    el = trees.getElement(new TreePath(path, efl.getVariable()));
                    if (el != null) {
                        refs.add(el);
                    }
                }                        
        }
        path = path.getParentPath();
    }
    return refs;
}
 
Example 5
Source File: BaseTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
List<Tree> getArgumentsUpToPos(Env env, Iterable<? extends ExpressionTree> args, int startPos, int position, boolean strict) {
    List<Tree> ret = new ArrayList<>();
    CompilationUnitTree root = env.getRoot();
    SourcePositions sourcePositions = env.getSourcePositions();
    if (args == null) {
        return null; //TODO: member reference???
    }
    for (ExpressionTree e : args) {
        int pos = (int) sourcePositions.getEndPosition(root, e);
        if (pos != Diagnostic.NOPOS && (position > pos || !strict && position == pos)) {
            startPos = pos;
            ret.add(e);
        } else {
            break;
        }
    }
    if (startPos < 0) {
        return ret;
    }
    if (position >= startPos) {
        TokenSequence<JavaTokenId> last = findLastNonWhitespaceToken(env, startPos, position);
        if (last == null) {
            if (!strict && !ret.isEmpty()) {
                ret.remove(ret.size() - 1);
                return ret;
            }
        } else if (last.token().id() == JavaTokenId.LPAREN || last.token().id() == JavaTokenId.COMMA) {
            return ret;
        }
    }
    return null;
}
 
Example 6
Source File: JavadocUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isInHeader(CompilationInfo info, MethodTree tree, int offset) {
    CompilationUnitTree cut = info.getCompilationUnit();
    SourcePositions sp = info.getTrees().getSourcePositions();
    long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree);
    
    List<? extends ExpressionTree> throwz;
    List<? extends VariableTree> params;
    List<? extends TypeParameterTree> typeparams;
    
    if ((throwz = tree.getThrows()) != null && !throwz.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, throwz.get(throwz.size() - 1));
    } else if ((params = tree.getParameters()) != null && !params.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, params.get(params.size() - 1));
    } else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1));
    } else if (tree.getReturnType() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getReturnType());
    } else if (tree.getModifiers() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers());
    }
    
    TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree);
    
    ts.move((int) lastKnownOffsetInHeader);
    
    while (ts.moveNext()) {
        if (ts.token().id() == JavaTokenId.LBRACE || ts.token().id() == JavaTokenId.SEMICOLON) {
            return offset < ts.offset();
        }
    }
    
    return false;
}
 
Example 7
Source File: GeneratorUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static ClassTree insertClassMembers(WorkingCopy wc, ClassTree clazz, List<? extends Tree> members, int offset) throws IllegalStateException {
    if (offset < 0 || getCodeStyle(wc).getClassMemberInsertionPoint() != CodeStyle.InsertionPoint.CARET_LOCATION) {
        return GeneratorUtilities.get(wc).insertClassMembers(clazz, members);
    }
    int index = 0;
    SourcePositions sp = wc.getTrees().getSourcePositions();
    GuardedDocument gdoc = null;
    try {
        Document doc = wc.getDocument();
        if (doc != null && doc instanceof GuardedDocument) {
            gdoc = (GuardedDocument)doc;
        }
    } catch (IOException ioe) {}
    Tree lastMember = null;
    for (Tree tree : clazz.getMembers()) {
        if (offset <= sp.getStartPosition(wc.getCompilationUnit(), tree)) {
            if (gdoc == null) {
                break;
            }
            int pos = (int)(lastMember != null ? sp.getEndPosition(wc.getCompilationUnit(), lastMember) : sp.getStartPosition(wc.getCompilationUnit(), clazz));
            pos = gdoc.getGuardedBlockChain().adjustToBlockEnd(pos);
            if (pos <= sp.getStartPosition(wc.getCompilationUnit(), tree)) {
                break;
            }
        }
        index++;
        lastMember = tree;
    }
    TreeMaker tm = wc.getTreeMaker();
    for (int i = members.size() - 1; i >= 0; i--) {
        clazz = tm.insertClassMember(clazz, index, members.get(i));
    }
    return clazz;
}
 
Example 8
Source File: JsfHintsUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns the part of the syntax tree to be highlighted.
 */
public static TextSpan getUnderlineSpan(CompilationInfo info, Tree tree) {
    SourcePositions srcPos = info.getTrees().getSourcePositions();
    int startOffset = (int) srcPos.getStartPosition(info.getCompilationUnit(), tree);
    int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(), tree);
    return new TextSpan(startOffset, endOffset);
}
 
Example 9
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Token<JavaTokenId> findIdentifierSpanImplForBindingPattern(CompilationInfo info, Tree tree, CompilationUnitTree cu, SourcePositions positions) {
    int start = (int)positions.getStartPosition(cu, tree);
    int endPosition = (int)positions.getEndPosition(cu, tree);
    
    if (start == (-1) || endPosition == (-1))
        return null;

    String member = TreeShims.getBinding(tree).toString();

    TokenHierarchy<?> th = info.getTokenHierarchy();
    TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language());

    if (ts.move(endPosition) == Integer.MAX_VALUE) {
        return null;
    }

    if (ts.moveNext()) {
        while (ts.offset() >= start) {
            Token<JavaTokenId> t = ts.token();

            if (t.id() == JavaTokenId.IDENTIFIER && member.equals(info.getTreeUtilities().decodeIdentifier(t.text()).toString())) {
                return t;
            }

            if (!ts.movePrevious())
                break;
        }
    }
    return null;
}
 
Example 10
Source File: HintsUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns the part of the syntax tree to be highlighted. It will be usually the class/method/variable
 * identifier.
 */
public static TextSpan getUnderlineSpan(CompilationInfo info, Tree tree) {
    SourcePositions srcPos = info.getTrees().getSourcePositions();

    int startOffset = (int) srcPos.getStartPosition(info.getCompilationUnit(), tree);
    int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(), tree);

    Tree startSearchingForNameIndentifierBehindThisTree = null;

    if (TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())) {
        startSearchingForNameIndentifierBehindThisTree = ((ClassTree) tree).getModifiers();

    } else if (tree.getKind() == Tree.Kind.METHOD) {
        startSearchingForNameIndentifierBehindThisTree = ((MethodTree) tree).getReturnType();
    } else if (tree.getKind() == Tree.Kind.VARIABLE) {
        startSearchingForNameIndentifierBehindThisTree = ((VariableTree) tree).getType();
    }

    if (startSearchingForNameIndentifierBehindThisTree != null) {
        int searchStart = (int) srcPos.getEndPosition(info.getCompilationUnit(),
                startSearchingForNameIndentifierBehindThisTree);

        TokenSequence tokenSequence = info.getTreeUtilities().tokensFor(tree);

        if (tokenSequence != null) {
            boolean eob = false;
            tokenSequence.move(searchStart);

            do {
                eob = !tokenSequence.moveNext();
            } while (!eob && tokenSequence.token().id() != JavaTokenId.IDENTIFIER);

            if (!eob) {
                Token identifier = tokenSequence.token();
                startOffset = identifier.offset(info.getTokenHierarchy());
                endOffset = startOffset + identifier.length();
            }
        }
    }

    return new TextSpan(startOffset, endOffset);
}
 
Example 11
Source File: WebSocketMethodsTask.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private List<Integer> getElementPosition(CompilationInfo info, Tree tree) {
    SourcePositions srcPos = info.getTrees().getSourcePositions();

    int startOffset = (int) srcPos.getStartPosition(
            info.getCompilationUnit(), tree);
    int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(),
            tree);

    Tree startTree = null;

    if (TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())) {
        startTree = ((ClassTree) tree).getModifiers();

    } else if (tree.getKind() == Tree.Kind.METHOD) {
        startTree = ((MethodTree) tree).getReturnType();
    } else if (tree.getKind() == Tree.Kind.VARIABLE) {
        startTree = ((VariableTree) tree).getType();
    }

    if (startTree != null) {
        int searchStart = (int) srcPos.getEndPosition(
                info.getCompilationUnit(), startTree);

        TokenSequence<?> tokenSequence = info.getTreeUtilities().tokensFor(
                tree);

        if (tokenSequence != null) {
            boolean eob = false;
            tokenSequence.move(searchStart);

            do {
                eob = !tokenSequence.moveNext();
            } while (!eob
                    && tokenSequence.token().id() != JavaTokenId.IDENTIFIER);

            if (!eob) {
                Token<?> identifier = tokenSequence.token();
                startOffset = identifier.offset(info.getTokenHierarchy());
                endOffset = startOffset + identifier.length();
            }
        }
    }

    List<Integer> result = new ArrayList<Integer>(2);
    result.add(startOffset);
    result.add(endOffset);
    return result;
}
 
Example 12
Source File: JavaMoveCodeElementAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private TreePath widenToElementBounds(CompilationInfo cInfo, BaseDocument doc, int[] bounds) {
    SourcePositions sp = cInfo.getTrees().getSourcePositions();
    TreeUtilities tu = cInfo.getTreeUtilities();
    int startOffset = getLineStart(doc, bounds[0]);
    int endOffset = getLineEnd(doc, bounds[1]);
    while (true) {
        TokenSequence<JavaTokenId> ts = SourceUtils.getJavaTokenSequence(cInfo.getTokenHierarchy(), startOffset);
        if (ts != null && (ts.moveNext() || ts.movePrevious())) {
            if (ts.offset() < startOffset && ts.token().id() != JavaTokenId.WHITESPACE) {
                startOffset = getLineStart(doc, ts.offset());
                continue;
            }
        }
        ts = SourceUtils.getJavaTokenSequence(cInfo.getTokenHierarchy(), endOffset);
        if (ts != null && (ts.moveNext() || ts.movePrevious())) {
            if (ts.offset() < endOffset && ts.token().id() != JavaTokenId.WHITESPACE) {
                endOffset = getLineEnd(doc, ts.offset() + ts.token().length());
                continue;
            }
        }
        boolean finish = true;
        TreePath tp = tu.pathFor(startOffset);
        while (tp != null) {
            Tree leaf = tp.getLeaf();
            List<? extends Tree> children = null;
            switch (leaf.getKind()) {
                case BLOCK:
                    if (endOffset < sp.getEndPosition(tp.getCompilationUnit(), leaf)) {
                        children = ((BlockTree) leaf).getStatements();
                    }
                    break;
                case CLASS:
                case INTERFACE:
                case ANNOTATION_TYPE:
                case ENUM:
                    if (endOffset < sp.getEndPosition(tp.getCompilationUnit(), leaf)) {
                        children = ((ClassTree) leaf).getMembers();
                    }
                    break;
            }
            if (children != null) {
                for (Tree tree : children) {
                    int startPos = (int) sp.getStartPosition(tp.getCompilationUnit(), tree);
                    int endPos = (int) sp.getEndPosition(tp.getCompilationUnit(), tree);
                    if (endPos > startOffset) {
                        if (startPos < startOffset) {
                            startOffset = getLineStart(doc, startPos);
                            finish = false;
                        }
                        if (startPos < endOffset && endOffset < endPos) {
                            endOffset = getLineEnd(doc, endPos);
                            finish = false;
                        }
                    }
                }
                break;
            }
            tp = tp.getParentPath();
        }
        if (finish) {
            bounds[0] = startOffset;
            bounds[1] = endOffset;
            return tp;
        }
    }
}
 
Example 13
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static Token<JavaTokenId> createHighlightImpl(CompilationInfo info, Document doc, TreePath tree) {
    Tree leaf = tree.getLeaf();
    SourcePositions positions = info.getTrees().getSourcePositions();
    CompilationUnitTree cu = info.getCompilationUnit();
    
    //XXX: do not use instanceof:
    if (leaf instanceof MethodTree || leaf instanceof VariableTree || leaf instanceof ClassTree
            || leaf instanceof MemberSelectTree || leaf instanceof AnnotatedTypeTree || leaf instanceof MemberReferenceTree
            || "BINDING_PATTERN".equals(leaf.getKind().name())) {
        return findIdentifierSpan(info, doc, tree);
    }
    
    int start = (int) positions.getStartPosition(cu, leaf);
    int end = (int) positions.getEndPosition(cu, leaf);
    
    if (start == Diagnostic.NOPOS || end == Diagnostic.NOPOS) {
        return null;
    }
    
    TokenHierarchy<?> th = info.getTokenHierarchy();
    TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language());
    
    if (ts.move(start) == Integer.MAX_VALUE) {
        return null;
    }
    
    if (ts.moveNext()) {
        Token<JavaTokenId> token = ts.token();
        if (ts.offset() == start && token != null) {
            final JavaTokenId id = token.id();
            if (id == JavaTokenId.IDENTIFIER) {
                return token;
            }
            if (id == JavaTokenId.THIS || id == JavaTokenId.SUPER) {
                return ts.offsetToken();
            }
        }
    }
    
    return null;
}
 
Example 14
Source File: RestScanTask.java    From netbeans with Apache License 2.0 4 votes vote down vote up
static List<Integer> getElementPosition(CompilationInfo info, Tree tree){
    SourcePositions srcPos = info.getTrees().getSourcePositions();
    
    int startOffset = (int) srcPos.getStartPosition(info.getCompilationUnit(), tree);
    int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(), tree);
    
    Tree startTree = null;
    
    if (TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())){
        startTree = ((ClassTree)tree).getModifiers();
        
    } else if (tree.getKind() == Tree.Kind.METHOD){
        startTree = ((MethodTree)tree).getReturnType();
    } else if (tree.getKind() == Tree.Kind.VARIABLE){
        startTree = ((VariableTree)tree).getType();
    }
    
    if (startTree != null){
        int searchStart = (int) srcPos.getEndPosition(info.getCompilationUnit(),
                startTree);
        
        TokenSequence<?> tokenSequence = info.getTreeUtilities().tokensFor(tree);
        
        if (tokenSequence != null){
            boolean eob = false;
            tokenSequence.move(searchStart);
            
            do{
                eob = !tokenSequence.moveNext();
            }
            while (!eob && tokenSequence.token().id() != JavaTokenId.IDENTIFIER);
            
            if (!eob){
                Token<?> identifier = tokenSequence.token();
                startOffset = identifier.offset(info.getTokenHierarchy());
                endOffset = startOffset + identifier.length();
            }
        }
    }
    
    List<Integer> result = new ArrayList<Integer>(2);
    result.add(startOffset);
    result.add(endOffset );
    return result;
}
 
Example 15
Source File: MarkOccurrencesHighlighterBase.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean isIn(CompilationUnitTree cu, SourcePositions sp, Tree tree, int position) {
    return sp.getStartPosition(cu, tree) <= position && position <= sp.getEndPosition(cu, tree);
}
 
Example 16
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns the part of the syntax tree to be highlighted.
 * It will be usually the class/method/variable identifier.
 */
public static TextSpan getUnderlineSpan(CompilationInfo info, Tree tree){
    SourcePositions srcPos = info.getTrees().getSourcePositions();
    
    int startOffset = (int) srcPos.getStartPosition(info.getCompilationUnit(), tree);
    int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(), tree);
    
    Tree startSearchingForNameIndentifierBehindThisTree = null;
    
    if(tree != null) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())){
            startSearchingForNameIndentifierBehindThisTree = ((ClassTree)tree).getModifiers();

        } else if (tree.getKind() == Tree.Kind.METHOD){
            startSearchingForNameIndentifierBehindThisTree = ((MethodTree)tree).getReturnType();
        } else if (tree.getKind() == Tree.Kind.VARIABLE){
            startSearchingForNameIndentifierBehindThisTree = ((VariableTree)tree).getType();
        }

        if (startSearchingForNameIndentifierBehindThisTree != null){
            int searchStart = (int) srcPos.getEndPosition(info.getCompilationUnit(),
                    startSearchingForNameIndentifierBehindThisTree);

            TokenSequence tokenSequence = info.getTreeUtilities().tokensFor(tree);

            if (tokenSequence != null){
                boolean eob = false;
                tokenSequence.move(searchStart);

                do{
                    eob = !tokenSequence.moveNext();
                }
                while (!eob && tokenSequence.token().id() != JavaTokenId.IDENTIFIER);

                if (!eob){
                    Token identifier = tokenSequence.token();
                    startOffset = identifier.offset(info.getTokenHierarchy());
                    endOffset = startOffset + identifier.length();
                }
            }
        }
    }
    return new TextSpan(startOffset, endOffset);
}
 
Example 17
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private TokenSequence<JavaTokenId> tokensFor(Tree tree, SourcePositions sourcePositions, int farEnd) {
    int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), tree);
    int end   = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), tree);
    
    return info.getTokenHierarchy().tokenSequence(JavaTokenId.language()).subSequence(start, Math.max(end, farEnd));
}
 
Example 18
Source File: JavaMoveCodeElementAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private int findDestinationOffset(CompilationInfo cInfo, BaseDocument doc, int offset, boolean insideBlock) {
    TreeUtilities tu = cInfo.getTreeUtilities();
    SourcePositions sp = cInfo.getTrees().getSourcePositions();
    while (true) {
        if (offset < 0 || offset > doc.getLength()) {
            return -1;
        }
        int destinationOffset = downward ? getLineEnd(doc, offset) : getLineStart(doc, offset);
        if (doc instanceof GuardedDocument && ((GuardedDocument)doc).isPosGuarded(destinationOffset)) {
            return -1;
        }
        if (destinationOffset < doc.getLength()) {
            TokenSequence<JavaTokenId> ts = SourceUtils.getJavaTokenSequence(cInfo.getTokenHierarchy(), destinationOffset);
            if (ts != null && (ts.moveNext() || ts.movePrevious())) {
                if (ts.offset() < destinationOffset && ts.token().id() != JavaTokenId.WHITESPACE) {
                    offset = downward ? ts.offset() + ts.token().length() : ts.offset();
                    continue;
                }
            }
        }
        TreePath destinationPath = tu.pathFor(destinationOffset);
        Tree leaf = destinationPath.getLeaf();
        if (insideBlock) {
            switch (leaf.getKind()) {
                case COMPILATION_UNIT:
                    return -1;
                case BLOCK:
                    return destinationOffset;
                case IF:
                case FOR_LOOP:
                case ENHANCED_FOR_LOOP:
                case WHILE_LOOP:
                case DO_WHILE_LOOP:
                case SWITCH:
                case CASE:
                case SYNCHRONIZED:
                case TRY:
                case CATCH:
                    offset = destinationOffset + (downward ? 1 : -1);
                    break;
                default:
                    offset = downward
                            ? (int) sp.getEndPosition(destinationPath.getCompilationUnit(), leaf)
                            : (int) sp.getStartPosition(destinationPath.getCompilationUnit(), leaf);
            }
        } else {
            switch (leaf.getKind()) {
                case COMPILATION_UNIT:
                    return -1;
                case CLASS:
                case INTERFACE:
                case ANNOTATION_TYPE:
                case ENUM:
                    return destinationOffset;
                default:
                    offset = downward
                            ? (int) sp.getEndPosition(destinationPath.getCompilationUnit(), leaf)
                            : (int) sp.getStartPosition(destinationPath.getCompilationUnit(), leaf);
            }
        }
    }
}
 
Example 19
Source File: PositionEstimator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override()
public void initialize() {
    int size = oldL.size();
    data = new ArrayList<int[]>(size);
    SourcePositions positions = diffContext.trees.getSourcePositions();
    CompilationUnitTree compilationUnit = diffContext.origUnit;
    
    for (Tree item : oldL) {
        int treeStart = (int) positions.getStartPosition(compilationUnit, item);
        int treeEnd = (int) positions.getEndPosition(compilationUnit, item);

        seq.move(treeStart);
        seq.moveNext();
        if (null != moveToSrcRelevant(seq, Direction.BACKWARD)) {
            seq.moveNext();
        }
        int previousEnd = seq.offset();
        Token<JavaTokenId> token;
        while (nonRelevant.contains((token = seq.token()).id())) {
            int localResult = -1;
            switch (token.id()) {
                case WHITESPACE:
                    int indexOf = token.text().toString().indexOf('\n');
                    if (indexOf > -1) {
                        localResult = seq.offset() + indexOf;
                    }
                    break;
                case LINE_COMMENT:
                    previousEnd = seq.offset() + token.text().length();
                    break;
            }
            if (localResult > 0) {
                previousEnd = localResult;
                break;
            }
            if (!seq.moveNext()) break;
        }
        data.add(new int[] { previousEnd, treeEnd, previousEnd });
    }
    initialized = true;
}
 
Example 20
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns the part of the syntax tree to be highlighted.
 * It will be usually the class/method/variable identifier.
 */
public static TextSpan getUnderlineSpan(CompilationInfo info, Tree tree) {
    SourcePositions srcPos = info.getTrees().getSourcePositions();

    int startOffset = (int) srcPos.getStartPosition(info.getCompilationUnit(), tree);
    int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(), tree);

    Tree startSearchingForNameIndentifierBehindThisTree = null;

    if (TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())) {
        startSearchingForNameIndentifierBehindThisTree = ((ClassTree) tree).getModifiers();
    } else if (tree.getKind() == Tree.Kind.METHOD) {
        startSearchingForNameIndentifierBehindThisTree = ((MethodTree) tree).getReturnType();
    } else if (tree.getKind() == Tree.Kind.VARIABLE) {
        startSearchingForNameIndentifierBehindThisTree = ((VariableTree) tree).getType();
    }

    if (startSearchingForNameIndentifierBehindThisTree != null) {
        int searchStart = (int) srcPos.getEndPosition(info.getCompilationUnit(),
                startSearchingForNameIndentifierBehindThisTree);

        TokenSequence<JavaTokenId> tokenSequence = info.getTreeUtilities().tokensFor(tree);

        if (tokenSequence != null) {
            boolean eob = false;
            tokenSequence.move(searchStart);

            do {
                eob = !tokenSequence.moveNext();
            } while (!eob && tokenSequence.token().id() != JavaTokenId.IDENTIFIER);

            if (!eob) {
                Token<JavaTokenId> identifier = tokenSequence.token();
                startOffset = identifier.offset(info.getTokenHierarchy());
                endOffset = startOffset + identifier.length();
            }
        }
    }

    return new TextSpan(startOffset, endOffset);
}