org.eclipse.jdt.core.dom.IMethodBinding Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.IMethodBinding. 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: MethodCallAnalyzer.java    From JDeodorant with MIT License 6 votes vote down vote up
public static boolean equalSignature(IMethodBinding methodBinding1, IMethodBinding methodBinding2) {
	if(!methodBinding1.getName().equals(methodBinding2.getName()))
		return false;
	ITypeBinding returnType1 = methodBinding1.getReturnType();
	ITypeBinding returnType2 = methodBinding2.getReturnType();
	if(!equalType(returnType1, returnType2))
		return false;
	ITypeBinding[] parameterTypes1 = methodBinding1.getParameterTypes();
	ITypeBinding[] parameterTypes2 = methodBinding2.getParameterTypes();
	if(parameterTypes1.length == parameterTypes2.length) {
		int i = 0;
		for(ITypeBinding typeBinding1 : parameterTypes1) {
			ITypeBinding typeBinding2 = parameterTypes2[i];
			if(!equalType(typeBinding1, typeBinding2))
				return false;
			i++;
		}
	}
	else return false;
	return true;
}
 
Example #2
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String asString(IMethodBinding method) {
	StringBuffer result= new StringBuffer();
	result.append(method.getDeclaringClass().getName());
	result.append(':');
	result.append(method.getName());
	result.append('(');
	ITypeBinding[] parameters= method.getParameterTypes();
	int lastComma= parameters.length - 1;
	for (int i= 0; i < parameters.length; i++) {
		ITypeBinding parameter= parameters[i];
		result.append(parameter.getName());
		if (i < lastComma)
			result.append(", "); //$NON-NLS-1$
	}
	result.append(')');
	return result.toString();
}
 
Example #3
Source File: NullAnnotationsRewriteOperations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static CompilationUnit findCUForMethod(CompilationUnit compilationUnit, ICompilationUnit cu, IMethodBinding methodBinding) {
	ASTNode methodDecl= compilationUnit.findDeclaringNode(methodBinding.getMethodDeclaration());
	if (methodDecl == null) {
		// is methodDecl defined in another CU?
		ITypeBinding declaringTypeDecl= methodBinding.getDeclaringClass().getTypeDeclaration();
		if (declaringTypeDecl.isFromSource()) {
			ICompilationUnit targetCU= null;
			try {
				targetCU= ASTResolving.findCompilationUnitForBinding(cu, compilationUnit, declaringTypeDecl);
			} catch (JavaModelException e) { /* can't do better */
			}
			if (targetCU != null) {
				return ASTResolving.createQuickFixAST(targetCU, null);
			}
		}
		return null;
	}
	return compilationUnit;
}
 
Example #4
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 6 votes vote down vote up
private ExpressionStatement convert(
    org.eclipse.jdt.core.dom.SuperConstructorInvocation expression) {
  IMethodBinding superConstructorBinding = expression.resolveConstructorBinding();
  MethodDescriptor methodDescriptor = JdtUtils.createMethodDescriptor(superConstructorBinding);
  List<Expression> arguments =
      convertArguments(superConstructorBinding, JdtUtils.asTypedList(expression.arguments()));
  Expression qualifier = convertOrNull(expression.getExpression());
  // super() call to an inner class without explicit qualifier, find the enclosing instance.
  DeclaredTypeDescriptor targetTypeDescriptor = methodDescriptor.getEnclosingTypeDescriptor();
  if (qualifier == null
      && targetTypeDescriptor.getTypeDeclaration().isCapturingEnclosingInstance()) {
    qualifier =
        resolveImplicitOuterClassReference(targetTypeDescriptor.getEnclosingTypeDescriptor());
  }
  return MethodCall.Builder.from(methodDescriptor)
      .setQualifier(qualifier)
      .setArguments(arguments)
      .setSourcePosition(getSourcePosition(expression))
      .build()
      .makeStatement(getSourcePosition(expression));
}
 
