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

The following examples show how to use org.eclipse.jdt.core.dom.Expression. 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
/**
 * Proposes a getter for this field.
 * 
 * @param context the proposal parameter
 * @param relevance relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addGetterProposal(ProposalParameter context, int relevance) {
	IMethodBinding method= findGetter(context);
	if (method != null) {
		Expression mi= createMethodInvocation(context, method, null);
		context.astRewrite.replace(context.accessNode, mi, null);

		String label= Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithgetter_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 #2
Source Project: JDeodorant   Author: tsantalis   File: PDGNodeMapping.java    License: MIT License 6 votes vote down vote up
public boolean isVoidMethodCallDifferenceCoveringEntireStatement() {
	boolean expression1IsVoidMethodCallDifference = false;
	boolean expression2IsVoidMethodCallDifference = false;
	for(ASTNodeDifference difference : nodeDifferences) {
		Expression expr1 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(difference.getExpression1().getExpression());
		Expression expr2 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(difference.getExpression2().getExpression());
		for(PreconditionViolation violation : getPreconditionViolations()) {
			if(violation instanceof ExpressionPreconditionViolation && violation.getType().equals(PreconditionViolationType.EXPRESSION_DIFFERENCE_IS_VOID_METHOD_CALL)) {
				ExpressionPreconditionViolation expressionViolation = (ExpressionPreconditionViolation)violation;
				Expression expression = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(expressionViolation.getExpression().getExpression());
				if(expression.equals(expr1)) {
					if(expr1.getParent() instanceof ExpressionStatement) {
						expression1IsVoidMethodCallDifference = true;
					}
				}
				if(expression.equals(expr2)) {
					if(expr2.getParent() instanceof ExpressionStatement) {
						expression2IsVoidMethodCallDifference = true;
					}
				}
			}
		}
	}
	return expression1IsVoidMethodCallDifference && expression2IsVoidMethodCallDifference;
}
 
Example #3
Source Project: JDeodorant   Author: tsantalis   File: ReplaceTypeCodeWithStateStrategy.java    License: MIT License 6 votes vote down vote up
private Set<MethodDeclaration> getMethodDeclarationsWithinAnonymousClassDeclarations(FieldDeclaration fieldDeclaration) {
	Set<MethodDeclaration> methods = new LinkedHashSet<MethodDeclaration>();
	List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
	for(VariableDeclarationFragment fragment : fragments) {
		Expression expression = fragment.getInitializer();
		if(expression != null && expression instanceof ClassInstanceCreation) {
			ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)expression;
			AnonymousClassDeclaration anonymousClassDeclaration = classInstanceCreation.getAnonymousClassDeclaration();
			if(anonymousClassDeclaration != null) {
				List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
				for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
					if(bodyDeclaration instanceof MethodDeclaration)
						methods.add((MethodDeclaration)bodyDeclaration);
				}
			}
		}
	}
	return methods;
}
 
Example #4
Source Project: eclipse.jdt.ls   Author: eclipse   File: GetterSetterCorrectionSubProcessor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Proposes a getter for this field.
 *
 * @param context
 *            the proposal parameter
 * @param relevance
 *            relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addGetterProposal(ProposalParameter context, int relevance) {
	IMethodBinding method = findGetter(context);
	if (method != null) {
		Expression mi = createMethodInvocation(context, method, null);
		context.astRewrite.replace(context.accessNode, mi, null);

		String label = Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithgetter_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 #5
/**
 * Is the specified name a target access?
 *
 * @param name
 *            the name to check
 * @return <code>true</code> if this name is a target access,
 *         <code>false</code> otherwise
 */
