Example usage for org.eclipse.jdt.core.compiler CharOperation subarray

List of usage examples for org.eclipse.jdt.core.compiler CharOperation subarray

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.compiler CharOperation subarray.

Prototype

public static final char[] subarray(char[] array, int start, int end) 

Source Link

Document

Answers a new array which is a copy of the given array starting at the given start and ending at the given end.

Usage

From source file:com.codenvy.ide.ext.java.server.core.search.SearchPattern.java

License:Open Source License

private static SearchPattern createFieldPattern(String patternString, int limitTo, int matchRule) {
    // use 1.7 as the source level as there are more valid tokens in 1.7 mode
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=376673
    Scanner scanner = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/,
            ClassFileConstants.JDK1_7/*sourceLevel*/, null /*taskTags*/, null/*taskPriorities*/,
            true/*taskCaseSensitive*/);
    scanner.setSource(patternString.toCharArray());
    final int InsideDeclaringPart = 1;
    final int InsideType = 2;
    int lastToken = -1;

    String declaringType = null, fieldName = null;
    String type = null;/*from  w w  w .  j  a va2  s  . c om*/
    int mode = InsideDeclaringPart;
    int token;
    try {
        token = scanner.getNextToken();
    } catch (InvalidInputException e) {
        return null;
    }
    while (token != TerminalTokens.TokenNameEOF) {
        switch (mode) {
        // read declaring type and fieldName
        case InsideDeclaringPart:
            switch (token) {
            case TerminalTokens.TokenNameDOT:
                if (declaringType == null) {
                    if (fieldName == null)
                        return null;
                    declaringType = fieldName;
                } else {
                    String tokenSource = scanner.getCurrentTokenString();
                    declaringType += tokenSource + fieldName;
                }
                fieldName = null;
                break;
            case TerminalTokens.TokenNameWHITESPACE:
                if (!(TerminalTokens.TokenNameWHITESPACE == lastToken
                        || TerminalTokens.TokenNameDOT == lastToken))
                    mode = InsideType;
                break;
            default: // all other tokens are considered identifiers (see bug 21763 Problem in Java search [search])
                if (fieldName == null)
                    fieldName = scanner.getCurrentTokenString();
                else
                    fieldName += scanner.getCurrentTokenString();
            }
            break;
        // read type
        case InsideType:
            switch (token) {
            case TerminalTokens.TokenNameWHITESPACE:
                break;
            default: // all other tokens are considered identifiers (see bug 21763 Problem in Java search [search])
                if (type == null)
                    type = scanner.getCurrentTokenString();
                else
                    type += scanner.getCurrentTokenString();
            }
            break;
        }
        lastToken = token;
        try {
            token = scanner.getNextToken();
        } catch (InvalidInputException e) {
            return null;
        }
    }
    if (fieldName == null)
        return null;

    char[] fieldNameChars = fieldName.toCharArray();
    if (fieldNameChars.length == 1 && fieldNameChars[0] == '*')
        fieldNameChars = null;

    char[] declaringTypeQualification = null, declaringTypeSimpleName = null;
    char[] typeQualification = null, typeSimpleName = null;

    // extract declaring type infos
    if (declaringType != null) {
        char[] declaringTypePart = declaringType.toCharArray();
        int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart);
        if (lastDotPosition >= 0) {
            declaringTypeQualification = CharOperation.subarray(declaringTypePart, 0, lastDotPosition);
            if (declaringTypeQualification.length == 1 && declaringTypeQualification[0] == '*')
                declaringTypeQualification = null;
            declaringTypeSimpleName = CharOperation.subarray(declaringTypePart, lastDotPosition + 1,
                    declaringTypePart.length);
        } else {
            declaringTypeSimpleName = declaringTypePart;
        }
        if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*')
            declaringTypeSimpleName = null;
    }
    // extract type infos
    if (type != null) {
        char[] typePart = type.toCharArray();
        int lastDotPosition = CharOperation.lastIndexOf('.', typePart);
        if (lastDotPosition >= 0) {
            typeQualification = CharOperation.subarray(typePart, 0, lastDotPosition);
            if (typeQualification.length == 1 && typeQualification[0] == '*') {
                typeQualification = null;
            } else {
                // prefix with a '*' as the full qualification could be bigger (because of an import)
                typeQualification = CharOperation.concat(IIndexConstants.ONE_STAR, typeQualification);
            }
            typeSimpleName = CharOperation.subarray(typePart, lastDotPosition + 1, typePart.length);
        } else {
            typeSimpleName = typePart;
        }
        if (typeSimpleName.length == 1 && typeSimpleName[0] == '*')
            typeSimpleName = null;
    }
    // Create field pattern
    return new FieldPattern(fieldNameChars, declaringTypeQualification, declaringTypeSimpleName,
            typeQualification, typeSimpleName, limitTo, matchRule);
}

From source file:com.codenvy.ide.ext.java.server.core.search.SearchPattern.java

License:Open Source License

