Java Code Examples for org.eclipse.jdt.core.dom.MethodInvocation#getExpression()

The following examples show how to use org.eclipse.jdt.core.dom.MethodInvocation#getExpression() . 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: MovedMemberAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(MethodInvocation node) {
	IBinding binding= node.resolveMethodBinding();
	if (isSourceAccess(binding)) {
		if (isMovedMember(binding)) {
			if (node.getExpression() != null)
				rewrite(node, fTarget);
		} else
			rewrite(node, fSource);

	} else if (isTargetAccess(binding)) {
		if (node.getExpression() != null) {
			fCuRewrite.getASTRewrite().remove(node.getExpression(), null);
			fCuRewrite.getImportRemover().registerRemovedNode(node.getExpression());
		}
	}
	return super.visit(node);
}
 
Example 2
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(final MethodInvocation it) {
  Expression _expression = it.getExpression();
  boolean _tripleNotEquals = (_expression != null);
  if (_tripleNotEquals) {
    it.getExpression().accept(this);
    if ((this.fallBackStrategy && this._aSTFlattenerUtils.isStaticMemberCall(it))) {
      this.appendToBuffer("::");
    } else {
      this.appendToBuffer(".");
    }
  }
  boolean _isEmpty = it.typeArguments().isEmpty();
  boolean _not = (!_isEmpty);
  if (_not) {
    this.appendTypeParameters(it.typeArguments());
  }
  it.getName().accept(this);
  this.appendToBuffer("(");
  this.visitAllSeparatedByComma(it.arguments());
  this.appendToBuffer(")");
  return false;
}
 
Example 3
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ITypeBinding getExpressionType(MethodInvocation invocation) {
	Expression expression= invocation.getExpression();
	ITypeBinding typeBinding= null;
	if (expression == null) {
		typeBinding= invocation.resolveMethodBinding().getDeclaringClass();
	} else {
		typeBinding= expression.resolveTypeBinding();
	}
	if (typeBinding != null && typeBinding.isTypeVariable()) {
		ITypeBinding[] typeBounds= typeBinding.getTypeBounds();
		if (typeBounds.length > 0) {
			for (ITypeBinding typeBound : typeBounds) {
				ITypeBinding expressionType= getExpressionType(invocation, typeBound);
				if (expressionType != null) {
					return expressionType;
				}
			}
			typeBinding= typeBounds[0].getTypeDeclaration();
		} else {
			typeBinding= invocation.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
		}
	}
	Assert.isNotNull(typeBinding, "Type binding of target expression may not be null"); //$NON-NLS-1$
	return typeBinding;
}
 
Example 4
Source File: OperationInvocation.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public OperationInvocation(CompilationUnit cu, String filePath, MethodInvocation invocation) {
	this.locationInfo = new LocationInfo(cu, filePath, invocation, CodeElementType.METHOD_INVOCATION);
	this.methodName = invocation.getName().getIdentifier();
	this.typeArguments = invocation.arguments().size();
	this.arguments = new ArrayList<String>();
	List<Expression> args = invocation.arguments();
	for(Expression argument : args) {
		this.arguments.add(argument.toString());
	}
	if(invocation.getExpression() != null) {
		this.expression = invocation.getExpression().toString();
		processExpression(invocation.getExpression(), this.subExpressions);
	}
}
 
Example 5
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks
 * <ul>
 * <li>whether the given infix expression is the argument of a StringBuilder#append() or
 * StringBuffer#append() invocation, and</li>
 * <li>the append method is called on a simple variable, and</li>
 * <li>the invocation occurs in a statement (not as nested expression)</li>
 * </ul>
 *
 * @param infixExpression the infix expression
 * @return the name of the variable we were appending to, or <code>null</code> if not matching
 */