Example #5
Source File: PreconditionExaminer.java    From JDeodorant with MIT License 6 votes vote down vote up
private Set<IMethodBinding> getDeclaredMethods(ITypeBinding typeBinding) {
	Set<IMethodBinding> declaredMethods = new LinkedHashSet<IMethodBinding>();
	//first add the directly declared methods
	for(IMethodBinding methodBinding : typeBinding.getDeclaredMethods()) {
		declaredMethods.add(methodBinding);
	}
	ITypeBinding superclassTypeBinding = typeBinding.getSuperclass();
	if(superclassTypeBinding != null) {
		declaredMethods.addAll(getDeclaredMethods(superclassTypeBinding));
	}
	ITypeBinding[] interfaces = typeBinding.getInterfaces();
	for(ITypeBinding interfaceTypeBinding : interfaces) {
		declaredMethods.addAll(getDeclaredMethods(interfaceTypeBinding));
	}
	return declaredMethods;
}
 
Example #6
Source File: JdtTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private boolean isParameterNamesAvailable() throws Exception {
	ASTParser parser = ASTParser.newParser(AST.JLS3);
	parser.setIgnoreMethodBodies(true);
	IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
	parser.setProject(javaProject);
	IType type = javaProject.findType("org.eclipse.xtext.common.types.testSetups.TestEnum");
	IBinding[] bindings = parser.createBindings(new IJavaElement[] { type }, null);
	ITypeBinding typeBinding = (ITypeBinding) bindings[0];
	IMethodBinding[] methods = typeBinding.getDeclaredMethods();
	for(IMethodBinding method: methods) {
		if (method.isConstructor()) {
			IMethod element = (IMethod) method.getJavaElement();
			if (element.exists()) {
				String[] parameterNames = element.getParameterNames();
				if (parameterNames.length == 1 && parameterNames[0].equals("string")) {
					return true;
				}
			} else {
				return false;
			}
		}
	}
	return false;
}
 
Example #7
Source File: AddCustomConstructorOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new add custom constructor operation.
 *
 * @param astRoot the compilation unit ast node
 * @param parentType the type to add the methods to
 * 	@param variables the variable bindings to use in the constructor
 * @param constructor the method binding of the super constructor
 * @param insert the insertion point, or <code>null</code>


 * @param settings the code generation settings to use
 * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
 * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
 */
public AddCustomConstructorOperation(CompilationUnit astRoot, ITypeBinding parentType, IVariableBinding[] variables, IMethodBinding constructor, IJavaElement insert, CodeGenerationSettings settings, boolean apply, boolean save) {
	Assert.isTrue(astRoot != null && astRoot.getTypeRoot() instanceof ICompilationUnit);
	Assert.isNotNull(parentType);
	Assert.isNotNull(variables);
	Assert.isNotNull(constructor);
	Assert.isNotNull(settings);
	fParentType= parentType;
	fInsert= insert;
	fASTRoot= astRoot;
	fFieldBindings= variables;
	fConstructorBinding= constructor;
	fSettings= settings;
	fSave= save;
	fApply= apply;
}
 
Example #8
Source File: ReplaceInvocationsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
	// TODO: update for fSelectionStart == -1
	final Map<String, String> arguments= new HashMap<String, String>();
	String project= null;
	IJavaProject javaProject= fSelectionTypeRoot.getJavaProject();
	if (javaProject != null)
		project= javaProject.getElementName();
	final IMethodBinding binding= fSourceProvider.getDeclaration().resolveBinding();
	int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
	if (!Modifier.isPrivate(binding.getModifiers()))
		flags|= RefactoringDescriptor.MULTI_CHANGE;
	final String description= Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(binding.getName()));
	final String header= Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(binding.getDeclaringClass(), JavaElementLabels.ALL_FULLY_QUALIFIED)});
	final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
	comment.addSetting(Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)));
	if (!fTargetProvider.isSingle())
		comment.addSetting(RefactoringCoreMessages.ReplaceInvocationsRefactoring_replace_references);
	final JavaRefactoringDescriptor descriptor= new JavaRefactoringDescriptor(ID_REPLACE_INVOCATIONS, project, description, comment.asString(), arguments, flags){}; //REVIEW Unregistered ID!
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fSelectionTypeRoot));
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
	arguments.put(ATTRIBUTE_MODE, new Integer(fTargetProvider.isSingle() ? 0 : 1).toString());
	return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.ReplaceInvocationsRefactoring_change_name, fChangeManager.getAllChanges());
}
 
