raz / commit c256837c

commit
c256837c2ee4fd5ab3d46d4ab0c7b790b8edb7f1
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
39edff85
Step 18: tools/Pretty.jed, the formatter, over tools/Scan.jed, shared with Doc

patch · log

11 files changed, +767 -170

CLAUDE.md modified +7 -5

@@ -14,8 +14,9 @@
1414 make tests # the small Pascal tests of scan, x64, link and elf
1515 make gdb # gdb stops at a line of a test and names it
1616 make stress # 40,000 native threads; make check runs a small version
17+ make fmt # lib/, examples/ and tools/ are formatted
1718
18-`make check` also runs `tools/Doc.jed`, the report's whole examples,
19+`make check` also runs `tools/Doc.jed` and `tools/Pretty.jed`, the report's whole examples,
1920 each library module's own `main` (its test), and the vim and emacs
2021 support headless where they are installed (`apt-get install -y vim
2122 emacs-nox`): each example must indent back exactly as written.
@@ -23,7 +24,7 @@
2324 `make check` must pass before every commit. Tests: `test/run/X.jed`
2425 with `X.expect` (stdout), optional `X.status` and `X.args`; modules they
2526 import in `test/run/mods`. `test/err/X.jed` must fail to compile with
26-the text in `X.err`. Examples in `examples/` work the same way.
27+the text in `X.err`. `test/pretty/X.jed` must format to `X.expect`. Examples in `examples/` work the same way.
2728
2829 ## How we work
2930
@@ -44,9 +45,10 @@
4445
4546 ## Where things stand
4647
47-Steps 1-17 are done: the language, the tools, `README.md` and the
48-guide to the compiler, `doc/compiler.md`. Next, only on the owner's
49-word, is step 18, the formatter. Keep `doc/compiler.md`'s table of
48+Steps 1-18 are done: the language, the tools (`tools/Doc.jed`, and
49+the formatter, `tools/Pretty.jed`, over the shared `tools/Scan.jed`),
50+`README.md` and the guide to the compiler, `doc/compiler.md`. Nothing
51+further is planned; new work starts only on the owner's word. Keep `doc/compiler.md`'s table of
5052 lines and its routine names true when the compiler changes. Left
5153 for later at the owner's word: tagging versions, and a rewrite of var
5254 parameters.

Makefile (history) modified +9 -1