private static SimpleName getEnclosingAppendBuffer(InfixExpression infixExpression) {
	if (infixExpression.getLocationInParent() == MethodInvocation.ARGUMENTS_PROPERTY) {
		MethodInvocation methodInvocation= (MethodInvocation)infixExpression.getParent();

		// ..not in an expression.. (e.g. not sb.append("high" + 5).append(6);)
		if (methodInvocation.getParent() instanceof Statement) {

			// ..of a function called append:
			if ("append".equals(methodInvocation.getName().getIdentifier())) { //$NON-NLS-1$
				Expression expression= methodInvocation.getExpression();

				// ..and the append is being called on a Simple object:
				if (expression instanceof SimpleName) {
					IBinding binding= ((SimpleName)expression).resolveBinding();
					if (binding instanceof IVariableBinding) {
						String typeName= ((IVariableBinding)binding).getType().getQualifiedName();

						// And the object's type is a StringBuilder or StringBuffer:
						if ("java.lang.StringBuilder".equals(typeName) || "java.lang.StringBuffer".equals(typeName)) { //$NON-NLS-1$ //$NON-NLS-2$
							return (SimpleName)expression;
						}
					}
				}
			}
		}
	}
	return null;
}
 
Example 6
Source File: SourceAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(MethodInvocation node) {
	if (fTypeCounter == 0) {
		Expression receiver= node.getExpression();
		if (receiver == null && !isStaticallyImported(node.getName())) {
			fImplicitReceivers.add(node);
		}
	}
	return true;
}
 
Example 7
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final boolean visit(final MethodInvocation node) {
	Assert.isNotNull(node);
	if (fAnonymousClass > 0) {
		final IMethodBinding binding= node.resolveMethodBinding();
		if (binding != null) {
			if (node.getExpression() == null && !Modifier.isStatic(binding.getModifiers()))
				fResult.add(node.getName());
		}
	}
	return true;
}
 
Example 8
Source File: BindingSignatureVisitor.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean visit(MethodInvocation expr) {
	if (expr.getExpression() != null) {
		handleExpression(expr.getExpression());
	}
	handleExpression(expr.getName());
	handleParameters(expr.arguments());
	return false;
}
 
Example 9
Source File: CamelJavaFileParser.java    From eip-designer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(MethodInvocation node) {
   if (inConfigure) {
      // We're in a fluent API usage...
      if (node.getExpression() != null) {
         expressionStack.addLast(node);
      } else {
         computeExpressionStack(node);
         // Reset stack for next expression.
         expressionStack.clear();
      }
     
   }
   return super.visit(node);
}
 
Example 10
Source File: AbstractLoopUtilities.java    From JDeodorant with MIT License 5 votes vote down vote up
public static boolean isCollectionSizeInvocation(Expression expression)
{
	if (expression instanceof MethodInvocation)
	{
		MethodInvocation methodInvocation = (MethodInvocation) expression;
		Expression callingExpression      = methodInvocation.getExpression();
		IMethodBinding methodBinding      = methodInvocation.resolveMethodBinding();
		if (methodBinding != null && callingExpression != null)
		{
			return (methodBinding.getName().equals("size") && AbstractLoopUtilities.isCollection(callingExpression.resolveTypeBinding()));
		}
	}
	return false;
}
 
Example 11
Source File: APICallVisitor.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
public String getFullyQualifiedMethodNameFor(final Expression exp, final String parentClassName,
		final Table<ASTNode, String, String> variableScopeNameTypes) {
	String fqName;
	String name;
	if (exp.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
		name = "<init>";
		fqName = getNameOfType(((ClassInstanceCreation) exp).getType());
	} else { // MethodInvocation
		final MethodInvocation node = (MethodInvocation) exp;
		name = node.getName().toString();
		if (node.getExpression() == null) {
			if (methodImports.containsKey(name))
				fqName = methodImports.get(name);
			else if (methodReturnTypes.containsKey(parentClassName + "." + name))
				fqName = parentClassName; // local
			else if (wildcardMethodImports.isEmpty())
				fqName = currentPackage; // package local method
			else
				fqName = "UNRESOLVED";
		} else if (node.getExpression().getNodeType() == ASTNode.THIS_EXPRESSION) {
			if (methodReturnTypes.containsKey(parentClassName + "." + name))
				fqName = parentClassName; // local
			else // superclass method
				fqName = "SUPER";
		} else {
			fqName = getFQMethodClassFor(node.getExpression(), parentClassName, variableScopeNameTypes);
		}
	}
	if (fqName.equals("UNRESOLVED"))
		unresMethods.add(name);
	return fqName + "." + name;
}
 