Example #9
Source File: APIMethodData.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
public void initByIMethodBinding(IMethodBinding mBinding) {
	IMethod iMethod = (IMethod) mBinding.getJavaElement();
	try {
		key = iMethod.getKey().substring(0, iMethod.getKey().indexOf("("))
				+ iMethod.getSignature();
		projectName = mBinding.getJavaElement().getJavaProject()
				.getElementName();
	} catch (Exception e) {
		projectName = "";
	}
	packageName = mBinding.getDeclaringClass().getPackage().getName();
	className = mBinding.getDeclaringClass().getName();
	name = mBinding.getName();

	parameters = new ArrayList<>();
	ITypeBinding[] parameterBindings = mBinding.getParameterTypes();
	for (int i = 0; i < parameterBindings.length; i++) {
		parameters.add(parameterBindings[i].getName());
	}
}
 
Example #10
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 6 votes vote down vote up
private Expression convert(org.eclipse.jdt.core.dom.MethodInvocation methodInvocation) {

      Expression qualifier = getExplicitQualifier(methodInvocation);

      IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
      MethodDescriptor methodDescriptor = JdtUtils.createMethodDescriptor(methodBinding);
      List<Expression> arguments =
          convertArguments(methodBinding, JdtUtils.asTypedList(methodInvocation.arguments()));
      MethodCall methodCall =
          MethodCall.Builder.from(methodDescriptor)
              .setQualifier(qualifier)
              .setArguments(arguments)
              .setSourcePosition(getSourcePosition(methodInvocation))
              .build();
      if (JdtUtils.hasUncheckedCastAnnotation(methodBinding)) {
        // Annotate the invocation with the expected type. When InsertErasureSureTypeSafetyCasts
        // runs, this invocation will be skipped as it will no longer be an assignment context.
        return JsDocCastExpression.newBuilder()
            .setExpression(methodCall)
            .setCastType(methodDescriptor.getReturnTypeDescriptor())
            .build();
      }
      return methodCall;
    }
 
Example #11
Source File: RefactoringUtility.java    From JDeodorant with MIT License 6 votes vote down vote up
public static TypeDeclaration findDeclaringTypeDeclaration(IMethodBinding methodBinding, TypeDeclaration typeDeclaration) {
	if(typeDeclaration.resolveBinding().isEqualTo(methodBinding.getDeclaringClass())) {
		return typeDeclaration;
	}
	//method was not found in typeDeclaration
	Type superclassType = typeDeclaration.getSuperclassType();
	if(superclassType != null) {
		String superclassQualifiedName = superclassType.resolveBinding().getQualifiedName();
		SystemObject system = ASTReader.getSystemObject();
		ClassObject superclassObject = system.getClassObject(superclassQualifiedName);
		if(superclassObject != null) {
			AbstractTypeDeclaration superclassTypeDeclaration = superclassObject.getAbstractTypeDeclaration();
			if(superclassTypeDeclaration instanceof TypeDeclaration) {
				return findDeclaringTypeDeclaration(methodBinding, (TypeDeclaration)superclassTypeDeclaration);
			}
		}
	}
	return null;
}
 