private static SearchPattern createMethodOrConstructorPattern(String patternString, int limitTo, int matchRule,
        boolean isConstructor) {
    // use 1.7 as the source level as there are more valid tokens in 1.7 mode
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=376673
    Scanner scanner = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/,
            ClassFileConstants.JDK1_7/*sourceLevel*/, null /*taskTags*/, null/*taskPriorities*/,
            true/*taskCaseSensitive*/);
    scanner.setSource(patternString.toCharArray());
    final int InsideSelector = 1;
    final int InsideTypeArguments = 2;
    final int InsideParameter = 3;
    final int InsideReturnType = 4;
    int lastToken = -1;

    String declaringType = null, selector = null, parameterType = null;
    String[] parameterTypes = null;
    char[][] typeArguments = null;
    String typeArgumentsString = null;
    int parameterCount = -1;
    String returnType = null;/*from  w  ww . j a va2s.com*/
    boolean foundClosingParenthesis = false;
    int mode = InsideSelector;
    int token, argCount = 0;
    try {
        token = scanner.getNextToken();
    } catch (InvalidInputException e) {
        return null;
    }
    while (token != TerminalTokens.TokenNameEOF) {
        switch (mode) {
        // read declaring type and selector
        case InsideSelector:
            if (argCount == 0) {
                switch (token) {
                case TerminalTokens.TokenNameLESS:
                    argCount++;
                    if (selector == null || lastToken == TerminalTokens.TokenNameDOT) {
                        typeArgumentsString = scanner.getCurrentTokenString();
                        mode = InsideTypeArguments;
                        break;
                    }
                    if (declaringType == null) {
                        declaringType = selector;
                    } else {
                        declaringType += '.' + selector;
                    }
                    declaringType += scanner.getCurrentTokenString();
                    selector = null;
                    break;
                case TerminalTokens.TokenNameDOT:
                    if (!isConstructor && typeArgumentsString != null)
                        return null; // invalid syntax
                    if (declaringType == null) {
                        if (selector == null)
                            return null; // invalid syntax
                        declaringType = selector;
                    } else if (selector != null) {
                        declaringType += scanner.getCurrentTokenString() + selector;
                    }
                    selector = null;
                    break;
                case TerminalTokens.TokenNameLPAREN:
                    parameterTypes = new String[5];
                    parameterCount = 0;
                    mode = InsideParameter;
                    break;
                case TerminalTokens.TokenNameWHITESPACE:
                    switch (lastToken) {
                    case TerminalTokens.TokenNameWHITESPACE:
                    case TerminalTokens.TokenNameDOT:
                    case TerminalTokens.TokenNameGREATER:
                    case TerminalTokens.TokenNameRIGHT_SHIFT:
                    case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT:
                        break;
                    default:
                        mode = InsideReturnType;
                        break;
                    }
                    break;
                default: // all other tokens are considered identifiers (see bug 21763 Problem in Java search [search])
                    if (selector == null)
                        selector = scanner.getCurrentTokenString();
                    else
                        selector += scanner.getCurrentTokenString();
                    break;
                }
            } else {
                if (declaringType == null)
                    return null; // invalid syntax
                switch (token) {
                case TerminalTokens.TokenNameGREATER:
                case TerminalTokens.TokenNameRIGHT_SHIFT:
                case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT:
                    argCount--;
                    break;
                case TerminalTokens.TokenNameLESS:
                    argCount++;
                    break;
                }
                declaringType += scanner.getCurrentTokenString();
            }
            break;
        // read type arguments
        case InsideTypeArguments:
            if (typeArgumentsString == null)
                return null; // invalid syntax
            typeArgumentsString += scanner.getCurrentTokenString();
            switch (token) {
            case TerminalTokens.TokenNameGREATER:
            case TerminalTokens.TokenNameRIGHT_SHIFT:
            case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT:
                argCount--;
                if (argCount == 0) {
                    String pseudoType = "Type" + typeArgumentsString; //$NON-NLS-1$
                    typeArguments = Signature
                            .getTypeArguments(Signature.createTypeSignature(pseudoType, false).toCharArray());
                    mode = InsideSelector;
                }
                break;
            case TerminalTokens.TokenNameLESS:
                argCount++;
                break;
            }
            break;
        // read parameter types
        case InsideParameter:
            if (argCount == 0) {
                switch (token) {
                case TerminalTokens.TokenNameWHITESPACE:
                    break;
                case TerminalTokens.TokenNameCOMMA:
                    if (parameterType == null)
                        return null;
                    if (parameterTypes != null) {
                        if (parameterTypes.length == parameterCount)
                            System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount * 2],
                                    0, parameterCount);
                        parameterTypes[parameterCount++] = parameterType;
                    }
                    parameterType = null;
                    break;
                case TerminalTokens.TokenNameRPAREN:
                    foundClosingParenthesis = true;
                    if (parameterType != null && parameterTypes != null) {
                        if (parameterTypes.length == parameterCount)
                            System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount * 2],
                                    0, parameterCount);
                        parameterTypes[parameterCount++] = parameterType;
                    }
                    mode = isConstructor ? InsideTypeArguments : InsideReturnType;
                    break;
                case TerminalTokens.TokenNameLESS:
                    argCount++;
                    if (parameterType == null)
                        return null; // invalid syntax
                    // $FALL-THROUGH$ - fall through next case to add token
                default: // all other tokens are considered identifiers (see bug 21763 Problem in Java search [search])
                    if (parameterType == null)
                        parameterType = scanner.getCurrentTokenString();
                    else
                        parameterType += scanner.getCurrentTokenString();
                }
            } else {
                if (parameterType == null)
                    return null; // invalid syntax
                switch (token) {
                case TerminalTokens.TokenNameGREATER:
                case TerminalTokens.TokenNameRIGHT_SHIFT:
                case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT:
                    argCount--;
                    break;
                case TerminalTokens.TokenNameLESS:
                    argCount++;
                    break;
                }
                parameterType += scanner.getCurrentTokenString();
            }
            break;
        // read return type
        case InsideReturnType:
            if (argCount == 0) {
                switch (token) {
                case TerminalTokens.TokenNameWHITESPACE:
                    break;
                case TerminalTokens.TokenNameLPAREN:
                    parameterTypes = new String[5];
                    parameterCount = 0;
                    mode = InsideParameter;
                    break;
                case TerminalTokens.TokenNameLESS:
                    argCount++;
                    if (returnType == null)
                        return null; // invalid syntax
                    // $FALL-THROUGH$ - fall through next case to add token
                default: // all other tokens are considered identifiers (see bug 21763 Problem in Java search [search])
                    if (returnType == null)
                        returnType = scanner.getCurrentTokenString();
                    else
                        returnType += scanner.getCurrentTokenString();
                }
            } else {
                if (returnType == null)
                    return null; // invalid syntax
                switch (token) {
                case TerminalTokens.TokenNameGREATER:
                case TerminalTokens.TokenNameRIGHT_SHIFT:
                case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT:
                    argCount--;
                    break;
                case TerminalTokens.TokenNameLESS:
                    argCount++;
                    break;
                }
                returnType += scanner.getCurrentTokenString();
            }
            break;
        }
        lastToken = token;
        try {
            token = scanner.getNextToken();
        } catch (InvalidInputException e) {
            return null;
        }
    }
    // parenthesis mismatch
    if (parameterCount > 0 && !foundClosingParenthesis)
        return null;
    // type arguments mismatch
    if (argCount > 0)
        return null;

    char[] selectorChars = null;
    if (isConstructor) {
        // retrieve type for constructor patterns
        if (declaringType == null)
            declaringType = selector;
        else if (selector != null)
            declaringType += '.' + selector;
    } else {
        // get selector chars
        if (selector == null)
            return null;
        selectorChars = selector.toCharArray();
        if (selectorChars.length == 1 && selectorChars[0] == '*')
            selectorChars = null;
    }

    char[] declaringTypeQualification = null, declaringTypeSimpleName = null;
    char[] returnTypeQualification = null, returnTypeSimpleName = null;
    char[][] parameterTypeQualifications = null, parameterTypeSimpleNames = null;
    // Signatures
    String declaringTypeSignature = null;
    String returnTypeSignature = null;
    String[] parameterTypeSignatures = null;

    // extract declaring type infos
    if (declaringType != null) {
        // get declaring type part and signature
        char[] declaringTypePart = null;
        try {
            declaringTypeSignature = Signature.createTypeSignature(declaringType, false);
            if (declaringTypeSignature.indexOf(Signature.C_GENERIC_START) < 0) {
                declaringTypePart = declaringType.toCharArray();
            } else {
                declaringTypePart = Signature
                        .toCharArray(Signature.getTypeErasure(declaringTypeSignature.toCharArray()));
            }
        } catch (IllegalArgumentException iae) {
            // declaring type is invalid
            return null;
        }
        int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart);
        if (lastDotPosition >= 0) {
            declaringTypeQualification = CharOperation.subarray(declaringTypePart, 0, lastDotPosition);
            if (declaringTypeQualification.length == 1 && declaringTypeQualification[0] == '*')
                declaringTypeQualification = null;
            declaringTypeSimpleName = CharOperation.subarray(declaringTypePart, lastDotPosition + 1,
                    declaringTypePart.length);
        } else {
            declaringTypeSimpleName = declaringTypePart;
        }
        if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*')
            declaringTypeSimpleName = null;
    }
    // extract parameter types infos
    if (parameterCount >= 0) {
        parameterTypeQualifications = new char[parameterCount][];
        parameterTypeSimpleNames = new char[parameterCount][];
        parameterTypeSignatures = new String[parameterCount];
        for (int i = 0; i < parameterCount; i++) {
            // get parameter type part and signature
            char[] parameterTypePart = null;
            try {
                if (parameterTypes != null) {
                    parameterTypeSignatures[i] = Signature.createTypeSignature(parameterTypes[i], false);
                    if (parameterTypeSignatures[i].indexOf(Signature.C_GENERIC_START) < 0) {
                        parameterTypePart = parameterTypes[i].toCharArray();
                    } else {
                        parameterTypePart = Signature.toCharArray(
                                Signature.getTypeErasure(parameterTypeSignatures[i].toCharArray()));
                    }
                }
            } catch (IllegalArgumentException iae) {
                // string is not a valid type syntax
                return null;
            }
            int lastDotPosition = parameterTypePart == null ? -1
                    : CharOperation.lastIndexOf('.', parameterTypePart);
            if (parameterTypePart != null && lastDotPosition >= 0) {
                parameterTypeQualifications[i] = CharOperation.subarray(parameterTypePart, 0, lastDotPosition);
                if (parameterTypeQualifications[i].length == 1 && parameterTypeQualifications[i][0] == '*') {
                    parameterTypeQualifications[i] = null;
                } else {
                    // prefix with a '*' as the full qualification could be bigger (because of an import)
                    parameterTypeQualifications[i] = CharOperation.concat(IIndexConstants.ONE_STAR,
                            parameterTypeQualifications[i]);
                }
                parameterTypeSimpleNames[i] = CharOperation.subarray(parameterTypePart, lastDotPosition + 1,
                        parameterTypePart.length);
            } else {
                parameterTypeQualifications[i] = null;
                parameterTypeSimpleNames[i] = parameterTypePart;
            }
            if (parameterTypeSimpleNames[i].length == 1 && parameterTypeSimpleNames[i][0] == '*')
                parameterTypeSimpleNames[i] = null;
        }
    }
    // extract return type infos
    if (returnType != null) {
        // get return type part and signature
        char[] returnTypePart = null;
        try {
            returnTypeSignature = Signature.createTypeSignature(returnType, false);
            if (returnTypeSignature.indexOf(Signature.C_GENERIC_START) < 0) {
                returnTypePart = returnType.toCharArray();
            } else {
                returnTypePart = Signature
                        .toCharArray(Signature.getTypeErasure(returnTypeSignature.toCharArray()));
            }
        } catch (IllegalArgumentException iae) {
            // declaring type is invalid
            return null;
        }
        int lastDotPosition = CharOperation.lastIndexOf('.', returnTypePart);
        if (lastDotPosition >= 0) {
            returnTypeQualification = CharOperation.subarray(returnTypePart, 0, lastDotPosition);
            if (returnTypeQualification.length == 1 && returnTypeQualification[0] == '*') {
                returnTypeQualification = null;
            } else {
                // because of an import
                returnTypeQualification = CharOperation.concat(IIndexConstants.ONE_STAR,
                        returnTypeQualification);
            }
            returnTypeSimpleName = CharOperation.subarray(returnTypePart, lastDotPosition + 1,
                    returnTypePart.length);
        } else {
            returnTypeSimpleName = returnTypePart;
        }
        if (returnTypeSimpleName.length == 1 && returnTypeSimpleName[0] == '*')
            returnTypeSimpleName = null;
    }
    // Create method/constructor pattern
    if (isConstructor) {
        return new ConstructorPattern(declaringTypeSimpleName, declaringTypeQualification,
                declaringTypeSignature, parameterTypeQualifications, parameterTypeSimpleNames,
                parameterTypeSignatures, typeArguments, limitTo, matchRule);
    } else {
        return new MethodPattern(selectorChars, declaringTypeQualification, declaringTypeSimpleName,
                declaringTypeSignature, returnTypeQualification, returnTypeSimpleName, returnTypeSignature,
                parameterTypeQualifications, parameterTypeSimpleNames, parameterTypeSignatures, typeArguments,
                limitTo, matchRule);
    }
}

