protected Map<Statement, Double> buildCodeFragmentFor(CtType cl, Coverage coverage) {
    Factory factory = cl.getFactory();
    Map<Statement, Double> codeFragments = new LinkedHashMap<>();

    for (CtMethod<?> mth : (Set<CtMethod>) cl.getMethods()) {
      if (!mth.getModifiers().contains(ModifierKind.ABSTRACT)
          && !mth.getModifiers().contains(ModifierKind.PRIVATE)) {
        //                    && getCoverageForMethod(coverage, cl, mth) != 1.0) {

        CtExecutableReference executableRef = factory.Executable().createReference(mth);
        executableRef.setStatic(mth.getModifiers().contains(ModifierKind.STATIC));
        CtInvocation invocation =
            factory.Code().createInvocation(buildVarRef(cl.getReference(), factory), executableRef);
        invocation.setArguments(
            mth.getParameters()
                .stream()
                .map(param -> buildVarRef(param.getType(), factory))
                .collect(Collectors.toList()));
        invocation.setType(mth.getType());
        Statement stmt = new Statement(invocation);
        codeFragments.put(stmt, getCoverageForMethod(coverage, cl, mth));
      }
    }
    return codeFragments;
  }
Beispiel #2
0
  /**
   * Create the content of the condition
   *
   * @param ctInvocation
   * @return
   */
  private CtBlock<Object> createThen(CtInvocation<?> ctInvocation) {
    CtBlock<Object> thenStatement = ctInvocation.getFactory().Core().createBlock();
    thenStatement.addStatement(
        (getFactory().Code().createCodeSnippetStatement("System.out.println(\"Else...\")")));
    thenStatement.addStatement(
        (getFactory()
            .Code()
            .createCodeSnippetStatement(
                "System.out.println(" + Debug.class.getCanonicalName() + ".getSolvedPC())")));

    CtAssert<Object> ctAssert = ctInvocation.getFactory().Core().createAssert();

    CtCodeSnippetExpression<Boolean> assertExpression =
        getFactory().Core().createCodeSnippetExpression();
    assertExpression.setValue("false");

    ctAssert.setAssertExpression(assertExpression);
    ctAssert.setExpression(
        getFactory()
            .Code()
            .createCodeSnippetExpression(
                String.format("\"%s\"", ctInvocation.toString().replaceAll("\"", "'"))));

    thenStatement.addStatement(ctAssert);

    return thenStatement;
  }
 @Test
 public void printerCanPrintInvocationWithoutException() throws Exception {
   String packageName = "spoon.test.subclass.prettyprinter";
   String className = "DefaultPrettyPrinterExample";
   String qualifiedName = packageName + "." + className;
   SpoonCompiler comp = new Launcher().createCompiler();
   List<SpoonResource> fileToBeSpooned =
       SpoonResourceHelper.resources(
           "./src/test/resources/printer-test/" + qualifiedName.replace('.', '/') + ".java");
   assertEquals(1, fileToBeSpooned.size());
   comp.addInputSources(fileToBeSpooned);
   List<SpoonResource> classpath =
       SpoonResourceHelper.resources(
           "./src/test/resources/printer-test/DefaultPrettyPrinterDependency.jar");
   assertEquals(1, classpath.size());
   comp.setSourceClasspath(classpath.get(0).getPath());
   comp.build();
   Factory factory = comp.getFactory();
   CtType<?> theClass = factory.Type().get(qualifiedName);
   List<CtInvocation<?>> elements =
       Query.getElements(theClass, new TypeFilter<CtInvocation<?>>(CtInvocation.class));
   assertEquals(3, elements.size());
   CtInvocation<?> mathAbsInvocation = elements.get(1);
   assertEquals("java.lang.Math.abs(message.length())", mathAbsInvocation.toString());
 }
  private static <T> void processConstructor(CtConstructor<T> c, CtClass<T> toMerge) {
    CtStatement firstStmt = c.getBody().getStatements().get(0);
    if (firstStmt instanceof CtInvocation) {
      CtInvocation<?> superConstructorCall = (CtInvocation) firstStmt;
      if (!(superConstructorCall.getExecutable().getDeclaration() instanceof CtConstructor)) return;
      CtConstructor superConstructor =
          (CtConstructor) superConstructorCall.getExecutable().getDeclaration();
      if (superConstructor.getDeclaringType() == toMerge) {
        CtBlock superConstructorBody = c.getFactory().Core().clone(superConstructor.getBody());
        superConstructorBody.accept(
            new CtScanner() {
              @Override
              public <T> void visitCtParameterReference(CtParameterReference<T> ref) {
                int parameterOrder = superConstructor.getParameters().indexOf(ref.getDeclaration());
                ref.setDeclaringExecutable(c.getReference());
                CtExpression<?> arg = superConstructorCall.getArguments().get(parameterOrder);
                if (!(arg instanceof CtVariableAccess))
                  throw sgce("super() should be directly called in " + c);
                CtVariable param = ((CtVariableAccess) arg).getVariable().getDeclaration();
                if (!(param instanceof CtParameter))
                  throw sgce("super() should be directly called in " + c);
                ref.setSimpleName(param.getSimpleName());

                super.visitCtParameterReference(ref);
              }
            });
        c.getBody().removeStatement(firstStmt);
        List<CtStatement> superConstructorBodyStatements = superConstructorBody.getStatements();
        for (int i = superConstructorBodyStatements.size() - 1; i >= 0; i--) {
          c.getBody().insertBegin(superConstructorBodyStatements.get(i));
        }
      }
    }
  }
