1 module RuleWriter;
2 
3 import std.array;
4 import std.stdio;
5 
6 class RuleWriter{
7 
8     private string pathName;
9     private string fileName;
10 
11     public ushort indentLevel;
12 
13     struct Result { ushort indent; string text;}
14 
15     private Result[] results;
16 
17     this() {
18     }
19 
20     this(string pathName) {
21         this.pathName = pathName;
22     }
23 
24     public void setOutputFilename(string fileName)
25     {
26         this.fileName = fileName;
27     }
28 
29     public void setOutputPath(string pathName)
30     {
31         this.pathName = pathName;
32     }
33 
34     public void clear() {
35         results.length = 0;
36     }
37 
38     public void put(string s) {
39         results ~= set(s);
40     }
41 
42     public void put(string[] s) {
43         foreach (el; s) {
44             results ~= set(el);
45         }
46     }
47 
48     public void putnl(string s) {
49         s ~= "\n";
50         Result r =  set(s);
51         results ~= r;
52     }
53 
54     public void put(Result r) {
55         results ~= set(r.text, r.indent);
56     }
57 
58     public void put(Result[] r) {
59         foreach (el; r) {
60             results ~= set(el.text, el.indent);
61         }
62     }
63 
64     public void putnl(Result r) {
65         Result res =  set(r.text ~ "\n", r.indent);
66         results ~= res;
67     }
68 
69     public Result set(string s) {
70         Result r;
71         r.indent = this.indentLevel;
72         r.text = s;
73         return r;
74     }
75 
76     public Result set(string s, short indent) {
77         Result r;
78         r.indent = indent;
79         r.text = s;
80         return r;
81     }
82 
83     public void print() {
84         auto r =  appender!string;
85         bool lastEndWithNL = true;
86         foreach (e; results) {
87             if (lastEndWithNL)
88                 while (e.indent-- > 0) {
89                     r.put("    "); //indent 4 spaces per level
90                 }
91             r.put(e.text);
92         if (e.text.length != 0 && e.text[$-1] == '\n')
93             lastEndWithNL = true;
94         else
95             lastEndWithNL = false;
96         }
97         if (pathName) {
98             auto f = File(pathName ~ "/" ~ fileName, "w");
99             f.write(r.data);
100             f.close;
101         }
102         else {
103             write(r.data);
104         }
105     }
106 }