From source file:com.codenvy.ide.ext.java.server.core.search.SearchPattern.java

License:Open Source License

/**
 * Returns a search pattern based on a given Java element.
 * The pattern is used to trigger the appropriate search, and can be parameterized as follows:
 *
 * @param element the Java element the search pattern is based on
 * @param limitTo determines the nature of the expected matches
 *   <ul>//from   w w w.ja  v a2 s . com
 *    <li>{@link IJavaSearchConstants#DECLARATIONS DECLARATIONS}: will search declarations matching
 *          with the corresponding element. In case the element is a method, declarations of matching
 *          methods in sub-types will also be found, allowing to find declarations of abstract methods, etc.
 *            Some additional flags may be specified while searching declaration:
 *            <ul>
 *               <li>{@link IJavaSearchConstants#IGNORE_DECLARING_TYPE IGNORE_DECLARING_TYPE}: declaring type will be ignored
 *                     during the search.<br>
 *                     For example using following test case:
 *               <pre>
 *                  class A { A method() { return null; } }
 *                  class B extends A { B method() { return null; } }
 *                  class C { A method() { return null; } }
 *               </pre>
 *                     search for <code>method</code> declaration with this flag
 *                     will return 2 matches: in A and in C
 *               </li>
 *               <li>{@link IJavaSearchConstants#IGNORE_RETURN_TYPE IGNORE_RETURN_TYPE}: return type will be ignored
 *                     during the search.<br>
 *                     Using same example, search for <code>method</code> declaration with this flag
 *                     will return 2 matches: in A and in B.
 *               </li>
 *            </ul>
 *            Note that these two flags may be combined and both declaring and return types can be ignored
 *            during the search. Then, using same example, search for <code>method</code> declaration
 *            with these 2 flags will return 3 matches: in A, in B  and in C
 *    </li>
 *       <li>{@link IJavaSearchConstants#REFERENCES REFERENCES}: will search references to the given element.</li>
 *       <li>{@link IJavaSearchConstants#ALL_OCCURRENCES ALL_OCCURRENCES}: will search for either declarations or
 *            references as specified above.
 *      </li>
 *       <li>All other fine grain constants defined in the <b>limitTo</b> category
 *            of the {@link IJavaSearchConstants} are also accepted nature:
 *          <table border=0>
 *              <tr>
 *               <th align=left>Fine grain constant
 *               <th align=left>Meaning
 *              <tr>
 *               <td>{@link IJavaSearchConstants#FIELD_DECLARATION_TYPE_REFERENCE FIELD_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used as the type of a field declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#LOCAL_VARIABLE_DECLARATION_TYPE_REFERENCE LOCAL_VARIABLE_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used as the type of a local variable declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#PARAMETER_DECLARATION_TYPE_REFERENCE PARAMETER_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used as the type of a method parameter declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#SUPERTYPE_TYPE_REFERENCE SUPERTYPE_TYPE_REFERENCE}
 *               <td>Return only type references used as a super type or as a super interface.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#THROWS_CLAUSE_TYPE_REFERENCE THROWS_CLAUSE_TYPE_REFERENCE}
 *               <td>Return only type references used in a throws clause.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#CAST_TYPE_REFERENCE CAST_TYPE_REFERENCE}
 *               <td>Return only type references used in a cast expression.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#CATCH_TYPE_REFERENCE CATCH_TYPE_REFERENCE}
 *               <td>Return only type references used in a catch header.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#CLASS_INSTANCE_CREATION_TYPE_REFERENCE CLASS_INSTANCE_CREATION_TYPE_REFERENCE}
 *               <td>Return only type references used in class instance creation.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#RETURN_TYPE_REFERENCE RETURN_TYPE_REFERENCE}
 *               <td>Return only type references used as a method return type.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#IMPORT_DECLARATION_TYPE_REFERENCE IMPORT_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used in an import declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#ANNOTATION_TYPE_REFERENCE ANNOTATION_TYPE_REFERENCE}
 *               <td>Return only type references used as an annotation.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#TYPE_ARGUMENT_TYPE_REFERENCE TYPE_ARGUMENT_TYPE_REFERENCE}
 *               <td>Return only type references used as a type argument in a parameterized type or a parameterized method.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#TYPE_VARIABLE_BOUND_TYPE_REFERENCE TYPE_VARIABLE_BOUND_TYPE_REFERENCE}
 *               <td>Return only type references used as a type variable bound.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#WILDCARD_BOUND_TYPE_REFERENCE WILDCARD_BOUND_TYPE_REFERENCE}
 *               <td>Return only type references used as a wildcard bound.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#INSTANCEOF_TYPE_REFERENCE INSTANCEOF_TYPE_REFERENCE}
 *               <td>Return only type references used as a type of an <code>instanceof</code> expression.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#SUPER_REFERENCE SUPER_REFERENCE}
 *               <td>Return only super field accesses or super method invocations (e.g. using the <code>super</code> qualifier).
 *              <tr>
 *               <td>{@link IJavaSearchConstants#QUALIFIED_REFERENCE QUALIFIED_REFERENCE}
 *               <td>Return only qualified field accesses or qualified method invocations.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#THIS_REFERENCE THIS_REFERENCE}
 *               <td>Return only primary field accesses or primary method invocations (e.g. using the <code>this</code> qualifier).
 *              <tr>
 *               <td>{@link IJavaSearchConstants#IMPLICIT_THIS_REFERENCE IMPLICIT_THIS_REFERENCE}
 *               <td>Return only field accesses or method invocations without any qualification.
 *          </table>
 *    </li>
 *   </ul>
 * @param matchRule one of the following match rules:
 *    <ul>
 *       <li>{@link #R_EXACT_MATCH}</li>
 *       <li>{@link #R_PREFIX_MATCH}</li>
 *       <li>{@link #R_PATTERN_MATCH}</li>
 *       <li>{@link #R_CAMELCASE_MATCH}</li>
 *       <li>{@link #R_CAMELCASE_SAME_PART_COUNT_MATCH}</li>
 *    </ul>
 *    , which may be also combined with one of the following flags:
 *    <ul>
 *       <li>{@link #R_CASE_SENSITIVE}</li>
 *       <li>{@link #R_ERASURE_MATCH}</li>
 *       <li>{@link #R_EQUIVALENT_MATCH}</li>
 *    </ul>
 *      For example,
 *      <ul>
 *         <li>{@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE}: if an exact
 *            and case sensitive match is requested,</li>
 *         <li>{@link #R_PREFIX_MATCH} if a case insensitive prefix match is requested</li>
 *         <li>{@link #R_EXACT_MATCH} | {@link #R_ERASURE_MATCH}: if a case
 *            insensitive and erasure match is requested.</li>
 *      </ul>
 *    Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} has no effect
 *    on non-generic types/methods search.
 *    <p>
 *    Note also that default behavior for generic types/methods search is to find exact matches.
 * @return a search pattern for a Java element or <code>null</code> if the given element is ill-formed
 * @since 3.1
 */
