Java Code Examples for spoon.reflect.code.BinaryOperatorKind

The following examples show how to use spoon.reflect.code.BinaryOperatorKind. 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
public void process(CtBinaryOperator<Boolean> binaryOperator) {
	BinaryOperatorKind kind = binaryOperator.getKind();
	
	if (LOGICAL_OPERATORS.contains(kind)) {
		mutateOperator(binaryOperator, LOGICAL_OPERATORS);
	} else if (COMPARISON_OPERATORS.contains(kind)) {
		if (isNumber(binaryOperator.getLeftHandOperand())
		 && isNumber(binaryOperator.getRightHandOperand()))
		{
			mutateOperator(binaryOperator, COMPARISON_OPERATORS);
		}
		 else {
			 EnumSet<BinaryOperatorKind> clone = REDUCED_COMPARISON_OPERATORS.clone();
			 clone.add(kind);
			 mutateOperator(binaryOperator, clone);
		 }
	}
}
 
Example 2
Source Project: coming   Source File: LogicalExpressionAnalyzer.java    License: MIT License 6 votes vote down vote up
public boolean isLogicalExpression(CtElement currentElement) {
	if (currentElement == null)
		return false;
	if ((currentElement instanceof CtBinaryOperator)) {
		CtBinaryOperator binOp = (CtBinaryOperator) currentElement;
					
		if(binOp.getKind().equals(BinaryOperatorKind.AND) || binOp.getKind().equals(BinaryOperatorKind.OR)
			|| binOp.getKind().equals(BinaryOperatorKind.EQ)
			|| binOp.getKind().equals(BinaryOperatorKind.GE)
			|| binOp.getKind().equals(BinaryOperatorKind.GT)
			|| binOp.getKind().equals(BinaryOperatorKind.INSTANCEOF)
			|| binOp.getKind().equals(BinaryOperatorKind.LE)
			|| binOp.getKind().equals(BinaryOperatorKind.LT)
			|| binOp.getKind().equals(BinaryOperatorKind.NE))
			   return true;
	}
	
	return false;
}
 
Example 3
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 4
Source Project: astor   Source File: WrapwithIfNullCheck.java    License: GNU General Public License v2.0 6 votes vote down vote up
private List<Ingredient> computeIngredientsNullCheck(ModificationPoint modificationPoint,
		List<CtVariableAccess> varAccessInModificationPoints) {

	List<Ingredient> ingredients = new ArrayList();

	for (CtVariableAccess iVariableAccess : varAccessInModificationPoints) {

		// Let's check the type, if primitive discard it
		if (iVariableAccess.getVariable() != null && iVariableAccess.getVariable().getType() != null
				&& iVariableAccess.getVariable().getType().isPrimitive())
			continue;

		CtVariableAccess iVariableAccessC = iVariableAccess.clone();
		MutationSupporter.clearPosition(iVariableAccessC);

		CtBinaryOperator<Boolean> binaryOp = new CtBinaryOperatorImpl<>();
		binaryOp.setLeftHandOperand(iVariableAccessC);
		binaryOp.setRightHandOperand(MutationSupporter.getFactory().createCodeSnippetExpression("null"));
		binaryOp.setKind(BinaryOperatorKind.NE);

		ingredients.add(new Ingredient(binaryOp));

	}

	return ingredients;
}
 
Example 5
Source Project: astor   Source File: OperatorReplacementOp.java    License: GNU General Public License v2.0 6 votes vote down vote up
public List<Ingredient> getNewBinary(CtBinaryOperator oldBinary, List<BinaryOperatorKind> ops) {
	List<Ingredient> mutationAll = new ArrayList<>();

	if (ops.contains(oldBinary.getKind())) {

		for (BinaryOperatorKind binaryOperatorKind2 : ops) {

			if (binaryOperatorKind2.equals(oldBinary.getKind()))
				continue;

			CtBinaryOperator binaryOp = MutationSupporter.getFactory().Code().createBinaryOperator(
					oldBinary.getLeftHandOperand().clone(), oldBinary.getRightHandOperand(), binaryOperatorKind2);
			MutationSupporter.clearPosition(binaryOp);
			Ingredient newIngredientExtended = new Ingredient(binaryOp);
			newIngredientExtended.setDerivedFrom(oldBinary);
			mutationAll.add(newIngredientExtended);
			newIngredientExtended.getMetadata().put("left_original", oldBinary.getLeftHandOperand());
			newIngredientExtended.getMetadata().put("right_original", oldBinary.getRightHandOperand());
			newIngredientExtended.getMetadata().put("operator", binaryOperatorKind2);
		}
	}

	return mutationAll;
}
 
