Java Code Examples for org.eclipse.jdt.core.dom.IMethodBinding#getParameterTypes()

The following examples show how to use org.eclipse.jdt.core.dom.IMethodBinding#getParameterTypes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new method parameter variable.
 *
 * @param method the method binding
 * @param index the index of the parameter
 * @return the created method parameter variable, or <code>null</code>
 */
public final ConstraintVariable2 createMethodParameterVariable(final IMethodBinding method, final int index) {
	final ITypeBinding[] parameters= method.getParameterTypes();
	if (parameters.length < 1)
		return null;
	ITypeBinding binding= parameters[Math.min(index, parameters.length - 1)];
	if (binding.isArray())
		binding= binding.getElementType();
	if (isConstrainedType(binding)) {
		ConstraintVariable2 variable= null;
		final TType type= createTType(binding);
		if (method.getDeclaringClass().isFromSource())
			variable= new ParameterTypeVariable2(type, index, method.getMethodDeclaration());
		else
			variable= new ImmutableTypeVariable2(type);
		return fConstraintVariables.addExisting(variable);
	}
	return null;
}
 
Example 2
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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);
			}
		}
	}
	// fall-back
	return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
 
Example 3
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocationCore problem,
		List<IMethodBinding> similarElements, ASTNode invocationNode, List<Expression> arguments,
		Collection<ChangeCorrectionProposal> proposals) throws CoreException {
	int nSimilarElements= similarElements.size();
	ITypeBinding[] argTypes= getArgumentTypes(arguments);
	if (argTypes == null || nSimilarElements == 0)  {
		return;
	}

	for (int i= 0; i < nSimilarElements; i++) {
		IMethodBinding elem = similarElements.get(i);
		int diff= elem.getParameterTypes().length - argTypes.length;
		if (diff == 0) {
			int nProposals= proposals.size();
			doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals);
			if (nProposals != proposals.size()) {
				return; // only suggest for one method (avoid duplicated proposals)
			}
		} else if (diff > 0) {
			doMoreParameters(context, invocationNode, argTypes, elem, proposals);
		} else {
			doMoreArguments(context, invocationNode, arguments, argTypes, elem, proposals);
		}
	}
}
 
Example 4
Source File: HashCodeEqualsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static String[] findExistingMethods(ITypeBinding typeBinding) {
	List<String> existingMethods = new ArrayList<>();
	IMethodBinding[] declaredMethods = typeBinding.getDeclaredMethods();
	for (IMethodBinding method : declaredMethods) {
		if (method.getName().equals(METHODNAME_EQUALS)) {
			ITypeBinding[] b = method.getParameterTypes();
			if ((b.length == 1) && (b[0].getQualifiedName().equals("java.lang.Object"))) {
				existingMethods.add(METHODNAME_EQUALS);
			}
		} else if (method.getName().equals(METHODNAME_HASH_CODE) && method.getParameterTypes().length == 0) {
			existingMethods.add(METHODNAME_HASH_CODE);
		}
		if (existingMethods.size() == 2) {
			break;
		}
	}
	return existingMethods.toArray(new String[0]);
}
 
Example 5
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static String[][] suggestArgumentNamesWithProposals(IJavaProject project, IMethodBinding binding) {
	int nParams= binding.getParameterTypes().length;
	if (nParams > 0) {
		try {
			IMethod method= (IMethod)binding.getMethodDeclaration().getJavaElement();
			if (method != null) {
				String[] parameterNames= method.getParameterNames();
				if (parameterNames.length == nParams) {
					return suggestArgumentNamesWithProposals(project, parameterNames);
				}
			}
		} catch (JavaModelException e) {
			// ignore
		}
	}
	String[][] names= new String[nParams][];
	for (int i= 0; i < names.length; i++) {
		names[i]= new String[] { "arg" + i }; //$NON-NLS-1$
	}
	return names;
}
 