Beispiel #5
0
 @Override
 public boolean isToBeProcessed(CtInvocation<?> candidate) {
   if (!candidate.getExecutable().getSimpleName().contains("assert")) {
     return false;
   }
   CtExecutableReference<?> executable = candidate.getExecutable();
   CtPackageReference executablePackage = executable.getDeclaringType().getPackage();
   if (executablePackage == null || !executablePackage.getSimpleName().contains("junit")) {
     return false;
   }
   CtMethod<?> parentMethod = candidate.getParent(CtMethod.class);
   if (parentMethod == null) {
     return false;
   }
   createExecutionMethod(candidate);
   return super.isToBeProcessed(candidate);
   /*
    * boolean found = false; for (TestCase testCase : faillingTest) { if
    * (testCase.className().equals(parentClass.getQualifiedName())) { if
    * (testCase.testName().equals(parentMethod.getSimpleName())) { found =
    * true; break; } } }
    *
    * return found;
    */
 }
Beispiel #6
0
  /**
   * replace assertTrue
   *
   * @param ctInvocation
   * @return
   */
  private CtStatement replaceAssertTrueFalse(boolean type, CtInvocation<?> ctInvocation) {
    List<?> arguments = ctInvocation.getArguments();
    CtIf newIf = ctInvocation.getFactory().Core().createIf();

    Object elem1 = arguments.get(0);
    if (arguments.size() > 1) {
      elem1 = arguments.get(1);
    }
    if (!type) {
      CtExpression<Boolean> condition =
          ctInvocation.getFactory().Code().createCodeSnippetExpression("!(" + elem1 + ")");
      newIf.setCondition(condition);
    } else {
      newIf.setCondition((CtExpression<Boolean>) elem1);
    }
    // newIf.setThenStatement(getFactory().Code().createCodeSnippetStatement(
    // Debug.class.getCanonicalName() + ".printPC(\"Path Condition: \")"));
    /*
     * CtBlock<Object> thenStatement = ctInvocation.getFactory().Core()
     * .createBlock(); // thenStatement.addStatement((getFactory().Code().
     * createCodeSnippetStatement("System.out.println(\"Then...\")")));
     * thenStatement.addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(" +
     * Debug.class.getCanonicalName() + ".getSolvedPC())")));
     * newIf.setThenStatement(thenStatement);
     */
    newIf.setThenStatement(createThen(ctInvocation));
    return newIf;
  }