Example 6
@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 7
@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 8
Source Project: astor   Source File: StaSynthBuilder.java    License: GNU General Public License v2.0 6 votes vote down vote up
public List<CtExpression> createNotNullExpr(List<CtVariableRead> cteVarReadList) {

		List<CtExpression> result = new ArrayList<>();

		for (CtVariableRead varr : cteVarReadList) {

			if (!varr.getType().isPrimitive()) {
				CtBinaryOperatorImpl binex = new CtBinaryOperatorImpl<>();
				binex.setKind(BinaryOperatorKind.NE);
				binex.setLeftHandOperand(varr);
				binex.setRightHandOperand(nullExp);
				result.add(binex);
			}
		}
		return result;
	}
 
Example 9
Source Project: astor   Source File: ExpressionRevolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static List<CtExpression<Boolean>> getExpressions(CtExpression<Boolean> element) {
	List<CtExpression<Boolean>> expsRetrieved = new ArrayList<CtExpression<Boolean>>();

	if (element instanceof CtUnaryOperator) {
		expsRetrieved.add(element);
		element = ((CtUnaryOperator) element).getOperand();
	}

	if (element instanceof CtBinaryOperator) {
		expsRetrieved.add(element);
		CtBinaryOperator bin = (CtBinaryOperator) element;
		if (bin.getKind().equals(BinaryOperatorKind.AND) || bin.getKind().equals(BinaryOperatorKind.OR)) {
			expsRetrieved.addAll(getExpressions(bin.getLeftHandOperand()));
			expsRetrieved.addAll(getExpressions(bin.getRightHandOperand()));
		}
	} else {
		if (element instanceof CtInvocation
				&& element.getType().getSimpleName().equals(boolean.class.getSimpleName())) {
			expsRetrieved.add(element);
		}
	}
	return expsRetrieved;
}
 
Example 10
/**
 * Converts "a op b" bean op one of "<", "<=", "==", ">=", "!=" to:
 *    (  (op(1, 0, "<")  && (a < b))
 *    || (op(1, 1, "<=") && (a <= b))
 *    || (op(1, 2, "==") && (a == b))
 *    || (op(1, 3, ">=") && (a >= b))
 *    || (op(1, 4, ">")  && (a > b))
 *    )
 *	 */
private void mutateOperator(final CtBinaryOperator<Boolean> expression, EnumSet<BinaryOperatorKind> operators) {
	
	if (!operators.contains(expression.getKind())) {
		throw new IllegalArgumentException("not consistent ");
	}

	if (alreadyInHotsSpot(expression)
			|| expression.toString().contains(".is(\"")) {
		System.out
				.println(String
						.format("Expression '%s' ignored because it is included in previous hot spot",
								expression));
		return;
	}

	int thisIndex = ++index;

	BinaryOperatorKind originalKind = expression.getKind();
	String newExpression = operators
			.stream()
			.map(kind -> {
				expression.setKind(kind);
				return String.format("("+ PREFIX + "%s.is(%s) && (%s))",
						thisIndex, kind.getDeclaringClass().getName()+"."+kind.name(), expression);
			}).collect(Collectors.joining(" || "));

	CtCodeSnippetExpression<Boolean> codeSnippet = getFactory().Core()
			.createCodeSnippetExpression();
	codeSnippet.setValue('(' + newExpression + ')');

	expression.replace(codeSnippet);
	expression.replace(expression);
	Selector.generateSelector(expression, originalKind, thisIndex, operators, PREFIX);

	hostSpots.add(expression);

}
 