protected boolean isTargetAccess(final Name name) {
	Assert.isNotNull(name);
	final IBinding binding= name.resolveBinding();
	if (Bindings.equals(fTarget, binding))
		return true;
	if (name.getParent() instanceof FieldAccess) {
		final FieldAccess access= (FieldAccess) name.getParent();
		final Expression expression= access.getExpression();
		if (expression instanceof Name)
			return isTargetAccess((Name) expression);
	} else if (name instanceof QualifiedName) {
		final QualifiedName qualified= (QualifiedName) name;
		if (qualified.getQualifier() != null)
			return isTargetAccess(qualified.getQualifier());
	}
	return false;
}
 
Example #6
Source Project: eclipse.jdt.ls   Author: eclipse   File: ExtractFieldRefactoring.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private IExpressionFragment getSelectedExpression() throws JavaModelException {
	if (fSelectedExpression != null) {
		return fSelectedExpression;
	}
	IASTFragment selectedFragment = ASTFragmentFactory.createFragmentForSourceRange(new SourceRange(fSelectionStart, fSelectionLength), fCompilationUnitNode, fCu);

	if (selectedFragment instanceof IExpressionFragment && !Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) {
		fSelectedExpression = (IExpressionFragment) selectedFragment;
	} else if (selectedFragment != null) {
		if (selectedFragment.getAssociatedNode() instanceof ExpressionStatement) {
			ExpressionStatement exprStatement = (ExpressionStatement) selectedFragment.getAssociatedNode();
			Expression expression = exprStatement.getExpression();
			fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(expression);
		} else if (selectedFragment.getAssociatedNode() instanceof Assignment) {
			Assignment assignment = (Assignment) selectedFragment.getAssociatedNode();
			fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(assignment);
		}
	}

	if (fSelectedExpression != null && Checks.isEnumCase(fSelectedExpression.getAssociatedExpression().getParent())) {
		fSelectedExpression = null;
	}

	return fSelectedExpression;
}
 
Example #7
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: AccessAnalyzer.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(PrefixExpression node) {
	Expression operand= node.getOperand();
	if (!considerBinding(resolveBinding(operand), operand))
		return true;

	PrefixExpression.Operator operator= node.getOperator();
	if (operator != PrefixExpression.Operator.INCREMENT && operator != PrefixExpression.Operator.DECREMENT)
		return true;

	checkParent(node);

	fRewriter.replace(node,
		createInvocation(node.getAST(), node.getOperand(), node.getOperator().toString()),
		createGroupDescription(PREFIX_ACCESS));
	return false;
}
 
Example #8
Source Project: junion   Author: TehLeo   File: BaseTranslator.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Expression methodB(String methodName, Type castType, Object... args) {
		MethodInvocation p = ast.newMethodInvocation();
		p.setExpression(name(MEM0_B));
//		p.setName(name(Translator.StringCache.getString(
//				type,
//				t,
//				opsymbol)));
		p.setName(name(methodName));

		for(Object arg : args)
			p.arguments().add(arg);
		
		if(castType != null) {
			CastExpression cast = ast.newCastExpression();			
			cast.setType(castType);
			cast.setExpression(p);
			cast.setProperty(TYPEBIND_PROP, FieldType.OBJECT);
			return cast;
		}
		return p;
	}
 
Example #9
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	ASTNode groupNode= getGroupRoot();

	List<Expression> allOperands= findGroupMembersInOrderFor(getGroupRoot());
	if (allOperands.size() == fOperands.size()) {
		if (replacement instanceof Name && groupNode.getParent() instanceof ParenthesizedExpression) {
			// replace including the parenthesized expression around it
			rewrite.replace(groupNode.getParent(), replacement, textEditGroup);
		} else {
			rewrite.replace(groupNode, replacement, textEditGroup);
		}
		return;
	}

	rewrite.replace(fOperands.get(0), replacement, textEditGroup);
	int first= allOperands.indexOf(fOperands.get(0));
	int after= first + fOperands.size();
	for (int i= first + 1; i < after; i++) {
		rewrite.remove(allOperands.get(i), textEditGroup);
	}
}
 
