com.github.javaparser.ast.stmt.IfStmt Java Examples

The following examples show how to use com.github.javaparser.ast.stmt.IfStmt. 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: DecisionContainerGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public List<Statement> setupStatements() {
    return Collections.singletonList(
            new IfStmt(
                    new BinaryExpr(
                            new MethodCallExpr(new MethodCallExpr(null, "config"), "decision"),
                            new NullLiteralExpr(),
                            BinaryExpr.Operator.NOT_EQUALS
                    ),
                    new BlockStmt().addStatement(new ExpressionStmt(new MethodCallExpr(
                            new NameExpr("decisionModels"), "init", NodeList.nodeList(new ThisExpr())
                    ))),
                    null
            )
    );
}
 
Example #2
Source File: ClassCodeAnalyser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void extractResultsFromIfStmt(IfStmt ifStmt, CodeAnalysisResult result) {
    Statement then = ifStmt.getThenStmt();
    Statement otherwise = ifStmt.getElseStmt().orElse(null);
    if (then instanceof BlockStmt) {

        List<Statement> thenBlockStmts = ((BlockStmt) then).getStatements();
        if (otherwise == null) {
            /*
             * This takes only the non-coverable one, meaning
             * that if } is on the same line of the last stmt it
             * is not considered here because it is should be already
             * considered
             */
            if (!thenBlockStmts.isEmpty()) {
                Statement lastInnerStatement = thenBlockStmts.get(thenBlockStmts.size() - 1);
                if (lastInnerStatement.getEnd().get().line < ifStmt.getEnd().get().line) {
                    result.closingBracket(Range.between(then.getBegin().get().line, ifStmt.getEnd().get().line));
                    result.nonCoverableCode(ifStmt.getEnd().get().line);
                }
            }
        } else {
            result.closingBracket(Range.between(then.getBegin().get().line, then.getEnd().get().line));
            result.nonCoverableCode(otherwise.getBegin().get().line);
        }
    }
}
 
Example #3
Source File: CodegenUtils.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static MethodDeclaration extractOptionalInjection(String type, String fieldName, String defaultMethod, DependencyInjectionAnnotator annotator) {
    BlockStmt body = new BlockStmt();
    MethodDeclaration extractMethod = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PROTECTED)
            .setName("extract_" + fieldName)
            .setType(type)
            .setBody(body);
    Expression condition = annotator.optionalInstanceExists(fieldName);
    IfStmt valueExists = new IfStmt(condition, new ReturnStmt(annotator.getOptionalInstance(fieldName)), new ReturnStmt(new NameExpr(defaultMethod)));
    body.addStatement(valueExists);
    return extractMethod;
}
 
Example #4
Source File: ProcessesContainerGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void addProcessToApplication(ProcessGenerator r) {
    ObjectCreationExpr newProcess = new ObjectCreationExpr()
            .setType(r.targetCanonicalName())
            .addArgument("application");
    IfStmt byProcessId = new IfStmt(new MethodCallExpr(new StringLiteralExpr(r.processId()), "equals", NodeList.nodeList(new NameExpr("processId"))),
                                    new ReturnStmt(new MethodCallExpr(
                                            newProcess,
                                            "configure")),
                                    null);

    byProcessIdMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(byProcessId);
}
 
Example #5
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void visit(final IfStmt n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printer.print("if (");
    n.getCondition().accept(this, arg);
    final boolean thenBlock = n.getThenStmt() instanceof BlockStmt;
    if (thenBlock) // block statement should start on the same line
        printer.print(") ");
    else {
        printer.println(")");
        printer.indent();
    }
    n.getThenStmt().accept(this, arg);
    if (!thenBlock)
        printer.unindent();
    if (n.getElseStmt().isPresent()) {
        if (thenBlock)
            printer.print(" ");
        else
            printer.println();
        final boolean elseIf = n.getElseStmt().orElse(null) instanceof IfStmt;
        final boolean elseBlock = n.getElseStmt().orElse(null) instanceof BlockStmt;
        if (elseIf || elseBlock) // put chained if and start of block statement on a same level
            printer.print("else ");
        else {
            printer.println("else");
            printer.indent();
        }
        if (n.getElseStmt().isPresent())
            n.getElseStmt().get().accept(this, arg);
        if (!(elseIf || elseBlock))
            printer.unindent();
    }
}
 