Example 12
Source File: ConstantChecks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(MethodInvocation node) {
	if(node.getExpression() == null) {
		visitName(node.getName());
	} else {
		fResult&= new LoadTimeConstantChecker((IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(node.getExpression())).check();
	}

	return false;
}
 
Example 13
Source File: ExtractMethodRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(MethodInvocation node) {
	Expression exp = node.getExpression();
	if (exp != null) {
		fIgnore.add(node.getName());
	}
	return true;
}
 
Example 14
Source File: CodeScopeBuilder.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(MethodInvocation node) {
	Expression receiver = node.getExpression();
	if (receiver == null) {
		SimpleName name = node.getName();
		if (fIgnoreBinding == null || !Bindings.equals(fIgnoreBinding, name.resolveBinding())) {
			node.getName().accept(this);
		}
	} else {
		receiver.accept(this);
	}
	accept(node.arguments());
	return false;
}
 
Example 15
Source File: CastCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
	AST ast= rewrite.getAST();

	ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);

	if (fCastType != null) {
		return importRewrite.addImport(fCastType, ast,context);
	}

	ASTNode node= fNodeToCast;
	ASTNode parent= node.getParent();
	if (parent instanceof CastExpression) {
		node= parent;
		parent= parent.getParent();
	}
	while (parent instanceof ParenthesizedExpression) {
		node= parent;
		parent= parent.getParent();
	}
	if (parent instanceof MethodInvocation) {
		MethodInvocation invocation= (MethodInvocation) node.getParent();
		if (invocation.getExpression() == node) {
			IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node);
			ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
			if (bindings.length > 0) {
				ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());

				Type newTypeNode= importRewrite.addImport(first, ast, context);
				addLinkedPosition(rewrite.track(newTypeNode), true, "casttype"); //$NON-NLS-1$
				for (int i= 0; i < bindings.length; i++) {
					addLinkedPositionProposal("casttype", bindings[i]); //$NON-NLS-1$
				}
				return newTypeNode;
			}
		}
	}
	Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
	addLinkedPosition(rewrite.track(newCastType), true, "casttype"); //$NON-NLS-1$
	return newCastType;
}
 
Example 16
Source File: ReferencedClassesParser.java    From BUILD_file_generator with Apache License 2.0 4 votes vote down vote up
@Override
public boolean visit(MethodInvocation node) {
  visitExpressionIfName(node.getExpression());
  if (node.getExpression() != null) {
    return true;
  }
  // node is of the form `methodName(...)`, and not eg., `Foo.methodName()`.

  org.eclipse.jdt.core.dom.SimpleName simpleName = node.getName();

  if (compilationUnit.findDeclaringNode(simpleName.resolveBinding()) != null) {
    // simpleName is defined somewhere in this compilation unit - so no need to import it.
    return true;
  }

  // Do not report methods that appear in inner/anonymous classes that have a superclass:
  // Jade doesn't currently fetch inherited symbols for inner/anonymous classes, which
  // leads to inherited methods being imported. (b/35660499, b/35727475)
  // This isn't perfect because another class might call a same-named method; if this
  // becomes a problem, I'll use a blacklist.
  AbstractTypeDeclaration containingClass = getContainingClass(node);
  if (!(containingClass.getParent() instanceof CompilationUnit)
      && containingClass instanceof TypeDeclaration
      && ((TypeDeclaration) containingClass).getSuperclassType() != null) {
    return true;
  }
  if (isDescendantOfAnonymousClassDeclaration(node)) {
    return true;
  }

  // Work around Eclipse JDT Bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=462192,
  // where `simpleName.resolveBinding() == null` happens even though 'simpleName' is
  // defined in the current compilation unit.
  Set<String> methods = methodsOfClass.get(containingClass);
  if (methods.isEmpty()) {
    methods.addAll(getMethodDeclarations(containingClass));
  }
  if (!methods.contains(simpleName.getIdentifier())) {
    int startPosition = simpleName.getStartPosition();
    symbols.put(
        simpleName.getIdentifier(),
        Metadata.create(
            compilationUnit.getLineNumber(startPosition),
            compilationUnit.getColumnNumber(startPosition),
            true));
  }
  return true;
}
 