Example #10
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: MIT License 6 votes vote down vote up
private void replaceThisExpressionWithSourceClassParameterInMethodInvocationArguments(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	ExpressionExtractor extractor = new ExpressionExtractor();
	List<Expression> methodInvocations = extractor.getMethodInvocations(newMethodDeclaration.getBody());
	for(Expression invocation : methodInvocations) {
		if(invocation instanceof MethodInvocation) {
			MethodInvocation methodInvocation = (MethodInvocation)invocation;
			List<Expression> arguments = methodInvocation.arguments();
			for(Expression argument : arguments) {
				if(argument instanceof ThisExpression) {
					SimpleName parameterName = null;
					if(!additionalArgumentsAddedToMovedMethod.contains("this")) {
						parameterName = addSourceClassParameterToMovedMethod(newMethodDeclaration, targetRewriter);
					}
					else {
						AST ast = newMethodDeclaration.getAST();
						String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier();
						parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0)))));
					}
					ListRewrite argumentRewrite = targetRewriter.getListRewrite(methodInvocation, MethodInvocation.ARGUMENTS_PROPERTY);
					argumentRewrite.replace(argument, parameterName, null);
				}
			}
		}
	}
}
 
Example #11
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: MIT License 6 votes vote down vote up
private void modifySourceStaticMethodInvocationsInTargetClass(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	ExpressionExtractor extractor = new ExpressionExtractor();	
	List<Expression> sourceMethodInvocations = extractor.getMethodInvocations(sourceMethod.getBody());
	List<Expression> newMethodInvocations = extractor.getMethodInvocations(newMethodDeclaration.getBody());
	int i = 0;
	for(Expression expression : sourceMethodInvocations) {
		if(expression instanceof MethodInvocation) {
			MethodInvocation methodInvocation = (MethodInvocation)expression;
			IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
			if((methodBinding.getModifiers() & Modifier.STATIC) != 0 &&
					methodBinding.getDeclaringClass().isEqualTo(sourceTypeDeclaration.resolveBinding()) &&
					!additionalMethodsToBeMoved.containsKey(methodInvocation)) {
				AST ast = newMethodDeclaration.getAST();
				SimpleName qualifier = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier());
				targetRewriter.set(newMethodInvocations.get(i), MethodInvocation.EXPRESSION_PROPERTY, qualifier, null);
				this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding());
			}
		}
		i++;
	}
}
 
Example #12
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: ClientBundleValidator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void validateSourceAnnotationValues(Annotation annotation) throws JavaModelException {
  Expression exp = JavaASTUtils.getAnnotationValue(annotation);
  if (exp == null) {
    return;
  }

  // There will usually just be one string value
  if (exp instanceof StringLiteral) {
    validateSourceAnnotationValue((StringLiteral) exp);
  }

  // But there could be multiple values; if so, check each one.
  if (exp instanceof ArrayInitializer) {
    ArrayInitializer array = (ArrayInitializer) exp;

    for (Expression item : (List<Expression>) array.expressions()) {
      if (item instanceof StringLiteral) {
        validateSourceAnnotationValue((StringLiteral) item);
      }
    }
  }
}
 
Example #13
Source Project: RefactoringMiner   Author: tsantalis   File: ObjectCreation.java    License: MIT License 6 votes vote down vote up
public ObjectCreation(CompilationUnit cu, String filePath, ClassInstanceCreation creation) {
	this.locationInfo = new LocationInfo(cu, filePath, creation, CodeElementType.CLASS_INSTANCE_CREATION);
	this.type = UMLType.extractTypeObject(cu, filePath, creation.getType(), 0);
	this.typeArguments = creation.arguments().size();
	this.arguments = new ArrayList<String>();
	List<Expression> args = creation.arguments();
	for(Expression argument : args) {
		this.arguments.add(argument.toString());
	}
	if(creation.getExpression() != null) {
		this.expression = creation.getExpression().toString();
	}
	if(creation.getAnonymousClassDeclaration() != null) {
		this.anonymousClassDeclaration = creation.getAnonymousClassDeclaration().toString();
	}
}
 