Beispiel #7
0
  private void createExecutionMethod(CtInvocation<?> ctInvocation) {
    CtClass<?> parent = ctInvocation.getParent(CtClass.class);
    if (!parent.isTopLevel()) {
      return;
    }
    if (parent.getModifiers().contains(ModifierKind.ABSTRACT)) {
      return;
    }
    CtTypeReference<String[]> typedReference = getFactory().Class().createReference(String[].class);
    if (parent.getMethod("runJPFTest", typedReference) != null) {
      return;
    }
    CtTypeReference<Object> returntypedReference = getFactory().Class().createReference("void");

    Set<ModifierKind> modifiers = new LinkedHashSet<ModifierKind>(2);
    modifiers.add(ModifierKind.PUBLIC);
    modifiers.add(ModifierKind.STATIC);

    String invocation = parent.getQualifiedName() + "(";
    if (parent.getConstructor() == null) {
      // CtTypeReference<?> superClass = parent.getSuperclass();
      if (parent.getConstructor(ctInvocation.getFactory().Class().STRING) != null) {
        invocation += "\"" + parent.getSimpleName() + "\"";
      } else {
        return;
      }
    }
    invocation += ")";

    CtBlock<?> body = getFactory().Core().createBlock();
    String bodyString = "for (String method : methods) {\n";
    bodyString += "\t\tSystem.out.println(method);\n\t\t";
    bodyString += parent.getQualifiedName() + " instance = new " + invocation + ";\n\t\t";
    if (parent.getMethod("setUp") != null) {
      bodyString += "instance.setUp();";
    }
    bodyString +=
        parent.getQualifiedName() + ".class.getMethod(method, null).invoke(instance);\n\t\t";
    bodyString += "}\n";
    body.addStatement(getFactory().Code().createCodeSnippetStatement(bodyString));
    HashSet<CtTypeReference<? extends Throwable>> exceptions =
        new HashSet<CtTypeReference<? extends Throwable>>();
    exceptions.add(getFactory().Class().createReference(Exception.class));
    CtMethod<?> method =
        getFactory()
            .Method()
            .create(
                parent,
                modifiers,
                returntypedReference,
                "runJPFTest",
                new ArrayList<CtParameter<?>>(),
                exceptions,
                body);
    getFactory().Method().createParameter(method, typedReference, "methods");
  }
Beispiel #8
0
  /**
   * replace assertNotNull
   *
   * @param ctInvocation
   * @return
   */
  private CtStatement replaceAssertNotNull(CtInvocation<?> ctInvocation) {
    List<?> arguments = ctInvocation.getArguments();
    CtIf newIf = ctInvocation.getFactory().Core().createIf();

    Object elem1 = arguments.get(0);
    CtExpression<Boolean> condition =
        ctInvocation.getFactory().Code().createCodeSnippetExpression("(" + elem1 + ") != null");
    newIf.setCondition(condition);
    // newIf.setThenStatement(getFactory().Code().createCodeSnippetStatement(
    // Debug.class.getCanonicalName() + ".printPC(\"Path Condition: \")"));
    /*
     * CtBlock<Object> thenStatement = ctInvocation.getFactory().Core()
     * .createBlock(); thenStatement .addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(\"Then...\")")));
     * thenStatement.addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(" +
     * Debug.class.getCanonicalName() + ".getSolvedPC())")));
     * newIf.setThenStatement(thenStatement);
     */
    newIf.setThenStatement(createThen(ctInvocation));
    return newIf;
  }
  private static <T> void processOverridden(
      CtClass<?> mergeInto, CtClass<?> toMerge, final CtMethod<T> methodToMerge) {
    List<CtInvocation<T>> superInvocations =
        mergeInto.getElements(
            new Filter<CtInvocation<T>>() {
              @Override
              public boolean matches(CtInvocation<T> invocation) {
                if (!(invocation.getTarget() instanceof CtSuperAccess)) return false;
                CtExecutable<?> m = invocation.getExecutable().getDeclaration();
                return m != null && MethodNode.overrides((CtMethod<?>) m, methodToMerge);
              }
            });

    methodToMerge.setSimpleName(classPrefixedName(toMerge, methodToMerge));
    methodToMerge.setVisibility(PRIVATE);
    removeAnnotation(methodToMerge, Override.class);

    for (CtInvocation<T> superInvocation : superInvocations) {
      superInvocation.setTarget(null);
      superInvocation.setExecutable(methodToMerge.getReference());
    }
    add(mergeInto, methodToMerge, mergeInto::addMethod);
  }
