Java Code Examples for org.eclipse.jdt.core.dom.Expression#accept()

The following examples show how to use org.eclipse.jdt.core.dom.Expression#accept() . 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: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Set<String> findVariableReferences(List<?> arguments) {
    final Set<String> refs = new HashSet<>();
    for (Object argumentObj : arguments) {
        Expression argument = (Expression) argumentObj;
        argument.accept(new ASTVisitor() {

            @Override
            public boolean visit(SimpleName node) {
                if (!(node.getParent() instanceof Type)) {
                    refs.add(node.getFullyQualifiedName());
                }
                return true;
            }

        });
    }
    return refs;
}
 
Example 2
Source File: AbstractExpression.java    From RefactoringMiner with MIT License 6 votes vote down vote up
public AbstractExpression(CompilationUnit cu, String filePath, Expression expression, CodeElementType codeElementType) {
  	this.locationInfo = new LocationInfo(cu, filePath, expression, codeElementType);
  	Visitor visitor = new Visitor(cu, filePath);
  	expression.accept(visitor);
this.variables = visitor.getVariables();
this.types = visitor.getTypes();
this.variableDeclarations = visitor.getVariableDeclarations();
this.methodInvocationMap = visitor.getMethodInvocationMap();
this.anonymousClassDeclarations = visitor.getAnonymousClassDeclarations();
this.stringLiterals = visitor.getStringLiterals();
this.numberLiterals = visitor.getNumberLiterals();
this.nullLiterals = visitor.getNullLiterals();
this.booleanLiterals = visitor.getBooleanLiterals();
this.typeLiterals = visitor.getTypeLiterals();
this.creationMap = visitor.getCreationMap();
this.infixOperators = visitor.getInfixOperators();
this.arrayAccesses = visitor.getArrayAccesses();
this.prefixExpressions = visitor.getPrefixExpressions();
this.postfixExpressions = visitor.getPostfixExpressions();
this.arguments = visitor.getArguments();
this.ternaryOperatorExpressions = visitor.getTernaryOperatorExpressions();
this.lambdas = visitor.getLambdas();
  	this.expression = expression.toString();
  	this.owner = null;
  }
 
Example 3
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(MethodInvocation node) {
	Expression expression= node.getExpression();
	if (expression == null) {
		IMethodBinding binding= node.resolveMethodBinding();
		if (binding != null) {
			if (isAccessToOuter(binding.getDeclaringClass())) {
				fMethodAccesses.add(node);
			}
		}
	} else {
		expression.accept(this);
	}
	List<Expression> arguments= node.arguments();
	for (int i= 0; i < arguments.size(); i++) {
		arguments.get(i).accept(this);
	}
	return false;
}
 
Example 4
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean replaceMarker(final ASTRewrite rewrite, final Expression qualifier, Expression assignedValue, final NullLiteral marker) {
	class MarkerReplacer extends ASTVisitor {

		private boolean fReplaced= false;

		@Override
		public boolean visit(NullLiteral node) {
			if (node == marker) {
				rewrite.replace(node, rewrite.createCopyTarget(qualifier), null);
				fReplaced= true;
				return false;
			}
			return true;
		}
	}
	if (assignedValue != null && qualifier != null) {
		MarkerReplacer visitor= new MarkerReplacer();
		assignedValue.accept(visitor);
		return visitor.fReplaced;
	}
	return false;
}
 
Example 5
Source File: BindingSignature.java    From JDeodorant with MIT License 5 votes vote down vote up
public BindingSignature(AbstractExpression expression) {
	if(expression != null) {
		Expression expr = expression.getExpression();
		expr = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(expr);
		BindingSignatureVisitor visitor = new BindingSignatureVisitor();
		expr.accept(visitor);
		this.bindingKeys = visitor.getBindingKeys();
		if(bindingKeys.isEmpty())
			bindingKeys.add(expr.toString());
	}
	else {
		this.bindingKeys = new ArrayList<String>();
		bindingKeys.add("this");
	}
}
 
Example 6
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 7
Source File: ImportReferencesCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void evalQualifyingExpression(Expression expr, Name selector) {
	if (expr != null) {
		if (expr instanceof Name) {
			Name name= (Name) expr;
			possibleTypeRefFound(name);
			possibleStaticImportFound(name);
		} else {
			expr.accept(this);
		}
	} else if (selector != null) {
		possibleStaticImportFound(selector);
	}
}
 
