11package org .hacksource .core ;
22
3- import com .github .javaparser .JavaParser ;
4- import com .github .javaparser .ParseResult ;
5-
3+ import com .github .javaparser .Range ;
64import com .github .javaparser .ast .CompilationUnit ;
75import com .github .javaparser .ast .Node ;
86import com .github .javaparser .ast .NodeList ;
97import com .github .javaparser .ast .stmt .*;
108
11-
129import java .io .*;
13- import java .nio .charset .StandardCharsets ;
14- import java .nio .file .Files ;
1510import java .nio .file .Paths ;
1611import java .util .Arrays ;
1712import java .util .List ;
18- import java .util .stream .Stream ;
1913
20- import static com .github .javaparser .ParseStart .*;
21- import static com .github .javaparser .Providers .provider ;
2214
2315public class SourceFormat {
2416
25- public static String format (String source ) throws SourceException {
26- JavaParser javaParser = new JavaParser ();
27- ParseResult <CompilationUnit > result = javaParser .parse (COMPILATION_UNIT , provider (source ));
28-
29- CompilationUnit cu = result .getResult ().orElseThrow (() -> new SourceException (result .getProblems ()));
17+ public static String format (CompilationUnit cu ) {
3018
3119 Arrays .stream (new Class []{
3220 IfStmt .class , ForStmt .class , ForEachStmt .class , WhileStmt .class
@@ -42,31 +30,19 @@ private static <T extends Statement> void addBracket(CompilationUnit cu, Class<T
4230 Statement block = (Statement )children .get (children .size () - 1 );
4331 if (!block .isBlockStmt ()) {
4432 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 ());
4535 }
4636 }
4737 });
4838 }
4939
50- public static void main (String [] args ) throws IOException {
40+ public static void main (String [] args ) throws IOException , SourceException {
5141
5242 String path = SourceFormat .class .getResource ("/example.java" ).getPath ();
5343 path = path .substring (1 );
5444
55- StringBuilder contentBuilder = new StringBuilder ();
56-
57- try (Stream <String > stream = Files .lines (Paths .get (path ), StandardCharsets .UTF_8 )) {
58- stream .forEach (s -> contentBuilder .append (s ).append ("\n " ));
59- }
60- catch (IOException e ) {
61- e .printStackTrace ();
62- }
63-
64- String output = "" ;
65- try {
66- output = format (contentBuilder .toString ());
67- } catch (SourceException e ) {
68- e .printStackTrace ();
69- }
45+ String output = format (SourceParser .parseFile (Paths .get (path )));
7046
7147 FileWriter fileWriter = new FileWriter ("generated/example.java" );
7248 fileWriter .write (output );
0 commit comments