Example usage for org.eclipse.jdt.internal.compiler.parser Scanner resetTo

List of usage examples for org.eclipse.jdt.internal.compiler.parser Scanner resetTo

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.parser Scanner resetTo.

Prototype

public void resetTo(int begin, int end) 

Source Link

Document

Reposition the scanner on some portion of the original source.

Usage

From source file:com.codenvy.ide.ext.java.server.internal.codeassist.SelectionEngine.java

License:Open Source License

private boolean checkSelection(char[] source, int selectionStart, int selectionEnd) {

    Scanner scanner = new Scanner(false /*comment*/, false /*whitespace*/, false /*nls*/,
            this.compilerOptions.sourceLevel, this.compilerOptions.complianceLevel, null/*taskTag*/,
            null/*taskPriorities*/, true /*taskCaseSensitive*/);
    scanner.setSource(source);//from   w w w.  ja  v a2  s  .c o  m

    int lastIdentifierStart = -1;
    int lastIdentifierEnd = -1;
    char[] lastIdentifier = null;
    int token;

    if (selectionStart > selectionEnd) {
        int end = source.length - 1;

        // compute start position of current line
        int currentPosition = selectionStart - 1;
        int nextCharacterPosition = selectionStart;
        char currentCharacter = ' ';
        try {
            lineLoop: while (currentPosition > 0) {

                if (source[currentPosition] == '\\' && source[currentPosition + 1] == 'u') {
                    int pos = currentPosition + 2;
                    int c1 = 0, c2 = 0, c3 = 0, c4 = 0;
                    while (source[pos] == 'u') {
                        pos++;
                    }

                    int endOfUnicode = pos + 3;
                    if (end < endOfUnicode) {
                        if (endOfUnicode < source.length) {
                            end = endOfUnicode;
                        } else {
                            return false; // not enough characters to decode an unicode
                        }
                    }

                    if ((c1 = ScannerHelper.getHexadecimalValue(source[pos++])) > 15 || c1 < 0
                            || (c2 = ScannerHelper.getHexadecimalValue(source[pos++])) > 15 || c2 < 0
                            || (c3 = ScannerHelper.getHexadecimalValue(source[pos++])) > 15 || c3 < 0
                            || (c4 = ScannerHelper.getHexadecimalValue(source[pos++])) > 15 || c4 < 0) {
                        return false;
                    } else {
                        currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
                        nextCharacterPosition = pos;
                    }
                } else {
                    currentCharacter = source[currentPosition];
                    nextCharacterPosition = currentPosition + 1;
                }

                switch (currentCharacter) {
                case '\r':
                case '\n':
                case '/':
                case '"':
                case '\'':
                    break lineLoop;
                }
                currentPosition--;
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            return false;
        }

        // compute start and end of the last token
        scanner.resetTo(nextCharacterPosition, end);
        isolateLastName: do {
            try {
                token = scanner.getNextToken();
            } catch (InvalidInputException e) {
                return false;
            }
            switch (token) {
            case TerminalTokens.TokenNamethis:
            case TerminalTokens.TokenNamesuper:
            case TerminalTokens.TokenNamenew:
            case TerminalTokens.TokenNameIdentifier:
                if (scanner.startPosition <= selectionStart && selectionStart <= scanner.currentPosition) {
                    if (scanner.currentPosition == scanner.eofPosition) {
                        int temp = scanner.eofPosition;
                        scanner.eofPosition = scanner.source.length;
                        while (scanner.getNextCharAsJavaIdentifierPart()) {
                            /*empty*/}
                        scanner.eofPosition = temp;
                    }
                    lastIdentifierStart = scanner.startPosition;
                    lastIdentifierEnd = scanner.currentPosition - 1;
                    lastIdentifier = scanner.getCurrentTokenSource();
                    break isolateLastName;
                }
                break;
            }
        } while (token != TerminalTokens.TokenNameEOF);
    } else {
        if (selectionStart == selectionEnd) { // Widen the selection to scan -> || :: if needed. No unicode handling for now.
            if (selectionStart > 0 && selectionEnd < source.length - 1) {
                if ((source[selectionStart] == '>' && source[selectionStart - 1] == '-')
                        || source[selectionStart] == ':' && source[selectionStart - 1] == ':') {
                    selectionStart--;
                } else {
                    if ((source[selectionStart] == '-' && source[selectionEnd + 1] == '>')
                            || source[selectionStart] == ':' && source[selectionEnd + 1] == ':') {
                        selectionEnd++;
                    }
                }
            }
        } // there could be some innocuous widening, shouldn't matter.
        scanner.resetTo(selectionStart, selectionEnd);

        boolean expectingIdentifier = true;
        do {
            try {
                token = scanner.getNextToken();
            } catch (InvalidInputException e) {
                return false;
            }
            switch (token) {
            case TerminalTokens.TokenNamethis:
            case TerminalTokens.TokenNamesuper:
            case TerminalTokens.TokenNamenew:
            case TerminalTokens.TokenNameIdentifier:
                if (!expectingIdentifier)
                    return false;
                lastIdentifier = scanner.getCurrentTokenSource();
                lastIdentifierStart = scanner.startPosition;
                lastIdentifierEnd = scanner.currentPosition - 1;
                if (lastIdentifierEnd > selectionEnd) {
                    lastIdentifierEnd = selectionEnd;
                    lastIdentifier = CharOperation.subarray(lastIdentifier, 0,
                            lastIdentifierEnd - lastIdentifierStart + 1);
                }
                expectingIdentifier = false;
                break;
            case TerminalTokens.TokenNameCOLON_COLON:
                if (selectionStart >= scanner.startPosition && selectionEnd < scanner.currentPosition) {
                    this.actualSelectionStart = selectionStart;
                    this.actualSelectionEnd = selectionEnd;
                    this.selectedIdentifier = CharOperation.NO_CHAR;
                    return true;
                }
                //$FALL-THROUGH$
            case TerminalTokens.TokenNameDOT:
                if (expectingIdentifier)
                    return false;
                expectingIdentifier = true;
                break;
            case TerminalTokens.TokenNameEOF:
                if (expectingIdentifier)
                    return false;
                break;
            case TerminalTokens.TokenNameLESS:
                if (!checkTypeArgument(scanner))
                    return false;
                break;
            case TerminalTokens.TokenNameAT:
                if (scanner.startPosition != scanner.initialPosition)
                    return false;
                break;
            case TerminalTokens.TokenNameARROW:
                if (selectionStart >= scanner.startPosition && selectionEnd < scanner.currentPosition) {
                    this.actualSelectionStart = selectionStart;
                    this.actualSelectionEnd = selectionEnd;
                    this.selectedIdentifier = CharOperation.NO_CHAR;
                    return true;
                }
                return false;
            default:
                return false;
            }
        } while (token != TerminalTokens.TokenNameEOF);
    }
    if (lastIdentifierStart > 0) {
        this.actualSelectionStart = lastIdentifierStart;
        this.actualSelectionEnd = lastIdentifierEnd;
        this.selectedIdentifier = lastIdentifier;
        return true;
    }
    return false;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Finds the accurate positions of the sequence of tokens given by qualifiedName
 * in the source and reports a reference to this this qualified name
 * to the search requestor./*w  w  w .  j  a  v  a  2s  . co  m*/
 */
protected void reportAccurateTypeReference(SearchMatch match, ASTNode typeRef, char[] name)
        throws CoreException {
    if (match.getRule() == 0)
        return;
    if (!encloses((IJavaElement) match.getElement()))
        return;

    int sourceStart = typeRef.sourceStart;
    int sourceEnd = typeRef.sourceEnd;

    // Compute source positions of the qualified reference
    if (name != null) {
        Scanner scanner = this.parser.scanner;
        scanner.setSource(this.currentPossibleMatch.getContents());
        scanner.resetTo(sourceStart, sourceEnd);

        int token = -1;
        int currentPosition;
        do {
            currentPosition = scanner.currentPosition;
            try {
                token = scanner.getNextToken();
            } catch (InvalidInputException e) {
                // ignore
            }
            if (token == TerminalTokens.TokenNameIdentifier
                    && this.pattern.matchesName(name, scanner.getCurrentTokenSource())) {
                int length = scanner.currentPosition - currentPosition;
                match.setOffset(currentPosition);
                match.setLength(length);
                report(match);
                return;
            }
        } while (token != TerminalTokens.TokenNameEOF);
    }

    //   Report match
    match.setOffset(sourceStart);
    match.setLength(sourceEnd - sourceStart + 1);
    report(match);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Finds the accurate positions of the sequence of tokens given by qualifiedName
 * in the source and reports a reference to this parameterized type name
 * to the search requestor./*from  w  ww. j av  a 2s .co  m*/
 * @since 3.1
 */
protected void reportAccurateParameterizedMethodReference(SearchMatch match, ASTNode statement,
        TypeReference[] typeArguments) throws CoreException {

    if (match.getRule() == 0)
        return;
    if (!encloses((IJavaElement) match.getElement()))
        return;

    // If there's type arguments, look for end (i.e. char '>') of last one.
    int start = match.getOffset();
    if (typeArguments != null && typeArguments.length > 0) {
        boolean isErasureMatch = (this.pattern instanceof OrPattern)
                ? ((OrPattern) this.pattern).isErasureMatch()
                : ((JavaSearchPattern) this.pattern).isErasureMatch();
        if (!isErasureMatch) {

            // Initialize scanner
            Scanner scanner = this.parser.scanner;
            char[] source = this.currentPossibleMatch.getContents();
            scanner.setSource(source);

            // Search previous opening '<'
            start = typeArguments[0].sourceStart;
            int end = statement.sourceEnd;
            scanner.resetTo(start, end);
            int lineStart = start;
            try {
                linesUp: while (true) {
                    while (scanner.source[scanner.currentPosition] != '\n') {
                        scanner.currentPosition--;
                        if (scanner.currentPosition == 0)
                            break linesUp;
                    }
                    lineStart = scanner.currentPosition + 1;
                    scanner.resetTo(lineStart, end);
                    while (!scanner.atEnd()) {
                        if (scanner.getNextToken() == TerminalTokens.TokenNameLESS) {
                            start = scanner.getCurrentTokenStartPosition();
                            break linesUp;
                        }
                    }
                    end = lineStart - 2;
                    scanner.currentPosition = end;
                }
            } catch (InvalidInputException ex) {
                // give up
            }
        }
    }

    // Report match
    match.setOffset(start);
    match.setLength(statement.sourceEnd - start + 1);
    report(match);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Finds the accurate positions of the sequence of tokens given by qualifiedName
 * in the source and reports a reference to this parameterized type name
 * to the search requestor./*www .j  a v a 2  s .  c o  m*/
 * @since 3.1
 */
protected void reportAccurateParameterizedTypeReference(SearchMatch match, TypeReference typeRef, int index,
        TypeReference[] typeArguments) throws CoreException {
    if (match.getRule() == 0)
        return;
    if (!encloses((IJavaElement) match.getElement()))
        return;

    // If there's type arguments, look for end (i.e. char '>') of last one.
    int end = typeRef.sourceEnd;
    if (typeArguments != null) {

        boolean shouldMatchErasure = (this.pattern instanceof OrPattern)
                ? ((OrPattern) this.pattern).isErasureMatch()
                : ((JavaSearchPattern) this.pattern).isErasureMatch();
        boolean hasSignatures = (this.pattern instanceof OrPattern) ? ((OrPattern) this.pattern).hasSignatures()
                : ((JavaSearchPattern) this.pattern).hasSignatures();
        if (shouldMatchErasure || !hasSignatures) {
            // if pattern is erasure only, then select the end of the reference
            if (typeRef instanceof QualifiedTypeReference && index >= 0) {
                long[] positions = ((QualifiedTypeReference) typeRef).sourcePositions;
                end = (int) positions[index];
            } else if (typeRef instanceof ArrayTypeReference) {
                end = ((ArrayTypeReference) typeRef).originalSourceEnd;
            }
        } else {
            // Initialize scanner
            Scanner scanner = this.parser.scanner;
            char[] source = this.currentPossibleMatch.getContents();
            scanner.setSource(source);

            // Set scanner position at end of last type argument
            scanner.resetTo(end, source.length - 1);
            int depth = 0;
            for (int i = typeArguments.length - 1; i >= 0; i--) {
                if (typeArguments[i] != null) {
                    long lastTypeArgInfo = findLastTypeArgumentInfo(typeArguments[i]);
                    depth = (int) (lastTypeArgInfo >>> 32) + 1;
                    scanner.resetTo(((int) lastTypeArgInfo) + 1, scanner.eofPosition - 1);
                    break;
                }
            }

            // Now, scan to search next closing '>'
            while (depth-- > 0) {
                while (!scanner.atEnd()) {
                    if (scanner.getNextChar() == '>') {
                        end = scanner.currentPosition - 1;
                        break;
                    }
                }
            }
        }
    }

    // Report match
    match.setLength(end - match.getOffset() + 1);
    report(match);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Finds the accurate positions of each valid token in the source and
 * reports a reference to this token to the search requestor.
 * A token is valid if it has an accuracy which is not -1.
 *//*w  w  w .j  av a2 s.co m*/
protected void reportAccurateEnumConstructorReference(SearchMatch match, FieldDeclaration field,
        AllocationExpression allocation) throws CoreException {
    // Verify that field declaration is really an enum constant
    if (allocation == null || allocation.enumConstant == null) {
        report(match);
        return;
    }

    // Get scan area
    int sourceStart = match.getOffset() + match.getLength();
    if (allocation.arguments != null && allocation.arguments.length > 0) {
        sourceStart = allocation.arguments[allocation.arguments.length - 1].sourceEnd + 1;
    }
    int sourceEnd = field.declarationSourceEnd;
    if (allocation instanceof QualifiedAllocationExpression) {
        QualifiedAllocationExpression qualifiedAllocation = (QualifiedAllocationExpression) allocation;
        if (qualifiedAllocation.anonymousType != null) {
            sourceEnd = qualifiedAllocation.anonymousType.sourceStart - 1;
        }
    }

    // Scan to find last closing parenthesis
    Scanner scanner = this.parser.scanner;
    scanner.setSource(this.currentPossibleMatch.getContents());
    scanner.resetTo(sourceStart, sourceEnd);
    try {
        int token = scanner.getNextToken();
        while (token != TerminalTokens.TokenNameEOF) {
            if (token == TerminalTokens.TokenNameRPAREN) {
                sourceEnd = scanner.getCurrentTokenEndPosition();
            }
            token = scanner.getNextToken();
        }
    } catch (InvalidInputException iie) {
        // give up
    }

    // Report match
    match.setLength(sourceEnd - match.getOffset() + 1);
    report(match);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Finds the accurate positions of each valid token in the source and
 * reports a reference to this token to the search requestor.
 * A token is valid if it has an accuracy which is not -1.
 *//*from w  w  w  .  ja v a2 s .c  o m*/
protected void reportAccurateFieldReference(SearchMatch[] matches, QualifiedNameReference qNameRef)
        throws CoreException {
    if (matches == null)
        return; // there's nothing to accurate in this case
    int matchesLength = matches.length;

    int sourceStart = qNameRef.sourceStart;
    int sourceEnd = qNameRef.sourceEnd;
    char[][] tokens = qNameRef.tokens;

    // compute source positions of the qualified reference
    Scanner scanner = this.parser.scanner;
    scanner.setSource(this.currentPossibleMatch.getContents());
    scanner.resetTo(sourceStart, sourceEnd);
    int sourceLength = sourceEnd - sourceStart + 1;

    int refSourceStart = -1, refSourceEnd = -1;
    int length = tokens.length;
    int token = -1;
    int previousValid = -1;
    int i = 0;
    int index = 0;
    do {
        int currentPosition = scanner.currentPosition;
        // read token
        try {
            token = scanner.getNextToken();
        } catch (InvalidInputException e) {
            //ignore
        }
        if (token != TerminalTokens.TokenNameEOF) {
            char[] currentTokenSource = scanner.getCurrentTokenSource();
            boolean equals = false;
            while (i < length && !(equals = this.pattern.matchesName(tokens[i++], currentTokenSource))) {
                /*empty*/}
            if (equals && (previousValid == -1 || previousValid == i - 2)) {
                previousValid = i - 1;
                if (refSourceStart == -1)
                    refSourceStart = currentPosition;
                refSourceEnd = scanner.currentPosition - 1;
            } else {
                i = 0;
                refSourceStart = -1;
                previousValid = -1;
            }
            // read '.'
            try {
                token = scanner.getNextToken();
            } catch (InvalidInputException e) {
                // ignore
            }
        }
        SearchMatch match = matches[index];
        if (match != null && match.getRule() != 0) {
            if (!encloses((IJavaElement) match.getElement()))
                return;
            // accept reference
            if (refSourceStart != -1) {
                match.setOffset(refSourceStart);
                match.setLength(refSourceEnd - refSourceStart + 1);
                report(match);
            } else {
                match.setOffset(sourceStart);
                match.setLength(sourceLength);
                report(match);
            }
            i = 0;
        }
        refSourceStart = -1;
        previousValid = -1;
        if (index < matchesLength - 1) {
            index++;
        }
    } while (token != TerminalTokens.TokenNameEOF);

}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Visit the given method declaration and report the nodes that match exactly the
 * search pattern (i.e. the ones in the matching nodes set)
 * Note that the method declaration has already been checked.
 *///  w  ww. j a v a  2  s . c  o m
protected void reportMatching(AbstractMethodDeclaration method, TypeDeclaration type, IJavaElement parent,
        int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException {
    IJavaElement enclosingElement = null;

    // report method declaration itself
    if (accuracy > -1) {
        enclosingElement = createHandle(method, parent);
        if (enclosingElement != null) { // skip if unable to find method
            // compute source positions of the selector
            Scanner scanner = this.parser.scanner;
            int nameSourceStart = method.sourceStart;
            scanner.setSource(this.currentPossibleMatch.getContents());
            scanner.resetTo(nameSourceStart, method.sourceEnd);
            try {
                scanner.getNextToken();
            } catch (InvalidInputException e) {
                // ignore
            }
            if (encloses(enclosingElement)) {
                SearchMatch match = null;
                if (method.isDefaultConstructor()) {
                    // Use type for match associated element as default constructor does not exist in source
                    int offset = type.sourceStart;
                    match = this.patternLocator.newDeclarationMatch(type, parent, type.binding, accuracy,
                            type.sourceEnd - offset + 1, this);
                } else {
                    int length = scanner.currentPosition - nameSourceStart;
                    match = this.patternLocator.newDeclarationMatch(method, enclosingElement, method.binding,
                            accuracy, length, this);
                }
                if (match != null) {
                    report(match);
                }
            }
        }
    }

    // handle nodes for the local type first
    if ((method.bits & ASTNode.HasLocalType) != 0) {
        if (enclosingElement == null) {
            enclosingElement = createHandle(method, parent);
        }
        // Traverse method declaration to report matches both in local types declaration
        // and in local variables declaration
        ASTNode[] nodes = typeInHierarchy
                ? nodeSet.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd)
                : null;
        boolean report = (this.matchContainer & PatternLocator.METHOD_CONTAINER) != 0
                && encloses(enclosingElement);
        MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement,
                report ? nodes : null, nodeSet, this);
        try {
            method.traverse(declarationVisitor, (ClassScope) null);
        } catch (WrappedCoreException e) {
            throw e.coreException;
        }
        // Report all nodes and remove them
        if (nodes != null) {
            int length = nodes.length;
            for (int i = 0; i < length; i++) {
                Integer level = (Integer) nodeSet.matchingNodes.removeKey(nodes[i]);
                if (report && level != null) {
                    this.patternLocator.matchReportReference(nodes[i], enclosingElement,
                            declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i),
                            method.binding, level.intValue(), this);
                }
            }
        }
    }

    // report the type parameters
    TypeParameter[] typeParameters = method.typeParameters();
    if (typeParameters != null) {
        if (enclosingElement == null) {
            enclosingElement = createHandle(method, parent);
        }
        if (enclosingElement != null) {
            reportMatching(typeParameters, enclosingElement, parent, method.binding, nodeSet);
        }
    }

    // report annotations
    if (method.annotations != null) {
        if (enclosingElement == null) {
            enclosingElement = createHandle(method, parent);
        }
        if (enclosingElement != null) {
            reportMatching(method.annotations, enclosingElement, null, method.binding, nodeSet, true, true);
        }
    }

    // references in this method
    if (typeInHierarchy) {
        ASTNode[] nodes = nodeSet.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd);
        if (nodes != null) {
            if ((this.matchContainer & PatternLocator.METHOD_CONTAINER) != 0) {
                if (enclosingElement == null) {
                    enclosingElement = createHandle(method, parent);
                }
                if (encloses(enclosingElement)) {
                    if (this.pattern.mustResolve) {
                        // Visit only if the pattern must resolve
                        MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(
                                enclosingElement, nodes, nodeSet, this);
                        method.traverse(declarationVisitor, (ClassScope) null);
                        int length = nodes.length;
                        for (int i = 0; i < length; i++) {
                            Integer level = (Integer) nodeSet.matchingNodes.removeKey(nodes[i]);
                            if (level != null) { // ensure that the reference has not been already reported while visiting
                                this.patternLocator.matchReportReference(nodes[i], enclosingElement,
                                        declarationVisitor.getLocalElement(i),
                                        declarationVisitor.getOtherElements(i), method.binding,
                                        level.intValue(), this);
                            }
                        }
                    } else {
                        for (int i = 0, l = nodes.length; i < l; i++) {
                            ASTNode node = nodes[i];
                            Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
                            if (level != null) { // ensure that the reference has not been already reported while visiting
                                this.patternLocator.matchReportReference(node, enclosingElement, null, null,
                                        method.binding, level.intValue(), this);
                            }
                        }
                    }
                    return;
                }
            }
            // Remove all remaining nodes
            for (int i = 0, l = nodes.length; i < l; i++) {
                nodeSet.matchingNodes.removeKey(nodes[i]);
            }
        }
    }
}

From source file:org.eclipse.che.jdt.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Finds the accurate positions of the sequence of tokens given by qualifiedName
 * in the source and reports a reference to this parameterized type name
 * to the search requestor./*from  w ww. j  av  a 2  s . c  om*/
 * @since 3.1
 */
protected void reportAccurateParameterizedMethodReference(SearchMatch match, ASTNode statement,
        TypeReference[] typeArguments) throws CoreException {
    if (match.getRule() == 0)
        return;
    if (!encloses((IJavaElement) match.getElement()))
        return;

    // If there's type arguments, look for end (i.e. char '>') of last one.
    int start = match.getOffset();
    if (typeArguments != null && typeArguments.length > 0) {
        boolean isErasureMatch = (this.pattern instanceof OrPattern)
                ? ((OrPattern) this.pattern).isErasureMatch()
                : ((JavaSearchPattern) this.pattern).isErasureMatch();
        if (!isErasureMatch) {

            // Initialize scanner
            Scanner scanner = this.parser.scanner;
            char[] source = this.currentPossibleMatch.getContents();
            scanner.setSource(source);

            // Search previous opening '<'
            start = typeArguments[0].sourceStart;
            int end = statement.sourceEnd;
            scanner.resetTo(start, end);
            int lineStart = start;
            try {
                linesUp: while (true) {
                    while (scanner.source[scanner.currentPosition] != '\n') {
                        scanner.currentPosition--;
                        if (scanner.currentPosition == 0)
                            break linesUp;
                    }
                    lineStart = scanner.currentPosition + 1;
                    scanner.resetTo(lineStart, end);
                    while (!scanner.atEnd()) {
                        if (scanner.getNextToken() == TerminalTokens.TokenNameLESS) {
                            start = scanner.getCurrentTokenStartPosition();
                            break linesUp;
                        }
                    }
                    end = lineStart - 2;
                    scanner.currentPosition = end;
                }
            } catch (InvalidInputException ex) {
                // give up
            }
        }
    }

    // Report match
    match.setOffset(start);
    match.setLength(statement.sourceEnd - start + 1);
    report(match);
}

From source file:org.eclipse.che.jdt.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
* Visit the given method declaration and report the nodes that match exactly the
* search pattern (i.e. the ones in the matching nodes set)
* Note that the method declaration has already been checked.
*//*from  ww w . j a va2s  .co  m*/
protected void reportMatching(AbstractMethodDeclaration method, TypeDeclaration type, IJavaElement parent,
        int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException {
    IJavaElement enclosingElement = null;

    // report method declaration itself
    if (accuracy > -1) {
        enclosingElement = createHandle(method, parent);
        if (enclosingElement != null) { // skip if unable to find method
            // compute source positions of the selector
            Scanner scanner = this.parser.scanner;
            int nameSourceStart = method.sourceStart;
            scanner.setSource(this.currentPossibleMatch.getContents());
            scanner.resetTo(nameSourceStart, method.sourceEnd);
            try {
                scanner.getNextToken();
            } catch (InvalidInputException e) {
                // ignore
            }
            if (encloses(enclosingElement)) {
                SearchMatch match = null;
                if (method.isDefaultConstructor()) {
                    // Use type for match associated element as default constructor does not exist in source
                    int offset = type.sourceStart;
                    match = this.patternLocator.newDeclarationMatch(type, parent, type.binding, accuracy,
                            type.sourceEnd - offset + 1, this);
                } else {
                    int length = scanner.currentPosition - nameSourceStart;
                    match = this.patternLocator.newDeclarationMatch(method, enclosingElement, method.binding,
                            accuracy, length, this);
                }
                if (match != null) {
                    report(match);
                }
            }
        }
    }

    // handle nodes for the local type first
    if ((method.bits & ASTNode.HasLocalType) != 0) {
        if (enclosingElement == null) {
            enclosingElement = createHandle(method, parent);
        }
        // Traverse method declaration to report matches both in local types declaration
        // and in local variables declaration
        ASTNode[] nodes = typeInHierarchy
                ? nodeSet.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd)
                : null;
        boolean report = (this.matchContainer & PatternLocator.METHOD_CONTAINER) != 0
                && encloses(enclosingElement);
        MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement,
                report ? nodes : null, nodeSet, this, typeInHierarchy);
        try {
            method.traverse(declarationVisitor, (ClassScope) null);
        } catch (WrappedCoreException e) {
            throw e.coreException;
        }
        // Report all nodes and remove them
        if (nodes != null) {
            int length = nodes.length;
            for (int i = 0; i < length; i++) {
                Integer level = (Integer) nodeSet.matchingNodes.removeKey(nodes[i]);
                if (report && level != null) {
                    this.patternLocator.matchReportReference(nodes[i], enclosingElement,
                            declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i),
                            method.binding, level.intValue(), this);
                }
            }
        }
    }

    // report the type parameters
    TypeParameter[] typeParameters = method.typeParameters();
    if (typeParameters != null) {
        if (enclosingElement == null) {
            enclosingElement = createHandle(method, parent);
        }
        if (enclosingElement != null) {
            reportMatching(typeParameters, enclosingElement, parent, method.binding, nodeSet);
        }
    }

    // report annotations
    if (method.annotations != null) {
        if (enclosingElement == null) {
            enclosingElement = createHandle(method, parent);
        }
        if (enclosingElement != null) {
            reportMatching(method.annotations, enclosingElement, null, method.binding, nodeSet, true, true);
        }
    }

    // references in this method
    if (typeInHierarchy) {
        ASTNode[] nodes = nodeSet.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd);
        if (nodes != null) {
            if ((this.matchContainer & PatternLocator.METHOD_CONTAINER) != 0) {
                if (enclosingElement == null) {
                    enclosingElement = createHandle(method, parent);
                }
                if (encloses(enclosingElement)) {
                    if (this.pattern.mustResolve) {
                        // Visit only if the pattern must resolve
                        MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(
                                enclosingElement, nodes, nodeSet, this, typeInHierarchy);
                        method.traverse(declarationVisitor, (ClassScope) null);
                        int length = nodes.length;
                        for (int i = 0; i < length; i++) {
                            Integer level = (Integer) nodeSet.matchingNodes.removeKey(nodes[i]);
                            if (level != null) { // ensure that the reference has not been already reported while visiting
                                this.patternLocator.matchReportReference(nodes[i], enclosingElement,
                                        declarationVisitor.getLocalElement(i),
                                        declarationVisitor.getOtherElements(i), method.binding,
                                        level.intValue(), this);
                            }
                        }
                    } else {
                        for (int i = 0, l = nodes.length; i < l; i++) {
                            ASTNode node = nodes[i];
                            Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
                            if (level != null) { // ensure that the reference has not been already reported while visiting
                                this.patternLocator.matchReportReference(node, enclosingElement, null, null,
                                        method.binding, level.intValue(), this);
                            }
                        }
                    }
                    return;
                }
            }
            // Remove all remaining nodes
            for (int i = 0, l = nodes.length; i < l; i++) {
                nodeSet.matchingNodes.removeKey(nodes[i]);
            }
        }
    }
}

