Java Code Examples for spoon.reflect.code.CtExpression

The following examples show how to use spoon.reflect.code.CtExpression. These examples are extracted from open source projects. 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
private boolean isNumber(CtExpression<?> operand) {

	if (operand.getType().toString().equals(CtTypeReference.NULL_TYPE_NAME))
		return false;
	
	if (operand.toString().contains(".class"))
		return false;
			
	return operand.getType().getSimpleName().equals("int")
		|| operand.getType().getSimpleName().equals("long")
		|| operand.getType().getSimpleName().equals("byte")
		|| operand.getType().getSimpleName().equals("char")
	|| operand.getType().getSimpleName().equals("float")
	|| operand.getType().getSimpleName().equals("double")
	|| operand.getType().isSubtypeOf(getFactory().Type().createReference(Number.class));
}
 
Example 2
Source Project: astor   Source File: ExpressionTransformer.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean doReplace(OperatorInstance operation) {
	boolean successful = false;

	try {

		CtExpression ctst = (CtExpression) operation.getOriginal();
		CtExpression fix = (CtExpression) operation.getModified();

		ctst.replace((CtExpression) fix);
		successful = true;
		operation.setSuccessfulyApplied((successful));

	} catch (Exception ex) {
		log.error("Error applying an operation, exception: " + ex.getMessage());
		operation.setExceptionAtApplied(ex);
		operation.setSuccessfulyApplied(false);
	}
	return successful;
}
 
Example 3
@SuppressWarnings({ "static-access", "rawtypes", "unchecked" })
public void visitCtIf(CtIf ifElement) {
	 
	super.visitCtIf(ifElement);
	CtExpression  cond = ifElement.getCondition();
	
	CtLiteral<Boolean> literalvalue = this.mutSupporter.getFactory().Core().createLiteral();
	Boolean bval=false;
	literalvalue.setValue(bval);
	
	CtBinaryOperator<?> newcond = this.mutSupporter.getFactory().Core().createBinaryOperator();
	newcond.setKind(BinaryOperatorKind.AND);
	newcond.setRightHandOperand(literalvalue);
	newcond.setLeftHandOperand(cond);
	
	ifElement.setCondition((CtExpression<Boolean>) newcond);
	saveSketchAndSynthesize();
	ifElement.setCondition(cond);
	resoreDiskFile();
}
 
Example 4
public void process(Bound annotation, CtParameter<?> element) {
	final CtMethod parent = element.getParent(CtMethod.class);

	// Build if check for min.
	CtIf anIf = getFactory().Core().createIf();
	anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " < " + annotation.min()));
	CtThrow throwStmt = getFactory().Core().createThrow();
	throwStmt.setThrownExpression((CtExpression<? extends Throwable>) getFactory().Core().createCodeSnippetExpression().setValue("new RuntimeException(\"out of min bound (\" + " + element.getSimpleName() + " + \" < " + annotation.min() + "\")"));
	anIf.setThenStatement(throwStmt);
	parent.getBody().insertBegin(anIf);
	anIf.setParent(parent);

	// Build if check for max.
	anIf = getFactory().Core().createIf();
	anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " > " + annotation.max()));
	anIf.setThenStatement(getFactory().Code().createCtThrow("new RuntimeException(\"out of max bound (\" + " + element.getSimpleName() + " + \" > " + annotation.max() + "\")"));
	parent.getBody().insertBegin(anIf);
	anIf.setParent(parent);
}
 
Example 5
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 6 votes vote down vote up
/**
 * Return if the Condition is a guard
 * 
 * @param condition
 * @return
 */
// we want the condition not to be null related check
public boolean checkNormalGuardCondition(CtExpression condition) {
	if (condition != null) {
		List<CtBinaryOperator> binOp = condition.getElements(new TypeFilter<>(CtBinaryOperator.class));
		if (binOp != null && binOp.size() > 0) {

			for (CtBinaryOperator ctBinaryOperator : binOp) {
				if (ctBinaryOperator.getRightHandOperand().toString().equals("null")
						|| ctBinaryOperator.getLeftHandOperand().toString().equals("null")) {

					return false;
				}
			}
		}

		return true;
	}
	return false;
}
 
Example 6
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 6 votes vote down vote up
public boolean checkNullCheckGuardCondition(CtExpression condition) {
	if (condition != null) {
		List<CtBinaryOperator> binOp = condition.getElements(new TypeFilter<>(CtBinaryOperator.class));
		if (binOp != null && binOp.size() > 0) {

			for (CtBinaryOperator ctBinaryOperator : binOp) {
				if (!ctBinaryOperator.getRightHandOperand().toString().equals("null")
						&& !ctBinaryOperator.getLeftHandOperand().toString().equals("null")) {

					return false;
				}
			}

			return true;
		}

		return false;
	}
	return false;
}
 