Example 6
Source File: CallInliner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if the method can be called without explicit casts;
 * otherwise <code>false</code>.
 * @param candidate the method to test
 * @return <code>true</code> if the method can be called without explicit casts
 */
private boolean canImplicitlyCall(IMethodBinding candidate) {
	ITypeBinding[] parameters= candidate.getParameterTypes();
	if (parameters.length != fTypes.length) {
		return false;
	}
	for (int i= 0; i < parameters.length; i++) {
		if (!fTypes[i].canAssignTo(fTypeEnvironment.create(parameters[i]))) {
			return false;
		}
	}
	return true;
}
 
Example 7
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean areSubTypeCompatible(IMethodBinding overridden, IMethodBinding overridable) {

		if (overridden.getParameterTypes().length != overridable.getParameterTypes().length)
			return false;

		ITypeBinding overriddenReturn= overridden.getReturnType();
		ITypeBinding overridableReturn= overridable.getReturnType();
		if (overriddenReturn == null || overridableReturn == null)
			return false;

		if (!overriddenReturn.getErasure().isSubTypeCompatible(overridableReturn.getErasure()))
			return false;

		ITypeBinding[] overriddenTypes= overridden.getParameterTypes();
		ITypeBinding[] overridableTypes= overridable.getParameterTypes();
		Assert.isTrue(overriddenTypes.length == overridableTypes.length);
		for (int index= 0; index < overriddenTypes.length; index++) {
			final ITypeBinding overridableErasure= overridableTypes[index].getErasure();
			final ITypeBinding overriddenErasure= overriddenTypes[index].getErasure();
			if (!overridableErasure.isSubTypeCompatible(overriddenErasure) || !overridableErasure.getKey().equals(overriddenErasure.getKey()))
				return false;
		}
		ITypeBinding[] overriddenExceptions= overridden.getExceptionTypes();
		ITypeBinding[] overridableExceptions= overridable.getExceptionTypes();
		boolean checked= false;
		for (int index= 0; index < overriddenExceptions.length; index++) {
			checked= false;
			for (int offset= 0; offset < overridableExceptions.length; offset++) {
				if (overriddenExceptions[index].isSubTypeCompatible(overridableExceptions[offset]))
					checked= true;
			}
			if (!checked)
				return false;
		}
		return true;
	}
 
Example 8
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding getParameterTypeBinding(IMethodBinding methodBinding, int argumentIndex) {
	ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
	if (methodBinding.isVarargs() && argumentIndex >= paramTypes.length - 1) {
		return paramTypes[paramTypes.length - 1].getComponentType();
	}
	if (argumentIndex >= 0 && argumentIndex < paramTypes.length) {
		return paramTypes[argumentIndex];
	}
	return null;
}
 
Example 9
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Collection<ITypeConstraint> getConstraintsForOverriding(IMethodBinding overridingMethod) {
	Collection<ITypeConstraint> result= new ArrayList<ITypeConstraint>();
	Set<ITypeBinding> declaringSupertypes= getDeclaringSuperTypes(overridingMethod);
	for (Iterator<ITypeBinding> iter= declaringSupertypes.iterator(); iter.hasNext();) {
		ITypeBinding superType= iter.next();
		IMethodBinding overriddenMethod= findMethod(overridingMethod, superType);
		Assert.isNotNull(overriddenMethod);//because we asked for declaring types
		if (Bindings.equals(overridingMethod, overriddenMethod))
			continue;
		ITypeConstraint[] returnTypeConstraint= fTypeConstraintFactory.createEqualsConstraint(
				fConstraintVariableFactory.makeReturnTypeVariable(overriddenMethod),
				fConstraintVariableFactory.makeReturnTypeVariable(overridingMethod));
		result.addAll(Arrays.asList(returnTypeConstraint));
		Assert.isTrue(overriddenMethod.getParameterTypes().length == overridingMethod.getParameterTypes().length);
		for (int i= 0, n= overriddenMethod.getParameterTypes().length; i < n; i++) {
			ITypeConstraint[] parameterTypeConstraint= fTypeConstraintFactory.createEqualsConstraint(
					fConstraintVariableFactory.makeParameterTypeVariable(overriddenMethod, i),
					fConstraintVariableFactory.makeParameterTypeVariable(overridingMethod, i));
			result.addAll(Arrays.asList(parameterTypeConstraint));
		}
		ITypeConstraint[] declaringTypeConstraint= fTypeConstraintFactory.createStrictSubtypeConstraint(
				fConstraintVariableFactory.makeDeclaringTypeVariable(overridingMethod),
				fConstraintVariableFactory.makeDeclaringTypeVariable(overriddenMethod));
		result.addAll(Arrays.asList(declaringTypeConstraint));
	}
	return result;
}
 