public static SearchPattern createPattern(IJavaElement element, int limitTo, int matchRule) {
    SearchPattern searchPattern = null;
    int lastDot;
    boolean ignoreDeclaringType = false;
    boolean ignoreReturnType = false;
    int maskedLimitTo = limitTo
            & ~(IJavaSearchConstants.IGNORE_DECLARING_TYPE + IJavaSearchConstants.IGNORE_RETURN_TYPE);
    if (maskedLimitTo == IJavaSearchConstants.DECLARATIONS
            || maskedLimitTo == IJavaSearchConstants.ALL_OCCURRENCES) {
        ignoreDeclaringType = (limitTo & IJavaSearchConstants.IGNORE_DECLARING_TYPE) != 0;
        ignoreReturnType = (limitTo & IJavaSearchConstants.IGNORE_RETURN_TYPE) != 0;
    }
    if ((matchRule = validateMatchRule(null, matchRule)) == -1) {
        return null;
    }
    char[] declaringSimpleName = null;
    char[] declaringQualification = null;
    switch (element.getElementType()) {
    case IJavaElement.FIELD:
        IField field = (IField) element;
        if (!ignoreDeclaringType) {
            IType declaringClass = field.getDeclaringType();
            declaringSimpleName = declaringClass.getElementName().toCharArray();
            declaringQualification = declaringClass.getPackageFragment().getElementName().toCharArray();
            char[][] enclosingNames = enclosingTypeNames(declaringClass);
            if (enclosingNames.length > 0) {
                declaringQualification = CharOperation.concat(declaringQualification,
                        CharOperation.concatWith(enclosingNames, '.'), '.');
            }
        }
        char[] name = field.getElementName().toCharArray();
        char[] typeSimpleName = null;
        char[] typeQualification = null;
        String typeSignature = null;
        if (!ignoreReturnType) {
            try {
                typeSignature = field.getTypeSignature();
                char[] signature = typeSignature.toCharArray();
                char[] typeErasure = Signature.toCharArray(Signature.getTypeErasure(signature));
                CharOperation.replace(typeErasure, '$', '.');
                if ((lastDot = CharOperation.lastIndexOf('.', typeErasure)) == -1) {
                    typeSimpleName = typeErasure;
                } else {
                    typeSimpleName = CharOperation.subarray(typeErasure, lastDot + 1, typeErasure.length);
                    typeQualification = CharOperation.subarray(typeErasure, 0, lastDot);
                    if (!field.isBinary()) {
                        // prefix with a '*' as the full qualification could be bigger (because of an import)
                        typeQualification = CharOperation.concat(IIndexConstants.ONE_STAR, typeQualification);
                    }
                }
            } catch (JavaModelException e) {
                return null;
            }
        }
        // Create field pattern
        searchPattern = new FieldPattern(name, declaringQualification, declaringSimpleName, typeQualification,
                typeSimpleName, typeSignature, limitTo, matchRule);
        break;
    case IJavaElement.IMPORT_DECLARATION:
        String elementName = element.getElementName();
        lastDot = elementName.lastIndexOf('.');
        if (lastDot == -1)
            return null; // invalid import declaration
        IImportDeclaration importDecl = (IImportDeclaration) element;
        if (importDecl.isOnDemand()) {
            searchPattern = createPackagePattern(elementName.substring(0, lastDot), maskedLimitTo, matchRule);
        } else {
            searchPattern = createTypePattern(elementName.substring(lastDot + 1).toCharArray(),
                    elementName.substring(0, lastDot).toCharArray(), null, null, null, maskedLimitTo,
                    matchRule);
        }
        break;
    case IJavaElement.LOCAL_VARIABLE:
        LocalVariable localVar = (LocalVariable) element;
        searchPattern = new LocalVariablePattern(localVar, limitTo, matchRule);
        break;
    case IJavaElement.TYPE_PARAMETER:
        ITypeParameter typeParam = (ITypeParameter) element;
        boolean findParamDeclarations = true;
        boolean findParamReferences = true;
        switch (maskedLimitTo) {
        case IJavaSearchConstants.DECLARATIONS:
            findParamReferences = false;
            break;
        case IJavaSearchConstants.REFERENCES:
            findParamDeclarations = false;
            break;
        }
        searchPattern = new TypeParameterPattern(findParamDeclarations, findParamReferences, typeParam,
                matchRule);
        break;
    case IJavaElement.METHOD:
        IMethod method = (IMethod) element;
        boolean isConstructor;
        try {
            isConstructor = method.isConstructor();
        } catch (JavaModelException e) {
            return null;
        }
        IType declaringClass = method.getDeclaringType();
        if (ignoreDeclaringType) {
            if (isConstructor)
                declaringSimpleName = declaringClass.getElementName().toCharArray();
        } else {
            declaringSimpleName = declaringClass.getElementName().toCharArray();
            declaringQualification = declaringClass.getPackageFragment().getElementName().toCharArray();
            char[][] enclosingNames = enclosingTypeNames(declaringClass);
            if (enclosingNames.length > 0) {
                declaringQualification = CharOperation.concat(declaringQualification,
                        CharOperation.concatWith(enclosingNames, '.'), '.');
            }
        }
        char[] selector = method.getElementName().toCharArray();
        char[] returnSimpleName = null;
        char[] returnQualification = null;
        String returnSignature = null;
        if (!ignoreReturnType) {
            try {
                returnSignature = method.getReturnType();
                char[] signature = returnSignature.toCharArray();
                char[] returnErasure = Signature.toCharArray(Signature.getTypeErasure(signature));
                CharOperation.replace(returnErasure, '$', '.');
                if ((lastDot = CharOperation.lastIndexOf('.', returnErasure)) == -1) {
                    returnSimpleName = returnErasure;
                } else {
                    returnSimpleName = CharOperation.subarray(returnErasure, lastDot + 1, returnErasure.length);
                    returnQualification = CharOperation.subarray(returnErasure, 0, lastDot);
                    if (!method.isBinary()) {
                        // prefix with a '*' as the full qualification could be bigger (because of an import)
                        CharOperation.concat(IIndexConstants.ONE_STAR, returnQualification);
                    }
                }
            } catch (JavaModelException e) {
                return null;
            }
        }
        String[] parameterTypes = method.getParameterTypes();
        int paramCount = parameterTypes.length;
        char[][] parameterSimpleNames = new char[paramCount][];
        char[][] parameterQualifications = new char[paramCount][];
        String[] parameterSignatures = new String[paramCount];
        for (int i = 0; i < paramCount; i++) {
            parameterSignatures[i] = parameterTypes[i];
            char[] signature = parameterSignatures[i].toCharArray();
            char[] paramErasure = Signature.toCharArray(Signature.getTypeErasure(signature));
            CharOperation.replace(paramErasure, '$', '.');
            if ((lastDot = CharOperation.lastIndexOf('.', paramErasure)) == -1) {
                parameterSimpleNames[i] = paramErasure;
                parameterQualifications[i] = null;
            } else {
                parameterSimpleNames[i] = CharOperation.subarray(paramErasure, lastDot + 1,
                        paramErasure.length);
                parameterQualifications[i] = CharOperation.subarray(paramErasure, 0, lastDot);
                if (!method.isBinary()) {
                    // prefix with a '*' as the full qualification could be bigger (because of an import)
                    CharOperation.concat(IIndexConstants.ONE_STAR, parameterQualifications[i]);
                }
            }
        }

        // Create method/constructor pattern
        if (isConstructor) {
            searchPattern = new ConstructorPattern(declaringSimpleName, declaringQualification,
                    parameterQualifications, parameterSimpleNames, parameterSignatures, method, limitTo,
                    matchRule);
        } else {
            searchPattern = new MethodPattern(selector, declaringQualification, declaringSimpleName,
                    returnQualification, returnSimpleName, returnSignature, parameterQualifications,
                    parameterSimpleNames, parameterSignatures, method, limitTo, matchRule);
        }
        break;
    case IJavaElement.TYPE:
        IType type = (IType) element;
        searchPattern = createTypePattern(type.getElementName().toCharArray(),
                type.getPackageFragment().getElementName().toCharArray(),
                ignoreDeclaringType ? null : enclosingTypeNames(type), null, type, maskedLimitTo, matchRule);
        break;
    case IJavaElement.PACKAGE_DECLARATION:
    case IJavaElement.PACKAGE_FRAGMENT:
        searchPattern = createPackagePattern(element.getElementName(), maskedLimitTo, matchRule);
        break;
    }
    if (searchPattern != null)
        MatchLocator.setFocus(searchPattern, element);
    return searchPattern;
}

