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

The following examples show how to use com.github.javaparser.ast.stmt.ExpressionStmt. 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: TestCodeVisitor.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void visit(ExpressionStmt stmt, Void args) {
    if (!isValid) {
        return;
    }
    String stringStmt = stmt.toString( new PrettyPrinterConfiguration().setPrintComments(false));
    for (String prohibited : CodeValidator.PROHIBITED_CALLS) {
        // This might be a bit too strict... We shall use typeSolver otherwise.
        if (stringStmt.contains(prohibited)) {
            messages.add("Test contains a prohibited call to " + prohibited);
            isValid = false;
            return;
        }
    }
    stmtCount++;
    super.visit(stmt, args);
}
 
Example #2
Source File: FormTask.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
private MethodDeclaration setterDeclaration(EntityField field) {
    MethodDeclaration decl = new MethodDeclaration(ModifierSet.PUBLIC,
            new VoidType(),
            "set" + CaseConverter.pascalCase(field.getName()),
            Collections.singletonList(new Parameter(
                    ASTHelper.createReferenceType(field.getType().getSimpleName(), 0),
                    new VariableDeclaratorId(field.getName()))));

    BlockStmt body = new BlockStmt();
    body.setStmts(
            Collections.singletonList(
                    new ExpressionStmt(
                            new AssignExpr(
                                    new FieldAccessExpr(new ThisExpr(), field.getName()),
                                    ASTHelper.createNameExpr(field.getName()),
                                    AssignExpr.Operator.assign
                            ))));
    decl.setBody(body);
    return decl;
}
 
Example #3
Source File: RuleUnitMetaModel.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public Statement injectCollection(
        String targetUnitVar, String sourceProcVar) {
    BlockStmt blockStmt = new BlockStmt();
    RuleUnitVariable v = ruleUnitDescription.getVar(targetUnitVar);
    String appendMethod = appendMethodOf(v.getType());
    blockStmt.addStatement(assignVar(v));
    blockStmt.addStatement(
            iterate(new VariableDeclarator()
                            .setType("Object").setName("it"),
                    new NameExpr(sourceProcVar))
                    .setBody(new ExpressionStmt(
                            new MethodCallExpr()
                                    .setScope(new NameExpr(localVarName(v)))
                                    .setName(appendMethod)
                                    .addArgument(new NameExpr("it")))));
    return blockStmt;
}
 
Example #4
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 #5
Source File: GeneralFixture.java    From TestSmellDetector with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void runAnalysis(CompilationUnit testFileCompilationUnit, CompilationUnit productionFileCompilationUnit, String testFileName, String productionFileName) throws FileNotFoundException {
    GeneralFixture.ClassVisitor classVisitor;
    classVisitor = new GeneralFixture.ClassVisitor();
    classVisitor.visit(testFileCompilationUnit, null); //This call will populate the list of test methods and identify the setup method [visit(ClassOrInterfaceDeclaration n)]

    //Proceed with general fixture analysis if setup method exists
    if (setupMethod != null) {
        //Get all fields that are initialized in the setup method
        //The following code block will identify the class level variables (i.e. fields) that are initialized in the setup method
        // TODO: There has to be a better way to do this identification/check!
        Optional<BlockStmt> blockStmt = setupMethod.getBody();
        NodeList nodeList = blockStmt.get().getStatements();
        for (int i = 0; i < nodeList.size(); i++) {
            for (int j = 0; j < fieldList.size(); j++) {
                for (int k = 0; k < fieldList.get(j).getVariables().size(); k++) {
                    if (nodeList.get(i) instanceof ExpressionStmt) {
                        ExpressionStmt expressionStmt = (ExpressionStmt) nodeList.get(i);
                        if (expressionStmt.getExpression() instanceof AssignExpr) {
                            AssignExpr assignExpr = (AssignExpr) expressionStmt.getExpression();
                            if (fieldList.get(j).getVariable(k).getNameAsString().equals(assignExpr.getTarget().toString())) {
                                setupFields.add(assignExpr.getTarget().toString());
                            }
                        }
                    }
                }
            }
        }
    }

    for (MethodDeclaration method : methodList) {
        //This call will visit each test method to identify the list of variables the method contains [visit(MethodDeclaration n)]
        classVisitor.visit(method, null);
    }
}
 
