Java Code Examples for org.eclipse.jdt.internal.corext.dom.Bindings#findMethodInHierarchy()

The following examples show how to use org.eclipse.jdt.internal.corext.dom.Bindings#findMethodInHierarchy() . 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: SynchronousInterfaceValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected List<CategorizedProblem> doValidateMethodOnDependentInterface(
    IMethodBinding dependentMethodBinding, TypeDeclaration changedInterface,
    ITypeBinding dependentTypeBinding) {
  String[] parameters = RemoteServiceUtilities.computeSyncParameterTypes(dependentMethodBinding);
  if (Bindings.findMethodInHierarchy(changedInterface.resolveBinding(),
      dependentMethodBinding.getName(), parameters) == null) {
    CategorizedProblem problem1 = RemoteServiceProblemFactory.newMissingSyncMethodOnSync(
        changedInterface, dependentMethodBinding);
    if (problem1 != null) {
      return Collections.singletonList(problem1);
    }
  }

  return Collections.emptyList();
}
 
Example 2
Source File: AsynchronousInterfaceValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected List<CategorizedProblem> doValidateMethodOnDependentInterface(
    IMethodBinding methodBinding, TypeDeclaration changedInterface,
    ITypeBinding dependentInterfaceBinding) {
  String[] parameters = RemoteServiceUtilities.computeAsyncParameterTypes(methodBinding);
  String methodName = methodBinding.getName();
  if (Bindings.findMethodInHierarchy(changedInterface.resolveBinding(),
      methodName, parameters) == null) {
    CategorizedProblem problem = RemoteServiceProblemFactory.newMissingAsyncMethodOnAsync(
        methodBinding, changedInterface);
    if (problem != null) {
      return Collections.singletonList(problem);
    }
  }

  return Collections.emptyList();
}
 
Example 3
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates the initializer for an iterator based <code>for</code> loop, which declares and
 * initializes the variable to loop over.
 * 
 * @param rewrite the instance of {@link ASTRewrite}
 * @param loopVariableName the proposed name of the loop variable
 * @return a {@link VariableDeclarationExpression} to use as initializer
 */
private VariableDeclarationExpression getIteratorBasedForInitializer(ASTRewrite rewrite, SimpleName loopVariableName) {
	AST ast= rewrite.getAST();
	IMethodBinding iteratorMethodBinding= Bindings.findMethodInHierarchy(fExpressionType, "iterator", new ITypeBinding[] {}); //$NON-NLS-1$
	// initializing fragment
	VariableDeclarationFragment varDeclarationFragment= ast.newVariableDeclarationFragment();
	varDeclarationFragment.setName(loopVariableName);
	MethodInvocation iteratorExpression= ast.newMethodInvocation();
	iteratorExpression.setName(ast.newSimpleName(iteratorMethodBinding.getName()));
	iteratorExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
	varDeclarationFragment.setInitializer(iteratorExpression);

	// declaration
	VariableDeclarationExpression varDeclarationExpression= ast.newVariableDeclarationExpression(varDeclarationFragment);
	varDeclarationExpression.setType(getImportRewrite().addImport(iteratorMethodBinding.getReturnType(), ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));

	return varDeclarationExpression;
}
 
Example 4
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection<ICommandAccess> proposals) {
	ITypeBinding castType= expression.getType().resolveBinding();
	if (castType == null) {
		return false;
	}
	if (paramTypes != null) {
		if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
			return false;
		}
	} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
		return false;
	}
	ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
	if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
		return false;
	}

	IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
	if (res != null) {
		AST ast= expression.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);
		CastExpression newCast= ast.newCastExpression();
		newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
		newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
		ParenthesizedExpression parents= ast.newParenthesizedExpression();
		parents.setExpression(newCast);

		ASTNode node= rewrite.createCopyTarget(expression.getExpression());
		rewrite.replace(expression, node, null);
		rewrite.replace(accessExpression, parents, null);

		String label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_PARENTHESES_AROUND_CAST, image);
		proposals.add(proposal);
		return true;
	}
	return false;
}
 