Beispiel #10
0
 /** Actually invokes from a compile-time invocation (by using runtime reflection). */
 @SuppressWarnings("unchecked")
 public static <T> T invoke(CtInvocation<T> i)
     throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
   Object target = i.getTarget() == null ? null : ((CtLiteral<?>) i.getTarget()).getValue();
   List<Object> args = new ArrayList<Object>();
   for (CtExpression<?> e : i.getArguments()) {
     args.add(((CtLiteral<?>) e).getValue());
   }
   Class<?> c = i.getExecutable().getDeclaringType().getActualClass();
   ArrayList<Class<?>> argTypes = new ArrayList<Class<?>>();
   for (CtTypeReference<?> type : i.getExecutable().getActualTypeArguments()) {
     argTypes.add(type.getActualClass());
   }
   return (T)
       c.getMethod(i.getExecutable().getSimpleName(), argTypes.toArray(new Class[argTypes.size()]))
           .invoke(target, args.toArray());
 }
  /**
   * Resolves all the variables used by the snippet. The ones which are initialized and the ones
   * which are not
   *
   * @return True if the context was extracted successfully
   */
  private boolean resolveDataContext(CtStatement statement) {

    needsInitialization = false;

    // Check some preconditions needed for the processor to run:
    // All variable access made inside the statement
    List<CtVariableAccess> access = statement.getElements(new TypeFilter<>(CtVariableAccess.class));

    if (statement.getElements(new TypeFilter<>(CtThisAccess.class)).size() > 0) {
      mustSerializeThiz =
          new Preconditions().checkTypeRef(statement.getParent(CtClass.class).getReference());
    }

    initialized = new HashSet<>();

    // Get all THIZ field access from all invocations used in the element
    HashSet<CtInvocation> visited = new HashSet<>();
    Stack<CtInvocation> invStack = new Stack<>();
    invStack.addAll(statement.getElements(new TypeFilter<>(CtInvocation.class)));
    while (!invStack.empty()) {
      CtInvocation inv = invStack.pop();
      if (!visited.contains(inv)) {
        visited.add(inv);
        CtBlock b;
        try {
          b = inv.getExecutable().getDeclaration().getBody();
        } catch (NullPointerException ex) {
          b = null;
        }
        if (visibility(inv) != PUBLIC && b != null) {
          for (CtFieldAccess ta :
              b.getElements(new TypeFilter<CtFieldAccess>(CtFieldAccess.class))) {
            if (ta.getTarget() instanceof CtThisAccess || ta.getTarget() == null) {
              access.add(ta);
              // initialized.add(ta);
            }
          }
          for (CtInvocation i : b.getElements(new TypeFilter<CtInvocation>(CtInvocation.class))) {
            if (!visited.contains(i)) invStack.push(i);
          }
        }
      }
    }

    access = cleanRepeatedAccesses(access);
    setAccesses(access);

    // Find initialized variables of allowed types
    ControlFlowBuilder v = new ControlFlowBuilder();
    CtMethod m = statement.getParent(CtMethod.class);
    if (m == null) return false;
    m.accept(v);
    ControlFlowGraph g = v.getResult();
    g.simplify();
    try {
      InitializedVariables vars = new InitializedVariables();
      vars.run(ControlFlowBuilder.firstNode(g, statement));

      for (CtVariableAccess a : access) {
        // A variable must be initialized if is local and is not a serializable field
        // Also if is not a constant. Constant get declared in the body of the microbenchmark
        if (isInitialized(a, statement, vars) && !isAConstant(a)) initialized.add(a);
      }
    } catch (NotFoundException e) {
      return false;
    } catch (StackOverflowError e) {
      System.out.print(g.toGraphVisText());
      throw e;
    }

    needsInitialization = initialized.size() > 0;
    if (access.size() <= 0) return true;

    int i = 0;
    int replaced = 0;
    do {
      if (i == 0) replaced = 0;
      CtVariableAccess a = access.get(i);
      if (canBeReplacedByTarget(a)) {
        CtVariableAccess targetOfA = null;
        CtTargetedExpression ta = (CtTargetedExpression) a;
        if (ta.getTarget() != null) {
          if (ta.getTarget() instanceof CtVariableAccess) {
            targetOfA = (CtVariableAccess) ta.getTarget();
          } else if (ta.getTarget() instanceof CtThisAccess) {
            mustSerializeThiz = true;
          }
        } else {
          mustSerializeThiz = true;
        }
        if (targetOfA != null) {
          if (!access.contains(targetOfA)) access.add(targetOfA);
          if (initialized.contains(a) && !initialized.contains(targetOfA))
            initialized.add(targetOfA);
        }
        access.remove(a);
        if (initialized.contains(a)) initialized.remove(a);
        replaced++;
      } else i++;
      if (i >= access.size()) i = 0;
    } while (replaced > 0 || i != 0);
    return true;
  }
  @Override
  public void process(CtConditional ctConditional) {
    CtStatement parent = ctConditional.getParent(CtStatement.class);
    while (!(parent.getParent() instanceof CtStatementList)) {
      parent = parent.getParent(CtStatement.class);
    }
    CtExpression condition = ctConditional.getCondition();

    CtIf anIf = getFactory().Core().createIf();
    anIf.setPosition(ctConditional.getPosition());

    if (parent instanceof CtReturn) {
      if (!((CtReturn) parent).getReturnedExpression().equals(ctConditional)) {
        return;
      }

      CtReturn returnThen = (CtReturn) parent.clone();
      CtReturn returnElse = (CtReturn) parent.clone();

      returnThen.setReturnedExpression(ctConditional.getThenExpression());
      returnElse.setReturnedExpression(ctConditional.getElseExpression());

      List<CtTypeReference> typeCasts = ctConditional.getTypeCasts();
      for (int i = 0; i < typeCasts.size(); i++) {
        CtTypeReference ctTypeReference = typeCasts.get(i);
        returnThen.getReturnedExpression().addTypeCast(ctTypeReference.clone());
        returnElse.getReturnedExpression().addTypeCast(ctTypeReference.clone());
      }

      anIf.setElseStatement(getFactory().Code().createCtBlock(returnElse));
      anIf.setThenStatement(getFactory().Code().createCtBlock(returnThen));
    } else if (parent instanceof CtAssignment) {
      CtAssignment assignment = (CtAssignment) parent;
      CtExpression ctExpression = assignment.getAssignment();
      if (!ctExpression.equals(ctConditional)) {
        if (ctExpression instanceof CtBinaryOperator) {
          CtBinaryOperator ctBinaryOperator = (CtBinaryOperator) ctExpression;

          createAssignment(ctConditional, anIf, assignment);
          CtBinaryOperator cloneThen = ctBinaryOperator.clone();
          CtBinaryOperator cloneElse = ctBinaryOperator.clone();

          if (ctBinaryOperator.getLeftHandOperand().equals(ctConditional)) {
            cloneThen.setLeftHandOperand(ctConditional.getThenExpression());
            ctConditional.getThenExpression().setParent(cloneThen);
            cloneElse.setLeftHandOperand(ctConditional.getElseExpression());
          } else if (ctBinaryOperator.getRightHandOperand().equals(ctConditional)) {
            cloneThen.setRightHandOperand(ctConditional.getThenExpression());
            cloneElse.setRightHandOperand(ctConditional.getElseExpression());
          }

          cloneThen.getLeftHandOperand().setParent(cloneThen);
          cloneElse.getLeftHandOperand().setParent(cloneElse);
          ((CtAssignment) ((CtBlock) anIf.getThenStatement()).getStatement(0))
              .setAssignment(cloneThen);
          ((CtAssignment) ((CtBlock) anIf.getElseStatement()).getStatement(0))
              .setAssignment(cloneElse);
        } else {
          return;
        }
      } else {
        createAssignment(ctConditional, anIf, assignment);
      }
    } else if (parent instanceof CtLocalVariable) {
      CtLocalVariable localVariable = (CtLocalVariable) parent;
      if (!localVariable.getDefaultExpression().equals(ctConditional)) {
        return;
      }

      CtLocalVariable clone = localVariable.clone();
      clone.setDefaultExpression(null);

      localVariable.insertBefore(clone);

      CtAssignment variableAssignment =
          getFactory()
              .Code()
              .createVariableAssignment(localVariable.getReference(), false, ctConditional);
      variableAssignment.setType(localVariable.getType().clone());
      variableAssignment.setPosition(ctConditional.getPosition());
      createAssignment(ctConditional, anIf, variableAssignment);
    } else if (parent instanceof CtInvocation) {
      CtInvocation invocation = (CtInvocation) parent;
      CtInvocation cloneThen = invocation.clone();
      CtInvocation cloneElse = invocation.clone();

      List arguments = cloneThen.getArguments();
      boolean found = false;
      for (int i = 0; i < arguments.size(); i++) {
        Object o = arguments.get(i);
        if (o.equals(ctConditional)) {
          ctConditional.getThenExpression().setParent(invocation);
          arguments.set(i, ctConditional.getThenExpression());
          ctConditional.getElseExpression().setParent(invocation);
          cloneElse.getArguments().set(i, ctConditional.getElseExpression());
          found = true;
          break;
        }
      }
      if (!found) {
        return;
      }

      cloneThen.setParent(anIf);
      cloneElse.setParent(anIf);

      anIf.setElseStatement(getFactory().Code().createCtBlock(cloneElse));
      anIf.setThenStatement(getFactory().Code().createCtBlock(cloneThen));
    } else if (parent instanceof CtConstructorCall) {
      CtConstructorCall invocation = (CtConstructorCall) parent;
      CtConstructorCall cloneThen = invocation.clone();
      CtConstructorCall cloneElse = invocation.clone();

      List arguments = cloneThen.getArguments();
      boolean found = false;
      for (int i = 0; i < arguments.size(); i++) {
        Object o = arguments.get(i);
        if (o.equals(ctConditional)) {
          arguments.set(i, ctConditional.getThenExpression());
          cloneElse.getArguments().set(i, ctConditional.getElseExpression());
          found = true;
          break;
        }
      }
      if (!found) {
        return;
      }

      cloneThen.setParent(anIf);
      cloneElse.setParent(anIf);

      anIf.setElseStatement(getFactory().Code().createCtBlock(cloneElse));
      anIf.setThenStatement(getFactory().Code().createCtBlock(cloneThen));
    } else if (parent instanceof CtIf) {
      CtIf elem = (CtIf) parent;
      if (!elem.getCondition().equals(ctConditional)) {
        return;
      }

      CtIf cloneThen = elem.clone();
      cloneThen.setParent(anIf);
      CtIf cloneElse = elem.clone();
      cloneElse.setParent(anIf);

      cloneThen.setCondition(ctConditional.getThenExpression());
      ctConditional.getThenExpression().setParent(cloneThen);

      cloneElse.setCondition(ctConditional.getElseExpression());
      ctConditional.getElseExpression().setParent(cloneElse);

      anIf.setElseStatement(getFactory().Code().createCtBlock(cloneElse));
      anIf.setThenStatement(getFactory().Code().createCtBlock(cloneThen));
    } else if (parent instanceof CtThrow) {
      return;
    } else if (parent instanceof CtLoop) {
      return;
    } else if (parent instanceof CtUnaryOperator) {
      return;
    } else {
      System.err.println(parent);
      throw new RuntimeException("Other " + parent.getClass());
    }
    /*if(ctConditional.getThenExpression().getTypeCasts() == null ||
            ctConditional.getThenExpression().getTypeCasts().isEmpty()) {
        ((CtExpression)anIf.getThenStatement()).setTypeCasts(ctConditional.getTypeCasts());
    }
    if(ctConditional.getElseExpression().getTypeCasts() == null ||
            ctConditional.getElseExpression().getTypeCasts().isEmpty()) {
        ((CtExpression) anIf.getElseStatement())
                .setTypeCasts(ctConditional.getTypeCasts());
    }*/
    anIf.setCondition(condition);
    condition.setParent(anIf);
    parent.replace(anIf);
  }