From source file:com.codenvy.ide.ext.java.server.core.search.SearchPattern.java

License:Open Source License

private static SearchPattern createTypePattern(String patternString, int limitTo, int matchRule,
        char indexSuffix) {
    // use 1.7 as the source level as there are more valid tokens in 1.7 mode
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=376673
    Scanner scanner = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/,
            ClassFileConstants.JDK1_7/*sourceLevel*/, null /*taskTags*/, null/*taskPriorities*/,
            true/*taskCaseSensitive*/);
    scanner.setSource(patternString.toCharArray());
    String type = null;/*  w w w . ja v  a  2  s.c o  m*/
    int token;
    try {
        token = scanner.getNextToken();
    } catch (InvalidInputException e) {
        return null;
    }
    int argCount = 0;
    while (token != TerminalTokens.TokenNameEOF) {
        if (argCount == 0) {
            switch (token) {
            case TerminalTokens.TokenNameWHITESPACE:
                break;
            case TerminalTokens.TokenNameLESS:
                argCount++;
                // $FALL-THROUGH$ - fall through default case to add token to type
            default: // all other tokens are considered identifiers (see bug 21763 Problem in Java search [search])
                if (type == null)
                    type = scanner.getCurrentTokenString();
                else
                    type += scanner.getCurrentTokenString();
            }
        } else {
            switch (token) {
            case TerminalTokens.TokenNameGREATER:
            case TerminalTokens.TokenNameRIGHT_SHIFT:
            case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT:
                argCount--;
                break;
            case TerminalTokens.TokenNameLESS:
                argCount++;
                break;
            }
            if (type == null)
                return null; // invalid syntax
            type += scanner.getCurrentTokenString();
        }
        try {
            token = scanner.getNextToken();
        } catch (InvalidInputException e) {
            return null;
        }
    }
    if (type == null)
        return null;
    String typeSignature = null;
    char[] qualificationChars = null, typeChars = null;

    // get type part and signature
    char[] typePart = null;
    try {
        typeSignature = Signature.createTypeSignature(type, false);
        if (typeSignature.indexOf(Signature.C_GENERIC_START) < 0) {
            typePart = type.toCharArray();
        } else {
            typePart = Signature.toCharArray(Signature.getTypeErasure(typeSignature.toCharArray()));
        }
    } catch (IllegalArgumentException iae) {
        // string is not a valid type syntax
        return null;
    }

    // get qualification name
    int lastDotPosition = CharOperation.lastIndexOf('.', typePart);
    if (lastDotPosition >= 0) {
        qualificationChars = CharOperation.subarray(typePart, 0, lastDotPosition);
        if (qualificationChars.length == 1 && qualificationChars[0] == '*')
            qualificationChars = null;
        typeChars = CharOperation.subarray(typePart, lastDotPosition + 1, typePart.length);
    } else {
        typeChars = typePart;
    }
    if (typeChars.length == 1 && typeChars[0] == '*') {
        typeChars = null;
    }
    switch (limitTo) {
    case IJavaSearchConstants.DECLARATIONS: // cannot search for explicit member types
        return new QualifiedTypeDeclarationPattern(qualificationChars, typeChars, indexSuffix, matchRule);
    case IJavaSearchConstants.REFERENCES:
        return new TypeReferencePattern(qualificationChars, typeChars, typeSignature, indexSuffix, matchRule);
    case IJavaSearchConstants.IMPLEMENTORS:
        return new SuperTypeReferencePattern(qualificationChars, typeChars,
                SuperTypeReferencePattern.ONLY_SUPER_INTERFACES, indexSuffix, matchRule);
    case IJavaSearchConstants.ALL_OCCURRENCES:
        return new OrPattern(
                new QualifiedTypeDeclarationPattern(qualificationChars, typeChars, indexSuffix, matchRule), // cannot search for explicit
                // member types
                new TypeReferencePattern(qualificationChars, typeChars, typeSignature, indexSuffix, matchRule));
    default:
        return new TypeReferencePattern(qualificationChars, typeChars, typeSignature, limitTo, indexSuffix,
                matchRule);
    }
}

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);//  w  w  w .  j  a v a 2 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.codeassist.SelectionEngine.java