From source file:org.eclipse.jdt.core.dom.ASTConverter.java

License:Open Source License

/**
 * Remove whitespaces and comments before and after the expression.
 *//*from w  w w .  j  ava2 s. co m*/
private void trimWhiteSpacesAndComments(org.eclipse.jdt.internal.compiler.ast.Expression expression) {
    int start = expression.sourceStart;
    int end = expression.sourceEnd;
    int token;
    int trimLeftPosition = expression.sourceStart;
    int trimRightPosition = expression.sourceEnd;
    boolean first = true;
    Scanner removeBlankScanner = this.ast.scanner;
    try {
        removeBlankScanner.setSource(this.compilationUnitSource);
        removeBlankScanner.resetTo(start, end);
        while (true) {
            token = removeBlankScanner.getNextToken();
            switch (token) {
            case TerminalTokens.TokenNameCOMMENT_JAVADOC:
            case TerminalTokens.TokenNameCOMMENT_LINE:
            case TerminalTokens.TokenNameCOMMENT_BLOCK:
                if (first) {
                    trimLeftPosition = removeBlankScanner.currentPosition;
                }
                break;
            case TerminalTokens.TokenNameWHITESPACE:
                if (first) {
                    trimLeftPosition = removeBlankScanner.currentPosition;
                }
                break;
            case TerminalTokens.TokenNameEOF:
                expression.sourceStart = trimLeftPosition;
                expression.sourceEnd = trimRightPosition;
                return;
            default:
                /*
                 * if we find something else than a whitespace or a comment,
                 * then we reset the trimRigthPosition to the expression
                 * source end.
                 */
                trimRightPosition = removeBlankScanner.currentPosition - 1;
                first = false;
            }
        }
    } catch (InvalidInputException e) {
        // ignore
    }
}