Beispiel #13
0
  /**
   * replace assert Equals
   *
   * @param ctInvocation
   * @return
   */
  private CtStatement replaceAssertEquals(CtInvocation<?> ctInvocation) {
    List<CtExpression<?>> arguments = ctInvocation.getArguments();
    CtIf newIf = ctInvocation.getFactory().Core().createIf();
    CtCodeSnippetExpression<Boolean> condition =
        ctInvocation.getFactory().Core().createCodeSnippetExpression();
    CtExpression<?> elem1 = arguments.get(0);
    CtExpression<?> elem2 = arguments.get(1);
    if (arguments.size() > 2
        && (elem1.getType().equals(ctInvocation.getFactory().Class().STRING)
            || elem1.getType().equals(getFactory().Class().nullType()))) {
      elem1 = arguments.get(1);
      elem2 = arguments.get(2);
    }

    boolean isNull = false;
    Class<?> classArg1 = null;
    if (elem1.toString().equals("null")) {
      isNull = true;
    } else {
      try {
        classArg1 = ((CtTypedElement<?>) elem1).getType().getActualClass();
      } catch (SpoonException e) {
        e.printStackTrace();
      }
    }
    if (isNull
        || (classArg1 != null
            && (classArg1.equals(int.class)
                || classArg1.equals(Integer.class)
                || classArg1.equals(boolean.class)
                || classArg1.equals(Boolean.class)
                || classArg1.equals(byte.class)
                || classArg1.equals(Byte.class)
                || classArg1.equals(long.class)
                || classArg1.equals(Long.class)
                || classArg1.equals(double.class)
                || classArg1.equals(Double.class)
                || classArg1.equals(float.class)
                || classArg1.equals(Float.class)
                || classArg1.equals(short.class)
                || classArg1.equals(Short.class)
                || classArg1.equals(char.class)
                || classArg1.equals(Character.class)))) {
      condition.setValue("" + elem1 + " == " + elem2 + "");
    } else {
      condition.setValue("(" + elem1 + ".equals(" + elem2 + "))");
    }
    newIf.setCondition(condition);
    // newIf.setThenStatement(getFactory().Code().createCodeSnippetStatement(
    // Debug.class.getCanonicalName() + ".printPC(\"Path Condition: \")"));
    // newIf.setThenStatement(getFactory().Code().createCodeSnippetStatement("System.out.println("+Debug.class.getCanonicalName()+".getSolvedPC())"));
    /*
     * CtBlock<Object> thenStatement = ctInvocation.getFactory().Core()
     * .createBlock(); thenStatement.addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(\"Then...\")")));
     * thenStatement.addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(" +
     * Debug.class.getCanonicalName() + ".getSolvedPC())")));
     * newIf.setThenStatement(thenStatement);
     */
    newIf.setThenStatement(createThen(ctInvocation));

    return newIf;
  }