License:Open Source License

/**
 * Ask the engine to compute the selection at the specified position
 * of the given compilation unit./*from  w ww  . ja  va  2  s .  c  om*/
        
 *  @param sourceUnit org.eclipse.jdt.internal.compiler.env.ICompilationUnit
 *      the source of the current compilation unit.
 *
 *  @param selectionSourceStart int
 *  @param selectionSourceEnd int
 *      a range in the source where the selection is.
 */
public void select(ICompilationUnit sourceUnit, int selectionSourceStart, int selectionSourceEnd) {

    char[] source = sourceUnit.getContents();

    if (DEBUG) {
        System.out.print("SELECTION IN "); //$NON-NLS-1$
        System.out.print(sourceUnit.getFileName());
        System.out.print(" FROM "); //$NON-NLS-1$
        System.out.print(selectionSourceStart);
        System.out.print(" TO "); //$NON-NLS-1$
        System.out.println(selectionSourceEnd);
        System.out.println("SELECTION - Source :"); //$NON-NLS-1$
        System.out.println(source);
    }
    if (!checkSelection(source, selectionSourceStart, selectionSourceEnd)) {
        return;
    }
    if (DEBUG) {
        System.out.print("SELECTION - Checked : \""); //$NON-NLS-1$
        System.out.print(new String(source, this.actualSelectionStart,
                this.actualSelectionEnd - this.actualSelectionStart + 1));
        System.out.println('"');
    }
    try {
        this.acceptedAnswer = false;
        CompilationResult result = new CompilationResult(sourceUnit, 1, 1,
                this.compilerOptions.maxProblemsPerUnit);
        CompilationUnitDeclaration parsedUnit = this.parser.dietParse(sourceUnit, result,
                this.actualSelectionStart, this.actualSelectionEnd);

        if (parsedUnit != null) {
            if (DEBUG) {
                System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
                System.out.println(parsedUnit.toString());
            }

            // scan the package & import statements first
            if (parsedUnit.currentPackage instanceof SelectionOnPackageReference) {
                char[][] tokens = ((SelectionOnPackageReference) parsedUnit.currentPackage).tokens;
                this.noProposal = false;
                this.requestor.acceptPackage(CharOperation.concatWith(tokens, '.'));
                return;
            }
            ImportReference[] imports = parsedUnit.imports;
            if (imports != null) {
                for (int i = 0, length = imports.length; i < length; i++) {
                    ImportReference importReference = imports[i];
                    if (importReference instanceof SelectionOnImportReference) {
                        char[][] tokens = ((SelectionOnImportReference) importReference).tokens;
                        this.noProposal = false;
                        this.requestor.acceptPackage(CharOperation.concatWith(tokens, '.'));
                        this.nameEnvironment.findTypes(CharOperation.concatWith(tokens, '.'), false, false,
                                IJavaSearchConstants.TYPE, this);

                        this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
                        if ((this.unitScope = parsedUnit.scope) != null) {
                            int tokenCount = tokens.length;
                            char[] lastToken = tokens[tokenCount - 1];
                            char[][] qualifierTokens = CharOperation.subarray(tokens, 0, tokenCount - 1);

                            if (qualifierTokens != null && qualifierTokens.length > 0) {
                                Binding binding = this.unitScope.getTypeOrPackage(qualifierTokens);
                                if (binding != null && binding instanceof ReferenceBinding) {
                                    ReferenceBinding ref = (ReferenceBinding) binding;
                                    selectMemberTypeFromImport(parsedUnit, lastToken, ref,
                                            importReference.isStatic());
                                    if (importReference.isStatic()) {
                                        selectStaticFieldFromStaticImport(parsedUnit, lastToken, ref);
                                        selectStaticMethodFromStaticImport(parsedUnit, lastToken, ref);
                                    }
                                }
                            }
                        }

                        // accept qualified types only if no unqualified type was accepted
                        if (!this.acceptedAnswer) {
                            acceptQualifiedTypes();
                            if (!this.acceptedAnswer) {
                                this.nameEnvironment.findTypes(this.selectedIdentifier, false, false,
                                        IJavaSearchConstants.TYPE, this);
                                // try with simple type name
                                if (!this.acceptedAnswer) {
                                    acceptQualifiedTypes();
                                }
                            }
                        }
                        if (this.noProposal && this.problem != null) {
                            this.requestor.acceptError(this.problem);
                        }
                        return;
                    }
                }
            }
            if (parsedUnit.types != null || parsedUnit.isPackageInfo()) {
                if (selectDeclaration(parsedUnit))
                    return;
                this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
                if ((this.unitScope = parsedUnit.scope) != null) {
                    try {
                        this.lookupEnvironment.completeTypeBindings(parsedUnit, true);

                        CompilationUnitDeclaration previousUnitBeingCompleted = this.lookupEnvironment.unitBeingCompleted;
                        this.lookupEnvironment.unitBeingCompleted = parsedUnit;
                        parsedUnit.scope.faultInTypes();
                        this.lookupEnvironment.unitBeingCompleted = previousUnitBeingCompleted;
                        ASTNode node = null;
                        if (parsedUnit.types != null)
                            node = parseBlockStatements(parsedUnit, selectionSourceStart);
                        if (DEBUG) {
                            System.out.println("SELECTION - AST :"); //$NON-NLS-1$
                            System.out.println(parsedUnit.toString());
                        }
                        parsedUnit.resolve();
                        if (node != null) {
                            selectLocalDeclaration(node);
                        }
                    } catch (SelectionNodeFound e) {
                        if (e.binding != null) {
                            if (DEBUG) {
                                System.out.println("SELECTION - Selection binding:"); //$NON-NLS-1$
                                System.out.println(e.binding.toString());
                            }
                            // if null then we found a problem in the selection node
                            selectFrom(e.binding, parsedUnit, sourceUnit, e.isDeclaration);
                        }
                    }
                }
            }
        }
        // only reaches here if no selection could be derived from the parsed tree
        // thus use the selected source and perform a textual type search
        if (!this.acceptedAnswer) {
            this.nameEnvironment.findTypes(this.selectedIdentifier, false, false, IJavaSearchConstants.TYPE,
                    this);

            // accept qualified types only if no unqualified type was accepted
            if (!this.acceptedAnswer) {
                acceptQualifiedTypes();

                // accept types from all the workspace only if no type was found in the project scope
                if (this.noProposal) {
                    findAllTypes(this.selectedIdentifier);
                }
            }
        }
        if (this.noProposal && this.problem != null) {
            this.requestor.acceptError(this.problem);
        }
    } catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D
        if (DEBUG) {
            System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$
            e.printStackTrace(System.out);
        }
    } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
        if (DEBUG) {
            System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$
            e.printStackTrace(System.out);
        }
    } finally {
        reset(true);
    }
}

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