Example #6
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private Expression getExpressionFromStmt(Statement stmt) {
  stmt = getStmtFromStmt(stmt);
  if (stmt instanceof ExpressionStmt) {
    return getUnenclosedExpr(((ExpressionStmt)stmt).getExpression());
  }
  return null;
}
 
Example #7
Source File: JFinalRoutesParser.java    From JApiDocs with Apache License 2.0 5 votes vote down vote up
private void parse(MethodDeclaration mdConfigRoute, File inJavaFile){
    mdConfigRoute.getBody()
            .ifPresent(blockStmt -> blockStmt.getStatements()
                    .stream()
                    .filter(statement -> statement instanceof ExpressionStmt)
                    .forEach(statement -> {
                       Expression expression = ((ExpressionStmt)statement).getExpression();
                       if(expression instanceof MethodCallExpr && ((MethodCallExpr)expression).getNameAsString().equals("add")){
                           NodeList<Expression> arguments = ((MethodCallExpr)expression).getArguments();
                           if(arguments.size() == 1 && arguments.get(0) instanceof ObjectCreationExpr){
                               String routeClassName = ((ObjectCreationExpr)((MethodCallExpr) expression).getArguments().get(0)).getType().getNameAsString();
                               File childRouteFile = ParseUtils.searchJavaFile(inJavaFile, routeClassName);
                               LogUtils.info("found child routes in file : %s" , childRouteFile.getName());
                               ParseUtils.compilationUnit(childRouteFile)
                                       .getChildNodesByType(ClassOrInterfaceDeclaration.class)
                                       .stream()
                                       .filter(cd -> routeClassName.endsWith(cd.getNameAsString()))
                                       .findFirst()
                                       .ifPresent(cd ->{
                                           LogUtils.info("found config() method, start to parse child routes in file : %s" , childRouteFile.getName());
                                           cd.getMethodsByName("config").stream().findFirst().ifPresent(m ->{
                                               parse(m, childRouteFile);
                                           });
                                       });
                           }else{
                               String basicUrl = Utils.removeQuotations(arguments.get(0).toString());
                               String controllerClass = arguments.get(1).toString();
                               String controllerFilePath = getControllerFilePath(inJavaFile, controllerClass);
                               routeNodeList.add(new RouteNode(basicUrl, controllerFilePath));
                           }
                       }
    }));
}
 
Example #8
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void visit(LambdaExpr n, Void arg) {
    printJavaComment(n.getComment(), arg);

    final NodeList<Parameter> parameters = n.getParameters();
    final boolean printPar = n.isEnclosingParameters();

    if (printPar) {
        printer.print("(");
    }
    for (Iterator<Parameter> i = parameters.iterator(); i.hasNext(); ) {
        Parameter p = i.next();
        p.accept(this, arg);
        if (i.hasNext()) {
            printer.print(", ");
        }
    }
    if (printPar) {
        printer.print(")");
    }

    printer.print(" -> ");
    final Statement body = n.getBody();
    if (body instanceof ExpressionStmt) {
        // Print the expression directly
        ((ExpressionStmt) body).getExpression().accept(this, arg);
    } else {
        body.accept(this, arg);
    }
}
 
Example #9
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 ExpressionStmt n, final Void arg) {
    printOrphanCommentsBeforeThisChildNode(n);
    printJavaComment(n.getComment(), arg);
    n.getExpression().accept(this, arg);
    printer.print(";");
}
 