Example #14
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: MoveStaticMemberAnalyzer.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected void rewrite(MethodInvocation node, ITypeBinding type) {
	Expression exp= node.getExpression();
	if (exp == null) {
		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(node, fCuRewrite.getImportRewrite());
		Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST(), context);
		fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
		exp= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
		fCuRewrite.getASTRewrite().set(node, MethodInvocation.EXPRESSION_PROPERTY, exp, fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
		fNeedsImport= true;
	} else if (exp instanceof Name) {
		rewriteName((Name)exp, type);
	} else {
		rewriteExpression(node, exp, type);
	}
	fProcessed.add(node.getName());
}
 
Example #15
Source Project: JDeodorant   Author: tsantalis   File: AbstractControlStructureUtilities.java    License: MIT License 6 votes vote down vote up
private static boolean isSameAssignee(Assignment assignment1, Assignment assignment2)
{
	Expression assignee1 = assignment1.getLeftHandSide();
	Expression assignee2 = assignment2.getLeftHandSide();
	IBinding binding1 = null;
	IBinding binding2 = null;
	if (assignee1 instanceof Name && assignee2 instanceof Name)
	{
		binding1 = ((Name)assignee1).resolveBinding();
		binding2 = ((Name)assignee2).resolveBinding();
	}
	else if (assignee1 instanceof FieldAccess && assignee2 instanceof FieldAccess)
	{
		binding1 = ((FieldAccess)assignee1).resolveFieldBinding();
		binding2 = ((FieldAccess)assignee2).resolveFieldBinding();
	}
	return (binding1 != null && binding2 != null &&
			binding1.getKind() == IBinding.VARIABLE && binding2.getKind() == IBinding.VARIABLE &&
			binding1.isEqualTo(binding2));
}
 
Example #16
Source Project: eclipse.jdt.ls   Author: eclipse   File: AssociativeInfixExpressionFragment.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	ASTNode groupNode = getGroupRoot();

	List<Expression> allOperands = findGroupMembersInOrderFor(getGroupRoot());
	if (allOperands.size() == fOperands.size()) {
		if (replacement instanceof Name && groupNode.getParent() instanceof ParenthesizedExpression) {
			// replace including the parenthesized expression around it
			rewrite.replace(groupNode.getParent(), replacement, textEditGroup);
		} else {
			rewrite.replace(groupNode, replacement, textEditGroup);
		}
		return;
	}

	rewrite.replace(fOperands.get(0), replacement, textEditGroup);
	int first = allOperands.indexOf(fOperands.get(0));
	int after = first + fOperands.size();
	for (int i = first + 1; i < after; i++) {
		rewrite.remove(allOperands.get(i), textEditGroup);
	}
}
 
Example #17
Source Project: JDeodorant   Author: tsantalis   File: MethodDeclarationUtility.java    License: MIT License 6 votes vote down vote up
public static AbstractVariable processMethodInvocationExpression(Expression expression) {
	if(expression != null) {
		if(expression instanceof QualifiedName) {
			QualifiedName qualifiedName = (QualifiedName)expression;
			return createVariable(qualifiedName.getName(), null);
		}
		else if(expression instanceof FieldAccess) {
			FieldAccess fieldAccess = (FieldAccess)expression;
			return createVariable(fieldAccess.getName(), null);
		}
		else if(expression instanceof SimpleName) {
			SimpleName simpleName = (SimpleName)expression;
			return createVariable(simpleName, null);
		}
	}
	return null;
}
 