Example #6
Source File: IfStmtMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override public IfStmt doMerge(IfStmt first, IfStmt second) {
  IfStmt is = new IfStmt();

  is.setCondition(mergeSingle(first.getCondition(),second.getCondition()));
  is.setElseStmt(mergeSingle(first.getElseStmt(),second.getElseStmt()));
  is.setThenStmt(mergeSingle(first.getThenStmt(),second.getThenStmt()));

  return is;
}
 
Example #7
Source File: IfStmtMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override public boolean doIsEquals(IfStmt first, IfStmt second) {

    if(!isEqualsUseMerger(first.getCondition(),second.getCondition())) return false;
    if(!isEqualsUseMerger(first.getElseStmt(),second.getElseStmt())) return false;
    if(!isEqualsUseMerger(first.getThenStmt(),second.getThenStmt())) return false;

    return true;
  }
 
Example #8
Source File: CodeValidator.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Check if the mutation introduce a change to an instanceof condition
 *
 * @param word_changes
 * @return
 */
private static boolean containsInstanceOfChanges(CompilationUnit originalCU, CompilationUnit mutatedCU) {
    final List<ReferenceType> instanceOfInsideOriginal = new ArrayList<>();
    final List<ReferenceType> instanceOfInsideMutated = new ArrayList<>();
    final AtomicBoolean analyzingMutant = new AtomicBoolean(false);


    ModifierVisitor<Void> visitor = new ModifierVisitor<Void>() {

        @Override
        public Visitable visit(IfStmt n, Void arg) {
            // Extract elements from the condition
            if (n.getCondition() instanceof InstanceOfExpr) {
                InstanceOfExpr expr = (InstanceOfExpr) n.getCondition();
                ReferenceType type = expr.getType();

                // Accumulate instanceOF
                if (analyzingMutant.get()) {
                    instanceOfInsideMutated.add(type);
                } else {
                    instanceOfInsideOriginal.add(type);
                }

            }
            return super.visit(n, arg);
        }
    };

    visitor.visit(originalCU,null);

    if( ! instanceOfInsideOriginal.isEmpty() ){
        analyzingMutant.set( true );
        visitor.visit(mutatedCU, null);
    }

    return ! instanceOfInsideMutated.equals( instanceOfInsideOriginal );
}
 
Example #9
Source File: MutationVisitor.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Node visit(IfStmt stmt, Void args) {
    if (!isValid) {
        return stmt;
    }
    super.visit(stmt, args);
    if (level.equals(CodeValidatorLevel.RELAXED)) {
        return stmt;
    }
    this.message = ValidationMessage.MUTATION_IF_STATEMENT;
    isValid = false;
    return stmt;
}
 
Example #10
Source File: TestCodeVisitor.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void visit(IfStmt stmt, Void args) {
    if (!isValid) {
        return;
    }
    messages.add("Test contains an invalid statement: " + stmt.toString());
    isValid = false;
}
 