Example 5
Source File: GetterSetterCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Proposes a setter for this field.
 * 
 * @param context the proposal parameter
 * @param relevance relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addSetterProposal(ProposalParameter context, int relevance) {
	boolean isBoolean= isBoolean(context);
	String setterName= GetterSetterUtil.getSetterName(context.variableBinding, context.compilationUnit.getJavaProject(), null, isBoolean);
	ITypeBinding declaringType= context.variableBinding.getDeclaringClass();
	if (declaringType == null)
		return null;

	IMethodBinding method= Bindings.findMethodInHierarchy(declaringType, setterName, new ITypeBinding[] { context.variableBinding.getType() });
	if (method != null && Bindings.isVoidType(method.getReturnType()) && (Modifier.isStatic(method.getModifiers()) == Modifier.isStatic(context.variableBinding.getModifiers()))) {
		Expression assignedValue= getAssignedValue(context);
		if (assignedValue == null)
			return null; //we don't know how to handle those cases.
		Expression mi= createMethodInvocation(context, method, assignedValue);
		context.astRewrite.replace(context.accessNode.getParent(), mi, null);

		String label= Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithsetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.compilationUnit, context.astRewrite, relevance, image);
		return proposal;
	} else {
		IJavaElement element= context.variableBinding.getJavaElement();
		if (element instanceof IField) {
			IField field= (IField) element;
			try {
				if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field))
					return new SelfEncapsulateFieldProposal(relevance, field);
			} catch (JavaModelException e) {
				JavaPlugin.log(e);
			}
		}
	}
	return null;
}
 
Example 6
Source File: GetterSetterCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IMethodBinding findGetter(ProposalParameter context) {
	ITypeBinding returnType= context.variableBinding.getType();
	String getterName= GetterSetterUtil.getGetterName(context.variableBinding, context.compilationUnit.getJavaProject(), null, isBoolean(context));
	ITypeBinding declaringType= context.variableBinding.getDeclaringClass();
	if (declaringType == null)
		return null;
	IMethodBinding getter= Bindings.findMethodInHierarchy(declaringType, getterName, new ITypeBinding[0]);
	if (getter != null && getter.getReturnType().isAssignmentCompatible(returnType) && Modifier.isStatic(getter.getModifiers()) == Modifier.isStatic(context.variableBinding.getModifiers()))
		return getter;
	return null;
}
 
Example 7
Source File: ExceptionOccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void handleResourceDeclarations(TryStatement tryStatement) {
	List<VariableDeclarationExpression> resources= tryStatement.resources();
	for (Iterator<VariableDeclarationExpression> iterator= resources.iterator(); iterator.hasNext();) {
		iterator.next().accept(this);
	}

	//check if the exception is thrown as a result of resource#close()
	boolean exitMarked= false;
	for (VariableDeclarationExpression variable : resources) {
		Type type= variable.getType();
		IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$
		if (methodBinding != null) {
			ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes();
			for (int j= 0; j < exceptionTypes.length; j++) {
				if (matches(exceptionTypes[j])) { // a close() throws the caught exception
					// mark name of resource
					for (VariableDeclarationFragment fragment : (List<VariableDeclarationFragment>) variable.fragments()) {
						SimpleName name= fragment.getName();
						fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription));
					}
					if (!exitMarked) {
						// mark exit position
						exitMarked= true;
						Block body= tryStatement.getBody();
						int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block
						fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.ExceptionOccurrencesFinder_occurrence_implicit_close_description,
								BasicElementLabels.getJavaElementName(fException.getName()))));
					}
				}
			}
		}
	}
}
 
Example 8
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean needsNoSuperCall(ITypeBinding typeBinding, String name, ITypeBinding[] parameters) {
	Assert.isNotNull(typeBinding);
	IMethodBinding binding= Bindings.findMethodInHierarchy(typeBinding.getSuperclass(), name, parameters);
	if (binding != null && !Modifier.isAbstract(binding.getModifiers())) {
		ITypeBinding declaring= binding.getDeclaringClass();
		return declaring.getQualifiedName().equals(JAVA_LANG_OBJECT);
	}
	return true;
}
 
