11package org .hacksource .core ;
22
33import com .github .javaparser .Range ;
4+ import com .github .javaparser .TokenRange ;
45import com .github .javaparser .ast .CompilationUnit ;
56import com .github .javaparser .ast .Node ;
67import com .github .javaparser .ast .NodeList ;
78import com .github .javaparser .ast .stmt .*;
89
910import java .io .*;
1011import java .nio .file .Paths ;
12+ import java .util .ArrayList ;
1113import java .util .Arrays ;
1214import java .util .List ;
1315
1416
1517public class SourceFormat {
1618
17- public static String format (CompilationUnit cu ) {
19+ public static String format (CompilationUnit cu , List < SourceProblem > list ) {
1820
1921 Arrays .stream (new Class []{
2022 IfStmt .class , ForStmt .class , ForEachStmt .class , WhileStmt .class
21- }).forEach (c -> addBracket (cu , c ));
23+ }).forEach (c -> addStmtBracket (cu , c , list ));
2224
2325 return cu .toString ();
2426 }
2527
26- private static <T extends Statement > void addBracket (CompilationUnit cu , Class <T > c ) {
28+ private static <T extends Statement > void addStmtBracket (CompilationUnit cu , Class <T > c , List < SourceProblem > list ) {
2729 cu .findAll (c ).forEach (stmt -> {
2830 List <Node > children = stmt .getChildNodes ();
31+
2932 if (children .size () != 0 ) {
3033 Statement block = (Statement )children .get (children .size () - 1 );
34+
3135 if (!block .isBlockStmt ()) {
32- stmt .replace (block , new BlockStmt (new NodeList <Statement >(block )));
33- Range range = stmt .getRange ().orElseThrow (() -> new RuntimeException ("cannot get range" ));
34- System .out .println (range .toString ());
36+ stmt .replace (block , new BlockStmt (new NodeList <>(block )));
37+
38+ TokenRange tokenRange = stmt .getTokenRange ().orElseThrow (() -> new RuntimeException ("cannot get range" ));
39+ list .add (new SourceProblem ("s4.1.1-braces-always-used" , tokenRange ));
3540 }
3641 }
3742 });
@@ -42,7 +47,10 @@ public static void main(String[] args) throws IOException, SourceException {
4247 String path = SourceFormat .class .getResource ("/example.java" ).getPath ();
4348 path = path .substring (1 );
4449
45- String output = format (SourceParser .parseFile (Paths .get (path )));
50+ List <SourceProblem > problems = new ArrayList <>();
51+ String output = format (SourceParser .parseFile (Paths .get (path )), problems );
52+
53+ problems .forEach (p -> System .out .println (p ));
4654
4755 FileWriter fileWriter = new FileWriter ("generated/example.java" );
4856 fileWriter .write (output );
0 commit comments