Example 7
@SuppressWarnings({ "rawtypes", "static-access" })
@Override
public <T> void visitCtBinaryOperator(CtBinaryOperator<T> operator) {
	super.visitCtBinaryOperator(operator);
	
	if(operator.getKind()==BinaryOperatorKind.AND||operator.getKind()==BinaryOperatorKind.OR) {
		CtExpression right = operator.getRightHandOperand();
		operator.setKind(BinaryOperatorKind.AND);
		CtLiteral<Boolean> literalvalue = this.mutSupporter.getFactory().Core().createLiteral();
		Boolean bval=true;
		literalvalue.setValue(bval);
		operator.setRightHandOperand(literalvalue);
		saveSketchAndSynthesize();
		operator.setRightHandOperand(right);
		resoreDiskFile();
		
		CtExpression left = operator.getLeftHandOperand();
		operator.setKind(BinaryOperatorKind.AND);
		operator.setLeftHandOperand(literalvalue);
		saveSketchAndSynthesize();
		operator.setLeftHandOperand(left);
		resoreDiskFile();
	}
}
 
Example 8
Source Project: coming   Source File: LogicalExpressionAnalyzer.java    License: MIT License 6 votes vote down vote up
public boolean isBooleanExpression(CtElement currentexpression) {
	
	if (currentexpression == null|| currentexpression instanceof CtVariableAccess)
		return false;
	
	if (isLogicalExpression(currentexpression)) {
		return true;
	}
	
	if(currentexpression instanceof CtExpression) {
		CtExpression exper= (CtExpression) currentexpression;
	   try {
	      if (exper.getType() != null
			&& exper.getType().unbox().toString().equals("boolean")) {
		  return true;
	     }
	   } catch (Exception e) {
		   return false;
	   }
	}

	return false;
}
 
Example 9
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public <T> void visitCtConstructorCall(CtConstructorCall<T> ctConstructorCall) {
	super.visitCtConstructorCall(ctConstructorCall);
	
	String type = ctConstructorCall.getType().getQualifiedName();
	List<CtExpression<?>>  argumentlist = ctConstructorCall.getArguments();
	List<String> orig = resolveTypes(argumentlist);

	CtClass classname = parser.getClassMap().get(type); 
	
	if(classname!=null) {
		Set<CtConstructor<T>> constructors=classname.getConstructors();
           for(CtConstructor constructor:constructors) {
           	List<CtParameter> paramlist=constructor.getParameters();
           	List<String> target=resolveParams(paramlist);
           	transformOneMethod(orig,target,ctConstructorCall);
           }
	} else {
		List<Class[]> params = parser.fetchMethods(type, type);
		for (Class[] p : params)
			transformOneConstructor(orig, ctConstructorCall, p);
	}
}
 
Example 10
Source Project: astor   Source File: TransformStrategy.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> void visitCtConstructorCall(CtConstructorCall<T> ctConstructorCall) {
	super.visitCtConstructorCall(ctConstructorCall);

	List<CtExpression<?>>  argumentlist = ctConstructorCall.getArguments();
	for (int i = 0; i < argumentlist.size(); i++) {
		@SuppressWarnings("rawtypes")
		CtExpression p = argumentlist.get(i);
		if (candidates.containsKey(p)) {
			argumentlist.set(i, candidates.get(p));
		//	ctConstructorCall.setArguments(argumentlist);
			saveSketchAndSynthesize();
			argumentlist.set(i, p);
			resoreDiskFile();
		//	ctConstructorCall.setArguments(argumentlist);
		}
	}
}
 
Example 11
Source Project: astor   Source File: ExpressionTransform.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> void visitCtFieldRead(CtFieldRead<T> fieldRead) {
	
	String type = fieldRead.getType().getQualifiedName();
	type = type.replaceAll("\\d","");
	
	CtEnum enumRead=enummap.get(type);
	
	@SuppressWarnings("rawtypes")
	CtExpression exp = null;
	if(enumRead==null)
	   exp = ExpressionGenerator.fetchEXP(this.mutSupporter, this.modificationPoint, type, querytype);
	else 		
	   exp = ExpressionGenerator.fetchENUM(enumRead, this.mutSupporter, type, querytype);
		
	if (exp != null)
		candidates.put(fieldRead, exp);
}
 
