List of usage examples for org.eclipse.jdt.core IMethod isConstructor
boolean isConstructor() throws JavaModelException;
From source file:at.bestsolution.fxide.jdt.corext.util.MethodOverrideTester.java
License:Open Source License
/** * Finds the method that is overridden by the given method. * First the super class is examined and then the implemented interfaces. * @param overriding the overriding method * @param testVisibility If true the result is tested on visibility. Null is returned if the method is not visible. * @return a method that is directly overridden by the given method, or <code>null</code> * @throws JavaModelException if a problem occurs *///w w w .j a v a2 s . c o m public IMethod findOverriddenMethod(IMethod overriding, boolean testVisibility) throws JavaModelException { int flags = overriding.getFlags(); if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overriding.isConstructor()) { return null; } IType type = overriding.getDeclaringType(); IType superClass = fHierarchy.getSuperclass(type); if (superClass != null) { IMethod res = findOverriddenMethodInHierarchy(superClass, overriding); if (res != null) { if (!testVisibility || JavaModelUtil.isVisibleInHierarchy(res, type.getPackageFragment())) { return res; } } } IType[] interfaces = fHierarchy.getSuperInterfaces(type); for (int i = 0; i < interfaces.length; i++) { IMethod res = findOverriddenMethodInHierarchy(interfaces[i], overriding); if (res != null) { return res; // methods from interfaces are always public and therefore visible } } return null; }
From source file:at.bestsolution.fxide.jdt.corext.util.MethodOverrideTester.java
License:Open Source License
/** * Finds an overridden method in a type. With generics it is possible that 2 methods in the same type are overridden at the same time. * In that case the first overridden method found is returned. * @param overriddenType The type to find methods in * @param overriding The overriding method * @return The first overridden method or <code>null</code> if no method is overridden * @throws JavaModelException if a problem occurs *//*from w w w . j av a 2 s.com*/ public IMethod findOverriddenMethodInType(IType overriddenType, IMethod overriding) throws JavaModelException { int flags = overriding.getFlags(); if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overriding.isConstructor()) return null; IMethod[] overriddenMethods = overriddenType.getMethods(); for (int i = 0; i < overriddenMethods.length; i++) { IMethod overridden = overriddenMethods[i]; flags = overridden.getFlags(); if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overridden.isConstructor()) continue; if (isSubsignature(overriding, overridden)) { return overridden; } } return null; }
From source file:at.bestsolution.fxide.jdt.corext.util.MethodOverrideTester.java
License:Open Source License
/** * Finds an overriding method in a type. * @param overridingType The type to find methods in * @param overridden The overridden method * @return The overriding method or <code>null</code> if no method is overriding. * @throws JavaModelException if a problem occurs *//*from w w w . j av a 2 s . c o m*/ public IMethod findOverridingMethodInType(IType overridingType, IMethod overridden) throws JavaModelException { int flags = overridden.getFlags(); if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overridden.isConstructor()) return null; IMethod[] overridingMethods = overridingType.getMethods(); for (int i = 0; i < overridingMethods.length; i++) { IMethod overriding = overridingMethods[i]; flags = overriding.getFlags(); if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overriding.isConstructor()) continue; if (isSubsignature(overriding, overridden)) { return overriding; } } return null; }
From source file:at.bestsolution.fxide.jdt.editor.internal.MethodUtil.java
License:Open Source License
/** * Tests if a method equals to the given signature. Parameter types are only * compared by the simple name, no resolving for the fully qualified type * name is done. Constructors are only compared by parameters, not the name. * * @param name Name of the method//from w ww. j a v a 2s . c o m * @param paramTypes The type signatures of the parameters e.g. * <code>{"QString;","I"}</code> * @param isConstructor Specifies if the method is a constructor * @param method the method to be compared with this info's method * @param typeVariables a map from type variables to types * @param type the given type that declares the method * @return Returns <code>true</code> if the method has the given name and * parameter types and constructor state. * @throws JavaModelException if the method does not exist or if an exception occurs while accessing its corresponding resource */ private boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IMethod method, Map<String, char[]> typeVariables, IType type) throws JavaModelException { if (isConstructor || name.equals(method.getElementName())) { if (isConstructor == method.isConstructor()) { String[] otherParams = method.getParameterTypes(); // types may be type variables boolean isBinaryConstructorForNonStaticMemberClass = method.isBinary() && type.isMember() && !Flags.isStatic(type.getFlags()); int syntheticParameterCorrection = isBinaryConstructorForNonStaticMemberClass && paramTypes.length == otherParams.length - 1 ? 1 : 0; if (paramTypes.length == otherParams.length - syntheticParameterCorrection) { fFallbackMatch = method; String signature = method.getSignature(); String[] otherParamsFromSignature = Signature.getParameterTypes(signature); // types are resolved / upper-bounded // no need to check method type variables since these are // not yet bound when proposing a method for (int i = 0; i < paramTypes.length; i++) { String ourParamName = computeSimpleTypeName(paramTypes[i], typeVariables); String otherParamName1 = computeSimpleTypeName( otherParams[i + syntheticParameterCorrection], typeVariables); String otherParamName2 = computeSimpleTypeName( otherParamsFromSignature[i + syntheticParameterCorrection], typeVariables); if (!ourParamName.equals(otherParamName1) && !ourParamName.equals(otherParamName2)) { return false; } } return true; } } } return false; }
From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java
License:Open Source License
/** * Appends the label for a method. Considers the M_* flags. * * @param method the element to render//from w w w . j ava 2s. co m * @param flags the rendering flags. Flags with names starting with 'M_' are considered. */ public void appendMethodLabel(IMethod method, long flags) { try { BindingKey resolvedKey = getFlag(flags, JavaElementLabels.USE_RESOLVED) && method.isResolved() ? new BindingKey(method.getKey()) : null; String resolvedSig = (resolvedKey != null) ? resolvedKey.toSignature() : null; // type parameters if (getFlag(flags, JavaElementLabels.M_PRE_TYPE_PARAMETERS)) { if (resolvedKey != null) { if (resolvedKey.isParameterizedMethod()) { String[] typeArgRefs = resolvedKey.getTypeArguments(); if (typeArgRefs.length > 0) { appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags); fBuffer.append(' '); } } else { String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig); if (typeParameterSigs.length > 0) { appendTypeParameterSignaturesLabel(typeParameterSigs, flags); fBuffer.append(' '); } } } else if (method.exists()) { ITypeParameter[] typeParameters = method.getTypeParameters(); if (typeParameters.length > 0) { appendTypeParametersLabels(typeParameters, flags); fBuffer.append(' '); } } } // return type if (getFlag(flags, JavaElementLabels.M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) { String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig) : method.getReturnType(); appendTypeSignatureLabel(method, returnTypeSig, flags); fBuffer.append(' '); } // qualification if (getFlag(flags, JavaElementLabels.M_FULLY_QUALIFIED)) { appendTypeLabel(method.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuffer.append('.'); } fBuffer.append(getElementName(method)); // constructor type arguments if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS) && method.exists() && method.isConstructor()) { if (resolvedSig != null && resolvedKey.isParameterizedType()) { BindingKey declaringType = resolvedKey.getDeclaringType(); if (declaringType != null) { String[] declaringTypeArguments = declaringType.getTypeArguments(); appendTypeArgumentSignaturesLabel(method, declaringTypeArguments, flags); } } } // parameters fBuffer.append('('); String[] declaredParameterTypes = method.getParameterTypes(); if (getFlag(flags, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES)) { String[] types = null; int nParams = 0; boolean renderVarargs = false; boolean isPolymorphic = false; if (getFlag(flags, JavaElementLabels.M_PARAMETER_TYPES)) { if (resolvedSig != null) { types = Signature.getParameterTypes(resolvedSig); } else { types = declaredParameterTypes; } nParams = types.length; renderVarargs = method.exists() && Flags.isVarargs(method.getFlags()); if (renderVarargs && resolvedSig != null && declaredParameterTypes.length == 1 && JavaModelUtil.isPolymorphicSignature(method)) { renderVarargs = false; isPolymorphic = true; } } String[] names = null; if (getFlag(flags, JavaElementLabels.M_PARAMETER_NAMES) && method.exists()) { names = method.getParameterNames(); if (isPolymorphic) { // handled specially below } else if (types == null) { nParams = names.length; } else { // types != null if (nParams != names.length) { if (resolvedSig != null && types.length > names.length) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=99137 nParams = names.length; String[] typesWithoutSyntheticParams = new String[nParams]; System.arraycopy(types, types.length - nParams, typesWithoutSyntheticParams, 0, nParams); types = typesWithoutSyntheticParams; } else { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=101029 // JavaPlugin.logErrorMessage("JavaElementLabels: Number of param types(" + nParams + ") != number of names(" + names.length + "): " + method.getElementName()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ names = null; // no names rendered } } } } ILocalVariable[] annotatedParameters = null; if (nParams > 0 && getFlag(flags, JavaElementLabels.M_PARAMETER_ANNOTATIONS)) { annotatedParameters = method.getParameters(); } for (int i = 0; i < nParams; i++) { if (i > 0) { fBuffer.append(JavaElementLabels.COMMA_STRING); } if (annotatedParameters != null && i < annotatedParameters.length) { appendAnnotationLabels(annotatedParameters[i].getAnnotations(), flags); } if (types != null) { String paramSig = types[i]; if (renderVarargs && (i == nParams - 1)) { int newDim = Signature.getArrayCount(paramSig) - 1; appendTypeSignatureLabel(method, Signature.getElementType(paramSig), flags); for (int k = 0; k < newDim; k++) { fBuffer.append('[').append(']'); } fBuffer.append(JavaElementLabels.ELLIPSIS_STRING); } else { appendTypeSignatureLabel(method, paramSig, flags); } } if (names != null) { if (types != null) { fBuffer.append(' '); } if (isPolymorphic) { fBuffer.append(names[0] + i); } else { fBuffer.append(names[i]); } } } } else { if (declaredParameterTypes.length > 0) { fBuffer.append(JavaElementLabels.ELLIPSIS_STRING); } } fBuffer.append(')'); if (getFlag(flags, JavaElementLabels.M_EXCEPTIONS)) { String[] types; if (resolvedKey != null) { types = resolvedKey.getThrownExceptions(); } else { types = method.exists() ? method.getExceptionTypes() : new String[0]; } if (types.length > 0) { fBuffer.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < types.length; i++) { if (i > 0) { fBuffer.append(JavaElementLabels.COMMA_STRING); } appendTypeSignatureLabel(method, types[i], flags); } } } if (getFlag(flags, JavaElementLabels.M_APP_TYPE_PARAMETERS)) { int offset = fBuffer.length(); if (resolvedKey != null) { if (resolvedKey.isParameterizedMethod()) { String[] typeArgRefs = resolvedKey.getTypeArguments(); if (typeArgRefs.length > 0) { fBuffer.append(' '); appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags); } } else { String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig); if (typeParameterSigs.length > 0) { fBuffer.append(' '); appendTypeParameterSignaturesLabel(typeParameterSigs, flags); } } } else if (method.exists()) { ITypeParameter[] typeParameters = method.getTypeParameters(); if (typeParameters.length > 0) { fBuffer.append(' '); appendTypeParametersLabels(typeParameters, flags); } } // if (getFlag(flags, JavaElementLabels.COLORIZE) && offset != fBuffer.length()) { // fBuffer.setStyle(offset, fBuffer.length() - offset, DECORATIONS_STYLE); // } } if (getFlag(flags, JavaElementLabels.M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) { int offset = fBuffer.length(); fBuffer.append(JavaElementLabels.DECL_STRING); String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig) : method.getReturnType(); appendTypeSignatureLabel(method, returnTypeSig, flags); // if (getFlag(flags, JavaElementLabels.COLORIZE)) { // fBuffer.setStyle(offset, fBuffer.length() - offset, DECORATIONS_STYLE); // } } // category if (getFlag(flags, JavaElementLabels.M_CATEGORY) && method.exists()) appendCategoryLabel(method, flags); // post qualification if (getFlag(flags, JavaElementLabels.M_POST_QUALIFIED)) { int offset = fBuffer.length(); fBuffer.append(JavaElementLabels.CONCAT_STRING); appendTypeLabel(method.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); // if (getFlag(flags, JavaElementLabels.COLORIZE)) { // fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE); // } } } catch (JavaModelException e) { //TODO e.printStackTrace(); } }
From source file:ca.mcgill.cs.swevo.jayfx.FastConverter.java
License:Open Source License
/** * Optimization to find an IMethod without having to resolve the parameters. * /*from w ww . java2s . c om*/ * @return the IMethod corresponding to a candidate. Null if none are found. */ private IJavaElement findMethod(final MethodElement pMethod, final IMethod[] pCandidates) { IJavaElement lReturn = null; final List<IMethod> lSimilar = new ArrayList<IMethod>(); for (final IMethod element : pCandidates) { String lName = element.getElementName(); try { if (element.isConstructor()) lName = "<init>"; } catch (final JavaModelException pException) { return null; } if (lName.equals(pMethod.getName())) if (element.getNumberOfParameters() == FastConverter.numberOfParams(pMethod.getParameters())) lSimilar.add(element); } if (lSimilar.size() == 1) lReturn = lSimilar.get(0); else for (int i = 0; i < lSimilar.size(); i++) try { if (this.getElement(lSimilar.get(i)) == pMethod) lReturn = lSimilar.get(i); } catch (final ConversionException pException) { // nothing, the method will return null } return lReturn; }
From source file:com.cb.eclipse.folding.java.calculation.MethodStrategy.java
License:Open Source License
private boolean isConstructor(IMethod elem) throws JavaModelException { // StopWatch watch = new StopWatch("isConstructor"); // watch.start(); boolean result = elem.isConstructor(); // watch.endAndReport(); return result; }
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 ww w . j a v a 2 s . c om*/ * <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.internal.core.BinaryTypeConverter.java
License:Open Source License
private AbstractMethodDeclaration convert(IMethod method, IType type) throws JavaModelException { AbstractMethodDeclaration methodDeclaration; org.eclipse.jdt.internal.compiler.ast.TypeParameter[] typeParams = null; // convert 1.5 specific constructs only if compliance is 1.5 or above if (this.has1_5Compliance) { /* convert type parameters */ ITypeParameter[] typeParameters = method.getTypeParameters(); if (typeParameters != null && typeParameters.length > 0) { int parameterCount = typeParameters.length; typeParams = new org.eclipse.jdt.internal.compiler.ast.TypeParameter[parameterCount]; for (int i = 0; i < parameterCount; i++) { ITypeParameter typeParameter = typeParameters[i]; typeParams[i] = createTypeParameter(typeParameter.getElementName().toCharArray(), stringArrayToCharArray(typeParameter.getBounds()), 0, 0); }//from w w w.j a v a 2 s . c om } } if (method.isConstructor()) { ConstructorDeclaration decl = new ConstructorDeclaration(this.compilationResult); decl.bits &= ~ASTNode.IsDefaultConstructor; decl.typeParameters = typeParams; methodDeclaration = decl; } else { MethodDeclaration decl = type.isAnnotation() ? new AnnotationMethodDeclaration(this.compilationResult) : new MethodDeclaration(this.compilationResult); /* convert return type */ TypeReference typeReference = createTypeReference(method.getReturnType()); if (typeReference == null) return null; decl.returnType = typeReference; decl.typeParameters = typeParams; methodDeclaration = decl; } methodDeclaration.selector = method.getElementName().toCharArray(); int flags = method.getFlags(); boolean isVarargs = Flags.isVarargs(flags); methodDeclaration.modifiers = flags & ~Flags.AccVarargs; /* convert arguments */ String[] argumentTypeNames = method.getParameterTypes(); String[] argumentNames = method.getParameterNames(); int argumentCount = argumentTypeNames == null ? 0 : argumentTypeNames.length; // Ignore synthetic arguments (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=212224) int startIndex = (method.isConstructor() && type.isMember() && !Flags.isStatic(type.getFlags())) ? 1 : 0; argumentCount -= startIndex; methodDeclaration.arguments = new Argument[argumentCount]; for (int i = 0; i < argumentCount; i++) { String argumentTypeName = argumentTypeNames[startIndex + i]; TypeReference typeReference = createTypeReference(argumentTypeName); if (typeReference == null) return null; if (isVarargs && i == argumentCount - 1) { typeReference.bits |= ASTNode.IsVarArgs; } methodDeclaration.arguments[i] = new Argument(argumentNames[i].toCharArray(), 0, typeReference, ClassFileConstants.AccDefault); // do not care whether was final or not } /* convert thrown exceptions */ String[] exceptionTypeNames = method.getExceptionTypes(); int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length; if (exceptionCount > 0) { methodDeclaration.thrownExceptions = new TypeReference[exceptionCount]; for (int i = 0; i < exceptionCount; i++) { TypeReference typeReference = createTypeReference(exceptionTypeNames[i]); if (typeReference == null) return null; methodDeclaration.thrownExceptions[i] = typeReference; } } return methodDeclaration; }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.BasicSearchEngine.java
License:Open Source License
public void searchAllConstructorDeclarations(final char[] packageName, final char[] typeName, final int typeMatchRule, IJavaSearchScope scope, final IRestrictedAccessConstructorRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException { // Validate match rule first final int validatedTypeMatchRule = SearchPattern .validateMatchRule(typeName == null ? null : new String(typeName), typeMatchRule); final int pkgMatchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE; final char NoSuffix = IIndexConstants.TYPE_SUFFIX; // Used as TYPE_SUFFIX has no effect in method #match(char, char[] , int, char[], int , int, char[], char[]) // Debug/*from w w w . j a v a 2 s.co m*/ if (VERBOSE) { Util.verbose( "BasicSearchEngine.searchAllConstructorDeclarations(char[], char[], int, IJavaSearchScope, IRestrictedAccessConstructorRequestor, int, IProgressMonitor)"); //$NON-NLS-1$ Util.verbose(" - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type name: " + (typeName == null ? "null" : new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type match rule: " + getMatchRuleString(typeMatchRule)); //$NON-NLS-1$ if (validatedTypeMatchRule != typeMatchRule) { Util.verbose(" - validated type match rule: " + getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$ } Util.verbose(" - scope: " + scope); //$NON-NLS-1$ } if (validatedTypeMatchRule == -1) return; // invalid match rule => return no results // Create pattern final ConstructorDeclarationPattern pattern = new ConstructorDeclarationPattern(packageName, typeName, validatedTypeMatchRule); // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor final HashSet workingCopyPaths = new HashSet(); String workingCopyPath = null; ICompilationUnit[] copies = getWorkingCopies(); final int copiesLength = copies == null ? 0 : copies.length; if (copies != null) { if (copiesLength == 1) { workingCopyPath = copies[0].getPath().toString(); } else { for (int i = 0; i < copiesLength; i++) { ICompilationUnit workingCopy = copies[i]; workingCopyPaths.add(workingCopy.getPath().toString()); } } } final String singleWkcpPath = workingCopyPath; // Index requestor IndexQueryRequestor searchRequestor = new IndexQueryRequestor() { public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types ConstructorDeclarationPattern record = (ConstructorDeclarationPattern) indexRecord; if ((record.extraFlags & ExtraFlags.IsMemberType) != 0) { return true; // filter out member classes } if ((record.extraFlags & ExtraFlags.IsLocalType) != 0) { return true; // filter out local and anonymous classes } switch (copiesLength) { case 0: break; case 1: if (singleWkcpPath.equals(documentPath)) { return true; // filter out *the* working copy } break; default: if (workingCopyPaths.contains(documentPath)) { return true; // filter out working copies } break; } // Accept document path AccessRestriction accessRestriction = null; if (access != null) { // Compute document relative path int pkgLength = (record.declaringPackageName == null || record.declaringPackageName.length == 0) ? 0 : record.declaringPackageName.length + 1; int nameLength = record.declaringSimpleName == null ? 0 : record.declaringSimpleName.length; char[] path = new char[pkgLength + nameLength]; int pos = 0; if (pkgLength > 0) { System.arraycopy(record.declaringPackageName, 0, path, pos, pkgLength - 1); CharOperation.replace(path, '.', '/'); path[pkgLength - 1] = '/'; pos += pkgLength; } if (nameLength > 0) { System.arraycopy(record.declaringSimpleName, 0, path, pos, nameLength); pos += nameLength; } // Update access restriction if path is not empty if (pos > 0) { accessRestriction = access.getViolatedRestriction(path); } } nameRequestor.acceptConstructor(record.modifiers, record.declaringSimpleName, record.parameterCount, record.signature, record.parameterTypes, record.parameterNames, record.declaringTypeModifiers, record.declaringPackageName, record.extraFlags, documentPath, accessRestriction); return true; } }; try { if (progressMonitor != null) { progressMonitor.beginTask(Messages.engine_searching, 1000); } // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob(pattern, getDefaultSearchParticipant(indexManager), // Java search only scope, searchRequestor, indexManager), waitingPolicy, progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000 - copiesLength)); // add type names from working copies if (copies != null) { for (int i = 0; i < copiesLength; i++) { final ICompilationUnit workingCopy = copies[i]; if (scope instanceof HierarchyScope) { if (!((HierarchyScope) scope).encloses(workingCopy, progressMonitor)) continue; } else { if (!scope.encloses(workingCopy)) continue; } final String path = workingCopy.getPath().toString(); if (workingCopy.isConsistent()) { IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations(); char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR : packageDeclarations[0].getElementName().toCharArray(); IType[] allTypes = workingCopy.getAllTypes(); for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { IType type = allTypes[j]; char[] simpleName = type.getElementName().toCharArray(); if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule, 0/*no kind*/, packageDeclaration, simpleName) && !type.isMember()) { int extraFlags = ExtraFlags.getExtraFlags(type); boolean hasConstructor = false; IMethod[] methods = type.getMethods(); for (int k = 0; k < methods.length; k++) { IMethod method = methods[k]; if (method.isConstructor()) { hasConstructor = true; String[] stringParameterNames = method.getParameterNames(); String[] stringParameterTypes = method.getParameterTypes(); int length = stringParameterNames.length; char[][] parameterNames = new char[length][]; char[][] parameterTypes = new char[length][]; for (int l = 0; l < length; l++) { parameterNames[l] = stringParameterNames[l].toCharArray(); parameterTypes[l] = Signature.toCharArray(Signature .getTypeErasure(stringParameterTypes[l]).toCharArray()); } nameRequestor.acceptConstructor(method.getFlags(), simpleName, parameterNames.length, null, // signature is not used for source type parameterTypes, parameterNames, type.getFlags(), packageDeclaration, extraFlags, path, null); } } if (!hasConstructor) { nameRequestor.acceptConstructor(Flags.AccPublic, simpleName, -1, null, // signature is not used for source type CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR, type.getFlags(), packageDeclaration, extraFlags, path, null); } } } } else { Parser basicParser = getParser(); org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy; CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult); if (parsedUnit != null) { final char[] packageDeclaration = parsedUnit.currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.'); class AllConstructorDeclarationsVisitor extends ASTVisitor { private TypeDeclaration[] declaringTypes = new TypeDeclaration[0]; private int declaringTypesPtr = -1; private void endVisit(TypeDeclaration typeDeclaration) { if (!hasConstructor(typeDeclaration) && typeDeclaration.enclosingType == null) { if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule, 0/*no kind*/, packageDeclaration, typeDeclaration.name)) { nameRequestor.acceptConstructor(Flags.AccPublic, typeName, -1, null, // signature is not used for source type CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR, typeDeclaration.modifiers, packageDeclaration, ExtraFlags.getExtraFlags(typeDeclaration), path, null); } } this.declaringTypes[this.declaringTypesPtr] = null; this.declaringTypesPtr--; } public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope s) { endVisit(typeDeclaration); } public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope s) { endVisit(memberTypeDeclaration); } private boolean hasConstructor(TypeDeclaration typeDeclaration) { AbstractMethodDeclaration[] methods = typeDeclaration.methods; int length = methods == null ? 0 : methods.length; for (int j = 0; j < length; j++) { if (methods[j].isConstructor()) { return true; } } return false; } public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope classScope) { TypeDeclaration typeDeclaration = this.declaringTypes[this.declaringTypesPtr]; if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule, 0/*no kind*/, packageDeclaration, typeDeclaration.name)) { Argument[] arguments = constructorDeclaration.arguments; int length = arguments == null ? 0 : arguments.length; char[][] parameterNames = new char[length][]; char[][] parameterTypes = new char[length][]; for (int l = 0; l < length; l++) { Argument argument = arguments[l]; parameterNames[l] = argument.name; if (argument.type instanceof SingleTypeReference) { parameterTypes[l] = ((SingleTypeReference) argument.type).token; } else { parameterTypes[l] = CharOperation.concatWith( ((QualifiedTypeReference) argument.type).tokens, '.'); } } TypeDeclaration enclosing = typeDeclaration.enclosingType; char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; while (enclosing != null) { enclosingTypeNames = CharOperation.arrayConcat( new char[][] { enclosing.name }, enclosingTypeNames); if ((enclosing.bits & ASTNode.IsMemberType) != 0) { enclosing = enclosing.enclosingType; } else { enclosing = null; } } nameRequestor.acceptConstructor(constructorDeclaration.modifiers, typeName, parameterNames.length, null, // signature is not used for source type parameterTypes, parameterNames, typeDeclaration.modifiers, packageDeclaration, ExtraFlags.getExtraFlags(typeDeclaration), path, null); } return false; // no need to find constructors from local/anonymous type } public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) { return false; } private boolean visit(TypeDeclaration typeDeclaration) { if (this.declaringTypes.length <= ++this.declaringTypesPtr) { int length = this.declaringTypesPtr; System.arraycopy(this.declaringTypes, 0, this.declaringTypes = new TypeDeclaration[length * 2 + 1], 0, length); } this.declaringTypes[this.declaringTypesPtr] = typeDeclaration; return true; } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope s) { return visit(typeDeclaration); } public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope s) { return visit(memberTypeDeclaration); } } parsedUnit.traverse(new AllConstructorDeclarationsVisitor(), parsedUnit.scope); } } if (progressMonitor != null) { if (progressMonitor.isCanceled()) throw new OperationCanceledException(); progressMonitor.worked(1); } } } } finally { if (progressMonitor != null) { progressMonitor.done(); } } }