Example #18
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ChangeSignatureProcessor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private Expression createNewExpression(ParameterInfo info, List<ParameterInfo> parameterInfos, List<Expression> nodes, CompilationUnitRewrite cuRewrite, MethodDeclaration method) {
	if (info.isNewVarargs() && info.getDefaultValue().trim().length() == 0)
		return null;
	else {
		if (fDefaultValueAdvisor == null)
			return (Expression) cuRewrite.getASTRewrite().createStringPlaceholder(info.getDefaultValue(), ASTNode.METHOD_INVOCATION);
		else
			return fDefaultValueAdvisor.createDefaultExpression(nodes, info, parameterInfos, method, false, cuRewrite);
	}
}
 
Example #19
/**
 * Creates the expression to access the new target.
 *
 * @param declaration
 *            the method declaration where to access the target
 * @return the corresponding expression
 */
protected Expression createSimpleTargetAccessExpression(final MethodDeclaration declaration) {
	Assert.isNotNull(declaration);
	Expression expression= null;
	final AST ast= declaration.getAST();
	final ITypeBinding type= fTarget.getDeclaringClass();
	if (type != null) {
		boolean shadows= false;
		final IVariableBinding[] bindings= getArgumentBindings(declaration);
		IVariableBinding variable= null;
		for (int index= 0; index < bindings.length; index++) {
			variable= bindings[index];
			if (fMethod.getDeclaringType().getField(variable.getName()).exists()) {
				shadows= true;
				break;
			}
		}
		if (fSettings.useKeywordThis || shadows) {
			final FieldAccess access= ast.newFieldAccess();
			access.setName(ast.newSimpleName(fTarget.getName()));
			access.setExpression(ast.newThisExpression());
			expression= access;
		} else
			expression= ast.newSimpleName(fTarget.getName());
	} else
		expression= ast.newSimpleName(fTarget.getName());
	return expression;
}
 
Example #20
Source Project: eclipse.jdt.ls   Author: eclipse   File: ExtractFieldRefactoring.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static boolean canReplace(IASTFragment fragment) {
	ASTNode node = fragment.getAssociatedNode();
	ASTNode parent = node.getParent();
	if (parent instanceof VariableDeclarationFragment) {
		VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent;
		if (node.equals(vdf.getName())) {
			return false;
		}
	}
	if (isMethodParameter(node)) {
		return false;
	}
	if (isThrowableInCatchBlock(node)) {
		return false;
	}
	if (parent instanceof ExpressionStatement) {
		return false;
	}
	if (parent instanceof LambdaExpression) {
		return false;
	}
	if (isLeftValue(node)) {
		return false;
	}
	if (isReferringToLocalVariableFromFor((Expression) node)) {
		return false;
	}
	if (isUsedInForInitializerOrUpdater((Expression) node)) {
		return false;
	}
	if (parent instanceof SwitchCase) {
		return false;
	}
	return true;
}
 
Example #21
protected void appendExpression(Expression expression) {
	MethodInvocation appendInvocation= fAst.newMethodInvocation();
	if (temporaryExpression != null)
		appendInvocation.setExpression(temporaryExpression);
	else
		appendInvocation.setExpression(fAst.newSimpleName(fBuilderVariableName));
	appendInvocation.setName(fAst.newSimpleName(APPEND_METHOD_NAME));
	appendInvocation.arguments().add(expression);
	temporaryExpression= appendInvocation;
}
 
Example #22
Source Project: jdt-codemining   Author: angelozerr   File: JavaCodeMiningASTVisitor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(MethodInvocation node) {
	/*
	 * if (Utils.isGeneratedByLombok(node)) { return super.visit(node); }
	 */
	if (showParameterName || showParameterType) {
		List arguments = node.arguments();
		if (arguments.size() > 0 && acceptMethod(node)) {
			for (int i = 0; i < arguments.size(); i++) {
				Expression exp = (Expression) arguments.get(i);
				if (showParameterOnlyForLiteral && !isLiteral(exp)) {
					continue;
				}
				// Ignore empty parameter
				if (exp instanceof SimpleName) {
					if ("$missing$".equals(((SimpleName) exp).getIdentifier())) {
						continue;
					}
				}
				minings.add(new JavaMethodParameterCodeMining(node, exp, i, cu, provider, showParameterName,
						showParameterType, showParameterByUsingFilters));
			}
		}
	}
	return super.visit(node);
}
 
