Java Code Examples for spoon.reflect.code.CtCodeSnippetExpression

The following examples show how to use spoon.reflect.code.CtCodeSnippetExpression. 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
/**
 * Add AbsoluteValue, Plus, Minus, Increment or Decrement Unary Operator on Numeric Variable 
 */
@Override
public void process(CtVariableRead candidate) {
	thisIndex++;
	
	String expression = "(";
	for(UNARY unary : absSet){
		if(unary.equals(UNARY.INIT)) continue;
		/*expression += PREFIX+thisIndex + ".is(\"" + unary.toString() + "\")?( " + UnaryEquivalent(unary)  + candidate.toString() + ")):";*/
		expression += PREFIX+thisIndex + ".is(" + unary.getClass().getCanonicalName()+'.'+unary.toString()+ ")?( " + UnaryEquivalent(unary)  + candidate.getVariable().getSimpleName() + ")):";
	}
	expression += "(" + candidate.toString() + "))";
	CtCodeSnippetExpression<Boolean> codeSnippet = getFactory().Core()
			.createCodeSnippetExpression();
	codeSnippet.setValue(expression);
	candidate.replace(codeSnippet);
	
	Selector.generateSelector(candidate, UNARY.INIT, thisIndex, absSet, PREFIX);
}
 
Example 2
Source Project: nopol   Source File: ConditionalAdder.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public CtIf processCondition(CtStatement element, String newCondition) {
    //logger.debug("##### {} ##### Before:\n{}", element, element.getParent());
    // if the element is not a line
    if (!new LineFilter().matches(element)) {
        element = element.getParent(new LineFilter());
    }
    CtElement parent = element.getParent();
    CtIf newIf = element.getFactory().Core().createIf();
    CtCodeSnippetExpression<Boolean> condition = element.getFactory().Core().createCodeSnippetExpression();
    condition.setValue(newCondition);
    newIf.setCondition(condition);
    // Fix : warning: ignoring inconsistent parent for [CtElem1] ( [CtElem2] != [CtElem3] )
    newIf.setParent(parent);
    element.replace(newIf);
    // this should be after the replace to avoid an StackOverflowException caused by the circular reference.
    newIf.setThenStatement(element);
    //logger.debug("##### {} ##### After:\n{}", element, element.getParent().getParent());
    return newIf;
}
 
Example 3
Source Project: astor   Source File: ExpressionGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private static CtExpression fetchExpressionOnType(Factory factory, List<CtVariable> visiablevars, String type, String query, Boolean whetherEnum) {
	if (type == null || type.equals(""))
		return null;
	CtCodeSnippetExpression typeexper = factory.Code().createCodeSnippetExpression(type+".class");
	ArrayList<CtExpression> param = getParameter(factory, visiablevars, type, whetherEnum);
	
	param.add(1, factory.Code().createCodeSnippetExpression(Integer.toString(0)));

	param.add(3, typeexper);
	
	CtExpression[] arr = param.toArray(new CtExpression[param.size()]);
	
	CtExecutableReference<Object> ref = factory.Core().createExecutableReference();
	ref.setSimpleName(query);
	
	CtInvocation methodcall=factory.Code().createInvocation(factory.Code().createCodeSnippetExpression("fr.inria.astor.approaches.scaffold.scaffoldsynthesis.ScaffoldSynthesisEntry"),
			ref, 
			arr);
			
	String castType = primToObj.containsKey(type) ? primToObj.get(type) : type;  
	CtCodeSnippetExpression castedexp = factory.Code().createCodeSnippetExpression("(" + castType+ ")"+"("+methodcall.toString()+
			".invoke()".toString()+")");
	return castedexp;
}
 
Example 4
@Override
public List<CtElement> executeSynthesis(ModificationPoint modificationPoint, CtElement hole, CtType expectedtype,
		List<CtVariable> contextOfModificationPoint, ExecutionContext values) {
	List<CtElement> result = new ArrayList<>();
	DynamothSynthesizer dynamothSynthesizer = new DynamothSynthesizer((DynamothSynthesisContext) values);
	Candidates candidates = dynamothSynthesizer.combineValues();

	for (fr.inria.lille.repair.expression.Expression expression : candidates) {
		String candidateCode = expression.toString();
		log.info("Candidate: " + candidateCode);

		if (hole instanceof CtExpression) {

			CtCodeSnippetExpression<Boolean> snippet = MutationSupporter.getFactory().Core()
					.createCodeSnippetExpression();
			snippet.setValue(candidateCode);
			result.add(snippet);
		} else {
			log.debug("Error: Other type not analyzed " + hole.getClass().getName());
		}

	}

	return result;
}
 
Example 5
/**
 * 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 6
/**
 *
 * @param expression
 * @param operators
 */
