@Override public Expression apply(Object object, MethodInvocation whenMethodInvocation) { MethodInvocation methodInvocation = methodInvocation(object, thenThrow).get(); List arguments = methodInvocation.arguments(); if (arguments.size() == 1) { MethodInvocation mockedMethodInvocation = (MethodInvocation) whenMethodInvocation.arguments().get(0); Expression toBeThrown = argumentAsExpression(arguments.get(0)); Expression throwingClosure = groovyClosureBuilder.aClosure() .withBodyStatement(nodeFactory.throwStatement(toBeThrown)) .build() .asExpression(); return nodeFactory.infixExpression(RIGHT_SHIFT_SIGNED, mockedMethodWithMatchers(mockedMethodInvocation), throwingClosure); } throw new UnsupportedOperationException("Supported only 1-arity thenThrow invocation"); }
public VariableDeclarationStatement variableDeclarationStatement(String name, Type type, Expression initializer) { VariableDeclarationFragment variableDeclarationFragment = variableDeclarationFragment(name); variableDeclarationFragment.setInitializer(initializer); VariableDeclarationStatement statement = ast.get().newVariableDeclarationStatement(variableDeclarationFragment); statement.setType(type); return statement; }
@Override public boolean visit(FieldDeclaration fieldDeclaration) { Type fieldType = fieldDeclaration.getType(); int fieldModifiers = fieldDeclaration.getModifiers(); Visibility visibility = getVisibility(fieldModifiers); // boolean isFinal = (fieldModifiers & Modifier.FINAL) != 0; boolean isStatic = (fieldModifiers & Modifier.STATIC) != 0; List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); for (VariableDeclarationFragment fragment : fragments) { String fieldName = fragment.getName().getIdentifier(); final SDAttribute attribute = model.createAttribute(fieldName, containerStack.peek()); attribute.setStatic(isStatic); attribute.setVisibility(visibility); attribute.setType(AstUtils.normalizeTypeName(fieldType, fragment.getExtraDimensions(), false)); Expression expression = fragment.getInitializer(); if (expression != null) { //attribute.setAssignment(srbForAttributes.buildSourceRepresentation(fileContent, expression.getStartPosition(), expression.getLength())); addClientCode(attribute.key().toString(), srbForAttributes.buildPartialSourceRepresentation(fileContent, expression)); } attribute.setClientCode(srbForAttributes.buildEmptySourceRepresentation()); } return true; }
private VariableDeclarationStatement createDeclaration(IVariableBinding binding, Expression intilizer) { VariableDeclaration original = ASTNodes.findVariableDeclaration(binding, fAnalyzer.getEnclosingBodyDeclaration()); VariableDeclarationFragment fragment = fAST.newVariableDeclarationFragment(); fragment.setName((SimpleName) ASTNode.copySubtree(fAST, original.getName())); fragment.setInitializer(intilizer); VariableDeclarationStatement result = fAST.newVariableDeclarationStatement(fragment); result.modifiers().addAll(ASTNode.copySubtrees(fAST, ASTNodes.getModifiers(original))); result.setType(ASTNodeFactory.newType(fAST, original, fImportRewriter, new ContextSensitiveImportRewriteContext(original, fImportRewriter))); return result; }
@Override public DSubTree handle() { DSubTree tree = new DSubTree(); // add the expression's subtree (e.g: foo(..).bar() should handle foo(..) first) DSubTree Texp = new DOMExpression(creation.getExpression()).handle(); tree.addNodes(Texp.getNodes()); // evaluate arguments first for (Object o : creation.arguments()) { DSubTree Targ = new DOMExpression((Expression) o).handle(); tree.addNodes(Targ.getNodes()); } IMethodBinding binding = creation.resolveConstructorBinding(); // get to the generic declaration, if this binding is an instantiation while (binding != null && binding.getMethodDeclaration() != binding) binding = binding.getMethodDeclaration(); MethodDeclaration localMethod = Utils.checkAndGetLocalMethod(binding); if (localMethod != null) { DSubTree Tmethod = new DOMMethodDeclaration(localMethod).handle(); tree.addNodes(Tmethod.getNodes()); } else if (Utils.isRelevantCall(binding)) tree.addNode(new DAPICall(binding, Visitor.V().getLineNumber(creation))); return tree; }
public RefinementString(Expression e) { if (knownConstants(e)) return; if ( !(e instanceof StringLiteral)) { this.exists = false; this.length = 0; this.containsPunct = false; return; } String s = ((StringLiteral) e).getLiteralValue(); this.exists = true; this.length = s.length(); this.containsPunct = hasPunct(s); }
@Override public Expression apply(Object object, MethodInvocation methodInvocation) { List arguments = methodInvocation.arguments(); if (arguments.size() == 1) { return argumentAsExpression(arguments.get(0)); } if (arguments.size() == 2) { return argumentAsExpression(arguments.get(1)); } throw new UnsupportedOperationException("Supported only 1-, 2-arity assertTrue invocation"); }
@Override public Expression apply(Object object, MethodInvocation methodInvocation) { List arguments = methodInvocation.arguments(); if (arguments.size() == 1) { return astNodeFactory.prefixExpression(NOT, argumentAsExpression(arguments.get(0))); } if (arguments.size() == 2) { return astNodeFactory.prefixExpression(NOT, argumentAsExpression(arguments.get(1))); } throw new UnsupportedOperationException("Supported only 1-, 2-arity assertFalse invocation"); }
@Override public InfixExpression apply(Object object, MethodInvocation verifyMethodInvocation) { List arguments = verifyMethodInvocation.arguments(); return nodeFactory.infixExpression(TIMES, nodeFactory.numberLiteral("0"), nodeFactory.fieldAccess("_", nodeFactory.clone((Expression) arguments.get(0)))); }
@Override public InfixExpression apply(Object object, MethodInvocation verifyMethodInvocation) { List arguments = verifyMethodInvocation.arguments(); MethodInvocation parentMethodInvocation = (MethodInvocation) verifyMethodInvocation.getParent(); return nodeFactory.infixExpression(TIMES, cardinality(arguments.size() == 2 ? Optional.of(arguments.get(1)) : empty()), nodeFactory.methodInvocation(parentMethodInvocation.getName().getFullyQualifiedName(), (List<Expression>) parentMethodInvocation.arguments().stream() .map(matcherHandler::applyMatchers).collect(toList()), nodeFactory.clone((Expression) arguments.get(0)))); }
public static Optional<GroovyClosure> asClosure(ASTNodeFactory nodeFactory, GroovyClosureBuilder groovyClosureBuilder, Expression expression, String methodName) { if (expression instanceof ClassInstanceCreation) { ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression; if (classInstanceCreation.getAnonymousClassDeclaration() != null) { AnonymousClassDeclaration classDeclaration = classInstanceCreation.getAnonymousClassDeclaration(); if (classDeclaration.bodyDeclarations().size() == 1 && classDeclaration.bodyDeclarations().get(0) instanceof MethodDeclaration && ((MethodDeclaration) classDeclaration.bodyDeclarations().get(0)) .getName().getIdentifier().equals(methodName)) { MethodDeclaration methodDeclaration = (MethodDeclaration) classDeclaration.bodyDeclarations().get(0); List<Statement> statements = nodeFactory.clone(methodDeclaration.getBody()).statements(); GroovyClosure closure = groovyClosureBuilder.aClosure() .withBodyStatements(statements) .withTypeLiteral(nodeFactory.typeLiteral(type(nodeFactory, classInstanceCreation))) .withArgument(nodeFactory.clone((SingleVariableDeclaration) methodDeclaration.parameters().get(0))) .build(); return Optional.of(closure); } } } return empty(); }
public boolean visit(CastExpression node) { if (mtbStack.isEmpty()) // not part of a method return true; Expression expression = node.getExpression(); ITypeBinding type = node.getType().resolveBinding(); IMethodBinding mtb = mtbStack.peek(); String exprStr = expression.toString(); String typeStr = getQualifiedName(type); String methodStr = getQualifiedName(mtb); exprStr = edit_str(exprStr); facts.add(Fact.makeCastFact(exprStr, typeStr, methodStr)); return true; }
private void handleVarDeclaration(VariableDeclarationFragment var, boolean isField) { String varName = var.getName().getIdentifier(); VariableInfo varInfo = current.addVar(varName, isField); Expression init = var.getInitializer(); if(init instanceof SimpleName) { String initVar = ((SimpleName) init).getIdentifier(); varInfo.addOperation(new VariableOperation(varName, VariableOperation.Type.INIT, initVar)); } }
private Object[] accessExpressions(ArrayAccess node) { Object[] exp = new Object[indexDepth(node)+1]; ArrayAccess a = node; int i = exp.length-1; do { Expression indexExp = a.getIndex(); if(!(indexExp instanceof SimpleName)) // TODO no modifiers return null; exp[i] = indexExp.toString(); Expression temp = a.getArray(); a = temp instanceof ArrayAccess ? (ArrayAccess) temp : null; i--; } while(i >= 0); return exp; }
private static boolean isAcumulationAssign(Assignment assignment, InfixExpression.Operator op, Predicate<Expression> acceptExpression) { if(!( assignment.getRightHandSide() instanceof InfixExpression && assignment.getLeftHandSide() instanceof SimpleName && assignment.getOperator() == Assignment.Operator.ASSIGN)) return false; InfixExpression exp = (InfixExpression) assignment.getRightHandSide(); if(exp.getOperator() != op) return false; String assignVar = assignment.getLeftHandSide().toString(); if( exp.getLeftOperand() instanceof SimpleName && exp.getLeftOperand().toString().equals(assignVar) && acceptExpression.test(exp.getRightOperand())) return true; if( exp.getRightOperand() instanceof SimpleName && exp.getRightOperand().toString().equals(assignVar) && acceptExpression.test(exp.getLeftOperand())) return true; return false; }
/** * Returns the binding of the variable written in an Assignment. * @param assignment The assignment * @return The binding or <code>null</code> if no bindings are available. */ public static IVariableBinding getAssignedVariable(Assignment assignment) { Expression leftHand = assignment.getLeftHandSide(); switch (leftHand.getNodeType()) { case ASTNode.SIMPLE_NAME: return (IVariableBinding) ((SimpleName) leftHand).resolveBinding(); case ASTNode.QUALIFIED_NAME: return (IVariableBinding) ((QualifiedName) leftHand).getName().resolveBinding(); case ASTNode.FIELD_ACCESS: return ((FieldAccess) leftHand).resolveFieldBinding(); case ASTNode.SUPER_FIELD_ACCESS: return ((SuperFieldAccess) leftHand).resolveFieldBinding(); default: return null; } }
/** * Returns whether an expression at the given location needs explicit boxing. * * @param expression the expression * @return <code>true</code> iff an expression at the given location needs explicit boxing * @since 3.6 */ private static boolean needsExplicitBoxing(Expression expression) { StructuralPropertyDescriptor locationInParent= expression.getLocationInParent(); if (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { return needsExplicitBoxing((ParenthesizedExpression) expression.getParent()); } if (locationInParent == ClassInstanceCreation.EXPRESSION_PROPERTY || locationInParent == FieldAccess.EXPRESSION_PROPERTY || locationInParent == MethodInvocation.EXPRESSION_PROPERTY) { return true; } return false; }
/** * Returns the receiver's type binding of the given method invocation. * * @param invocation method invocation to resolve type of * @return the type binding of the receiver */ public static ITypeBinding getReceiverTypeBinding(MethodInvocation invocation) { ITypeBinding result= null; Expression exp= invocation.getExpression(); if(exp != null) { return exp.resolveTypeBinding(); } else { AbstractTypeDeclaration type= (AbstractTypeDeclaration)getParent(invocation, AbstractTypeDeclaration.class); if (type != null) { return type.resolveBinding(); } } return result; }
/** * Returns the topmost ancestor of <code>node</code> that is a {@link Type} (but not a {@link UnionType}). * <p> * <b>Note:</b> The returned node often resolves to a different binding than the given <code>node</code>! * * @param node the starting node, can be <code>null</code> * @return the topmost type or <code>null</code> if the node is not a descendant of a type node * @see #getNormalizedNode(ASTNode) */ public static Type getTopMostType(ASTNode node) { ASTNode result= null; while (node instanceof Type && !(node instanceof UnionType) || node instanceof Name || node instanceof Annotation || node instanceof MemberValuePair || node instanceof Expression) { // Expression could maybe be reduced to expression node types that can appear in an annotation result= node; node= node.getParent(); } if (result instanceof Type) { return (Type) result; } return null; }
private static boolean isAllOperandsHaveSameType(InfixExpression expression, ITypeBinding leftOperandType, ITypeBinding rightOperandType) { ITypeBinding binding= leftOperandType; if (binding == null) { return false; } ITypeBinding current= rightOperandType; if (binding != current) { return false; } for (Iterator<Expression> iterator= expression.extendedOperands().iterator(); iterator.hasNext();) { Expression operand= iterator.next(); current= operand.resolveTypeBinding(); if (binding != current) { return false; } } return true; }
/** * returns the name associated with an assignment instruction * * @param instr * @return */ public static String getSimpleAssignName(AssignmentInstruction instr) { if (instr instanceof LoadLiteralInstruction) return ((LoadLiteralInstruction) instr).getLiteral().toString(); ASTNode parentInstr = instr.getNode().getParent(); if (parentInstr instanceof VariableDeclarationFragment) { return ((VariableDeclarationFragment) parentInstr).getName().getFullyQualifiedName(); } if (parentInstr instanceof Assignment) { Expression leftHnsd = ((Assignment) parentInstr).getLeftHandSide(); if (leftHnsd instanceof SimpleName) { return ((SimpleName) leftHnsd).getFullyQualifiedName(); } else if (leftHnsd instanceof FieldAccess) { return ((FieldAccess) leftHnsd).getName().getFullyQualifiedName(); } } throw new IllegalStateException("cannot find local variable associated with " + instr); }
@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; }
public static String[] getVariableNameSuggestions(int variableKind, IJavaProject project, Type expectedType, Expression assignedExpression, Collection<String> excluded) { LinkedHashSet<String> res= new LinkedHashSet<>(); // avoid duplicates but keep order if (assignedExpression != null) { String nameFromExpression= getBaseNameFromExpression(project, assignedExpression, variableKind); if (nameFromExpression != null) { add(getVariableNameSuggestions(variableKind, project, nameFromExpression, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural. } String nameFromParent= getBaseNameFromLocationInParent(assignedExpression); if (nameFromParent != null) { add(getVariableNameSuggestions(variableKind, project, nameFromParent, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural. } } if (expectedType != null) { String[] names= getVariableNameSuggestions(variableKind, project, expectedType, excluded, false); for (int i= 0; i < names.length; i++) { res.add(names[i]); } } if (res.isEmpty()) { return getDefaultVariableNameSuggestions(variableKind, excluded); } return res.toArray(new String[res.size()]); }
@Override protected boolean addInitializer(final VariableDeclarationFragment fragment, final ASTNode declarationNode) { Assert.isNotNull(fragment); final Expression expression= fragment.getAST().newNumberLiteral(DEFAULT_EXPRESSION); if (expression != null) { fragment.setInitializer(expression); } return true; }
@Override protected void addLinkedPositions(final ASTRewrite rewrite, final VariableDeclarationFragment fragment, final LinkedProposalModel positionGroups) { Assert.isNotNull(rewrite); Assert.isNotNull(fragment); final Expression initializer= fragment.getInitializer(); if (initializer != null) { LinkedProposalPositionGroup group= new LinkedProposalPositionGroup(GROUP_INITIALIZER); group.addPosition(rewrite.track(initializer), true); positionGroups.addPositionGroup(group); } }
private void splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, VariableDeclarationStatement originalStatement, List<Expression> sideEffects) { if (sideEffects.size() > 0) { ListRewrite statementRewrite= rewrite.getListRewrite(originalStatement.getParent(), (ChildListPropertyDescriptor) originalStatement.getLocationInParent()); Statement previousStatement= originalStatement; for (int i= 0; i < sideEffects.size(); i++) { Expression sideEffect= sideEffects.get(i); Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect); ExpressionStatement wrapped= rewrite.getAST().newExpressionStatement(movedInit); statementRewrite.insertAfter(wrapped, previousStatement, group); previousStatement= wrapped; } VariableDeclarationStatement newDeclaration= null; List<VariableDeclarationFragment> fragments= originalStatement.fragments(); int fragIndex= fragments.indexOf(frag); ListIterator<VariableDeclarationFragment> fragmentIterator= fragments.listIterator(fragIndex+1); while (fragmentIterator.hasNext()) { VariableDeclarationFragment currentFragment= fragmentIterator.next(); VariableDeclarationFragment movedFragment= (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment); if (newDeclaration == null) { newDeclaration= rewrite.getAST().newVariableDeclarationStatement(movedFragment); Type copiedType= (Type) rewrite.createCopyTarget(originalStatement.getType()); newDeclaration.setType(copiedType); } else { newDeclaration.fragments().add(movedFragment); } } if (newDeclaration != null){ statementRewrite.insertAfter(newDeclaration, previousStatement, group); if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){ rewrite.remove(originalStatement, group); } } } }
private void removeVariableWithInitializer(ASTRewrite rewrite, ASTNode initializerNode, ASTNode statementNode, TextEditGroup group) { boolean performRemove= fForceRemove; if (!performRemove) { ArrayList<Expression> sideEffectNodes= new ArrayList<>(); initializerNode.accept(new SideEffectFinder(sideEffectNodes)); performRemove= sideEffectNodes.isEmpty(); } if (performRemove) { removeStatement(rewrite, statementNode, group); fRemovedAssignmentsCount++; } else { ASTNode initNode = rewrite.createMoveTarget(initializerNode); ExpressionStatement statement = rewrite.getAST().newExpressionStatement((Expression) initNode); rewrite.replace(statementNode, statement, null); fAlteredAssignmentsCount++; } }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { TextEditGroup group= createTextEditGroup(FixMessages.UnusedCodeFix_RemoveCast_description, cuRewrite); ASTRewrite rewrite= cuRewrite.getASTRewrite(); CastExpression cast= fCast; Expression expression= cast.getExpression(); if (expression instanceof ParenthesizedExpression) { Expression childExpression= ((ParenthesizedExpression) expression).getExpression(); if (NecessaryParenthesesChecker.needsParentheses(childExpression, cast, CastExpression.EXPRESSION_PROPERTY)) { expression= childExpression; } } replaceCast(cast, expression, rewrite, group); }
private static void replaceCast(CastExpression castExpression, Expression replacement, ASTRewrite rewrite, TextEditGroup group) { boolean castEnclosedInNecessaryParentheses= castExpression.getParent() instanceof ParenthesizedExpression && NecessaryParenthesesChecker.needsParentheses(castExpression, castExpression.getParent().getParent(), castExpression.getParent().getLocationInParent()); ASTNode toReplace= castEnclosedInNecessaryParentheses ? castExpression.getParent() : castExpression; ASTNode move; if (NecessaryParenthesesChecker.needsParentheses(replacement, toReplace.getParent(), toReplace.getLocationInParent())) { if (replacement.getParent() instanceof ParenthesizedExpression) { move= rewrite.createMoveTarget(replacement.getParent()); } else if (castEnclosedInNecessaryParentheses) { toReplace= castExpression; move= rewrite.createMoveTarget(replacement); } else { ParenthesizedExpression parentheses= replacement.getAST().newParenthesizedExpression(); parentheses.setExpression((Expression) rewrite.createMoveTarget(replacement)); move= parentheses; } } else { move= rewrite.createMoveTarget(replacement); } rewrite.replace(toReplace, move, group); }
static boolean isLeftHandSideOfAssignment(ASTNode node) { Assignment assignment = (Assignment) ASTNodes.getParent(node, ASTNode.ASSIGNMENT); if (assignment != null) { Expression leftHandSide = assignment.getLeftHandSide(); if (leftHandSide == node) { return true; } if (ASTNodes.isParent(node, leftHandSide)) { switch (leftHandSide.getNodeType()) { case ASTNode.SIMPLE_NAME: return true; case ASTNode.FIELD_ACCESS: return node == ((FieldAccess) leftHandSide).getName(); case ASTNode.QUALIFIED_NAME: return node == ((QualifiedName) leftHandSide).getName(); case ASTNode.SUPER_FIELD_ACCESS: return node == ((SuperFieldAccess) leftHandSide).getName(); default: return false; } } } return false; }
@Override public void endVisit(VariableDeclarationFragment node) { if (skipNode(node)) { return; } IVariableBinding binding = node.resolveBinding(); LocalFlowInfo nameInfo = null; Expression initializer = node.getInitializer(); if (binding != null && !binding.isField() && initializer != null) { nameInfo = new LocalFlowInfo(binding, FlowInfo.WRITE, fFlowContext); } GenericSequentialFlowInfo info = processSequential(node, initializer); info.merge(nameInfo, fFlowContext); }
private void endVisitIncDecOperation(Expression node, Expression operand) { if (skipNode(node)) { return; } FlowInfo info = getFlowInfo(operand); if (info instanceof LocalFlowInfo) { // Normally we should do this in the parent node since the write access take place later. // But I couldn't come up with a case where this influences the flow analysis. So I kept // it here to simplify the code. GenericSequentialFlowInfo result = createSequential(node); result.merge(info, fFlowContext); result.merge(new LocalFlowInfo((LocalFlowInfo) info, FlowInfo.WRITE, fFlowContext), fFlowContext); } else { setFlowInfo(node, info); } }
@Override public boolean visit(MethodInvocation node) { Expression exp = node.getExpression(); if (exp != null) { fIgnore.add(node.getName()); } return true; }
public ITypeBinding getTypeBinding(AST ast) { boolean couldBeObject= false; for (int i= 0; i < fResult.size(); i++) { ReturnStatement node= fResult.get(i); Expression expr= node.getExpression(); if (expr != null) { ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding()); if (binding != null) { return binding; } else { couldBeObject= true; } } else { return ast.resolveWellKnownType("void"); //$NON-NLS-1$ } } if (couldBeObject) { return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } return ast.resolveWellKnownType("void"); //$NON-NLS-1$ }
public static void addMethodReturnsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) throws JavaModelException { CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof ReturnStatement)) { return; } ReturnStatement returnStatement= (ReturnStatement) selectedNode; Expression expression= returnStatement.getExpression(); if (expression == null) { return; } BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { MethodDeclaration methDecl= (MethodDeclaration) decl; Type retType= methDecl.getReturnType2(); if (retType == null || retType.resolveBinding() == null) { return; } TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals); } }
@Override protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) { ScopeAnalyzer analyzer= new ScopeAnalyzer(root); IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(root, returnOffset, 0); ASTNode varDeclFrag= ASTResolving.findAncestor(finder.getCoveringNode(), ASTNode.VARIABLE_DECLARATION_FRAGMENT); IVariableBinding varDeclFragBinding= null; if (varDeclFrag != null) varDeclFragBinding= ((VariableDeclarationFragment) varDeclFrag).resolveBinding(); for (int i= 0; i < bindings.length; i++) { IVariableBinding curr= (IVariableBinding) bindings[i]; ITypeBinding type= curr.getType(); // Bindings are compared to make sure that a lambda does not return a variable which is yet to be initialised. if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr) && !Bindings.equals(curr, varDeclFragBinding)) { if (result == null) { result= ast.newSimpleName(curr.getName()); } addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName()); } } return result; }
private Expression evaluateArgumentExpressions(AST ast, ITypeBinding requiredType, String key) { CompilationUnit root= (CompilationUnit) fCallerNode.getRoot(); int offset= fCallerNode.getStartPosition(); Expression best= null; ITypeBinding bestType= null; ScopeAnalyzer analyzer= new ScopeAnalyzer(root); IBinding[] bindings= analyzer.getDeclarationsInScope(offset, ScopeAnalyzer.VARIABLES); for (int i= 0; i < bindings.length; i++) { IVariableBinding curr= (IVariableBinding) bindings[i]; ITypeBinding type= curr.getType(); if (type != null && canAssign(type, requiredType) && testModifier(curr)) { if (best == null || isMoreSpecific(bestType, type)) { best= ast.newSimpleName(curr.getName()); bestType= type; } } } Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, requiredType); if (best == null) { best= defaultExpression; } return best; }
private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List<IMethodBinding> similarElements, ASTNode invocationNode, List<Expression> arguments, Collection<CUCorrectionProposal> 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); } } }
private static ChangeDescription[] createSignatureChangeDescription(int[] indexOfDiff, int nDiffs, ITypeBinding[] paramTypes, List<Expression> arguments, ITypeBinding[] argTypes) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; for (int i= 0; i < nDiffs; i++) { int diffIndex= indexOfDiff[i]; Expression arg= arguments.get(diffIndex); String name= getExpressionBaseName(arg); ITypeBinding argType= argTypes[diffIndex]; if (argType.isWildcardType()) { argType= ASTResolving.normalizeWildcardType(argType, true, arg.getAST()); if (argType== null) { return null; } } changeDesc[diffIndex]= new EditDescription(argType, name); } return changeDesc; }
private static String getExpressionBaseName(Expression expr) { IBinding argBinding= Bindings.resolveExpressionBinding(expr, true); if (argBinding instanceof IVariableBinding) { IJavaProject project= null; ASTNode root= expr.getRoot(); if (root instanceof CompilationUnit) { ITypeRoot typeRoot= ((CompilationUnit) root).getTypeRoot(); if (typeRoot != null) { project= typeRoot.getJavaProject(); } } return StubUtility.getBaseName((IVariableBinding)argBinding, project); } if (expr instanceof SimpleName) { return ((SimpleName) expr).getIdentifier(); } return null; }