spoon.reflect.code.CtLocalVariable Java Examples
The following examples show how to use
spoon.reflect.code.CtLocalVariable.
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: SpecialStatementFixSpaceProcessor.java From astor with GNU General Public License v2.0 | 6 votes |
@Override public void process(CtStatement element) { if (element instanceof CtIf) { add(((CtIf) element).getCondition()); } else if (element instanceof CtFor) { add(((CtFor) element).getExpression()); } else if (element instanceof CtWhile) { add(((CtWhile) element).getLoopingExpression()); } else if (element instanceof CtDo) { add(((CtDo) element).getLoopingExpression()); } else if (element instanceof CtThrow) { add(((CtThrow) element).getThrownExpression()); } else if (element instanceof CtInvocation && (element.getParent() instanceof CtBlock)) { add(element); } else if (element instanceof CtAssignment || element instanceof CtConstructorCall || element instanceof CtCFlowBreak || element instanceof CtLocalVariable) { add(element); } }
Example #2
Source File: LoggingInstrumenter.java From nopol with GNU General Public License v2.0 | 6 votes |
@Override public void process(CtStatement statement) { String evaluationAccess = "runtimeAngelicValue"; // create the angelic value String type = subprocessor.getType().getCanonicalName(); CtLocalVariable<?> evaluation = newLocalVariableDeclaration( statement.getFactory(), subprocessor.getType(), evaluationAccess, "(" + type + ")" + this.getClass().getCanonicalName() + ".getValue(" + subprocessor.getDefaultValue() + ")"); // insert angelic value before the statement insertBeforeUnderSameParent(evaluation, statement); // collect values of the statement appendValueCollection(statement, evaluationAccess); // insert angelic value in the condition subprocessor.setValue("runtimeAngelicValue"); subprocessor().process(statement); }
Example #3
Source File: LiteralReplacer.java From nopol with GNU General Public License v2.0 | 6 votes |
private void replaceInteger(CtExpression ctElement) { if (getValue() == null) { CtLocalVariable<Integer> evaluation = newLocalVariableDeclaration( ctElement.getFactory(), int.class, "guess_fix", Debug.class.getCanonicalName() + ".makeSymbolicInteger(\"guess_fix\")"); CtStatement firstStatement = getFirstStatement(ctElement); if (firstStatement == null) { return; } SpoonStatementLibrary.insertBeforeUnderSameParent(evaluation, firstStatement); // SpoonStatementLibrary.insertAfterUnderSameParent(getFactory().Code().createCodeSnippetStatement("System.out.println(\"guess_fix: \" + guess_fix)"), // getFirstStatement(ctElement)); ctElement.replace(getFactory().Code().createCodeSnippetExpression("guess_fix")); } else { ctElement.replace(getFactory().Code().createCodeSnippetExpression(getValue())); } }
Example #4
Source File: LiteralReplacer.java From nopol with GNU General Public License v2.0 | 6 votes |
private void replaceDouble(CtExpression ctElement) { if (getValue() == null) { CtLocalVariable<Double> evaluation = newLocalVariableDeclaration( ctElement.getFactory(), double.class, "guess_fix", Debug.class.getCanonicalName() + ".makeSymbolicReal(\"guess_fix\")"); CtStatement firstStatement = getFirstStatement(ctElement); if (firstStatement == null) { return; } SpoonStatementLibrary.insertBeforeUnderSameParent(evaluation, firstStatement); // SpoonStatementLibrary.insertAfterUnderSameParent(getFactory().Code().createCodeSnippetStatement("System.out.println(\"guess_fix: \" + guess_fix)"), // getFirstStatement(ctElement)); ctElement.replace(getFactory().Code().createCodeSnippetExpression("guess_fix")); } else { ctElement.replace(getFactory().Code().createCodeSnippetExpression(getValue())); } }
Example #5
Source File: AssertionGenerationTest.java From spoon-examples with GNU General Public License v2.0 | 5 votes |
@Test public void test() { Launcher launcher = new Launcher(); launcher.getEnvironment().setAutoImports(true); launcher.getEnvironment().setLevel(Level.ALL.toString()); launcher.addInputResource("src/test/resources/project/src/main/java/"); launcher.addInputResource("src/test/resources/project/src/test/java/"); launcher.addInputResource("src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java"); launcher.getEnvironment().setSourceClasspath(getPathToJunit()); launcher.buildModel(); final Analyzer analyzer = new Analyzer(); final Collector collector = new Collector(launcher.getFactory()); final AssertionAdder assertionAdder = new AssertionAdder(launcher.getFactory()); launcher.getFactory().Class().getAll().forEach(ctClass -> { // Analyze Map<CtMethod, List<CtLocalVariable>> localVariablesPerTestMethod = analyzer.analyze(ctClass); localVariablesPerTestMethod.keySet().stream().forEach(key -> System.out.println("{"+ key.getParent(CtClass.class).getSimpleName() + "#" + key.getSimpleName() + "=["+ localVariablesPerTestMethod.get(key) +"]")); if (!localVariablesPerTestMethod.isEmpty()) { // Collect localVariablesPerTestMethod.keySet().forEach(ctMethod -> collector.collect(launcher, ctMethod, localVariablesPerTestMethod.get(ctMethod))); // Generate localVariablesPerTestMethod.keySet().forEach(ctMethod -> assertionAdder.addAssertion(ctMethod, localVariablesPerTestMethod.get(ctMethod))); } }); }
Example #6
Source File: AssertionAdder.java From spoon-examples with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("unchecked") void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> { String key = getKey(getter); CtInvocation invocationToGetter = invok(getter, localVariable); CtInvocation invocationToAssert = createAssert("assertEquals", factory.createLiteral(Logger.observations.get(key)), // expected invocationToGetter); // actual testMethod.getBody().insertEnd(invocationToAssert); }); }
Example #7
Source File: Analyzer.java From spoon-examples with GNU General Public License v2.0 | 5 votes |
public Map<CtMethod, List<CtLocalVariable>> analyze(CtType<?> ctClass) { CtTypeReference<Test> reference = ctClass.getFactory().Type().createReference(Test.class); return ctClass.getMethods().stream() .filter(ctMethod -> ctMethod.getAnnotation(reference) != null) .collect(Collectors.toMap( ctMethod -> ctMethod, this::analyze) ); }
Example #8
Source File: Analyzer.java From spoon-examples with GNU General Public License v2.0 | 5 votes |
List<CtLocalVariable> analyze(CtMethod testMethod) { TypeFilter filterLocalVar = new TypeFilter(CtLocalVariable.class) { public boolean matches(CtLocalVariable localVariable) { return !localVariable.getType().isPrimitive(); } }; return testMethod.getElements(filterLocalVar); }
Example #9
Source File: Collector.java From spoon-examples with GNU General Public License v2.0 | 5 votes |
void instrument(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> { CtInvocation invocationToGetter = invok(getter, localVariable); CtInvocation invocationToObserve = createObserve(getter, invocationToGetter); testMethod.getBody().insertEnd(invocationToObserve); }); }
Example #10
Source File: VariableResolver.java From coming with MIT License | 5 votes |
/** * Return the local variables of a block from the beginning until the element * located at positionEl. * * @param positionEl analyze variables from the block until that position. * @param pb a block to search the local variables * @return */ protected static List<CtLocalVariable> retrieveLocalVariables(int positionEl, CtBlock pb) { List stmt = pb.getStatements(); List<CtLocalVariable> variables = new ArrayList<CtLocalVariable>(); for (int i = 0; i < positionEl; i++) { CtElement ct = (CtElement) stmt.get(i); if (ct instanceof CtLocalVariable) { variables.add((CtLocalVariable) ct); } } CtElement beforei = pb; CtElement parenti = pb.getParent(); boolean continueSearch = true; // We find the parent block while (continueSearch) { if (parenti == null) { continueSearch = false; parenti = null; } else if (parenti instanceof CtBlock) { continueSearch = false; } else { beforei = parenti; parenti = parenti.getParent(); } } if (parenti != null) { int pos = ((CtBlock) parenti).getStatements().indexOf(beforei); variables.addAll(retrieveLocalVariables(pos, (CtBlock) parenti)); } return variables; }
Example #11
Source File: Collector.java From spoon-examples with GNU General Public License v2.0 | 5 votes |
public void collect(Launcher launcher, CtMethod<?> testMethod, List<CtLocalVariable> localVariables) { CtClass testClass = testMethod.getParent(CtClass.class); testClass.removeMethod(testMethod); CtMethod<?> clone = testMethod.clone(); instrument(clone, localVariables); testClass.addMethod(clone); System.out.println(clone); run(launcher, testClass, clone); testClass.removeMethod(clone); testClass.addMethod(testMethod); }
Example #12
Source File: Util.java From spoon-examples with GNU General Public License v2.0 | 5 votes |
public static List<CtMethod> getGetters(CtLocalVariable localVariable) { return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() .filter(method -> method.getParameters().isEmpty() && method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && (method.getSimpleName().startsWith("get") || method.getSimpleName().startsWith("is")) ).collect(Collectors.toList()); }
Example #13
Source File: LiteralReplacer.java From nopol with GNU General Public License v2.0 | 5 votes |
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 #14
Source File: LiteralReplacer.java From nopol with GNU General Public License v2.0 | 5 votes |
@Override public void process(CtStatement ctStatement) { if (!(ctStatement instanceof CtLocalVariable<?>) && !(ctStatement instanceof CtAssignment<?, ?>)) return; Class<?> localVariableClass = ((CtTypedElement<?>) ctStatement).getType().getActualClass(); if (localVariableClass.equals(Integer.class) || localVariableClass.equals(int.class)) { if (ctStatement instanceof CtAssignment<?, ?>) { replaceInteger(((CtAssignment<?, ?>) ctStatement).getAssignment()); } else { replaceInteger(((CtLocalVariable<?>) ctStatement).getDefaultExpression()); } } else if (localVariableClass.equals(Double.class) || localVariableClass.equals(double.class)) { if (ctStatement instanceof CtAssignment<?, ?>) { replaceDouble(((CtAssignment<?, ?>) ctStatement).getAssignment()); } else { replaceDouble(((CtLocalVariable<?>) ctStatement).getDefaultExpression()); } } else if (localVariableClass.equals(Boolean.class) || localVariableClass.equals(boolean.class)) { if (ctStatement instanceof CtAssignment<?, ?>) { replaceBoolean(((CtAssignment<?, ?>) ctStatement).getAssignment()); } else { replaceBoolean(((CtLocalVariable<?>) ctStatement).getDefaultExpression()); } } }
Example #15
Source File: LiteralReplacer.java From nopol with GNU General Public License v2.0 | 5 votes |
public LiteralReplacer(Class<?> cl, CtStatement statement, RepairType repairType) { super(statement, repairType); if (statement instanceof CtAssignment<?, ?>) { super.setDefaultValue(((CtAssignment<?, ?>) statement).getAssignment().toString()); } else if (statement instanceof CtLocalVariable<?>) { super.setDefaultValue(((CtLocalVariable<?>) statement).getDefaultExpression().toString()); } super.setType(cl); }
Example #16
Source File: RemoveOp.java From astor with GNU General Public License v2.0 | 5 votes |
@Override public boolean canBeAppliedToPoint(ModificationPoint point) { if (!(point.getCodeElement() instanceof CtStatement)) return false; // Do not remove local declaration if (point.getCodeElement() instanceof CtLocalVariable) { CtLocalVariable lv = (CtLocalVariable) point.getCodeElement(); boolean shadow = false; CtClass parentC = point.getCodeElement().getParent(CtClass.class); List<CtField> ff = parentC.getFields(); for (CtField<?> f : ff) { if (f.getSimpleName().equals(lv.getSimpleName())) shadow = true; } if (!shadow) return false; } // do not remove the last statement CtMethod parentMethd = point.getCodeElement().getParent(CtMethod.class); if (point.getCodeElement() instanceof CtReturn && parentMethd.getBody().getLastStatement().equals(point.getCodeElement())) { return false; } // Otherwise, accept the element return true; }
Example #17
Source File: VariableResolver.java From astor with GNU General Public License v2.0 | 5 votes |
private static List<CtLocalVariable> getVarsInFor(CtElement element) { List<CtLocalVariable> variables = new ArrayList<CtLocalVariable>(); CtElement currentElement = element; CtFor ff = currentElement.getParent(CtFor.class); while (ff != null) { variables.addAll(ff.getForInit().stream().filter(e -> e instanceof CtLocalVariable) .map(CtLocalVariable.class::cast).collect(Collectors.toList())); ff = ff.getParent(CtFor.class); } return variables; }
Example #18
Source File: VariableResolver.java From astor with GNU General Public License v2.0 | 5 votes |
private static List<CtLocalVariable> getVarsInForEach(CtElement element) { List<CtLocalVariable> variables = new ArrayList<CtLocalVariable>(); CtElement currentElement = element; CtForEach ff = currentElement.getParent(CtForEach.class); while (ff != null) { variables.add((CtLocalVariable) ff.getVariable()); ff = ff.getParent(CtForEach.class); } return variables; }
Example #19
Source File: VariableResolver.java From astor with GNU General Public License v2.0 | 5 votes |
/** * Return the local variables of a block from the beginning until the element * located at positionEl. * * @param positionEl analyze variables from the block until that position. * @param pb a block to search the local variables * @return */ protected static List<CtLocalVariable> retrieveLocalVariables(int positionEl, CtBlock pb) { List stmt = pb.getStatements(); List<CtLocalVariable> variables = new ArrayList<CtLocalVariable>(); for (int i = 0; i < positionEl; i++) { CtElement ct = (CtElement) stmt.get(i); if (ct instanceof CtLocalVariable) { variables.add((CtLocalVariable) ct); } } CtElement beforei = pb; CtElement parenti = pb.getParent(); boolean continueSearch = true; // We find the parent block while (continueSearch) { if (parenti == null) { continueSearch = false; parenti = null; } else if (parenti instanceof CtBlock) { continueSearch = false; } else { beforei = parenti; parenti = parenti.getParent(); } } if (parenti != null) { int pos = ((CtBlock) parenti).getStatements().indexOf(beforei); variables.addAll(retrieveLocalVariables(pos, (CtBlock) parenti)); } return variables; }
Example #20
Source File: AstComparatorTest.java From gumtree-spoon-ast-diff with Apache License 2.0 | 5 votes |
@Test public void test_t_211903() throws Exception { AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_211903/left_MemberFilePersister_1.4.java // src/test/resources/examples/t_211903/right_MemberFilePersister_1.5.java File fl = new File("src/test/resources/examples/t_211903/left_MemberFilePersister_1.4.java"); File fr = new File("src/test/resources/examples/t_211903/right_MemberFilePersister_1.5.java"); Diff result = diff.compare(fl, fr); // result.debugInformation(); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtConstructorCall); assertEquals(88, ancestor.getPosition().getLine()); List<Operation> actions = result.getRootOperations(); // result.debugInformation(); assertTrue( result.containsOperation(OperationKind.Update, "ConstructorCall", "java.io.FileReader(java.io.File)")); assertTrue(result.containsOperation(OperationKind.Insert, "ConstructorCall", "java.io.InputStreamReader(java.io.InputStream,java.lang.String)")); // additional checks on low-level actions assertTrue(result.containsOperations(result.getAllOperations(), OperationKind.Insert, "Literal", "\"UTF-8\"")); // the change is in the local variable declaration CtElement elem = actions.get(0).getNode(); assertNotNull(elem); assertNotNull(elem.getParent(CtLocalVariable.class)); }
Example #21
Source File: OriginalFeatureExtractor.java From coming with MIT License | 4 votes |
private EnumSet<ValueFeature> getValueFeature(final String valueStr, final Repair repair, Map<String, CtElement> valueExprInfo) { EnumSet<ValueFeature> valueFeatures = EnumSet.noneOf(ValueFeature.class); if (repair.oldRExpr != null && repair.newRExpr != null) { String oldStr = repair.oldRExpr.toString(); String newStr = repair.newRExpr.toString(); if (valueStr.equals(newStr)) valueFeatures.add(ValueFeature.MODIFIED_VF); // I can not figure out the meaning of MODIFIED_SIMILAR_VF if (oldStr.length() > 0 && newStr.length() > 0) { double ratio = ((double)oldStr.length()) / newStr.length(); if (ratio > 0.5 && ratio < 2 && oldStr.length() > 3 && newStr.length() > 3) if (oldStr.contains(newStr) || newStr.contains(oldStr)) valueFeatures.add(ValueFeature.MODIFIED_SIMILAR_VF); } } CtElement element = repair.dstElem; if (element != null) { CtMethod FD = element.getParent(new TypeFilter<>(CtMethod.class)); if (FD != null) { for (Object parameter: FD.getParameters()) { if (parameter instanceof CtParameter) { CtParameter VD = (CtParameter) parameter; if (VD.getSimpleName().equals(valueStr)) valueFeatures.add(ValueFeature.FUNC_ARGUMENT_VF); } } } } assert(valueExprInfo.containsKey(valueStr)); CtElement E = valueExprInfo.get(valueStr); if (E instanceof CtVariableAccess || E instanceof CtArrayAccess || E instanceof CtLocalVariable) { if (E instanceof CtLocalVariable) { valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF); } else { valueFeatures.add(ValueFeature.GLOBAL_VARIABLE_VF); } } else if (E instanceof CtExecutableReference){ // just make CALLEE_AF be meaningful if (((CtExecutableReference) E).getParameters().size() > 0){ valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF); } } else if (E instanceof CtIf){ // just make R_STMT_COND_AF be meaningful valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF); } // if (E instanceof CtVariable) { // if (E instanceof CtLocalVariable) // valueFeatures.add(SchemaFeature.LOCAL_VARIABLE_VF); // else // valueFeatures.add(SchemaFeature.GLOBAL_VARIABLE_VF); // } else if (E instanceof CtVariableReference) { // if (E instanceof CtLocalVariableReference) // valueFeatures.add(SchemaFeature.LOCAL_VARIABLE_VF); // else // valueFeatures.add(SchemaFeature.GLOBAL_VARIABLE_VF); // } if (valueStr.contains("length") || valueStr.contains("size")) valueFeatures.add(ValueFeature.SIZE_LITERAL_VF); if (E.getElements(new TypeFilter<>(CtField.class)).size() > 0) valueFeatures.add(ValueFeature.MEMBER_VF); if (E instanceof CtLiteral) { Object value = ((CtLiteral)E).getValue(); if (value instanceof String) { valueFeatures.add(ValueFeature.STRING_LITERAL_VF); } else if (value instanceof Integer) { // ? if ((Integer) value == 0) { valueFeatures.add(ValueFeature.ZERO_CONST_VF); } else { valueFeatures.add(ValueFeature.NONZERO_CONST_VF); } } } return valueFeatures; }
Example #22
Source File: VariableResolverTest.java From astor with GNU General Public License v2.0 | 4 votes |
@Test public void testExample288VariablesLocalAccess() throws Exception { // then to remove induction variables from varAccessCollected, // we would look for the induction variables' names in // varAccessCollected // and remove the local accesses but leave static references to those // names in the collection AstorMain main1 = new AstorMain(); String[] args = new String[] { "-dependencies", dep, "-mode", "jgenprog", "-failing", "org.apache.commons.math.optimization.linear.SimplexSolverTest", "-location", new File("./examples/Math-issue-288").getAbsolutePath(), "-package", "org.apache.commons", "-srcjavafolder", "/src/main/java/", "-srctestfolder", "/src/main/test/", "-binjavafolder", "/target/classes", "-bintestfolder", "/target/test-classes", "-javacompliancelevel", "7", // "-flthreshold", "0.2", "-out", // out.getAbsolutePath(), "-scope", "package", "-seed", "10", // Force not evolution "-maxgen", "0", "-population", "1", // "-stopfirst", "true", "-maxtime", "100" }; main1.execute(args); List<ProgramVariant> variants = main1.getEngine().getVariants(); JGenProg jgp = (JGenProg) main1.getEngine(); ModificationPoint mp = findModPoint(variants.get(0).getModificationPoints(), "return minPos");// variants.get(0).getModificationPoints().get(0); log.debug("Mpoint \n" + mp); log.debug(mp.getCtClass()); log.debug("Mpoint Context \n" + mp.getContextOfModificationPoint()); IngredientPool ispace = jgp.getIngredientSearchStrategy().getIngredientSpace(); List<Ingredient> ingredients = ispace.getIngredients(mp.getCodeElement()); // For with a induction variable CtElement ifor = findElement(ingredients, "for (int i = tableau.getNumObjectiveFunctions").getCode();// ingredients.get(46); // //for // (int // i // = // tableau.getNumObjectiveFunctions() assertTrue(ifor.toString().startsWith("for (int i = tableau.getNumObjectiveFunctions")); assertTrue(ifor instanceof CtFor); log.debug("fit? " + ifor + " in context: " + mp.getContextOfModificationPoint()); boolean matchFor = VariableResolver.fitInContext(mp.getContextOfModificationPoint(), ifor, true); // the variable 'i' is declared inside the ingredient, and event it does // not exist assertTrue(matchFor); CtElement iif = findElement(ingredients, "if ((org.apache.commons.math.util.MathUtils.compareTo(tableau.getEntry(0, i)").getCode();// ingredients.get(45); // //if // ((org.apache.commons.math.util.MathUtils.compareTo(tableau.getEntry(0, // i), assertTrue(TestHelper.getWithoutParentheses(iif.toString()).startsWith(TestHelper.getWithoutParentheses( "if ((org.apache.commons.math.util.MathUtils.compareTo(tableau.getEntry(0, i)"))); assertTrue(iif instanceof CtIf); boolean matchIf = VariableResolver.fitInContext(mp.getContextOfModificationPoint(), iif, true); // the variable 'i' does not exist in the context assertFalse(matchIf); CtElement iStaticSame = findElement(ingredients, "setMaxIterations(").getCode();// ingredients.get(0);//static // setMaxIterations(org.apache.commons.math.optimization.linear.AbstractLinearOptimizer.DEFAULT_MAX_ITERATIONS) assertTrue(iStaticSame instanceof CtInvocation); assertTrue(iStaticSame.toString().startsWith("setMaxIterations(")); boolean matchStSame = VariableResolver.fitInContext(mp.getContextOfModificationPoint(), iStaticSame, true); assertTrue(matchStSame); CtElement iStaticDouble = findElement(ingredients, "double minRatio = java.lang.Double.MAX_VALUE").getCode();// ingredients.get(55);//static assertTrue(iStaticDouble instanceof CtLocalVariable); assertTrue(iStaticDouble.toString().startsWith("double minRatio = java.lang.Double.MAX_VALUE")); boolean matchSt = VariableResolver.fitInContext(mp.getContextOfModificationPoint(), iStaticDouble, true); assertTrue(matchSt); }
Example #23
Source File: AstComparatorTest.java From gumtree-spoon-ast-diff with Apache License 2.0 | 4 votes |
@Test public void testReplaceMovesFromRoot2() { String c1 = "" + "class X {" + "public void foo0() {" + " int z = 0;" + " int x = 0;" + " int y = 0;" + "}" + "};"; String c2 = "" + "class X {" + "public void foo0() {" + " int x = 0;" + " int y = 0;" + "if(y>0){ int z = 0;}" + "}" + "};"; AstComparator diff = new AstComparator(); Diff editScript = diff.compare(c1, c2); assertEquals(2, editScript.getRootOperations().size()); assertEquals(1, editScript.getAllOperations().stream().filter(e -> e instanceof MoveOperation).count()); Optional<Operation> moveOpt = editScript.getAllOperations().stream().filter(e -> e instanceof MoveOperation) .findAny(); assertTrue(moveOpt.isPresent()); List<Operation> newOps = ActionClassifier.replaceMoveFromRoots(editScript); Optional<Operation> moveOptN = newOps.stream().filter(e -> e instanceof MoveOperation).findAny(); assertFalse(moveOptN.isPresent()); Move moveAction = (Move) (moveOpt.get().getAction()); assertFalse(editScript.getMappingsComp().hasSrc(moveAction.getParent())); assertFalse(editScript.getMappingsComp().hasDst(moveAction.getParent())); Optional<Operation> insertOpt = newOps.stream() .filter(e -> e instanceof InsertOperation && e.getNode() instanceof CtLocalVariable).findAny(); // The insert must not exist assertFalse(insertOpt.isPresent()); Optional<Operation> deleteOpt = newOps.stream() .filter(e -> e instanceof DeleteOperation && e.getNode() instanceof CtLocalVariable).findAny(); assertTrue(deleteOpt.isPresent()); assertEquals(2, newOps.size()); Optional<Operation> insertIfOpt = newOps.stream() .filter(e -> e instanceof InsertOperation && e.getNode() instanceof CtIf).findAny(); assertTrue(insertIfOpt.isPresent()); // Same object assertTrue(deleteOpt.get().getNode() == moveOpt.get().getNode()); assertTrue(deleteOpt.get().getAction().getNode() == moveOpt.get().getAction().getNode()); // Same content assertEquals(deleteOpt.get().getNode().toString(), moveOpt.get().getNode().toString()); }
Example #24
Source File: VariableAnalyzer.java From coming with MIT License | 4 votes |
private void analyzeV15_LastthreeVariableIntroduction (List<CtVariableAccess> varsAffected, CtElement element, Cntx<Object> context) { try { CtExecutable methodParent = element.getParent(CtExecutable.class); if (methodParent == null) // the element is not in a method. return; List<CtStatement> statements=methodParent.getElements(new LineFilter()); // For each variable affected for (CtVariableAccess variableAffected : varsAffected) { List<CtStatement> statementbefore = new ArrayList<>(); boolean lastthreesametypeloc=false; for (CtStatement aStatement : statements) { CtStatement parent = variableAffected.getParent(new LineFilter()); if (!isElementBeforeVariable(variableAffected, aStatement)) continue; if (isStatementInControl(parent, aStatement) || parent==aStatement) continue; if(aStatement instanceof CtIf || aStatement instanceof CtLoop) continue; statementbefore.add(aStatement); } List<CtStatement> statinterest = new ArrayList<>(); if(statementbefore.size()<=4) statinterest=statementbefore; else { statinterest.add(statementbefore.get(statementbefore.size()-1)); statinterest.add(statementbefore.get(statementbefore.size()-2)); statinterest.add(statementbefore.get(statementbefore.size()-3)); statinterest.add(statementbefore.get(statementbefore.size()-4)); } for (int index=0; index< statinterest.size(); index++) { if(statinterest.get(index) instanceof CtLocalVariable) { CtLocalVariable ctLocalVariable=(CtLocalVariable)statinterest.get(index); if (!ctLocalVariable.getReference().getSimpleName() .equals(variableAffected.getVariable().getSimpleName()) && compareTypes(ctLocalVariable.getType(), variableAffected.getType())) { lastthreesametypeloc = true; break; } } } writeGroupedInfo(context, adjustIdentifyInJson(variableAffected), CodeFeatures.V15_VAR_LAST_THREE_SAME_TYPE_LOC, (lastthreesametypeloc), "FEATURES_VARS"); } } catch (Throwable e) { e.printStackTrace(); } }
Example #25
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 #26
Source File: AstComparatorTest.java From gumtree-spoon-ast-diff with Apache License 2.0 | 4 votes |
@Test public void testReplaceMovesFromAll2() { String c1 = "" + "class X {" + "public void foo0() {" + " int z = 0;" + " int x = 0;" + " int y = 0;" + "}" + "};"; String c2 = "" + "class X {" + "public void foo0() {" + " int x = 0;" + " int y = 0;" + "if(y>0){ int z = 0;}" + "}" + "};"; AstComparator diff = new AstComparator(); Diff editScript = diff.compare(c1, c2); assertEquals(2, editScript.getRootOperations().size()); assertEquals(1, editScript.getAllOperations().stream().filter(e -> e instanceof MoveOperation).count()); Optional<Operation> moveOpt = editScript.getAllOperations().stream().filter(e -> e instanceof MoveOperation) .findAny(); assertTrue(moveOpt.isPresent()); List<Operation> newOps = ActionClassifier.replaceMoveFromAll(editScript); Optional<Operation> moveOptN = newOps.stream().filter(e -> e instanceof MoveOperation).findAny(); assertFalse(moveOptN.isPresent()); Move moveAction = (Move) (moveOpt.get().getAction()); assertFalse(editScript.getMappingsComp().hasSrc(moveAction.getParent())); assertFalse(editScript.getMappingsComp().hasDst(moveAction.getParent())); Optional<Operation> insertOpt = newOps.stream() .filter(e -> e instanceof InsertOperation && e.getNode() instanceof CtLocalVariable).findAny(); // The insert must exist in all assertTrue(insertOpt.isPresent()); Optional<Operation> deleteOpt = newOps.stream() .filter(e -> e instanceof DeleteOperation && e.getNode() instanceof CtLocalVariable).findAny(); assertTrue(deleteOpt.isPresent()); Optional<Operation> insertIfOpt = newOps.stream() .filter(e -> e instanceof InsertOperation && e.getNode() instanceof CtIf).findAny(); assertTrue(insertIfOpt.isPresent()); // Same object assertTrue(deleteOpt.get().getNode() == moveOpt.get().getNode()); assertTrue(deleteOpt.get().getAction().getNode() == moveOpt.get().getAction().getNode()); // Same content assertEquals(deleteOpt.get().getNode().toString(), moveOpt.get().getNode().toString()); }
Example #27
Source File: VariableAnalyzer.java From coming with MIT License | 4 votes |
/** * For each involved variable, is there any other variable in scope that is a * certain function transformation of the involved variable * * @param varsAffected * @param element * @param context */ @SuppressWarnings("rawtypes") private void analyzeV5_AffectedVariablesInTransformation(List<CtVariableAccess> varsAffected, CtElement element, Cntx<Object> context) { try { CtMethod methodParent = element.getParent(CtMethod.class); List<CtExpression> assignments = new ArrayList<>(); CtScanner assignmentScanner = new CtScanner() { @Override public <T, A extends T> void visitCtAssignment(CtAssignment<T, A> assignement) { if (assignement.getAssignment() != null) assignments.add(assignement.getAssignment()); } @Override public <T> void visitCtLocalVariable(CtLocalVariable<T> localVariable) { if (localVariable.getAssignment() != null) assignments.add(localVariable.getAssignment()); } }; assignmentScanner.scan(methodParent); for (CtVariableAccess variableAffected : varsAffected) { boolean v5_currentVarHasvar = false; for (CtExpression assignment : assignments) { if (!isElementBeforeVariable(variableAffected, assignment)) continue; // let's collect the var access in the right part List<CtVariableAccess> varsInRightPart = VariableResolver.collectVariableRead(assignment); // VariableResolver.collectVariableAccess(assignment); // if the var access in the right is the same that the affected for (CtVariableAccess varInAssign : varsInRightPart) { if (hasSameName(variableAffected, varInAssign)) { v5_currentVarHasvar = true; break; } } } writeGroupedInfo(context, adjustIdentifyInJson(variableAffected), CodeFeatures.V5_HAS_VAR_IN_TRANSFORMATION, (v5_currentVarHasvar), "FEATURES_VARS"); } } catch (Throwable e) { e.printStackTrace(); } }
Example #28
Source File: AssertionAdder.java From spoon-examples with GNU General Public License v2.0 | 4 votes |
@SuppressWarnings("unchecked") public void addAssertion(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.addAssertion(testMethod, ctLocalVariable)); System.out.println(testMethod); }
Example #29
Source File: Collector.java From spoon-examples with GNU General Public License v2.0 | 4 votes |
@SuppressWarnings("unchecked") public void instrument(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.instrument(testMethod, ctLocalVariable)); }
Example #30
Source File: Util.java From spoon-examples with GNU General Public License v2.0 | 4 votes |
public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { final CtExecutableReference reference = method.getReference(); final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); return method.getFactory().createInvocation(variableRead, reference); }