License:Open Source License

/**
 * Asks the engine to compute the selection of the given type
 * from the given context//from  w  w w. j ava2 s. c om
 *
 *  @param typeName char[]
 *      a type name which is to be resolved in the context of a compilation unit.
 *      NOTE: the type name is supposed to be correctly reduced (no whitespaces, no unicodes left)
 *
 *  @param context org.eclipse.jdt.core.IType
 *      the context in which code assist is invoked.
 */
public void selectType(char[] typeName, IType context) throws JavaModelException {
    try {
        this.acceptedAnswer = false;

        // only the type erasure are returned by IType.resolvedType(...)
        if (CharOperation.indexOf('<', typeName) != -1) {
            char[] typeSig = Signature.createCharArrayTypeSignature(typeName, false/*not resolved*/);
            typeSig = Signature.getTypeErasure(typeSig);
            typeName = Signature.toCharArray(typeSig);
        }

        CompilationUnitDeclaration parsedUnit = null;
        TypeDeclaration typeDeclaration = null;
        org.eclipse.jdt.core.ICompilationUnit cu = context.getCompilationUnit();
        if (cu != null) {
            IType[] topLevelTypes = cu.getTypes();
            int length = topLevelTypes.length;
            SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length];
            for (int i = 0; i < length; i++) {
                topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType) topLevelTypes[i]).getElementInfo();
            }
            CompilationResult result = new CompilationResult(
                    (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) cu, 1, 1,
                    this.compilerOptions.maxProblemsPerUnit);
            int flags = SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE;
            if (context.isAnonymous() || context.isLocal())
                flags |= SourceTypeConverter.LOCAL_TYPE;
            parsedUnit = SourceTypeConverter.buildCompilationUnit(topLevelInfos, flags,
                    this.parser.problemReporter(), result);
            if (parsedUnit != null && parsedUnit.types != null) {
                if (DEBUG) {
                    System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
                    System.out.println(parsedUnit.toString());
                }
                // find the type declaration that corresponds to the original source type
                typeDeclaration = new ASTNodeFinder(parsedUnit).findType(context);
            }
        } else { // binary type
            ClassFile classFile = (ClassFile) context.getClassFile();
            ClassFileReader reader = (ClassFileReader) classFile.getBinaryTypeInfo(
                    (IFile) null/*classFile.resource()*/,
                    false/*don't fully initialize so as to keep constant pool (used below)*/);
            CompilationResult result = new CompilationResult(reader.getFileName(), 1, 1,
                    this.compilerOptions.maxProblemsPerUnit);
            parsedUnit = new CompilationUnitDeclaration(this.parser.problemReporter(), result, 0);
            HashSetOfCharArrayArray typeNames = new HashSetOfCharArrayArray();

            BinaryTypeConverter converter = new BinaryTypeConverter(this.parser.problemReporter(), result,
                    typeNames);
            typeDeclaration = converter.buildTypeDeclaration(context, parsedUnit);
            parsedUnit.imports = converter.buildImports(reader);
        }

        if (typeDeclaration != null) {

            // add fake field with the type we're looking for
            // note: since we didn't ask for fields above, there is no field defined yet
            FieldDeclaration field = new FieldDeclaration();
            int dot;
            if ((dot = CharOperation.lastIndexOf('.', typeName)) == -1) {
                this.selectedIdentifier = typeName;
                field.type = new SelectionOnSingleTypeReference(typeName, -1);
                // position not used
            } else {
                char[][] previousIdentifiers = CharOperation.splitOn('.', typeName, 0, dot);
                char[] selectionIdentifier = CharOperation.subarray(typeName, dot + 1, typeName.length);
                this.selectedIdentifier = selectionIdentifier;
                field.type = new SelectionOnQualifiedTypeReference(previousIdentifiers, selectionIdentifier,
                        new long[previousIdentifiers.length + 1]);
            }
            field.name = "<fakeField>".toCharArray(); //$NON-NLS-1$
            typeDeclaration.fields = new FieldDeclaration[] { field };

            // build bindings
            this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
            if ((this.unitScope = parsedUnit.scope) != null) {
                try {
                    // build fields
                    // note: this builds fields only in the parsed unit (the buildFieldsAndMethods flag is not passed along)
                    this.lookupEnvironment.completeTypeBindings(parsedUnit, true);

                    // resolve
                    parsedUnit.scope.faultInTypes();
                    parsedUnit.resolve();
                } catch (SelectionNodeFound e) {
                    if (e.binding != null) {
                        if (DEBUG) {
                            System.out.println("SELECTION - Selection binding :"); //$NON-NLS-1$
                            System.out.println(e.binding.toString());
                        }
                        // if null then we found a problem in the selection node
                        selectFrom(e.binding, parsedUnit, e.isDeclaration);
                    }
                }
            }
        }
        if (this.noProposal && this.problem != null) {
            this.requestor.acceptError(this.problem);
        }
    } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
    } finally {
        reset(true);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.compiler.parser.SourceTypeConverter.java

License:Open Source License

private AbstractMethodDeclaration convert(SourceMethod methodHandle, SourceMethodElementInfo methodInfo,
        CompilationResult compilationResult) throws JavaModelException {
    AbstractMethodDeclaration method;/*from w  ww .j  a  va2  s .  co  m*/

    /* only source positions available */
    int start = methodInfo.getNameSourceStart();
    int end = methodInfo.getNameSourceEnd();

    /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=324850, Even when this type is being constructed
       on behalf of a 1.4 project we must internalize type variables properly in order to be able to
       recognize usages of them in the method signature, to apply substitutions and thus to be able to
       detect overriding in the presence of generics. If we simply drop them, when the method signature
       refers to the type parameter, we won't know it should be bound to the type parameter and perform
       incorrect lookup and may mistakenly end up with missing types
     */
    TypeParameter[] typeParams = null;
    char[][] typeParameterNames = methodInfo.getTypeParameterNames();
    if (typeParameterNames != null) {
        int parameterCount = typeParameterNames.length;
        if (parameterCount > 0) { // method's type parameters must be null if no type parameter
            char[][][] typeParameterBounds = methodInfo.getTypeParameterBounds();
            typeParams = new TypeParameter[parameterCount];
            for (int i = 0; i < parameterCount; i++) {
                typeParams[i] = createTypeParameter(typeParameterNames[i], typeParameterBounds[i], start, end);
            }
        }
    }

    int modifiers = methodInfo.getModifiers();
    if (methodInfo.isConstructor()) {
        ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult);
        decl.bits &= ~ASTNode.IsDefaultConstructor;
        method = decl;
        decl.typeParameters = typeParams;
    } else {
        MethodDeclaration decl;
        if (methodInfo.isAnnotationMethod()) {
            AnnotationMethodDeclaration annotationMethodDeclaration = new AnnotationMethodDeclaration(
                    compilationResult);

            /* conversion of default value */
            SourceAnnotationMethodInfo annotationMethodInfo = (SourceAnnotationMethodInfo) methodInfo;
            boolean hasDefaultValue = annotationMethodInfo.defaultValueStart != -1
                    || annotationMethodInfo.defaultValueEnd != -1;
            if ((this.flags & FIELD_INITIALIZATION) != 0) {
                if (hasDefaultValue) {
                    char[] defaultValueSource = CharOperation.subarray(getSource(),
                            annotationMethodInfo.defaultValueStart, annotationMethodInfo.defaultValueEnd + 1);
                    if (defaultValueSource != null) {
                        Expression expression = parseMemberValue(defaultValueSource);
                        if (expression != null) {
                            annotationMethodDeclaration.defaultValue = expression;
                        }
                    } else {
                        // could not retrieve the default value
                        hasDefaultValue = false;
                    }
                }
            }
            if (hasDefaultValue)
                modifiers |= ClassFileConstants.AccAnnotationDefault;
            decl = annotationMethodDeclaration;
        } else {
            decl = new MethodDeclaration(compilationResult);
        }

        // convert return type
        decl.returnType = createTypeReference(methodInfo.getReturnTypeName(), start, end);

        // type parameters
        decl.typeParameters = typeParams;

        method = decl;
    }
    method.selector = methodHandle.getElementName().toCharArray();
    boolean isVarargs = (modifiers & ClassFileConstants.AccVarargs) != 0;
    method.modifiers = modifiers & ~ClassFileConstants.AccVarargs;
    method.sourceStart = start;
    method.sourceEnd = end;
    method.declarationSourceStart = methodInfo.getDeclarationSourceStart();
    method.declarationSourceEnd = methodInfo.getDeclarationSourceEnd();

    // convert 1.5 specific constructs only if compliance is 1.5 or above
    if (this.has1_5Compliance) {
        /* convert annotations */
        method.annotations = convertAnnotations(methodHandle);
    }

    /* convert arguments */
    String[] argumentTypeSignatures = methodHandle.getParameterTypes();
    char[][] argumentNames = methodInfo.getArgumentNames();
    int argumentCount = argumentTypeSignatures == null ? 0 : argumentTypeSignatures.length;
    if (argumentCount > 0) {
        ILocalVariable[] parameters = methodHandle.getParameters();
        long position = ((long) start << 32) + end;
        method.arguments = new Argument[argumentCount];
        for (int i = 0; i < argumentCount; i++) {
            TypeReference typeReference = createTypeReference(argumentTypeSignatures[i], start, end);
            if (isVarargs && i == argumentCount - 1) {
                typeReference.bits |= ASTNode.IsVarArgs;
            }
            method.arguments[i] = new Argument(argumentNames[i], position, typeReference,
                    ClassFileConstants.AccDefault);
            // do not care whether was final or not
            // convert 1.5 specific constructs only if compliance is 1.5 or above
            if (this.has1_5Compliance) {
                /* convert annotations */
                method.arguments[i].annotations = convertAnnotations(parameters[i]);
            }
        }
    }

    /* convert thrown exceptions */
    char[][] exceptionTypeNames = methodInfo.getExceptionTypeNames();
    int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length;
    if (exceptionCount > 0) {
        method.thrownExceptions = new TypeReference[exceptionCount];
        for (int i = 0; i < exceptionCount; i++) {
            method.thrownExceptions[i] = createTypeReference(exceptionTypeNames[i], start, end);
        }
    }

    /* convert local and anonymous types */
    if ((this.flags & LOCAL_TYPE) != 0) {
        IJavaElement[] children = methodInfo.getChildren();
        int typesLength = children.length;
        if (typesLength != 0) {
            Statement[] statements = new Statement[typesLength];
            for (int i = 0; i < typesLength; i++) {
                SourceType type = (SourceType) children[i];
                TypeDeclaration localType = convert(type, compilationResult);
                if ((localType.bits & ASTNode.IsAnonymousType) != 0) {
                    QualifiedAllocationExpression expression = new QualifiedAllocationExpression(localType);
                    expression.type = localType.superclass;
                    localType.superclass = null;
                    localType.superInterfaces = null;
                    localType.allocation = expression;
                    statements[i] = expression;
                } else {
                    statements[i] = localType;
                }
            }
            method.statements = statements;
        }
    }

    return method;
}