Example #11
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
   * Visitor for if stmts
   *   - removes feature missing test
   */
  @Override
  public void visit(IfStmt n, Object ignore) {
    do {
      // if (get_set_method == null) break;  // sometimes, these occur outside of recogn. getters/setters
      
      Expression c = n.getCondition(), e;
      BinaryExpr be, be2; 
      List<Statement> stmts;
      if ((c instanceof BinaryExpr) &&
          ((be = (BinaryExpr)c).getLeft() instanceof FieldAccessExpr) &&
          ((FieldAccessExpr)be.getLeft()).getNameAsString().equals("featOkTst")) {
        // remove the feature missing if statement
        
        // verify the remaining form 
        if (! (be.getRight() instanceof BinaryExpr) 
         || ! ((be2 = (BinaryExpr)be.getRight()).getRight() instanceof NullLiteralExpr) 
         || ! (be2.getLeft() instanceof FieldAccessExpr)

         || ! ((e = getExpressionFromStmt(n.getThenStmt())) instanceof MethodCallExpr)
         || ! (((MethodCallExpr)e).getNameAsString()).equals("throwFeatMissing")) {
          reportDeletedCheckModified("The featOkTst was modified:\n" + n.toString() + '\n');
        }
              
        BlockStmt parent = (BlockStmt) n.getParentNode().get();
        stmts = parent.getStatements();
        stmts.set(stmts.indexOf(n), new EmptyStmt()); //dont remove
                                            // otherwise iterators fail
//        parent.getStmts().remove(n);
        return;
      }
    } while (false);
    
    super.visit(n,  ignore);
  }
 
Example #12
Source File: RuleUnitInstanceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private MethodDeclaration bindMethod() {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    BlockStmt methodBlock = new BlockStmt();
    methodDeclaration.setName("bind")
            .addAnnotation( "Override" )
            .addModifier(Modifier.Keyword.PROTECTED)
            .addParameter(KieSession.class.getCanonicalName(), "runtime")
            .addParameter(ruleUnitDescription.getRuleUnitName(), "value")
            .setType(void.class)
            .setBody(methodBlock);

    try {


        for (RuleUnitVariable m : ruleUnitDescription.getUnitVarDeclarations()) {
            String methodName = m.getter();
            String propertyName = m.getName();

            if ( m.isDataSource() ) {

                if (m.setter() != null) { // if writable and DataSource is null create and set a new one
                    Expression nullCheck = new BinaryExpr(new MethodCallExpr(new NameExpr("value"), methodName), new NullLiteralExpr(), BinaryExpr.Operator.EQUALS);
                    Expression createDataSourceExpr = new MethodCallExpr(new NameExpr(DataSource.class.getCanonicalName()), ruleUnitHelper.createDataSourceMethodName(m.getBoxedVarType()));
                    Expression dataSourceSetter = new MethodCallExpr(new NameExpr("value"), m.setter(), new NodeList<>(createDataSourceExpr));
                    methodBlock.addStatement( new IfStmt( nullCheck, new BlockStmt().addStatement( dataSourceSetter ), null ) );
                }

                //  value.$method())
                Expression fieldAccessor =
                        new MethodCallExpr(new NameExpr("value"), methodName);

                // .subscribe( new EntryPointDataProcessor(runtime.getEntryPoint()) )

                String entryPointName = getEntryPointName(ruleUnitDescription, propertyName);
                MethodCallExpr drainInto = new MethodCallExpr(fieldAccessor, "subscribe")
                        .addArgument(new ObjectCreationExpr(null, StaticJavaParser.parseClassOrInterfaceType( EntryPointDataProcessor.class.getName() ), NodeList.nodeList(
                                new MethodCallExpr(
                                        new NameExpr("runtime"), "getEntryPoint",
                                        NodeList.nodeList(new StringLiteralExpr( entryPointName ))))));

                methodBlock.addStatement(drainInto);
            }

            MethodCallExpr setGlobalCall = new MethodCallExpr( new NameExpr("runtime"), "setGlobal" );
            setGlobalCall.addArgument( new StringLiteralExpr( propertyName ) );
            setGlobalCall.addArgument( new MethodCallExpr(new NameExpr("value"), methodName) );
            methodBlock.addStatement(setGlobalCall);
        }

    } catch (Exception e) {
        throw new Error(e);
    }

    return methodDeclaration;
}
 
Example #13
Source File: ClassCodeAnalyser.java    From CodeDefenders with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void visit(IfStmt ifStmt, CodeAnalysisResult result) {
    super.visit(ifStmt, result);
    extractResultsFromIfStmt(ifStmt, result);
}
 
Example #14
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(IfStmt n, Void arg) {
    out.println("IfStmt: " + (extended ? n : n.getCondition()));
    super.visit(n, arg);
}