From c5489654648eb8e1337650810fc5add2a27039e4 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:23:02 +0100 Subject: [PATCH] Self step 1: Diag and Scan in raz, tested against the seed self/Diag.raz and self/Scan.raz, with Jump.raz (setjmp and longjmp in assembly, for the parser's recovery). make self runs each unit against the seed's on 428 files, the same output, messages and status; make self-bench: scan takes 83 ms against the seed's 75. self/README.md lists what the port found. CLAUDE.md says what the seed is. --- diff --git a/CLAUDE.md b/CLAUDE.md index 7bc0812..d45d05e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -129,6 +129,13 @@ a link in its `mods`. A test or example without `.expect` is only compiled (`examples/Window.raz` needs a display). +## The seed and self + +`src/`, the Free Pascal compiler, is the **seed**. `self/` is its port +to raz (`PLAN.md`, "Self"): one module to a seed unit, the same names. +Never edit the seed to suit the port; a difference found goes on the +plan, for the owner. + ## Readings of the report already taken These are how the compiler behaves; keep them unless the owner says diff --git a/Makefile b/Makefile index 52a3b2b..a0ade28 100644 --- a/Makefile +++ b/Makefile @@ -35,6 +35,13 @@ check: raz build/raz-lib.3 test/check.sh +# the raz compiler in raz, self/, tested against the seed's units +self: raz | build + self/check.sh + +self-bench: raz | build + self/bench.sh + # line numbers: gdb stops at a line and names it gdb: raz test/gdb.sh @@ -69,7 +76,7 @@ # formatted already fmt: raz | build ./raz -o build/Pretty tools/Pretty.raz - @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz; do \ + @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz self/*.raz self/test/*.raz; do \ build/Pretty $$f | cmp -s - $$f || { echo "not formatted: $$f"; fail=1; }; \ done; test $$fail = 0 @@ -149,4 +156,4 @@ site: raz python3 site/build.py -.PHONY: units tests check gdb bench kernels stress fmt loc man pdf dist site clean install uninstall +.PHONY: units tests self self-bench check gdb bench kernels stress fmt loc man pdf dist site clean install uninstall diff --git a/PLAN.md b/PLAN.md index 026f5b8..fb94ee4 100644 --- a/PLAN.md +++ b/PLAN.md @@ -24,7 +24,7 @@ Steps: -1. `diag` and `scan`: the trial. Measure `scan`'s speed against the +1. `diag` and `scan` (done): the trial. Measure `scan`'s speed against the seed's and list what `Sys` and the library lacked. Stop for review: if the cost is too high, mend the code generator first. 2. `chunk`, `sym`, `link`, `elf`, `x64`. diff --git a/self/Diag.raz b/self/Diag.raz new file mode 100644 index 0000000..fc1ab64 --- /dev/null +++ b/self/Diag.raz @@ -0,0 +1,410 @@ +(* Diag: messages. + + The one place the compiler's messages are made. A message is an + error or a warning at a position, which it shows as the file, line + and column, then the line of source with the position underlined; + notes, each at a position of its own, and help, a line of advice, + may follow it. Colour is used when standard error is a terminal and + NO_COLOR isn't set. Diag keeps every source file it is given, so + that a note can show a line of a module compiled earlier. + + Depends on: Sys, to write and to ask about the terminal; Buf and Fmt, + to build what it writes. + Leaves out: wording. The callers say what is wrong, with say; a + message is at most 255 characters, which every message so far keeps + well within. A message made by say is kept for good, since it is + made only where it is about to be shown. *) +module Diag; +import Sys, Rt, Heap, Mem, Buf, Fmt, Str; + +type + (* A stretch of a source file: bytes a up to but not including b. + a = b marks the place between two characters. *) + Pos* = record f*, a*, b*: INT; end; + + File = record + path: []U8; + buf: ^U8; + len: INT; + end; + +const + MaxErrors* = 20; + Bold = "\x1B[1m"; Red = "\x1B[1;31m"; Yellow = "\x1B[1;33m"; + Cyan = "\x1B[1;36m"; Green = "\x1B[1;32m"; Blue = "\x1B[1;34m"; + Plain = "\x1B[0m"; + (* A long line is shown cut to this many bytes around the place, its + cut ends marked ... *) + ShownBytes = 100; + +var + errors*, warnings*: INT; + werror*: BOOL; (* -Werror: a warning counts as an error *) + (* The construct being read uses a name already reported as not + declared: its errors follow from that one, and aren't shown. *) + quiet*: BOOL; + + files: ^File; (* numFiles of them, in room for cap *) + numFiles, cap: INT; + colour, colourKnown, cwdKnown: BOOL; + cwd: Buf.Buf; (* the working directory and a /, or empty if unknown *) + out: Buf.Buf; (* the message being made *) + lastError: Pos; (* where the last error was *) + shown: BOOL; (* whether it was shown: its notes and help are only then *) + +(* Exported variables can't be set from outside, so these do it. *) +proc setWerror*(yes: BOOL); +begin + werror := yes; +end; + +proc setQuiet*(yes: BOOL); +begin + quiet := yes; +end; + +(* Paths are shown from the working directory where they are under it, + so messages read the same wherever the compiler or its library is. *) +proc shownPath*(path: []U8): []U8; +var d: []U8; err: INT; c: []U8; +begin + if not cwdKnown then + d, err := Sys.workDir(); + if err = 0 then + Buf.str(ADR(cwd), d); + Buf.add(ADR(cwd), '/'); + end; + cwdKnown := true; + end; + c := Buf.bytes(ADR(cwd)); + if (LEN(c) > 0) and Str.hasPrefix(path, c) then return path[LEN(c)..LEN(path)]; end; + return path; +end; + +proc fatal*(msg: []U8); forward; + +(* Memory, or the end of the compile when there is none *) +proc grab(size: INT): ^U8; +var p: ^U8; +begin + p := Mem.alloc(Heap.heap, size, 8); + if p = nil then fatal("out of memory"); end; + return p; +end; + +(* Keeps buf, len bytes of a file, under a number, which it gives back; + buf stays as it is, and its path is copied. *) +proc addFile*(path: []U8; buf: ^U8; len: INT): INT; +var more: ^File; i: INT; p: []U8; ok: BOOL; +begin + if numFiles = cap then + more := ^File(grab((2 * cap + 8) * SIZE(File))); + for i := 0 to numFiles - 1 do more[i] := files[i]; end; + if files # nil then Mem.free(Heap.heap, ^U8(files)); end; + files := more; + cap := 2 * cap + 8; + end; + p, ok := Str.copy(Heap.heap, shownPath(path)); + if not ok then fatal("out of memory"); end; + files[numFiles] := {path: p, buf: buf, len: len}; + INC(numFiles); + return numFiles - 1; +end; + +proc pathOf*(f: INT): []U8; +begin + return files[f].path; +end; + +(* Writing *) + +(* Whether NO_COLOR is set. The library can't tell it set to nothing + from not set, so that counts as not set, as no-color.org has it. *) +proc noColour: BOOL; +begin + return LEN(Sys.env("NO_COLOR")) > 0; +end; + +proc put(s: []U8); +begin + Buf.str(ADR(out), s); +end; + +proc putc(c: U8); +begin + Buf.add(ADR(out), c); +end; + +proc putNum(n: INT); +begin + Fmt.write(ADR(out), "{}", [Fmt.int(n)]); +end; + +(* The text of a number *) +proc say*(f: []U8; args: []Fmt.Arg): []U8; +var b: ^Buf.Buf; +begin + b := ^Buf.Buf(grab(SIZE(Buf.Buf))); + Buf.init(b, Heap.heap); + Fmt.write(b, f, args); + return Buf.bytes(b); +end; + +(* c, when colour is on *) +proc paintOn(c: []U8); +begin + if not colourKnown then + colour := Sys.isTerminal(2) and not noColour(); + colourKnown := true; + end; + if colour then put(c); end; +end; + +(* s in colour c, when colour is on *) +proc paint(c, s: []U8); +begin + paintOn(c); + put(s); + paintOn(Plain); +end; + +(* What has been made, written to standard error *) +proc flush; +var s: []U8; n: INT; +begin + s := Buf.bytes(ADR(out)); + while LEN(s) > 0 do + n := Sys.write(Sys.stderr, s); + if n <= 0 then break; end; + s := s[n..LEN(s)]; + end; + Buf.reset(ADR(out)); +end; + +(* Positions *) + +(* The line of p, and the byte where it starts. Lines are counted from + the start of the file, which is slow only next to compiling it. *) +proc locate(p: Pos): (INT, INT); +var i, line, start: INT; buf: ^U8; +begin + buf := files[p.f].buf; + line := 1; + start := 0; + for i := 0 to p.a - 1 do + if buf[i] = 10 then INC(line); start := i + 1; end; + end; + return line, start; +end; + +proc lineOf*(p: Pos): INT; +var line: INT; +begin + line, _ := locate(p); + return line; +end; + +(* A byte that starts a character: every one but a UTF-8 continuation *) +proc starts(c: U8): BOOL; +begin + return (c & 0C0H) # 80H; +end; + +(* Characters from byte i to byte j of buf *) +proc chars(buf: ^U8; i, j: INT): INT; +var n: INT; +begin + n := 0; + while i < j do + if starts(buf[i]) then INC(n); end; + INC(i); + end; + return n; +end; + +(* "file:line:col: kind: msg", then the line with p underlined. A tab + before p is copied into the underline, so that the two line up + whatever the terminal makes of tabs. *) +proc show(p: Pos; kind, kindColour, msg: []U8); +var line, start, stop, lo, hi, i, n: INT; buf: ^U8; f: ^File; digits: []U8; +begin + if p.f >= numFiles then + (* about no place in a file, as for Rt, which the compiler + imports before it reads one *) + paint(Bold, "raz:"); + put(" "); + paintOn(kindColour); put(kind); put(":"); paintOn(Plain); + put(" "); + paint(Bold, msg); + putc('\n'); + flush; + return; + end; + line, start := locate(p); + f := ADR(files[p.f]); + buf := f^.buf; + paintOn(Bold); + put(f^.path); put(":"); putNum(line); put(":"); putNum(chars(buf, start, p.a) + 1); put(":"); + paintOn(Plain); + put(" "); + paintOn(kindColour); put(kind); put(":"); paintOn(Plain); + put(" "); + paint(Bold, msg); + putc('\n'); + stop := start; + while (stop < f^.len) and (buf[stop] # 10) do INC(stop); end; + lo := start; + hi := stop; + if hi - lo > ShownBytes then + if p.a - lo > ShownBytes div 2 then lo := p.a - ShownBytes div 2; end; + while not starts(buf[lo]) do INC(lo); end; + if hi - lo > ShownBytes then hi := lo + ShownBytes; end; + while (hi < stop) and not starts(buf[hi]) do INC(hi); end; + end; + paintOn(Blue); + digits := say("{}", [Fmt.int(line)]); + for i := LEN(digits) to 4 do put(" "); end; + put(digits); put(" |"); + paintOn(Plain); + put(" "); + if lo > start then put("..."); end; + put(buf[lo..hi]); + if hi < stop then put("..."); end; + putc('\n'); + paint(Blue, " |"); + put(" "); + if lo > start then put(" "); end; + for i := lo to p.a - 1 do + if buf[i] = '\t' then putc('\t'); elsif starts(buf[i]) then putc(' '); end; + end; + if p.b < hi then n := chars(buf, p.a, p.b); else n := chars(buf, p.a, hi); end; + if n < 1 then n := 1; end; + paintOn(kindColour); + for i := 1 to n do putc('^'); end; + paintOn(Plain); + putc('\n'); + flush; +end; + +(* From the start of p to the end of q *) +proc join*(p, q: Pos): Pos; +begin + p.b := q.b; + return p; +end; + +(* The text at p, at most the 255 bytes a message can hold *) +proc source*(p: Pos): []U8; +var n: INT; +begin + n := p.b - p.a; + if n > 255 then n := 255; end; + return files[p.f].buf[p.a..p.a + n]; +end; + +(* Messages *) + +(* Line line of the file at path, as written, to at most 255 bytes *) +proc lineText*(path: []U8; line: INT): []U8; +var i, k, n, j: INT; f: ^File; want: []U8; +begin + want := shownPath(path); + for i := 0 to numFiles - 1 do + f := ADR(files[i]); + if f^.path = want then + k := 0; + n := 1; + while (n < line) and (k < f^.len) do + if f^.buf[k] = 10 then INC(n); end; + INC(k); + end; + j := k; + while (j < f^.len) and (f^.buf[j] # 10) and (j - k < 255) do INC(j); end; + return f^.buf[k..j]; + end; + end; + return ""; +end; + +proc error*(p: Pos; msg: []U8); +begin + (* a second error at one place follows from the first: when a symbol + ends a construct with an error, the one around it may stop there too *) + shown := not quiet and not ((errors > 0) and (p.f = lastError.f) and (p.a = lastError.a)); + if not shown then return; end; + lastError := p; + show(p, "error", Red, msg); + INC(errors); + if errors >= MaxErrors then + put("raz: stopping after "); + putNum(MaxErrors); + put(" errors\n"); + flush; + Rt.exit(1); + end; +end; + +proc warning*(p: Pos; msg: []U8); +begin + if werror then + error(p, msg); + else + show(p, "warning", Yellow, msg); + shown := true; + INC(warnings); + end; +end; + +(* Notes and help follow an error or a warning, and are shown with it *) +proc note*(p: Pos; msg: []U8); +begin + if shown then show(p, "note", Cyan, msg); end; +end; + +proc help*(msg: []U8); +begin + if shown then + paint(Green, "help:"); + put(" "); + put(msg); + putc('\n'); + flush; + end; +end; + +(* An error with no place in the source, such as a file that can't be + read: it stops the compiler at once. *) +proc fatal*(msg: []U8); +begin + put("raz: "); + put(msg); + putc('\n'); + flush; + Rt.exit(1); +end; + +proc count(n: INT; what: []U8): []U8; +begin + if n = 1 then return say("1 {}", [Fmt.str(what)]); end; + return say("{} {}s", [Fmt.int(n), Fmt.str(what)]); +end; + +(* Says how many errors and warnings there were, and stops the compiler + if there were errors. *) +proc finish*; +begin + if (errors > 0) and (warnings > 0) then + put("raz: "); put(count(errors, "error")); put(", "); put(count(warnings, "warning")); putc('\n'); + elsif errors > 0 then + put("raz: "); put(count(errors, "error")); putc('\n'); + elsif warnings > 0 then + put("raz: "); put(count(warnings, "warning")); putc('\n'); + end; + flush; + if errors > 0 then Rt.exit(1); end; +end; + +begin + Buf.init(ADR(cwd), Heap.heap); + Buf.init(ADR(out), Heap.heap); +end Diag. diff --git a/self/Jump.raz b/self/Jump.raz new file mode 100644 index 0000000..d86a3c3 --- /dev/null +++ b/self/Jump.raz @@ -0,0 +1,55 @@ +(* Jump: setjmp and longjmp, for a compiler that goes on after an error. + The parser reads on from the statement or declaration after one it + found wrong; raz has no exceptions, so the scanner's Fail, which the + parser's errors end in, jumps back to where the parser saved its + place. Written in assembly, since no raz code can return twice. + + Depends on: nothing. + Leaves out: saving anything but what System V says a procedure must + keep (rbx, rbp, rsp, r12 to r15) and the place to go on at. A + variable changed between save and jump may be held in a register + that jump restores, so a variable that is read after the jump is + written before save, or lives in memory the compiler can't reach + (a field of a record by pointer, a module's variable). *) +module Jump; + +type + Env* = record + rbx, rbp, rsp, r12, r13, r14, r15, rip: INT; + end; + +(* Saves the place after the call in e, and returns 0. When jump(e) is + called later, from any procedure that save's caller is still under, + save returns again, with 1. *) +proc save*(e: ^Env): INT; +code + mov rax, [rsp]; + lea rcx, [rsp + 8]; + mov [rdi], rbx; + mov [rdi + 8], rbp; + mov [rdi + 16], rcx; + mov [rdi + 24], r12; + mov [rdi + 32], r13; + mov [rdi + 40], r14; + mov [rdi + 48], r15; + mov [rdi + 56], rax; + xor eax, eax; + ret; +end save; + +(* Goes back to the save that filled e, which returns 1. *) +proc jump*(e: ^Env); +code + mov rbx, [rdi]; + mov rbp, [rdi + 8]; + mov rsp, [rdi + 16]; + mov r12, [rdi + 24]; + mov r13, [rdi + 32]; + mov r14, [rdi + 40]; + mov r15, [rdi + 48]; + mov rcx, [rdi + 56]; + mov eax, 1; + db 0FFH, 0E1H; (* jmp rcx, which the assembler has no form for *) +end jump; + +end Jump. diff --git a/self/README.md b/self/README.md index 68fa4e9..01004df 100644 --- a/self/README.md +++ b/self/README.md @@ -6,3 +6,38 @@ One module to a seed unit, with the seed's name, written to the same rules: plain code, each module opening with what it is, what it depends on and what it leaves out. The seed is never edited from here. + + make self # each unit against the seed's, on the same files + make self-bench # the scanner's speed against the seed's + +`check.sh` builds a dumper for each side, `test/ScanDump.pas` over the +seed's units and `test/ScanDump.raz` over these, and has both read the +library, the examples, every test of the compiler and a file for each +message the scanner makes (`test/genlex.py`) and for hundreds of reals +that are hard to read exactly (`test/genreals.py`): the output, the +messages and the status must be the same. + +## What the port found + +Not the seed's to mend; for the owner to choose. + +- **Names.** An exported variable is read-only outside its module, so + what the parser sets in the seed's `diag` and `scan` (`quiet`, + `werror`, `recovery`, `skipping`) have setters. The `sbuf` array, + which can't be sliced outside, is `strBytes`. +- **Going on after an error.** raz has no `setjmp`: `Jump.raz` is the + two in assembly, which the parser's recovery needs. The assembler has + no `jmp reg`, so it is written `db 0FFH, 0E1H;`. +- **`NO_COLOR` set to nothing.** `Sys.env` gives "" for a variable that + is unset and for one that is empty, so the port reads the second as + the first, as no-color.org has it. The seed reads it as set. +- **Strings are slices.** A message is a `[]U8` made by `Diag.say`, + which keeps what it makes: messages are made only to be shown. A name + from `nameOf` stays valid, since names are kept in chunks that are + never moved; the seed's was a copy. +- **No bit cast.** A real's bits and back go through a pointer. +- **Speed.** On the 348,025 lines of `test/genbench.py`, 7.6 MB, the + seed's scanner takes 75 ms and this one 83 ms. Two things cost the + rest: a slice comparison, `a[0..n] = b[0..n]`, is 25% slower than the + same bytes in a loop, and a procedure call to ask whether a byte is + in a name (a table now). The compiler could mend the first. diff --git a/self/Scan.raz b/self/Scan.raz new file mode 100644 index 0000000..3d921b6 --- /dev/null +++ b/self/Scan.raz @@ -0,0 +1,998 @@ +(* Scan: the scanner. + + Reads a raz source file and hands the parser one symbol at a time: + reserved words, identifiers, numbers, characters, strings and + operators. Identifiers are interned, so that the rest of the compiler + compares names as small integers. The scanner also says where the + current symbol is, for messages. + + Depends on: Sys, to read files; Diag, to report errors; Jump, to go + on after the parser's errors. + Leaves out: recovery from errors in the text itself, such as a string + not closed: the first such error stops the compiler. The parser goes + on after its own errors, through recovery below. *) +module Scan; +import Sys, Heap, Mem, Fmt, Diag, Jump; + +type + NamePtr = ^U8; + + Sym* = (sNull, sIdent, sInt, sReal, sChar, sString, + sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq, + sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis, + sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sAmp, sTilde, sBar, + sBlank, + (* the reserved words, in the order of words below *) + sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse, + sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink, + sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord, + sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sType, sUntil, sVar, + sVariant, sVolatile, sWhile, sXor, + sEof); + + (* Where the scanner is. Importing a module compiles it in the middle + of another, so the parser saves this and restores it afterwards. *) + State* = record + buf: ^U8; + len, pos, line, lineStart: INT; + tokPos, tokLine, tokLineStart: INT; + prevEnd: INT; (* where the symbol before this one ends *) + tok: Sym; + ival: I64; + rval: F64; + id: INT; + f: INT; (* the file, as Diag knows it *) + end; + +const + MaxIdent* = 63; + MaxStr* = 65536; + NumWords = 42; + NumOps = 28; + words: [NumWords][]U8 = [ + "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"]; + (* sPlus to sBlank *) + ops: [NumOps][]U8 = [ + "+", "-", "*", "/", "=", "#", "<", "<=", ">", ">=", + ":=", ":", ";", ",", ".", "..", "...", + "(", ")", "[", "]", "{", "}", "^", "&", "~", "|", "_"]; + PoolChunk = 65536; + +var + tok*: Sym; (* the current symbol *) + ival*: I64; (* sInt, sChar: its value *) + rval*: F64; (* sReal: its value *) + id*: INT; (* sIdent: its name *) + slen*: INT; (* sString: how many bytes *) + sbuf: [MaxStr + 1]U8; (* sString: its bytes, then a zero *) + + (* Where the parser goes on after an error: the innermost statement or + declaration being read. nil stops the compiler at the first error. *) + recovery: ^Jump.Env; + (* The parser is skipping what it has read once already, after an + error, so slips in it aren't reported again. *) + skipping: BOOL; + + (* Whether a byte may be in a name: a letter, a digit or _. A table, + since the loop that reads a name asks it of every byte. *) + nameChar: [256]BOOL; + + cur: State; (* buf .. f; tok, ival, rval and id live above *) + + (* The name table: every distinct identifier once, found through an + open-addressed hash table. A name's bytes are in a chunk of memory + that is never moved, so that nameOf can hand out a slice of them. *) + chunk: ^U8; (* where names are put; chunkLeft bytes are left *) + chunkLeft: INT; + namePtr: ^NamePtr; + nameLen, nameHash: ^INT; + numNames, nameCap: INT; + table: ^INT; (* name + 1, or 0 for an empty slot *) + tableMask: INT; + +(* Exported variables can't be set from outside, so these do it. *) +proc setRecovery*(r: ^Jump.Env); +begin + recovery := r; +end; + +proc setSkipping*(yes: BOOL); +begin + skipping := yes; +end; + +(* The bytes of the string just read, without the zero after them *) +proc strBytes*: []U8; +begin + return sbuf[0..slen]; +end; + +(* Memory, or the end of the compile when there is none *) +proc grab(size: INT): ^U8; +var p: ^U8; +begin + p := Mem.alloc(Heap.heap, size, 8); + if p = nil then Diag.fatal("out of memory"); end; + return p; +end; + +(* n zeroed words *) +proc words64(n: INT): ^INT; +var p: ^INT; i: INT; +begin + p := ^INT(grab(n * SIZE(INT))); + for i := 0 to n - 1 do p[i] := 0; end; + return p; +end; + +(* Names *) + +proc hash(p: ^U8; n: INT): INT; +var h: U32; i: INT; +begin + h := 2166136261; + for i := 0 to n - 1 do h := (h xor U32(p[i])) * 16777619; end; + return INT(h & 7FFFFFFFH); +end; + +(* A table twice the size, and room for twice the names *) +proc grow; +var i, n, j: INT; ptrs: ^NamePtr; lens, hashes: ^INT; +begin + Mem.free(Heap.heap, ^U8(table)); + tableMask := tableMask * 2 + 1; + table := words64(tableMask + 1); + for n := 0 to numNames - 1 do + i := nameHash[n] & tableMask; + while table[i] # 0 do i := (i + 1) & tableMask; end; + table[i] := n + 1; + end; + j := nameCap * 2; + ptrs := ^NamePtr(grab(j * SIZE(NamePtr))); + lens := ^INT(grab(j * SIZE(INT))); + hashes := ^INT(grab(j * SIZE(INT))); + for n := 0 to numNames - 1 do + ptrs[n] := namePtr[n]; + lens[n] := nameLen[n]; + hashes[n] := nameHash[n]; + end; + Mem.free(Heap.heap, ^U8(namePtr)); + Mem.free(Heap.heap, ^U8(nameLen)); + Mem.free(Heap.heap, ^U8(nameHash)); + namePtr := ptrs; + nameLen := lens; + nameHash := hashes; + nameCap := j; +end; + +(* Whether the n bytes at p and at q are the same *) +proc same(p, q: ^U8; n: INT): BOOL; +var i: INT; +begin + for i := 0 to n - 1 do + if p[i] # q[i] then return false; end; + end; + return true; +end; + +(* The number of the name of the n bytes at p; a new name gets the next *) +proc intern*(p: ^U8; n: INT): INT; +var h, i, k: INT; +begin + h := hash(p, n); + i := h & tableMask; + while table[i] # 0 do + k := table[i] - 1; + if (nameHash[k] = h) and (nameLen[k] = n) and same(namePtr[k], p, n) then + return k; + end; + i := (i + 1) & tableMask; + end; + if n > chunkLeft then + chunk := grab(PoolChunk); + chunkLeft := PoolChunk; + end; + COPY(chunk[0..n], p[0..n]); + k := numNames; + namePtr[k] := chunk; + nameLen[k] := n; + nameHash[k] := h; + chunk := chunk + n; + chunkLeft := chunkLeft - n; + INC(numNames); + table[i] := k + 1; + if numNames * 2 > tableMask then grow; end; + return k; +end; + +(* The name n, which stays as it is *) +proc nameOf*(n: INT): []U8; +begin + return namePtr[n][0..nameLen[n]]; +end; + +(* Errors *) + +(* The current symbol *) +proc tokPos*: Diag.Pos; +begin + return {f: cur.f, a: cur.tokPos, b: cur.pos}; +end; + +(* The place just after the symbol before the current one, where a + missing symbol belongs *) +proc afterPrev*: Diag.Pos; +begin + return {f: cur.f, a: cur.prevEnd, b: cur.prevEnd}; +end; + +(* Where to say a symbol is missing: at the current symbol, unless it + starts a later line than the symbol before it, which is more likely + where the missing one belongs *) +proc missingPos*: Diag.Pos; +var i: INT; p: Diag.Pos; +begin + p := tokPos(); + for i := cur.prevEnd to cur.tokPos - 1 do + if cur.buf[i] = '\n' then p := afterPrev(); end; + end; + return p; +end; + +(* From the start of p to the end of the symbol before the current one: + the whole of a construct that has just been read *) +proc spanFrom*(p: Diag.Pos): Diag.Pos; +begin + p.b := cur.prevEnd; + return p; +end; + +proc curLine*: INT; +begin + return cur.tokLine; +end; + +(* The line and column of byte a of the file, at or before the current + symbol: counted back from the symbol's line, so that it costs only + the distance. A column counts characters, as Diag's do. *) +proc lineCol*(a: INT): (INT, INT); +var i, line, start, col: INT; +begin + line := cur.tokLine; + start := cur.tokLineStart; + while a < start do + DEC(line); + DEC(start); + while (start > 0) and (cur.buf[start - 1] # '\n') do DEC(start); end; + end; + col := 1; + for i := start to a - 1 do + if (cur.buf[i] & 0C0H) # 80H then INC(col); end; + end; + return line, col; +end; + +proc curCol*: INT; +var col: INT; +begin + _, col := lineCol(cur.tokPos); + return col; +end; + +(* After an error in the parser's construct, reported with its notes + and help: the parser goes on from the recovery point. *) +proc fail*; +begin + if recovery = nil then Diag.finish; end; + Jump.jump(recovery); +end; + +(* An error at p: reported, then the parser goes on from its recovery + point. *) +proc markAt*(p: Diag.Pos; msg: []U8); +begin + Diag.error(p, msg); + fail; +end; + +proc mark*(msg: []U8); +begin + markAt(tokPos(), msg); +end; + +(* markAt, with a line of help after the message. *) +proc markHelp*(p: Diag.Pos; msg, hint: []U8); +begin + Diag.error(p, msg); + Diag.help(hint); + fail; +end; + +(* An error in the text at bytes a to b of the file being read, which + stops the compiler: past it, the symbols can't be trusted. *) +proc markBytes(a, b: INT; msg: []U8); +begin + Diag.setQuiet(false); + Diag.error({f: cur.f, a: a, b: b}, msg); + Diag.finish; +end; + +proc lexError(msg: []U8); +begin + markBytes(cur.tokPos, cur.pos, msg); +end; + +(* The n characters at the scanner are how another language writes t: + an error, but reading goes on as if t were written. *) +proc slip(n: INT; t: Sym; msg: []U8); +begin + if not skipping then Diag.error({f: cur.f, a: cur.pos, b: cur.pos + n}, msg); end; + INC(cur.pos, n); + tok := t; +end; + +(* How an operator or reserved word is written, quoted, for messages. *) +proc symText*(s: Sym): []U8; +begin + if (s >= sPlus) and (s <= sBlank) then + return Diag.say("\"{}\"", [Fmt.str(ops[INT(s) - INT(sPlus)])]); + end; + return Diag.say("\"{}\"", [Fmt.str(words[INT(s) - INT(sAnd)])]); +end; + +(* The current symbol, for "expected ..., found ...": a name as it is, + a literal by its kind, an operator or reserved word quoted. *) +proc found*: []U8; +begin + match tok of + | sIdent: return nameOf(id); + | sInt: return "a number"; + | sReal: return "a number"; + | sChar: return "a character"; + | sString: return "a string"; + | sEof: return "the end of the file"; + | else: return symText(tok); + end; +end; + +(* The current symbol is the first on its line: at the top level of a + module, by the usual layout, so where reading can start again. *) +proc atLineStart*: BOOL; +begin + return cur.tokPos = cur.tokLineStart; +end; + +(* The column the current symbol's line is indented to *) +proc indent*: INT; +var i: INT; +begin + i := cur.tokLineStart; + while (cur.buf[i] = ' ') or (cur.buf[i] = '\t') do INC(i); end; + return i - cur.tokLineStart + 1; +end; + +(* Files *) + +(* Name n is a reserved word *) +proc reserved*(n: INT): BOOL; +begin + return n < NumWords; +end; + +(* Reads the file at path to scan it; "" if it can, else why not *) +proc open*(path: []U8): []U8; +var fd, n, got, r, err: INT; info: Sys.Info; +begin + info, err := Sys.info(path); + if err = -2 then return "there is no such file"; end; + if err = -13 then return "permission denied"; end; + if err < 0 then return "it can't be opened"; end; + if not info.file then return "it isn't a file"; end; + fd := Sys.openRead(path); + if fd = -2 then return "there is no such file"; end; + if fd = -13 then return "permission denied"; end; + if fd < 0 then return "it can't be opened"; end; + n := INT(info.size); + cur.buf := grab(n + 1); + got := 0; + while got < n do + r := Sys.read(fd, cur.buf[got..n]); + if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end; + got := got + r; + end; + Sys.close(fd); + cur.buf[n] := 0; (* the sentinel that ends every scan *) + cur.len := n; + cur.pos := 0; + cur.line := 1; + cur.lineStart := 0; + cur.tokPos := 0; + cur.tokLine := 1; + cur.tokLineStart := 0; + cur.f := Diag.addFile(path, cur.buf, n); + return ""; +end; + +proc saveScan*(var st: State); +begin + st := cur; + st.tok := tok; + st.ival := ival; + st.rval := rval; + st.id := id; +end; + +proc restoreScan*(st: State); +begin + cur := st; + tok := st.tok; + ival := st.ival; + rval := st.rval; + id := st.id; +end; + +(* UTF-8 *) + +(* Decodes the character at buf[pos], which is not ASCII, checking that + it is well formed; returns its code point and moves pos past it. *) +proc utf8(var pos: INT): INT; +var b0, b1, n, i, cp: INT; lo, hi: INT; +begin + b0 := INT(cur.buf[pos]); + lo := 80H; + hi := 0BFH; + n := 0; + cp := 0; + match b0 of + | 0C2H..0DFH: n := 1; cp := b0 & 1FH; + | 0E0H: n := 2; lo := 0A0H; + | 0E1H..0ECH, 0EEH, 0EFH: n := 2; cp := b0 & 0FH; + | 0EDH: n := 2; cp := 0DH; hi := 9FH; (* no surrogates *) + | 0F0H: n := 3; lo := 90H; + | 0F1H..0F3H: n := 3; cp := b0 & 7; + | 0F4H: n := 3; cp := 4; hi := 8FH; (* up to 10FFFFH *) + | else: + cur.tokPos := pos; + lexError("invalid UTF-8"); + end; + for i := 1 to n do + b1 := INT(cur.buf[pos + i]); + if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then + cur.tokPos := pos; + lexError("bad UTF-8"); + end; + cp := cp shl 6 | (b1 & 3FH); + lo := 80H; + hi := 0BFH; + end; + pos := pos + n + 1; + return cp; +end; + +proc put(b: INT); +begin + if slen >= MaxStr then + lexError(Diag.say("a string holds at most {} bytes", [Fmt.int(MaxStr)])); + end; + sbuf[slen] := U8(b); + INC(slen); +end; + +proc putUtf8(cp: INT); +begin + if cp < 80H then + put(cp); + elsif cp < 800H then + put(0C0H | cp shr 6); put(80H | cp & 3FH); + elsif cp < 10000H then + put(0E0H | cp shr 12); put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH); + else + put(0F0H | cp shr 18); put(80H | cp shr 12 & 3FH); + put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH); + end; +end; + +proc isDigit(c: U8): BOOL; +begin + return (c >= '0') and (c <= '9'); +end; + +proc isLetter(c: U8): BOOL; +begin + return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') or (c = '_'); +end; + +proc hexVal(c: U8): INT; +begin + if isDigit(c) then return INT(c) - '0'; + elsif (c >= 'A') and (c <= 'F') then return INT(c) - 'A' + 10; + elsif (c >= 'a') and (c <= 'f') then return INT(c) - 'a' + 10; + end; + return -1; +end; + +(* The text of the file from byte a up to but not including b *) +proc text(a, b: INT): []U8; +begin + return Diag.source({f: cur.f, a: a, b: b}); +end; + +(* One character of a character or string literal, at buf[pos]: its code + point, or for \xHH, minus one minus the byte. *) +proc litChar(inString: BOOL): INT; +var c: U8; v, d, n, esc, digits: INT; +begin + c := cur.buf[cur.pos]; + esc := cur.pos; + v := 0; + if c = '\\' then + INC(cur.pos); + c := cur.buf[cur.pos]; + INC(cur.pos); + match c of + | 'n': v := 10; + | 't': v := 9; + | 'r': v := 13; + | '0': v := 0; + | '\\', '\'', '"': v := INT(c); + | 'x': + if not inString then markBytes(esc, cur.pos, "\\x is only for strings"); end; + d := hexVal(cur.buf[cur.pos]); + n := hexVal(cur.buf[cur.pos + 1]); + if (d < 0) or (n < 0) then markBytes(esc, cur.pos + 2, "\\x needs two hex digits"); end; + INC(cur.pos, 2); + v := -1 - (d * 16 + n); + | 'u': + if cur.buf[cur.pos] # '{' then markBytes(esc, cur.pos, "expected \"{\" after \\u"); end; + INC(cur.pos); + digits := cur.pos; + v := 0; + n := 0; + while hexVal(cur.buf[cur.pos]) >= 0 do + v := v * 16 + hexVal(cur.buf[cur.pos]); + INC(n); + INC(cur.pos); + if n > 6 then markBytes(esc, cur.pos, "a code point has at most 6 hex digits"); end; + end; + if (n = 0) or (cur.buf[cur.pos] # '}') then + markBytes(esc, cur.pos, "expected hex digits and \"}\" after \\u{"); + end; + INC(cur.pos); + if (v > 10FFFFH) or (v >= 0D800H) and (v <= 0DFFFH) then + markBytes(esc, cur.pos, Diag.say("{} isn't a code point", [Fmt.str(text(digits, cur.pos - 1))])); + end; + | else: + markBytes(esc, cur.pos, Diag.say("unknown escape \\{}", [Fmt.char(c)])); + end; + elsif c >= 80H then + v := utf8(cur.pos); + elsif (c < ' ') or (c = 127) then + if inString then lexError("string not closed"); else lexError("character not closed"); end; + else + v := INT(c); + INC(cur.pos); + end; + return v; +end; + +(* Symbols *) + +proc comment; +var depth, open: INT; c: U8; +begin + depth := 1; + open := cur.pos; + INC(cur.pos, 2); + repeat + c := cur.buf[cur.pos]; + if c = 0 then + if cur.pos >= cur.len then markBytes(open, open + 2, "comment not closed"); end; + INC(cur.pos); + elsif (c = '(') and (cur.buf[cur.pos + 1] = '*') then + INC(depth); + INC(cur.pos, 2); + elsif (c = '*') and (cur.buf[cur.pos + 1] = ')') then + DEC(depth); + INC(cur.pos, 2); + elsif c = '\n' then + INC(cur.pos); + INC(cur.line); + cur.lineStart := cur.pos; + elsif c >= 80H then + _ := utf8(cur.pos); + else + INC(cur.pos); + end; + until depth = 0; +end; + +(* Reading a decimal real exactly: the F64 nearest to digits times 10 to + an exponent, ties to the even one, which a library's reader doesn't + promise. The number is a fraction of two big integers, num / den, + scaled by 2^e until its whole part has 53 or 54 bits; that part and + the remainder give the bits and the rounding. *) +type + Big = record + n: INT; (* words in use; 0 is zero *) + w: [96]U32; (* least significant first *) + end; +(* 96 words, 3072 bits, are plenty: a string holds at most 255 + digits, so readReal's den is at most 10^(330 + 255), about 2^1944, + and num below 10^310; the shift that follows makes the larger one at + most 54 bits longer than den, about 2000 bits in all. *) + +(* a := a * m + add *) +proc bigMul(var a: Big; m, add: U32); +var i: INT; c: U64; +begin + c := U64(add); + for i := 0 to a.n - 1 do + c := U64(a.w[i]) * U64(m) + c; + a.w[i] := U32(c); + c := c shr 32; + end; + if c # 0 then + a.w[a.n] := U32(c); + INC(a.n); + end; +end; + +proc bigShl(var a: Big; k: INT); +var i, ws, bits: INT; +begin + if a.n = 0 then return; end; + ws := k div 32; + bits := k mod 32; + a.w[a.n + ws] := 0; + for i := a.n - 1 to 0 by -1 do + if bits > 0 then a.w[i + ws + 1] := a.w[i + ws + 1] | (a.w[i] shr (32 - bits)); end; + a.w[i + ws] := a.w[i] shl bits; + end; + for i := 0 to ws - 1 do a.w[i] := 0; end; + INC(a.n, ws + 1); + while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end; +end; + +proc bigShr1(var a: Big); +var i: INT; +begin + for i := 0 to a.n - 1 do + a.w[i] := a.w[i] shr 1; + if i + 1 < a.n then a.w[i] := a.w[i] | (a.w[i + 1] shl 31); end; + end; + while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end; +end; + +(* -1, 0 or 1 as a is below, equal to or above b *) +proc bigCmp(a, b: Big): INT; +var i: INT; +begin + if a.n # b.n then + if a.n > b.n then return 1; end; + return -1; + end; + for i := a.n - 1 to 0 by -1 do + if a.w[i] # b.w[i] then + if a.w[i] > b.w[i] then return 1; end; + return -1; + end; + end; + return 0; +end; + +(* a := a - b, b not above a *) +proc bigSub(var a: Big; b: Big); +var i: INT; d: I64; +begin + d := 0; + for i := 0 to a.n - 1 do + d := d + I64(a.w[i]); + if i < b.n then d := d - I64(b.w[i]); end; + a.w[i] := U32(d); + if d < 0 then d := -1; else d := 0; end; (* a borrow *) + end; + while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end; +end; + +proc bigBits(a: Big): INT; +var t: U32; bits: INT; +begin + if a.n = 0 then return 0; end; + bits := (a.n - 1) * 32; + t := a.w[a.n - 1]; + while t # 0 do + INC(bits); + t := t shr 1; + end; + return bits; +end; + +(* s is digits, a point, digits, and maybe E, a sign and digits. False if + the value is past the largest F64; one below the smallest is 0. *) +proc readReal(s: []U8): (F64, BOOL); +var + num, den, d: Big; i, digits, e, ex: INT; neg, half, sticky: BOOL; + q, b: U64; x: F64; bits: ^F64; +begin + num.n := 0; + den.n := 1; + den.w[0] := 1; + digits := 0; + e := 0; + i := 0; + while (i < LEN(s)) and (s[i] # 'E') do + if s[i] = '.' then + e := 1; + else + bigMul(num, 10, U32(INT(s[i]) - '0')); + if num.n > 0 then INC(digits); end; (* counted from the first that isn't 0 *) + if e > 0 then INC(e); end; + end; + INC(i); + end; + if e > 0 then e := 1 - e; end; (* minus the digits after the point *) + ex := 0; + neg := false; + if i < LEN(s) then + INC(i); + neg := s[i] = '-'; + if (s[i] = '+') or (s[i] = '-') then INC(i); end; + while i < LEN(s) do + if ex < 100000 then ex := ex * 10 + INT(s[i]) - '0'; end; + INC(i); + end; + end; + if neg then ex := -ex; end; + INC(e, ex); + x := 0.0; + if num.n = 0 then return x, true; end; + if digits + e > 310 then return x, false; end; (* 10^310 is past every F64 *) + if digits + e < -330 then return x, true; end; (* and 10^-330 below half the least *) + for i := 1 to e do bigMul(num, 10, 0); end; + for i := 1 to -e do bigMul(den, 10, 0); end; + (* num / den 2^-e from 2^52 to 2^54, but not past the least exponent *) + e := bigBits(num) - bigBits(den) - 53; + if e < -1074 then e := -1074; end; + if e < 0 then bigShl(num, -e); else bigShl(den, e); end; + (* q, its whole part, by long division; num is left the remainder *) + d := den; + bigShl(d, 53); + q := 0; + for i := 53 to 0 by -1 do + if bigCmp(num, d) >= 0 then + bigSub(num, d); + q := q | (U64(1) shl i); + end; + bigShr1(d); + end; + if q >= U64(1) shl 53 then (* a bit too many: it rounds *) + half := (q & 1) # 0; + sticky := num.n > 0; + q := q shr 1; + INC(e); + else (* the remainder against half of den *) + bigShl(num, 1); + i := bigCmp(num, den); + half := i >= 0; + sticky := i > 0; + end; + if half and (sticky or ((q & 1) # 0)) then + INC(q); + if q = U64(1) shl 53 then + q := q shr 1; + INC(e); + end; + end; + if e > 971 then return x, false; end; + if q >= U64(1) shl 52 then + b := U64(e + 1075) shl 52 | (q & (U64(1) shl 52 - 1)); + else + b := q; (* below the least normal, e is -1074 *) + end; + bits := ^F64(ADR(b)); + return bits^, true; +end; + +proc number; +var start, i, d: INT; allDec, ok: BOOL; v: U64; +begin + start := cur.pos; + allDec := true; + while isDigit(cur.buf[cur.pos]) or (cur.buf[cur.pos] >= 'A') and (cur.buf[cur.pos] <= 'F') do + if cur.buf[cur.pos] > '9' then allDec := false; end; + INC(cur.pos); + end; + if cur.buf[cur.pos] = 'H' then + v := 0; + for i := start to cur.pos - 1 do + if v shr 60 # 0 then lexError(Diag.say("{} is too big for U64", [Fmt.str(text(start, cur.pos))])); end; + v := v * 16 + U64(hexVal(cur.buf[i])); + end; + INC(cur.pos); + tok := sInt; + ival := I64(v); (* 16 digits are the bits of a 64-bit word *) + elsif (cur.buf[cur.pos] = '.') and isDigit(cur.buf[cur.pos + 1]) then + if not allDec then lexError("a decimal number has only the digits 0 to 9"); end; + INC(cur.pos); + while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end; + if cur.buf[cur.pos] = 'E' then + INC(cur.pos); + if (cur.buf[cur.pos] = '+') or (cur.buf[cur.pos] = '-') then INC(cur.pos); end; + if not isDigit(cur.buf[cur.pos]) then lexError("expected a digit in the exponent"); end; + while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end; + end; + if cur.pos - start > 255 then lexError("a number has at most 255 characters"); end; + rval, ok := readReal(cur.buf[start..cur.pos]); + if not ok then lexError(Diag.say("{} is out of the range of F64", [Fmt.str(text(start, cur.pos))])); end; + tok := sReal; + else + if not allDec then lexError("a hex number ends with H"); end; + v := 0; + for i := start to cur.pos - 1 do + d := INT(cur.buf[i]) - '0'; + if v > (U64(9223372036854775807) - U64(d)) div 10 then + lexError(Diag.say("{} is too big for I64", [Fmt.str(text(start, cur.pos))])); + end; + v := v * 10 + U64(d); + end; + tok := sInt; + ival := I64(v); + end; + if nameChar[cur.buf[cur.pos]] then + lexError("a name can't start with a digit"); + end; +end; + +(* Reads the next symbol *) +proc next*; +var c: U8; start, h, v, i: INT; +begin + cur.prevEnd := cur.pos; + repeat + c := cur.buf[cur.pos]; + while (c = ' ') or (c = '\t') or (c = '\r') or (c = '\n') do + if c = '\n' then + INC(cur.line); + cur.lineStart := cur.pos + 1; + end; + INC(cur.pos); + c := cur.buf[cur.pos]; + end; + if (c = '(') and (cur.buf[cur.pos + 1] = '*') then + comment; + c := ' '; + end; + until c # ' '; + cur.tokPos := cur.pos; + cur.tokLine := cur.line; + cur.tokLineStart := cur.lineStart; + match c of + | 'A'..'Z', 'a'..'z', '_': + start := cur.pos; + repeat INC(cur.pos); until not nameChar[cur.buf[cur.pos]]; + if cur.pos - start > MaxIdent then + lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)])); + end; + h := intern(cur.buf + start, cur.pos - start); + if (cur.pos - start = 1) and (c = '_') then + tok := sBlank; + elsif h < NumWords then + tok := Sym(INT(sAnd) + h); + else + tok := sIdent; + id := h; + end; + | '0'..'9': number; + | '\'': + INC(cur.pos); + if cur.buf[cur.pos] = '\'' then lexError("empty character"); end; + v := litChar(false); + if cur.buf[cur.pos] # '\'' then + (* 'ab': several characters, as some languages write a string *) + i := cur.pos; + while (cur.buf[i] # '\'') and (cur.buf[i] # '\n') and (cur.buf[i] # 0) do INC(i); end; + if cur.buf[i] = '\'' then + markBytes(cur.tokPos, i + 1, + Diag.say("a character is one character: the string is \"{}\"", [Fmt.str(text(cur.tokPos + 1, i))])); + else + lexError("character not closed"); + end; + end; + INC(cur.pos); + tok := sChar; + ival := I64(v); + | '"': + INC(cur.pos); + slen := 0; + while cur.buf[cur.pos] # '"' do + v := litChar(true); + if v < 0 then put(-1 - v); else putUtf8(v); end; + end; + INC(cur.pos); + sbuf[slen] := 0; + tok := sString; + | '+': INC(cur.pos); tok := sPlus; + | '-': INC(cur.pos); tok := sMinus; + | '*': INC(cur.pos); tok := sTimes; + | '/': INC(cur.pos); tok := sSlash; + | '=': + if cur.buf[cur.pos + 1] = '=' then + slip(2, sEql, "comparing is written =, not =="); + else + INC(cur.pos); + tok := sEql; + end; + | '&': + if cur.buf[cur.pos + 1] = '&' then + slip(2, sAnd, "\"and\" is written and, not &&"); + else + INC(cur.pos); + tok := sAmp; + end; + | '#': INC(cur.pos); tok := sNeq; + | '<': + INC(cur.pos); + if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sLeq; else tok := sLss; end; + | '>': + INC(cur.pos); + if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sGeq; else tok := sGtr; end; + | ':': + INC(cur.pos); + if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sBecomes; else tok := sColon; end; + | ';': INC(cur.pos); tok := sSemicolon; + | ',': INC(cur.pos); tok := sComma; + | '.': + INC(cur.pos); + if cur.buf[cur.pos] = '.' then + INC(cur.pos); + if cur.buf[cur.pos] = '.' then INC(cur.pos); tok := sEllipsis; else tok := sUpto; end; + else + tok := sPeriod; + end; + | '(': INC(cur.pos); tok := sLparen; + | ')': INC(cur.pos); tok := sRparen; + | '[': INC(cur.pos); tok := sLbrak; + | ']': INC(cur.pos); tok := sRbrak; + | '{': INC(cur.pos); tok := sLbrace; + | '}': INC(cur.pos); tok := sRbrace; + | '^': INC(cur.pos); tok := sArrow; + | '|': + if cur.buf[cur.pos + 1] = '|' then + slip(2, sOr, "\"or\" is written or, not ||"); + else + INC(cur.pos); + tok := sBar; + end; + | '~': INC(cur.pos); tok := sTilde; + | '!': + if cur.buf[cur.pos + 1] = '=' then + slip(2, sNeq, "\"not equal\" is written #, not !="); + else + slip(1, sNot, "\"not\" is written not, not !"); + end; + | 0: + if cur.pos < cur.len then markBytes(cur.pos, cur.pos + 1, "NUL byte in the text"); end; + tok := sEof; + | else: + if c >= 80H then lexError("only ASCII outside strings, characters and comments"); end; + markBytes(cur.pos, cur.pos + 1, Diag.say("unexpected character \"{}\"", [Fmt.char(c)])); + end; +end; + +var i: INT; + +begin + for i := 0 to 255 do nameChar[i] := isLetter(U8(i)) or isDigit(U8(i)); end; + chunkLeft := 0; + nameCap := 1 shl 12; + namePtr := ^NamePtr(grab(nameCap * SIZE(NamePtr))); + nameLen := ^INT(grab(nameCap * SIZE(INT))); + nameHash := ^INT(grab(nameCap * SIZE(INT))); + tableMask := 2 * nameCap - 1; + table := words64(tableMask + 1); + for i := 0 to NumWords - 1 do _ := intern(ADR(words[i][0]), LEN(words[i])); end; +end Scan. diff --git a/self/bench.sh b/self/bench.sh new file mode 100755 index 0000000..fd7131a --- /dev/null +++ b/self/bench.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# The scanner's speed against the seed's, on the compiler's own +# benchmark program: the best of seven runs of each. Run from the +# repository root, after self/check.sh has built the tests. +set -e +b=build/self +python3 test/genbench.py 12000 >$b/Bench.raz +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/scanbench.seed self/test/ScanBench.pas >/dev/null +./raz -Werror -I self -o $b/scanbench.self self/test/ScanBench.raz +echo "$(wc -l <$b/Bench.raz) lines" +for t in seed self; do + best=0 + for i in 1 2 3 4 5 6 7; do + s=$(date +%s%N); $b/scanbench.$t $b/Bench.raz >/dev/null; e=$(date +%s%N) + d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi + done + echo "$t: $best ms" +done diff --git a/self/check.sh b/self/check.sh new file mode 100755 index 0000000..7f94c79 --- /dev/null +++ b/self/check.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Tests self/'s units against the seed's: each dumper reads the same +# files and must give the same standard output, standard error and +# status. Run from the repository root, after `make raz`; the seed's +# side is built by fpc from src/. +set -e +b=build/self +mkdir -p $b +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/scandump.seed self/test/ScanDump.pas >/dev/null +./raz -Werror -I self -o $b/scandump.self self/test/ScanDump.raz +python3 self/test/genreals.py > $b/reals.raz +# one small file for each message the scanner makes, and the places +# diag shows them in: a tab, a long line, characters before the place +mkdir -p $b/lex +python3 self/test/genlex.py $b/lex +n=0; bad=0 +for f in $b/lex/*.raz lib/*.raz examples/*.raz tools/*.raz self/*.raz self/test/*.raz test/run/*.raz test/err/*.raz \ + conform/*/*.raz $b/reals.raz; do + [ -f "$f" ] || continue + s1=0; s2=0 + $b/scandump.seed $f >$b/seed.out 2>$b/seed.err || s1=$? + $b/scandump.self $f >$b/self.out 2>$b/self.err || s2=$? + n=$((n + 1)) + if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then + echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1)) + fi +done +echo "$n files, $bad differ" +test $bad = 0 + +# Jump: a parser's way of going on after an error +./raz -Werror -I self -o $b/recover self/test/Recover.raz +printf 'a bad b bad bad c\nd bad\n' >$b/rec.raz +r=$($b/recover $b/rec.raz 2>/dev/null) || test $? = 1 +test "$r" = "8 names, 4 jumps, 4 errors" && echo "recover ok" diff --git a/self/test/Recover.raz b/self/test/Recover.raz new file mode 100644 index 0000000..a2c9756 --- /dev/null +++ b/self/test/Recover.raz @@ -0,0 +1,36 @@ +(* Tests Jump through Scan.fail: a driver reads a file's symbols and + reports each name `bad` as an error, which jumps back to where it + saved its place and goes on, as the parser does after an error. The + count lives in a module variable, which a jump leaves as it was. *) +module Recover; +import Out, Files, Diag, Scan, Jump; + +var + env: Jump.Env; + jumps, names: INT; + +proc deep(n: INT); +begin + if n > 0 then deep(n - 1); else Scan.mark("a bad name"); end; +end; + +proc main*; +begin + if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; + Scan.setRecovery(ADR(env)); + if Jump.save(ADR(env)) # 0 then INC(jumps); end; + while Scan.tok # Scan.sEof do + Scan.next; + if Scan.tok = Scan.sIdent then + INC(names); + if Scan.nameOf(Scan.id) = "bad" then deep(5); end; + end; + end; + Out.int(names); Out.str(" names, "); Out.int(jumps); Out.str(" jumps, "); + Out.int(Diag.errors); Out.str(" errors\n"); + Scan.setRecovery(nil); + Scan.mark("last"); + Out.str("not reached\n"); +end; + +end Recover. diff --git a/self/test/ScanBench.pas b/self/test/ScanBench.pas new file mode 100644 index 0000000..861f7a0 --- /dev/null +++ b/self/test/ScanBench.pas @@ -0,0 +1,12 @@ +{ Counts the symbols of a file and nothing else, for timing scan.pas + against self/Scan.raz (ScanBench.raz). } +program scanbench; +{$mode objfpc}{$H-} +uses diag, scan; +var n: longint; +begin + if Open(ParamStr(1)) <> '' then Fatal('no file'); + n := 0; + repeat Next; inc(n) until tok = sEof; + writeln(n, ' symbols'); +end. diff --git a/self/test/ScanBench.raz b/self/test/ScanBench.raz new file mode 100644 index 0000000..a49e516 --- /dev/null +++ b/self/test/ScanBench.raz @@ -0,0 +1,15 @@ +(* Counts the symbols of a file and nothing else, for timing Scan.raz + against the seed's scan.pas (ScanBench.pas). *) +module ScanBench; +import Out, Files, Diag, Scan; + +proc main*; +var n: INT; +begin + if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; + n := 0; + repeat Scan.next; INC(n); until Scan.tok = Scan.sEof; + Out.int(n); Out.str(" symbols\n"); +end; + +end ScanBench. diff --git a/self/test/ScanDump.pas b/self/test/ScanDump.pas new file mode 100644 index 0000000..b184002 --- /dev/null +++ b/self/test/ScanDump.pas @@ -0,0 +1,21 @@ +{ Prints the symbols of a file, one per line: the seed's side of a test + of self/Scan.raz, which prints the same. A real is shown by its bits, + so that no formatting library decides what is the same. } +program scandump; +{$mode objfpc}{$H-} +uses diag, scan; +var i: longint; bits: int64; +begin + if Open(ParamStr(1)) <> '' then Fatal('no file'); + repeat + Next; + write(LineOf(TokPos), ':', TokPos.a, ':', TokPos.b, ' ', CurLine, ':', CurCol, ' ', ord(tok)); + case tok of + sIdent: write(' ', NameOf(id), ' ', id); + sInt, sChar: write(' ', ival); + sReal: begin Move(rval, bits, 8); write(' ', HexStr(bits, 16)) end; + sString: begin write(' "'); for i := 0 to slen - 1 do write(sbuf[i], ','); write('"') end; + end; + writeln; + until tok = sEof; +end. diff --git a/self/test/ScanDump.raz b/self/test/ScanDump.raz new file mode 100644 index 0000000..dbf9075 --- /dev/null +++ b/self/test/ScanDump.raz @@ -0,0 +1,35 @@ +(* Prints the symbols of a file, one per line: self/Scan.raz's side of a + test against the seed's, ScanDump.pas, which prints the same. *) +module ScanDump; +import Out, Fmt, Files, Diag, Scan; + +proc main*; +var p: Diag.Pos; bits: ^U64; i: INT; str: []U8; r: F64; +begin + if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; + repeat + Scan.next; + p := Scan.tokPos(); + Fmt.print("{}:{}:{} {}:{} {}", [Fmt.int(Diag.lineOf(p)), Fmt.int(p.a), Fmt.int(p.b), + Fmt.int(Scan.curLine()), Fmt.int(Scan.curCol()), Fmt.int(INT(Scan.tok))]); + match Scan.tok of + | sIdent: Fmt.print(" {} {}", [Fmt.str(Scan.nameOf(Scan.id)), Fmt.int(Scan.id)]); + | sInt: Fmt.print(" {}", [Fmt.int(Scan.ival)]); + | sChar: Fmt.print(" {}", [Fmt.int(Scan.ival)]); + | sReal: + r := Scan.rval; + bits := ^U64(ADR(r)); + Out.str(" "); + Out.hex(bits^, 16); + | sString: + Out.str(" \""); + str := Scan.strBytes(); + for i := 0 to LEN(str) - 1 do Fmt.print("{},", [Fmt.int(INT(str[i]))]); end; + Out.str("\""); + | else: + end; + Out.ln; + until Scan.tok = Scan.sEof; +end; + +end ScanDump. diff --git a/self/test/genlex.py b/self/test/genlex.py new file mode 100644 index 0000000..5aa49e6 --- /dev/null +++ b/self/test/genlex.py @@ -0,0 +1,29 @@ +# Writes into the directory given a file for each message the scanner +# makes, with the places diag shows them in: after a tab, in a long +# line, after characters of several bytes, in a CRLF file. +import sys +d = sys.argv[1] +cases = { + "slip1": "x == y;\n", "slip2": "a && b;\n", "slip3": "a || b;\n", "slip4": "a != b;\n", "slip5": "!a;\n", + "str": "x := \"abc\n", "chr": "x := 'a\n", "chr2": "x := 'ab';\n", "chr3": "x := '';\n", + "esc": "x := \"\\q\";\n", "esc2": "x := 'a\\x41';\n", "esc3": "x := \"\\x4\";\n", + "esc4": "x := \"\\u41\";\n", "esc5": "x := \"\\u{110000}\";\n", "esc6": "x := \"\\u{D800}\";\n", + "esc7": "x := \"\\u{1234567}\";\n", "esc8": "x := \"\\u{}\";\n", "esc9": "x := \"\\u{41\";\n", + "esc10": "x := \"\\u{1F600}\\u{e9}\\x00\\xff\\n\\t\\r\\0\\\\\\'\\\"\";\n", + "cmt": "x := 1; (* open (* nested *)\n", "nul": "x := 1;\0 y;\n", "hexbad": "x := 12AB;\n", + "hexbig": "x := 1FFFFFFFFFFFFFFFFH;\n", "hexok": "x := 0FFFFFFFFFFFFFFFFH; y := 7FFFFFFFFFFFFFFFH;\n", + "decbig": "x := 9223372036854775808;\n", "decmax": "x := 9223372036854775807;\n", + "realhex": "x := 1A.5;\n", "realexp": "x := 1.5E;\n", "realexp2": "x := 1.5E+;\n", "realbig": "x := 1.0E309;\n", + "realmax": "x := 1.7976931348623159E308;\n", "reallong": "x := " + "1" * 254 + ".5;\n", + "digname": "x := 12abc;\n", "uni": "x := \u00e9;\n", "badutf": b"x := \"a\xc3(\";\n", "badutf2": b"x := \"\xed\xa0\x80\";\n", + "badutf3": b"x := \"\xc0\x80\";\n", "badutf4": b"x := \"\xf5\x80\x80\x80\";\n", "badutf5": b"x := \"\xe2\x82\";\n", + "okutf": "x := \"h\u00e9llo \u20ac \U0001F600\"; y := '\u00e9'; (* \u00e9 *)\n", + "unexp": "x := @;\n", "long": "x := " + "a + " * 60 + "@;\n", "longmid": "x := " + "a + " * 40 + "@ " + "+ b" * 40 + ";\n", + "tab": "\t\tx := @;\n", "multi": "x := \"\u00e9\u00e9\u00e9\" + @;\n", "ident64": "x" * 64 + ";\n", "ident63": "x" * 63 + ";\n", + "bigstr": "x := \"" + "a" * 70000 + "\";\n", "empty": "", "nonl": "x := y", + "ops": "+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ & ~ | _ __ _a\n", + "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 Volatile\n", +} +for k, v in cases.items(): + open(f"{d}/{k}.raz", "wb").write(v.encode("utf-8", "surrogateescape") if isinstance(v, str) else v) +open(f"{d}/crlf.raz", "wb").write(b"x := 1;\r\ny := @;\r\n") diff --git a/self/test/genreals.py b/self/test/genreals.py new file mode 100644 index 0000000..3074392 --- /dev/null +++ b/self/test/genreals.py @@ -0,0 +1,19 @@ +# Prints a raz module of reals that are hard to read exactly: the +# extremes, halves between neighbours, and many random ones. +import random +random.seed(7) +v = ["0.0", "1.0", "0.1", "4.9E-324", "2.4703282292062327E-324", "2.4703282292062328E-324", + "2.2250738585072014E-308", "2.2250738585072011E-308", "1.7976931348623157E308", + "9007199254740993.0", "9007199254740992.5", "9007199254740993.5", "0.000001E+3", + "123456789012345678901234567890.0E-10", "1.0E-400", "0.5E1", "5.0E-1"] +for _ in range(3000): + d = random.randint(1, 10 ** random.randint(1, 30)) + e = random.randint(-320, 300) + s = str(d) + v.append(s[0] + "." + (s[1:] or "0") + "E" + ("%+d" % e if random.random() < .5 else str(e))) +for _ in range(500): + v.append("%d.%d" % (random.randint(0, 10 ** 6), random.randint(0, 10 ** 12))) +print("module Reals;\nvar x: F64;\nbegin") +for s in v: + print(" x := " + s + ";") +print("end Reals.")