Example 10
Source File: TypeURIHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public URI getFullURI(IMethodBinding binding) {
	StringBuilder uriBuilder = createURIBuilder();
	getFullURI(binding.getDeclaringClass(), uriBuilder);
	uriBuilder.append(".");
	uriBuilder.append(binding.getName());
	uriBuilder.append("(");
	ITypeBinding[] parameterTypes = binding.getParameterTypes();
	for (int i = 0; i < parameterTypes.length; i++) {
		if (i != 0)
			uriBuilder.append(',');
		uriBuilder.append(getQualifiedName(parameterTypes[i]));
	}
	uriBuilder.append(")");
	return createURI(uriBuilder);
}
 
Example 11
Source File: ParameterTypeVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ParameterTypeVariable(IMethodBinding methodBinding, int parameterIndex) {
	super(methodBinding.getParameterTypes()[parameterIndex]);
	Assert.isNotNull(methodBinding);
	Assert.isTrue(0 <= parameterIndex);
	Assert.isTrue(parameterIndex < methodBinding.getParameterTypes().length);
	fMethodBinding= methodBinding;
	fParameterIndex= parameterIndex;
}
 
Example 12
Source File: RemoteServiceUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Computes the synchronous method parameter types from the asynchronous
 * method binding.
 */
static String[] computeSyncParameterTypes(IMethodBinding asyncMethodBinding) {
  List<String> parameters = new ArrayList<String>();

  ITypeBinding[] parameterTypes = asyncMethodBinding.getParameterTypes();
  for (int i = 0; i < parameterTypes.length - 1; ++i) {
    parameters.add(parameterTypes[i].getErasure().getQualifiedName());
  }

  return parameters.toArray(NO_STRINGS);
}
 
Example 13
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean parameterTypesMatch(IMethodBinding m1, IMethodBinding m2) {
    ITypeBinding[] m1Params= m1.getParameterTypes();
    ITypeBinding[] m2Params= m2.getParameterTypes();
    if (m1Params.length != m2Params.length)
        return false;
    for (int i= 0; i < m2Params.length; i++) {
        if (!m1Params[i].equals(m2Params[i]))
            return false;
    }
    return true;
}
 
Example 14
Source File: SrcTreeGenerator.java    From sahagin-java with Apache License 2.0 5 votes vote down vote up
private List<String> getArgClassQualifiedNames(IMethodBinding method) {
    ITypeBinding[] paramTypes;
    if (method.isParameterizedMethod()) {
        // Use generic type to get argument class types
        // instead of the actual type resolved by JDT.
        IMethodBinding originalMethod = method.getMethodDeclaration();
        paramTypes = originalMethod.getParameterTypes();
    } else {
        paramTypes = method.getParameterTypes();
    }

    List<String> result = new ArrayList<>(paramTypes.length);
    for (ITypeBinding param : paramTypes) {
        // AdditionalTestDoc's argClassQualifiedNames are defined by type erasure.
        // TODO is this generic handling logic always work well??
        ITypeBinding erasure = param.getErasure();
        if (erasure.isPrimitive() || erasure.isArray()) {
            // "int", "boolean", etc
            result.add(erasure.getQualifiedName());
        } else {
            // getBinaryName and getQualifiedName are not the same.
            // For example, getBinaryName returns parent$child for inner class,
            // but getQualifiedName returns parent.child
            result.add(erasure.getBinaryName());
        }
    }
    return result;
}
 