private void mutateOperator(final CtExpression expression, EnumSet<Null> operators) {
			
	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;
	
	String actualExpression = expression.toString();
	
	String newExpression = String.format("(%s%s.is(%s))?"+actualExpression+":null",PREFIX,thisIndex,"metamutator.Null.NO");
	
	CtCodeSnippetExpression codeSnippet = getFactory().Core()
			.createCodeSnippetExpression();
	codeSnippet.setValue('(' + newExpression + ')');
	
	expression.replace(codeSnippet);
	expression.replace(expression);
	
	Selector.generateSelector(expression, Null.NO, thisIndex, operators, PREFIX);

	hostSpots.add(expression);

}
 
Example 7
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 8
public void process(CtStatement element) {
    logger.debug("##### {} ##### Before:\n{}", element, element.getParent());
    CtElement parent = element.getParent();
    CtIf newIf = element.getFactory().Core().createIf();
    CtCodeSnippetExpression<Boolean> condition;
    if (getValue() != null) {
        switch (getValue()) {
            case "1":
                condition = element.getFactory().Code()
                        .createCodeSnippetExpression("true");
                break;
            case "0":
                condition = element.getFactory().Code()
                        .createCodeSnippetExpression("false");
                break;
            default:
                condition = element.getFactory().Code()
                        .createCodeSnippetExpression(getValue());
        }
    } else {
        condition = element
                .getFactory()
                .Code()
                .createCodeSnippetExpression(
                        Debug.class.getCanonicalName()
                                + ".makeSymbolicBoolean(\"guess_fix\")");
    }
    newIf.setCondition(condition);
    // Fix : warning: ignoring inconsistent parent for [CtElem1] ( [CtElem2] != [CtElem3] )
    newIf.setParent(parent);
    element.replace(newIf);
    // this should be after the replace to avoid an StackOverflowException caused by the circular reference.
    newIf.setThenStatement(element);
    // Fix : warning: ignoring inconsistent parent for [CtElem1] ( [CtElem2] != [CtElem3] )
    newIf.getThenStatement().setParent(newIf);
    logger.debug("##### {} ##### After:\n{}", element, element.getParent().getParent());
}
 
Example 9
Source Project: astor   Source File: EvalTOSCoreApproach.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected IngredientFromDyna createIngredient(Expression expression) {
	String candidateCode = expression.asPatch();
	CtCodeSnippetExpression<Boolean> snippet = MutationSupporter.getFactory().Core().createCodeSnippetExpression();
	snippet.setValue(candidateCode);
	IngredientFromDyna ingredient = new IngredientFromDyna(snippet, expression);
	// take one form the cluster by type
	log.debug("Creating ingredient from Dynamoth expression: " + expression + " --result--> Spoon Ingredient: "
			+ ingredient + "| value: " + expression.getValue().getRealValue());
	return ingredient;
}
 
Example 10
Source Project: astor   Source File: OperatorGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "static-access" })
public static CtExpression fetchROP(CtBinaryOperator operator, MutationSupporter mutSupporter, 
		ModificationPoint modificationPoint, String type, String querytype) {
	if (type == null || type.equals(""))
		return null;
	
	CtCodeSnippetExpression typeexper = mutSupporter.getFactory().Code().createCodeSnippetExpression(type+".class");

	ArrayList<CtExpression> param = getParameter(mutSupporter.getFactory(), operator);
	param.add(1, mutSupporter.getFactory().Code().createCodeSnippetExpression(Integer.toString(0)));

	param.add(3, typeexper);
	
       CtExpression[] arr = param.toArray(new CtExpression[param.size()]);
	
	CtExecutableReference<Object> ref = mutSupporter.getFactory().Core().createExecutableReference();
	ref.setSimpleName(querytype);
	
	CtInvocation methodcall=mutSupporter.getFactory().Code().createInvocation(mutSupporter.getFactory().Code().
			createCodeSnippetExpression("fr.inria.astor.approaches.scaffold.scaffoldsynthesis.ScaffoldSynthesisEntry"),
			ref, 
			arr);
	
	CtCodeSnippetExpression invokemethod = mutSupporter.getFactory().Code().createCodeSnippetExpression(methodcall.toString()
			+".invoke()".toString());	
	
	return invokemethod;
}
 
Example 11
Source Project: metamutator   Source File: Selector.java    License: GNU General Public License v3.0 4 votes vote down vote up
/** Generates a field containing a new selector for this element and adds it to the current class 
 * 
 */