Example 8
Source File: CodeScopeBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.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 9
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void checkTempInitializerForLocalTypeUsage() {
  	Expression initializer= fTempDeclarationNode.getInitializer();
  	if (initializer == null)
       return;

IMethodBinding declaringMethodBinding= getMethodDeclaration().resolveBinding();
ITypeBinding[] methodTypeParameters= declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
   LocalTypeAndVariableUsageAnalyzer localTypeAnalyer= new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
   initializer.accept(localTypeAnalyer);
   fInitializerUsesLocalTypes= ! localTypeAnalyer.getUsageOfEnclosingNodes().isEmpty();
  }
 
Example 10
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 FieldAccess node) {
	Assert.isNotNull(node);
	final Expression expression= node.getExpression();
	final IVariableBinding variable= node.resolveFieldBinding();
	final AST ast= fRewrite.getAST();
	if (expression instanceof ThisExpression) {
		if (Bindings.equals(fTarget, variable)) {
			if (fAnonymousClass > 0) {
				final ThisExpression target= ast.newThisExpression();
				target.setQualifier(ast.newSimpleName(fTargetType.getElementName()));
				fRewrite.replace(node, target, null);
			} else
				fRewrite.replace(node, ast.newThisExpression(), null);
			return false;
		} else {
			expression.accept(this);
			return false;
		}
	} else if (expression instanceof FieldAccess) {
		final FieldAccess access= (FieldAccess) expression;
		final IBinding binding= access.getName().resolveBinding();
		if (access.getExpression() instanceof ThisExpression && Bindings.equals(fTarget, binding)) {
			ASTNode newFieldAccess= getFieldReference(node.getName(), fRewrite);
			fRewrite.replace(node, newFieldAccess, null);
			return false;
		}
	} else if (expression != null) {
		expression.accept(this);
		return false;
	}
	return true;
}
 
Example 11
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public void appendAsRichString(final Expression expression) {
  if ((expression instanceof StringLiteral)) {
    this.appendToBuffer(this.richTextValue(((StringLiteral)expression)));
  } else {
    final boolean stringConcat = ((expression instanceof InfixExpression) && 
      this._aSTFlattenerUtils.canConvertToRichText(((InfixExpression) expression)));
    if ((!stringConcat)) {
      this.appendToBuffer("�");
    }
    expression.accept(this);
    if ((!stringConcat)) {
      this.appendToBuffer("�");
    }
  }
}
 
Example 12
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void checkTempInitializerForLocalTypeUsage() throws JavaModelException {
	Expression initializer = getSelectedExpression().getAssociatedExpression();
	IMethodBinding declaringMethodBinding = getMethodDeclaration().resolveBinding();
	ITypeBinding[] methodTypeParameters = declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
	LocalTypeAndVariableUsageAnalyzer localTypeAnalyer = new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
	initializer.accept(localTypeAnalyer);
	fInitializerUsesLocalTypes = !localTypeAnalyer.getUsageOfEnclosingNodes().isEmpty();
}
 