From source file:com.codenvy.ide.ext.java.server.internal.compiler.parser.SourceTypeConverter.java

License:Open Source License

private Annotation[] convertAnnotations(IAnnotatable element) throws JavaModelException {
    IAnnotation[] annotations = element.getAnnotations();
    int length = annotations.length;
    Annotation[] astAnnotations = new Annotation[length];
    if (length > 0) {
        char[] cuSource = getSource();
        int recordedAnnotations = 0;
        for (int i = 0; i < length; i++) {
            ISourceRange positions = annotations[i].getSourceRange();
            int start = positions.getOffset();
            int end = start + positions.getLength();
            char[] annotationSource = CharOperation.subarray(cuSource, start, end);
            if (annotationSource != null) {
                Expression expression = parseMemberValue(annotationSource);
                /*/*ww w.j  av a2 s . c om*/
                 * expression can be null or not an annotation if the source has changed between
                 * the moment where the annotation source positions have been retrieved and the moment were
                 * this parsing occurred.
                 * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=90916
                 */
                if (expression instanceof Annotation) {
                    astAnnotations[recordedAnnotations++] = (Annotation) expression;
                }
            }
        }
        if (length != recordedAnnotations) {
            // resize to remove null annotations
            System.arraycopy(astAnnotations, 0, (astAnnotations = new Annotation[recordedAnnotations]), 0,
                    recordedAnnotations);
        }
    }
    return astAnnotations;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.BasicCompilationUnit.java

License:Open Source License

public char[] getMainTypeName() {
    if (this.mainTypeName == null) {
        int start = CharOperation.lastIndexOf('/', this.fileName) + 1;
        if (start == 0 || start < CharOperation.lastIndexOf('\\', this.fileName))
            start = CharOperation.lastIndexOf('\\', this.fileName) + 1;
        int separator = CharOperation.indexOf('|', this.fileName) + 1;
        if (separator > start) // case of a .class file in a default package in a jar
            start = separator;//from  w  ww . ja  va  2s  .co  m

        int end = CharOperation.lastIndexOf('$', this.fileName);
        if (end == -1 || !Util.isClassFileName(this.fileName)) {
            end = CharOperation.lastIndexOf('.', this.fileName);
            if (end == -1)
                end = this.fileName.length;
        }

        this.mainTypeName = CharOperation.subarray(this.fileName, start, end);
    }
    return this.mainTypeName;
}