Example 15
Source File: RemoteServiceProblemFactory.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
static String toAsyncMethodSignature(IMethodBinding syncMethod) {
  StringBuilder sb = new StringBuilder();
  sb.append(syncMethod.getName());
  sb.append("(");
  ITypeBinding[] parameterTypes = syncMethod.getParameterTypes();
  for (int i = 0; i < parameterTypes.length; ++i) {
    if (i != 0) {
      sb.append(", ");
    }

    sb.append(parameterTypes[i].getName());
  }

  if (parameterTypes.length > 0) {
    sb.append(", ");
  }

  sb.append("AsyncCallback<");
  ITypeBinding returnType = syncMethod.getReturnType();
  if (returnType.isPrimitive()) {
    sb.append(Signature.getSimpleName(JavaASTUtils.getWrapperTypeName(returnType.getName())));
  } else {
    sb.append(returnType.getName());
  }
  sb.append(">");
  sb.append(")");

  return sb.toString();
}
 
Example 16
Source File: ConstructorFromSuperclassProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
	String name= fTypeNode.getName().getIdentifier();
	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.setConstructor(true);
	decl.setName(ast.newSimpleName(name));
	Block body= ast.newBlock();
	decl.setBody(body);

	SuperConstructorInvocation invocation= null;

	List<SingleVariableDeclaration> parameters= decl.parameters();
	String[] paramNames= getArgumentNames(binding);

	ITypeBinding enclosingInstance= getEnclosingInstance();
	if (enclosingInstance != null) {
		invocation= addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
	}

	if (binding == null) {
		decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
	} else {
		decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));

		ITypeBinding[] params= binding.getParameterTypes();
		for (int i= 0; i < params.length; i++) {
			SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
			var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext));
			var.setName(ast.newSimpleName(paramNames[i]));
			parameters.add(var);
		}

		List<Type> thrownExceptions= decl.thrownExceptionTypes();
		ITypeBinding[] excTypes= binding.getExceptionTypes();
		for (int i= 0; i < excTypes.length; i++) {
			Type excType= getImportRewrite().addImport(excTypes[i], ast, importRewriteContext);
			thrownExceptions.add(excType);
		}

		if (invocation == null) {
			invocation= ast.newSuperConstructorInvocation();
		}

		List<Expression> arguments= invocation.arguments();
		for (int i= 0; i < paramNames.length; i++) {
			Name argument= ast.newSimpleName(paramNames[i]);
			arguments.add(argument);
			addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]); //$NON-NLS-1$
		}
	}

	String bodyStatement= (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true)); //$NON-NLS-1$
	String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
	if (placeHolder != null) {
		ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
		body.statements().add(todoNode);
	}
	if (commentSettings != null) {
		String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 17
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Name) {
		IBinding binding= ((Name) selectedNode).resolveBinding();
		if (binding instanceof IVariableBinding) {
			IVariableBinding variableBinding= (IVariableBinding) binding;
			if (variableBinding.isField()) {
				String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName();
				String fieldName= variableBinding.getName();
				String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName));
				if (methodName != null) {
					AST ast= selectedNode.getAST();
					ASTRewrite astRewrite= ASTRewrite.create(ast);
					ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true);

					MethodInvocation method= ast.newMethodInvocation();
					String qfn= importRewrite.addImport(methodName[0]);
					method.setExpression(ast.newName(qfn));
					method.setName(ast.newSimpleName(methodName[1]));
					ASTNode parent= selectedNode.getParent();
					ICompilationUnit cu= context.getCompilationUnit();
					// add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works):
					if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is18OrHigher(cu.getJavaProject())) {
						IMethodBinding methodBinding= Invocations.resolveBinding(parent);
						if (methodBinding != null) {
							ITypeBinding[] parameterTypes= methodBinding.getParameterTypes();
							int i= Invocations.getArguments(parent).indexOf(selectedNode);
							if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) {
								ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments();
								for (int j= 0; j < typeArguments.length; j++) {
									ITypeBinding typeArgument= typeArguments[j];
									typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
									if (! TypeRules.isJavaLangObject(typeArgument)) {
										// add all type arguments if at least one is found to be necessary:
										List<Type> typeArgumentsList= method.typeArguments();
										for (int k= 0; k < typeArguments.length; k++) {
											typeArgument= typeArguments[k];
											typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
											typeArgumentsList.add(importRewrite.addImport(typeArgument, ast));
										}
										break;
									}
								}
							}
						}
					}
					
					astRewrite.replace(selectedNode, method, null);

					String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(method)));
					Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
					ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image);
					proposal.setImportRewrite(importRewrite);
					proposals.add(proposal);
				}
			}
		}
	}
}
 
