spoon.reflect.visitor.Filter Java Examples
The following examples show how to use
spoon.reflect.visitor.Filter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QueryExampleTest.java From spoon-examples with GNU General Public License v2.0 | 6 votes |
@SuppressWarnings("all") @Test public void main() { MavenLauncher launcher = new MavenLauncher( "./src/test/resources/project/", MavenLauncher.SOURCE_TYPE.APP_SOURCE); CtModel model = launcher.buildModel(); List<CtMethod> methodList = model. filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "ow2con")). filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "publicapi")). filterChildren(new TypeFilter<CtMethod>(CtMethod.class)). filterChildren(new Filter<CtMethod>() { @Override public boolean matches(CtMethod element) { boolean isPublic = element.isPublic(); CtTypeReference returnType = element.getType(); String privateApiPackage = "ow2con.privateapi"; boolean isTypeFromPrivateApi = returnType.getQualifiedName().contains(privateApiPackage); return isPublic && isTypeFromPrivateApi; } }).list(); }
Example #2
Source File: LoopExpressionMetaMutator.java From metamutator with GNU General Public License v3.0 | 5 votes |
public String breakOrReturn(CtLoop candidate) { Filter<CtCFlowBreak> filter = new ReturnOrThrowFilter(); if(candidate.getBody().getElements(filter).size() > 0) { return candidate.getBody().getElements(filter).get(0).toString() + ";"; }else { return "break;"; } }
Example #3
Source File: CollectableValueFinder.java From nopol with GNU General Public License v2.0 | 5 votes |
private boolean wasInitializedBefore(CtStatement statement, CtVariable<?> variable) { if (variable.getDefaultExpression() == null) { CtBlock<?> block = variable.getParent(CtBlock.class); Filter<CtAssignment<?, ?>> filter = initializationAssignmentsFilterFor(variable, statement); return !block.getElements(filter).isEmpty(); } return true; }
Example #4
Source File: CollectableValueFinder.java From nopol with GNU General Public License v2.0 | 5 votes |
private Filter<CtAssignment<?, ?>> initializationAssignmentsFilterFor(CtVariable<?> variable, CtStatement statement) { VariableAssignmentFilter variableAssignment = new VariableAssignmentFilter(variable); BeforeLocationFilter<CtAssignment<?, ?>> beforeLocation = new BeforeLocationFilter(CtAssignment.class, statement.getPosition()); InBlockFilter<CtAssignment<?, ?>> inVariableDeclarationBlock = new InBlockFilter(CtAssignment.class, asList(variable.getParent(CtBlock.class))); InBlockFilter<CtAssignment<?, ?>> inStatementBlock = new InBlockFilter(CtAssignment.class, asList(statement.getParent(CtBlock.class))); Filter<CtAssignment<?, ?>> inBlockFilter = new CompositeFilter(FilteringOperator.UNION, inStatementBlock, inVariableDeclarationBlock); return new CompositeFilter(FilteringOperator.INTERSECTION, variableAssignment, beforeLocation, inBlockFilter); }
Example #5
Source File: IfCountingInstrumentingProcessor.java From nopol with GNU General Public License v2.0 | 5 votes |
@Override public void process(final CtMethod<?> method) { if (method != null) { if (isTestCase(method)) { instrumentMethod(method); } else { if (method.getBody() != null) { List<CtIf> ifList = method.getBody().getElements( new Filter<CtIf>() { @Override public boolean matches(CtIf arg0) { if (!(arg0 instanceof CtIf)) { return false; } return true; } }); for (CtIf tmp : ifList) { instrumentIfInsideMethod(tmp); } } } String s = method.getDeclaringType().getQualifiedName(); if (this.ifMetric != null && !this.ifMetric.modifyClass.contains(s)) { this.ifMetric.modifyClass.add(s); } } }
Example #6
Source File: ValuesCollectorTest.java From nopol with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings({"unchecked", "rawtypes"}) private CtElement elementFromSnippet(File sourceFile, String codeSnippet) { Factory model = SpoonModelLibrary.modelFor(new File[]{sourceFile}); Filter filter = new CodeSnippetFilter(sourceFile, codeSnippet); // used to debug when the pretty-printed format of Spoon changes // for (CtType t : model.getModel().getAllTypes()) { // System.out.println(t); //} List<CtElement> elements = SpoonElementLibrary.filteredElements(model, filter); assertEquals(1, elements.size()); return elements.get(0); }
Example #7
Source File: StatementDeletionMetaMutator.java From metamutator with GNU General Public License v3.0 | 4 votes |
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); }
Example #8
Source File: SpoonElementLibrary.java From nopol with GNU General Public License v2.0 | 4 votes |
public static <T extends CtElement> List<T> filteredElements(Factory factory, Filter<T> filter) { return Query.getElements(factory, filter); }
Example #9
Source File: OnTheFlyTransfoTest.java From spoon-examples with GNU General Public License v2.0 | 4 votes |
@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 #10
Source File: BigTransfoScenarioTest.java From spoon-examples with GNU General Public License v2.0 | 4 votes |
@SuppressWarnings("all") @Test public void main() { MavenLauncher launcher = new MavenLauncher( "./src/test/resources/project/", MavenLauncher.SOURCE_TYPE.APP_SOURCE); CtModel model = launcher.buildModel(); List<CtMethod> methodList = model. filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "ow2con")). filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "publicapi")). filterChildren(new TypeFilter<CtMethod>(CtMethod.class)). filterChildren(new Filter<CtMethod>() { @Override public boolean matches(CtMethod element) { boolean isPublic = element.isPublic(); CtTypeReference returnType = element.getType(); String privateApiPackage = "ow2con.privateapi"; boolean isTypeFromPrivateApi = returnType.getQualifiedName().contains(privateApiPackage); return isPublic && isTypeFromPrivateApi; } }).list(); Factory factory = launcher.getFactory(); CtClass<? extends Throwable> exceptionClass = factory.createClass("ow2con.PrivateAPIException"); CtConstructorCall<? extends Throwable> exceptionInstance = factory.createConstructorCall(exceptionClass.getReference()); for (CtMethod method : methodList) { CtBlock methodBody = method.getBody(); List<CtComment> bodyComments = new ArrayList<>(); ArrayList<CtStatement> ctStatements = new ArrayList<>(methodBody.getStatements()); for (CtStatement ctStatement : ctStatements) { String statement = ctStatement.toString(); CtComment statementAsComment = factory.createInlineComment(statement); bodyComments.add(statementAsComment); methodBody.removeStatement(ctStatement); } CtThrow throwMyException = factory.createThrow(); CtConstructorCall<? extends Throwable> constructorCall = exceptionInstance.clone(); throwMyException.setThrownExpression(constructorCall); methodBody.addStatement(throwMyException); bodyComments.add( factory.createInlineComment( "FIXME: The private API type should never be return in a public API." ) ); for (CtComment bodyComment : bodyComments) { throwMyException.addComment(bodyComment); } } Environment environment = launcher.getEnvironment(); environment.setCommentEnabled(true); environment.setAutoImports(true); // the transformation must produce compilable code environment.setShouldCompile(true); launcher.prettyprint(); // look in folder spooned/ow2con/publicapi/ the transformed code }
Example #11
Source File: MutationTester.java From spoon-examples with GNU General Public License v2.0 | 4 votes |
/** returns a list of mutant classes */ public void generateMutants() { Launcher l = new Launcher(); l.addInputResource(sourceCodeToBeMutated); l.buildModel(); CtClass origClass = (CtClass) l.getFactory().Package().getRootPackage() .getElements(new TypeFilter(CtClass.class)).get(0); // now we apply a transformation // we replace "+" and "*" by "-" List<CtElement> elementsToBeMutated = origClass.getElements(new Filter<CtElement>() { @Override public boolean matches(CtElement arg0) { return mutator.isToBeProcessed(arg0); } }); for (CtElement e : elementsToBeMutated) { // this loop is the trickiest part // because we want one mutation after the other // cloning the AST element CtElement op = l.getFactory().Core().clone(e); // mutate the element mutator.process(op); // temporarily replacing the original AST node with the mutated element replace(e,op); // creating a new class containing the mutating code CtClass klass = l.getFactory().Core() .clone(op.getParent(CtClass.class)); // setting the package klass.setParent(origClass.getParent()); // adding the new mutant to the list mutants.add(klass); // restoring the original code replace(op, e); } }