Example 9
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void checkMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding returnType, ITypeBinding[] parameters, RefactoringStatus result, boolean reUseMethod) {
	IMethodBinding method= Bindings.findMethodInHierarchy(type, methodName, parameters);
	if (method != null) {
		boolean returnTypeClash= false;
		ITypeBinding methodReturnType= method.getReturnType();
		if (returnType != null && methodReturnType != null) {
			String returnTypeKey= returnType.getKey();
			String methodReturnTypeKey= methodReturnType.getKey();
			if (returnTypeKey == null && methodReturnTypeKey == null) {
				returnTypeClash= returnType != methodReturnType;
			} else if (returnTypeKey != null && methodReturnTypeKey != null) {
				returnTypeClash= !returnTypeKey.equals(methodReturnTypeKey);
			}
		}
		ITypeBinding dc= method.getDeclaringClass();
		if (returnTypeClash) {
			result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_returnTypeClash,
				new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}),
				JavaStatusContext.create(method));
		} else {
			if (!reUseMethod)
				result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides,
						new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}),
					JavaStatusContext.create(method));
		}
	} else {
		if (reUseMethod){
			result.addError(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_nosuchmethod_status_fatalError,
					BasicElementLabels.getJavaElementName(methodName)),
					JavaStatusContext.create(method));
		}
	}
}
 
Example 10
Source File: AbstractExceptionAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(VariableDeclarationExpression node) {
	if (node.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) {
		Type type= node.getType();
		ITypeBinding resourceTypeBinding= type.resolveBinding();
		if (resourceTypeBinding != null) {
			IMethodBinding methodBinding= Bindings.findMethodInHierarchy(resourceTypeBinding, "close", new ITypeBinding[0]); //$NON-NLS-1$
			if (methodBinding != null) {
				addExceptions(methodBinding.getExceptionTypes(), node.getAST());
			}
		}
	}
	return super.visit(node);
}
 
Example 11
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus findCommonParent(ITypeBinding typeBinding) {

		RefactoringStatus status= new RefactoringStatus();

		ITypeBinding highest= fIntermediaryFirstParameterType;
		ITypeBinding current= typeBinding;

		if (current.equals(highest) || Bindings.isSuperType(highest, current))
			// current is the same as highest or highest is already a supertype of current in the same hierarchy => no change
			return status;

		// find lowest common supertype with the method
		// search in bottom-up order
		ITypeBinding[] currentAndSupers= getTypeAndAllSuperTypes(current);
		ITypeBinding[] highestAndSupers= getTypeAndAllSuperTypes(highest);

		ITypeBinding foundBinding= null;
		for (int i1= 0; i1 < currentAndSupers.length; i1++) {
			for (int i2= 0; i2 < highestAndSupers.length; i2++) {
				if (highestAndSupers[i2].isEqualTo(currentAndSupers[i1])
						&& (Bindings.findMethodInHierarchy(highestAndSupers[i2], fTargetMethodBinding.getName(), fTargetMethodBinding.getParameterTypes()) != null)) {
					foundBinding= highestAndSupers[i2];
					break;
				}
			}
			if (foundBinding != null)
				break;
		}

		if (foundBinding != null) {
			fIntermediaryFirstParameterType= foundBinding;
		} else {
			String type1= BasicElementLabels.getJavaElementName(fIntermediaryFirstParameterType.getQualifiedName());
			String type2= BasicElementLabels.getJavaElementName(current.getQualifiedName());
			status.addFatalError(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_open_hierarchy_error, new String[] { type1, type2 }));
		}

		return status;
	}
 
Example 12
Source File: GetterSetterCorrectionSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Proposes a setter for this field.
 *
 * @param context
 *            the proposal parameter
 * @param relevance
 *            relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addSetterProposal(ProposalParameter context, int relevance) {
	boolean isBoolean = isBoolean(context);
	String setterName = GetterSetterUtil.getSetterName(context.variableBinding, context.compilationUnit.getJavaProject(), null, isBoolean);
	ITypeBinding declaringType = context.variableBinding.getDeclaringClass();
	if (declaringType == null) {
		return null;
	}

	IMethodBinding method = Bindings.findMethodInHierarchy(declaringType, setterName, new ITypeBinding[] { context.variableBinding.getType() });
	if (method != null && Bindings.isVoidType(method.getReturnType()) && (Modifier.isStatic(method.getModifiers()) == Modifier.isStatic(context.variableBinding.getModifiers()))) {
		Expression assignedValue = getAssignedValue(context);
		if (assignedValue == null) {
			return null; //we don't know how to handle those cases.
		}
		Expression mi = createMethodInvocation(context, method, assignedValue);
		context.astRewrite.replace(context.accessNode.getParent(), mi, null);

		String label = Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithsetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
		ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.compilationUnit, context.astRewrite, relevance);
		return proposal;
	} else {
		IJavaElement element = context.variableBinding.getJavaElement();
		if (element instanceof IField) {
			IField field = (IField) element;
			try {
				if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) {
					return new SelfEncapsulateFieldProposal(relevance, field);
				}
			} catch (JavaModelException e) {
				JavaLanguageServerPlugin.log(e);
			}
		}
	}
	return null;
}
 