Example 12
Source Project: astor   Source File: MetaGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static MetaOperatorInstance createMetaFineGrainedReplacement(ModificationPoint modificationPoint,
		CtExpression elementSource, int variableCounter, List<Ingredient> ingredients,
		List<CtParameter<?>> parameters, List<CtExpression<?>> realParameters, AstorOperator parentOperator,
		CtTypeReference returnType) {

	MetaOperatorInstance opMega = new MetaOperatorInstance((MetaOperator) parentOperator,
			MetaGenerator.getNewIdentifier());

	List<OperatorInstance> opsOfVariant = new ArrayList();
	Map<Integer, Ingredient> ingredientOfMapped = new HashMap<>();

	createMetaForSingleElement(opMega, modificationPoint, elementSource, variableCounter, ingredients, parameters,
			realParameters, returnType, opsOfVariant, ingredientOfMapped);

	opMega.setOperatorInstances(opsOfVariant);
	opMega.setAllIngredients(ingredientOfMapped);
	opMega.setOperationApplied(parentOperator);
	opMega.setOriginal(elementSource);
	opMega.setModificationPoint(modificationPoint);

	return opMega;
}
 
Example 13
Source Project: astor   Source File: BinaryOperatorMutator.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates alternatives Expressions (Binary Operations) given a list of Binary
 * operators kind operators. The original kind (that one included in the
 * original expression is not analyzed)
 * 
 * @param result
 * @param op
 * @param kind
 * @param operators
 */
protected void addRemainings(List<CtExpression> result, CtBinaryOperator<?> op, BinaryOperatorKind kind,
		List<BinaryOperatorKind> operators) {
	// TODO: recursive?
	if (operators.contains(kind)) {
		for (BinaryOperatorKind binaryOperatorKind : operators) {
			if (binaryOperatorKind != kind) {
				// Cloning
				CtExpression right = factory.Core().clone(op.getRightHandOperand());
				CtExpression left = factory.Core().clone(op.getLeftHandOperand());

				CtBinaryOperator binaryOp = factory.Code().createBinaryOperator(left, right, binaryOperatorKind);
				// Set parent
				right.setParent(binaryOp);
				left.setParent(binaryOp);

				result.add(binaryOp);
			}
		}
	}
}
 
Example 14
Source Project: astor   Source File: SingleLogicExpOperator.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean applyModification() {
	CtBinaryOperator binaryOperator = new CtBinaryOperatorImpl<>();
	binaryOperator.setKind(operator);

	CtExpression leftOriginal2 = (CtExpression) MetaGenerator.geOriginalElement(leftOriginal);
	binaryOperator.setLeftHandOperand(leftOriginal2.clone());

	CtExpression newRightExpression = rightNew;
	binaryOperator.setRightHandOperand(newRightExpression);

	//
	binaryOperator.setFactory(MutationSupporter.getFactory());
	binaryOperator.setParent(leftOriginal2.getParent());
	//

	super.setOriginal(leftOriginal2);
	super.setModified(binaryOperator);

	return super.applyModification();
}
 
Example 15
Source Project: astor   Source File: MetaGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static List<CtExpression<?>> filterParameter(List<CtExpression<?>> realParameters) {
	List<CtExpression<?>> parametersN = new ArrayList<>();
	HashMap<String, CtVariableAccess> seen = new HashMap();
	for (CtExpression<?> ctParameter : realParameters) {
		if (ctParameter instanceof CtVariableAccess) {
			CtVariableAccess va = (CtVariableAccess) ctParameter;
			if (!seen.containsKey(va.getVariable().getSimpleName())) {
				parametersN.add(ctParameter);
				seen.put(va.getVariable().getSimpleName(), va);
			} else {
				// we have a var with the same name
				CtVariableAccess other = seen.get(va.getVariable().getSimpleName());
				if (other instanceof CtFieldAccess && !(va instanceof CtFieldAccess)) {
					// replace the field access by the other var access
					int ind = parametersN.indexOf(other);
					parametersN.remove(ind);
					parametersN.add(ind, va);
					seen.put(va.getVariable().getSimpleName(), va);
				}
			}
		}
	}

	return parametersN;
}
 