Example 13
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
public StringBuffer handleInfixRightSide(final InfixExpression infixParent, final InfixExpression.Operator operator, final Expression rightSide) {
  StringBuffer _switchResult = null;
  boolean _matched = false;
  if (Objects.equal(operator, InfixExpression.Operator.XOR)) {
    _matched=true;
    StringBuffer _xifexpression = null;
    boolean _isBooleanInvolved = this.isBooleanInvolved(infixParent);
    if (_isBooleanInvolved) {
      StringBuffer _xblockexpression = null;
      {
        this.appendToBuffer(".xor(");
        rightSide.accept(this);
        _xblockexpression = this.appendToBuffer(")");
      }
      _xifexpression = _xblockexpression;
    } else {
      StringBuffer _xblockexpression_1 = null;
      {
        this.appendToBuffer(".bitwiseXor(");
        rightSide.accept(this);
        _xblockexpression_1 = this.appendToBuffer(")");
      }
      _xifexpression = _xblockexpression_1;
    }
    _switchResult = _xifexpression;
  }
  if (!_matched) {
    if (Objects.equal(operator, InfixExpression.Operator.AND)) {
      _matched=true;
    }
    if (!_matched) {
      if (Objects.equal(operator, InfixExpression.Operator.OR)) {
        _matched=true;
      }
    }
    if (_matched) {
      StringBuffer _xifexpression_1 = null;
      boolean _isBooleanInvolved_1 = this.isBooleanInvolved(infixParent);
      boolean _not = (!_isBooleanInvolved_1);
      if (_not) {
        StringBuffer _xblockexpression_2 = null;
        {
          StringConcatenation _builder = new StringConcatenation();
          _builder.append(".bitwise");
          String _xifexpression_2 = null;
          boolean _equals = Objects.equal(operator, InfixExpression.Operator.AND);
          if (_equals) {
            _xifexpression_2 = "And";
          } else {
            _xifexpression_2 = "Or";
          }
          _builder.append(_xifexpression_2);
          _builder.append("(");
          this.appendToBuffer(_builder.toString());
          rightSide.accept(this);
          _xblockexpression_2 = this.appendToBuffer(")");
        }
        _xifexpression_1 = _xblockexpression_2;
      } else {
        this.appendSpaceToBuffer();
        String _string = operator.toString();
        String _multiply = this.operator_multiply(_string, 2);
        this.appendToBuffer(_multiply);
        this.appendSpaceToBuffer();
        rightSide.accept(this);
      }
      _switchResult = _xifexpression_1;
    }
  }
  if (!_matched) {
    if (Objects.equal(operator, InfixExpression.Operator.EQUALS)) {
      _matched=true;
      this.appendToBuffer(" === ");
      rightSide.accept(this);
    }
  }
  if (!_matched) {
    if (Objects.equal(operator, InfixExpression.Operator.NOT_EQUALS)) {
      _matched=true;
      this.appendToBuffer(" !== ");
      rightSide.accept(this);
    }
  }
  if (!_matched) {
    {
      this.appendSpaceToBuffer();
      this.appendToBuffer(operator.toString());
      this.appendSpaceToBuffer();
      rightSide.accept(this);
    }
  }
  return _switchResult;
}
 
Example 14
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void perform(Expression initializer) {
	initializer.accept(this);
	addExplicitTypeArgumentsIfNecessary(initializer);
}
 
Example 15
Source File: CallInliner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean canInline(Expression actualParameter, ParameterData formalParameter) {
	InlineEvaluator evaluator= new InlineEvaluator(formalParameter);
	actualParameter.accept(evaluator);
	return evaluator.getResult();
}
 
Example 16
Source File: AccessAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean visit(Assignment node) {
	Expression leftHandSide= node.getLeftHandSide();
	if (!considerBinding(resolveBinding(leftHandSide), leftHandSide))
		return true;

	checkParent(node);
	Expression rightHandSide= node.getRightHandSide();
	if (!fIsFieldFinal) {
		// Write access.
		AST ast= node.getAST();
		MethodInvocation invocation= ast.newMethodInvocation();
		invocation.setName(ast.newSimpleName(fSetter));
		fReferencingSetter= true;
		Expression receiver= getReceiver(leftHandSide);
		if (receiver != null)
			invocation.setExpression((Expression)fRewriter.createCopyTarget(receiver));
		List<Expression> arguments= invocation.arguments();
		if (node.getOperator() == Assignment.Operator.ASSIGN) {
			arguments.add((Expression)fRewriter.createCopyTarget(rightHandSide));
		} else {
			// This is the compound assignment case: field+= 10;
			InfixExpression exp= ast.newInfixExpression();
			exp.setOperator(ASTNodes.convertToInfixOperator(node.getOperator()));
			MethodInvocation getter= ast.newMethodInvocation();
			getter.setName(ast.newSimpleName(fGetter));
			fReferencingGetter= true;
			if (receiver != null)
				getter.setExpression((Expression)fRewriter.createCopyTarget(receiver));
			exp.setLeftOperand(getter);
			Expression rhs= (Expression)fRewriter.createCopyTarget(rightHandSide);
			if (NecessaryParenthesesChecker.needsParenthesesForRightOperand(rightHandSide, exp, leftHandSide.resolveTypeBinding())) {
				ParenthesizedExpression p= ast.newParenthesizedExpression();
				p.setExpression(rhs);
				rhs= p;
			}
			exp.setRightOperand(rhs);
			arguments.add(exp);
		}
		fRewriter.replace(node, invocation, createGroupDescription(WRITE_ACCESS));
	}
	rightHandSide.accept(this);
	return false;
}
 
