Search in sources :

Example 1 with IMethodBinding

use of org.eclipse.jdt.core.dom.IMethodBinding in project che by eclipse.

the class AddImportsOperation method evaluateEdits.

private TextEdit evaluateEdits(CompilationUnit root, ImportRewrite importRewrite, int offset, int length, IProgressMonitor monitor) throws JavaModelException {
    SimpleName nameNode = null;
    if (root != null) {
        // got an AST
        ASTNode node = NodeFinder.perform(root, offset, length);
        if (node instanceof MarkerAnnotation) {
            node = ((Annotation) node).getTypeName();
        }
        if (node instanceof QualifiedName) {
            nameNode = ((QualifiedName) node).getName();
        } else if (node instanceof SimpleName) {
            nameNode = (SimpleName) node;
        }
    }
    String name, simpleName, containerName;
    int qualifierStart;
    int simpleNameStart;
    if (nameNode != null) {
        simpleName = nameNode.getIdentifier();
        simpleNameStart = nameNode.getStartPosition();
        if (nameNode.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
            Name qualifier = ((QualifiedName) nameNode.getParent()).getQualifier();
            containerName = qualifier.getFullyQualifiedName();
            name = JavaModelUtil.concatenateName(containerName, simpleName);
            qualifierStart = qualifier.getStartPosition();
        } else if (nameNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY) {
            NameQualifiedType nameQualifiedType = (NameQualifiedType) nameNode.getParent();
            Name qualifier = nameQualifiedType.getQualifier();
            containerName = qualifier.getFullyQualifiedName();
            name = JavaModelUtil.concatenateName(containerName, simpleName);
            qualifierStart = qualifier.getStartPosition();
            List<Annotation> annotations = nameQualifiedType.annotations();
            if (!annotations.isEmpty()) {
                // don't remove annotations
                simpleNameStart = annotations.get(0).getStartPosition();
            }
        } else if (nameNode.getLocationInParent() == MethodInvocation.NAME_PROPERTY) {
            ASTNode qualifier = ((MethodInvocation) nameNode.getParent()).getExpression();
            if (qualifier instanceof Name) {
                containerName = ASTNodes.asString(qualifier);
                name = JavaModelUtil.concatenateName(containerName, simpleName);
                qualifierStart = qualifier.getStartPosition();
            } else {
                return null;
            }
        } else {
            //$NON-NLS-1$
            containerName = "";
            name = simpleName;
            qualifierStart = simpleNameStart;
        }
        IBinding binding = nameNode.resolveBinding();
        if (binding != null && !binding.isRecovered()) {
            if (binding instanceof ITypeBinding) {
                ITypeBinding typeBinding = ((ITypeBinding) binding).getTypeDeclaration();
                String qualifiedBindingName = typeBinding.getQualifiedName();
                if (containerName.length() > 0 && !qualifiedBindingName.equals(name)) {
                    return null;
                }
                ImportRewriteContext context = new ContextSensitiveImportRewriteContext(root, qualifierStart, importRewrite);
                String res = importRewrite.addImport(typeBinding, context);
                if (containerName.length() > 0 && !res.equals(simpleName)) {
                    // adding import failed
                    fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
                    return null;
                }
                if (containerName.length() == 0 && res.equals(simpleName)) {
                    // no change necessary
                    return null;
                }
                return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, new String());
            } else if (JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject()) && (binding instanceof IVariableBinding || binding instanceof IMethodBinding)) {
                boolean isField = binding instanceof IVariableBinding;
                ITypeBinding declaringClass = isField ? ((IVariableBinding) binding).getDeclaringClass() : ((IMethodBinding) binding).getDeclaringClass();
                if (declaringClass == null) {
                    // variableBinding.getDeclaringClass() is null for array.length
                    return null;
                }
                if (Modifier.isStatic(binding.getModifiers())) {
                    if (containerName.length() > 0) {
                        if (containerName.equals(declaringClass.getName()) || containerName.equals(declaringClass.getQualifiedName())) {
                            ASTNode node = nameNode.getParent();
                            boolean isDirectlyAccessible = false;
                            while (node != null) {
                                if (isTypeDeclarationSubTypeCompatible(node, declaringClass)) {
                                    isDirectlyAccessible = true;
                                    break;
                                }
                                node = node.getParent();
                            }
                            if (!isDirectlyAccessible) {
                                if (Modifier.isPrivate(declaringClass.getModifiers())) {
                                    fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_not_visible_class, BasicElementLabels.getJavaElementName(declaringClass.getName())), null);
                                    return null;
                                }
                                String res = importRewrite.addStaticImport(declaringClass.getQualifiedName(), binding.getName(), isField);
                                if (!res.equals(simpleName)) {
                                    // adding import failed
                                    return null;
                                }
                            }
                            //$NON-NLS-1$
                            return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
                        }
                    }
                }
                // no static imports for packages
                return null;
            } else {
                return null;
            }
        }
        if (binding != null && binding.getKind() != IBinding.TYPE) {
            // recovered binding
            return null;
        }
    } else {
        IBuffer buffer = fCompilationUnit.getBuffer();
        qualifierStart = getNameStart(buffer, offset);
        int nameEnd = getNameEnd(buffer, offset + length);
        int len = nameEnd - qualifierStart;
        name = buffer.getText(qualifierStart, len).trim();
        if (name.length() == 0) {
            return null;
        }
        simpleName = Signature.getSimpleName(name);
        containerName = Signature.getQualifier(name);
        IJavaProject javaProject = fCompilationUnit.getJavaProject();
        if (simpleName.length() == 0 || JavaConventionsUtil.validateJavaTypeName(simpleName, javaProject).matches(IStatus.ERROR) || (containerName.length() > 0 && JavaConventionsUtil.validateJavaTypeName(containerName, javaProject).matches(IStatus.ERROR))) {
            fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_invalid_selection, null);
            return null;
        }
        simpleNameStart = getSimpleNameStart(buffer, qualifierStart, containerName);
        int res = importRewrite.getDefaultImportRewriteContext().findInContext(containerName, simpleName, ImportRewriteContext.KIND_TYPE);
        if (res == ImportRewriteContext.RES_NAME_CONFLICT) {
            fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
            return null;
        } else if (res == ImportRewriteContext.RES_NAME_FOUND) {
            //$NON-NLS-1$
            return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
        }
    }
    IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { fCompilationUnit.getJavaProject() });
    TypeNameMatch[] types = findAllTypes(simpleName, searchScope, nameNode, new SubProgressMonitor(monitor, 1));
    if (types.length == 0) {
        fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_notresolved_message, BasicElementLabels.getJavaElementName(simpleName)), null);
        return null;
    }
    if (monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    TypeNameMatch chosen;
    if (types.length > 1 && fQuery != null) {
        chosen = fQuery.chooseImport(types, containerName);
        if (chosen == null) {
            throw new OperationCanceledException();
        }
    } else {
        chosen = types[0];
    }
    ImportRewriteContext context = root == null ? null : new ContextSensitiveImportRewriteContext(root, simpleNameStart, importRewrite);
    importRewrite.addImport(chosen.getFullyQualifiedName(), context);
    //$NON-NLS-1$
    return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) IBinding(org.eclipse.jdt.core.dom.IBinding) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) IBuffer(org.eclipse.jdt.core.IBuffer) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) MarkerAnnotation(org.eclipse.jdt.core.dom.MarkerAnnotation) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) List(java.util.List) ArrayList(java.util.ArrayList) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Example 2 with IMethodBinding