Example #23
Source Project: eclipse.jdt.ls   Author: eclipse   File: InvertBooleanUtility.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static Expression getInversedNotExpression(ASTRewrite rewrite, Expression expression, AST ast) {
	PrefixExpression prefixExpression = ast.newPrefixExpression();
	prefixExpression.setOperator(PrefixExpression.Operator.NOT);
	ParenthesizedExpression parenthesizedExpression = getParenthesizedExpression(ast, (Expression) rewrite.createCopyTarget(expression));
	prefixExpression.setOperand(parenthesizedExpression);
	return prefixExpression;
}
 
Example #24
Source Project: JDeodorant   Author: tsantalis   File: DualExpressionPreconditionViolation.java    License: MIT License 5 votes vote down vote up
public StyledString getStyledViolation() {
	StyledString styledString = new StyledString();
	BoldStyler boldStyler = new BoldStyler();
	NormalStyler normalStyler = new NormalStyler();
	if(type.equals(PreconditionViolationType.INFEASIBLE_UNIFICATION_DUE_TO_VARIABLE_TYPE_MISMATCH)) {
		Expression expression1 = this.expression1.getExpression();
		Expression expression2 = this.expression2.getExpression();
		if(expression1 instanceof Name && ((Name)expression1).resolveBinding().getKind() == IBinding.TYPE &&
				expression2 instanceof Name && ((Name)expression2).resolveBinding().getKind() == IBinding.TYPE) {
			styledString.append("Type ", normalStyler);
			styledString.append(expression1.resolveTypeBinding().getQualifiedName(), boldStyler);
			styledString.append(" does not match with ", normalStyler);
			styledString.append("type ", normalStyler);
			styledString.append(expression2.resolveTypeBinding().getQualifiedName(), boldStyler);
		}
		else {
			expression1 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(expression1);
			expression2 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(expression2);
			styledString.append("Type ", normalStyler);
			styledString.append(expression1.resolveTypeBinding().getQualifiedName(), boldStyler);
			styledString.append(" of variable ", normalStyler);
			styledString.append(expression1.toString(), boldStyler);
			styledString.append(" does not match with ", normalStyler);
			styledString.append("type ", normalStyler);
			styledString.append(expression2.resolveTypeBinding().getQualifiedName(), boldStyler);
			styledString.append(" of variable ", normalStyler);
			styledString.append(expression2.toString(), boldStyler);
		}
	}
	return styledString;
}
 
Example #25
/**
 * Creates an invocation of a method that takes zero or one argument
 * 
 * @param expression the receiver expression
 * @param methodName the method name
 * @param argument the argument, can be <code>null</code> if the method does not take any arguments
 * @return MethodInvocation in following form: <code>expression.methodName(argument)</code>
 */
protected MethodInvocation createMethodInvocation(Expression expression, String methodName, Expression argument) {
	MethodInvocation invocation= fAst.newMethodInvocation();
	invocation.setExpression(expression);
	invocation.setName(fAst.newSimpleName(methodName));
	if (argument != null)
		invocation.arguments().add(argument);
	return invocation;
}
 
Example #26
private static ITypeBinding[] getParameterTypes(List<Expression> args) {
	ITypeBinding[] params= new ITypeBinding[args.size()];
	for (int i= 0; i < args.size(); i++) {
		Expression expr= args.get(i);
		ITypeBinding curr= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
		if (curr != null && curr.isWildcardType()) {
			curr= ASTResolving.normalizeWildcardType(curr, true, expr.getAST());
		}
		if (curr == null) {
			curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
		}
		params[i]= curr;
	}
	return params;
}
 