Example #12
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void setParameterNamesAndAnnotations(IMethodBinding method, ITypeBinding[] parameterTypes,
		String[] parameterNames, JvmExecutable result) {
	InternalEList<JvmFormalParameter> parameters = (InternalEList<JvmFormalParameter>)result.getParameters();
	for (int i = 0; i < parameterTypes.length; i++) {
		IAnnotationBinding[] parameterAnnotations;
		try {
			parameterAnnotations = method.getParameterAnnotations(i);
		} catch(AbortCompilation aborted) {
			parameterAnnotations = null;
		}
		ITypeBinding parameterType = parameterTypes[i];
		String parameterName = parameterNames == null ? null /* lazy */ : i < parameterNames.length ? parameterNames[i] : "arg" + i;
		JvmFormalParameter formalParameter = createFormalParameter(parameterType, parameterName, parameterAnnotations);
		parameters.addUnique(formalParameter);
	}
}
 
Example #13
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	CompilationUnit compilationUnit= cuRewrite.getRoot();
	importType(fDeclaringClass, fName, cuRewrite.getImportRewrite(), compilationUnit);
	TextEditGroup group;
	if (fName.resolveBinding() instanceof IMethodBinding) {
		group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyMethodWithDeclClass_description, cuRewrite);
	} else {
		group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyFieldWithDeclClass_description, cuRewrite);
	}
	IJavaElement javaElement= fDeclaringClass.getJavaElement();
	if (javaElement instanceof IType) {
		Name qualifierName= compilationUnit.getAST().newName(((IType)javaElement).getElementName());
		SimpleName simpleName= (SimpleName)rewrite.createMoveTarget(fName);
		QualifiedName qualifiedName= compilationUnit.getAST().newQualifiedName(qualifierName, simpleName);
		rewrite.replace(fName, qualifiedName, group);
	}
}
 
Example #14
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static boolean isMoveStaticMemberAvailable(ASTNode declaration) throws JavaModelException {
	if (declaration instanceof MethodDeclaration) {
		IMethodBinding method = ((MethodDeclaration) declaration).resolveBinding();
		return method != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IMember) method.getJavaElement());
	} else if (declaration instanceof FieldDeclaration) {
		List<IMember> members = new ArrayList<>();
		for (Object fragment : ((FieldDeclaration) declaration).fragments()) {
			IVariableBinding variable = ((VariableDeclarationFragment) fragment).resolveBinding();
			if (variable != null) {
				members.add((IField) variable.getJavaElement());
			}
		}
		return RefactoringAvailabilityTesterCore.isMoveStaticMembersAvailable(members.toArray(new IMember[0]));
	} else if (declaration instanceof AbstractTypeDeclaration) {
		ITypeBinding type = ((AbstractTypeDeclaration) declaration).resolveBinding();
		return type != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IType) type.getJavaElement());
	}

	return false;
}
 
Example #15
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void createTypeParameters(ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) {
	ITypeBinding[] typeParams= binding.getTypeParameters();
	List<TypeParameter> typeParameters= decl.typeParameters();
	for (int i= 0; i < typeParams.length; i++) {
		ITypeBinding curr= typeParams[i];
		TypeParameter newTypeParam= ast.newTypeParameter();
		newTypeParam.setName(ast.newSimpleName(curr.getName()));
		ITypeBinding[] typeBounds= curr.getTypeBounds();
		if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$
			List<Type> newTypeBounds= newTypeParam.typeBounds();
			for (int k= 0; k < typeBounds.length; k++) {
				newTypeBounds.add(imports.addImport(typeBounds[k], ast, context));
			}
		}
		typeParameters.add(newTypeParam);
	}
}
 
Example #16
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 #17
Source File: AddUnimplementedConstructorsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new add unimplemented constructors operation.
 *
 * @param astRoot the compilation unit AST node
 * @param type the type to add the methods to
 * @param constructorsToImplement the method binding keys to implement
 * @param insertPos the insertion point, or <code>-1</code>
 * @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise
 * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
 * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
 */