Example 11
private String permutations(BinaryOperatorKind value) {
	switch(value) {
		case PLUS : return "+";
		case MINUS : return "-";
		case DIV : return "/";
		case MUL : return "*";
		default : return "";
	}
}
 
Example 12
public void process(CtBinaryOperator<Boolean> binaryOperator) {
	BinaryOperatorKind kind = binaryOperator.getKind();
	if(ARITHMETIC_OPERATORS.contains(kind)){
		if(binaryOperator.getLeftHandOperand().getType() != null && binaryOperator.getRightHandOperand().getType() != null)
			if ( isNumber(binaryOperator.getLeftHandOperand())
			&& isNumber(binaryOperator.getRightHandOperand()))
			{
				mutateOperator(binaryOperator, ARITHMETIC_OPERATORS);
			}
	}
}
 
Example 13
@Override
public void process(CtElement candidate) {
	if (!(candidate instanceof CtBinaryOperator)) {
		return;
	}
	CtBinaryOperator op = (CtBinaryOperator)candidate;
	op.setKind(BinaryOperatorKind.MINUS);
}
 
Example 14
Source Project: coming   Source File: BinaryOperatorAnalyzer.java    License: MIT License 5 votes vote down vote up
private void analyzeBinaryLogicalOperator(CtBinaryOperator operatorunderstudy, int operatorindex, Cntx<Object> context) {
	
	boolean whethercontainnotoperator = false;
	
	BinaryOperatorKind operatorkind = operatorunderstudy.getKind();

	if(logicalOperator.contains(operatorkind)) {
		
		CtExpression leftexpression = operatorunderstudy.getLeftHandOperand();
		CtExpression rightexpression = operatorunderstudy.getRightHandOperand();
				
		List<CtBinaryOperator> logicalOperatorLeft = leftexpression.getElements(
		  e -> e instanceof CtBinaryOperator && logicalOperator.contains(((CtBinaryOperator) e).getKind()));
		
		List<CtBinaryOperator> logicalOperatorRight = rightexpression.getElements(
				  e -> e instanceof CtBinaryOperator && logicalOperator.contains(((CtBinaryOperator) e).getKind()));
		
		if(logicalOperatorLeft.size() == 0) {	
			if(scannotoperator(leftexpression))
				whethercontainnotoperator=true;
		}
			
		if(!whethercontainnotoperator && logicalOperatorRight.size() == 0)	{
			if(scannotoperator(rightexpression))
				whethercontainnotoperator=true;
		}
	}
	
	writeGroupedInfo(context, Integer.toString(operatorindex)+"_"+operatorunderstudy, CodeFeatures.O2_LOGICAL_CONTAIN_NOT, 
			whethercontainnotoperator, "FEATURES_BINARYOPERATOR");
	
}
 
Example 15
Source Project: coming   Source File: BinaryOperatorAnalyzer.java    License: MIT License 5 votes vote down vote up
private void analyzeBinaryOperatorKind(CtBinaryOperator operatorunderstudy, int operatorindex, Cntx<Object> context) {
	
	BinaryOperatorKind operatorkind = operatorunderstudy.getKind();
	
	String operatorstring="";
	
	if(logicalOperator.contains(operatorkind)) {
		operatorstring="logical";
	} else if (bitOperator.contains(operatorkind)) {
		operatorstring="bit";
	} else if (compareOperator.contains(operatorkind)) {
		operatorstring="compare";
	} else if (shiftOperator.contains(operatorkind)) {
		operatorstring="shift";
	} else if (mathOperator.contains(operatorkind)) {
		operatorstring="math";
	} else operatorstring="others";
	
	for(int index=0; index<binoperatortype.size(); index++) {
		CodeFeatures cerainfeature = binoperatortype.get(index);
		
		if(cerainfeature.toString().endsWith(operatorstring.toUpperCase()))
			writeGroupedInfo(context,  Integer.toString(operatorindex)+"_"+operatorunderstudy, cerainfeature, 
						true, "FEATURES_BINARYOPERATOR");
		else writeGroupedInfo(context,  Integer.toString(operatorindex)+"_"+operatorunderstudy, cerainfeature, 
				false, "FEATURES_BINARYOPERATOR");
	}	
}
 