Example #10
Source File: RuleUnitMetaModel.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Statement extractIntoScalar(String sourceUnitVar, String targetProcessVar) {
    BlockStmt blockStmt = new BlockStmt();
    RuleUnitVariable v = ruleUnitDescription.getVar(sourceUnitVar);
    String localVarName = localVarName(v);
    blockStmt.addStatement(assignVar(v))
            .addStatement(new ExpressionStmt(
                    new MethodCallExpr(new NameExpr(localVarName), "subscribe")
                            .addArgument(new MethodCallExpr(
                                    new NameExpr(DataObserver.class.getCanonicalName()), "ofUpdatable")
                                                 .addArgument(parseExpression("o -> kcontext.setVariable(\"" + targetProcessVar + "\", o)")))));

    return blockStmt;
}
 
Example #11
Source File: RuleUnitMetaModel.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Statement extractIntoCollection(String sourceUnitVar, String targetProcessVar) {
    BlockStmt blockStmt = new BlockStmt();
    RuleUnitVariable v = ruleUnitDescription.getVar(sourceUnitVar);
    String localVarName = localVarName(v);
    blockStmt.addStatement(assignVar(v))
            .addStatement(new ExpressionStmt(
                    new MethodCallExpr(new NameExpr(localVarName), "subscribe")
                            .addArgument(new MethodCallExpr(
                                    new NameExpr(DataObserver.class.getCanonicalName()), "of")
                                                 .addArgument(parseExpression(targetProcessVar + "::add")))));
    return blockStmt;
}
 
Example #12
Source File: RuleUnitMetaModel.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public NodeList<Statement> hoistVars() {
    NodeList<Statement> statements = new NodeList<>();
    for (RuleUnitVariable v : ruleUnitDescription.getUnitVarDeclarations()) {
        statements.add(new ExpressionStmt(assignVar(v)));
    }
    return statements;
}
 
Example #13
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected Statement makeAssignmentFromModel(Variable v, String name) {
    ClassOrInterfaceType type = parseClassOrInterfaceType(v.getType().getStringType());
    // `type` `name` = (`type`) `model.get<Name>
    AssignExpr assignExpr = new AssignExpr(
            new VariableDeclarationExpr(type, name),
            new CastExpr(
                    type,
                    new MethodCallExpr(
                            new NameExpr("model"),
                            "get" + StringUtils.capitalize(name))),
            AssignExpr.Operator.ASSIGN);

    return new ExpressionStmt(assignExpr);
}
 
Example #14
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static Statement makeAssignment(String targetLocalVariable, Variable processVariable) {
    ClassOrInterfaceType type = parseClassOrInterfaceType(processVariable.getType().getStringType());
    // `type` `name` = (`type`) `kcontext.getVariable
    AssignExpr assignExpr = new AssignExpr(
            new VariableDeclarationExpr(type, targetLocalVariable),
            new CastExpr(
                    type,
                    new MethodCallExpr(
                            new NameExpr(KCONTEXT_VAR),
                            "getVariable")
                            .addArgument(new StringLiteralExpr(targetLocalVariable))),
            AssignExpr.Operator.ASSIGN);
    return new ExpressionStmt(assignExpr);
}
 
Example #15
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(ExpressionStmt n, Void arg) {
    out.println("ExpressionStmt: " + (extended ? n : n.getExpression()));
    super.visit(n, arg);
}
 
Example #16
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/** 
 * visitor for method calls
 */