Example 17
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean visit(final ClassInstanceCreation node) {
  Expression _expression = node.getExpression();
  boolean _tripleNotEquals = (_expression != null);
  if (_tripleNotEquals) {
    node.getExpression().accept(this);
    this.appendToBuffer(".");
  }
  boolean _isLambdaCase = this._aSTFlattenerUtils.isLambdaCase(node);
  if (_isLambdaCase) {
    if (this.fallBackStrategy) {
      this.appendToBuffer("(");
    }
    this.appendToBuffer("[");
    Object _get = node.getAnonymousClassDeclaration().bodyDeclarations().get(0);
    final MethodDeclaration method = ((MethodDeclaration) _get);
    boolean _isEmpty = method.parameters().isEmpty();
    boolean _not = (!_isEmpty);
    if (_not) {
      this.visitAllSeparatedByComma(method.parameters());
      this.appendToBuffer("|");
    } else {
      if (this.fallBackStrategy) {
        this.appendToBuffer("|");
      }
    }
    this.visitAll(method.getBody().statements());
    this.appendToBuffer("]");
    if (this.fallBackStrategy) {
      this.appendToBuffer(" as ");
      boolean _isEmpty_1 = node.typeArguments().isEmpty();
      boolean _not_1 = (!_isEmpty_1);
      if (_not_1) {
        this.appendTypeParameters(node.typeArguments());
      }
      node.getType().accept(this);
      this.appendToBuffer(")");
    }
  } else {
    this.appendToBuffer("new ");
    boolean _isEmpty_2 = node.typeArguments().isEmpty();
    boolean _not_2 = (!_isEmpty_2);
    if (_not_2) {
      this.appendTypeParameters(node.typeArguments());
    }
    node.getType().accept(this);
    this.appendToBuffer("(");
    for (Iterator<Expression> it = node.arguments().iterator(); it.hasNext();) {
      {
        Expression e = it.next();
        e.accept(this);
        boolean _hasNext = it.hasNext();
        if (_hasNext) {
          this.appendToBuffer(",");
        }
      }
    }
    this.appendToBuffer(")");
    AnonymousClassDeclaration _anonymousClassDeclaration = node.getAnonymousClassDeclaration();
    boolean _tripleNotEquals_1 = (_anonymousClassDeclaration != null);
    if (_tripleNotEquals_1) {
      node.getAnonymousClassDeclaration().accept(this);
    }
  }
  return false;
}
 
Example 18
Source File: AccessAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean visit(Assignment node) {
	Expression leftHandSide = node.getLeftHandSide();
	if (!considerBinding(resolveBinding(leftHandSide), leftHandSide)) {
		return true;
	}

	checkParent(node);
	Expression rightHandSide = node.getRightHandSide();
	if (!fIsFieldFinal) {
		// Write access.
		AST ast = node.getAST();
		MethodInvocation invocation = ast.newMethodInvocation();
		invocation.setName(ast.newSimpleName(fSetter));
		fReferencingSetter = true;
		Expression receiver = getReceiver(leftHandSide);
		if (receiver != null) {
			invocation.setExpression((Expression) fRewriter.createCopyTarget(receiver));
		}
		List<Expression> arguments = invocation.arguments();
		if (node.getOperator() == Assignment.Operator.ASSIGN) {
			arguments.add((Expression) fRewriter.createCopyTarget(rightHandSide));
		} else {
			// This is the compound assignment case: field+= 10;
			InfixExpression exp = ast.newInfixExpression();
			exp.setOperator(ASTNodes.convertToInfixOperator(node.getOperator()));
			MethodInvocation getter = ast.newMethodInvocation();
			getter.setName(ast.newSimpleName(fGetter));
			fReferencingGetter = true;
			if (receiver != null) {
				getter.setExpression((Expression) fRewriter.createCopyTarget(receiver));
			}
			exp.setLeftOperand(getter);
			Expression rhs = (Expression) fRewriter.createCopyTarget(rightHandSide);
			if (NecessaryParenthesesChecker.needsParenthesesForRightOperand(rightHandSide, exp, leftHandSide.resolveTypeBinding())) {
				ParenthesizedExpression p = ast.newParenthesizedExpression();
				p.setExpression(rhs);
				rhs = p;
			}
			exp.setRightOperand(rhs);
			arguments.add(exp);
		}
		fRewriter.replace(node, invocation, createGroupDescription(WRITE_ACCESS));
	}
	rightHandSide.accept(this);
	return false;
}
 