@@ -52,8 +52,16 @@
5252 build/Stress 40000 200
5353 (ulimit -v 60000; build/Stress fail)
5454
55+# the formatter, tools/Pretty.jed: the library, examples and tools are
56+# formatted already
57+fmt: jed | build
58+ ./jed -o build/Pretty tools/Pretty.jed
59+ @fail=0; for f in lib/*.jed examples/*.jed tools/*.jed; do \
60+ build/Pretty $$f | cmp -s - $$f || { echo "not formatted: $$f"; fail=1; }; \
61+ done; test $$fail = 0
62+
5563 # lines of the compiler: all of them, and those that aren't blank or comments
5664 loc:
5765 @python3 test/loc.py src/*.pas
5866
59-.PHONY: units tests check gdb bench stress loc clean
67+.PHONY: units tests check gdb bench stress fmt loc clean

PLAN.md (history) modified +4 -3

@@ -163,9 +163,10 @@
163163
164164 Later
165165
166-- [ ] 18. `tools/Pretty.jed`, a formatter that keeps every line break
166+- [x] 18. `tools/Pretty.jed`, a formatter that keeps every line break
167167 and comment where it is: it fixes indentation (4 spaces a level)
168168 and the spaces around operators and after `,` and `;`, and
169169 leaves formatted code as it is. It shares with `Doc.jed` a
170- scanner that keeps comments. `make fmt` checks that `lib/`,
171- `examples/` and `tools/` come through unchanged.
170+ scanner that keeps comments, `tools/Scan.jed`. `make fmt` checks
171+ that `lib/`, `examples/` and `tools/` come through unchanged, and
172+ `make check` does too, with the cases in `test/pretty`.

README.md (history) modified +10 -0

@@ -39,6 +39,7 @@
3939 | `lib/` | The library, in jed; the compiler finds it beside itself |
4040 | `examples/` | Small programs, each with the output it should give |
4141 | `tools/Doc.jed` | Prints what a module exports, with its comments |
42+| `tools/Pretty.jed` | The formatter: fixes indentation and spacing |
4243 | `editor/` | Support for vim and emacs |
4344 | `test/` | Tests, and the scripts that run them |
4445 | `PLAN.md` | How the compiler was built, step by step |
@@ -57,6 +58,7 @@
5758 make bench # the compiler's speed on a program of 350,000 lines
5859 make stress # 40,000 threads, started and joined
5960 make gdb # gdb stops at a line of jed and names it
61+ make fmt # the library, examples and tools are formatted
6062 make loc # the compiler's lines
6163 make tests # tests of the scanner, encoder and linker on their own
6264
@@ -114,6 +116,14 @@
114116 detection: add it to `runtimepath`. `editor/emacs/jed-mode.el` is a
115117 major mode: put it on `load-path` and `(require 'jed-mode)`. Both
116118 colour the language and indent it as the examples are indented.
119+
120+`tools/Pretty.jed` formats a whole file the same way: it fixes the
121+indentation, 4 spaces a level, and the spaces around operators and
122+after `,` and `;`, and keeps every line break and comment where it is.
123+
124+ $ ./jed -o Pretty tools/Pretty.jed
125+ $ ./Pretty Module.jed # prints it, formatted
126+ $ ./Pretty -w *.jed # rewrites those that aren't, and names them
117127
118128 ## Versions
119129

test/check.sh (history) modified +21 -2

@@ -8,8 +8,8 @@
88 # A program without X.expect is compiled, not run. test/libc puts
99 # lib/Sys.jed, over the C library, before the system call one.
1010 # Programs in test/err must not compile, and must print X.err. Then
11-# the version, tools/Doc.jed, the report's examples, and the library's
12-# own tests.
11+# the version, tools/Doc.jed, the report's examples, tools/Pretty.jed,
12+# and the library's own tests.
1313
1414 jed=./jed
1515 out=build/check
@@ -89,6 +89,25 @@
8989 done
9090 else
9191 echo "FAIL tools/Doc.jed: $(cat $out/Doc.cerr)"; fail=$((fail + 1))
92+fi
93+
94+# tools/Pretty.jed: each test/pretty/X.jed comes out as X.expect, which
95+# comes out as it is; so do the library, the examples and the tools
96+if ./jed -o $out/Pretty tools/Pretty.jed 2>$out/Pretty.cerr; then
97+ for f in test/pretty/*.jed; do
98+ want=test/pretty/$(basename $f .jed).expect
99+ if $out/Pretty $f | cmp -s - $want && $out/Pretty $want | cmp -s - $want; then
100+ pass=$((pass + 1))
101+ else echo "FAIL Pretty $f: output differs"; fail=$((fail + 1)); fi
102+ done
103+ for f in lib/*.jed examples/*.jed tools/*.jed; do
104+ if ! $out/Pretty $f | cmp -s - $f; then
105+ echo "FAIL Pretty $f: not formatted"; fail=$((fail + 1))
106+ fi
107+ done
108+ pass=$((pass + 1))
109+else
110+ echo "FAIL tools/Pretty.jed: $(cat $out/Pretty.cerr)"; fail=$((fail + 1))
92111 fi
93112
94113 # each library module's main is its test; Sys over C is tested in test/libc

test/pretty/Messy.expect (history) added +57 -0

@@ -0,0 +1,57 @@
1+(* A module laid out badly. *)
2+module Messy;
3+import Out, Rt;
4+
5+const
6+ max* = 10;
7+ min = -1;
8+
9+type
10+ Pair* = record
11+ a*, b: I64; (* two numbers *)
12+ end;
13+ Shape = variant
14+ circle(r: I64);
15+ dot;
16+ end;
17+
18+(* the bigger *)
19+proc max2*(a, b:I64):I64;
20+var m : I64;
21+begin
22+ if a > b then m := a;
23+ elsif a = b then
24+ m := a;
25+ else
26+ m := b; end;
27+ return m;
28+end;
29+
30+proc area(s: Shape): I64;
31+begin
32+ match s of
33+ | circle(r): return 3 * r * r;
34+ | dot:
35+ return 0;
36+ end;
37+end;
38+
39+proc main*;
40+var i, s:I64; p: Pair;
41+begin
42+ s := 0;
43+ for i := -3 to max - 1 do s := s + i * 2 - -1; end;
44+ repeat
45+ s := s - 1;
46+ until s < 0;
47+ if (s # -1) or (max2(3, 4) # 4)
48+ or (area({dot}) # 0) then Rt.stop("Messy"); end;
49+ p := {a: -s, b:2};
50+ Out.int(p.a); (* the first *)
51+ Out.ln;
52+ (* and done:
53+ a comment that moves
54+ with its line *)
55+end;
56+
57+end Messy.

test/pretty/Messy.jed added +57 -0

@@ -0,0 +1,57 @@
1+(* A module laid out badly. *)
2+ module Messy;
3+import Out,Rt;
4+
5+const
6+max* =10;
7+ min=-1;
8+
9+type
10+ Pair* = record
11+ a*,b: I64; (* two numbers *)
12+ end;
13+ Shape = variant
14+ circle(r: I64);
15+ dot;
16+ end;
17+
18+ (* the bigger *)
19+ proc max2*(a,b:I64):I64;
20+var m : I64;
21+ begin
22+if a>b then m:=a;
23+ elsif a=b then
24+ m :=a ;
25+ else
26+ m:= b;end;
27+ return m;
28+ end;
29+
30+proc area(s: Shape): I64;
31+begin
32+match s of
33+ | circle(r): return 3*r*r;
34+| dot:
35+ return 0;
36+ end;
37+end;
38+
39+proc main*;
40+var i,s:I64; p: Pair;
41+begin
42+ s:=0;
43+ for i:=-3 to max-1 do s:=s+i*2- -1;end;
44+ repeat
45+ s := s-1 ;
46+ until s<0;
47+ if (s # -1) or (max2(3,4) # 4)
48+ or (area({dot}) # 0) then Rt.stop("Messy"); end;
49+ p := {a: -s, b:2};
50+ Out.int(p.a); (* the first *)
51+ Out.ln;
52+ (* and done:
53+ a comment that moves
54+ with its line *)
55+end;
56+
57+end Messy.

tools/Doc.jed modified +46 -159

@@ -10,144 +10,33 @@
1010 module to end, with no ... left out, to dir/Name.jed, and prints
1111 the names, one a line. *)
1212 module Doc;
13-import Out, Sys, Rt, Str, Buf, Heap;
13+import Out, Rt, Str, Buf, Heap, Scan, Files;
1414
15-type
16- Kind = (ident, other, eof);
17-
1815 var
19- src: []U8; (* the text being read *)
20- pos: I64;
21- kind: Kind; (* the current token *)
22- tokStart, tokEnd: I64;
16+ sc: Scan.Scanner; (* the text being read, at the current symbol *)
17+ src: []U8;
2318 docStart, docEnd: I64; (* the comment just before it, or -1 *)
2419
25-(* Argument i, a C string, as a slice. *)
26-proc arg(i: I64): []U8;
27-var s: ^U8; n: I64;
28-begin
29- s := ARGV()[i];
30- n := 0;
31- while s[n] # 0 do INC(n); end;
32- return s[0..n];
33-end;
34-
35-proc readFile(path: []U8; b: ^Buf.Buf): BOOL;
36-var fd, n: I64; chunk: [4096]U8;
20+(* On to the next symbol that isn't a comment, keeping where the last
21+ comment that starts a line was: one after code on its line belongs
22+ to that code. *)
23+proc next;
24+var newLine: BOOL;
3725 begin
38- fd := Sys.openRead(path);
39- if fd < 0 then return false; end;
26+ docStart := -1;
27+ newLine := false;
4028 repeat
41- n := Sys.read(fd, chunk);
42- if n > 0 then Buf.str(b, chunk[0..n]); end;
43- until n <= 0;
44- Sys.close(fd);
45- return n = 0;
46-end;
47-
48-proc writeFile(path, data: []U8): BOOL;
49-var fd, n, at: I64;
50-begin
51- fd := Sys.create(path);
52- if fd < 0 then return false; end;
53- at := 0;
54- while at < LEN(data) do
55- n := Sys.write(fd, data[at..LEN(data)]);
56- if n <= 0 then Sys.close(fd); return false; end;
57- at := at + n;
58- end;
59- Sys.close(fd);
60- return true;
61-end;
62-
63-proc isSpace(c: U8): BOOL;
64-begin
65- return (c = ' ') or (c = 9) or (c = 10) or (c = 13);
66-end;
67-
68-proc isWord(c: U8): BOOL;
69-begin
70- return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z')
71- or (c >= '0') and (c <= '9') or (c = '_');
72-end;
73-
74-(* Past a string or character literal that starts at pos. *)
75-proc skipLiteral;
76-var q: U8;
77-begin
78- q := src[pos];
79- INC(pos);
80- while (pos < LEN(src)) and (src[pos] # q) do
81- if src[pos] = '\\' then INC(pos); end;
82- INC(pos);
83- end;
84- INC(pos);
85-end;
86-
87-(* Past the comment at pos. *)
88-proc skipComment;
89-var depth: I64;
90-begin
91- depth := 0;
92- repeat
93- if (src[pos] = '(') and (pos + 1 < LEN(src)) and (src[pos + 1] = '*') then
94- INC(depth); INC(pos, 2);
95- elsif (src[pos] = '*') and (pos + 1 < LEN(src)) and (src[pos + 1] = ')') then
96- DEC(depth); INC(pos, 2);
97- else
98- INC(pos);
29+ Scan.next(ADR(sc));
30+ newLine := newLine or sc.lineBreak;
31+ if (sc.kind = Scan.comment) and newLine then
32+ docStart := sc.start; docEnd := sc.stop;
9933 end;
100- until (depth = 0) or (pos >= LEN(src));
101-end;
102-
103-proc atComment(p: I64): BOOL;
104-begin
105- return (p + 1 < LEN(src)) and (src[p] = '(') and (src[p + 1] = '*');
34+ until sc.kind # Scan.comment;
10635 end;
10736
108-(* Past spaces and comments, keeping where the last comment that starts
109- a line was: one after code on its line belongs to that code. *)
110-proc skipSpace;
111-var start: I64; newLine: BOOL;
112-begin
113- docStart := -1;
114- newLine := pos = 0;
115- while pos < LEN(src) do
116- if isSpace(src[pos]) then
117- if src[pos] = 10 then newLine := true; end;
118- INC(pos);
119- elsif atComment(pos) then
120- start := pos;
121- skipComment;
122- if newLine then docStart := start; docEnd := pos; end;
123- else
124- break;
125- end;
126- end;
127-end;
128-
129-proc next;
130-begin
131- skipSpace;
132- tokStart := pos;
133- if pos >= LEN(src) then
134- kind := eof;
135- elsif isWord(src[pos]) then
136- while (pos < LEN(src)) and isWord(src[pos]) do INC(pos); end;
137- kind := ident;
138- elsif (src[pos] = '"') or (src[pos] = '\'') then
139- skipLiteral;
140- kind := other;
141- else
142- INC(pos);
143- kind := other;
144- end;
145- tokEnd := pos;
146-end;
147-
14837 proc text: []U8;
14938 begin
150- return src[tokStart..tokEnd];
39+ return Scan.text(ADR(sc));
15140 end;
15241
15342 proc is(s: []U8): BOOL;
@@ -168,27 +57,25 @@
16857 var depth: I64;
16958 begin
17059 depth := 0;
171- while kind # eof do
60+ while sc.kind # Scan.eof do
17261 if is("(") or is("[") or is("{") or is("record") or is("variant") then INC(depth);
17362 elsif is(")") or is("]") or is("}") or is("end") then DEC(depth);
174- elsif is(";") and (depth <= 0) then return tokEnd;
63+ elsif is(";") and (depth <= 0) then return sc.stop;
17564 end;
17665 next;
17766 end;
178- return pos;
67+ return sc.pos;
17968 end;
18069
18170 (* stop, or the end of a comment that follows it on its line. *)
18271 proc trailing(stop: I64): I64;
183-var save: I64;
72+var t: Scan.Scanner;
18473 begin
18574 while (stop < LEN(src)) and ((src[stop] = ' ') or (src[stop] = 9)) do INC(stop); end;
186- if not atComment(stop) then return stop; end;
187- save := pos;
188- pos := stop;
189- skipComment;
190- stop := pos;
191- pos := save;
75+ t := sc;
76+ t.pos := stop;
77+ Scan.next(ADR(t));
78+ if (t.kind = Scan.comment) and (t.start = stop) then return t.stop; end;
19279 return stop;
19380 end;
19481
@@ -225,8 +112,8 @@
225112 if start < 0 then return; end;
226113 i := start + 2;
227114 j := stop - 2;
228- while (i < j) and isSpace(src[i]) do INC(i); end;
229- while (j > i) and isSpace(src[j - 1]) do DEC(j); end;
115+ while (i < j) and Scan.isSpace(src[i]) do INC(i); end;
116+ while (j > i) and Scan.isSpace(src[j - 1]) do DEC(j); end;
230117 atLine := true;
231118 while i < j do
232119 if atLine then Out.str(" "); atLine := false; end;
@@ -266,7 +153,7 @@
266153 begin
267154 depth := 0;
268155 sawBegin := false;
269- while kind # eof do
156+ while sc.kind # Scan.eof do
270157 if is("begin") then
271158 if depth = 0 then sawBegin := true; end;
272159 INC(depth);
@@ -276,7 +163,7 @@
276163 DEC(depth);
277164 if (depth = 0) and sawBegin then
278165 next;
279- if kind = ident then next; end;
166+ if sc.kind = Scan.word then next; end;
280167 return;
281168 end;
282169 end;
@@ -287,7 +174,7 @@
287174 proc procedure;
288175 var start, ds, de, stop: I64; exp: BOOL;
289176 begin
290- start := tokStart; ds := docStart; de := docEnd;
177+ start := sc.start; ds := docStart; de := docEnd;
291178 exp := name();
292179 stop := toSemicolon();
293180 next;
@@ -303,9 +190,9 @@
303190 begin
304191 word := text();
305192 next;
306- while (kind = ident) and not reserved() do
307- start := tokStart; ds := docStart; de := docEnd;
308- pos := tokStart; (* name reads the name again *)
193+ while (sc.kind = Scan.word) and not reserved() do
194+ start := sc.start; ds := docStart; de := docEnd;
195+ sc.pos := sc.start; (* name reads the name again *)
309196 exp := name();
310197 stop := toSemicolon();
311198 if exp then
@@ -321,7 +208,7 @@
321208 proc external;
322209 var start, ds, de, stop: I64; exp: BOOL;
323210 begin
324- start := tokStart; ds := docStart; de := docEnd;
211+ start := sc.start; ds := docStart; de := docEnd;
325212 next;
326213 exp := name();
327214 stop := toSemicolon();
@@ -333,18 +220,18 @@
333220 var b: Buf.Buf; start, ds, de: I64;
334221 begin
335222 Buf.init(ADR(b), Heap.heap);
336- if not readFile(path, ADR(b)) then Rt.stop("Doc: can't read the file"); end;
223+ if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the file"); end;
337224 src := Buf.bytes(ADR(b));
338- pos := 0;
225+ Scan.init(ADR(sc), src);
339226 next;
340- while (kind # eof) and not is("module") do next; end;
341- if kind = eof then Rt.stop("Doc: no module"); end;
342- start := tokStart;
227+ while (sc.kind # Scan.eof) and not is("module") do next; end;
228+ if sc.kind = Scan.eof then Rt.stop("Doc: no module"); end;
229+ start := sc.start;
343230 ds := docStart; de := docEnd;
344231 block(start, toSemicolon());
345232 comment(ds, de);
346233 next;
347- while (kind # eof) and not is("begin") and not is("end") do
234+ while (sc.kind # Scan.eof) and not is("begin") and not is("end") do
348235 if is("const") or is("type") or is("var") then section;
349236 elsif is("proc") then procedure;
350237 elsif is("extern") then external;
@@ -360,8 +247,8 @@
360247 begin
361248 i := 0;
362249 j := LEN(line);
363- while (i < j) and isSpace(line[i]) do INC(i); end;
364- while (j > i) and isSpace(line[j - 1]) do DEC(j); end;
250+ while (i < j) and Scan.isSpace(line[i]) do INC(i); end;
251+ while (j > i) and Scan.isSpace(line[j - 1]) do DEC(j); end;
365252 return line[i..j];
366253 end;
367254
@@ -373,7 +260,7 @@
373260 begin
374261 Buf.init(ADR(b), Heap.heap);
375262 Buf.init(ADR(out), Heap.heap);
376- if not readFile(path, ADR(b)) then Rt.stop("Doc: can't read the report"); end;
263+ if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the report"); end;
377264 s := Buf.bytes(ADR(b));
378265 inBlock := false;
379266 start := 0;
@@ -386,12 +273,12 @@
386273 if inBlock and whole and Str.hasPrefix(first, "module ") and Str.hasPrefix(last, "end ") then
387274 name := first[7..LEN(first)];
388275 n := 0;
389- while (n < LEN(name)) and isWord(name[n]) do INC(n); end;
276+ while (n < LEN(name)) and Scan.isWord(name[n]) do INC(n); end;
390277 name := name[0..n];
391278 Buf.reset(ADR(out));
392279 Buf.str(ADR(out), dir); Buf.str(ADR(out), "/"); Buf.str(ADR(out), name);
393280 Buf.str(ADR(out), ".jed");
394- if not writeFile(Buf.bytes(ADR(out)), s[start..i]) then
281+ if not Files.write(Buf.bytes(ADR(out)), s[start..i]) then
395282 Rt.stop("Doc: can't write an example");
396283 end;
397284 Out.str(name); Out.ln;
@@ -413,8 +300,8 @@
413300
414301 proc main*;
415302 begin
416- if (ARGC() = 4) and (arg(1) = "examples") then examples(arg(2), arg(3));
417- elsif ARGC() = 2 then document(arg(1));
303+ if (ARGC() = 4) and (Files.arg(1) = "examples") then examples(Files.arg(2), Files.arg(3));
304+ elsif ARGC() = 2 then document(Files.arg(1));
418305 else Rt.stop("usage: Doc Module.jed, or Doc examples report.md dir");
419306 end;
420307 end;

tools/Files.jed added +46 -0

@@ -0,0 +1,46 @@
1+(* Files: what the tools need of the command line and of files: an
2+ argument as a string, and a whole file read or written. *)
3+module Files;
4+import Sys, Buf;
5+
6+(* Argument i, a C string, as a slice. *)
7+proc arg*(i: I64): []U8;
8+var s: ^U8; n: I64;
9+begin
10+ s := ARGV()[i];
11+ n := 0;
12+ while s[n] # 0 do INC(n); end;
13+ return s[0..n];
14+end;
15+
16+(* Adds the file at path to b; false if it can't be read. *)
17+proc read*(path: []U8; b: ^Buf.Buf): BOOL;
18+var fd, n: I64; chunk: [4096]U8;
19+begin
20+ fd := Sys.openRead(path);
21+ if fd < 0 then return false; end;
22+ repeat
23+ n := Sys.read(fd, chunk);
24+ if n > 0 then Buf.str(b, chunk[0..n]); end;
25+ until n <= 0;
26+ Sys.close(fd);
27+ return n = 0;
28+end;
29+
30+(* Makes the file at path hold data; false if it can't be written. *)
31+proc write*(path, data: []U8): BOOL;
32+var fd, n, at: I64;
33+begin
34+ fd := Sys.create(path);
35+ if fd < 0 then return false; end;
36+ at := 0;
37+ while at < LEN(data) do
38+ n := Sys.write(fd, data[at..LEN(data)]);
39+ if n <= 0 then Sys.close(fd); return false; end;
40+ at := at + n;
41+ end;
42+ Sys.close(fd);
43+ return true;
44+end;
45+
46+end Files.

tools/Pretty.jed added +339 -0

@@ -0,0 +1,339 @@
1+(* Pretty: jed source laid out the one way.
2+
3+ Pretty Module.jed
4+ prints the module, formatted.
5+
6+ Pretty -w File.jed...
7+ rewrites each file that isn't formatted already.
8+
9+ Every line break and comment stays where it is. A line is indented
10+ 4 spaces for each block it stands in: the statements of if, while,
11+ for, repeat and begin, the fields of a record or variant, the
12+ declarations of const, type and var. end, until, else, elsif and a
13+ match's arms stand at the level of the statement that opened them;
14+ module, import, proc, the sections and begin at the margin, with the
15+ comment just before them. A line that goes on with the expression of
16+ the line before keeps its indent, moved as far as the statement's
17+ first line moved; so does the text of a comment.
18+
19+ Within a line, a binary operator has one space on each side, a unary
20+ minus none after it, and , and ; none before them and one after. A
21+ comment after code keeps its column. Other spaces stay as written,
22+ so that lined-up match arms stay lined up. No line ends in spaces. *)
23+module Pretty;
24+import Out, Rt, Buf, Heap, Scan, Files;
25+
26+const
27+ width = 4; (* the spaces of a level *)
28+ openers = "if while for match record variant begin repeat";
29+ declarations = "module import link extern proc const type var begin code";
30+ binaryWords = "div mod and or xor shl shr in";
31+ binarySymbols = "+ - * / = # < <= > >= :=";
32+
33+var
34+ sc: Scan.Scanner; (* the source, at the symbol being written *)
35+ src: []U8;
36+ out: Buf.Buf;
37+ lineAt: I64; (* where the line being written starts in out *)
38+ lineDelta: I64; (* how far this line's indent moved *)
39+
40+ (* the blocks open, each with the indent of the statement that
41+ opened it *)
42+ bases: [100]I64;
43+ depth: I64;
44+ brackets: I64; (* brackets open *)
45+ inSection: BOOL; (* among the declarations of const, type or var *)
46+ stmtIndent: I64; (* the indent of the current statement's first line *)
47+ stmtDelta: I64; (* and how far that moved *)
48+
49+ (* the last symbol that wasn't a comment, and the one before it *)
50+ prev, prev2: Scan.Scanner;
51+ prevBinary, prevUnary: BOOL;
52+ afterComment: BOOL; (* the last symbol written was a comment *)
53+ last: I64; (* where the last symbol written ends in src *)
54+
55+proc spaces(n: I64);
56+begin
57+ while n > 0 do Buf.add(ADR(out), ' '); DEC(n); end;
58+end;
59+
60+(* Drops the spaces at the end of the line in out. *)
61+proc trim;
62+var s: []U8;
63+begin
64+ s := Buf.bytes(ADR(out));
65+ while (out.len > lineAt) and ((s[out.len - 1] = ' ') or (s[out.len - 1] = '\t')) do
66+ DEC(out.len);
67+ end;
68+end;
69+
70+proc newLine;
71+begin
72+ trim;
73+ Buf.add(ADR(out), '\n');
74+ lineAt := out.len;
75+end;
76+
77+(* Where the line holding p starts in src. *)
78+proc lineStart(p: I64): I64;
79+begin
80+ while (p > 0) and (src[p - 1] # '\n') do DEC(p); end;
81+ return p;
82+end;
83+
84+(* The column src[p] is at, a tab going on to the next multiple of 8. *)
85+proc column(p: I64): I64;
86+var i, col: I64;
87+begin
88+ col := 0;
89+ for i := lineStart(p) to p - 1 do
90+ if src[i] = '\t' then col := (col div 8 + 1) * 8; else INC(col); end;
91+ end;
92+ return col;
93+end;
94+
95+(* Whether s ends an operand, so that a - after it subtracts. *)
96+proc endsOperand(s: ^Scan.Scanner): BOOL;
97+begin
98+ if s^.kind = Scan.word then return not Scan.reserved(Scan.text(s)); end;
99+ return (s^.kind = Scan.number) or (s^.kind = Scan.literal)
100+ or Scan.is(s, ")") or Scan.is(s, "]") or Scan.is(s, "}") or Scan.is(s, "^");
101+end;
102+
103+(* The symbol after the current one that isn't a comment. *)
104+proc following: Scan.Scanner;
105+var s: Scan.Scanner;
106+begin
107+ s := sc;
108+ repeat Scan.next(ADR(s)); until s.kind # Scan.comment;
109+ return s;
110+end;
111+
112+(* Whether the current symbol is a binary operator. A * after a name
113+ and before ; , : = ) or a procedure's parameters exports the name. *)
114+proc binary: BOOL;
115+var n: Scan.Scanner;
116+begin
117+ if sc.kind = Scan.word then return Scan.among(Scan.text(ADR(sc)), binaryWords); end;
118+ if (sc.kind # Scan.symbol) or not Scan.among(Scan.text(ADR(sc)), binarySymbols) then
119+ return false;
120+ end;
121+ if Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+") then return endsOperand(ADR(prev)); end;
122+ if Scan.is(ADR(sc), "*") and (prev.kind = Scan.word) then
123+ n := following();
124+ if Scan.among(Scan.text(ADR(n)), "; , : = )") then return false; end;
125+ if Scan.is(ADR(n), "(") and Scan.is(ADR(prev2), "proc") then return false; end;
126+ end;
127+ return true;
128+end;
129+
130+(* Whether the current symbol, first on its line, goes on with the
131+ expression of the line before. *)
132+proc continues: BOOL;
133+var t: []U8;
134+begin
135+ if (brackets > 0) or prevBinary or Scan.is(ADR(prev), ",") then return true; end;
136+ t := Scan.text(ADR(sc));
137+ if sc.kind = Scan.word then return Scan.among(t, binaryWords) or Scan.among(t, "then do of"); end;
138+ return (sc.kind = Scan.symbol) and Scan.among(t, binarySymbols);
139+end;
140+
141+(* Whether s starts a declaration at the margin: proc( starts a
142+ procedure type. *)
143+proc declaration(s: Scan.Scanner): BOOL;
144+begin
145+ if (s.kind # Scan.word) or not Scan.among(Scan.text(ADR(s)), declarations) then return false; end;
146+ if not Scan.is(ADR(s), "proc") then return true; end;
147+ Scan.next(ADR(s));
148+ return not Scan.is(ADR(s), "(");
149+end;
150+
151+(* The indent of the block's own lines, or of its end. *)
152+proc inner: I64;
153+begin
154+ if depth > 0 then return bases[depth - 1] + width; end;
155+ if inSection then return width; end;
156+ return 0;
157+end;
158+
159+proc outer: I64;
160+begin
161+ if depth > 0 then return bases[depth - 1]; end;
162+ return 0;
163+end;
164+
165+(* The indent of the line the current symbol starts, which was at old. *)
166+proc indent(old: I64): I64;
167+var n: Scan.Scanner;
168+begin
169+ if continues() then
170+ if old + stmtDelta < 0 then return 0; end;
171+ return old + stmtDelta;
172+ end;
173+ if sc.kind = Scan.comment then
174+ n := following();
175+ if n.lineBreak and declaration(n) then return 0; end;
176+ return inner();
177+ end;
178+ if declaration(sc) then
179+ depth := 0;
180+ inSection := Scan.among(Scan.text(ADR(sc)), "const type var");
181+ return 0;
182+ end;
183+ if Scan.among(Scan.text(ADR(sc)), "end until else elsif |") then
184+ return outer();
185+ end;
186+ return inner();
187+end;
188+
189+(* Starts the line of the current symbol, at its indent. *)
190+proc startLine;
191+var old, new: I64;
192+begin
193+ old := column(sc.start);
194+ new := indent(old);
195+ lineDelta := new - old;
196+ if (sc.kind # Scan.comment) and not continues() then
197+ stmtIndent := new;
198+ stmtDelta := lineDelta;
199+ end;
200+ spaces(new);
201+end;
202+
203+(* The spaces between the last symbol written and the current one, on
204+ the same line. *)
205+proc gap(binaryNow: BOOL);
206+var n: I64;
207+begin
208+ if sc.kind = Scan.comment then
209+ n := column(sc.start) + lineDelta - (out.len - lineAt);
210+ if (n < 1) and (sc.start > last) then n := 1; end;
211+ spaces(n);
212+ elsif afterComment then
213+ Buf.str(ADR(out), src[last..sc.start]);
214+ elsif Scan.is(ADR(sc), ",") or Scan.is(ADR(sc), ";") then
215+ elsif Scan.is(ADR(prev), ",") or Scan.is(ADR(prev), ";") or binaryNow or prevBinary then
216+ if not prevUnary then spaces(1); end;
217+ elsif not prevUnary then
218+ Buf.str(ADR(out), src[last..sc.start]);
219+ end;
220+end;
221+
222+(* The current symbol as written; each line of a comment after its
223+ first is moved as far as the line the comment starts on. *)
224+proc write;
225+var i, k: I64;
226+begin
227+ i := sc.start;
228+ while i < sc.stop do
229+ if src[i] = '\n' then
230+ newLine;
231+ k := i + 1;
232+ while (k < sc.stop) and (src[k] = ' ') do INC(k); end;
233+ if (k < sc.stop) and (src[k] # '\n') then spaces(k - (i + 1) + lineDelta); end;
234+ i := k;
235+ else
236+ Buf.add(ADR(out), src[i]);
237+ INC(i);
238+ end;
239+ end;
240+end;
241+
242+(* After a symbol that isn't a comment: the blocks and brackets it opens
243+ or closes. *)
244+proc track(binaryNow: BOOL);
245+var t: []U8;
246+begin
247+ t := Scan.text(ADR(sc));
248+ if sc.kind = Scan.word then
249+ if Scan.among(t, openers) then
250+ if depth = LEN(bases) then Rt.stop("Pretty: blocks nested too deep"); end;
251+ bases[depth] := stmtIndent;
252+ INC(depth);
253+ elsif ((t = "end") or (t = "until")) and (depth > 0) then
254+ DEC(depth);
255+ end;
256+ elsif sc.kind = Scan.symbol then
257+ if Scan.among(t, "( [ {") then INC(brackets);
258+ elsif Scan.among(t, ") ] }") and (brackets > 0) then DEC(brackets);
259+ end;
260+ end;
261+ prevUnary := (Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+")) and not binaryNow;
262+ prevBinary := binaryNow;
263+ prev2 := prev;
264+ prev := sc;
265+end;
266+
267+(* The line breaks in src[from..upto]. *)
268+proc lineBreaks(from, upto: I64);
269+var i: I64;
270+begin
271+ for i := from to upto - 1 do
272+ if src[i] = '\n' then newLine; end;
273+ end;
274+end;
275+
276+(* src, formatted, into out. *)
277+proc format(text: []U8);
278+var b: BOOL;
279+begin
280+ src := text;
281+ Buf.reset(ADR(out));
282+ lineAt := 0;
283+ depth := 0;
284+ brackets := 0;
285+ inSection := false;
286+ stmtIndent := 0;
287+ stmtDelta := 0;
288+ Scan.init(ADR(sc), src);
289+ prev := sc;
290+ prev2 := sc;
291+ prevBinary := false;
292+ prevUnary := false;
293+ afterComment := false;
294+ last := 0;
295+ Scan.next(ADR(sc));
296+ while sc.kind # Scan.eof do
297+ b := (sc.kind # Scan.comment) and binary();
298+ if sc.lineBreak then
299+ lineBreaks(last, sc.start);
300+ startLine;
301+ else
302+ gap(b);
303+ end;
304+ write;
305+ afterComment := sc.kind = Scan.comment;
306+ if not afterComment then track(b); end;
307+ last := sc.stop;
308+ Scan.next(ADR(sc));
309+ end;
310+ lineBreaks(last, LEN(src));
311+ trim;
312+end;
313+
314+proc main*;
315+var b: Buf.Buf; i: I64; path: []U8;
316+begin
317+ Buf.init(ADR(b), Heap.heap);
318+ Buf.init(ADR(out), Heap.heap);
319+ if (ARGC() >= 3) and (Files.arg(1) = "-w") then
320+ for i := 2 to ARGC() - 1 do
321+ path := Files.arg(i);
322+ Buf.reset(ADR(b));
323+ if not Files.read(path, ADR(b)) then Rt.stop("Pretty: can't read a file"); end;
324+ format(Buf.bytes(ADR(b)));
325+ if Buf.bytes(ADR(out)) # Buf.bytes(ADR(b)) then
326+ if not Files.write(path, Buf.bytes(ADR(out))) then Rt.stop("Pretty: can't write a file"); end;
327+ Out.str(path); Out.ln;
328+ end;
329+ end;
330+ elsif ARGC() = 2 then
331+ if not Files.read(Files.arg(1), ADR(b)) then Rt.stop("Pretty: can't read the file"); end;
332+ format(Buf.bytes(ADR(b)));
333+ Out.str(Buf.bytes(ADR(out)));
334+ else
335+ Rt.stop("usage: Pretty Module.jed, or Pretty -w File.jed...");
336+ end;
337+end;
338+
339+end Pretty.

tools/Scan.jed added +171 -0

@@ -0,0 +1,171 @@
1+(* Scan: the symbols of jed source, for the tools. Unlike the
2+ compiler's scanner it keeps comments, as symbols of their own, and
3+ says where each symbol is in the text and whether a line break comes
4+ before it. It doesn't check what it reads: a malformed number is
5+ read as far as it goes, and a string, character or comment left open
6+ ends with its line or the text. *)
7+module Scan;
8+
9+type
10+ Kind* = (word, number, literal, symbol, comment, eof);
11+
12+ (* word is an identifier or a reserved word; literal a string or a
13+ character; symbol an operator or delimiter. *)
14+ Scanner* = record
15+ src*: []U8;
16+ pos*: I64; (* where the next symbol is looked for *)
17+ kind*: Kind; (* the current symbol *)
18+ start*, stop*: I64; (* its text: src[start..stop] *)
19+ lineBreak*: BOOL; (* a line break comes before it, or it is the first *)
20+ end;
21+
22+const
23+ words = "and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc record repeat return set shl shr then to type until var variant VOLATILE while xor";
24+
25+proc isSpace*(c: U8): BOOL;
26+begin
27+ return (c = ' ') or (c = '\t') or (c = '\n') or (c = '\r');
28+end;
29+
30+proc isWord*(c: U8): BOOL;
31+begin
32+ return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z')
33+ or (c >= '0') and (c <= '9') or (c = '_');
34+end;
35+
36+proc isDigit(c: U8): BOOL;
37+begin
38+ return (c >= '0') and (c <= '9');
39+end;
40+
41+(* Whether w is one of the words of list, which are separated by
42+ single spaces. *)
43+proc among*(w, list: []U8): BOOL;
44+var i, j: I64;
45+begin
46+ i := 0;
47+ while i < LEN(list) do
48+ j := i;
49+ while (j < LEN(list)) and (list[j] # ' ') do INC(j); end;
50+ if list[i..j] = w then return true; end;
51+ i := j + 1;
52+ end;
53+ return false;
54+end;
55+
56+(* Whether w is one of the report's reserved words. *)
57+proc reserved*(w: []U8): BOOL;
58+begin
59+ return among(w, words);
60+end;
61+
62+(* The scanner at the start of src; next gives the first symbol. *)
63+proc init*(s: ^Scanner; src: []U8);
64+begin
65+ s^ := {src: src, kind: eof};
66+end;
67+
68+(* Past the comment that starts at p, its nested comments with it. *)
69+proc pastComment(src: []U8; p: I64): I64;
70+var depth: I64;
71+begin
72+ depth := 0;
73+ repeat
74+ if (src[p] = '(') and (p + 1 < LEN(src)) and (src[p + 1] = '*') then
75+ INC(depth); INC(p, 2);
76+ elsif (src[p] = '*') and (p + 1 < LEN(src)) and (src[p + 1] = ')') then
77+ DEC(depth); INC(p, 2);
78+ else
79+ INC(p);
80+ end;
81+ until (depth = 0) or (p >= LEN(src));
82+ return p;
83+end;
84+
85+(* Past the number that starts at p: digits and letters, then a real's
86+ point, digits and exponent, as in 0FFH and 2.0E-3. *)
87+proc pastNumber(src: []U8; p: I64): I64;
88+begin
89+ while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
90+ if (p + 1 < LEN(src)) and (src[p] = '.') and isDigit(src[p + 1]) then
91+ INC(p);
92+ while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
93+ if (src[p - 1] = 'E') and (p < LEN(src)) and ((src[p] = '-') or (src[p] = '+')) then
94+ INC(p);
95+ while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
96+ end;
97+ end;
98+ return p;
99+end;
100+
101+(* Past the string or character that starts at p, or to its line's end. *)
102+proc pastLiteral(src: []U8; p: I64): I64;
103+var q: U8;
104+begin
105+ q := src[p];
106+ INC(p);
107+ while (p < LEN(src)) and (src[p] # q) and (src[p] # '\n') do
108+ if (src[p] = '\\') and (p + 1 < LEN(src)) then INC(p); end;
109+ INC(p);
110+ end;
111+ if (p < LEN(src)) and (src[p] = q) then INC(p); end;
112+ return p;
113+end;
114+
115+(* Whether src[p..] starts with the symbol t. *)
116+proc at(src: []U8; p: I64; t: []U8): BOOL;
117+begin
118+ return (p + LEN(t) <= LEN(src)) and (src[p..p + LEN(t)] = t);
119+end;
120+
121+(* On to the next symbol. *)
122+proc next*(s: ^Scanner);
123+var src: []U8; p: I64; c: U8;
124+begin
125+ src := s^.src;
126+ p := s^.pos;
127+ s^.lineBreak := p = 0;
128+ while (p < LEN(src)) and isSpace(src[p]) do
129+ if src[p] = '\n' then s^.lineBreak := true; end;
130+ INC(p);
131+ end;
132+ s^.start := p;
133+ if p >= LEN(src) then
134+ s^.kind := eof;
135+ else
136+ c := src[p];
137+ if at(src, p, "(*") then
138+ s^.kind := comment; p := pastComment(src, p);
139+ elsif isDigit(c) then
140+ s^.kind := number; p := pastNumber(src, p);
141+ elsif isWord(c) then
142+ s^.kind := word;
143+ while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
144+ elsif (c = '"') or (c = '\'') then
145+ s^.kind := literal; p := pastLiteral(src, p);
146+ else
147+ s^.kind := symbol;
148+ if at(src, p, "...") then INC(p, 3);
149+ elsif at(src, p, ":=") or at(src, p, "<=") or at(src, p, ">=") or at(src, p, "..") then
150+ INC(p, 2);
151+ else
152+ INC(p);
153+ end;
154+ end;
155+ end;
156+ s^.stop := p;
157+ s^.pos := p;
158+end;
159+
160+proc text*(s: ^Scanner): []U8;
161+begin
162+ return s^.src[s^.start..s^.stop];
163+end;
164+
165+(* Whether the current symbol is t. *)
166+proc is*(s: ^Scanner; t: []U8): BOOL;
167+begin
168+ return text(s) = t;
169+end;
170+
171+end Scan.