raz / commit c5489654

commit
c5489654648eb8e1337650810fc5add2a27039e4
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
ac309c8c
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.

patch · log

16 files changed, +1735 -3

CLAUDE.md modified +7 -0

@@ -129,6 +129,13 @@
129129 a link in its `mods`. A test or example without `.expect` is only
130130 compiled (`examples/Window.raz` needs a display).
131131
132+## The seed and self
133+
134+`src/`, the Free Pascal compiler, is the **seed**. `self/` is its port
135+to raz (`PLAN.md`, "Self"): one module to a seed unit, the same names.
136+Never edit the seed to suit the port; a difference found goes on the
137+plan, for the owner.
138+
132139 ## Readings of the report already taken
133140
134141 These are how the compiler behaves; keep them unless the owner says

Makefile (history) modified +9 -2

@@ -35,6 +35,13 @@
3535 check: raz build/raz-lib.3
3636 test/check.sh
3737
38+# the raz compiler in raz, self/, tested against the seed's units
39+self: raz | build
40+ self/check.sh
41+
42+self-bench: raz | build
43+ self/bench.sh
44+
3845 # line numbers: gdb stops at a line and names it
3946 gdb: raz
4047 test/gdb.sh
@@ -69,7 +76,7 @@
6976 # formatted already
7077 fmt: raz | build
7178 ./raz -o build/Pretty tools/Pretty.raz
72- @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz; do \
79+ @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz self/*.raz self/test/*.raz; do \
7380 build/Pretty $$f | cmp -s - $$f || { echo "not formatted: $$f"; fail=1; }; \
7481 done; test $$fail = 0
7582
@@ -149,4 +156,4 @@
149156 site: raz
150157 python3 site/build.py
151158
152-.PHONY: units tests check gdb bench kernels stress fmt loc man pdf dist site clean install uninstall
159+.PHONY: units tests self self-bench check gdb bench kernels stress fmt loc man pdf dist site clean install uninstall

PLAN.md (history) modified +1 -1

@@ -24,7 +24,7 @@
2424
2525 Steps:
2626
27-1. `diag` and `scan`: the trial. Measure `scan`'s speed against the
27+1. `diag` and `scan` (done): the trial. Measure `scan`'s speed against the
2828 seed's and list what `Sys` and the library lacked. Stop for review:
2929 if the cost is too high, mend the code generator first.
3030 2. `chunk`, `sym`, `link`, `elf`, `x64`.

self/Diag.raz added +410 -0

@@ -0,0 +1,410 @@
1+(* Diag: messages.
2+
3+ The one place the compiler's messages are made. A message is an
4+ error or a warning at a position, which it shows as the file, line
5+ and column, then the line of source with the position underlined;
6+ notes, each at a position of its own, and help, a line of advice,
7+ may follow it. Colour is used when standard error is a terminal and
8+ NO_COLOR isn't set. Diag keeps every source file it is given, so
9+ that a note can show a line of a module compiled earlier.
10+
11+ Depends on: Sys, to write and to ask about the terminal; Buf and Fmt,
12+ to build what it writes.
13+ Leaves out: wording. The callers say what is wrong, with say; a
14+ message is at most 255 characters, which every message so far keeps
15+ well within. A message made by say is kept for good, since it is
16+ made only where it is about to be shown. *)
17+module Diag;
18+import Sys, Rt, Heap, Mem, Buf, Fmt, Str;
19+
20+type
21+ (* A stretch of a source file: bytes a up to but not including b.
22+ a = b marks the place between two characters. *)
23+ Pos* = record f*, a*, b*: INT; end;
24+
25+ File = record
26+ path: []U8;
27+ buf: ^U8;
28+ len: INT;
29+ end;
30+
31+const
32+ MaxErrors* = 20;
33+ Bold = "\x1B[1m"; Red = "\x1B[1;31m"; Yellow = "\x1B[1;33m";
34+ Cyan = "\x1B[1;36m"; Green = "\x1B[1;32m"; Blue = "\x1B[1;34m";
35+ Plain = "\x1B[0m";
36+ (* A long line is shown cut to this many bytes around the place, its
37+ cut ends marked ... *)
38+ ShownBytes = 100;
39+
40+var
41+ errors*, warnings*: INT;
42+ werror*: BOOL; (* -Werror: a warning counts as an error *)
43+ (* The construct being read uses a name already reported as not
44+ declared: its errors follow from that one, and aren't shown. *)
45+ quiet*: BOOL;
46+
47+ files: ^File; (* numFiles of them, in room for cap *)
48+ numFiles, cap: INT;
49+ colour, colourKnown, cwdKnown: BOOL;
50+ cwd: Buf.Buf; (* the working directory and a /, or empty if unknown *)
51+ out: Buf.Buf; (* the message being made *)
52+ lastError: Pos; (* where the last error was *)
53+ shown: BOOL; (* whether it was shown: its notes and help are only then *)
54+
55+(* Exported variables can't be set from outside, so these do it. *)
56+proc setWerror*(yes: BOOL);
57+begin
58+ werror := yes;
59+end;
60+
61+proc setQuiet*(yes: BOOL);
62+begin
63+ quiet := yes;
64+end;
65+
66+(* Paths are shown from the working directory where they are under it,
67+ so messages read the same wherever the compiler or its library is. *)
68+proc shownPath*(path: []U8): []U8;
69+var d: []U8; err: INT; c: []U8;
70+begin
71+ if not cwdKnown then
72+ d, err := Sys.workDir();
73+ if err = 0 then
74+ Buf.str(ADR(cwd), d);
75+ Buf.add(ADR(cwd), '/');
76+ end;
77+ cwdKnown := true;
78+ end;
79+ c := Buf.bytes(ADR(cwd));
80+ if (LEN(c) > 0) and Str.hasPrefix(path, c) then return path[LEN(c)..LEN(path)]; end;
81+ return path;
82+end;
83+
84+proc fatal*(msg: []U8); forward;
85+
86+(* Memory, or the end of the compile when there is none *)
87+proc grab(size: INT): ^U8;
88+var p: ^U8;
89+begin
90+ p := Mem.alloc(Heap.heap, size, 8);
91+ if p = nil then fatal("out of memory"); end;
92+ return p;
93+end;
94+
95+(* Keeps buf, len bytes of a file, under a number, which it gives back;
96+ buf stays as it is, and its path is copied. *)
97+proc addFile*(path: []U8; buf: ^U8; len: INT): INT;
98+var more: ^File; i: INT; p: []U8; ok: BOOL;
99+begin
100+ if numFiles = cap then
101+ more := ^File(grab((2 * cap + 8) * SIZE(File)));
102+ for i := 0 to numFiles - 1 do more[i] := files[i]; end;
103+ if files # nil then Mem.free(Heap.heap, ^U8(files)); end;
104+ files := more;
105+ cap := 2 * cap + 8;
106+ end;
107+ p, ok := Str.copy(Heap.heap, shownPath(path));
108+ if not ok then fatal("out of memory"); end;
109+ files[numFiles] := {path: p, buf: buf, len: len};
110+ INC(numFiles);
111+ return numFiles - 1;
112+end;
113+
114+proc pathOf*(f: INT): []U8;
115+begin
116+ return files[f].path;
117+end;
118+
119+(* Writing *)
120+
121+(* Whether NO_COLOR is set. The library can't tell it set to nothing
122+ from not set, so that counts as not set, as no-color.org has it. *)
123+proc noColour: BOOL;
124+begin
125+ return LEN(Sys.env("NO_COLOR")) > 0;
126+end;
127+
128+proc put(s: []U8);
129+begin
130+ Buf.str(ADR(out), s);
131+end;
132+
133+proc putc(c: U8);
134+begin
135+ Buf.add(ADR(out), c);
136+end;
137+
138+proc putNum(n: INT);
139+begin
140+ Fmt.write(ADR(out), "{}", [Fmt.int(n)]);
141+end;
142+
143+(* The text of a number *)
144+proc say*(f: []U8; args: []Fmt.Arg): []U8;
145+var b: ^Buf.Buf;
146+begin
147+ b := ^Buf.Buf(grab(SIZE(Buf.Buf)));
148+ Buf.init(b, Heap.heap);
149+ Fmt.write(b, f, args);
150+ return Buf.bytes(b);
151+end;
152+
153+(* c, when colour is on *)
154+proc paintOn(c: []U8);
155+begin
156+ if not colourKnown then
157+ colour := Sys.isTerminal(2) and not noColour();
158+ colourKnown := true;
159+ end;
160+ if colour then put(c); end;
161+end;
162+
163+(* s in colour c, when colour is on *)
164+proc paint(c, s: []U8);
165+begin
166+ paintOn(c);
167+ put(s);
168+ paintOn(Plain);
169+end;
170+
171+(* What has been made, written to standard error *)
172+proc flush;
173+var s: []U8; n: INT;
174+begin
175+ s := Buf.bytes(ADR(out));
176+ while LEN(s) > 0 do
177+ n := Sys.write(Sys.stderr, s);
178+ if n <= 0 then break; end;
179+ s := s[n..LEN(s)];
180+ end;
181+ Buf.reset(ADR(out));
182+end;
183+
184+(* Positions *)
185+
186+(* The line of p, and the byte where it starts. Lines are counted from
187+ the start of the file, which is slow only next to compiling it. *)
188+proc locate(p: Pos): (INT, INT);
189+var i, line, start: INT; buf: ^U8;
190+begin
191+ buf := files[p.f].buf;
192+ line := 1;
193+ start := 0;
194+ for i := 0 to p.a - 1 do
195+ if buf[i] = 10 then INC(line); start := i + 1; end;
196+ end;
197+ return line, start;
198+end;
199+
200+proc lineOf*(p: Pos): INT;
201+var line: INT;
202+begin
203+ line, _ := locate(p);
204+ return line;
205+end;
206+
207+(* A byte that starts a character: every one but a UTF-8 continuation *)
208+proc starts(c: U8): BOOL;
209+begin
210+ return (c & 0C0H) # 80H;
211+end;
212+
213+(* Characters from byte i to byte j of buf *)
214+proc chars(buf: ^U8; i, j: INT): INT;
215+var n: INT;
216+begin
217+ n := 0;
218+ while i < j do
219+ if starts(buf[i]) then INC(n); end;
220+ INC(i);
221+ end;
222+ return n;
223+end;
224+
225+(* "file:line:col: kind: msg", then the line with p underlined. A tab
226+ before p is copied into the underline, so that the two line up
227+ whatever the terminal makes of tabs. *)
228+proc show(p: Pos; kind, kindColour, msg: []U8);
229+var line, start, stop, lo, hi, i, n: INT; buf: ^U8; f: ^File; digits: []U8;
230+begin
231+ if p.f >= numFiles then
232+ (* about no place in a file, as for Rt, which the compiler
233+ imports before it reads one *)
234+ paint(Bold, "raz:");
235+ put(" ");
236+ paintOn(kindColour); put(kind); put(":"); paintOn(Plain);
237+ put(" ");
238+ paint(Bold, msg);
239+ putc('\n');
240+ flush;
241+ return;
242+ end;
243+ line, start := locate(p);
244+ f := ADR(files[p.f]);
245+ buf := f^.buf;
246+ paintOn(Bold);
247+ put(f^.path); put(":"); putNum(line); put(":"); putNum(chars(buf, start, p.a) + 1); put(":");
248+ paintOn(Plain);
249+ put(" ");
250+ paintOn(kindColour); put(kind); put(":"); paintOn(Plain);
251+ put(" ");
252+ paint(Bold, msg);
253+ putc('\n');
254+ stop := start;
255+ while (stop < f^.len) and (buf[stop] # 10) do INC(stop); end;
256+ lo := start;
257+ hi := stop;
258+ if hi - lo > ShownBytes then
259+ if p.a - lo > ShownBytes div 2 then lo := p.a - ShownBytes div 2; end;
260+ while not starts(buf[lo]) do INC(lo); end;
261+ if hi - lo > ShownBytes then hi := lo + ShownBytes; end;
262+ while (hi < stop) and not starts(buf[hi]) do INC(hi); end;
263+ end;
264+ paintOn(Blue);
265+ digits := say("{}", [Fmt.int(line)]);
266+ for i := LEN(digits) to 4 do put(" "); end;
267+ put(digits); put(" |");
268+ paintOn(Plain);
269+ put(" ");
270+ if lo > start then put("..."); end;
271+ put(buf[lo..hi]);
272+ if hi < stop then put("..."); end;
273+ putc('\n');
274+ paint(Blue, " |");
275+ put(" ");
276+ if lo > start then put(" "); end;
277+ for i := lo to p.a - 1 do
278+ if buf[i] = '\t' then putc('\t'); elsif starts(buf[i]) then putc(' '); end;
279+ end;
280+ if p.b < hi then n := chars(buf, p.a, p.b); else n := chars(buf, p.a, hi); end;
281+ if n < 1 then n := 1; end;
282+ paintOn(kindColour);
283+ for i := 1 to n do putc('^'); end;
284+ paintOn(Plain);
285+ putc('\n');
286+ flush;
287+end;
288+
289+(* From the start of p to the end of q *)
290+proc join*(p, q: Pos): Pos;
291+begin
292+ p.b := q.b;
293+ return p;
294+end;
295+
296+(* The text at p, at most the 255 bytes a message can hold *)
297+proc source*(p: Pos): []U8;
298+var n: INT;
299+begin
300+ n := p.b - p.a;
301+ if n > 255 then n := 255; end;
302+ return files[p.f].buf[p.a..p.a + n];
303+end;
304+
305+(* Messages *)
306+
307+(* Line line of the file at path, as written, to at most 255 bytes *)
308+proc lineText*(path: []U8; line: INT): []U8;
309+var i, k, n, j: INT; f: ^File; want: []U8;
310+begin
311+ want := shownPath(path);
312+ for i := 0 to numFiles - 1 do
313+ f := ADR(files[i]);
314+ if f^.path = want then
315+ k := 0;
316+ n := 1;
317+ while (n < line) and (k < f^.len) do
318+ if f^.buf[k] = 10 then INC(n); end;
319+ INC(k);
320+ end;
321+ j := k;
322+ while (j < f^.len) and (f^.buf[j] # 10) and (j - k < 255) do INC(j); end;
323+ return f^.buf[k..j];
324+ end;
325+ end;
326+ return "";
327+end;
328+
329+proc error*(p: Pos; msg: []U8);
330+begin
331+ (* a second error at one place follows from the first: when a symbol
332+ ends a construct with an error, the one around it may stop there too *)
333+ shown := not quiet and not ((errors > 0) and (p.f = lastError.f) and (p.a = lastError.a));
334+ if not shown then return; end;
335+ lastError := p;
336+ show(p, "error", Red, msg);
337+ INC(errors);
338+ if errors >= MaxErrors then
339+ put("raz: stopping after ");
340+ putNum(MaxErrors);
341+ put(" errors\n");
342+ flush;
343+ Rt.exit(1);
344+ end;
345+end;
346+
347+proc warning*(p: Pos; msg: []U8);
348+begin
349+ if werror then
350+ error(p, msg);
351+ else
352+ show(p, "warning", Yellow, msg);
353+ shown := true;
354+ INC(warnings);
355+ end;
356+end;
357+
358+(* Notes and help follow an error or a warning, and are shown with it *)
359+proc note*(p: Pos; msg: []U8);
360+begin
361+ if shown then show(p, "note", Cyan, msg); end;
362+end;
363+
364+proc help*(msg: []U8);
365+begin
366+ if shown then
367+ paint(Green, "help:");
368+ put(" ");
369+ put(msg);
370+ putc('\n');
371+ flush;
372+ end;
373+end;
374+
375+(* An error with no place in the source, such as a file that can't be
376+ read: it stops the compiler at once. *)
377+proc fatal*(msg: []U8);
378+begin
379+ put("raz: ");
380+ put(msg);
381+ putc('\n');
382+ flush;
383+ Rt.exit(1);
384+end;
385+
386+proc count(n: INT; what: []U8): []U8;
387+begin
388+ if n = 1 then return say("1 {}", [Fmt.str(what)]); end;
389+ return say("{} {}s", [Fmt.int(n), Fmt.str(what)]);
390+end;
391+
392+(* Says how many errors and warnings there were, and stops the compiler
393+ if there were errors. *)
394+proc finish*;
395+begin
396+ if (errors > 0) and (warnings > 0) then
397+ put("raz: "); put(count(errors, "error")); put(", "); put(count(warnings, "warning")); putc('\n');
398+ elsif errors > 0 then
399+ put("raz: "); put(count(errors, "error")); putc('\n');
400+ elsif warnings > 0 then
401+ put("raz: "); put(count(warnings, "warning")); putc('\n');
402+ end;
403+ flush;
404+ if errors > 0 then Rt.exit(1); end;
405+end;
406+
407+begin
408+ Buf.init(ADR(cwd), Heap.heap);
409+ Buf.init(ADR(out), Heap.heap);
410+end Diag.

self/Jump.raz added +55 -0

@@ -0,0 +1,55 @@
1+(* Jump: setjmp and longjmp, for a compiler that goes on after an error.
2+ The parser reads on from the statement or declaration after one it
3+ found wrong; raz has no exceptions, so the scanner's Fail, which the
4+ parser's errors end in, jumps back to where the parser saved its
5+ place. Written in assembly, since no raz code can return twice.
6+
7+ Depends on: nothing.
8+ Leaves out: saving anything but what System V says a procedure must
9+ keep (rbx, rbp, rsp, r12 to r15) and the place to go on at. A
10+ variable changed between save and jump may be held in a register
11+ that jump restores, so a variable that is read after the jump is
12+ written before save, or lives in memory the compiler can't reach
13+ (a field of a record by pointer, a module's variable). *)
14+module Jump;
15+
16+type
17+ Env* = record
18+ rbx, rbp, rsp, r12, r13, r14, r15, rip: INT;
19+ end;
20+
21+(* Saves the place after the call in e, and returns 0. When jump(e) is
22+ called later, from any procedure that save's caller is still under,
23+ save returns again, with 1. *)
24+proc save*(e: ^Env): INT;
25+code
26+ mov rax, [rsp];
27+ lea rcx, [rsp + 8];
28+ mov [rdi], rbx;
29+ mov [rdi + 8], rbp;
30+ mov [rdi + 16], rcx;
31+ mov [rdi + 24], r12;
32+ mov [rdi + 32], r13;
33+ mov [rdi + 40], r14;
34+ mov [rdi + 48], r15;
35+ mov [rdi + 56], rax;
36+ xor eax, eax;
37+ ret;
38+end save;
39+
40+(* Goes back to the save that filled e, which returns 1. *)
41+proc jump*(e: ^Env);
42+code
43+ mov rbx, [rdi];
44+ mov rbp, [rdi + 8];
45+ mov rsp, [rdi + 16];
46+ mov r12, [rdi + 24];
47+ mov r13, [rdi + 32];
48+ mov r14, [rdi + 40];
49+ mov r15, [rdi + 48];
50+ mov rcx, [rdi + 56];
51+ mov eax, 1;
52+ db 0FFH, 0E1H; (* jmp rcx, which the assembler has no form for *)
53+end jump;
54+
55+end Jump.

self/README.md modified +35 -0

@@ -6,3 +6,38 @@
66 One module to a seed unit, with the seed's name, written to the same
77 rules: plain code, each module opening with what it is, what it
88 depends on and what it leaves out. The seed is never edited from here.
9+
10+ make self # each unit against the seed's, on the same files
11+ make self-bench # the scanner's speed against the seed's
12+
13+`check.sh` builds a dumper for each side, `test/ScanDump.pas` over the
14+seed's units and `test/ScanDump.raz` over these, and has both read the
15+library, the examples, every test of the compiler and a file for each
16+message the scanner makes (`test/genlex.py`) and for hundreds of reals
17+that are hard to read exactly (`test/genreals.py`): the output, the
18+messages and the status must be the same.
19+
20+## What the port found
21+
22+Not the seed's to mend; for the owner to choose.
23+
24+- **Names.** An exported variable is read-only outside its module, so
25+ what the parser sets in the seed's `diag` and `scan` (`quiet`,
26+ `werror`, `recovery`, `skipping`) have setters. The `sbuf` array,
27+ which can't be sliced outside, is `strBytes`.
28+- **Going on after an error.** raz has no `setjmp`: `Jump.raz` is the
29+ two in assembly, which the parser's recovery needs. The assembler has
30+ no `jmp reg`, so it is written `db 0FFH, 0E1H;`.
31+- **`NO_COLOR` set to nothing.** `Sys.env` gives "" for a variable that
32+ is unset and for one that is empty, so the port reads the second as
33+ the first, as no-color.org has it. The seed reads it as set.
34+- **Strings are slices.** A message is a `[]U8` made by `Diag.say`,
35+ which keeps what it makes: messages are made only to be shown. A name
36+ from `nameOf` stays valid, since names are kept in chunks that are
37+ never moved; the seed's was a copy.
38+- **No bit cast.** A real's bits and back go through a pointer.
39+- **Speed.** On the 348,025 lines of `test/genbench.py`, 7.6 MB, the
40+ seed's scanner takes 75 ms and this one 83 ms. Two things cost the
41+ rest: a slice comparison, `a[0..n] = b[0..n]`, is 25% slower than the
42+ same bytes in a loop, and a procedure call to ask whether a byte is
43+ in a name (a table now). The compiler could mend the first.

self/Scan.raz added +998 -0

@@ -0,0 +1,998 @@
1+(* Scan: the scanner.
2+
3+ Reads a raz source file and hands the parser one symbol at a time:
4+ reserved words, identifiers, numbers, characters, strings and
5+ operators. Identifiers are interned, so that the rest of the compiler
6+ compares names as small integers. The scanner also says where the
7+ current symbol is, for messages.
8+
9+ Depends on: Sys, to read files; Diag, to report errors; Jump, to go
10+ on after the parser's errors.
11+ Leaves out: recovery from errors in the text itself, such as a string
12+ not closed: the first such error stops the compiler. The parser goes
13+ on after its own errors, through recovery below. *)
14+module Scan;
15+import Sys, Heap, Mem, Fmt, Diag, Jump;
16+
17+type
18+ NamePtr = ^U8;
19+
20+ Sym* = (sNull, sIdent, sInt, sReal, sChar, sString,
21+ sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq,
22+ sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis,
23+ sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sAmp, sTilde, sBar,
24+ sBlank,
25+ (* the reserved words, in the order of words below *)
26+ sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse,
27+ sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink,
28+ sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord,
29+ sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sType, sUntil, sVar,
30+ sVariant, sVolatile, sWhile, sXor,
31+ sEof);
32+
33+ (* Where the scanner is. Importing a module compiles it in the middle
34+ of another, so the parser saves this and restores it afterwards. *)
35+ State* = record
36+ buf: ^U8;
37+ len, pos, line, lineStart: INT;
38+ tokPos, tokLine, tokLineStart: INT;
39+ prevEnd: INT; (* where the symbol before this one ends *)
40+ tok: Sym;
41+ ival: I64;
42+ rval: F64;
43+ id: INT;
44+ f: INT; (* the file, as Diag knows it *)
45+ end;
46+
47+const
48+ MaxIdent* = 63;
49+ MaxStr* = 65536;
50+ NumWords = 42;
51+ NumOps = 28;
52+ words: [NumWords][]U8 = [
53+ "and", "begin", "break", "by", "code", "const", "defer", "div", "do",
54+ "else", "elsif", "end", "extern", "for", "forward", "if", "import",
55+ "in", "link", "match", "mod", "module", "not", "of", "or", "packed",
56+ "proc", "record", "repeat", "return", "set", "shl", "shr", "then",
57+ "to", "type", "until", "var", "variant", "VOLATILE", "while", "xor"];
58+ (* sPlus to sBlank *)
59+ ops: [NumOps][]U8 = [
60+ "+", "-", "*", "/", "=", "#", "<", "<=", ">", ">=",
61+ ":=", ":", ";", ",", ".", "..", "...",
62+ "(", ")", "[", "]", "{", "}", "^", "&", "~", "|", "_"];
63+ PoolChunk = 65536;
64+
65+var
66+ tok*: Sym; (* the current symbol *)
67+ ival*: I64; (* sInt, sChar: its value *)
68+ rval*: F64; (* sReal: its value *)
69+ id*: INT; (* sIdent: its name *)
70+ slen*: INT; (* sString: how many bytes *)
71+ sbuf: [MaxStr + 1]U8; (* sString: its bytes, then a zero *)
72+
73+ (* Where the parser goes on after an error: the innermost statement or
74+ declaration being read. nil stops the compiler at the first error. *)
75+ recovery: ^Jump.Env;
76+ (* The parser is skipping what it has read once already, after an
77+ error, so slips in it aren't reported again. *)
78+ skipping: BOOL;
79+
80+ (* Whether a byte may be in a name: a letter, a digit or _. A table,
81+ since the loop that reads a name asks it of every byte. *)
82+ nameChar: [256]BOOL;
83+
84+ cur: State; (* buf .. f; tok, ival, rval and id live above *)
85+
86+ (* The name table: every distinct identifier once, found through an
87+ open-addressed hash table. A name's bytes are in a chunk of memory
88+ that is never moved, so that nameOf can hand out a slice of them. *)
89+ chunk: ^U8; (* where names are put; chunkLeft bytes are left *)
90+ chunkLeft: INT;
91+ namePtr: ^NamePtr;
92+ nameLen, nameHash: ^INT;
93+ numNames, nameCap: INT;
94+ table: ^INT; (* name + 1, or 0 for an empty slot *)
95+ tableMask: INT;
96+
97+(* Exported variables can't be set from outside, so these do it. *)
98+proc setRecovery*(r: ^Jump.Env);
99+begin
100+ recovery := r;
101+end;
102+
103+proc setSkipping*(yes: BOOL);
104+begin
105+ skipping := yes;
106+end;
107+
108+(* The bytes of the string just read, without the zero after them *)
109+proc strBytes*: []U8;
110+begin
111+ return sbuf[0..slen];
112+end;
113+
114+(* Memory, or the end of the compile when there is none *)
115+proc grab(size: INT): ^U8;
116+var p: ^U8;
117+begin
118+ p := Mem.alloc(Heap.heap, size, 8);
119+ if p = nil then Diag.fatal("out of memory"); end;
120+ return p;
121+end;
122+
123+(* n zeroed words *)
124+proc words64(n: INT): ^INT;
125+var p: ^INT; i: INT;
126+begin
127+ p := ^INT(grab(n * SIZE(INT)));
128+ for i := 0 to n - 1 do p[i] := 0; end;
129+ return p;
130+end;
131+
132+(* Names *)
133+
134+proc hash(p: ^U8; n: INT): INT;
135+var h: U32; i: INT;
136+begin
137+ h := 2166136261;
138+ for i := 0 to n - 1 do h := (h xor U32(p[i])) * 16777619; end;
139+ return INT(h & 7FFFFFFFH);
140+end;
141+
142+(* A table twice the size, and room for twice the names *)
143+proc grow;
144+var i, n, j: INT; ptrs: ^NamePtr; lens, hashes: ^INT;
145+begin
146+ Mem.free(Heap.heap, ^U8(table));
147+ tableMask := tableMask * 2 + 1;
148+ table := words64(tableMask + 1);
149+ for n := 0 to numNames - 1 do
150+ i := nameHash[n] & tableMask;
151+ while table[i] # 0 do i := (i + 1) & tableMask; end;
152+ table[i] := n + 1;
153+ end;
154+ j := nameCap * 2;
155+ ptrs := ^NamePtr(grab(j * SIZE(NamePtr)));
156+ lens := ^INT(grab(j * SIZE(INT)));
157+ hashes := ^INT(grab(j * SIZE(INT)));
158+ for n := 0 to numNames - 1 do
159+ ptrs[n] := namePtr[n];
160+ lens[n] := nameLen[n];
161+ hashes[n] := nameHash[n];
162+ end;
163+ Mem.free(Heap.heap, ^U8(namePtr));
164+ Mem.free(Heap.heap, ^U8(nameLen));
165+ Mem.free(Heap.heap, ^U8(nameHash));
166+ namePtr := ptrs;
167+ nameLen := lens;
168+ nameHash := hashes;
169+ nameCap := j;
170+end;
171+
172+(* Whether the n bytes at p and at q are the same *)
173+proc same(p, q: ^U8; n: INT): BOOL;
174+var i: INT;
175+begin
176+ for i := 0 to n - 1 do
177+ if p[i] # q[i] then return false; end;
178+ end;
179+ return true;
180+end;
181+
182+(* The number of the name of the n bytes at p; a new name gets the next *)
183+proc intern*(p: ^U8; n: INT): INT;
184+var h, i, k: INT;
185+begin
186+ h := hash(p, n);
187+ i := h & tableMask;
188+ while table[i] # 0 do
189+ k := table[i] - 1;
190+ if (nameHash[k] = h) and (nameLen[k] = n) and same(namePtr[k], p, n) then
191+ return k;
192+ end;
193+ i := (i + 1) & tableMask;
194+ end;
195+ if n > chunkLeft then
196+ chunk := grab(PoolChunk);
197+ chunkLeft := PoolChunk;
198+ end;
199+ COPY(chunk[0..n], p[0..n]);
200+ k := numNames;
201+ namePtr[k] := chunk;
202+ nameLen[k] := n;
203+ nameHash[k] := h;
204+ chunk := chunk + n;
205+ chunkLeft := chunkLeft - n;
206+ INC(numNames);
207+ table[i] := k + 1;
208+ if numNames * 2 > tableMask then grow; end;
209+ return k;
210+end;
211+
212+(* The name n, which stays as it is *)
213+proc nameOf*(n: INT): []U8;
214+begin
215+ return namePtr[n][0..nameLen[n]];
216+end;
217+
218+(* Errors *)
219+
220+(* The current symbol *)
221+proc tokPos*: Diag.Pos;
222+begin
223+ return {f: cur.f, a: cur.tokPos, b: cur.pos};
224+end;
225+
226+(* The place just after the symbol before the current one, where a
227+ missing symbol belongs *)
228+proc afterPrev*: Diag.Pos;
229+begin
230+ return {f: cur.f, a: cur.prevEnd, b: cur.prevEnd};
231+end;
232+
233+(* Where to say a symbol is missing: at the current symbol, unless it
234+ starts a later line than the symbol before it, which is more likely
235+ where the missing one belongs *)
236+proc missingPos*: Diag.Pos;
237+var i: INT; p: Diag.Pos;
238+begin
239+ p := tokPos();
240+ for i := cur.prevEnd to cur.tokPos - 1 do
241+ if cur.buf[i] = '\n' then p := afterPrev(); end;
242+ end;
243+ return p;
244+end;
245+
246+(* From the start of p to the end of the symbol before the current one:
247+ the whole of a construct that has just been read *)
248+proc spanFrom*(p: Diag.Pos): Diag.Pos;
249+begin
250+ p.b := cur.prevEnd;
251+ return p;
252+end;
253+
254+proc curLine*: INT;
255+begin
256+ return cur.tokLine;
257+end;
258+
259+(* The line and column of byte a of the file, at or before the current
260+ symbol: counted back from the symbol's line, so that it costs only
261+ the distance. A column counts characters, as Diag's do. *)
262+proc lineCol*(a: INT): (INT, INT);
263+var i, line, start, col: INT;
264+begin
265+ line := cur.tokLine;
266+ start := cur.tokLineStart;
267+ while a < start do
268+ DEC(line);
269+ DEC(start);
270+ while (start > 0) and (cur.buf[start - 1] # '\n') do DEC(start); end;
271+ end;
272+ col := 1;
273+ for i := start to a - 1 do
274+ if (cur.buf[i] & 0C0H) # 80H then INC(col); end;
275+ end;
276+ return line, col;
277+end;
278+
279+proc curCol*: INT;
280+var col: INT;
281+begin
282+ _, col := lineCol(cur.tokPos);
283+ return col;
284+end;
285+
286+(* After an error in the parser's construct, reported with its notes
287+ and help: the parser goes on from the recovery point. *)
288+proc fail*;
289+begin
290+ if recovery = nil then Diag.finish; end;
291+ Jump.jump(recovery);
292+end;
293+
294+(* An error at p: reported, then the parser goes on from its recovery
295+ point. *)
296+proc markAt*(p: Diag.Pos; msg: []U8);
297+begin
298+ Diag.error(p, msg);
299+ fail;
300+end;
301+
302+proc mark*(msg: []U8);
303+begin
304+ markAt(tokPos(), msg);
305+end;
306+
307+(* markAt, with a line of help after the message. *)
308+proc markHelp*(p: Diag.Pos; msg, hint: []U8);
309+begin
310+ Diag.error(p, msg);
311+ Diag.help(hint);
312+ fail;
313+end;
314+
315+(* An error in the text at bytes a to b of the file being read, which
316+ stops the compiler: past it, the symbols can't be trusted. *)
317+proc markBytes(a, b: INT; msg: []U8);
318+begin
319+ Diag.setQuiet(false);
320+ Diag.error({f: cur.f, a: a, b: b}, msg);
321+ Diag.finish;
322+end;
323+
324+proc lexError(msg: []U8);
325+begin
326+ markBytes(cur.tokPos, cur.pos, msg);
327+end;
328+
329+(* The n characters at the scanner are how another language writes t:
330+ an error, but reading goes on as if t were written. *)
331+proc slip(n: INT; t: Sym; msg: []U8);
332+begin
333+ if not skipping then Diag.error({f: cur.f, a: cur.pos, b: cur.pos + n}, msg); end;
334+ INC(cur.pos, n);
335+ tok := t;
336+end;
337+
338+(* How an operator or reserved word is written, quoted, for messages. *)
339+proc symText*(s: Sym): []U8;
340+begin
341+ if (s >= sPlus) and (s <= sBlank) then
342+ return Diag.say("\"{}\"", [Fmt.str(ops[INT(s) - INT(sPlus)])]);
343+ end;
344+ return Diag.say("\"{}\"", [Fmt.str(words[INT(s) - INT(sAnd)])]);
345+end;
346+
347+(* The current symbol, for "expected ..., found ...": a name as it is,
348+ a literal by its kind, an operator or reserved word quoted. *)
349+proc found*: []U8;
350+begin
351+ match tok of
352+ | sIdent: return nameOf(id);
353+ | sInt: return "a number";
354+ | sReal: return "a number";
355+ | sChar: return "a character";
356+ | sString: return "a string";
357+ | sEof: return "the end of the file";
358+ | else: return symText(tok);
359+ end;
360+end;
361+
362+(* The current symbol is the first on its line: at the top level of a
363+ module, by the usual layout, so where reading can start again. *)
364+proc atLineStart*: BOOL;
365+begin
366+ return cur.tokPos = cur.tokLineStart;
367+end;
368+
369+(* The column the current symbol's line is indented to *)
370+proc indent*: INT;
371+var i: INT;
372+begin
373+ i := cur.tokLineStart;
374+ while (cur.buf[i] = ' ') or (cur.buf[i] = '\t') do INC(i); end;
375+ return i - cur.tokLineStart + 1;
376+end;
377+
378+(* Files *)
379+
380+(* Name n is a reserved word *)
381+proc reserved*(n: INT): BOOL;
382+begin
383+ return n < NumWords;
384+end;
385+
386+(* Reads the file at path to scan it; "" if it can, else why not *)
387+proc open*(path: []U8): []U8;
388+var fd, n, got, r, err: INT; info: Sys.Info;
389+begin
390+ info, err := Sys.info(path);
391+ if err = -2 then return "there is no such file"; end;
392+ if err = -13 then return "permission denied"; end;
393+ if err < 0 then return "it can't be opened"; end;
394+ if not info.file then return "it isn't a file"; end;
395+ fd := Sys.openRead(path);
396+ if fd = -2 then return "there is no such file"; end;
397+ if fd = -13 then return "permission denied"; end;
398+ if fd < 0 then return "it can't be opened"; end;
399+ n := INT(info.size);
400+ cur.buf := grab(n + 1);
401+ got := 0;
402+ while got < n do
403+ r := Sys.read(fd, cur.buf[got..n]);
404+ if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end;
405+ got := got + r;
406+ end;
407+ Sys.close(fd);
408+ cur.buf[n] := 0; (* the sentinel that ends every scan *)
409+ cur.len := n;
410+ cur.pos := 0;
411+ cur.line := 1;
412+ cur.lineStart := 0;
413+ cur.tokPos := 0;
414+ cur.tokLine := 1;
415+ cur.tokLineStart := 0;
416+ cur.f := Diag.addFile(path, cur.buf, n);
417+ return "";
418+end;
419+
420+proc saveScan*(var st: State);
421+begin
422+ st := cur;
423+ st.tok := tok;
424+ st.ival := ival;
425+ st.rval := rval;
426+ st.id := id;
427+end;
428+
429+proc restoreScan*(st: State);
430+begin
431+ cur := st;
432+ tok := st.tok;
433+ ival := st.ival;
434+ rval := st.rval;
435+ id := st.id;
436+end;
437+
438+(* UTF-8 *)
439+
440+(* Decodes the character at buf[pos], which is not ASCII, checking that
441+ it is well formed; returns its code point and moves pos past it. *)
442+proc utf8(var pos: INT): INT;
443+var b0, b1, n, i, cp: INT; lo, hi: INT;
444+begin
445+ b0 := INT(cur.buf[pos]);
446+ lo := 80H;
447+ hi := 0BFH;
448+ n := 0;
449+ cp := 0;
450+ match b0 of
451+ | 0C2H..0DFH: n := 1; cp := b0 & 1FH;
452+ | 0E0H: n := 2; lo := 0A0H;
453+ | 0E1H..0ECH, 0EEH, 0EFH: n := 2; cp := b0 & 0FH;
454+ | 0EDH: n := 2; cp := 0DH; hi := 9FH; (* no surrogates *)
455+ | 0F0H: n := 3; lo := 90H;
456+ | 0F1H..0F3H: n := 3; cp := b0 & 7;
457+ | 0F4H: n := 3; cp := 4; hi := 8FH; (* up to 10FFFFH *)
458+ | else:
459+ cur.tokPos := pos;
460+ lexError("invalid UTF-8");
461+ end;
462+ for i := 1 to n do
463+ b1 := INT(cur.buf[pos + i]);
464+ if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then
465+ cur.tokPos := pos;
466+ lexError("bad UTF-8");
467+ end;
468+ cp := cp shl 6 | (b1 & 3FH);
469+ lo := 80H;
470+ hi := 0BFH;
471+ end;
472+ pos := pos + n + 1;
473+ return cp;
474+end;
475+
476+proc put(b: INT);
477+begin
478+ if slen >= MaxStr then
479+ lexError(Diag.say("a string holds at most {} bytes", [Fmt.int(MaxStr)]));
480+ end;
481+ sbuf[slen] := U8(b);
482+ INC(slen);
483+end;
484+
485+proc putUtf8(cp: INT);
486+begin
487+ if cp < 80H then
488+ put(cp);
489+ elsif cp < 800H then
490+ put(0C0H | cp shr 6); put(80H | cp & 3FH);
491+ elsif cp < 10000H then
492+ put(0E0H | cp shr 12); put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH);
493+ else
494+ put(0F0H | cp shr 18); put(80H | cp shr 12 & 3FH);
495+ put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH);
496+ end;
497+end;
498+
499+proc isDigit(c: U8): BOOL;
500+begin
501+ return (c >= '0') and (c <= '9');
502+end;
503+
504+proc isLetter(c: U8): BOOL;
505+begin
506+ return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') or (c = '_');
507+end;
508+
509+proc hexVal(c: U8): INT;
510+begin
511+ if isDigit(c) then return INT(c) - '0';
512+ elsif (c >= 'A') and (c <= 'F') then return INT(c) - 'A' + 10;
513+ elsif (c >= 'a') and (c <= 'f') then return INT(c) - 'a' + 10;
514+ end;
515+ return -1;
516+end;
517+
518+(* The text of the file from byte a up to but not including b *)
519+proc text(a, b: INT): []U8;
520+begin
521+ return Diag.source({f: cur.f, a: a, b: b});
522+end;
523+
524+(* One character of a character or string literal, at buf[pos]: its code
525+ point, or for \xHH, minus one minus the byte. *)
526+proc litChar(inString: BOOL): INT;
527+var c: U8; v, d, n, esc, digits: INT;
528+begin
529+ c := cur.buf[cur.pos];
530+ esc := cur.pos;
531+ v := 0;
532+ if c = '\\' then
533+ INC(cur.pos);
534+ c := cur.buf[cur.pos];
535+ INC(cur.pos);
536+ match c of
537+ | 'n': v := 10;
538+ | 't': v := 9;
539+ | 'r': v := 13;
540+ | '0': v := 0;
541+ | '\\', '\'', '"': v := INT(c);
542+ | 'x':
543+ if not inString then markBytes(esc, cur.pos, "\\x is only for strings"); end;
544+ d := hexVal(cur.buf[cur.pos]);
545+ n := hexVal(cur.buf[cur.pos + 1]);
546+ if (d < 0) or (n < 0) then markBytes(esc, cur.pos + 2, "\\x needs two hex digits"); end;
547+ INC(cur.pos, 2);
548+ v := -1 - (d * 16 + n);
549+ | 'u':
550+ if cur.buf[cur.pos] # '{' then markBytes(esc, cur.pos, "expected \"{\" after \\u"); end;
551+ INC(cur.pos);
552+ digits := cur.pos;
553+ v := 0;
554+ n := 0;
555+ while hexVal(cur.buf[cur.pos]) >= 0 do
556+ v := v * 16 + hexVal(cur.buf[cur.pos]);
557+ INC(n);
558+ INC(cur.pos);
559+ if n > 6 then markBytes(esc, cur.pos, "a code point has at most 6 hex digits"); end;
560+ end;
561+ if (n = 0) or (cur.buf[cur.pos] # '}') then
562+ markBytes(esc, cur.pos, "expected hex digits and \"}\" after \\u{");
563+ end;
564+ INC(cur.pos);
565+ if (v > 10FFFFH) or (v >= 0D800H) and (v <= 0DFFFH) then
566+ markBytes(esc, cur.pos, Diag.say("{} isn't a code point", [Fmt.str(text(digits, cur.pos - 1))]));
567+ end;
568+ | else:
569+ markBytes(esc, cur.pos, Diag.say("unknown escape \\{}", [Fmt.char(c)]));
570+ end;
571+ elsif c >= 80H then
572+ v := utf8(cur.pos);
573+ elsif (c < ' ') or (c = 127) then
574+ if inString then lexError("string not closed"); else lexError("character not closed"); end;
575+ else
576+ v := INT(c);
577+ INC(cur.pos);
578+ end;
579+ return v;
580+end;
581+
582+(* Symbols *)
583+
584+proc comment;
585+var depth, open: INT; c: U8;
586+begin
587+ depth := 1;
588+ open := cur.pos;
589+ INC(cur.pos, 2);
590+ repeat
591+ c := cur.buf[cur.pos];
592+ if c = 0 then
593+ if cur.pos >= cur.len then markBytes(open, open + 2, "comment not closed"); end;
594+ INC(cur.pos);
595+ elsif (c = '(') and (cur.buf[cur.pos + 1] = '*') then
596+ INC(depth);
597+ INC(cur.pos, 2);
598+ elsif (c = '*') and (cur.buf[cur.pos + 1] = ')') then
599+ DEC(depth);
600+ INC(cur.pos, 2);
601+ elsif c = '\n' then
602+ INC(cur.pos);
603+ INC(cur.line);
604+ cur.lineStart := cur.pos;
605+ elsif c >= 80H then
606+ _ := utf8(cur.pos);
607+ else
608+ INC(cur.pos);
609+ end;
610+ until depth = 0;
611+end;
612+
613+(* Reading a decimal real exactly: the F64 nearest to digits times 10 to
614+ an exponent, ties to the even one, which a library's reader doesn't
615+ promise. The number is a fraction of two big integers, num / den,
616+ scaled by 2^e until its whole part has 53 or 54 bits; that part and
617+ the remainder give the bits and the rounding. *)
618+type
619+ Big = record
620+ n: INT; (* words in use; 0 is zero *)
621+ w: [96]U32; (* least significant first *)
622+ end;
623+(* 96 words, 3072 bits, are plenty: a string holds at most 255
624+ digits, so readReal's den is at most 10^(330 + 255), about 2^1944,
625+ and num below 10^310; the shift that follows makes the larger one at
626+ most 54 bits longer than den, about 2000 bits in all. *)
627+
628+(* a := a * m + add *)
629+proc bigMul(var a: Big; m, add: U32);
630+var i: INT; c: U64;
631+begin
632+ c := U64(add);
633+ for i := 0 to a.n - 1 do
634+ c := U64(a.w[i]) * U64(m) + c;
635+ a.w[i] := U32(c);
636+ c := c shr 32;
637+ end;
638+ if c # 0 then
639+ a.w[a.n] := U32(c);
640+ INC(a.n);
641+ end;
642+end;
643+
644+proc bigShl(var a: Big; k: INT);
645+var i, ws, bits: INT;
646+begin
647+ if a.n = 0 then return; end;
648+ ws := k div 32;
649+ bits := k mod 32;
650+ a.w[a.n + ws] := 0;
651+ for i := a.n - 1 to 0 by -1 do
652+ if bits > 0 then a.w[i + ws + 1] := a.w[i + ws + 1] | (a.w[i] shr (32 - bits)); end;
653+ a.w[i + ws] := a.w[i] shl bits;
654+ end;
655+ for i := 0 to ws - 1 do a.w[i] := 0; end;
656+ INC(a.n, ws + 1);
657+ while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
658+end;
659+
660+proc bigShr1(var a: Big);
661+var i: INT;
662+begin
663+ for i := 0 to a.n - 1 do
664+ a.w[i] := a.w[i] shr 1;
665+ if i + 1 < a.n then a.w[i] := a.w[i] | (a.w[i + 1] shl 31); end;
666+ end;
667+ while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
668+end;
669+
670+(* -1, 0 or 1 as a is below, equal to or above b *)
671+proc bigCmp(a, b: Big): INT;
672+var i: INT;
673+begin
674+ if a.n # b.n then
675+ if a.n > b.n then return 1; end;
676+ return -1;
677+ end;
678+ for i := a.n - 1 to 0 by -1 do
679+ if a.w[i] # b.w[i] then
680+ if a.w[i] > b.w[i] then return 1; end;
681+ return -1;
682+ end;
683+ end;
684+ return 0;
685+end;
686+
687+(* a := a - b, b not above a *)
688+proc bigSub(var a: Big; b: Big);
689+var i: INT; d: I64;
690+begin
691+ d := 0;
692+ for i := 0 to a.n - 1 do
693+ d := d + I64(a.w[i]);
694+ if i < b.n then d := d - I64(b.w[i]); end;
695+ a.w[i] := U32(d);
696+ if d < 0 then d := -1; else d := 0; end; (* a borrow *)
697+ end;
698+ while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
699+end;
700+
701+proc bigBits(a: Big): INT;
702+var t: U32; bits: INT;
703+begin
704+ if a.n = 0 then return 0; end;
705+ bits := (a.n - 1) * 32;
706+ t := a.w[a.n - 1];
707+ while t # 0 do
708+ INC(bits);
709+ t := t shr 1;
710+ end;
711+ return bits;
712+end;
713+
714+(* s is digits, a point, digits, and maybe E, a sign and digits. False if
715+ the value is past the largest F64; one below the smallest is 0. *)
716+proc readReal(s: []U8): (F64, BOOL);
717+var
718+ num, den, d: Big; i, digits, e, ex: INT; neg, half, sticky: BOOL;
719+ q, b: U64; x: F64; bits: ^F64;
720+begin
721+ num.n := 0;
722+ den.n := 1;
723+ den.w[0] := 1;
724+ digits := 0;
725+ e := 0;
726+ i := 0;
727+ while (i < LEN(s)) and (s[i] # 'E') do
728+ if s[i] = '.' then
729+ e := 1;
730+ else
731+ bigMul(num, 10, U32(INT(s[i]) - '0'));
732+ if num.n > 0 then INC(digits); end; (* counted from the first that isn't 0 *)
733+ if e > 0 then INC(e); end;
734+ end;
735+ INC(i);
736+ end;
737+ if e > 0 then e := 1 - e; end; (* minus the digits after the point *)
738+ ex := 0;
739+ neg := false;
740+ if i < LEN(s) then
741+ INC(i);
742+ neg := s[i] = '-';
743+ if (s[i] = '+') or (s[i] = '-') then INC(i); end;
744+ while i < LEN(s) do
745+ if ex < 100000 then ex := ex * 10 + INT(s[i]) - '0'; end;
746+ INC(i);
747+ end;
748+ end;
749+ if neg then ex := -ex; end;
750+ INC(e, ex);
751+ x := 0.0;
752+ if num.n = 0 then return x, true; end;
753+ if digits + e > 310 then return x, false; end; (* 10^310 is past every F64 *)
754+ if digits + e < -330 then return x, true; end; (* and 10^-330 below half the least *)
755+ for i := 1 to e do bigMul(num, 10, 0); end;
756+ for i := 1 to -e do bigMul(den, 10, 0); end;
757+ (* num / den 2^-e from 2^52 to 2^54, but not past the least exponent *)
758+ e := bigBits(num) - bigBits(den) - 53;
759+ if e < -1074 then e := -1074; end;
760+ if e < 0 then bigShl(num, -e); else bigShl(den, e); end;
761+ (* q, its whole part, by long division; num is left the remainder *)
762+ d := den;
763+ bigShl(d, 53);
764+ q := 0;
765+ for i := 53 to 0 by -1 do
766+ if bigCmp(num, d) >= 0 then
767+ bigSub(num, d);
768+ q := q | (U64(1) shl i);
769+ end;
770+ bigShr1(d);
771+ end;
772+ if q >= U64(1) shl 53 then (* a bit too many: it rounds *)
773+ half := (q & 1) # 0;
774+ sticky := num.n > 0;
775+ q := q shr 1;
776+ INC(e);
777+ else (* the remainder against half of den *)
778+ bigShl(num, 1);
779+ i := bigCmp(num, den);
780+ half := i >= 0;
781+ sticky := i > 0;
782+ end;
783+ if half and (sticky or ((q & 1) # 0)) then
784+ INC(q);
785+ if q = U64(1) shl 53 then
786+ q := q shr 1;
787+ INC(e);
788+ end;
789+ end;
790+ if e > 971 then return x, false; end;
791+ if q >= U64(1) shl 52 then
792+ b := U64(e + 1075) shl 52 | (q & (U64(1) shl 52 - 1));
793+ else
794+ b := q; (* below the least normal, e is -1074 *)
795+ end;
796+ bits := ^F64(ADR(b));
797+ return bits^, true;
798+end;
799+
800+proc number;
801+var start, i, d: INT; allDec, ok: BOOL; v: U64;
802+begin
803+ start := cur.pos;
804+ allDec := true;
805+ while isDigit(cur.buf[cur.pos]) or (cur.buf[cur.pos] >= 'A') and (cur.buf[cur.pos] <= 'F') do
806+ if cur.buf[cur.pos] > '9' then allDec := false; end;
807+ INC(cur.pos);
808+ end;
809+ if cur.buf[cur.pos] = 'H' then
810+ v := 0;
811+ for i := start to cur.pos - 1 do
812+ if v shr 60 # 0 then lexError(Diag.say("{} is too big for U64", [Fmt.str(text(start, cur.pos))])); end;
813+ v := v * 16 + U64(hexVal(cur.buf[i]));
814+ end;
815+ INC(cur.pos);
816+ tok := sInt;
817+ ival := I64(v); (* 16 digits are the bits of a 64-bit word *)
818+ elsif (cur.buf[cur.pos] = '.') and isDigit(cur.buf[cur.pos + 1]) then
819+ if not allDec then lexError("a decimal number has only the digits 0 to 9"); end;
820+ INC(cur.pos);
821+ while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end;
822+ if cur.buf[cur.pos] = 'E' then
823+ INC(cur.pos);
824+ if (cur.buf[cur.pos] = '+') or (cur.buf[cur.pos] = '-') then INC(cur.pos); end;
825+ if not isDigit(cur.buf[cur.pos]) then lexError("expected a digit in the exponent"); end;
826+ while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end;
827+ end;
828+ if cur.pos - start > 255 then lexError("a number has at most 255 characters"); end;
829+ rval, ok := readReal(cur.buf[start..cur.pos]);
830+ if not ok then lexError(Diag.say("{} is out of the range of F64", [Fmt.str(text(start, cur.pos))])); end;
831+ tok := sReal;
832+ else
833+ if not allDec then lexError("a hex number ends with H"); end;
834+ v := 0;
835+ for i := start to cur.pos - 1 do
836+ d := INT(cur.buf[i]) - '0';
837+ if v > (U64(9223372036854775807) - U64(d)) div 10 then
838+ lexError(Diag.say("{} is too big for I64", [Fmt.str(text(start, cur.pos))]));
839+ end;
840+ v := v * 10 + U64(d);
841+ end;
842+ tok := sInt;
843+ ival := I64(v);
844+ end;
845+ if nameChar[cur.buf[cur.pos]] then
846+ lexError("a name can't start with a digit");
847+ end;
848+end;
849+
850+(* Reads the next symbol *)
851+proc next*;
852+var c: U8; start, h, v, i: INT;
853+begin
854+ cur.prevEnd := cur.pos;
855+ repeat
856+ c := cur.buf[cur.pos];
857+ while (c = ' ') or (c = '\t') or (c = '\r') or (c = '\n') do
858+ if c = '\n' then
859+ INC(cur.line);
860+ cur.lineStart := cur.pos + 1;
861+ end;
862+ INC(cur.pos);
863+ c := cur.buf[cur.pos];
864+ end;
865+ if (c = '(') and (cur.buf[cur.pos + 1] = '*') then
866+ comment;
867+ c := ' ';
868+ end;
869+ until c # ' ';
870+ cur.tokPos := cur.pos;
871+ cur.tokLine := cur.line;
872+ cur.tokLineStart := cur.lineStart;
873+ match c of
874+ | 'A'..'Z', 'a'..'z', '_':
875+ start := cur.pos;
876+ repeat INC(cur.pos); until not nameChar[cur.buf[cur.pos]];
877+ if cur.pos - start > MaxIdent then
878+ lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)]));
879+ end;
880+ h := intern(cur.buf + start, cur.pos - start);
881+ if (cur.pos - start = 1) and (c = '_') then
882+ tok := sBlank;
883+ elsif h < NumWords then
884+ tok := Sym(INT(sAnd) + h);
885+ else
886+ tok := sIdent;
887+ id := h;
888+ end;
889+ | '0'..'9': number;
890+ | '\'':
891+ INC(cur.pos);
892+ if cur.buf[cur.pos] = '\'' then lexError("empty character"); end;
893+ v := litChar(false);
894+ if cur.buf[cur.pos] # '\'' then
895+ (* 'ab': several characters, as some languages write a string *)
896+ i := cur.pos;
897+ while (cur.buf[i] # '\'') and (cur.buf[i] # '\n') and (cur.buf[i] # 0) do INC(i); end;
898+ if cur.buf[i] = '\'' then
899+ markBytes(cur.tokPos, i + 1,
900+ Diag.say("a character is one character: the string is \"{}\"", [Fmt.str(text(cur.tokPos + 1, i))]));
901+ else
902+ lexError("character not closed");
903+ end;
904+ end;
905+ INC(cur.pos);
906+ tok := sChar;
907+ ival := I64(v);
908+ | '"':
909+ INC(cur.pos);
910+ slen := 0;
911+ while cur.buf[cur.pos] # '"' do
912+ v := litChar(true);
913+ if v < 0 then put(-1 - v); else putUtf8(v); end;
914+ end;
915+ INC(cur.pos);
916+ sbuf[slen] := 0;
917+ tok := sString;
918+ | '+': INC(cur.pos); tok := sPlus;
919+ | '-': INC(cur.pos); tok := sMinus;
920+ | '*': INC(cur.pos); tok := sTimes;
921+ | '/': INC(cur.pos); tok := sSlash;
922+ | '=':
923+ if cur.buf[cur.pos + 1] = '=' then
924+ slip(2, sEql, "comparing is written =, not ==");
925+ else
926+ INC(cur.pos);
927+ tok := sEql;
928+ end;
929+ | '&':
930+ if cur.buf[cur.pos + 1] = '&' then
931+ slip(2, sAnd, "\"and\" is written and, not &&");
932+ else
933+ INC(cur.pos);
934+ tok := sAmp;
935+ end;
936+ | '#': INC(cur.pos); tok := sNeq;
937+ | '<':
938+ INC(cur.pos);
939+ if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sLeq; else tok := sLss; end;
940+ | '>':
941+ INC(cur.pos);
942+ if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sGeq; else tok := sGtr; end;
943+ | ':':
944+ INC(cur.pos);
945+ if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sBecomes; else tok := sColon; end;
946+ | ';': INC(cur.pos); tok := sSemicolon;
947+ | ',': INC(cur.pos); tok := sComma;
948+ | '.':
949+ INC(cur.pos);
950+ if cur.buf[cur.pos] = '.' then
951+ INC(cur.pos);
952+ if cur.buf[cur.pos] = '.' then INC(cur.pos); tok := sEllipsis; else tok := sUpto; end;
953+ else
954+ tok := sPeriod;
955+ end;
956+ | '(': INC(cur.pos); tok := sLparen;
957+ | ')': INC(cur.pos); tok := sRparen;
958+ | '[': INC(cur.pos); tok := sLbrak;
959+ | ']': INC(cur.pos); tok := sRbrak;
960+ | '{': INC(cur.pos); tok := sLbrace;
961+ | '}': INC(cur.pos); tok := sRbrace;
962+ | '^': INC(cur.pos); tok := sArrow;
963+ | '|':
964+ if cur.buf[cur.pos + 1] = '|' then
965+ slip(2, sOr, "\"or\" is written or, not ||");
966+ else
967+ INC(cur.pos);
968+ tok := sBar;
969+ end;
970+ | '~': INC(cur.pos); tok := sTilde;
971+ | '!':
972+ if cur.buf[cur.pos + 1] = '=' then
973+ slip(2, sNeq, "\"not equal\" is written #, not !=");
974+ else
975+ slip(1, sNot, "\"not\" is written not, not !");
976+ end;
977+ | 0:
978+ if cur.pos < cur.len then markBytes(cur.pos, cur.pos + 1, "NUL byte in the text"); end;
979+ tok := sEof;
980+ | else:
981+ if c >= 80H then lexError("only ASCII outside strings, characters and comments"); end;
982+ markBytes(cur.pos, cur.pos + 1, Diag.say("unexpected character \"{}\"", [Fmt.char(c)]));
983+ end;
984+end;
985+
986+var i: INT;
987+
988+begin
989+ for i := 0 to 255 do nameChar[i] := isLetter(U8(i)) or isDigit(U8(i)); end;
990+ chunkLeft := 0;
991+ nameCap := 1 shl 12;
992+ namePtr := ^NamePtr(grab(nameCap * SIZE(NamePtr)));
993+ nameLen := ^INT(grab(nameCap * SIZE(INT)));
994+ nameHash := ^INT(grab(nameCap * SIZE(INT)));
995+ tableMask := 2 * nameCap - 1;
996+ table := words64(tableMask + 1);
997+ for i := 0 to NumWords - 1 do _ := intern(ADR(words[i][0]), LEN(words[i])); end;
998+end Scan.

self/bench.sh added (executable) +18 -0

@@ -0,0 +1,18 @@
1+#!/bin/sh
2+# The scanner's speed against the seed's, on the compiler's own
3+# benchmark program: the best of seven runs of each. Run from the
4+# repository root, after self/check.sh has built the tests.
5+set -e
6+b=build/self
7+python3 test/genbench.py 12000 >$b/Bench.raz
8+fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/scanbench.seed self/test/ScanBench.pas >/dev/null
9+./raz -Werror -I self -o $b/scanbench.self self/test/ScanBench.raz
10+echo "$(wc -l <$b/Bench.raz) lines"
11+for t in seed self; do
12+ best=0
13+ for i in 1 2 3 4 5 6 7; do
14+ s=$(date +%s%N); $b/scanbench.$t $b/Bench.raz >/dev/null; e=$(date +%s%N)
15+ d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi
16+ done
17+ echo "$t: $best ms"
18+done

self/check.sh added (executable) +35 -0

@@ -0,0 +1,35 @@
1+#!/bin/sh
2+# Tests self/'s units against the seed's: each dumper reads the same
3+# files and must give the same standard output, standard error and
4+# status. Run from the repository root, after `make raz`; the seed's
5+# side is built by fpc from src/.
6+set -e
7+b=build/self
8+mkdir -p $b
9+fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/scandump.seed self/test/ScanDump.pas >/dev/null
10+./raz -Werror -I self -o $b/scandump.self self/test/ScanDump.raz
11+python3 self/test/genreals.py > $b/reals.raz
12+# one small file for each message the scanner makes, and the places
13+# diag shows them in: a tab, a long line, characters before the place
14+mkdir -p $b/lex
15+python3 self/test/genlex.py $b/lex
16+n=0; bad=0
17+for f in $b/lex/*.raz lib/*.raz examples/*.raz tools/*.raz self/*.raz self/test/*.raz test/run/*.raz test/err/*.raz \
18+ conform/*/*.raz $b/reals.raz; do
19+ [ -f "$f" ] || continue
20+ s1=0; s2=0
21+ $b/scandump.seed $f >$b/seed.out 2>$b/seed.err || s1=$?
22+ $b/scandump.self $f >$b/self.out 2>$b/self.err || s2=$?
23+ n=$((n + 1))
24+ if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then
25+ echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1))
26+ fi
27+done
28+echo "$n files, $bad differ"
29+test $bad = 0
30+
31+# Jump: a parser's way of going on after an error
32+./raz -Werror -I self -o $b/recover self/test/Recover.raz
33+printf 'a bad b bad bad c\nd bad\n' >$b/rec.raz
34+r=$($b/recover $b/rec.raz 2>/dev/null) || test $? = 1
35+test "$r" = "8 names, 4 jumps, 4 errors" && echo "recover ok"