Example #27
Source Project: jdt2famix   Author: feenkcom   File: AstVisitor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(Assignment node) {
	Access writeAccess = importer.createAccessFromExpression((Expression) node.getLeftHandSide());
	writeAccess.setIsWrite(true);
	importer.createAccessFromExpression((Expression) node.getRightHandSide());
	return true;
}
 
Example #28
Source Project: JDeodorant   Author: tsantalis   File: ExtractMethodFragmentRefactoring.java    License: MIT License 5 votes vote down vote up
protected Expression generateDefaultValue(ASTRewrite sourceRewriter, AST ast, ITypeBinding returnTypeBinding) {
	Expression returnedExpression = null;
	if(returnTypeBinding.isPrimitive()) {
		if(returnTypeBinding.getQualifiedName().equals("boolean")) {
			returnedExpression = ast.newBooleanLiteral(false);
		}
		else if(returnTypeBinding.getQualifiedName().equals("char")) {
			CharacterLiteral characterLiteral = ast.newCharacterLiteral();
			sourceRewriter.set(characterLiteral, CharacterLiteral.ESCAPED_VALUE_PROPERTY, "\u0000", null);
			returnedExpression = characterLiteral;
		}
		else if(returnTypeBinding.getQualifiedName().equals("int") ||
				returnTypeBinding.getQualifiedName().equals("short") ||
				returnTypeBinding.getQualifiedName().equals("byte")) {
			returnedExpression = ast.newNumberLiteral("0");
		}
		else if(returnTypeBinding.getQualifiedName().equals("long")) {
			returnedExpression = ast.newNumberLiteral("0L");
		}
		else if(returnTypeBinding.getQualifiedName().equals("float")) {
			returnedExpression = ast.newNumberLiteral("0.0f");
		}
		else if(returnTypeBinding.getQualifiedName().equals("double")) {
			returnedExpression = ast.newNumberLiteral("0.0d");
		}
		else if(returnTypeBinding.getQualifiedName().equals("void")) {
			returnedExpression = null;
		}
	}
	else {
		returnedExpression = ast.newNullLiteral();
	}
	return returnedExpression;
}
 
Example #29
private static boolean getInverseIfProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
	if (!(covering instanceof IfStatement)) {
		return false;
	}
	IfStatement ifStatement= (IfStatement) covering;
	if (ifStatement.getElseStatement() == null) {
		return false;
	}
	//  we could produce quick assist
	if (resultingCollections == null) {
		return true;
	}
	//
	AST ast= covering.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	Statement thenStatement= ifStatement.getThenStatement();
	Statement elseStatement= ifStatement.getElseStatement();

	// prepare original nodes
	Expression inversedExpression= getInversedExpression(rewrite, ifStatement.getExpression());

	Statement newElseStatement= (Statement) rewrite.createMoveTarget(thenStatement);
	Statement newThenStatement= (Statement) rewrite.createMoveTarget(elseStatement);
	// set new nodes
	rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, inversedExpression, null);

	if (elseStatement instanceof IfStatement) {// bug 79507 && bug 74580
		Block elseBlock= ast.newBlock();
		elseBlock.statements().add(newThenStatement);
		newThenStatement= elseBlock;
	}
	rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, newThenStatement, null);
	rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, newElseStatement, null);
	// add correction proposal
	String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseIf_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_IF_STATEMENT, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example #30
Source Project: JDeodorant   Author: tsantalis   File: PreconditionExaminer.java    License: MIT License 5 votes vote down vote up
private boolean isInsideDifference(SimpleName simpleName, Expression difference) {
	int startOffset = simpleName.getStartPosition();
	int endOffset = simpleName.getStartPosition() + simpleName.getLength();
	int differenceStartOffset = difference.getStartPosition();
	int differenceEndOffset = difference.getStartPosition() + difference.getLength();
	if(startOffset >= differenceStartOffset && endOffset <= differenceEndOffset)
		return true;
	return false;
}