use of org.eclipse.jdt.core.dom.IMethodBinding in project che by eclipse.

the class ASTNodeFactory method newType.

private static Type newType(LambdaExpression lambdaExpression, VariableDeclarationFragment declaration, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) {
    IMethodBinding method = lambdaExpression.resolveMethodBinding();
    if (method != null) {
        ITypeBinding[] parameterTypes = method.getParameterTypes();
        int index = lambdaExpression.parameters().indexOf(declaration);
        ITypeBinding typeBinding = parameterTypes[index];
        if (importRewrite != null) {
            return importRewrite.addImport(typeBinding, ast, context);
        } else {
            String qualifiedName = typeBinding.getQualifiedName();
            if (qualifiedName.length() > 0) {
                return newType(ast, qualifiedName);
            }
        }
    }
    //$NON-NLS-1$
    return ast.newSimpleType(ast.newSimpleName("Object"));
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding)

Example 3 with IMethodBinding

use of org.eclipse.jdt.core.dom.IMethodBinding in project che by eclipse.

the class Bindings method findMethodInHierarchy.

/**
     * Finds the method specified by <code>methodName</code> and </code>parameters</code> in
     * the type hierarchy denoted by the given type. Returns <code>null</code> if no such method
     * exists. If the method is defined in more than one super type only the first match is
     * returned. First the super class is examined and then the implemented interfaces.
     *
     * @param type The type to search the method in
     * @param methodName The name of the method to find
     * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only the name is matched and parameters are ignored.
     * @return the method binding representing the method
     */