Example 17
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean visit(final MethodInvocation node) {
	if (!fRemoveMethodQualifiers)
		return true;

	Expression expression= node.getExpression();
	if (!(expression instanceof ThisExpression))
		return true;

	final SimpleName name= node.getName();
	if (name.resolveBinding() == null)
		return true;

	if (hasConflict(expression.getStartPosition(), name, ScopeAnalyzer.METHODS | ScopeAnalyzer.CHECK_VISIBILITY))
		return true;

	Name qualifier= ((ThisExpression)expression).getQualifier();
	if (qualifier != null) {
		ITypeBinding declaringClass= ((IMethodBinding)name.resolveBinding()).getDeclaringClass();
		if (declaringClass == null)
			return true;

		ITypeBinding caller= getDeclaringType(node);
		if (caller == null)
			return true;

		ITypeBinding callee= (ITypeBinding)qualifier.resolveBinding();
		if (callee == null)
			return true;

		if (callee.isAssignmentCompatible(declaringClass) && caller.isAssignmentCompatible(declaringClass))
			return true;
	}

	fOperations.add(new CompilationUnitRewriteOperation() {
		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			TextEditGroup group= createTextEditGroup(FixMessages.CodeStyleFix_removeThis_groupDescription, cuRewrite);
			rewrite.remove(node.getExpression(), group);
		}
	});
	return super.visit(node);
}
 
Example 18
Source File: AbstractLoopUtilities.java    From JDeodorant with MIT License 4 votes vote down vote up
public static List<ASTNode> getVariableDeclarationsAndAssignmentsContainingAccessUsingVariable(Statement body, ControlVariable variable)
{
	StatementExtractor statementExtractor = new StatementExtractor();
	ExpressionExtractor expressionExtractor = new ExpressionExtractor();
	ArrayList<ASTNode> returnList = new ArrayList<ASTNode>();
	List<Statement> variableDeclarationStatements = statementExtractor.getVariableDeclarationStatements(body);
	List<Expression> assignments = expressionExtractor.getAssignments(body);
	for (Statement currentStatement : variableDeclarationStatements)
	{
		List<VariableDeclarationFragment> fragments = ((VariableDeclarationStatement)currentStatement).fragments();
		for (VariableDeclarationFragment fragment : fragments)
		{
			Expression initializer = fragment.getInitializer();
			if (isAccessUsingVariable(initializer, variable))
			{
				returnList.add(fragment);
			}
		}
	}
	for (Expression currentExpression : assignments)
	{
		Assignment currentAssignment = (Assignment)currentExpression;
		Expression rightHandSide = currentAssignment.getRightHandSide();
		if (isAccessUsingVariable(rightHandSide, variable))
		{
			returnList.add(currentAssignment);
		}
	}
	List<Expression> methodInvocations = expressionExtractor.getMethodInvocations(body);
	for (Expression expression : methodInvocations)
	{
		if (expression instanceof MethodInvocation)
		{
			MethodInvocation methodInvocation = (MethodInvocation)expression;
			Expression methodInvocationExpression = methodInvocation.getExpression();
			if(methodInvocationExpression != null)
			{
				if (isAccessUsingVariable(methodInvocationExpression, variable))
				{
					returnList.add(methodInvocation);
				}
			}
		}
	}
	return returnList;
}
 
