raz / src / Scan.raz

1288 lines · 40.1 KiB · raw · history · last change 2b92b442

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 For an editor (raz -q), one file's text may come from standard
10 input instead (setStdin), and a place in it may be marked: the
11 symbol there is a name, atCursor, standing for what is typed of the
12 name at the cursor, prefix, and for the name written there whole,
13 word, so that the parser can say what names can be typed there, or
14 where the name there is declared.
15
16 Depends on: Sys, to read files; Diag, to report errors.
17 Leaves out: recovery from errors in the text itself, such as a string
18 not closed: the first such error stops the compiler. The parser goes
19 on after its own errors: mark and the others report one and give
20 back Failed, which it passes up with try to where it can read on. *)
21module Scan;
22import Sys, Heap, Mem, Fmt, Str, Diag;
23import SYSTEM;
24
25type
26 NamePtr = ^U8;
27
28 (* The parser's readers for a code procedure's assembler, X64's or
29 A64's, here so that both Gens take the same types: of an integer
30 constant, a whole expression or, when whole is false, a single
31 factor; and of a name that stands for an address, a procedure or a
32 module variable, bare or qualified, its chunk, or -1, nothing read,
33 if the name is anything else, which is then read as a constant *)
34 ConstFn* = proc(whole: BOOL): (I64, ERROR);
35 NameFn* = proc: (INT, ERROR);
36
37 Sym* = (sNull, sIdent, sInt, sReal, sChar, sString,
38 sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq,
39 sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis,
40 sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sAmp, sTilde, sBar,
41 sBlank,
42 (* the reserved words, in the order of words below *)
43 sAnd, sBegin, sBreak, sBy, sCode, sConst, sContinue, sDefer, sDiv, sDo, sElse,
44 sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink,
45 sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord,
46 sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sTry, sType, sUntil, sVar,
47 sVariant, sVolatile, sWhile, sXor,
48 sEof);
49
50 (* Where the scanner is. Importing a module compiles it in the middle
51 of another, so the parser saves this and restores it afterwards. *)
52 State* = record
53 buf: ^U8;
54 len, pos, line, lineStart: INT;
55 tokPos, tokLine, tokLineStart: INT;
56 prevEnd: INT; (* where the symbol before this one ends *)
57 commentEnd: INT; (* just after the end of the last comment, or 0 *)
58 tok: Sym;
59 ival: I64;
60 rval: F64;
61 id: INT;
62 f: INT; (* the file, as Diag knows it *)
63 cursor: INT; (* raz -q words: the byte the cursor is at, until
64 the symbol there is made; else MAX(INT) *)
65 end;
66
67const
68 Failed*: ERROR = "reported"; (* an error has been shown: the parser returns it *)
69 MaxIdent* = 63;
70 MaxStr* = 65536;
71 NumWords = 44;
72 NumOps = 28;
73 words: [NumWords][]const U8 = [
74 "and", "begin", "break", "by", "code", "const", "continue", "defer", "div", "do",
75 "else", "elsif", "end", "extern", "for", "forward", "if", "import",
76 "in", "link", "match", "mod", "module", "not", "of", "or", "packed",
77 "proc", "record", "repeat", "return", "set", "shl", "shr", "then",
78 "to", "try", "type", "until", "var", "variant", "VOLATILE", "while",
79 "xor"];
80 (* sPlus to sBlank *)
81 ops: [NumOps][]const U8 = [
82 "+", "-", "*", "/", "=", "#", "<", "<=", ">", ">=",
83 ":=", ":", ";", ",", ".", "..", "...",
84 "(", ")", "[", "]", "{", "}", "^", "&", "~", "|", "_"];
85 (* the operators that no longer one starts, so that one byte is the symbol *)
86 alone = "+-*/#;,()[]{}^~";
87 PoolChunk = 65536;
88
89var
90 tok*: Sym; (* the current symbol *)
91 ival*: I64; (* sInt, sChar: its value *)
92 rval*: F64; (* sReal: its value *)
93 id*: INT; (* sIdent: its name *)
94 slen*: INT; (* sString: how many bytes *)
95 sbuf: [MaxStr + 1]U8; (* sString: its bytes, then a zero *)
96
97 (* The parser is skipping what it has read once already, after an
98 error, so slips in it aren't reported again. *)
99 skipping*: BOOL;
100
101 (* In arm64's code procedure, ! is a symbol, sNot, of a pre-index, as
102 in [sp, #-16]!, not a slip for not (A64.assemble) *)
103 bang: BOOL;
104
105 atCursor*: INT; (* the name the symbol at the cursor has *)
106 prefix*: []const U8; (* what is typed of the name at the cursor *)
107 word*: []const U8; (* the whole name at the cursor, as raz -q def asks of it *)
108 stdinPath: []const U8; (* the file whose text is standard input, or "" *)
109 cursorLine, cursorCol: INT; (* the cursor in it, from 1, or 0 for none *)
110
111 (* Whether a byte may be in a name: a letter, a digit or _. A table,
112 since the loop that reads a name asks it of every byte. *)
113 nameChar: [256]BOOL;
114
115 (* The symbol a byte is by itself, as + is, or sNull: a table, since
116 most symbols are of this kind and a match would test them one by one. *)
117 single: [256]Sym;
118
119 cur: State; (* buf .. f; tok, ival, rval and id live above *)
120
121 (* The name table: every distinct identifier once, found through an
122 open-addressed hash table. A name's bytes are in a chunk of memory
123 that is never moved, so that nameOf can hand out a slice of them. *)
124 chunk: ^U8; (* where names are put; chunkLeft bytes are left *)
125 chunkLeft: INT;
126 namePtr: ^NamePtr;
127 nameLen, nameHash: ^INT;
128 numNames, nameCap: INT;
129 table: ^INT; (* name + 1, or 0 for an empty slot *)
130 tableMask: INT;
131
132(* Exported variables can't be set from outside, so these do it. *)
133proc setSkipping*(yes: BOOL);
134begin
135 skipping := yes;
136end;
137
138proc setBang*(yes: BOOL);
139begin
140 bang := yes;
141end;
142
143(* The bytes of the string just read, without the zero after them *)
144proc strBytes*: []const U8;
145begin
146 return sbuf[0..slen];
147end;
148
149(* The string just read and the zero after it, for the code that makes a
150 chunk of it: an empty string has bytes to point at, though none to index *)
151proc strWithZero*: ^U8;
152begin
153 return SYSTEM.ADR(sbuf[0]);
154end;
155
156(* Memory, or the end of the compile when there is none *)
157proc grab*(size: INT): ^U8;
158var p: ^U8;
159begin
160 p := Mem.alloc(Heap.heap, size, 8);
161 if p = nil then Diag.fatal("out of memory"); end;
162 return p;
163end;
164
165(* p, which holds used bytes, moved to a block of size bytes *)
166proc regrab*(p: ^U8; used, size: INT): ^U8;
167var q: ^U8;
168begin
169 q := grab(size);
170 COPY(q[0..used], p[0..used]);
171 Mem.free(Heap.heap, p);
172 return q;
173end;
174
175(* n zeroed words *)
176proc words64(n: INT): ^INT;
177var p: ^INT; i: INT;
178begin
179 p := ^INT(grab(n * SIZE(INT)));
180 for i := 0 to n - 1 do p[i] := 0; end;
181 return p;
182end;
183
184(* Names *)
185
186proc hash(p: ^U8; n: INT): INT;
187var h: U32; i: INT;
188begin
189 h := 2166136261;
190 for i := 0 to n - 1 do h := (h xor U32(p[i])) * 16777619; end;
191 return INT(h & 7FFFFFFFH);
192end;
193
194(* A table twice the size, and room for twice the names *)
195proc grow;
196var i, n, j: INT; ptrs: ^NamePtr; lens, hashes: ^INT;
197begin
198 Mem.free(Heap.heap, ^U8(table));
199 tableMask := tableMask * 2 + 1;
200 table := words64(tableMask + 1);
201 for n := 0 to numNames - 1 do
202 i := nameHash[n] & tableMask;
203 while table[i] # 0 do i := (i + 1) & tableMask; end;
204 table[i] := n + 1;
205 end;
206 j := nameCap * 2;
207 ptrs := ^NamePtr(grab(j * SIZE(NamePtr)));
208 lens := ^INT(grab(j * SIZE(INT)));
209 hashes := ^INT(grab(j * SIZE(INT)));
210 for n := 0 to numNames - 1 do
211 ptrs[n] := namePtr[n];
212 lens[n] := nameLen[n];
213 hashes[n] := nameHash[n];
214 end;
215 Mem.free(Heap.heap, ^U8(namePtr));
216 Mem.free(Heap.heap, ^U8(nameLen));
217 Mem.free(Heap.heap, ^U8(nameHash));
218 namePtr := ptrs;
219 nameLen := lens;
220 nameHash := hashes;
221 nameCap := j;
222end;
223
224(* Whether the n bytes at p and at q are the same *)
225proc same(p, q: ^U8; n: INT): BOOL;
226var i: INT;
227begin
228 for i := 0 to n - 1 do
229 if p[i] # q[i] then return false; end;
230 end;
231 return true;
232end;
233
234(* The number of the name of the n bytes at p; a new name gets the next *)
235proc intern*(p: ^U8; n: INT): INT;
236var h, i, k: INT;
237begin
238 h := hash(p, n);
239 i := h & tableMask;
240 while table[i] # 0 do
241 k := table[i] - 1;
242 if (nameHash[k] = h) and (nameLen[k] = n) and same(namePtr[k], p, n) then
243 return k;
244 end;
245 i := (i + 1) & tableMask;
246 end;
247 if n > chunkLeft then
248 chunk := grab(PoolChunk);
249 chunkLeft := PoolChunk;
250 end;
251 COPY(chunk[0..n], p[0..n]);
252 k := numNames;
253 namePtr[k] := chunk;
254 nameLen[k] := n;
255 nameHash[k] := h;
256 chunk := chunk + n;
257 chunkLeft := chunkLeft - n;
258 INC(numNames);
259 table[i] := k + 1;
260 if numNames * 2 > tableMask then grow; end;
261 return k;
262end;
263
264(* The name n, which stays as it is *)
265proc nameOf*(n: INT): []const U8;
266begin
267 return namePtr[n][0..nameLen[n]];
268end;
269
270(* Errors *)
271
272(* The current symbol *)
273proc tokPos*: Diag.Pos;
274begin
275 return {f: cur.f, a: cur.tokPos, b: cur.pos};
276end;
277
278(* The place just after the symbol before the current one, where a
279 missing symbol belongs *)
280proc afterPrev*: Diag.Pos;
281begin
282 return {f: cur.f, a: cur.prevEnd, b: cur.prevEnd};
283end;
284
285(* Where to say a symbol is missing: at the current symbol, unless it
286 starts a later line than the symbol before it, which is more likely
287 where the missing one belongs *)
288proc missingPos*: Diag.Pos;
289var i: INT; p: Diag.Pos;
290begin
291 p := tokPos();
292 for i := cur.prevEnd to cur.tokPos - 1 do
293 if cur.buf[i] = '\n' then p := afterPrev(); end;
294 end;
295 return p;
296end;
297
298(* Whether a comment stands between the symbol before the current one
299 and it, which may put many lines between the two *)
300proc commentBetween*: BOOL;
301begin
302 return cur.commentEnd > cur.prevEnd;
303end;
304
305(* The end of a comment that closed just before byte a of the file
306 being read, with only blanks between, and true. A comment that
307 quotes the two characters that end one ends there, and what it went
308 on to say is read as code. *)
309proc commentClosed*(a: INT): (Diag.Pos, BOOL);
310var i: INT;
311begin
312 if (cur.commentEnd = 0) or (cur.commentEnd > a) then return {}, false; end;
313 for i := cur.commentEnd to a - 1 do
314 if (cur.buf[i] # ' ') and (cur.buf[i] # 9) then return {}, false; end;
315 end;
316 return {f: cur.f, a: cur.commentEnd - 2, b: cur.commentEnd}, true;
317end;
318
319(* Whether the string at the scanner has a \0 before a
320 digit, '0' to '7': where, and true. A zero byte and the digit are two
321 characters, but a C reader sees one octal escape. A raw string has no
322 escapes. *)
323proc zeroDigit*: (Diag.Pos, BOOL);
324var i: INT;
325begin
326 i := cur.tokPos;
327 if (cur.buf[i] # '"') and (cur.buf[i] # '\'') then return {}, false; end;
328 while i < cur.pos do
329 if cur.buf[i] # '\\' then
330 INC(i);
331 elsif (cur.buf[i + 1] = '0') and (cur.buf[i + 2] >= '0') and (cur.buf[i + 2] <= '7') then
332 return {f: cur.f, a: i, b: i + 3}, true;
333 else
334 INC(i, 2); (* an escape: the character after the backslash is not one *)
335 end;
336 end;
337 return {}, false;
338end;
339
340(* From the start of p to the end of the symbol before the current one:
341 the whole of a construct that has just been read *)
342proc spanFrom*(p: Diag.Pos): Diag.Pos;
343begin
344 p.b := cur.prevEnd;
345 return p;
346end;
347
348(* The same from a start that tokStart noted, which costs less than a
349 whole place: the parser notes one at every level of an expression *)
350proc tokStart*: INT;
351begin
352 return cur.tokPos;
353end;
354
355proc spanFromAt*(a: INT): Diag.Pos;
356begin
357 return {f: cur.f, a: a, b: cur.prevEnd};
358end;
359
360proc curLine*: INT;
361begin
362 return cur.tokLine;
363end;
364
365var
366 (* what lineCol found last, in file lcFile: byte lcAt is in line lcLine,
367 which starts at lcStart, at column lcCol. The next ask is likely
368 near it, as the places of the checks of a procedure are told in order,
369 and a line's statements come one after another. *)
370 lcFile, lcAt, lcLine, lcStart, lcCol: INT;
371
372(* The line and column of byte a of the file: counted from the place last
373 found, or the current symbol's, back or forward, so that it costs only
374 the distance. A column counts characters, as Diag's do. *)
375proc lineCol*(a: INT): (INT, INT);
376var i, line, start, col: INT;
377begin
378 if lcFile = cur.f then
379 line := lcLine;
380 start := lcStart;
381 i := lcAt;
382 col := lcCol;
383 else
384 line := cur.tokLine;
385 start := cur.tokLineStart;
386 i := start;
387 col := 1;
388 end;
389 if a < i then
390 (* before the place, back to the start of its line, or of the
391 line before until a is in it *)
392 i := start;
393 col := 1;
394 while a < start do
395 DEC(line);
396 DEC(start);
397 while (start > 0) and (cur.buf[start - 1] # '\n') do DEC(start); end;
398 end;
399 i := start;
400 end;
401 while i < a do
402 if cur.buf[i] = '\n' then
403 INC(line);
404 start := i + 1;
405 col := 1;
406 elsif (cur.buf[i] & 0C0H) # 80H then
407 INC(col);
408 end;
409 INC(i);
410 end;
411 lcFile := cur.f;
412 lcAt := a;
413 lcLine := line;
414 lcStart := start;
415 lcCol := col;
416 return line, col;
417end;
418
419(* The column of the current symbol: only its line's start to count
420 from, which the scanner noted *)
421proc curCol*: INT;
422var i, col: INT;
423begin
424 col := 1;
425 for i := cur.tokLineStart to cur.tokPos - 1 do
426 if (cur.buf[i] & 0C0H) # 80H then INC(col); end;
427 end;
428 return col;
429end;
430
431(* An error at p, shown: the parser returns Failed, which try passes up
432 to where it goes on. *)
433proc markAt*(p: Diag.Pos; msg: []const U8): ERROR;
434begin
435 Diag.error(p, msg);
436 return Failed;
437end;
438
439proc mark*(msg: []const U8): ERROR;
440begin
441 return markAt(tokPos(), msg);
442end;
443
444(* markAt, with a line of help after the message. *)
445proc markHelp*(p: Diag.Pos; msg, hint: []const U8): ERROR;
446begin
447 Diag.error(p, msg);
448 Diag.help(hint);
449 return Failed;
450end;
451
452(* An error in the text at bytes a to b of the file being read, which
453 stops the compiler: past it, the symbols can't be trusted. *)
454proc markBytes(a, b: INT; msg: []const U8);
455begin
456 Diag.setQuiet(false);
457 Diag.error({f: cur.f, a: a, b: b}, msg);
458 Diag.finish;
459end;
460
461proc lexError(msg: []const U8);
462begin
463 markBytes(cur.tokPos, cur.pos, msg);
464end;
465
466(* The n characters at the scanner are how another language writes t:
467 an error, but reading goes on as if t were written. *)
468proc slip(n: INT; t: Sym; msg: []const U8);
469begin
470 if not skipping then Diag.error({f: cur.f, a: cur.pos, b: cur.pos + n}, msg); end;
471 INC(cur.pos, n);
472 tok := t;
473end;
474
475(* How an operator or reserved word is written, quoted, for messages. *)
476proc symText*(s: Sym): []const U8;
477begin
478 if (s >= sPlus) and (s <= sBlank) then
479 return Diag.say("\"{}\"", [Fmt.str(ops[INT(s) - INT(sPlus)])]);
480 end;
481 return Diag.say("\"{}\"", [Fmt.str(words[INT(s) - INT(sAnd)])]);
482end;
483
484(* The current symbol, for "expected ..., found ...": a name as it is,
485 a literal by its kind, an operator or reserved word quoted. *)
486proc found*: []const U8;
487begin
488 match tok of
489 | sIdent: return nameOf(id);
490 | sInt: return "a number";
491 | sReal: return "a number";
492 | sChar: return "a character";
493 | sString: return "a string";
494 | sEof: return "the end of the file";
495 | else: return symText(tok);
496 end;
497end;
498
499(* The current symbol is the first on its line: at the top level of a
500 module, by the usual layout, so where reading can start again. *)
501proc atLineStart*: BOOL;
502begin
503 return cur.tokPos = cur.tokLineStart;
504end;
505
506(* The column the current symbol's line is indented to *)
507proc indent*: INT;
508var i: INT;
509begin
510 i := cur.tokLineStart;
511 while (cur.buf[i] = ' ') or (cur.buf[i] = '\t') do INC(i); end;
512 return i - cur.tokLineStart + 1;
513end;
514
515(* Files *)
516
517(* Name n is a reserved word *)
518proc reserved*(n: INT): BOOL;
519begin
520 return n < NumWords;
521end;
522
523(* raz -q: the text of the file at path is standard input, and the
524 cursor is at line and col there (bytes, from 1), or nowhere if 0 *)
525proc setStdin*(path: []const U8; line, col: INT);
526begin
527 stdinPath := path;
528 cursorLine := line;
529 cursorCol := col;
530end;
531
532(* Standard input, read whole; its length is the second result *)
533proc readStdin: (^U8, INT);
534var buf: ^U8; n, size, r: INT;
535begin
536 size := 65536;
537 buf := grab(size);
538 n := 0;
539 r := 1;
540 while r # 0 do
541 if n + 1 = size then
542 buf := regrab(buf, n, 2 * size);
543 size := 2 * size;
544 end;
545 r := Sys.read(Sys.stdin, buf[n..size - 1]);
546 if r > 0 then
547 n := n + r;
548 elsif (r < 0) and (r # Sys.errIntr) then
549 Diag.fatal("can't read standard input");
550 end;
551 end;
552 return buf, n;
553end;
554
555(* The byte of buf, n long, at line and col, both from 1; n if past it *)
556proc byteAt(buf: ^U8; n, line, col: INT): INT;
557var i, l: INT;
558begin
559 i := 0;
560 l := 1;
561 while (i < n) and (l < line) do
562 if buf[i] = '\n' then INC(l); end;
563 INC(i);
564 end;
565 if i + col - 1 < n then return i + col - 1; end;
566 return n;
567end;
568
569(* Reads the file at path to scan it; "" if it can, else why not *)
570proc open*(path: []const U8): []const U8;
571var fd, n, got, r, err: INT; info: Sys.Info;
572begin
573 cur.cursor := MAX(INT);
574 if (LEN(stdinPath) > 0) and (path = stdinPath) then
575 cur.buf, n := readStdin();
576 if cursorLine > 0 then cur.cursor := byteAt(cur.buf, n, cursorLine, cursorCol); end;
577 else
578 info, err := Sys.info(path);
579 if err = Sys.errNoEntry then return "there is no such file"; end;
580 if err = Sys.errDenied then return "permission denied"; end;
581 if err < 0 then return "it can't be opened"; end;
582 if not info.file then return "it isn't a file"; end;
583 fd := Sys.openRead(path);
584 if fd = Sys.errNoEntry then return "there is no such file"; end;
585 if fd = Sys.errDenied then return "permission denied"; end;
586 if fd < 0 then return "it can't be opened"; end;
587 n := INT(info.size);
588 cur.buf := grab(n + 1);
589 got := 0;
590 while got < n do
591 r := Sys.read(fd, cur.buf[got..n]);
592 if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end;
593 got := got + r;
594 end;
595 Sys.close(fd);
596 end;
597 cur.buf[n] := 0; (* the sentinel that ends every scan *)
598 cur.len := n;
599 cur.pos := 0;
600 cur.line := 1;
601 cur.lineStart := 0;
602 cur.tokPos := 0;
603 cur.tokLine := 1;
604 cur.tokLineStart := 0;
605 cur.f := Diag.addFile(path, cur.buf, n);
606 return "";
607end;
608
609proc saveScan*(var st: State);
610begin
611 st := cur;
612 st.tok := tok;
613 st.ival := ival;
614 st.rval := rval;
615 st.id := id;
616end;
617
618proc restoreScan*(st: State);
619begin
620 cur := st;
621 tok := st.tok;
622 ival := st.ival;
623 rval := st.rval;
624 id := st.id;
625end;
626
627(* UTF-8 *)
628
629(* Decodes the character at buf[pos], which is not ASCII, checking that
630 it is well formed; returns its code point and moves pos past it. *)
631proc utf8(var pos: INT): INT;
632var b0, b1, n, i, cp: INT; lo, hi: INT;
633begin
634 b0 := INT(cur.buf[pos]);
635 lo := 80H;
636 hi := 0BFH;
637 n := 0;
638 cp := 0;
639 match b0 of
640 | 0C2H..0DFH: n := 1; cp := b0 & 1FH;
641 | 0E0H: n := 2; lo := 0A0H;
642 | 0E1H..0ECH, 0EEH, 0EFH: n := 2; cp := b0 & 0FH;
643 | 0EDH: n := 2; cp := 0DH; hi := 9FH; (* no surrogates *)
644 | 0F0H: n := 3; lo := 90H;
645 | 0F1H..0F3H: n := 3; cp := b0 & 7;
646 | 0F4H: n := 3; cp := 4; hi := 8FH; (* up to 10FFFFH *)
647 | else:
648 cur.tokPos := pos;
649 lexError("invalid UTF-8");
650 end;
651 for i := 1 to n do
652 b1 := INT(cur.buf[pos + i]);
653 if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then
654 cur.tokPos := pos;
655 lexError("bad UTF-8");
656 end;
657 cp := cp shl 6 | (b1 & 3FH);
658 lo := 80H;
659 hi := 0BFH;
660 end;
661 pos := pos + n + 1;
662 return cp;
663end;
664
665proc put(b: INT);
666begin
667 if slen >= MaxStr then
668 lexError(Diag.say("a string holds at most {} bytes", [Fmt.int(MaxStr)]));
669 end;
670 sbuf[slen] := U8(b);
671 INC(slen);
672end;
673
674proc putUtf8(cp: INT);
675begin
676 if cp < 80H then
677 put(cp);
678 elsif cp < 800H then
679 put(0C0H | cp shr 6); put(80H | cp & 3FH);
680 elsif cp < 10000H then
681 put(0E0H | cp shr 12); put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH);
682 else
683 put(0F0H | cp shr 18); put(80H | cp shr 12 & 3FH);
684 put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH);
685 end;
686end;
687
688proc isDigit(c: U8): BOOL;
689begin
690 return (c >= '0') and (c <= '9');
691end;
692
693proc isLetter(c: U8): BOOL;
694begin
695 return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') or (c = '_');
696end;
697
698proc hexVal(c: U8): INT;
699begin
700 if isDigit(c) then return INT(c) - '0';
701 elsif (c >= 'A') and (c <= 'F') then return INT(c) - 'A' + 10;
702 elsif (c >= 'a') and (c <= 'f') then return INT(c) - 'a' + 10;
703 end;
704 return -1;
705end;
706
707(* The text of the file from byte a up to but not including b *)
708proc text(a, b: INT): []const U8;
709begin
710 return Diag.source({f: cur.f, a: a, b: b});
711end;
712
713(* One character of a character or string literal, at buf[pos]: its code
714 point, or for \xHH, minus one minus the byte. *)
715proc litChar(inString: BOOL): INT;
716var c: U8; v, d, n, esc, digits: INT;
717begin
718 c := cur.buf[cur.pos];
719 esc := cur.pos;
720 v := 0;
721 if c = '\\' then
722 INC(cur.pos);
723 c := cur.buf[cur.pos];
724 INC(cur.pos);
725 match c of
726 | 'n': v := 10;
727 | 't': v := 9;
728 | 'r': v := 13;
729 | '0': v := 0;
730 | '\\', '\'', '"': v := INT(c);
731 | 'x':
732 if not inString then markBytes(esc, cur.pos, "\\x is only for strings"); end;
733 d := hexVal(cur.buf[cur.pos]);
734 n := hexVal(cur.buf[cur.pos + 1]);
735 if (d < 0) or (n < 0) then markBytes(esc, cur.pos + 2, "\\x needs two hex digits"); end;
736 INC(cur.pos, 2);
737 v := -1 - (d * 16 + n);
738 | 'u':
739 if cur.buf[cur.pos] # '{' then markBytes(esc, cur.pos, "expected \"{\" after \\u"); end;
740 INC(cur.pos);
741 digits := cur.pos;
742 v := 0;
743 n := 0;
744 while hexVal(cur.buf[cur.pos]) >= 0 do
745 v := v * 16 + hexVal(cur.buf[cur.pos]);
746 INC(n);
747 INC(cur.pos);
748 if n > 6 then markBytes(esc, cur.pos, "a code point has at most 6 hex digits"); end;
749 end;
750 if (n = 0) or (cur.buf[cur.pos] # '}') then
751 markBytes(esc, cur.pos, "expected hex digits and \"}\" after \\u{");
752 end;
753 INC(cur.pos);
754 if (v > 10FFFFH) or (v >= 0D800H) and (v <= 0DFFFH) then
755 markBytes(esc, cur.pos, Diag.say("{} isn't a code point", [Fmt.str(text(digits, cur.pos - 1))]));
756 end;
757 | else:
758 markBytes(esc, cur.pos, Diag.say("unknown escape \\{}", [Fmt.char(c)]));
759 end;
760 elsif c >= 80H then
761 v := utf8(cur.pos);
762 elsif (c < ' ') or (c = 127) then
763 if inString then lexError("string not closed"); else lexError("character not closed"); end;
764 else
765 v := INT(c);
766 INC(cur.pos);
767 end;
768 return v;
769end;
770
771(* Symbols *)
772
773proc comment;
774var depth, open: INT; c: U8;
775begin
776 depth := 1;
777 open := cur.pos;
778 INC(cur.pos, 2);
779 repeat
780 c := cur.buf[cur.pos];
781 if c = 0 then
782 if cur.pos >= cur.len then markBytes(open, open + 2, "comment not closed"); end;
783 INC(cur.pos);
784 elsif (c = '(') and (cur.buf[cur.pos + 1] = '*') then
785 INC(depth);
786 INC(cur.pos, 2);
787 elsif (c = '*') and (cur.buf[cur.pos + 1] = ')') then
788 DEC(depth);
789 INC(cur.pos, 2);
790 elsif c = '\n' then
791 INC(cur.pos);
792 INC(cur.line);
793 cur.lineStart := cur.pos;
794 elsif c >= 80H then
795 _ := utf8(cur.pos);
796 else
797 INC(cur.pos);
798 end;
799 until depth = 0;
800 cur.commentEnd := cur.pos;
801 if (open < cur.cursor) and (cur.cursor < cur.pos) then cur.cursor := MAX(INT); end; (* no names in a comment *)
802end;
803
804(* Reading a decimal real exactly: the F64 nearest to digits times 10 to
805 an exponent, ties to the even one, which a library's reader doesn't
806 promise. The number is a fraction of two big integers, num / den,
807 scaled by 2^e until its whole part has 53 or 54 bits; that part and
808 the remainder give the bits and the rounding. *)
809type
810 Big = record
811 n: INT; (* words in use; 0 is zero *)
812 w: [96]U32; (* least significant first *)
813 end;
814(* 96 words, 3072 bits, are plenty: a string holds at most 255
815 digits, so readReal's den is at most 10^(330 + 255), about 2^1944,
816 and num below 10^310; the shift that follows makes the larger one at
817 most 54 bits longer than den, about 2000 bits in all. *)
818
819(* a := a * m + add *)
820proc bigMul(var a: Big; m, add: U32);
821var i: INT; c: U64;
822begin
823 c := U64(add);
824 for i := 0 to a.n - 1 do
825 c := U64(a.w[i]) * U64(m) + c;
826 a.w[i] := U32(c);
827 c := c shr 32;
828 end;
829 if c # 0 then
830 a.w[a.n] := U32(c);
831 INC(a.n);
832 end;
833end;
834
835proc bigShl(var a: Big; k: INT);
836var i, ws, bits: INT;
837begin
838 if a.n = 0 then return; end;
839 ws := k div 32;
840 bits := k mod 32;
841 a.w[a.n + ws] := 0;
842 for i := a.n - 1 to 0 by -1 do
843 if bits > 0 then a.w[i + ws + 1] := a.w[i + ws + 1] | (a.w[i] shr (32 - bits)); end;
844 a.w[i + ws] := a.w[i] shl bits;
845 end;
846 for i := 0 to ws - 1 do a.w[i] := 0; end;
847 INC(a.n, ws + 1);
848 while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
849end;
850
851proc bigShr1(var a: Big);
852var i: INT;
853begin
854 for i := 0 to a.n - 1 do
855 a.w[i] := a.w[i] shr 1;
856 if i + 1 < a.n then a.w[i] := a.w[i] | (a.w[i + 1] shl 31); end;
857 end;
858 while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
859end;
860
861(* -1, 0 or 1 as a is below, equal to or above b *)
862proc bigCmp(a, b: Big): INT;
863var i: INT;
864begin
865 if a.n # b.n then
866 if a.n > b.n then return 1; end;
867 return -1;
868 end;
869 for i := a.n - 1 to 0 by -1 do
870 if a.w[i] # b.w[i] then
871 if a.w[i] > b.w[i] then return 1; end;
872 return -1;
873 end;
874 end;
875 return 0;
876end;
877
878(* a := a - b, b not above a *)
879proc bigSub(var a: Big; b: Big);
880var i: INT; d: I64;
881begin
882 d := 0;
883 for i := 0 to a.n - 1 do
884 d := d + I64(a.w[i]);
885 if i < b.n then d := d - I64(b.w[i]); end;
886 a.w[i] := U32(d);
887 if d < 0 then d := -1; else d := 0; end; (* a borrow *)
888 end;
889 while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
890end;
891
892proc bigBits(a: Big): INT;
893var t: U32; bits: INT;
894begin
895 if a.n = 0 then return 0; end;
896 bits := (a.n - 1) * 32;
897 t := a.w[a.n - 1];
898 while t # 0 do
899 INC(bits);
900 t := t shr 1;
901 end;
902 return bits;
903end;
904
905(* s is digits, a point, digits, and maybe E, a sign and digits. False if
906 the value is past the largest F64; one below the smallest is 0. *)
907proc readReal(s: []const U8): (F64, BOOL);
908var
909 num, den, d: Big; i, digits, e, ex: INT; neg, half, sticky: BOOL;
910 q, b: U64; x: F64; bits: ^F64;
911begin
912 num.n := 0;
913 den.n := 1;
914 den.w[0] := 1;
915 digits := 0;
916 e := 0;
917 i := 0;
918 while (i < LEN(s)) and (s[i] # 'E') do
919 if s[i] = '.' then
920 e := 1;
921 else
922 bigMul(num, 10, U32(INT(s[i]) - '0'));
923 if num.n > 0 then INC(digits); end; (* counted from the first that isn't 0 *)
924 if e > 0 then INC(e); end;
925 end;
926 INC(i);
927 end;
928 if e > 0 then e := 1 - e; end; (* minus the digits after the point *)
929 ex := 0;
930 neg := false;
931 if i < LEN(s) then
932 INC(i);
933 neg := s[i] = '-';
934 if (s[i] = '+') or (s[i] = '-') then INC(i); end;
935 while i < LEN(s) do
936 if ex < 100000 then ex := ex * 10 + INT(s[i]) - '0'; end;
937 INC(i);
938 end;
939 end;
940 if neg then ex := -ex; end;
941 INC(e, ex);
942 x := 0.0;
943 if num.n = 0 then return x, true; end;
944 if digits + e > 310 then return x, false; end; (* 10^310 is past every F64 *)
945 if digits + e < -330 then return x, true; end; (* and 10^-330 below half the least *)
946 for i := 1 to e do bigMul(num, 10, 0); end;
947 for i := 1 to -e do bigMul(den, 10, 0); end;
948 (* num / den 2^-e from 2^52 to 2^54, but not past the least exponent *)
949 e := bigBits(num) - bigBits(den) - 53;
950 if e < -1074 then e := -1074; end;
951 if e < 0 then bigShl(num, -e); else bigShl(den, e); end;
952 (* q, its whole part, by long division; num is left the remainder *)
953 d := den;
954 bigShl(d, 53);
955 q := 0;
956 for i := 53 to 0 by -1 do
957 if bigCmp(num, d) >= 0 then
958 bigSub(num, d);
959 q := q | (U64(1) shl i);
960 end;
961 bigShr1(d);
962 end;
963 if q >= U64(1) shl 53 then (* a bit too many: it rounds *)
964 half := (q & 1) # 0;
965 sticky := num.n > 0;
966 q := q shr 1;
967 INC(e);
968 else (* the remainder against half of den *)
969 bigShl(num, 1);
970 i := bigCmp(num, den);
971 half := i >= 0;
972 sticky := i > 0;
973 end;
974 if half and (sticky or ((q & 1) # 0)) then
975 INC(q);
976 if q = U64(1) shl 53 then
977 q := q shr 1;
978 INC(e);
979 end;
980 end;
981 if e > 971 then return x, false; end;
982 if q >= U64(1) shl 52 then
983 b := U64(e + 1075) shl 52 | (q & (U64(1) shl 52 - 1));
984 else
985 b := q; (* below the least normal, e is -1074 *)
986 end;
987 bits := ^F64(SYSTEM.ADR(b));
988 return bits^, true;
989end;
990
991proc number;
992var start, i, d: INT; allDec, ok: BOOL; v: U64;
993begin
994 start := cur.pos;
995 allDec := true;
996 while isDigit(cur.buf[cur.pos]) or (cur.buf[cur.pos] >= 'A') and (cur.buf[cur.pos] <= 'F') do
997 if cur.buf[cur.pos] > '9' then allDec := false; end;
998 INC(cur.pos);
999 end;
1000 if cur.buf[cur.pos] = 'H' then
1001 v := 0;
1002 for i := start to cur.pos - 1 do
1003 if v shr 60 # 0 then lexError(Diag.say("{} is too big for U64", [Fmt.str(text(start, cur.pos))])); end;
1004 v := v * 16 + U64(hexVal(cur.buf[i]));
1005 end;
1006 INC(cur.pos);
1007 tok := sInt;
1008 ival := I64(v); (* 16 digits are the bits of a 64-bit word *)
1009 elsif (cur.buf[cur.pos] = '.') and isDigit(cur.buf[cur.pos + 1]) then
1010 if not allDec then lexError("a decimal number has only the digits 0 to 9"); end;
1011 INC(cur.pos);
1012 while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end;
1013 if cur.buf[cur.pos] = 'E' then
1014 INC(cur.pos);
1015 if (cur.buf[cur.pos] = '+') or (cur.buf[cur.pos] = '-') then INC(cur.pos); end;
1016 if not isDigit(cur.buf[cur.pos]) then lexError("expected a digit in the exponent"); end;
1017 while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end;
1018 end;
1019 if cur.pos - start > 255 then lexError("a number has at most 255 characters"); end;
1020 rval, ok := readReal(cur.buf[start..cur.pos]);
1021 if not ok then lexError(Diag.say("{} is out of the range of F64", [Fmt.str(text(start, cur.pos))])); end;
1022 tok := sReal;
1023 else
1024 if not allDec then lexError("a hex number ends with H"); end;
1025 v := 0;
1026 for i := start to cur.pos - 1 do
1027 d := INT(cur.buf[i]) - '0';
1028 if v > (U64(9223372036854775807) - U64(d)) div 10 then
1029 lexError(Diag.say("{} is too big for I64", [Fmt.str(text(start, cur.pos))]));
1030 end;
1031 v := v * 10 + U64(d);
1032 end;
1033 tok := sInt;
1034 ival := I64(v);
1035 end;
1036 if nameChar[cur.buf[cur.pos]] then
1037 lexError("a name can't start with a digit");
1038 end;
1039end;
1040
1041(* A raw string, between backquotes (report, section 2): its bytes as
1042 they stand, with no escapes, over as many lines as it runs; carriage
1043 returns are left out. It is indented if the opening backquote ends
1044 its line and the closing one has only blanks before it: the lines
1045 between are its text, each without those blanks at its start. So
1046
1047 Out.str(`
1048 a
1049 b
1050 `);
1051
1052 is "a\n b\n". The text is read twice: to the closing backquote,
1053 for its blanks, then line by line into sbuf. *)
1054proc rawString;
1055var p, close, last, q, i, j: INT; c: U8; indented: BOOL;
1056begin
1057 INC(cur.pos);
1058 p := cur.pos;
1059 while cur.buf[cur.pos] # '`' do
1060 c := cur.buf[cur.pos];
1061 if c = 0 then
1062 if cur.pos >= cur.len then markBytes(cur.tokPos, cur.tokPos + 1, "string not closed"); end;
1063 markBytes(cur.pos, cur.pos + 1, "NUL byte in the text");
1064 elsif c >= 80H then
1065 _ := utf8(cur.pos);
1066 else
1067 if c = '\n' then INC(cur.line); cur.lineStart := cur.pos + 1; end;
1068 INC(cur.pos);
1069 end;
1070 end;
1071 close := cur.pos;
1072 q := close; (* where the blanks before the closing backquote start *)
1073 while (q > p) and ((cur.buf[q - 1] = ' ') or (cur.buf[q - 1] = '\t')) do DEC(q); end;
1074 i := p;
1075 if cur.buf[i] = '\r' then INC(i); end;
1076 indented := (cur.buf[i] = '\n') and (q > i) and (cur.buf[q - 1] = '\n');
1077 if indented then INC(i); last := q; else i := p; last := close; end;
1078 slen := 0;
1079 while i < last do
1080 (* i is where a line starts *)
1081 if indented then
1082 j := i;
1083 while (cur.buf[j] = ' ') or (cur.buf[j] = '\t') do INC(j); end;
1084 if (cur.buf[j] = '\n') or (cur.buf[j] = '\r') then
1085 i := j; (* only blanks: an empty line *)
1086 elsif (j - i < close - q) or (cur.buf[i..i + close - q] # cur.buf[q..close]) then
1087 markBytes(i, j + 1, "this line doesn't start with the blanks before the closing backquote");
1088 else
1089 i := i + close - q;
1090 end;
1091 end;
1092 repeat
1093 c := cur.buf[i];
1094 INC(i);
1095 if c # '\r' then put(INT(c)); end;
1096 until (c = '\n') or (i >= last);
1097 end;
1098 cur.pos := close + 1;
1099 sbuf[slen] := 0;
1100 tok := sString;
1101end;
1102
1103(* Makes the current symbol the name at the cursor, typed from start up
1104 to at, and written whole up to stop; the cursor is passed then *)
1105proc cursorName(start, at, stop: INT);
1106begin
1107 prefix := cur.buf[start..at];
1108 word := cur.buf[start..stop];
1109 cur.cursor := MAX(INT);
1110 tok := sIdent;
1111 id := atCursor;
1112end;
1113
1114(* Reads the next symbol *)
1115proc next*;
1116var c: U8; start, h, v, i, p: INT; buf: ^U8;
1117begin
1118 (* the position and the text are kept in variables, in registers,
1119 while the loops run: cur is in memory, and each step through it
1120 waits for the one before *)
1121 buf := cur.buf;
1122 p := cur.pos;
1123 cur.prevEnd := p;
1124 repeat
1125 c := buf[p];
1126 while (c = ' ') or (c = '\t') or (c = '\r') or (c = '\n') do
1127 if c = '\n' then
1128 INC(cur.line);
1129 cur.lineStart := p + 1;
1130 end;
1131 INC(p);
1132 c := buf[p];
1133 end;
1134 if (c = '(') and (buf[p + 1] = '*') then
1135 cur.pos := p;
1136 comment;
1137 p := cur.pos;
1138 c := ' ';
1139 end;
1140 until c # ' ';
1141 cur.pos := p;
1142 cur.tokPos := p;
1143 cur.tokLine := cur.line;
1144 cur.tokLineStart := cur.lineStart;
1145 if p >= cur.cursor then
1146 (* the cursor is before this symbol: if it was between symbols, not
1147 in a string or a comment, a name of nothing typed is made there;
1148 at the start of a name, the name is the cursor's, read below *)
1149 if (p = cur.cursor) and (isLetter(c) or (c = '_')) then
1150 (* the name's own branch makes it *)
1151 elsif cur.prevEnd <= cur.cursor then
1152 cursorName(cur.cursor, cur.cursor, cur.cursor);
1153 return;
1154 else
1155 cur.cursor := MAX(INT);
1156 end;
1157 end;
1158 if single[c] # sNull then
1159 INC(cur.pos);
1160 tok := single[c];
1161 return;
1162 end;
1163 match c of
1164 | 'A'..'Z', 'a'..'z', '_':
1165 start := p;
1166 repeat INC(p); until not nameChar[buf[p]];
1167 cur.pos := p;
1168 if p >= cur.cursor then (* the name the cursor is in or just after *)
1169 cursorName(start, cur.cursor, p);
1170 return;
1171 end;
1172 if p - start > MaxIdent then
1173 lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)]));
1174 end;
1175 h := intern(buf + start, p - start);
1176 if (p - start = 1) and (c = '_') then
1177 tok := sBlank;
1178 elsif h < NumWords then
1179 tok := Sym(INT(sAnd) + h);
1180 else
1181 tok := sIdent;
1182 id := h;
1183 end;
1184 | '0'..'9': number;
1185 | '\'':
1186 INC(cur.pos);
1187 if cur.buf[cur.pos] = '\'' then lexError("empty character"); end;
1188 v := litChar(false);
1189 if cur.buf[cur.pos] # '\'' then
1190 (* 'ab': several characters, as some languages write a string *)
1191 i := cur.pos;
1192 while (cur.buf[i] # '\'') and (cur.buf[i] # '\n') and (cur.buf[i] # 0) do INC(i); end;
1193 if cur.buf[i] = '\'' then
1194 markBytes(cur.tokPos, i + 1,
1195 Diag.say("a character is one character: the string is \"{}\"", [Fmt.str(text(cur.tokPos + 1, i))]));
1196 else
1197 lexError("character not closed");
1198 end;
1199 end;
1200 INC(cur.pos);
1201 tok := sChar;
1202 ival := I64(v);
1203 | '"':
1204 INC(cur.pos);
1205 slen := 0;
1206 while cur.buf[cur.pos] # '"' do
1207 v := litChar(true);
1208 if v < 0 then put(-1 - v); else putUtf8(v); end;
1209 end;
1210 INC(cur.pos);
1211 sbuf[slen] := 0;
1212 tok := sString;
1213 | '`': rawString;
1214 | '=':
1215 if cur.buf[cur.pos + 1] = '=' then
1216 slip(2, sEql, "comparing is written =, not ==");
1217 else
1218 INC(cur.pos);
1219 tok := sEql;
1220 end;
1221 | '&':
1222 if cur.buf[cur.pos + 1] = '&' then
1223 slip(2, sAnd, "\"and\" is written and, not &&");
1224 else
1225 INC(cur.pos);
1226 tok := sAmp;
1227 end;
1228 | '<':
1229 INC(cur.pos);
1230 if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sLeq; else tok := sLss; end;
1231 | '>':
1232 INC(cur.pos);
1233 if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sGeq; else tok := sGtr; end;
1234 | ':':
1235 INC(cur.pos);
1236 if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sBecomes; else tok := sColon; end;
1237 | '.':
1238 INC(cur.pos);
1239 if cur.buf[cur.pos] = '.' then
1240 INC(cur.pos);
1241 if cur.buf[cur.pos] = '.' then INC(cur.pos); tok := sEllipsis; else tok := sUpto; end;
1242 else
1243 tok := sPeriod;
1244 end;
1245 | '|':
1246 if cur.buf[cur.pos + 1] = '|' then
1247 slip(2, sOr, "\"or\" is written or, not ||");
1248 else
1249 INC(cur.pos);
1250 tok := sBar;
1251 end;
1252 | '!':
1253 if bang then
1254 INC(cur.pos);
1255 tok := sNot;
1256 elsif cur.buf[cur.pos + 1] = '=' then
1257 slip(2, sNeq, "\"not equal\" is written #, not !=");
1258 else
1259 slip(1, sNot, "\"not\" is written not, not !");
1260 end;
1261 | 0:
1262 if cur.pos < cur.len then markBytes(cur.pos, cur.pos + 1, "NUL byte in the text"); end;
1263 tok := sEof;
1264 | else:
1265 if c >= 80H then lexError("only ASCII outside strings, characters and comments"); end;
1266 markBytes(cur.pos, cur.pos + 1, Diag.say("unexpected character \"{}\"", [Fmt.char(c)]));
1267 end;
1268end;
1269
1270var i: INT;
1271
1272begin
1273 for i := 0 to 255 do nameChar[i] := isLetter(U8(i)) or isDigit(U8(i)); end;
1274 for i := 0 to NumOps - 1 do
1275 if (LEN(ops[i]) = 1) and (Str.find(alone, ops[i]) >= 0) then
1276 single[ops[i][0]] := Sym(INT(sPlus) + i);
1277 end;
1278 end;
1279 chunkLeft := 0;
1280 nameCap := 1 shl 12;
1281 namePtr := ^NamePtr(grab(nameCap * SIZE(NamePtr)));
1282 nameLen := ^INT(grab(nameCap * SIZE(INT)));
1283 nameHash := ^INT(grab(nameCap * SIZE(INT)));
1284 tableMask := 2 * nameCap - 1;
1285 table := words64(tableMask + 1);
1286 for i := 0 to NumWords - 1 do _ := intern(SYSTEM.PTR(words[i]), LEN(words[i])); end;
1287 atCursor := intern(SYSTEM.PTR("(cursor)"), 8); (* no name can be written so *)
1288end Scan.