@Override
public void visit(MethodCallExpr n, Object ignore) {
  Optional<Node> p1, p2, p3 = null; 
  Node updatedNode = null;
  NodeList<Expression> args;
  
  do {
    if (get_set_method == null) break;
   
    /** remove checkArraybounds statement **/
    if (n.getNameAsString().equals("checkArrayBounds") &&
        ((p1 = n.getParentNode()).isPresent() && p1.get() instanceof ExpressionStmt) &&
        ((p2 = p1.get().getParentNode()).isPresent() && p2.get() instanceof BlockStmt) &&
        ((p3 = p2.get().getParentNode()).isPresent() && p3.get() == get_set_method)) {
      NodeList<Statement> stmts = ((BlockStmt)p2.get()).getStatements();
      stmts.set(stmts.indexOf(p1.get()), new EmptyStmt());
      return;
    }
         
    // convert simpleCore expression ll_get/setRangeValue
    boolean useGetter = isGetter || isArraySetter;
    if (n.getNameAsString().startsWith("ll_" + (useGetter ? "get" : "set") + rangeNameV2Part + "Value")) {
      args = n.getArguments();
      if (args.size() != (useGetter ? 2 : 3)) break;
      String suffix = useGetter ? "Nc" : rangeNamePart.equals("Feature") ? "NcWj" : "Nfc";
      String methodName = "_" + (useGetter ? "get" : "set") + rangeNamePart + "Value" + suffix; 
      args.remove(0);    // remove the old addr arg
      // arg 0 converted when visiting args FieldAccessExpr 
      n.setScope(null);
      n.setName(methodName);
    }
    
    // convert array sets/gets
    String z = "ll_" + (isGetter ? "get" : "set");
    String nname = n.getNameAsString();
    if (nname.startsWith(z) &&
        nname.endsWith("ArrayValue")) {
      
      String s = nname.substring(z.length());
      s = s.substring(0,  s.length() - "Value".length()); // s = "ShortArray",  etc.
      if (s.equals("RefArray")) s = "FSArray";
      if (s.equals("IntArray")) s = "IntegerArray";
      EnclosedExpr ee = new EnclosedExpr(
          new CastExpr(new ClassOrInterfaceType(s), n.getArguments().get(0)));
      
      n.setScope(ee);    // the getter for the array fs
      n.setName(isGetter ? "get" : "set");
      n.getArguments().remove(0);
    }
    
    /** remove ll_getFSForRef **/
    /** remove ll_getFSRef **/
    if (n.getNameAsString().equals("ll_getFSForRef") ||
        n.getNameAsString().equals("ll_getFSRef")) {
      updatedNode = replaceInParent(n, n.getArguments().get(0));        
    }
    
    
    
  } while (false);
      
  if (updatedNode != null) {
    updatedNode.accept(this,  null);
  } else {
    super.visit(n, null);
  }
}
 
Example #17
Source File: ExpressionStmtMerger.java    From dolphin with Apache License 2.0 3 votes vote down vote up
@Override public ExpressionStmt doMerge(ExpressionStmt first, ExpressionStmt second) {
  ExpressionStmt es = new ExpressionStmt();

  es.setExpression(mergeSingle(first.getExpression(),second.getExpression()));

  return es;
}
 
Example #18
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 3 votes vote down vote up
/**
 * Generates something like
 * <code>P_INDEX_UPDATER.lazySet(this, newValue)</code>
 *
 * @param fieldUpdaterFieldName
 * @param newValueName
 * @return
 */
protected BlockStmt fieldUpdaterLazySet(String fieldUpdaterFieldName, String newValueName) {
    BlockStmt body = new BlockStmt();
    body.addStatement(new ExpressionStmt(
            methodCallExpr(fieldUpdaterFieldName, "lazySet", new ThisExpr(), new NameExpr(newValueName))));
    return body;
}
 
Example #19
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 3 votes vote down vote up
/**
 * Generates something like <code>field = newValue</code>
 *
 * @param fieldName
 * @param valueName
 * @return
 */
protected BlockStmt fieldAssignment(String fieldName, String valueName) {
    BlockStmt body = new BlockStmt();
    body.addStatement(
            new ExpressionStmt(new AssignExpr(new NameExpr(fieldName), new NameExpr(valueName), Operator.ASSIGN)));
    return body;
}
 
Example #20
Source File: ExpressionStmtMerger.java    From dolphin with Apache License 2.0 2 votes vote down vote up
@Override public boolean doIsEquals(ExpressionStmt first, ExpressionStmt second) {

    if(!isEqualsUseMerger(first.getExpression(),second.getExpression())) return false;

    return true;
  }