Example 19
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus updateMethodInvocation(MethodInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) throws JavaModelException {

		RefactoringStatus status= new RefactoringStatus();

		// If the method invocation utilizes type arguments, skip this
		// call as the new target method may have additional parameters
		if (originalInvocation.typeArguments().size() > 0)
			return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_type_arguments);

		MethodInvocation newInvocation= unitRewriter.getAST().newMethodInvocation();
		List<Expression> newInvocationArgs= newInvocation.arguments();
		List<Expression> originalInvocationArgs= originalInvocation.arguments();

		// static call => always use a qualifier
		String qualifier= unitRewriter.getImportRewrite().addImport(fIntermediaryTypeBinding);
		newInvocation.setExpression(ASTNodeFactory.newName(unitRewriter.getAST(), qualifier));
		newInvocation.setName(unitRewriter.getAST().newSimpleName(getIntermediaryMethodName()));

		final Expression expression= originalInvocation.getExpression();

		if (!isStaticTarget()) {
			// Add the expression as the first parameter
			if (expression == null) {
				// There is no expression for this call. Use a (possibly qualified) "this" expression.
				ThisExpression expr= unitRewriter.getAST().newThisExpression();
				RefactoringStatus qualifierStatus= qualifyThisExpression(expr, originalInvocation, enclosing, unitRewriter);
				status.merge(qualifierStatus);
				if (qualifierStatus.hasEntries())
					// warning means don't include this invocation
					return status;
				newInvocationArgs.add(expr);
			} else {
				Expression expressionAsParam= (Expression) unitRewriter.getASTRewrite().createMoveTarget(expression);
				newInvocationArgs.add(expressionAsParam);
			}
		} else {
			if (expression != null) {
				// Check if expression is the type name. If not, there may
				// be side effects (e.g. inside methods) -> don't update
				if (! (expression instanceof Name) || ASTNodes.getTypeBinding((Name) expression) == null)
					return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_static_expression_access);
			}
		}

		for (int i= 0; i < originalInvocationArgs.size(); i++) {
			Expression originalInvocationArg= originalInvocationArgs.get(i);
			Expression movedArg= (Expression) unitRewriter.getASTRewrite().createMoveTarget(originalInvocationArg);
			newInvocationArgs.add(movedArg);
		}

		unitRewriter.getASTRewrite().replace(originalInvocation, newInvocation,
				unitRewriter.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_replace_call));

		return status;
	}
 
Example 20
Source File: CallInliner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @param status the status
 * @return <code>true</code> if explicit cast is needed otherwise <code>false</code>
 */
private boolean needsExplicitCast(RefactoringStatus status) {
	// if the return type of the method is the same as the type of the
	// returned expression then we don't need an explicit cast.
	if (fSourceProvider.returnTypeMatchesReturnExpressions())
			return false;

	List<Expression> returnExprs= fSourceProvider.getReturnExpressions();
	// it is inferred that only methods consisting of a single
	// return statement can be inlined as parameters in other
	// method invocations
	if (returnExprs.size() != 1)
		return false;

	if (fTargetNode.getLocationInParent() == MethodInvocation.ARGUMENTS_PROPERTY) {
		MethodInvocation methodInvocation= (MethodInvocation)fTargetNode.getParent();
		if(methodInvocation.getExpression() == fTargetNode)
			return false;
		IMethodBinding method= methodInvocation.resolveMethodBinding();
		if (method == null) {
			status.addError(RefactoringCoreMessages.CallInliner_cast_analysis_error,
				JavaStatusContext.create(fCUnit, methodInvocation));
			return false;
		}
		ITypeBinding[] parameters= method.getParameterTypes();
		int argumentIndex= methodInvocation.arguments().indexOf(fInvocation);

		ITypeBinding parameterType= returnExprs.get(0).resolveTypeBinding();
		if (method.isVarargs() && argumentIndex >= parameters.length - 1) {
			argumentIndex= parameters.length - 1;
			parameterType= parameterType.createArrayType(1);
		}
		parameters[argumentIndex]= parameterType;

		ITypeBinding type= ASTNodes.getReceiverTypeBinding(methodInvocation);
		TypeBindingVisitor visitor= new AmbiguousMethodAnalyzer(
			fTypeEnvironment, method, fTypeEnvironment.create(parameters));
		if(!visitor.visit(type)) {
			return true;
		} else if (type.isInterface()) {
			return !Bindings.visitInterfaces(type, visitor);
		} else if (Modifier.isAbstract(type.getModifiers())) {
			return !Bindings.visitHierarchy(type, visitor);
		} else {
			// it is not needed to visit interfaces if receiver is a concrete class
			return !Bindings.visitSuperclasses(type, visitor);
		}
	} else {
		ITypeBinding explicitCast= ASTNodes.getExplicitCast(returnExprs.get(0), (Expression)fTargetNode);
		return explicitCast != null;
	}
}