self/test/Recover.raz added +36 -0

@@ -0,0 +1,36 @@
1+(* Tests Jump through Scan.fail: a driver reads a file's symbols and
2+ reports each name `bad` as an error, which jumps back to where it
3+ saved its place and goes on, as the parser does after an error. The
4+ count lives in a module variable, which a jump leaves as it was. *)
5+module Recover;
6+import Out, Files, Diag, Scan, Jump;
7+
8+var
9+ env: Jump.Env;
10+ jumps, names: INT;
11+
12+proc deep(n: INT);
13+begin
14+ if n > 0 then deep(n - 1); else Scan.mark("a bad name"); end;
15+end;
16+
17+proc main*;
18+begin
19+ if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
20+ Scan.setRecovery(ADR(env));
21+ if Jump.save(ADR(env)) # 0 then INC(jumps); end;
22+ while Scan.tok # Scan.sEof do
23+ Scan.next;
24+ if Scan.tok = Scan.sIdent then
25+ INC(names);
26+ if Scan.nameOf(Scan.id) = "bad" then deep(5); end;
27+ end;
28+ end;
29+ Out.int(names); Out.str(" names, "); Out.int(jumps); Out.str(" jumps, ");
30+ Out.int(Diag.errors); Out.str(" errors\n");
31+ Scan.setRecovery(nil);
32+ Scan.mark("last");
33+ Out.str("not reached\n");
34+end;
35+
36+end Recover.