Example 19
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Remove the field or variable declaration including the initializer.
 * @param rewrite the AST rewriter to use
 * @param reference a reference to the variable to remove
 * @param group the text edit group to use
 */
private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference, TextEditGroup group) {
	ASTNode parent= reference.getParent();
	while (parent instanceof QualifiedName) {
		parent= parent.getParent();
	}
	if (parent instanceof FieldAccess) {
		parent= parent.getParent();
	}

	int nameParentType= parent.getNodeType();
	if (nameParentType == ASTNode.ASSIGNMENT) {
		Assignment assignment= (Assignment) parent;
		Expression rightHand= assignment.getRightHandSide();

		ASTNode assignParent= assignment.getParent();
		if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
			removeVariableWithInitializer(rewrite, rightHand, assignParent, group);
		}	else {
			rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), group);
		}
	} else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
		rewrite.remove(parent, group);
	} else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
		VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
		ASTNode varDecl= frag.getParent();
		List<VariableDeclarationFragment> fragments;
		if (varDecl instanceof VariableDeclarationExpression) {
			fragments= ((VariableDeclarationExpression) varDecl).fragments();
		} else if (varDecl instanceof FieldDeclaration) {
			fragments= ((FieldDeclaration) varDecl).fragments();
		} else {
			fragments= ((VariableDeclarationStatement) varDecl).fragments();
		}
		Expression initializer = frag.getInitializer();
		ArrayList<Expression> sideEffects= new ArrayList<Expression>();
		if (initializer != null) {
			initializer.accept(new SideEffectFinder(sideEffects));
		}
		boolean sideEffectInitializer= sideEffects.size() > 0;
		if (fragments.size() == fUnusedNames.length) {
			if (fForceRemove) {
				rewrite.remove(varDecl, group);
				return;
			}
			if (parent.getParent() instanceof FieldDeclaration) {
				rewrite.remove(varDecl, group);
				return;
			}
			if (sideEffectInitializer) {
				Statement[] wrapped= new Statement[sideEffects.size()];
				for (int i= 0; i < wrapped.length; i++) {
					Expression sideEffect= sideEffects.get(i);
					Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect);
					wrapped[i]= rewrite.getAST().newExpressionStatement(movedInit);
				}
				StatementRewrite statementRewrite= new StatementRewrite(rewrite, new ASTNode[] { varDecl });
				statementRewrite.replace(wrapped, group);
			} else {
				rewrite.remove(varDecl, group);
			}
		} else {
			if (fForceRemove) {
				rewrite.remove(frag, group);
				return;
			}
			//multiple declarations in one line
			ASTNode declaration = parent.getParent();
			if (declaration instanceof FieldDeclaration) {
				rewrite.remove(frag, group);
				return;
			}
			if (declaration instanceof VariableDeclarationStatement) {
				splitUpDeclarations(rewrite, group, frag, (VariableDeclarationStatement) declaration, sideEffects);
				rewrite.remove(frag, group);
				return;
			}
			if (declaration instanceof VariableDeclarationExpression) {
				//keep constructors and method invocations
				if (!sideEffectInitializer){
					rewrite.remove(frag, group);
				}
			}
		}
	} else if (nameParentType == ASTNode.POSTFIX_EXPRESSION || nameParentType == ASTNode.PREFIX_EXPRESSION) {
		Expression expression= (Expression)parent;
		ASTNode expressionParent= expression.getParent();
		if (expressionParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
			removeStatement(rewrite, expressionParent, group);
		} else {
			rewrite.remove(expression, group);
		}
	}
}