Example 13
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Extracts the type parameter of the variable contained in fCurrentExpression or the elements
 * type to iterate over an array using <code>foreach</code>.
 * 
 * @param ast the current {@link AST} instance
 * @return the {@link ITypeBinding} of the elements to iterate over
 */
private ITypeBinding extractElementType(AST ast) {
	if (fExpressionType.isArray()) {
		return Bindings.normalizeForDeclarationUse(fExpressionType.getElementType(), ast);
	}

	// extract elements type directly out of the bindings
	IMethodBinding iteratorMethodBinding= Bindings.findMethodInHierarchy(fExpressionType, "iterator", new ITypeBinding[] {}); //$NON-NLS-1$
	IMethodBinding iteratorNextMethodBinding= Bindings.findMethodInHierarchy(iteratorMethodBinding.getReturnType(), "next", new ITypeBinding[] {}); //$NON-NLS-1$

	ITypeBinding currentElementBinding= iteratorNextMethodBinding.getReturnType();

	return Bindings.normalizeForDeclarationUse(currentElementBinding, ast);
}
 
Example 14
Source File: AbstractExceptionAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(VariableDeclarationExpression node) {
	if (node.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) {
		Type type = node.getType();
		ITypeBinding resourceTypeBinding = type.resolveBinding();
		if (resourceTypeBinding != null) {
			IMethodBinding methodBinding = Bindings.findMethodInHierarchy(resourceTypeBinding, "close", new ITypeBinding[0]); //$NON-NLS-1$
			if (methodBinding != null) {
				addExceptions(methodBinding.getExceptionTypes(), node.getAST());
			}
		}
	}
	return super.visit(node);
}
 
Example 15
Source File: OverrideCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite,
		boolean snippetStringSupport)
				throws CoreException, BadLocationException {
	Document recoveredDocument= new Document();
	CompilationUnit unit= getRecoveredAST(document, offset, recoveredDocument);
	ImportRewriteContext context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);

	ITypeBinding declaringType= null;
	ChildListPropertyDescriptor descriptor= null;
	ASTNode node= NodeFinder.perform(unit, offset, 1);
	node= ASTResolving.findParentType(node);
	String result = null;
	if (node instanceof AnonymousClassDeclaration) {
		declaringType= ((AnonymousClassDeclaration) node).resolveBinding();
		descriptor= AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
	} else if (node instanceof AbstractTypeDeclaration) {
		AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) node;
		descriptor= declaration.getBodyDeclarationsProperty();
		declaringType= declaration.resolveBinding();
	}
	if (declaringType != null) {
		ASTRewrite rewrite= ASTRewrite.create(unit.getAST());
		IMethodBinding methodToOverride= Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
		if (methodToOverride == null && declaringType.isInterface()) {
			methodToOverride= Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes); //$NON-NLS-1$
		}
		if (methodToOverride != null) {
			CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(fJavaProject.getProject());
			MethodDeclaration stub = StubUtility2Core.createImplementationStubCore(fCompilationUnit, rewrite, importRewrite,
					context, methodToOverride, declaringType, settings, declaringType.isInterface(), node,
					snippetStringSupport);
			ListRewrite rewriter= rewrite.getListRewrite(node, descriptor);
			rewriter.insertFirst(stub, null);

			ITrackedNodePosition position= rewrite.track(stub);
			try {
				Map<String, String> options = fJavaProject.getOptions(true);

				rewrite.rewriteAST(recoveredDocument, options).apply(recoveredDocument);

				String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());

				String indentAt = getIndentAt(recoveredDocument, position.getStartPosition(), settings);
				int generatedIndent = IndentManipulation.measureIndentUnits(indentAt, settings.tabWidth,
						settings.indentWidth);
				// Kinda fishy but empirical data shows Override needs to change indent by at
				// least 1
				generatedIndent = Math.max(1, generatedIndent);

				// Cancel generated code indent
				String delimiter = TextUtilities.getDefaultLineDelimiter(document);
				result = IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth,
						settings.indentWidth, "", delimiter);

			} catch (MalformedTreeException | BadLocationException exception) {
				JavaLanguageServerPlugin.logException("Unable to compute override proposal", exception);
			}
		}
	}
	return result;
}
 