public AddUnimplementedConstructorsOperation(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] constructorsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) {
	if (astRoot == null || !(astRoot.getJavaElement() instanceof ICompilationUnit)) {
		throw new IllegalArgumentException("AST must not be null and has to be created from a ICompilationUnit"); //$NON-NLS-1$
	}
	if (type == null) {
		throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$
	}
	ASTNode node= astRoot.findDeclaringNode(type);
	if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) {
		throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$
	}

	fType= type;
	fInsertPos= insertPos;
	fASTRoot= astRoot;
	fConstructorsToImplement= constructorsToImplement;
	fSave= save;
	fApply= apply;
	fImports= imports;

	fCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaProject());
	fVisibility= Modifier.PUBLIC;
	fOmitSuper= false;
}
 
Example #18
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new return type variable.
 *
 * @param method the method binding
 * @return the created return type variable, or <code>null</code>
 */
public final ConstraintVariable2 createReturnTypeVariable(final IMethodBinding method) {
	if (!method.isConstructor()) {
		ITypeBinding binding= method.getReturnType();
		if (binding != null && binding.isArray())
			binding= binding.getElementType();
		if (binding != null && isConstrainedType(binding)) {
			ConstraintVariable2 variable= null;
			final TType type= createTType(binding);
			if (method.getDeclaringClass().isFromSource())
				variable= new ReturnTypeVariable2(type, method);
			else
				variable= new ImmutableTypeVariable2(type);
			return fConstraintVariables.addExisting(variable);
		}
	}
	return null;
}
 
Example #19
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean checkOverriddenBinaryMethods() {
	if (fMethodBinding != null){
		Set<ITypeBinding> declaringSupertypes= getDeclaringSuperTypes(fMethodBinding);
		for (Iterator<ITypeBinding> iter= declaringSupertypes.iterator(); iter.hasNext();) {
			ITypeBinding superType= iter.next();
			IMethodBinding overriddenMethod= findMethod(fMethodBinding, superType);
			Assert.isNotNull(overriddenMethod);//because we asked for declaring types
			IMethod iMethod= (IMethod) overriddenMethod.getJavaElement();
			if (iMethod.isBinary()){
				return true;
			}
		}
	}
	return false;
}
 
Example #20
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private SegmentSequence getSignatureAsSegmentSequence(IMethodBinding method) {
	String key = method.getKey();
	int start = key.indexOf('(');
	int end = key.lastIndexOf(')');
	SegmentSequence signaturex = SegmentSequence.create(";", key.substring(start + 1, end));
	return signaturex;
}
 
Example #21
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 5 votes vote down vote up
private AnnotationTypeAttribute ensureAnnotationTypeAttributeFromBinding(IMethodBinding binding) {
	ITypeBinding parentTypeBinding = binding.getDeclaringClass();
	if (parentTypeBinding == null) {
		return null;
	}
	AnnotationType annotationType = (AnnotationType) ensureTypeFromTypeBinding(parentTypeBinding);
	AnnotationTypeAttribute attribute = ensureAnnotationTypeAttribute(annotationType, binding.getName());
	ITypeBinding returnType = binding.getReturnType();
	if ((returnType != null) && !(returnType.isPrimitive() && returnType.getName().equals("void"))) {
		// we do not want to set void as a return type
		attribute.setDeclaredType(ensureTypeFromTypeBinding(returnType));
	}
	return attribute;
}
 
Example #22
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ITypeConstraint[] create(ConstructorInvocation invocation){
	List<Expression> arguments= invocation.arguments();
	List<ITypeConstraint> result= new ArrayList<ITypeConstraint>(arguments.size());
	IMethodBinding methodBinding= invocation.resolveConstructorBinding();
	result.addAll(Arrays.asList(getArgumentConstraints(arguments, methodBinding)));
	return result.toArray(new ITypeConstraint[result.size()]);
}
 