public static IMethodBinding findMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding[] parameters) {
    IMethodBinding method = findMethodInType(type, methodName, parameters);
    if (method != null)
        return method;
    ITypeBinding superClass = type.getSuperclass();
    if (superClass != null) {
        method = findMethodInHierarchy(superClass, methodName, parameters);
        if (method != null)
            return method;
    }
    ITypeBinding[] interfaces = type.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        method = findMethodInHierarchy(interfaces[i], methodName, parameters);
        if (method != null)
            return method;
    }
    return null;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding)

Example 4 with IMethodBinding

use of org.eclipse.jdt.core.dom.IMethodBinding in project che by eclipse.

the class StubUtility method getParameterTypeNamesForSeeTag.

/*
	 * Returns the parameters type names used in see tags. Currently, these are always fully qualified.
	 */
private static String[] getParameterTypeNamesForSeeTag(IMethod overridden) {
    try {
        CheASTParser parser = CheASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setProject(overridden.getJavaProject());
        IBinding[] bindings = parser.createBindings(new IJavaElement[] { overridden }, null);
        if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) {
            return getParameterTypeNamesForSeeTag((IMethodBinding) bindings[0]);
        }
    } catch (IllegalStateException e) {
    // method does not exist
    }
    // fall back code. Not good for generic methods!
    String[] paramTypes = overridden.getParameterTypes();
    String[] paramTypeNames = new String[paramTypes.length];
    for (int i = 0; i < paramTypes.length; i++) {
        paramTypeNames[i] = Signature.toString(Signature.getTypeErasure(paramTypes[i]));
    }
    return paramTypeNames;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) IBinding(org.eclipse.jdt.core.dom.IBinding) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser)

Example 5 with IMethodBinding

use of org.eclipse.jdt.core.dom.IMethodBinding in project che by eclipse.

the class StubUtility2 method getDelegateCandidates.