Example 16
public ArithmeticBinaryOperatorMutator(Factory factory) {
	super(factory);
	operators = Arrays.asList(BinaryOperatorKind.PLUS, BinaryOperatorKind.MINUS, BinaryOperatorKind.MUL,
			BinaryOperatorKind.DIV, BinaryOperatorKind.MOD

	);

}
 
Example 17
Source Project: astor   Source File: BinaryOperatorMutator.java    License: GNU General Public License v2.0 5 votes vote down vote up
private CtBinaryOperator createBinaryOp(CtBinaryOperator<?> op, BinaryOperatorKind binaryOperatorKind,
		CtExpression left_i, CtExpression right_i) {
	CtExpression right_c = factory.Core().clone(right_i);
	CtExpression left_c = factory.Core().clone(left_i);

	CtBinaryOperator binaryOp = factory.Code().createBinaryOperator(left_c, right_c, binaryOperatorKind);
	// Set parent
	right_c.setParent(binaryOp);
	left_c.setParent(binaryOp);
	return binaryOp;

}
 
Example 18
public RelationalBinaryOperatorMutator(Factory factory) {
	super(factory);
	operators2 =
	          Arrays.asList(
	              BinaryOperatorKind.EQ,
	              BinaryOperatorKind.NE,
	              BinaryOperatorKind.GE, 
	              BinaryOperatorKind.GT,
	              BinaryOperatorKind.LE,
	              BinaryOperatorKind.LT
	            
	        		  );

}
 
Example 19
Source Project: astor   Source File: LogicExpOperator.java    License: GNU General Public License v2.0 5 votes vote down vote up
private List<Ingredient> computeIngredientsFromExpressionExplansion(ModificationPoint modificationPoint,
		CtExpression previousExpression, List<IngredientFromDyna> ingredientsDynamoth,
		BinaryOperatorKind operatorKind2) {

	List<Ingredient> ingredientsNewBinaryExpressions = new ArrayList();

	for (IngredientFromDyna ingredientFromDyna : ingredientsDynamoth) {

		CtBinaryOperator binaryOperator = new CtBinaryOperatorImpl<>();
		binaryOperator.setKind(operatorKind2);

		CtExpression previousExpressionCloned = previousExpression.clone();
		MutationSupporter.clearPosition(previousExpressionCloned);
		binaryOperator.setLeftHandOperand(previousExpressionCloned);

		CtExpression newRightExpression = MutationSupporter.getFactory()
				.createCodeSnippetExpression(ingredientFromDyna.getDynmothExpression().toString());
		binaryOperator.setRightHandOperand(newRightExpression);

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

		Ingredient newIngredientExtended = new Ingredient(binaryOperator);
		// Updated: new code
		newIngredientExtended.getMetadata().put("operator", operatorKind2);
		newIngredientExtended.getMetadata().put("right", newRightExpression);
		newIngredientExtended.getMetadata().put("leftoriginal", previousExpression);
		//

		ingredientsNewBinaryExpressions.add(newIngredientExtended);
	}

	return ingredientsNewBinaryExpressions;
}
 
Example 20
public SingleOperatorChangeOperator(ModificationPoint modificationPoint, CtBinaryOperator original,
		CtExpression leftOriginal, CtExpression rightNew, BinaryOperatorKind operator,
		AstorOperator astoroperator) {
	super();
	this.leftOriginal = leftOriginal;
	this.rightOriginal = rightNew;
	this.operator = operator;
	this.original = original;
	super.setOperationApplied(astoroperator);
	super.setModificationPoint(modificationPoint);
}
 
Example 21
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 22
@Override
public <T> void visitCtBinaryOperator(CtBinaryOperator<T> operator) {
	super.visitCtBinaryOperator(operator);
	
	if(operator.getKind()==BinaryOperatorKind.AND||operator.getKind()==BinaryOperatorKind.OR) {
		fetchCOND(operator);
	}
}
 