Example #23
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether a method with the given name and parameter types
 * is a subsignature of the given method binding.
 * 
 * @param method a method
 * @param methodName method name to match
 * @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 <code>true</code> iff the method
 * 		m1 (with name <code>methodName</code> and method parameters <code>parameters</code>)
 * 		is a subsignature of the method <code>m2</code>. Accessibility and return types are not taken into account.
 */
public static boolean isEqualMethod(IMethodBinding method, String methodName, String[] parameters) {
	if (!method.getName().equals(methodName))
		return false;

	ITypeBinding[] methodParameters= method.getParameterTypes();
	if (methodParameters.length != parameters.length)
		return false;
	String first, second;
	int index;
	for (int i= 0; i < parameters.length; i++) {
		first= parameters[i];
		index= first.indexOf('<');
		if (index > 0){
			int lastIndex= first.lastIndexOf('>');
			StringBuffer buf= new StringBuffer();
			buf.append(first.substring(0, index));
			if (lastIndex < first.length() - 1)
				buf.append(first.substring(lastIndex + 1, first.length()));
			first= buf.toString();
		}
		second= methodParameters[i].getQualifiedName();
		if (!first.equals(second)) {
			second= methodParameters[i].getErasure().getQualifiedName();
			if (!first.equals(second))
				return false;
		}
	}
	return true;
}
 
Example #24
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ITypeConstraint[] create(MethodDeclaration declaration){
	List<ITypeConstraint> result= new ArrayList<ITypeConstraint>();
	IMethodBinding methodBinding= declaration.resolveBinding();
	if (methodBinding == null)
		return new ITypeConstraint[0];
	ITypeConstraint[] constraints = fTypeConstraintFactory.createDefinesConstraint(
			fConstraintVariableFactory.makeDeclaringTypeVariable(methodBinding),
			fConstraintVariableFactory.makeRawBindingVariable(methodBinding.getDeclaringClass()));
	result.addAll(Arrays.asList(constraints));
	if (! methodBinding.isConstructor() && ! methodBinding.getReturnType().isPrimitive()){
		ConstraintVariable returnTypeBindingVariable= fConstraintVariableFactory.makeReturnTypeVariable(methodBinding);
		ConstraintVariable returnTypeVariable= fConstraintVariableFactory.makeTypeVariable(declaration.getReturnType2());
		ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
				returnTypeBindingVariable, returnTypeVariable);
		result.addAll(Arrays.asList(defines));
	}
	for (int i= 0, n= declaration.parameters().size(); i < n; i++) {
		SingleVariableDeclaration paramDecl= (SingleVariableDeclaration)declaration.parameters().get(i);
		ConstraintVariable parameterTypeVariable= fConstraintVariableFactory.makeParameterTypeVariable(methodBinding, i);
		ConstraintVariable parameterNameVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(paramDecl.getName(), getContext());
		ITypeConstraint[] constraint= fTypeConstraintFactory.createDefinesConstraint(
				parameterTypeVariable, parameterNameVariable);
		result.addAll(Arrays.asList(constraint));
	}
	if (MethodChecks.isVirtual(methodBinding)){
		Collection<ITypeConstraint> constraintsForOverriding = getConstraintsForOverriding(methodBinding);
		result.addAll(constraintsForOverriding);
	}
	return result.toArray(new ITypeConstraint[result.size()]);
}
 