//	public static DelegateEntry[] getDelegatableMethods(ITypeBinding binding) {
//		final List<DelegateEntry> tuples= new ArrayList<DelegateEntry>();
//		final List<IMethodBinding> declared= new ArrayList<IMethodBinding>();
//		IMethodBinding[] typeMethods= binding.getDeclaredMethods();
//		for (int index= 0; index < typeMethods.length; index++)
//			declared.add(typeMethods[index]);
//		IVariableBinding[] typeFields= binding.getDeclaredFields();
//		for (int index= 0; index < typeFields.length; index++) {
//			IVariableBinding fieldBinding= typeFields[index];
//			if (fieldBinding.isField() && !fieldBinding.isEnumConstant() && !fieldBinding.isSynthetic())
//				getDelegatableMethods(new ArrayList<IMethodBinding>(declared), fieldBinding, fieldBinding.getType(), binding, tuples);
//		}
//		// list of tuple<IVariableBinding, IMethodBinding>
//		return tuples.toArray(new DelegateEntry[tuples.size()]);
//	}
//
//	private static void getDelegatableMethods(List<IMethodBinding> methods, IVariableBinding fieldBinding, ITypeBinding typeBinding, ITypeBinding binding, List<DelegateEntry> result) {
//		boolean match= false;
//		if (typeBinding.isTypeVariable()) {
//			ITypeBinding[] typeBounds= typeBinding.getTypeBounds();
//			if (typeBounds.length > 0) {
//				for (int i= 0; i < typeBounds.length; i++) {
//					getDelegatableMethods(methods, fieldBinding, typeBounds[i], binding, result);
//				}
//			} else {
//				ITypeBinding objectBinding= Bindings.findTypeInHierarchy(binding, "java.lang.Object"); //$NON-NLS-1$
//				if (objectBinding != null) {
//					getDelegatableMethods(methods, fieldBinding, objectBinding, binding, result);
//				}
//			}
//		} else {
//			IMethodBinding[] candidates= getDelegateCandidates(typeBinding, binding);
//			for (int index= 0; index < candidates.length; index++) {
//				match= false;
//				final IMethodBinding methodBinding= candidates[index];
//				for (int offset= 0; offset < methods.size() && !match; offset++) {
//					if (Bindings.areOverriddenMethods(methods.get(offset), methodBinding))
//						match= true;
//				}
//				if (!match) {
//					result.add(new DelegateEntry(methodBinding, fieldBinding));
//					methods.add(methodBinding);
//				}
//			}
//			final ITypeBinding superclass= typeBinding.getSuperclass();
//			if (superclass != null)
//				getDelegatableMethods(methods, fieldBinding, superclass, binding, result);
//			ITypeBinding[] superInterfaces= typeBinding.getInterfaces();
//			for (int offset= 0; offset < superInterfaces.length; offset++)
//				getDelegatableMethods(methods, fieldBinding, superInterfaces[offset], binding, result);
//		}
//	}
private static IMethodBinding[] getDelegateCandidates(ITypeBinding binding, ITypeBinding hierarchy) {
    List<IMethodBinding> allMethods = new ArrayList<IMethodBinding>();
    boolean isInterface = binding.isInterface();
    IMethodBinding[] typeMethods = binding.getDeclaredMethods();
    for (int index = 0; index < typeMethods.length; index++) {
        final int modifiers = typeMethods[index].getModifiers();
        if (!typeMethods[index].isConstructor() && !Modifier.isStatic(modifiers) && (isInterface || Modifier.isPublic(modifiers))) {
            IMethodBinding result = Bindings.findOverriddenMethodInHierarchy(hierarchy, typeMethods[index]);
            if (result != null && Flags.isFinal(result.getModifiers()))
                continue;
            ITypeBinding[] parameterBindings = typeMethods[index].getParameterTypes();
            boolean upper = false;
            for (int offset = 0; offset < parameterBindings.length; offset++) {
                if (parameterBindings[offset].isWildcardType() && parameterBindings[offset].isUpperbound())
                    upper = true;
            }
            if (!upper)
                allMethods.add(typeMethods[index]);
        }
    }
    return allMethods.toArray(new IMethodBinding[allMethods.size()]);
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ArrayList(java.util.ArrayList)

Aggregations

IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)164 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)103 ASTNode (org.eclipse.jdt.core.dom.ASTNode)46 Expression (org.eclipse.jdt.core.dom.Expression)34 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)33 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)32 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)28 ArrayList (java.util.ArrayList)27 IBinding (org.eclipse.jdt.core.dom.IBinding)24 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)20 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)20 CastExpression (org.eclipse.jdt.core.dom.CastExpression)19 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)19 SimpleName (org.eclipse.jdt.core.dom.SimpleName)19 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)18 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)18 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)17 Image (org.eclipse.swt.graphics.Image)16 AST (org.eclipse.jdt.core.dom.AST)15 Type (org.eclipse.jdt.core.dom.Type)15