Example 16
Source Project: astor   Source File: SupportOperators.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static List<CtInvocation> realInvocationsFromCombination(CtMethod anotherMethod, CtExpression target,
		List<List<CtExpression<?>>> possibleArguments) {
	List<CtInvocation> newInvocations = new ArrayList<>();

	for (List<CtExpression<?>> arguments : possibleArguments) {
		CtInvocation newInvocation = MutationSupporter.getFactory().createInvocation(target,
				anotherMethod.getReference(), arguments);
		newInvocation.setExecutable(anotherMethod.getReference());
		newInvocation.setArguments(arguments);
		newInvocation.setTarget(target);

		newInvocations.add(newInvocation);

	}
	return newInvocations;
}
 
Example 17
Source Project: astor   Source File: ExpressionTransform.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> void visitCtBinaryOperator(CtBinaryOperator<T> operator) {
	super.visitCtBinaryOperator(operator);
	@SuppressWarnings("rawtypes")
	CtExpression left = operator.getLeftHandOperand();
	if (candidates.containsKey(left)) {
		operator.setLeftHandOperand(candidates.get(left));
		saveSketchAndSynthesize();
		operator.setLeftHandOperand(left);
		resoreDiskFile();
	}

	@SuppressWarnings("rawtypes")
	CtExpression right = operator.getRightHandOperand();
	if (candidates.containsKey(right)) {
		operator.setRightHandOperand(candidates.get(right));
		saveSketchAndSynthesize();
		operator.setRightHandOperand(right);
		resoreDiskFile();
	}
}
 
Example 18
private boolean isNumber(CtExpression<?> operand) {
	return operand.getType().getSimpleName().equals("int")
		|| operand.getType().getSimpleName().equals("long")
		|| operand.getType().getSimpleName().equals("byte")
		|| operand.getType().getSimpleName().equals("char")
	|| operand.getType().getSimpleName().equals("float")
	|| operand.getType().getSimpleName().equals("double")
	|| Number.class.isAssignableFrom(operand.getType().getActualClass());
}
 
Example 19
Source Project: astor   Source File: SingleLogicExpOperator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public SingleLogicExpOperator(ModificationPoint modificationPoint, CtExpression leftOriginal, CtExpression rightNew,
		BinaryOperatorKind operator, AstorOperator astoroperator) {
	super();
	this.leftOriginal = leftOriginal;
	this.rightNew = rightNew;
	this.operator = operator;
	super.setOperationApplied(astoroperator);
	super.setModificationPoint(modificationPoint);
}
 
Example 20
private static <T> CtIf collectionWrappingIf(List<CtStatement> collectingStatements, RuntimeValues<T> runtimeValues, CtStatement insertionPoint) {
    Factory factory = insertionPoint.getFactory();
    CtStatement newBlock = newBlock(factory, collectingStatements);
    CtExpression<Boolean> isEnabled = newExpressionFromSnippet(factory, runtimeValues.isEnabledInquiry(), Boolean.class);
    CtIf newIf = newIf(factory, isEnabled, newBlock);
    insertBeforeUnderSameParent(newIf, insertionPoint);
    return newIf;
}
 
Example 21
Source Project: astor   Source File: TransformStrategy.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public <T> void visitCtArrayWrite(CtArrayWrite<T> arrayWrite) {
	super.visitCtArrayWrite(arrayWrite);
	
	CtExpression exper=arrayWrite.getIndexExpression();
	if (candidates.containsKey(exper)) {
		arrayWrite.setIndexExpression(candidates.get(exper));
		saveSketchAndSynthesize();
		arrayWrite.setIndexExpression(exper);
		resoreDiskFile();
	}
}
 
Example 22
Source Project: astor   Source File: ExpressionTransformer.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static boolean undoReplace(OperatorInstance operation) {
	try {
		CtExpression ctst = (CtExpression) operation.getOriginal();
		CtExpression fix = (CtExpression) operation.getModified();
		fix.replace(ctst);
		return true;

	} catch (Exception ex) {
		log.error("Error applying an operation, exception: " + ex.getMessage());
		return false;
	}

}
 
Example 23
Source Project: astor   Source File: TransformStrategy.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void visitCtFor(CtFor forLoop) {
	super.visitCtFor(forLoop);

	@SuppressWarnings("rawtypes")
	CtExpression exper=forLoop.getExpression();
	if (candidates.containsKey(exper)) {
		forLoop.setExpression(candidates.get(exper));
		saveSketchAndSynthesize();
		forLoop.setExpression(exper);
		resoreDiskFile();
	}
}
 
Example 24
Source Project: nopol   Source File: ConditionalReplacer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public CtIf processCondition(CtStatement element, String newCondition) {
    CtCodeSnippetExpression<Boolean> snippet = element.getFactory().Core().createCodeSnippetExpression();
    snippet.setValue(newCondition);
    CtExpression<Boolean> condition = getCondition(element);
    condition.replace(snippet);
    return (CtIf) element;
}
 