Example #25
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void checkName(RefactoringStatus status, String name, List<IMethodBinding> usedNames, IType type, boolean reUseExistingField, IField field) {
	if ("".equals(name)) { //$NON-NLS-1$
		status.addFatalError(RefactoringCoreMessages.Checks_Choose_name);
		return;
	}
	boolean isStatic = false;
	try {
		isStatic = Flags.isStatic(field.getFlags());
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.log(e);
	}
	status.merge(Checks.checkMethodName(name, field));
	for (Iterator<IMethodBinding> iter = usedNames.iterator(); iter.hasNext();) {
		IMethodBinding method = iter.next();
		String selector = method.getName();
		if (selector.equals(name)) {
			if (!reUseExistingField) {
				status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_method_exists,
						new String[] { BindingLabelProviderCore.getBindingLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED), BasicElementLabels.getJavaElementName(type.getElementName()) }));
			} else {
				boolean methodIsStatic = Modifier.isStatic(method.getModifiers());
				if (methodIsStatic && !isStatic) {
					status.addWarning(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_static_method_but_nonstatic_field,
							new String[] { BasicElementLabels.getJavaElementName(method.getName()), BasicElementLabels.getJavaElementName(field.getElementName()) }));
				}
				if (!methodIsStatic && isStatic) {
					status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_nonstatic_method_but_static_field, new String[] { BasicElementLabels.getJavaElementName(method.getName()), BasicElementLabels.getJavaElementName(field.getElementName()) }));
				}
				return;
			}

		}
	}
	if (reUseExistingField) {
		status.addFatalError(Messages.format(
			RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_methoddoesnotexist_status_fatalError,
			new String[] { BasicElementLabels.getJavaElementName(name), BasicElementLabels.getJavaElementName(type.getElementName())}));
	}
}
 
Example #26
Source File: ConstantChecks.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isMemberReferenceValidInClassInitialization(Name name) {
	IBinding binding = name.resolveBinding();
	Assert.isTrue(binding instanceof IVariableBinding || binding instanceof IMethodBinding);

	if (name instanceof SimpleName) {
		return Modifier.isStatic(binding.getModifiers());
	} else {
		Assert.isTrue(name instanceof QualifiedName);
		return checkName(((QualifiedName) name).getQualifier());
	}
}
 
Example #27
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IBinding resolveSuperclassConstructor(ITypeBinding superClassDeclaration, IMethodBinding constructor) {
	IMethodBinding[] methods= superClassDeclaration.getDeclaredMethods();
	for (int i= 0; i < methods.length; i++) {
		IMethodBinding method= methods[i];
		if (method.isConstructor() && constructor.isSubsignature(method))
			return method;
	}
	return null;
}
 
Example #28
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isStaticAccess(SimpleName memberName) {
	IBinding binding= memberName.resolveBinding();
	Assert.isTrue(binding instanceof IVariableBinding || binding instanceof IMethodBinding || binding instanceof ITypeBinding);

	if (binding instanceof ITypeBinding)
		return true;

	if (binding instanceof IVariableBinding)
		return ((IVariableBinding) binding).isField();

	int modifiers= binding.getModifiers();
	return Modifier.isStatic(modifiers);
}
 
Example #29
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 #30
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private Expression convertAnonymousClassCreation(
    org.eclipse.jdt.core.dom.ClassInstanceCreation expression) {
  IMethodBinding constructorBinding = expression.resolveConstructorBinding();

  List<Expression> arguments =
      convertArguments(constructorBinding, JdtUtils.asTypedList(expression.arguments()));
  if (expression.getExpression() != null) {
    // Add the explicit super constructor as the first parameter.
    arguments.add(0, convert(expression.getExpression()));
  }

  MethodDescriptor constructorDescriptor =
      convertAnonymousClassDeclaration(
          checkNotNull(expression.getAnonymousClassDeclaration()),
          constructorBinding,
          expression.getExpression() == null
              ? null
              : JdtUtils.createTypeDescriptor(expression.getExpression().resolveTypeBinding()));

  // the qualifier for the NewInstance.
  DeclaredTypeDescriptor anonymousClassTypeDescriptor =
      constructorDescriptor.getEnclosingTypeDescriptor();
  Expression newInstanceQualifier =
      anonymousClassTypeDescriptor.getTypeDeclaration().isCapturingEnclosingInstance()
          ? resolveImplicitOuterClassReference(
              anonymousClassTypeDescriptor.getEnclosingTypeDescriptor())
          : null;
  return NewInstance.Builder.from(constructorDescriptor)
      .setQualifier(newInstanceQualifier)
      .setArguments(arguments)
      .build();
}