From c256837c2ee4fd5ab3d46d4ab0c7b790b8edb7f1 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sat, 10 Oct 2026 15:15:56 +0000 Subject: [PATCH] Step 18: tools/Pretty.jed, the formatter, over tools/Scan.jed, shared with Doc --- diff --git a/CLAUDE.md b/CLAUDE.md index 6bfee23..952d532 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,8 +14,9 @@ make tests # the small Pascal tests of scan, x64, link and elf make gdb # gdb stops at a line of a test and names it make stress # 40,000 native threads; make check runs a small version + make fmt # lib/, examples/ and tools/ are formatted -`make check` also runs `tools/Doc.jed`, the report's whole examples, +`make check` also runs `tools/Doc.jed` and `tools/Pretty.jed`, the report's whole examples, each library module's own `main` (its test), and the vim and emacs support headless where they are installed (`apt-get install -y vim emacs-nox`): each example must indent back exactly as written. @@ -23,7 +24,7 @@ `make check` must pass before every commit. Tests: `test/run/X.jed` with `X.expect` (stdout), optional `X.status` and `X.args`; modules they import in `test/run/mods`. `test/err/X.jed` must fail to compile with -the text in `X.err`. Examples in `examples/` work the same way. +the text in `X.err`. `test/pretty/X.jed` must format to `X.expect`. Examples in `examples/` work the same way. ## How we work @@ -44,9 +45,10 @@ ## Where things stand -Steps 1-17 are done: the language, the tools, `README.md` and the -guide to the compiler, `doc/compiler.md`. Next, only on the owner's -word, is step 18, the formatter. Keep `doc/compiler.md`'s table of +Steps 1-18 are done: the language, the tools (`tools/Doc.jed`, and +the formatter, `tools/Pretty.jed`, over the shared `tools/Scan.jed`), +`README.md` and the guide to the compiler, `doc/compiler.md`. Nothing +further is planned; new work starts only on the owner's word. Keep `doc/compiler.md`'s table of lines and its routine names true when the compiler changes. Left for later at the owner's word: tagging versions, and a rewrite of var parameters. diff --git a/Makefile b/Makefile index 3385833..e8ed72b 100644 --- a/Makefile +++ b/Makefile @@ -52,8 +52,16 @@ build/Stress 40000 200 (ulimit -v 60000; build/Stress fail) +# the formatter, tools/Pretty.jed: the library, examples and tools are +# formatted already +fmt: jed | build + ./jed -o build/Pretty tools/Pretty.jed + @fail=0; for f in lib/*.jed examples/*.jed tools/*.jed; do \ + build/Pretty $$f | cmp -s - $$f || { echo "not formatted: $$f"; fail=1; }; \ + done; test $$fail = 0 + # lines of the compiler: all of them, and those that aren't blank or comments loc: @python3 test/loc.py src/*.pas -.PHONY: units tests check gdb bench stress loc clean +.PHONY: units tests check gdb bench stress fmt loc clean diff --git a/PLAN.md b/PLAN.md index a4f3918..3bd4e37 100644 --- a/PLAN.md +++ b/PLAN.md @@ -163,9 +163,10 @@ Later -- [ ] 18. `tools/Pretty.jed`, a formatter that keeps every line break +- [x] 18. `tools/Pretty.jed`, a formatter that keeps every line break and comment where it is: it fixes indentation (4 spaces a level) and the spaces around operators and after `,` and `;`, and leaves formatted code as it is. It shares with `Doc.jed` a - scanner that keeps comments. `make fmt` checks that `lib/`, - `examples/` and `tools/` come through unchanged. + scanner that keeps comments, `tools/Scan.jed`. `make fmt` checks + that `lib/`, `examples/` and `tools/` come through unchanged, and + `make check` does too, with the cases in `test/pretty`. diff --git a/README.md b/README.md index 6f40265..d449be9 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ | `lib/` | The library, in jed; the compiler finds it beside itself | | `examples/` | Small programs, each with the output it should give | | `tools/Doc.jed` | Prints what a module exports, with its comments | +| `tools/Pretty.jed` | The formatter: fixes indentation and spacing | | `editor/` | Support for vim and emacs | | `test/` | Tests, and the scripts that run them | | `PLAN.md` | How the compiler was built, step by step | @@ -57,6 +58,7 @@ make bench # the compiler's speed on a program of 350,000 lines make stress # 40,000 threads, started and joined make gdb # gdb stops at a line of jed and names it + make fmt # the library, examples and tools are formatted make loc # the compiler's lines make tests # tests of the scanner, encoder and linker on their own @@ -114,6 +116,14 @@ detection: add it to `runtimepath`. `editor/emacs/jed-mode.el` is a major mode: put it on `load-path` and `(require 'jed-mode)`. Both colour the language and indent it as the examples are indented. + +`tools/Pretty.jed` formats a whole file the same way: it fixes the +indentation, 4 spaces a level, and the spaces around operators and +after `,` and `;`, and keeps every line break and comment where it is. + + $ ./jed -o Pretty tools/Pretty.jed + $ ./Pretty Module.jed # prints it, formatted + $ ./Pretty -w *.jed # rewrites those that aren't, and names them ## Versions diff --git a/test/check.sh b/test/check.sh index da98d7d..98c9f7a 100755 --- a/test/check.sh +++ b/test/check.sh @@ -8,8 +8,8 @@ # A program without X.expect is compiled, not run. test/libc puts # lib/Sys.jed, over the C library, before the system call one. # Programs in test/err must not compile, and must print X.err. Then -# the version, tools/Doc.jed, the report's examples, and the library's -# own tests. +# the version, tools/Doc.jed, the report's examples, tools/Pretty.jed, +# and the library's own tests. jed=./jed out=build/check @@ -89,6 +89,25 @@ done else echo "FAIL tools/Doc.jed: $(cat $out/Doc.cerr)"; fail=$((fail + 1)) +fi + +# tools/Pretty.jed: each test/pretty/X.jed comes out as X.expect, which +# comes out as it is; so do the library, the examples and the tools +if ./jed -o $out/Pretty tools/Pretty.jed 2>$out/Pretty.cerr; then + for f in test/pretty/*.jed; do + want=test/pretty/$(basename $f .jed).expect + if $out/Pretty $f | cmp -s - $want && $out/Pretty $want | cmp -s - $want; then + pass=$((pass + 1)) + else echo "FAIL Pretty $f: output differs"; fail=$((fail + 1)); fi + done + for f in lib/*.jed examples/*.jed tools/*.jed; do + if ! $out/Pretty $f | cmp -s - $f; then + echo "FAIL Pretty $f: not formatted"; fail=$((fail + 1)) + fi + done + pass=$((pass + 1)) +else + echo "FAIL tools/Pretty.jed: $(cat $out/Pretty.cerr)"; fail=$((fail + 1)) fi # each library module's main is its test; Sys over C is tested in test/libc diff --git a/test/pretty/Messy.expect b/test/pretty/Messy.expect new file mode 100644 index 0000000..0390c35 --- /dev/null +++ b/test/pretty/Messy.expect @@ -0,0 +1,57 @@ +(* A module laid out badly. *) +module Messy; +import Out, Rt; + +const + max* = 10; + min = -1; + +type + Pair* = record + a*, b: I64; (* two numbers *) + end; + Shape = variant + circle(r: I64); + dot; + end; + +(* the bigger *) +proc max2*(a, b:I64):I64; +var m : I64; +begin + if a > b then m := a; + elsif a = b then + m := a; + else + m := b; end; + return m; +end; + +proc area(s: Shape): I64; +begin + match s of + | circle(r): return 3 * r * r; + | dot: + return 0; + end; +end; + +proc main*; +var i, s:I64; p: Pair; +begin + s := 0; + for i := -3 to max - 1 do s := s + i * 2 - -1; end; + repeat + s := s - 1; + until s < 0; + if (s # -1) or (max2(3, 4) # 4) + or (area({dot}) # 0) then Rt.stop("Messy"); end; + p := {a: -s, b:2}; + Out.int(p.a); (* the first *) + Out.ln; + (* and done: + a comment that moves + with its line *) +end; + +end Messy. diff --git a/test/pretty/Messy.jed b/test/pretty/Messy.jed new file mode 100644 index 0000000..7b38220 --- /dev/null +++ b/test/pretty/Messy.jed @@ -0,0 +1,57 @@ +(* A module laid out badly. *) + module Messy; +import Out,Rt; + +const +max* =10; + min=-1; + +type + Pair* = record + a*,b: I64; (* two numbers *) + end; + Shape = variant + circle(r: I64); + dot; + end; + + (* the bigger *) + proc max2*(a,b:I64):I64; +var m : I64; + begin +if a>b then m:=a; + elsif a=b then + m :=a ; + else + m:= b;end; + return m; + end; + +proc area(s: Shape): I64; +begin +match s of + | circle(r): return 3*r*r; +| dot: + return 0; + end; +end; + +proc main*; +var i,s:I64; p: Pair; +begin + s:=0; + for i:=-3 to max-1 do s:=s+i*2- -1;end; + repeat + s := s-1 ; + until s<0; + if (s # -1) or (max2(3,4) # 4) + or (area({dot}) # 0) then Rt.stop("Messy"); end; + p := {a: -s, b:2}; + Out.int(p.a); (* the first *) + Out.ln; + (* and done: + a comment that moves + with its line *) +end; + +end Messy. diff --git a/tools/Doc.jed b/tools/Doc.jed index 979a81a..419f878 100644 --- a/tools/Doc.jed +++ b/tools/Doc.jed @@ -10,144 +10,33 @@ module to end, with no ... left out, to dir/Name.jed, and prints the names, one a line. *) module Doc; -import Out, Sys, Rt, Str, Buf, Heap; +import Out, Rt, Str, Buf, Heap, Scan, Files; -type - Kind = (ident, other, eof); - var - src: []U8; (* the text being read *) - pos: I64; - kind: Kind; (* the current token *) - tokStart, tokEnd: I64; + sc: Scan.Scanner; (* the text being read, at the current symbol *) + src: []U8; docStart, docEnd: I64; (* the comment just before it, or -1 *) -(* Argument i, a C string, as a slice. *) -proc arg(i: I64): []U8; -var s: ^U8; n: I64; -begin - s := ARGV()[i]; - n := 0; - while s[n] # 0 do INC(n); end; - return s[0..n]; -end; - -proc readFile(path: []U8; b: ^Buf.Buf): BOOL; -var fd, n: I64; chunk: [4096]U8; +(* On to the next symbol that isn't a comment, keeping where the last + comment that starts a line was: one after code on its line belongs + to that code. *) +proc next; +var newLine: BOOL; begin - fd := Sys.openRead(path); - if fd < 0 then return false; end; + docStart := -1; + newLine := false; repeat - n := Sys.read(fd, chunk); - if n > 0 then Buf.str(b, chunk[0..n]); end; - until n <= 0; - Sys.close(fd); - return n = 0; -end; - -proc writeFile(path, data: []U8): BOOL; -var fd, n, at: I64; -begin - fd := Sys.create(path); - if fd < 0 then return false; end; - at := 0; - while at < LEN(data) do - n := Sys.write(fd, data[at..LEN(data)]); - if n <= 0 then Sys.close(fd); return false; end; - at := at + n; - end; - Sys.close(fd); - return true; -end; - -proc isSpace(c: U8): BOOL; -begin - return (c = ' ') or (c = 9) or (c = 10) or (c = 13); -end; - -proc isWord(c: U8): BOOL; -begin - return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') - or (c >= '0') and (c <= '9') or (c = '_'); -end; - -(* Past a string or character literal that starts at pos. *) -proc skipLiteral; -var q: U8; -begin - q := src[pos]; - INC(pos); - while (pos < LEN(src)) and (src[pos] # q) do - if src[pos] = '\\' then INC(pos); end; - INC(pos); - end; - INC(pos); -end; - -(* Past the comment at pos. *) -proc skipComment; -var depth: I64; -begin - depth := 0; - repeat - if (src[pos] = '(') and (pos + 1 < LEN(src)) and (src[pos + 1] = '*') then - INC(depth); INC(pos, 2); - elsif (src[pos] = '*') and (pos + 1 < LEN(src)) and (src[pos + 1] = ')') then - DEC(depth); INC(pos, 2); - else - INC(pos); + Scan.next(ADR(sc)); + newLine := newLine or sc.lineBreak; + if (sc.kind = Scan.comment) and newLine then + docStart := sc.start; docEnd := sc.stop; end; - until (depth = 0) or (pos >= LEN(src)); -end; - -proc atComment(p: I64): BOOL; -begin - return (p + 1 < LEN(src)) and (src[p] = '(') and (src[p + 1] = '*'); + until sc.kind # Scan.comment; end; -(* Past spaces and comments, keeping where the last comment that starts - a line was: one after code on its line belongs to that code. *) -proc skipSpace; -var start: I64; newLine: BOOL; -begin - docStart := -1; - newLine := pos = 0; - while pos < LEN(src) do - if isSpace(src[pos]) then - if src[pos] = 10 then newLine := true; end; - INC(pos); - elsif atComment(pos) then - start := pos; - skipComment; - if newLine then docStart := start; docEnd := pos; end; - else - break; - end; - end; -end; - -proc next; -begin - skipSpace; - tokStart := pos; - if pos >= LEN(src) then - kind := eof; - elsif isWord(src[pos]) then - while (pos < LEN(src)) and isWord(src[pos]) do INC(pos); end; - kind := ident; - elsif (src[pos] = '"') or (src[pos] = '\'') then - skipLiteral; - kind := other; - else - INC(pos); - kind := other; - end; - tokEnd := pos; -end; - proc text: []U8; begin - return src[tokStart..tokEnd]; + return Scan.text(ADR(sc)); end; proc is(s: []U8): BOOL; @@ -168,27 +57,25 @@ var depth: I64; begin depth := 0; - while kind # eof do + while sc.kind # Scan.eof do if is("(") or is("[") or is("{") or is("record") or is("variant") then INC(depth); elsif is(")") or is("]") or is("}") or is("end") then DEC(depth); - elsif is(";") and (depth <= 0) then return tokEnd; + elsif is(";") and (depth <= 0) then return sc.stop; end; next; end; - return pos; + return sc.pos; end; (* stop, or the end of a comment that follows it on its line. *) proc trailing(stop: I64): I64; -var save: I64; +var t: Scan.Scanner; begin while (stop < LEN(src)) and ((src[stop] = ' ') or (src[stop] = 9)) do INC(stop); end; - if not atComment(stop) then return stop; end; - save := pos; - pos := stop; - skipComment; - stop := pos; - pos := save; + t := sc; + t.pos := stop; + Scan.next(ADR(t)); + if (t.kind = Scan.comment) and (t.start = stop) then return t.stop; end; return stop; end; @@ -225,8 +112,8 @@ if start < 0 then return; end; i := start + 2; j := stop - 2; - while (i < j) and isSpace(src[i]) do INC(i); end; - while (j > i) and isSpace(src[j - 1]) do DEC(j); end; + while (i < j) and Scan.isSpace(src[i]) do INC(i); end; + while (j > i) and Scan.isSpace(src[j - 1]) do DEC(j); end; atLine := true; while i < j do if atLine then Out.str(" "); atLine := false; end; @@ -266,7 +153,7 @@ begin depth := 0; sawBegin := false; - while kind # eof do + while sc.kind # Scan.eof do if is("begin") then if depth = 0 then sawBegin := true; end; INC(depth); @@ -276,7 +163,7 @@ DEC(depth); if (depth = 0) and sawBegin then next; - if kind = ident then next; end; + if sc.kind = Scan.word then next; end; return; end; end; @@ -287,7 +174,7 @@ proc procedure; var start, ds, de, stop: I64; exp: BOOL; begin - start := tokStart; ds := docStart; de := docEnd; + start := sc.start; ds := docStart; de := docEnd; exp := name(); stop := toSemicolon(); next; @@ -303,9 +190,9 @@ begin word := text(); next; - while (kind = ident) and not reserved() do - start := tokStart; ds := docStart; de := docEnd; - pos := tokStart; (* name reads the name again *) + while (sc.kind = Scan.word) and not reserved() do + start := sc.start; ds := docStart; de := docEnd; + sc.pos := sc.start; (* name reads the name again *) exp := name(); stop := toSemicolon(); if exp then @@ -321,7 +208,7 @@ proc external; var start, ds, de, stop: I64; exp: BOOL; begin - start := tokStart; ds := docStart; de := docEnd; + start := sc.start; ds := docStart; de := docEnd; next; exp := name(); stop := toSemicolon(); @@ -333,18 +220,18 @@ var b: Buf.Buf; start, ds, de: I64; begin Buf.init(ADR(b), Heap.heap); - if not readFile(path, ADR(b)) then Rt.stop("Doc: can't read the file"); end; + if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the file"); end; src := Buf.bytes(ADR(b)); - pos := 0; + Scan.init(ADR(sc), src); next; - while (kind # eof) and not is("module") do next; end; - if kind = eof then Rt.stop("Doc: no module"); end; - start := tokStart; + while (sc.kind # Scan.eof) and not is("module") do next; end; + if sc.kind = Scan.eof then Rt.stop("Doc: no module"); end; + start := sc.start; ds := docStart; de := docEnd; block(start, toSemicolon()); comment(ds, de); next; - while (kind # eof) and not is("begin") and not is("end") do + while (sc.kind # Scan.eof) and not is("begin") and not is("end") do if is("const") or is("type") or is("var") then section; elsif is("proc") then procedure; elsif is("extern") then external; @@ -360,8 +247,8 @@ begin i := 0; j := LEN(line); - while (i < j) and isSpace(line[i]) do INC(i); end; - while (j > i) and isSpace(line[j - 1]) do DEC(j); end; + while (i < j) and Scan.isSpace(line[i]) do INC(i); end; + while (j > i) and Scan.isSpace(line[j - 1]) do DEC(j); end; return line[i..j]; end; @@ -373,7 +260,7 @@ begin Buf.init(ADR(b), Heap.heap); Buf.init(ADR(out), Heap.heap); - if not readFile(path, ADR(b)) then Rt.stop("Doc: can't read the report"); end; + if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the report"); end; s := Buf.bytes(ADR(b)); inBlock := false; start := 0; @@ -386,12 +273,12 @@ if inBlock and whole and Str.hasPrefix(first, "module ") and Str.hasPrefix(last, "end ") then name := first[7..LEN(first)]; n := 0; - while (n < LEN(name)) and isWord(name[n]) do INC(n); end; + while (n < LEN(name)) and Scan.isWord(name[n]) do INC(n); end; name := name[0..n]; Buf.reset(ADR(out)); Buf.str(ADR(out), dir); Buf.str(ADR(out), "/"); Buf.str(ADR(out), name); Buf.str(ADR(out), ".jed"); - if not writeFile(Buf.bytes(ADR(out)), s[start..i]) then + if not Files.write(Buf.bytes(ADR(out)), s[start..i]) then Rt.stop("Doc: can't write an example"); end; Out.str(name); Out.ln; @@ -413,8 +300,8 @@ proc main*; begin - if (ARGC() = 4) and (arg(1) = "examples") then examples(arg(2), arg(3)); - elsif ARGC() = 2 then document(arg(1)); + if (ARGC() = 4) and (Files.arg(1) = "examples") then examples(Files.arg(2), Files.arg(3)); + elsif ARGC() = 2 then document(Files.arg(1)); else Rt.stop("usage: Doc Module.jed, or Doc examples report.md dir"); end; end; diff --git a/tools/Files.jed b/tools/Files.jed new file mode 100644 index 0000000..3306d5f --- /dev/null +++ b/tools/Files.jed @@ -0,0 +1,46 @@ +(* Files: what the tools need of the command line and of files: an + argument as a string, and a whole file read or written. *) +module Files; +import Sys, Buf; + +(* Argument i, a C string, as a slice. *) +proc arg*(i: I64): []U8; +var s: ^U8; n: I64; +begin + s := ARGV()[i]; + n := 0; + while s[n] # 0 do INC(n); end; + return s[0..n]; +end; + +(* Adds the file at path to b; false if it can't be read. *) +proc read*(path: []U8; b: ^Buf.Buf): BOOL; +var fd, n: I64; chunk: [4096]U8; +begin + fd := Sys.openRead(path); + if fd < 0 then return false; end; + repeat + n := Sys.read(fd, chunk); + if n > 0 then Buf.str(b, chunk[0..n]); end; + until n <= 0; + Sys.close(fd); + return n = 0; +end; + +(* Makes the file at path hold data; false if it can't be written. *) +proc write*(path, data: []U8): BOOL; +var fd, n, at: I64; +begin + fd := Sys.create(path); + if fd < 0 then return false; end; + at := 0; + while at < LEN(data) do + n := Sys.write(fd, data[at..LEN(data)]); + if n <= 0 then Sys.close(fd); return false; end; + at := at + n; + end; + Sys.close(fd); + return true; +end; + +end Files. diff --git a/tools/Pretty.jed b/tools/Pretty.jed new file mode 100644 index 0000000..fb8b343 --- /dev/null +++ b/tools/Pretty.jed @@ -0,0 +1,339 @@ +(* Pretty: jed source laid out the one way. + + Pretty Module.jed + prints the module, formatted. + + Pretty -w File.jed... + rewrites each file that isn't formatted already. + + Every line break and comment stays where it is. A line is indented + 4 spaces for each block it stands in: the statements of if, while, + for, repeat and begin, the fields of a record or variant, the + declarations of const, type and var. end, until, else, elsif and a + match's arms stand at the level of the statement that opened them; + module, import, proc, the sections and begin at the margin, with the + comment just before them. A line that goes on with the expression of + the line before keeps its indent, moved as far as the statement's + first line moved; so does the text of a comment. + + Within a line, a binary operator has one space on each side, a unary + minus none after it, and , and ; none before them and one after. A + comment after code keeps its column. Other spaces stay as written, + so that lined-up match arms stay lined up. No line ends in spaces. *) +module Pretty; +import Out, Rt, Buf, Heap, Scan, Files; + +const + width = 4; (* the spaces of a level *) + openers = "if while for match record variant begin repeat"; + declarations = "module import link extern proc const type var begin code"; + binaryWords = "div mod and or xor shl shr in"; + binarySymbols = "+ - * / = # < <= > >= :="; + +var + sc: Scan.Scanner; (* the source, at the symbol being written *) + src: []U8; + out: Buf.Buf; + lineAt: I64; (* where the line being written starts in out *) + lineDelta: I64; (* how far this line's indent moved *) + + (* the blocks open, each with the indent of the statement that + opened it *) + bases: [100]I64; + depth: I64; + brackets: I64; (* brackets open *) + inSection: BOOL; (* among the declarations of const, type or var *) + stmtIndent: I64; (* the indent of the current statement's first line *) + stmtDelta: I64; (* and how far that moved *) + + (* the last symbol that wasn't a comment, and the one before it *) + prev, prev2: Scan.Scanner; + prevBinary, prevUnary: BOOL; + afterComment: BOOL; (* the last symbol written was a comment *) + last: I64; (* where the last symbol written ends in src *) + +proc spaces(n: I64); +begin + while n > 0 do Buf.add(ADR(out), ' '); DEC(n); end; +end; + +(* Drops the spaces at the end of the line in out. *) +proc trim; +var s: []U8; +begin + s := Buf.bytes(ADR(out)); + while (out.len > lineAt) and ((s[out.len - 1] = ' ') or (s[out.len - 1] = '\t')) do + DEC(out.len); + end; +end; + +proc newLine; +begin + trim; + Buf.add(ADR(out), '\n'); + lineAt := out.len; +end; + +(* Where the line holding p starts in src. *) +proc lineStart(p: I64): I64; +begin + while (p > 0) and (src[p - 1] # '\n') do DEC(p); end; + return p; +end; + +(* The column src[p] is at, a tab going on to the next multiple of 8. *) +proc column(p: I64): I64; +var i, col: I64; +begin + col := 0; + for i := lineStart(p) to p - 1 do + if src[i] = '\t' then col := (col div 8 + 1) * 8; else INC(col); end; + end; + return col; +end; + +(* Whether s ends an operand, so that a - after it subtracts. *) +proc endsOperand(s: ^Scan.Scanner): BOOL; +begin + if s^.kind = Scan.word then return not Scan.reserved(Scan.text(s)); end; + return (s^.kind = Scan.number) or (s^.kind = Scan.literal) + or Scan.is(s, ")") or Scan.is(s, "]") or Scan.is(s, "}") or Scan.is(s, "^"); +end; + +(* The symbol after the current one that isn't a comment. *) +proc following: Scan.Scanner; +var s: Scan.Scanner; +begin + s := sc; + repeat Scan.next(ADR(s)); until s.kind # Scan.comment; + return s; +end; + +(* Whether the current symbol is a binary operator. A * after a name + and before ; , : = ) or a procedure's parameters exports the name. *) +proc binary: BOOL; +var n: Scan.Scanner; +begin + if sc.kind = Scan.word then return Scan.among(Scan.text(ADR(sc)), binaryWords); end; + if (sc.kind # Scan.symbol) or not Scan.among(Scan.text(ADR(sc)), binarySymbols) then + return false; + end; + if Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+") then return endsOperand(ADR(prev)); end; + if Scan.is(ADR(sc), "*") and (prev.kind = Scan.word) then + n := following(); + if Scan.among(Scan.text(ADR(n)), "; , : = )") then return false; end; + if Scan.is(ADR(n), "(") and Scan.is(ADR(prev2), "proc") then return false; end; + end; + return true; +end; + +(* Whether the current symbol, first on its line, goes on with the + expression of the line before. *) +proc continues: BOOL; +var t: []U8; +begin + if (brackets > 0) or prevBinary or Scan.is(ADR(prev), ",") then return true; end; + t := Scan.text(ADR(sc)); + if sc.kind = Scan.word then return Scan.among(t, binaryWords) or Scan.among(t, "then do of"); end; + return (sc.kind = Scan.symbol) and Scan.among(t, binarySymbols); +end; + +(* Whether s starts a declaration at the margin: proc( starts a + procedure type. *) +proc declaration(s: Scan.Scanner): BOOL; +begin + if (s.kind # Scan.word) or not Scan.among(Scan.text(ADR(s)), declarations) then return false; end; + if not Scan.is(ADR(s), "proc") then return true; end; + Scan.next(ADR(s)); + return not Scan.is(ADR(s), "("); +end; + +(* The indent of the block's own lines, or of its end. *) +proc inner: I64; +begin + if depth > 0 then return bases[depth - 1] + width; end; + if inSection then return width; end; + return 0; +end; + +proc outer: I64; +begin + if depth > 0 then return bases[depth - 1]; end; + return 0; +end; + +(* The indent of the line the current symbol starts, which was at old. *) +proc indent(old: I64): I64; +var n: Scan.Scanner; +begin + if continues() then + if old + stmtDelta < 0 then return 0; end; + return old + stmtDelta; + end; + if sc.kind = Scan.comment then + n := following(); + if n.lineBreak and declaration(n) then return 0; end; + return inner(); + end; + if declaration(sc) then + depth := 0; + inSection := Scan.among(Scan.text(ADR(sc)), "const type var"); + return 0; + end; + if Scan.among(Scan.text(ADR(sc)), "end until else elsif |") then + return outer(); + end; + return inner(); +end; + +(* Starts the line of the current symbol, at its indent. *) +proc startLine; +var old, new: I64; +begin + old := column(sc.start); + new := indent(old); + lineDelta := new - old; + if (sc.kind # Scan.comment) and not continues() then + stmtIndent := new; + stmtDelta := lineDelta; + end; + spaces(new); +end; + +(* The spaces between the last symbol written and the current one, on + the same line. *) +proc gap(binaryNow: BOOL); +var n: I64; +begin + if sc.kind = Scan.comment then + n := column(sc.start) + lineDelta - (out.len - lineAt); + if (n < 1) and (sc.start > last) then n := 1; end; + spaces(n); + elsif afterComment then + Buf.str(ADR(out), src[last..sc.start]); + elsif Scan.is(ADR(sc), ",") or Scan.is(ADR(sc), ";") then + elsif Scan.is(ADR(prev), ",") or Scan.is(ADR(prev), ";") or binaryNow or prevBinary then + if not prevUnary then spaces(1); end; + elsif not prevUnary then + Buf.str(ADR(out), src[last..sc.start]); + end; +end; + +(* The current symbol as written; each line of a comment after its + first is moved as far as the line the comment starts on. *) +proc write; +var i, k: I64; +begin + i := sc.start; + while i < sc.stop do + if src[i] = '\n' then + newLine; + k := i + 1; + while (k < sc.stop) and (src[k] = ' ') do INC(k); end; + if (k < sc.stop) and (src[k] # '\n') then spaces(k - (i + 1) + lineDelta); end; + i := k; + else + Buf.add(ADR(out), src[i]); + INC(i); + end; + end; +end; + +(* After a symbol that isn't a comment: the blocks and brackets it opens + or closes. *) +proc track(binaryNow: BOOL); +var t: []U8; +begin + t := Scan.text(ADR(sc)); + if sc.kind = Scan.word then + if Scan.among(t, openers) then + if depth = LEN(bases) then Rt.stop("Pretty: blocks nested too deep"); end; + bases[depth] := stmtIndent; + INC(depth); + elsif ((t = "end") or (t = "until")) and (depth > 0) then + DEC(depth); + end; + elsif sc.kind = Scan.symbol then + if Scan.among(t, "( [ {") then INC(brackets); + elsif Scan.among(t, ") ] }") and (brackets > 0) then DEC(brackets); + end; + end; + prevUnary := (Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+")) and not binaryNow; + prevBinary := binaryNow; + prev2 := prev; + prev := sc; +end; + +(* The line breaks in src[from..upto]. *) +proc lineBreaks(from, upto: I64); +var i: I64; +begin + for i := from to upto - 1 do + if src[i] = '\n' then newLine; end; + end; +end; + +(* src, formatted, into out. *) +proc format(text: []U8); +var b: BOOL; +begin + src := text; + Buf.reset(ADR(out)); + lineAt := 0; + depth := 0; + brackets := 0; + inSection := false; + stmtIndent := 0; + stmtDelta := 0; + Scan.init(ADR(sc), src); + prev := sc; + prev2 := sc; + prevBinary := false; + prevUnary := false; + afterComment := false; + last := 0; + Scan.next(ADR(sc)); + while sc.kind # Scan.eof do + b := (sc.kind # Scan.comment) and binary(); + if sc.lineBreak then + lineBreaks(last, sc.start); + startLine; + else + gap(b); + end; + write; + afterComment := sc.kind = Scan.comment; + if not afterComment then track(b); end; + last := sc.stop; + Scan.next(ADR(sc)); + end; + lineBreaks(last, LEN(src)); + trim; +end; + +proc main*; +var b: Buf.Buf; i: I64; path: []U8; +begin + Buf.init(ADR(b), Heap.heap); + Buf.init(ADR(out), Heap.heap); + if (ARGC() >= 3) and (Files.arg(1) = "-w") then + for i := 2 to ARGC() - 1 do + path := Files.arg(i); + Buf.reset(ADR(b)); + if not Files.read(path, ADR(b)) then Rt.stop("Pretty: can't read a file"); end; + format(Buf.bytes(ADR(b))); + if Buf.bytes(ADR(out)) # Buf.bytes(ADR(b)) then + if not Files.write(path, Buf.bytes(ADR(out))) then Rt.stop("Pretty: can't write a file"); end; + Out.str(path); Out.ln; + end; + end; + elsif ARGC() = 2 then + if not Files.read(Files.arg(1), ADR(b)) then Rt.stop("Pretty: can't read the file"); end; + format(Buf.bytes(ADR(b))); + Out.str(Buf.bytes(ADR(out))); + else + Rt.stop("usage: Pretty Module.jed, or Pretty -w File.jed..."); + end; +end; + +end Pretty. diff --git a/tools/Scan.jed b/tools/Scan.jed new file mode 100644 index 0000000..8d67ee0 --- /dev/null +++ b/tools/Scan.jed @@ -0,0 +1,171 @@ +(* Scan: the symbols of jed source, for the tools. Unlike the + compiler's scanner it keeps comments, as symbols of their own, and + says where each symbol is in the text and whether a line break comes + before it. It doesn't check what it reads: a malformed number is + read as far as it goes, and a string, character or comment left open + ends with its line or the text. *) +module Scan; + +type + Kind* = (word, number, literal, symbol, comment, eof); + + (* word is an identifier or a reserved word; literal a string or a + character; symbol an operator or delimiter. *) + Scanner* = record + src*: []U8; + pos*: I64; (* where the next symbol is looked for *) + kind*: Kind; (* the current symbol *) + start*, stop*: I64; (* its text: src[start..stop] *) + lineBreak*: BOOL; (* a line break comes before it, or it is the first *) + end; + +const + 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"; + +proc isSpace*(c: U8): BOOL; +begin + return (c = ' ') or (c = '\t') or (c = '\n') or (c = '\r'); +end; + +proc isWord*(c: U8): BOOL; +begin + return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') + or (c >= '0') and (c <= '9') or (c = '_'); +end; + +proc isDigit(c: U8): BOOL; +begin + return (c >= '0') and (c <= '9'); +end; + +(* Whether w is one of the words of list, which are separated by + single spaces. *) +proc among*(w, list: []U8): BOOL; +var i, j: I64; +begin + i := 0; + while i < LEN(list) do + j := i; + while (j < LEN(list)) and (list[j] # ' ') do INC(j); end; + if list[i..j] = w then return true; end; + i := j + 1; + end; + return false; +end; + +(* Whether w is one of the report's reserved words. *) +proc reserved*(w: []U8): BOOL; +begin + return among(w, words); +end; + +(* The scanner at the start of src; next gives the first symbol. *) +proc init*(s: ^Scanner; src: []U8); +begin + s^ := {src: src, kind: eof}; +end; + +(* Past the comment that starts at p, its nested comments with it. *) +proc pastComment(src: []U8; p: I64): I64; +var depth: I64; +begin + depth := 0; + repeat + if (src[p] = '(') and (p + 1 < LEN(src)) and (src[p + 1] = '*') then + INC(depth); INC(p, 2); + elsif (src[p] = '*') and (p + 1 < LEN(src)) and (src[p + 1] = ')') then + DEC(depth); INC(p, 2); + else + INC(p); + end; + until (depth = 0) or (p >= LEN(src)); + return p; +end; + +(* Past the number that starts at p: digits and letters, then a real's + point, digits and exponent, as in 0FFH and 2.0E-3. *) +proc pastNumber(src: []U8; p: I64): I64; +begin + while (p < LEN(src)) and isWord(src[p]) do INC(p); end; + if (p + 1 < LEN(src)) and (src[p] = '.') and isDigit(src[p + 1]) then + INC(p); + while (p < LEN(src)) and isWord(src[p]) do INC(p); end; + if (src[p - 1] = 'E') and (p < LEN(src)) and ((src[p] = '-') or (src[p] = '+')) then + INC(p); + while (p < LEN(src)) and isWord(src[p]) do INC(p); end; + end; + end; + return p; +end; + +(* Past the string or character that starts at p, or to its line's end. *) +proc pastLiteral(src: []U8; p: I64): I64; +var q: U8; +begin + q := src[p]; + INC(p); + while (p < LEN(src)) and (src[p] # q) and (src[p] # '\n') do + if (src[p] = '\\') and (p + 1 < LEN(src)) then INC(p); end; + INC(p); + end; + if (p < LEN(src)) and (src[p] = q) then INC(p); end; + return p; +end; + +(* Whether src[p..] starts with the symbol t. *) +proc at(src: []U8; p: I64; t: []U8): BOOL; +begin + return (p + LEN(t) <= LEN(src)) and (src[p..p + LEN(t)] = t); +end; + +(* On to the next symbol. *) +proc next*(s: ^Scanner); +var src: []U8; p: I64; c: U8; +begin + src := s^.src; + p := s^.pos; + s^.lineBreak := p = 0; + while (p < LEN(src)) and isSpace(src[p]) do + if src[p] = '\n' then s^.lineBreak := true; end; + INC(p); + end; + s^.start := p; + if p >= LEN(src) then + s^.kind := eof; + else + c := src[p]; + if at(src, p, "(*") then + s^.kind := comment; p := pastComment(src, p); + elsif isDigit(c) then + s^.kind := number; p := pastNumber(src, p); + elsif isWord(c) then + s^.kind := word; + while (p < LEN(src)) and isWord(src[p]) do INC(p); end; + elsif (c = '"') or (c = '\'') then + s^.kind := literal; p := pastLiteral(src, p); + else + s^.kind := symbol; + if at(src, p, "...") then INC(p, 3); + elsif at(src, p, ":=") or at(src, p, "<=") or at(src, p, ">=") or at(src, p, "..") then + INC(p, 2); + else + INC(p); + end; + end; + end; + s^.stop := p; + s^.pos := p; +end; + +proc text*(s: ^Scanner): []U8; +begin + return s^.src[s^.start..s^.stop]; +end; + +(* Whether the current symbol is t. *) +proc is*(s: ^Scanner; t: []U8): BOOL; +begin + return text(s) = t; +end; + +end Scan.