Example 16
Source File: UiBinderUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Resolves a snippet (assumed to be trailing a reference to the given
 * <code>baseType</code>) to the right-most possible type.
 * <p>
 * For example, a base type of String and a snippet of
 * "toString.getClass.getDeclaredField" will return the Field type.
 *
 * @param contextType the type which will be used as the starting point for
 *          the snippet
 * @param snippet the string to trail onto a reference to the base type
 * @param visitor optional visitor that receives the corresponding
 *          {@link IMethod} for each fragment. This will be called even for
 *          methods whose return types do not resolve.
 * @return the resolved type, or null if type is a primitive or the type could
 *         not be resolved
 */
public static IType resolveJavaElExpression(IType contextType,
    String snippet, ElExpressionFragmentVisitor visitor) {
  int offset = 0;
  String[] snippetFragments = snippet.split("[.]");
  IType currentType = contextType;

  for (int i = 0; i < snippetFragments.length; i++) {
    if (i > 0) {
      // Count the previous fragment
      offset += snippetFragments[i - 1].length();

      // Count the period
      offset++;
    }

    String fragment = snippetFragments[i];

    try {
      ITypeHierarchy hierarchy = currentType.newSupertypeHierarchy(NULL_PROGRESS_MONITOR);
      IMethod method = JavaModelSearch.findMethodInHierarchy(hierarchy,
          currentType, fragment, new String[0]);
      if (method != null) {
        if (visitor != null) {
          visitor.visitResolvedFragmentMethod(method, offset,
              fragment.length());
        }

        String returnTypeSignature = method.getReturnType();
        if (SignatureUtilities.isPrimitiveType(returnTypeSignature)) {
          if (i != snippetFragments.length - 1) {
            // It returns a primitive but isn't the last fragment
            if (visitor != null) {
              visitor.visitNonterminalPrimitiveFragment(fragment, offset,
                  snippet.length() - offset);
            }
          }

          return null;
        }

        IType fragmentType = JavaModelSearch.resolveType(
            method.getDeclaringType(),
            returnTypeSignature);
        if (JavaModelSearch.isValidElement(fragmentType)) {
          currentType = fragmentType;
          continue;
        }

        // Final attempt to resolve the type, this resolves the binding
        // in the case of generics or parameterized types. Fixes issue 373
        ITypeBinding binding = JavaASTUtils.findTypeBinding(currentType);
        IMethodBinding methodBinding = Bindings.findMethodInHierarchy(binding,
            fragment, new ITypeBinding[] {});
        if(methodBinding.getReturnType() != null) {
          currentType = fragmentType;
          continue;
        }
      }
    } catch (JavaModelException e) {
      // Ignore, and continue the search
    }

    if (visitor != null) {
      visitor.visitUnresolvedFragment(fragment, offset, fragment.length(),
          currentType);
    }
    return null;
  }

  return currentType;
}
 
Example 17
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Attempts to qualify a "this" expression for a method invocation with an appropriate qualifier.
 * The invoked method is analyzed according to the following specs:
 *
 * 'this' must be qualified iff method is declared in an enclosing type or a supertype of an enclosing type
 *
 * 1) The method is declared somewhere outside of the cu of the invocation
 *      1a) inside a supertype of the current type
 *      1b) inside a supertype of an enclosing type
 * 2) The method is declared inside of the cu of the invocation
 * 		2a) inside the type of the invocation
 * 		2b) outside the type of the invocation
 *
 * In case of 1a) and 2b), qualify with the enclosing type.
 * @param expr a {@link ThisExpression}
 * @param originalInvocation the original method invocation
 * @param enclosing the enclosing member of the original method invocation
 * @param unitRewriter the rewrite
 * @return resulting status
 *
 */