self/test/ScanBench.pas added +12 -0

@@ -0,0 +1,12 @@
1+{ Counts the symbols of a file and nothing else, for timing scan.pas
2+ against self/Scan.raz (ScanBench.raz). }
3+program scanbench;
4+{$mode objfpc}{$H-}
5+uses diag, scan;
6+var n: longint;
7+begin
8+ if Open(ParamStr(1)) <> '' then Fatal('no file');
9+ n := 0;
10+ repeat Next; inc(n) until tok = sEof;
11+ writeln(n, ' symbols');
12+end.

self/test/ScanBench.raz added +15 -0

@@ -0,0 +1,15 @@
1+(* Counts the symbols of a file and nothing else, for timing Scan.raz
2+ against the seed's scan.pas (ScanBench.pas). *)
3+module ScanBench;
4+import Out, Files, Diag, Scan;
5+
6+proc main*;
7+var n: INT;
8+begin
9+ if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
10+ n := 0;
11+ repeat Scan.next; INC(n); until Scan.tok = Scan.sEof;
12+ Out.int(n); Out.str(" symbols\n");
13+end;
14+
15+end ScanBench.

self/test/ScanDump.pas added +21 -0

@@ -0,0 +1,21 @@
1+{ Prints the symbols of a file, one per line: the seed's side of a test
2+ of self/Scan.raz, which prints the same. A real is shown by its bits,
3+ so that no formatting library decides what is the same. }
4+program scandump;
5+{$mode objfpc}{$H-}
6+uses diag, scan;
7+var i: longint; bits: int64;
8+begin
9+ if Open(ParamStr(1)) <> '' then Fatal('no file');
10+ repeat
11+ Next;
12+ write(LineOf(TokPos), ':', TokPos.a, ':', TokPos.b, ' ', CurLine, ':', CurCol, ' ', ord(tok));
13+ case tok of
14+ sIdent: write(' ', NameOf(id), ' ', id);
15+ sInt, sChar: write(' ', ival);
16+ sReal: begin Move(rval, bits, 8); write(' ', HexStr(bits, 16)) end;
17+ sString: begin write(' "'); for i := 0 to slen - 1 do write(sbuf[i], ','); write('"') end;
18+ end;
19+ writeln;
20+ until tok = sEof;
21+end.

self/test/ScanDump.raz added +35 -0

@@ -0,0 +1,35 @@
1+(* Prints the symbols of a file, one per line: self/Scan.raz's side of a
2+ test against the seed's, ScanDump.pas, which prints the same. *)
3+module ScanDump;
4+import Out, Fmt, Files, Diag, Scan;
5+
6+proc main*;
7+var p: Diag.Pos; bits: ^U64; i: INT; str: []U8; r: F64;
8+begin
9+ if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
10+ repeat
11+ Scan.next;
12+ p := Scan.tokPos();
13+ Fmt.print("{}:{}:{} {}:{} {}", [Fmt.int(Diag.lineOf(p)), Fmt.int(p.a), Fmt.int(p.b),
14+ Fmt.int(Scan.curLine()), Fmt.int(Scan.curCol()), Fmt.int(INT(Scan.tok))]);
15+ match Scan.tok of
16+ | sIdent: Fmt.print(" {} {}", [Fmt.str(Scan.nameOf(Scan.id)), Fmt.int(Scan.id)]);
17+ | sInt: Fmt.print(" {}", [Fmt.int(Scan.ival)]);
18+ | sChar: Fmt.print(" {}", [Fmt.int(Scan.ival)]);
19+ | sReal:
20+ r := Scan.rval;
21+ bits := ^U64(ADR(r));
22+ Out.str(" ");
23+ Out.hex(bits^, 16);
24+ | sString:
25+ Out.str(" \"");
26+ str := Scan.strBytes();
27+ for i := 0 to LEN(str) - 1 do Fmt.print("{},", [Fmt.int(INT(str[i]))]); end;
28+ Out.str("\"");
29+ | else:
30+ end;
31+ Out.ln;
32+ until Scan.tok = Scan.sEof;
33+end;
34+
35+end ScanDump.

self/test/genlex.py added +29 -0

@@ -0,0 +1,29 @@
1+# Writes into the directory given a file for each message the scanner
2+# makes, with the places diag shows them in: after a tab, in a long
3+# line, after characters of several bytes, in a CRLF file.
4+import sys
5+d = sys.argv[1]
6+cases = {
7+ "slip1": "x == y;\n", "slip2": "a && b;\n", "slip3": "a || b;\n", "slip4": "a != b;\n", "slip5": "!a;\n",
8+ "str": "x := \"abc\n", "chr": "x := 'a\n", "chr2": "x := 'ab';\n", "chr3": "x := '';\n",
9+ "esc": "x := \"\\q\";\n", "esc2": "x := 'a\\x41';\n", "esc3": "x := \"\\x4\";\n",
10+ "esc4": "x := \"\\u41\";\n", "esc5": "x := \"\\u{110000}\";\n", "esc6": "x := \"\\u{D800}\";\n",
11+ "esc7": "x := \"\\u{1234567}\";\n", "esc8": "x := \"\\u{}\";\n", "esc9": "x := \"\\u{41\";\n",
12+ "esc10": "x := \"\\u{1F600}\\u{e9}\\x00\\xff\\n\\t\\r\\0\\\\\\'\\\"\";\n",
13+ "cmt": "x := 1; (* open (* nested *)\n", "nul": "x := 1;\0 y;\n", "hexbad": "x := 12AB;\n",
14+ "hexbig": "x := 1FFFFFFFFFFFFFFFFH;\n", "hexok": "x := 0FFFFFFFFFFFFFFFFH; y := 7FFFFFFFFFFFFFFFH;\n",
15+ "decbig": "x := 9223372036854775808;\n", "decmax": "x := 9223372036854775807;\n",
16+ "realhex": "x := 1A.5;\n", "realexp": "x := 1.5E;\n", "realexp2": "x := 1.5E+;\n", "realbig": "x := 1.0E309;\n",
17+ "realmax": "x := 1.7976931348623159E308;\n", "reallong": "x := " + "1" * 254 + ".5;\n",
18+ "digname": "x := 12abc;\n", "uni": "x := \u00e9;\n", "badutf": b"x := \"a\xc3(\";\n", "badutf2": b"x := \"\xed\xa0\x80\";\n",
19+ "badutf3": b"x := \"\xc0\x80\";\n", "badutf4": b"x := \"\xf5\x80\x80\x80\";\n", "badutf5": b"x := \"\xe2\x82\";\n",
20+ "okutf": "x := \"h\u00e9llo \u20ac \U0001F600\"; y := '\u00e9'; (* \u00e9 *)\n",
21+ "unexp": "x := @;\n", "long": "x := " + "a + " * 60 + "@;\n", "longmid": "x := " + "a + " * 40 + "@ " + "+ b" * 40 + ";\n",
22+ "tab": "\t\tx := @;\n", "multi": "x := \"\u00e9\u00e9\u00e9\" + @;\n", "ident64": "x" * 64 + ";\n", "ident63": "x" * 63 + ";\n",
23+ "bigstr": "x := \"" + "a" * 70000 + "\";\n", "empty": "", "nonl": "x := y",
24+ "ops": "+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ & ~ | _ __ _a\n",
25+ "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",
26+}
27+for k, v in cases.items():
28+ open(f"{d}/{k}.raz", "wb").write(v.encode("utf-8", "surrogateescape") if isinstance(v, str) else v)
29+open(f"{d}/crlf.raz", "wb").write(b"x := 1;\r\ny := @;\r\n")

self/test/genreals.py added +19 -0

@@ -0,0 +1,19 @@
1+# Prints a raz module of reals that are hard to read exactly: the
2+# extremes, halves between neighbours, and many random ones.
3+import random
4+random.seed(7)
5+v = ["0.0", "1.0", "0.1", "4.9E-324", "2.4703282292062327E-324", "2.4703282292062328E-324",
6+ "2.2250738585072014E-308", "2.2250738585072011E-308", "1.7976931348623157E308",
7+ "9007199254740993.0", "9007199254740992.5", "9007199254740993.5", "0.000001E+3",
8+ "123456789012345678901234567890.0E-10", "1.0E-400", "0.5E1", "5.0E-1"]
9+for _ in range(3000):
10+ d = random.randint(1, 10 ** random.randint(1, 30))
11+ e = random.randint(-320, 300)
12+ s = str(d)
13+ v.append(s[0] + "." + (s[1:] or "0") + "E" + ("%+d" % e if random.random() < .5 else str(e)))
14+for _ in range(500):
15+ v.append("%d.%d" % (random.randint(0, 10 ** 6), random.randint(0, 10 ** 12)))
16+print("module Reals;\nvar x: F64;\nbegin")
17+for s in v:
18+ print(" x := " + s + ";")
19+print("end Reals.")