Example 23
Source Project: astor   Source File: OperatorTransform.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> void visitCtBinaryOperator(CtBinaryOperator<T> operator) {
	super.visitCtBinaryOperator(operator);
	@SuppressWarnings("rawtypes")
	CtExpression left = operator.getLeftHandOperand();
	
	String typelefthand=left.getType().getQualifiedName();
	String typeoperator=operator.getType().getQualifiedName();
	typelefthand = typelefthand.replaceAll("\\d","");
	typeoperator = typeoperator.replaceAll("\\d","");
	@SuppressWarnings("rawtypes")
	CtExpression exp = null;
	
	BinaryOperatorKind kind=operator.getKind();
	if(rop.contains(kind))
		exp = OperatorGenerator.fetchROP(operator, this.mutSupporter, this.modificationPoint, typelefthand, "ROP");
	else if(aop.contains(kind))
		exp = OperatorGenerator.fetchROP(operator, this.mutSupporter, this.modificationPoint, typeoperator, "AOP");
			
	if (exp != null)
		candidates.put(operator, exp);
	
	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 24
/**
 * Converts "a op b" bean op one of "-", "+", "*", "/"
 *    (  (op(1, 0, "-") && (a - b))
 *    || (op(1, 1, "+") && (a + b))
 *    || (op(1, 2, "*") && (a * b))
 *    || (op(1, 3, "/") && (a / b))
 *    )
 *
 * @param expression
 * @param operators
 */
private void mutateOperator(final CtBinaryOperator<Boolean> expression, EnumSet<BinaryOperatorKind> operators) {
	
	if (!operators.contains(expression.getKind())) {
		throw new IllegalArgumentException("not consistent");
	}

	if (alreadyInHotsSpot(expression)
			|| expression.toString().contains(".is(\"")) {
		System.out
				.println(String
						.format("Expression '%s' ignored because it is included in previous hot spot",
								expression));
		return;
	}

	int thisIndex = ++index;
	BinaryOperatorKind originalKind = expression.getKind();
	String originalExpression = expression.toString();
	
	String newExpression = "";
	
	int cpt = 0;
	BinaryOperatorKind tmp = null;
	for(BinaryOperatorKind op : ARITHMETIC_OPERATORS){
			expression.setKind(op);
			newExpression += "(" + PREFIX + thisIndex + ".is(" + op.getClass().getCanonicalName()+"."+op.toString() + ")) ? (" + expression + ")";
			newExpression += " : ";
	}

	newExpression += "(" + originalExpression + ")"; 
	CtCodeSnippetExpression<Boolean> codeSnippet = getFactory().Core()
			.createCodeSnippetExpression();
	codeSnippet.setValue('(' + newExpression + ')');
	expression.replace(codeSnippet);
	expression.replace(expression);
	Selector.generateSelector(expression, originalKind, thisIndex, operators, PREFIX);
	System.out.println("nb mutants " +index);

	hostSpots.add(expression);
}
 
Example 25
Source Project: nopol   Source File: SpoonModelLibrary.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static CtExpression<Boolean> newConjunctionExpression(Factory factory, CtExpression<Boolean> leftExpression, CtExpression<Boolean> rightExpression) {
    return newComposedExpression(factory, leftExpression, rightExpression, BinaryOperatorKind.AND);
}
 
Example 26
Source Project: nopol   Source File: SpoonModelLibrary.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static CtExpression<Boolean> newDisjunctionExpression(Factory factory, CtExpression<Boolean> leftExpression, CtExpression<Boolean> rightExpression) {
    return newComposedExpression(factory, leftExpression, rightExpression, BinaryOperatorKind.OR);
}
 
Example 27
Source Project: nopol   Source File: SpoonModelLibrary.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static <T> CtExpression<T> newComposedExpression(Factory factory, CtExpression<T> leftExpression, CtExpression<T> rightExpression, BinaryOperatorKind operator) {
    CtBinaryOperator<T> composedExpression = factory.Code().createBinaryOperator(leftExpression, rightExpression, operator);
    setParent(composedExpression, leftExpression, rightExpression);
    return composedExpression;
}
 
Example 28
@Test
public void example() throws Exception {
 Launcher l = new Launcher();
 
 // required for having IFoo.class in the classpath in Maven
 l.setArgs(new String[] {"--source-classpath","target/test-classes"});
 
 l.addInputResource("src/test/resources/transformation/");
 l.buildModel();
 
 CtClass foo = l.getFactory().Package().getRootPackage().getElements(new NamedElementFilter<>(CtClass.class, "Foo1")).get(0);

 // compiling and testing the initial class
 Class<?> fooClass = InMemoryJavaCompiler.newInstance().compile(foo.getQualifiedName(), "package "+foo.getPackage().getQualifiedName()+";"+foo.toString());
 IFoo x = (IFoo) fooClass.newInstance();
 // testing its behavior
 assertEquals(5, x.m());

 // now we apply a transformation
 // we replace "+" by "-"
 for(Object e : foo.getElements(new TypeFilter(CtBinaryOperator.class))) {
  CtBinaryOperator op = (CtBinaryOperator)e;
  if (op.getKind()==BinaryOperatorKind.PLUS) {
	  op.setKind(BinaryOperatorKind.MINUS);
  }
 }
 
 // first assertion on the results of the transfo
 
 // there are no more additions in the code
 assertEquals(0, foo.getElements(new Filter<CtBinaryOperator<?>>() {
@Override
public boolean matches(CtBinaryOperator<?> arg0) {
	return arg0.getKind()==BinaryOperatorKind.PLUS;
}		  
 }).size());

 // second assertions on the behavior of the transformed code
 
 // compiling and testing the transformed class
 fooClass = InMemoryJavaCompiler.newInstance().compile(foo.getQualifiedName(), "package "+foo.getPackage().getQualifiedName()+";"+foo.toString());
 IFoo y = (IFoo) fooClass.newInstance();
 // testing its behavior with subtraction
 assertEquals(1, y.m());
 
 System.out.println("yes y.m()="+y.m());
}
 
Example 29
Source Project: coming   Source File: LogicalExpressionAnalyzer.java    License: MIT License 4 votes vote down vote up
private void analyzeLE9_BothNULLAndNormal(List<CtExpression> logicalExperssions, Cntx<Object> context) {
	
	try {
		
		List<BinaryOperatorKind> logicOperators = Arrays.asList(BinaryOperatorKind.OR, BinaryOperatorKind.AND);

		for (int indexlogical=0; indexlogical<logicalExperssions.size(); indexlogical++) {
			
               CtExpression logicalexpression = logicalExperssions.get(indexlogical);	
			
			List<CtBinaryOperator> binOps = new ArrayList();
			
			CtScanner scanner = new CtScanner() {
				@Override
				public <T> void visitCtBinaryOperator(CtBinaryOperator<T> operator) {
					super.visitCtBinaryOperator(operator);
					
					if (logicOperators.contains(operator.getKind()))
						binOps.add(operator);
				}
			};
			
			scanner.scan(logicalexpression);
			
			List<CtExpression> atomicboolexperssions = new ArrayList();
			
			for(int index=0; index<binOps.size(); index++) {
				CtExpression left= binOps.get(index).getLeftHandOperand();
				CtExpression right=binOps.get(index).getRightHandOperand();
				if(!wheteherCompundBoolExper(binOps, left))
					atomicboolexperssions.add(left);
				if(!wheteherCompundBoolExper(binOps, right))
					atomicboolexperssions.add(right);
			}
			
			boolean whethercontainnormalcheck=false;
			boolean whethercontainnullcheck=false;
			boolean equalnullcheck=false;
			boolean notequalnullcheck=false;
			
			for(int index=0; index<atomicboolexperssions.size(); index++) {
				
				if(!whethercontainnormalcheck) {
				  if(checkNormalGuardCondition(atomicboolexperssions.get(index)))
					  whethercontainnormalcheck=true;
				}
				
			    if(checkNullCheckGuardCondition(atomicboolexperssions.get(index))) {
			    	
					 whethercontainnullcheck=true;
				     List<CtBinaryOperator> specificbinOps = atomicboolexperssions.get(index).getElements(new TypeFilter<>(CtBinaryOperator.class));
 
				     for(int binopindex=0; binopindex<specificbinOps.size(); binopindex++) {
				    	 
				    	 if(specificbinOps.get(binopindex).getKind().toString().equals(BinaryOperatorKind.EQ.toString()))
				    		 equalnullcheck=true;
				    	 if(specificbinOps.get(binopindex).getKind().toString().equals(BinaryOperatorKind.NE.toString()))
				    		 notequalnullcheck=true;
				    	 
				    	 if(equalnullcheck && notequalnullcheck)
				    		 break;
				     }   
				}	
			    
			    if(whethercontainnormalcheck && whethercontainnullcheck && equalnullcheck && notequalnullcheck)
			    	break;
			}
			
			writeGroupedInfo(context, "logical_expression_"+Integer.toString(indexlogical)+"_"+logicalexpression,  
					CodeFeatures.LE9_NORMAL_CHECK,
					(whethercontainnormalcheck && !whethercontainnullcheck), "FEATURES_LOGICAL_EXPRESSION");
			
			writeGroupedInfo(context, "logical_expression_"+Integer.toString(indexlogical)+"_"+logicalexpression,  
					CodeFeatures.LE9_NULL_CHECK,
					(!whethercontainnormalcheck && whethercontainnullcheck), "FEATURES_LOGICAL_EXPRESSION");
			
			writeGroupedInfo(context, "logical_expression_"+Integer.toString(indexlogical)+"_"+logicalexpression,  
					CodeFeatures.LE9_MIX_CHECK,
					(whethercontainnormalcheck && whethercontainnullcheck), "FEATURES_LOGICAL_EXPRESSION");
			
			writeGroupedInfo(context, "logical_expression_"+Integer.toString(indexlogical)+"_"+logicalexpression,  
					CodeFeatures.LE9_EQUAL_NOTEQUAL_NULL_CHECK,
					(equalnullcheck && notequalnullcheck), "FEATURES_LOGICAL_EXPRESSION");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 30
Source Project: coming   Source File: LogicalExpressionAnalyzer.java    License: MIT License 4 votes vote down vote up
private void analyzeLE10_Analyze_Atomic_Boolexps(List<CtExpression> logicalExperssions, Cntx<Object> context) {
	
	try {	
		for (int indexlogical=0; indexlogical<logicalExperssions.size(); indexlogical++) {
			
			CtExpression logicalexpression = logicalExperssions.get(indexlogical);
			
			List<BinaryOperatorKind> logicOperators = Arrays.asList(BinaryOperatorKind.OR, BinaryOperatorKind.AND);
			List<CtBinaryOperator> binOps = new ArrayList();
			
			CtScanner scanner = new CtScanner() {
				@Override
				public <T> void visitCtBinaryOperator(CtBinaryOperator<T> operator) {
					super.visitCtBinaryOperator(operator);
					
					if (logicOperators.contains(operator.getKind()))
						binOps.add(operator);
				}
			};
			
			ExpressionCapturerScanner scanner2 = new ExpressionCapturerScanner();
			scanner2.scan(logicalexpression);
			if (scanner2.toScan != null) {
				scanner.scan(scanner2.toScan);
			} else {
				scanner.scan(logicalexpression);
			}
			
			List<CtExpression> atomicboolexperssions = new ArrayList();
			
			for(int index=0; index<binOps.size(); index++) {
				CtExpression left= binOps.get(index).getLeftHandOperand();
				CtExpression right=binOps.get(index).getRightHandOperand();
				if(!wheteherCompundBoolExper(binOps, left))
					atomicboolexperssions.add(left);
				if(!wheteherCompundBoolExper(binOps, right))
					atomicboolexperssions.add(right);
			}
			
			if(binOps.size()==0)
				atomicboolexperssions.add(logicalexpression);
			
			analyzeExpressions(atomicboolexperssions, context, indexlogical,logicalexpression);
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}