Beispiel #14
0
  @Override
  public void process(CtInvocation<?> ctInvocation) {
    // ignore no assert invocation
    // CtTypeReference<?> executableType = executable.getDeclaringType();

    // List<CtExpression<?>> parameters = ctInvocation.getArguments();
    // int parametersSize = parameters.size();
    // Class<?>[] parameterTypes = new Class<?>[parametersSize];
    // for (int i = 0; i < parametersSize; i++) {
    // parameterTypes[0] = parameters.get(i).getType().getActualClass();
    // }
    // List<CtExpression<?>> arguments = ctInvocation.getArguments();
    // CtIf newIf = ctInvocation.getFactory().Core().createIf();
    // String body = Assert.class.getCanonicalName() + "."
    // + ctInvocation.getExecutable().getSimpleName() + "(";
    // for (int i = 0; i < arguments.size(); i++) {
    // CtExpression<?> ctExpression = arguments.get(i);
    // body += ctExpression;
    // if (i < arguments.size() - 1) {
    // body += ", ";
    // }
    // }
    // body += ")";
    // CtCodeSnippetExpression<Boolean> condition =
    // ctInvocation.getFactory()
    // .Code().createCodeSnippetExpression(body);
    // newIf.setCondition(condition);
    // newIf.setElseStatement(createThen(ctInvocation));
    // ctInvocation.replace(newIf);
    // createExecutionMethod(ctInvocation);
    // return;
    // CtTry ctTry = getFactory().Core().createTry();
    // CtCatch ctCatch = getFactory().Core().createCatch();
    CtCatchVariable<Exception> localVariable =
        getFactory()
            .Code()
            .createCatchVariable(
                getFactory().Class().createReference(Exception.class),
                "exception" + (++exceptionCount));
    // ctCatch.setParameter(localVariable);
    // ctCatch.setBody(createThen(ctInvocation));
    // ctTry.addCatcher(ctCatch);
    CtBlock<Object> tryBody = ctInvocation.getFactory().Core().createBlock();
    // ctTry.setBody(tryBody);
    switch (ctInvocation.getExecutable().getSimpleName()) {
      case "assertEquals":
        ctInvocation.replace(replaceAssertEquals(ctInvocation));
        break;
      case "assertFalse":
        ctInvocation.replace(replaceAssertTrueFalse(false, ctInvocation));
        break;
      case "assertTrue":
        ctInvocation.replace(replaceAssertTrueFalse(true, ctInvocation));
        break;
      case "assertNull":
        ctInvocation.replace(replaceAssertNull(ctInvocation));
        break;
      case "assertNotNull":
        ctInvocation.replace(replaceAssertNotNull(ctInvocation));
        break;
      default:
        // System.out.println("Assert transformation not found: " +
        // ctInvocation.getExecutable().getSimpleName());
        return;
    }
    // insertAfterUnderSameParent(((getFactory().Code().createCodeSnippetStatement("System.out.println(\"Fianlly: \" + "+Debug.class.getCanonicalName()+".getSolvedPC())"))),
    // ctInvocation);
    /*if(ctInvocation.getParent(CtTry.class) == null) {
    	ctInvocation.replace(ctTry);
    } else {
    	ctInvocation.replace(tryBody);
    }*/
    /*
     * System.out.println("REPLACE: "); System.out.println(ctInvocation);
     * System.out.println("BY: "); System.out.println(ctTry);
     */
    // createExecutionMethod(ctInvocation);
  }