Example 18
Source File: ConstructorFromSuperclassProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
	String name= fTypeNode.getName().getIdentifier();
	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.setConstructor(true);
	decl.setName(ast.newSimpleName(name));
	Block body= ast.newBlock();
	decl.setBody(body);

	SuperConstructorInvocation invocation= null;

	List<SingleVariableDeclaration> parameters= decl.parameters();
	String[] paramNames= getArgumentNames(binding);

	ITypeBinding enclosingInstance= getEnclosingInstance();
	if (enclosingInstance != null) {
		invocation= addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
	}

	if (binding == null) {
		decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
	} else {
		decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));

		ITypeBinding[] params= binding.getParameterTypes();
		for (int i= 0; i < params.length; i++) {
			SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
			var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext, TypeLocation.LOCAL_VARIABLE));
			var.setName(ast.newSimpleName(paramNames[i]));
			parameters.add(var);
		}

		List<Type> thrownExceptions= decl.thrownExceptionTypes();
		ITypeBinding[] excTypes= binding.getExceptionTypes();
		for (int i= 0; i < excTypes.length; i++) {
			Type excType= getImportRewrite().addImport(excTypes[i], ast, importRewriteContext, TypeLocation.EXCEPTION);
			thrownExceptions.add(excType);
		}

		if (invocation == null) {
			invocation= ast.newSuperConstructorInvocation();
		}

		List<Expression> arguments= invocation.arguments();
		for (int i= 0; i < paramNames.length; i++) {
			Name argument= ast.newSimpleName(paramNames[i]);
			arguments.add(argument);
			addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]); //$NON-NLS-1$
		}
	}

	String bodyStatement = (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true)); //$NON-NLS-1$
	String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
	if (placeHolder != null) {
		ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
		body.statements().add(todoNode);
	}
	if (commentSettings != null) {
		String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 19
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @since 2.4
 */
protected void enhanceExecutable(StringBuilder fqn, String handleIdentifier, String[] path, JvmExecutable result, IMethodBinding method) {
	String name = method.getName();
	fqn.append(name);
	fqn.append('(');
	ITypeBinding[] parameterTypes = method.getParameterTypes();
	for (int i = 0; i < parameterTypes.length; i++) {
		if (i != 0)
			fqn.append(',');
		fqn.append(getQualifiedName(parameterTypes[i]));
	}
	fqn.append(')');
	result.internalSetIdentifier(fqn.toString());
	result.setSimpleName(name);
	setVisibility(result, method.getModifiers());
	result.setDeprecated(method.isDeprecated());
	if (parameterTypes.length > 0) {
		result.setVarArgs(method.isVarargs());
		String[] parameterNames = null;

		// If the method is derived from source, we can efficiently determine the parameter names now.
		//
		ITypeBinding declaringClass = method.getDeclaringClass();
		if (declaringClass.isFromSource()) {
			parameterNames = getParameterNamesFromSource(fqn, method);
		} else {
			// Use the key to determine the signature for the method.
			//
			SegmentSequence signaturex = getSignatureAsSegmentSequence(method);
			ParameterNameInitializer initializer = jdtCompliance.createParameterNameInitializer(method, workingCopyOwner, result, handleIdentifier, path, name, signaturex);
			((JvmExecutableImplCustom)result).setParameterNameInitializer(initializer);
		}

		setParameterNamesAndAnnotations(method, parameterTypes, parameterNames, result);
	}

	ITypeBinding[] exceptionTypes = method.getExceptionTypes();
	if (exceptionTypes.length > 0) {
		InternalEList<JvmTypeReference> exceptions = (InternalEList<JvmTypeReference>)result.getExceptions();
		for (ITypeBinding exceptionType : exceptionTypes) {
			exceptions.addUnique(createTypeReference(exceptionType));
		}
	}
}
 
Example 20
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean visit(ITypeBinding type) {
	IMethodBinding[] methods= type.getDeclaredMethods();
	for (int i= 0; i < methods.length; i++) {
		IMethodBinding candidate= methods[i];
		if (candidate.getMethodDeclaration() == fOriginalMethod.getMethodDeclaration()) {
			continue;
		}
		ITypeBinding candidateDeclaringType= candidate.getDeclaringClass();
		if (fDeclaringType != candidateDeclaringType) {
			int modifiers= candidate.getModifiers();
			if (candidateDeclaringType.isInterface() && Modifier.isStatic(modifiers)) {
				continue;
			}
			if (Modifier.isPrivate(modifiers)) {
				continue;
			}
		}
		if (fOriginalMethod.getName().equals(candidate.getName()) && !fOriginalMethod.overrides(candidate)) {
			ITypeBinding[] originalParameterTypes= fOriginalMethod.getParameterTypes();
			ITypeBinding[] candidateParameterTypes= candidate.getParameterTypes();
			
			boolean couldBeAmbiguous;
			if (originalParameterTypes.length == candidateParameterTypes.length) {
				couldBeAmbiguous= true;
			} else if (fOriginalMethod.isVarargs() || candidate.isVarargs() ) {
				int candidateMinArgumentCount= candidateParameterTypes.length;
				if (candidate.isVarargs())
					candidateMinArgumentCount--;
				couldBeAmbiguous= fArgumentCount >= candidateMinArgumentCount;
			} else {
				couldBeAmbiguous= false;
			}
			if (couldBeAmbiguous) {
				ITypeBinding parameterType= ASTResolving.getParameterTypeBinding(candidate, fArgIndex);
				if (parameterType != null && parameterType.getFunctionalInterfaceMethod() != null) {
					if (!fExpressionIsExplicitlyTyped) {
						/* According to JLS8 15.12.2.2, implicitly typed lambda expressions are not "pertinent to applicability"
						 * and hence potentially applicable methods are always "applicable by strict invocation",
						 * regardless of whether argument expressions are compatible with the method's parameter types or not.
						 * If there are multiple such methods, 15.12.2.5 results in an ambiguous method invocation.
						 */
						return false;
					}
					/* Explicitly typed lambda expressions are pertinent to applicability, and hence
					 * compatibility with the corresponding method parameter type is checked. And since this check
					 * separates functional interface methods by their void-compatibility state, functional interfaces
					 * with a different void compatibility are not applicable any more and hence can't cause
					 * an ambiguous method invocation.
					 */
					ITypeBinding origParamType= ASTResolving.getParameterTypeBinding(fOriginalMethod, fArgIndex);
					boolean originalIsVoidCompatible=  Bindings.isVoidType(origParamType.getFunctionalInterfaceMethod().getReturnType());
					boolean candidateIsVoidCompatible= Bindings.isVoidType(parameterType.getFunctionalInterfaceMethod().getReturnType());
					if (originalIsVoidCompatible == candidateIsVoidCompatible) {
						return false;
					}
				}
			}
		}
	}
	return true;
}