private RefactoringStatus qualifyThisExpression(ThisExpression expr, MethodInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) {

	RefactoringStatus status= new RefactoringStatus();

	IMethodBinding methodBinding= originalInvocation.resolveMethodBinding();
	MethodDeclaration methodDeclaration= (MethodDeclaration) ASTNodes.findDeclaration(methodBinding, originalInvocation.getRoot());

	ITypeBinding currentTypeBinding= null;
	if (methodDeclaration != null) {
		// Case 1) : Declaring type is inside this cu => use its name if it's declared in an enclosing type
		if (ASTNodes.isParent(originalInvocation, methodDeclaration.getParent()))
			currentTypeBinding= methodBinding.getDeclaringClass();
		else
			currentTypeBinding= ASTNodes.getEnclosingType(originalInvocation);
	} else {
		// Case 2) : Declaring type is outside of this cu => find subclass in this cu
		ASTNode currentTypeDeclaration= getEnclosingTypeDeclaration(originalInvocation);
		currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
		while (currentTypeDeclaration != null && (Bindings.findMethodInHierarchy(currentTypeBinding, methodBinding.getName(), methodBinding.getParameterTypes()) == null)) {
			currentTypeDeclaration= getEnclosingTypeDeclaration(currentTypeDeclaration.getParent());
			currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
		}
	}

	if (currentTypeBinding == null) {
		status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_declaring_type_not_found));
		return status;
	}

	currentTypeBinding= currentTypeBinding.getTypeDeclaration();

	ITypeBinding typeOfCall= ASTNodes.getEnclosingType(originalInvocation);
	if (!typeOfCall.equals(currentTypeBinding)) {
		if (currentTypeBinding.isAnonymous()) {
			// Cannot qualify, see bug 115277
			status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_anonymous_cannot_qualify));
		} else {
			expr.setQualifier(unitRewriter.getAST().newSimpleName(currentTypeBinding.getName()));
		}
	} else {
		// do not qualify, only use "this.".
	}

	return status;
}
 
Example 18
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression,
		Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes,
		Collection<ChangeCorrectionProposal> proposals) {
	ITypeBinding castType= expression.getType().resolveBinding();
	if (castType == null) {
		return false;
	}
	if (paramTypes != null) {
		if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
			return false;
		}
	} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
		return false;
	}
	ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
	if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
		return false;
	}

	IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
	if (res != null) {
		AST ast= expression.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);
		CastExpression newCast= ast.newCastExpression();
		newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
		newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
		ParenthesizedExpression parents= ast.newParenthesizedExpression();
		parents.setExpression(newCast);

		ASTNode node= rewrite.createCopyTarget(expression.getExpression());
		rewrite.replace(expression, node, null);
		rewrite.replace(accessExpression, parents, null);

		String label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
		ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, rewrite,
				IProposalRelevance.ADD_PARENTHESES_AROUND_CAST);
		proposals.add(proposal);
		return true;
	}
	return false;
}
 
Example 19
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender,
		List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig = org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getMethodSignature(methodName, parameterTypes, false);
				boolean is18OrHigher= JavaModelUtil.is18OrHigher(targetCU.getJavaProject());

				boolean isSenderBindingInterface= senderDeclBinding.isInterface();
				if (nodeParentType == senderDeclBinding) {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
				} else {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
				}
				if (is18OrHigher || !isSenderBindingInterface
						|| (nodeParentType != senderDeclBinding && (!(sender instanceof SimpleName) || !((SimpleName) sender).getIdentifier().equals(senderDeclBinding.getName())))) {
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments,
							senderDeclBinding, IProposalRelevance.CREATE_METHOD));
				}

				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						isSenderBindingInterface= senderDeclBinding.isInterface();
						if (!senderDeclBinding.isAnonymous()) {
							if (is18OrHigher || !isSenderBindingInterface) {
								String[] args = new String[] { sig,
										org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) };
								label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
								proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode,
										arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD));
							}
						}
					}
				}
			}
		}
	}
}
 
Example 20
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender, List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName, Collection<ICommandAccess> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			Image image;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig= ASTResolving.getMethodSignature(methodName, parameterTypes, false);

				if (ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
					if (nodeParentType == senderDeclBinding) {
						label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
						image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
					} else {
						label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
						image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
					}
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD, image));
				}
				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						if (!senderDeclBinding.isAnonymous() && ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
							String[] args= new String[] { sig, ASTResolving.getTypeSignature(senderDeclBinding) };
							label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
							image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
							proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD, image));
						}
					}
				}
			}
		}
	}
}