public static <E> void generateSelector(CtElement element, E initialChoice, int selectorId, EnumSet<?> possibleChoices, String prefix ) {
	
	Class<?> choiceClass = possibleChoices.iterator().next().getClass();
	
	long hashCode = (element.getPosition().toString() + element.getParent()
	.toString()).hashCode();

	CtTypeReference<Object> fieldType = element.getFactory().Type().createTypeParameterReference(ISelector.class.getCanonicalName());
	
	//doesn't work with spoon for the moment
	//CtTypeReference<Object> genericRefs = element.getFactory().Type().createTypeParameterReference(choiceClass.getCanonicalName());
	//fieldType.addActualTypeArgument(genericRefs);
	
	String selectorFieldName = prefix + selectorId;
	
	CtCodeSnippetExpression<Object> codeSnippet = element.getFactory().Core()
			.createCodeSnippetExpression();
	StringBuilder sb = new StringBuilder(Selector.class.getCanonicalName() + ".of(");
	
	// we disable the ids
	// sb.append(procId+""+selectorId);
	// sb.append(',');

	// now the options
	sb.append("new "+choiceClass.getCanonicalName()+"[]{");
	
	// the original operator, always the first one
	sb.append(initialChoice.getClass().getCanonicalName()+"."+initialChoice.toString());
	
	// the other alternatives
	for (Object choose : possibleChoices) {
		if (choose.equals(initialChoice)) {
			continue;
		}
		sb.append(',').append(choose.getClass().getCanonicalName()+"."+choose.toString());
	}
	
	sb.append("})");
	
	// adding location
	if (element.getParent(CtType.class).isTopLevel()) {
		sb.append(".in("
				+ element.getParent(CtType.class).getQualifiedName()
				+ ".class)");
	}
	
	// adding identifier
	sb.append(".id(\"" + selectorFieldName + "\")");
	
	codeSnippet.setValue(sb.toString());
	
	CtClass<?> type = getTopLevelClass(element);
	
	CtField<Object> field = element.getFactory().Field().create(
			type,
			EnumSet.of(ModifierKind.FINAL, ModifierKind.PRIVATE,
					ModifierKind.STATIC), fieldType, selectorFieldName,
			codeSnippet);
	
	type.addField(field);
}
 
Example 12
/**
 * 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 13
private void mutateOperator(final CtStatement expression) {
	
	
	/*if (alreadyInHotsSpot(expression)) {
		System.out
				.println(String
						.format("Expression '%s' ignored because it is included in previous hot spot",
								expression));
		return;
	}*/
	int thisIndex = ++selectorIndex;
	
	ACTIVABLE kind = ACTIVABLE.ENABLED;
	String expressionContent =  String.format("("+ PREFIX + "%s.is(%s))",
			thisIndex, kind.getClass().getCanonicalName()+"."+kind.name());
	
	//create IfChoice with right condition
	CtIf ifChoice = getFactory().Core().createIf();
	CtCodeSnippetExpression expIf = getFactory().Code().createCodeSnippetExpression(expressionContent);
	ifChoice.setCondition(expIf);
		
	
	
	//create block from a clone of expression
	CtStatement exp2 = getFactory().Core().clone(expression);
	CtBlock thenBlock = getFactory().Code().createCtBlock(exp2);
	
	//set if and replace the expression with the new if
	ifChoice.setThenStatement(thenBlock);
	expression.replace(ifChoice);
	
	//to be sure
	ifChoice.getParent().updateAllParentsBelow();
	
	//if there are return or throws, set else with value of return.
	Filter<CtCFlowBreak> filterReturn = new ReturnOrThrowFilter();
	if(!thenBlock.getElements(filterReturn).isEmpty()){
		SetElseStatementWithReturn(ifChoice);
	}

	
	//to avoid to delete assignement in statement, we assign a default value to all local variable.
	Filter<CtLocalVariable> filterLocalVariable =  new TypeFilter<CtLocalVariable>(CtLocalVariable.class);
	CtMethod method = ifChoice.getParent(CtMethod.class);
	if(method != null && !method.getElements(filterLocalVariable).isEmpty()){
		for(CtLocalVariable var : method.getElements(filterLocalVariable)){
			if(var.getAssignment() == null){
				//create right side expression from template.
				Class classOfAssignment = var.getType().getActualClass();
				CtLiteral rightHand = null;
				
				//Particular case of ForEach (int x : numbers) can't be (int x = 0 : numbers)
				if(var.getParent() instanceof CtForEach){
					continue;
				}
				if(PrimitiveTemplateExpressions.containsKey(classOfAssignment)){
					CtLiteral templateExpression = PrimitiveTemplateExpressions.get(classOfAssignment);
					rightHand = getFactory().Core().clone(templateExpression);
				}else{
					rightHand = getFactory().createLiteral().setValue(null);
				}
				var.setAssignment(rightHand);
			}
		}
	}
	
	Selector.generateSelector(expression, ACTIVABLE.ENABLED, thisIndex, ActivableSet, PREFIX);
	//hotSpots.add(expression);

}