Example 25
Source Project: astor   Source File: LogicRedOperator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void addOperator(List<Ingredient> ingredientsReducedExpressions, CtBinaryOperator binaryOperatorToReduce,
		CtExpression subterm) {

	MutationSupporter.clearPosition(subterm);
	Ingredient newIngredientExtended = new Ingredient(subterm.clone());
	newIngredientExtended.setDerivedFrom(binaryOperatorToReduce);
	ingredientsReducedExpressions.add(newIngredientExtended);

	newIngredientExtended.getMetadata().put("original", binaryOperatorToReduce);
	newIngredientExtended.getMetadata().put("reduced", subterm);
}
 
Example 26
Source Project: nopol   Source File: LiteralReplacer.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void replaceBoolean(CtExpression ctElement) {
    if (getValue() == null) {
        CtLocalVariable<Boolean> evaluation = newLocalVariableDeclaration(
                ctElement.getFactory(), boolean.class, "guess_fix",
                Debug.class.getCanonicalName() + ".makeSymbolicBoolean(\"guess_fix\")");
        CtStatement firstStatement = getFirstStatement(ctElement);
        if (firstStatement == null) {
            return;
        }
        SpoonStatementLibrary.insertBeforeUnderSameParent(evaluation,
                firstStatement);
        ctElement.replace(getFactory().Code().createCodeSnippetExpression(
                "guess_fix"));
    } else {
        switch (getValue()) {
            case "1":
                ctElement.replace(getFactory().Code().createCodeSnippetExpression("true"));
                break;
            case "0":
                ctElement.replace(getFactory().Code().createCodeSnippetExpression("false"));
                break;
            default:
                ctElement.replace(getFactory().Code().createCodeSnippetExpression(getValue()));
                break;
        }
    }
}
 
Example 27
Source Project: coming   Source File: ExpressionAnalyzer.java    License: MIT License 5 votes vote down vote up
private boolean getExpressionType (CtExpression anexpression) {
	
	if (anexpression.getType()!=null && anexpression.getType().isPrimitive()) {		
		return true;
	}
	
	return false;
}
 
Example 28
Source Project: astor   Source File: ConditionAddTransform.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "static-access", "unchecked", "rawtypes" })
private void writeCondition(String type, CtBlock parent, int id) {
	CtExpression conditionExp = ExpressionGenerator.fetchEXP(this.mutSupporter, this.modificationPoint, type, querytype);
       
	CtIf ifStmt = this.mutSupporter.getFactory().Core().createIf();
	ifStmt.setCondition(conditionExp);
	ifStmt.setThenStatement((CtStatement)this.modificationPoint.getCodeElement());
	parent.addStatement(id, ifStmt);
	parent.removeStatement((CtStatement)this.modificationPoint.getCodeElement());
	saveSketchAndSynthesize();
	parent.addStatement(id, (CtStatement)this.modificationPoint.getCodeElement());
	parent.removeStatement(ifStmt);
	resoreDiskFile();
}
 
Example 29
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 5 votes vote down vote up
public boolean isNullCheckGuard(CtElement element, CtStatement parentStatement) {

		// Two cases: if and conditional
		CtExpression condition = null;
		CtConditional parentConditional = element.getParent(CtConditional.class);

		if (parentConditional != null) {// TODO, maybe force that the var must be in the condition, or not.
			CtConditional cond = (CtConditional) parentConditional;
			condition = cond.getCondition();
			return checkNullCheckGuardCondition(condition);

		} else {
			CtElement parentElement = getParentNotBlock(parentStatement);
			// First, find the condition

			if (parentElement instanceof CtIf) {

				CtIf guardCandidateIf = (CtIf) parentElement;

				if (whethereffectiveguard(guardCandidateIf, parentStatement)) {
					condition = guardCandidateIf.getCondition();
					boolean isConditionAGuard = checkNullCheckGuardCondition(condition);
					return isConditionAGuard;
				}
			}
		}
		return false;
	}
 
Example 30
Source Project: astor   Source File: ExpressionTransform.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> void visitCtVariableRead(CtVariableRead<T> variableRead) {
	
	String type = variableRead.getType().getQualifiedName();
	type = type.replaceAll("\\d","");
	@SuppressWarnings("rawtypes")
	CtExpression exp = null;
	exp = ExpressionGenerator.fetchEXP(this.mutSupporter, this.modificationPoint, type, querytype);
			
	if (exp != null)
		candidates.put(variableRead, exp);
}