raz / commit 7797fa8a

commit
7797fa8aa8a68a6407c73e04f4b7ed2552dce0c3
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
52396b00
Self step 4: Parse and Raz in raz, the first compiler that builds

self/Parse.raz and self/Raz.raz: the parser and the command line. The seed's
longjmp recovery is an ERROR passed up by try to the statement or declaration
that is the recovery point. check.sh has the seed's and this compiler compile
the library, examples, tools, self/, every test of test/ and conform/ and the
348,025-line benchmark, and compares executables, messages and status: 409
files, none differ. 452,000 lines a second against the seed's 815,000.
Mended on the way: Item.makeStr stopped on an empty string; ItemDump.raz was
not formatted. README and PLAN say what the port found.

patch · log

9 files changed, +4183 -12

PLAN.md (history) modified +7 -3

@@ -35,7 +35,10 @@
3535 3. `gen` (3a, done: `Gen.raz`, tested by `test/GenDump`, a script of
3636 calls whose bytes and listing are the same), `item` (3b, done: `Item.raz`, tested by
3737 `test/ItemDump`, 60 scripts of operations with mistakes in them).
38-4. `parse`, `raz`: the first compiler that builds.
38+4. `parse`, `raz` (done: `Parse.raz`, `Raz.raz`): the first compiler that
39+ builds, tested by compiling 409 programs, the library and the compiler
40+ itself with both and comparing the executables, messages and status;
41+ 452,000 lines a second, the seed's 815,000.
3942 5. Fixpoint: the seed builds `self`, that builds `self`, that builds
4043 `self` again, and the last two are byte for byte the same. Then
4144 the seed's last tag is the bootstrap, and the split of `src/` from
@@ -88,5 +91,6 @@
8891 may not change `x` (nor take its address), so the caller may pass the
8992 address of a record or array without a copy, and the program means the
9093 same. Met in Self step 3b, where the seed's `const x: TItem` (about 130
91- bytes) became a value parameter, copied at every call. Not measured
92- yet; the speed test of Self step 4 will say what it costs.
94+ bytes) became a value parameter, copied at every call. Measured in Self
95+ step 4: not what stands out, the compiler's profile is flat
96+ (`Scan.tokPos` is 9%).

self/Item.raz modified +1 -1

@@ -174,7 +174,7 @@
174174 x.typ := Sym.tStr;
175175 x.val := Scan.slen;
176176 x.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1);
177- Chunk.setData(x.chunk, ADR(Scan.strBytes()[0]), Scan.slen + 1, 1);
177+ Chunk.setData(x.chunk, Scan.strWithZero(), Scan.slen + 1, 1);
178178 end;
179179
180180 proc frameAdr*(off: I64): Gen.Adr;

self/Parse.raz added +3775 -0

@@ -0,0 +1,3775 @@
1+(* Parse: the parser.
2+
3+ Reads modules by recursive descent and has Gen emit code as it goes:
4+ one pass, no tree. Importing a module that isn't compiled yet
5+ compiles it there and then, so modules are finished in an order where
6+ each comes after the modules it imports; that is the order in which
7+ their bodies run.
8+
9+ A module may come in one file per target (Name.linux-x86_64.raz and
10+ so on). The file for this target is compiled; the others beside it
11+ are read for their declarations only, and must export the same
12+ interface.
13+
14+ Depends on: Scan, Sym, Chunk for data, Item and Gen for code.
15+ Leaves out: linking; a module only records the libraries it names,
16+ and whether it uses C or says link static.
17+
18+ The seed's errors ended in a jump back to the statement or
19+ declaration being read (Scan.mark, longjmp). Here every routine that
20+ can find an error returns an ERROR as its last result, and the ones
21+ that call it pass it up with try, as Item does; the statement or
22+ declaration that is a recovery point (guard) looks at what comes back
23+ and reads on. What has been made by then is what the seed had made
24+ when it jumped. A seed `var` that only gave a value back is a result
25+ where that is shorter; the others stay as they were. A set of
26+ Scan.Sym is a chain of tests, since it has more names than a set
27+ holds. *)
28+module Parse;
29+import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap;
30+
31+type
32+ PType = ^Sym.Type;
33+ PObj = ^Sym.Obj;
34+ PModule = ^Sym.Module;
35+ TItem = Item.Item;
36+
37+ (* The innermost loop: the chain of its breaks and the deferred
38+ statements in force outside it *)
39+ Loop = record
40+ brk: INT;
41+ base: INT;
42+ end;
43+ PLoop = ^Loop;
44+
45+ (* A generic module's import whose instance isn't made yet (deferred,
46+ numDeferred); not to be confused with a defer statement (defers) *)
47+ Deferred = record
48+ o: PObj; (* the name it imports as *)
49+ home: PModule; (* the module that imports it *)
50+ mname: INT; (* the generic module *)
51+ args: Scan.State; (* at the "(" of its arguments *)
52+ at: Diag.Pos; (* the import *)
53+ end;
54+
55+const
56+ (* Whether the target has reals (report, appendix A): x86-64 always has
57+ SSE2. Without them, used code that computes with one is an error,
58+ which Raz reports once it knows what the program uses. *)
59+ HasReals* = true;
60+
61+ MaxNames = 64; (* names in one declaration, and the like *)
62+ MaxFwd = 256; (* pointers to types not yet declared *)
63+ MaxDefers = 64; (* defer statements in force *)
64+ MaxDrops = 4096; (* calls that drop results, in one module *)
65+ MaxDeferred = 64; (* generic imports not yet made *)
66+ MaxLabels = 1024; (* labels of one match *)
67+ MaxElements = 1024; (* elements of an array literal *)
68+ MaxFixes = 4096; (* addresses in one constant *)
69+ MaxPending = 64; (* modules being compiled at once *)
70+ Suffixes: [4][]U8 = [".linux-x86_64", ".linux", ".x86_64", ""];
71+
72+var
73+ libDir*, mainDir: []U8;
74+ incDirs*: [16][]U8;
75+ numInc*: INT;
76+ firstModule*, lastModule*: PModule; (* in the order they were finished *)
77+
78+ checkMode: BOOL; (* reading a file only for its interface *)
79+ inTypes: BOOL; (* in a type section: ^T may name a later type *)
80+ fwdTypes: [MaxFwd]PType;
81+ fwdPos: [MaxFwd]Diag.Pos; (* where each names its type *)
82+ numFwd: INT;
83+ lastCalled: PObj; (* the procedure the last call was of, if it had a name *)
84+ passOn: BOOL; (* the next factor may be a call with several results, for return *)
85+ curProc: PObj; (* the procedure being compiled, or nil *)
86+ declExported: BOOL; (* the export mark of the declaration being read *)
87+ curLoop: PLoop; (* the innermost loop, or nil *)
88+ defers: [MaxDefers]INT; (* the defer statements in force, their code's addresses *)
89+ numDefers: INT;
90+ deferring: BOOL; (* compiling a defer statement's statement *)
91+ directDefer: BOOL; (* ... as the statement itself, not in a list *)
92+ deferSlot: I64; (* keeps a result while deferred statements run *)
93+ curResult: PType; (* the result type of the procedure being compiled *)
94+ inExtern: BOOL; (* reading an extern's signature: ... allowed *)
95+ tArgv, tBodySig: PType;
96+ nameRt, nameFail, nameBody, nameStatic, nameCheck, nameOff, nameAdr: INT;
97+ declaring: [MaxNames]INT; (* the names the declaration being read declares *)
98+ numDeclaring: INT;
99+ skipped: BOOL; (* the last statement had an error and was skipped *)
100+ deferred: [MaxDeferred]Deferred; (* generic imports not yet made, not defer statements *)
101+ numDeferred: INT;
102+ making: BOOL; (* reading an instance's arguments, at its first use *)
103+ stray: BOOL; (* an "end" in this procedure stood left of its statement's line *)
104+ strayAt: Diag.Pos; (* ... the first such statement *)
105+ elseIf: BOOL; (* an "else if" in this procedure *)
106+ drops: [MaxDrops]record
107+ at: Diag.Pos; (* a call standing on its own that drops results *)
108+ n: INT; (* ... how many *)
109+ end;
110+ numDrops: INT; (* the module being compiled has those from its
111+ first one, saved by compileFile, to here *)
112+ ends: BOOL; (* the statements just read never go on past
113+ their end: each way through them returns *)
114+ useAt: Diag.Pos; (* ... which is here *)
115+ guards: INT; (* the recovery points open *)
116+
117+proc expression(var x: TItem; want: PType): ERROR; forward;
118+proc parseType: (PType, ERROR); forward;
119+proc statements: ERROR; forward;
120+proc statement: ERROR; forward;
121+
122+(* Little helpers *)
123+
124+proc setLibDir*(dir: []U8);
125+begin
126+ libDir := dir;
127+end;
128+
129+proc addIncDir*(dir: []U8);
130+begin
131+ incDirs[numInc] := dir;
132+ INC(numInc);
133+end;
134+
135+proc nameOf(n: INT): []U8;
136+begin
137+ return Scan.nameOf(n);
138+end;
139+
140+(* The name number of s, which isn't empty *)
141+proc internName(s: []U8): INT;
142+begin
143+ return Scan.intern(ADR(s[0]), LEN(s));
144+end;
145+
146+proc say1(f, a: []U8): []U8;
147+begin
148+ return Diag.say(f, [Fmt.str(a)]);
149+end;
150+
151+proc say2(f, a, b: []U8): []U8;
152+begin
153+ return Diag.say(f, [Fmt.str(a), Fmt.str(b)]);
154+end;
155+
156+proc say3(f, a, b, c: []U8): []U8;
157+begin
158+ return Diag.say(f, [Fmt.str(a), Fmt.str(b), Fmt.str(c)]);
159+end;
160+
161+(* More than n of what, as a message *)
162+proc tooMany(n: INT; what: []U8): []U8;
163+begin
164+ return Diag.say("more than {} {}", [Fmt.int(n), Fmt.str(what)]);
165+end;
166+
167+(* A missing symbol is reported just after the one before it. *)
168+proc expected(what: []U8): ERROR;
169+begin
170+ if Scan.tok = Scan.sBlank then
171+ return Scan.mark("_ isn't a name: it is the blank, which stands only left of :=");
172+ end;
173+ return Scan.markAt(Scan.missingPos(), say2("expected {}, found {}", what, Scan.found()));
174+end;
175+
176+proc expect(s: Scan.Sym): ERROR;
177+begin
178+ if (Scan.tok = Scan.sLbrace) and ((s = Scan.sThen) or (s = Scan.sDo)) then
179+ return Scan.markHelp(Scan.missingPos(), say2("expected {}, found {}", Scan.symText(s), Scan.found()),
180+ say1("a block is written {} ... end", Scan.symText(s)));
181+ end;
182+ if Scan.tok # s then return expected(Scan.symText(s)); end;
183+ Scan.next;
184+ return nil;
185+end;
186+
187+(* The end of a block statement at start, whose line is indented to
188+ ind. An "end" left of that was most likely meant for a block around
189+ the statement, which leaves the statement's own "end" missing: the
190+ first such is kept for endMissing. *)
191+proc closeEnd(start: Diag.Pos; ind: INT): ERROR;
192+begin
193+ if (Scan.tok = Scan.sEnd) and not stray and (Scan.indent() < ind) then
194+ stray := true;
195+ strayAt := start;
196+ end;
197+ return expect(Scan.sEnd);
198+end;
199+
200+(* The error of a procedure or module whose own "end" isn't where it
201+ should be, with what closeEnd saw *)
202+proc endMissing(p: Diag.Pos; msg: []U8): ERROR;
203+begin
204+ Diag.error(p, msg);
205+ if stray then Diag.note(strayAt, "is this statement's \"end\" missing? one further left closes it"); end;
206+ if elseIf then Diag.help("raz writes elsif: \"else if\" begins an if that needs its own \"end\""); end;
207+ return Scan.Failed;
208+end;
209+
210+(* A name being declared, and whether it is exported; at is the name *)
211+proc identDef(var n: INT; var exp: BOOL; var at: Diag.Pos): ERROR;
212+begin
213+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
214+ n := Scan.id;
215+ at := Scan.tokPos();
216+ Scan.next;
217+ exp := false;
218+ if Scan.tok = Scan.sTimes then
219+ exp := true;
220+ Scan.next;
221+ end;
222+ return nil;
223+end;
224+
225+(* Declares o in the innermost scope. Its module keeps its declarations
226+ in order: its own, for the interface check, and its procedures', to
227+ warn of those never used. *)
228+proc declare(o: PObj): ERROR;
229+var m: PModule;
230+begin
231+ m := Sym.curModule;
232+ try Sym.insert(o, Sym.topScope());
233+ if Sym.topScope() = m^.scope then
234+ if m^.last = nil then m^.first := o; else m^.last^.chain := o; end;
235+ m^.last := o;
236+ else
237+ if m^.lastLocal = nil then m^.locals := o; else m^.lastLocal^.chain := o; end;
238+ m^.lastLocal := o;
239+ end;
240+ return nil;
241+end;
242+
243+(* o is named: a procedure naming itself doesn't count *)
244+proc named(o: PObj);
245+begin
246+ if o # curProc then
247+ o^.used := true;
248+ o^.read := true;
249+ end;
250+end;
251+
252+(* Recovery
253+
254+ After an error the parser goes on with the next statement or
255+ declaration, so that one run reports every error. Each statement and
256+ declaration is a recovery point: it notes the state of the scanner
257+ and the parser where it starts, and when what it read comes back with
258+ an error, the state is put back, the scanner reads the construct
259+ again from its start, skipping to its end, and the parser carries on
260+ after it. Nothing is generated after an error, so the code half made
261+ for the construct does no harm. A name that isn't declared is
262+ declared where it is used, with type tPoison, and what follows from
263+ it is not reported again; so are the names of a declaration that had
264+ an error.
265+
266+ Skipping counts the words that open and close blocks. A symbol at
267+ the start of a line is taken to start a declaration of the module,
268+ as layout has it: a statement skipped up to one gives up its
269+ procedure, and the procedure is skipped up to its end. *)
270+
271+type
272+ Recover = record
273+ scan: Scan.State;
274+ scopes, depth, pushed, numDefers: INT;
275+ guards: INT;
276+ loop: PLoop;
277+ result: PType;
278+ deferring, directDefer, quiet: BOOL;
279+ end;
280+
281+proc guard(var r: Recover);
282+begin
283+ Scan.saveScan(r.scan);
284+ r.guards := guards;
285+ r.scopes := Sym.scopeDepth(); r.depth := Gen.depth; r.pushed := Gen.pushed; r.numDefers := numDefers;
286+ r.loop := curLoop; r.result := curResult;
287+ r.deferring := deferring; r.directDefer := directDefer; r.quiet := Diag.quiet;
288+ INC(guards);
289+ Diag.setQuiet(false);
290+end;
291+
292+proc unguard(var r: Recover);
293+begin
294+ guards := r.guards;
295+ Diag.setQuiet(r.quiet);
296+ Scan.setSkipping(false);
297+end;
298+
299+(* After an error: the state as it was at the start of r's construct,
300+ whose first symbol is again the current one *)
301+proc restore(var r: Recover);
302+begin
303+ Scan.restoreScan(r.scan);
304+ Scan.setSkipping(true);
305+ Sym.cutScopes(r.scopes);
306+ Gen.resetStack(r.depth, r.pushed);
307+ numDefers := r.numDefers;
308+ curLoop := r.loop; curResult := r.result;
309+ deferring := r.deferring; directDefer := r.directDefer;
310+ inTypes := false; declExported := false; inExtern := false; making := false;
311+end;
312+
313+(* Gives up the construct r is for, and the one around it: the error
314+ goes on up to the next recovery point, or ends the compile if there
315+ is none *)
316+proc giveUp(var r: Recover): ERROR;
317+begin
318+ unguard(r);
319+ if guards = 0 then Diag.finish(); end;
320+ return Scan.Failed;
321+end;
322+
323+(* Reads to the end of a statement or declaration, from its first
324+ symbol: up to the ";" that ends it, not read, or to the "end",
325+ "else", "elsif", "until" or "|" of the statement around it (an arm's
326+ "|" comes after a ";", the operator's after an operand). False if it
327+ stopped at a symbol that starts a line, or the end of the file. *)
328+proc skipConstruct: BOOL;
329+var d, p: INT; prev: Scan.Sym;
330+begin
331+ d := 0; p := 0; prev := Scan.sSemicolon;
332+ repeat
333+ match Scan.tok of
334+ | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d);
335+ | sEnd, sUntil:
336+ if d = 0 then return true; end;
337+ DEC(d);
338+ | sElse, sElsif: if (d = 0) and (p = 0) then return true; end;
339+ | sBar: if (d = 0) and (p = 0) and (prev = Scan.sSemicolon) then return true; end;
340+ | sLparen, sLbrak, sLbrace: INC(p);
341+ | sRparen, sRbrak, sRbrace: if p > 0 then DEC(p); end;
342+ | sSemicolon: if (d = 0) and (p = 0) then return true; end;
343+ | sEof: return false;
344+ | else:
345+ end;
346+ prev := Scan.tok;
347+ Scan.next;
348+ until Scan.atLineStart();
349+ return false;
350+end;
351+
352+(* Declares n where it is used, after it was reported as not declared,
353+ or after the declaration of it had an error *)
354+proc poison(n: INT);
355+var o: PObj;
356+begin
357+ o := Sym.newObj(Sym.oConst, n, Sym.tPoison);
358+ _ := Sym.insert(o, Sym.topScope()); (* n isn't in this scope, so it can't be twice *)
359+end;
360+
361+proc willDeclare(n: INT);
362+begin
363+ if numDeclaring < MaxNames then declaring[numDeclaring] := n; end;
364+ INC(numDeclaring);
365+end;
366+
367+(* After a declaration had an error: its names are poison, and reading
368+ goes on after it *)
369+proc skipDeclaration;
370+var i: INT;
371+begin
372+ for i := 0 to numDeclaring - 1 do
373+ if (i < MaxNames) and (Sym.find(Sym.topScope(), declaring[i]) = nil) then
374+ poison(declaring[i]);
375+ end;
376+ end;
377+ if skipConstruct() and (Scan.tok = Scan.sSemicolon) then Scan.next; end;
378+end;
379+
380+proc constValue(var x: TItem): (I64, ERROR);
381+begin
382+ if x.mode # Item.mConst then return 0, Scan.markAt(x.pos, "expected a constant"); end;
383+ return x.val, nil;
384+end;
385+
386+proc constExpr: (I64, ERROR);
387+var x: TItem;
388+begin
389+ try expression(x, nil);
390+ if not Sym.isInt(x.typ) then
391+ return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x)));
392+ end;
393+ return constValue(x);
394+end;
395+
396+(* Help after a name that isn't found: o, the closest name in reach *)
397+proc didYouMean(o: PObj);
398+begin
399+ if o # nil then Diag.help(say1("did you mean {}?", nameOf(o^.name))); end;
400+end;
401+
402+(* Where module n is found, if it is: dir and the file in it *)
403+proc moduleFile(n: INT): ([]U8, []U8, BOOL); forward;
404+
405+(* name in lower case, in memory that is never freed, as messages are *)
406+proc lowerCase(s: []U8): []U8;
407+var p: ^U8; i: INT;
408+begin
409+ if LEN(s) = 0 then return ""; end;
410+ p := Scan.grab(LEN(s));
411+ for i := 0 to LEN(s) - 1 do
412+ if (s[i] >= 'A') and (s[i] <= 'Z') then p[i] := s[i] + 32; else p[i] := s[i]; end;
413+ end;
414+ return p[0..LEN(s)];
415+end;
416+
417+(* Reports name n at p as not declared, with what it may have meant *)
418+proc notDeclared(p: Diag.Pos; n: INT);
419+var found: BOOL; low: []U8;
420+begin
421+ Diag.error(p, say1("{} isn't declared", nameOf(n)));
422+ _, _, found := moduleFile(n);
423+ low := lowerCase(nameOf(n));
424+ if found then Diag.help(say2("{} is a module: import {}", nameOf(n), nameOf(n)));
425+ elsif (nameOf(n) = "elif") or (nameOf(n) = "elseif") then Diag.help("raz writes elsif");
426+ elsif Scan.reserved(internName(low)) then Diag.help(say1("a reserved word is written in lower case: {}", low));
427+ else didYouMean(Sym.closest(n, -1));
428+ end;
429+end;
430+
431+proc firstUse(o: PObj; at: Diag.Pos): ERROR; forward;
432+proc instancesFor(wholeRest: BOOL): ERROR; forward;
433+proc addImport(m, im: PModule); forward;
434+
435+proc qualIdent: (PObj, ERROR);
436+var o: PObj; m: PModule; at: Diag.Pos;
437+begin
438+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
439+ at := Scan.tokPos();
440+ o := Sym.lookup(Scan.id);
441+ if o = nil then
442+ if not making then poison(Scan.id); end; (* it may yet be declared *)
443+ Diag.setQuiet(false);
444+ notDeclared(at, Scan.id);
445+ if making then Diag.note(useAt, "the instance is made here, where it is first used"); end;
446+ return nil, Scan.Failed;
447+ end;
448+ if o^.typ = Sym.tPoison then Diag.setQuiet(true); end;
449+ named(o);
450+ Scan.next;
451+ if o^.cls = Sym.oModule then
452+ if o^.home = nil then try firstUse(o, at); end;
453+ try expect(Scan.sPeriod);
454+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
455+ m := o^.home;
456+ o := Sym.find(m^.scope, Scan.id);
457+ if (o = nil) or not o^.exported then
458+ Diag.error(Scan.tokPos(), say2("{} isn't exported by {}", nameOf(Scan.id), nameOf(m^.name)));
459+ if o # nil then Diag.note(o^.pos, say1("{} is declared here, without a *", nameOf(Scan.id)));
460+ else didYouMean(Sym.closest(Scan.id, m^.scope));
461+ end;
462+ return nil, Scan.Failed;
463+ end;
464+ Scan.next;
465+ end;
466+ return o, nil;
467+end;
468+
469+(* The field of record type t named by the current symbol *)
470+proc fieldOf(t: PType): (PObj, ERROR);
471+var f: PObj;
472+begin
473+ f := Sym.find(t^.scope, Scan.id);
474+ if f = nil then
475+ Diag.error(Scan.tokPos(), say2("{} has no field {}", Sym.typeName(t), nameOf(Scan.id)));
476+ didYouMean(Sym.closest(Scan.id, t^.scope));
477+ return nil, Scan.Failed;
478+ end;
479+ if not f^.exported and (t^.home # Sym.curModule) then
480+ Diag.error(Scan.tokPos(), say2("field {} of {} isn't exported", nameOf(Scan.id), Sym.typeName(t)));
481+ Diag.note(f^.pos, say1("{} is declared here, without a *", nameOf(Scan.id)));
482+ return nil, Scan.Failed;
483+ end;
484+ return f, nil;
485+end;
486+
487+proc newPtr(base: PType; vol: BOOL): PType;
488+var t: PType;
489+begin
490+ t := Sym.newType(Sym.fPtr, 8, 8);
491+ t^.base := base;
492+ t^.vol := vol;
493+ return t;
494+end;
495+
496+(* Types *)
497+
498+proc recordType: (PType, ERROR);
499+var
500+ t, ft: PType; f, last: PObj; names: [MaxNames]INT;
501+ exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos;
502+ n, i: INT; off, a, maxA: I64;
503+begin
504+ t := Sym.newType(Sym.fRecord, 0, 1);
505+ if Scan.tok = Scan.sPacked then t^.packd := true; Scan.next; end;
506+ try expect(Scan.sRecord);
507+ t^.scope := Sym.newScope();
508+ off := 0; maxA := 1; last := nil;
509+ while Scan.tok = Scan.sIdent do
510+ n := 0;
511+ repeat
512+ if n >= MaxNames then return nil, Scan.mark(tooMany(MaxNames, "names in one declaration")); end;
513+ try identDef(names[n], exps[n], poss[n]);
514+ INC(n);
515+ if Scan.tok # Scan.sComma then break; end;
516+ Scan.next;
517+ until false;
518+ try expect(Scan.sColon);
519+ ft := try parseType();
520+ if t^.packd then a := 1; else a := ft^.align; end;
521+ for i := 0 to n - 1 do
522+ off := Sym.alignUp(off, a);
523+ f := Sym.newObj(Sym.oField, names[i], ft);
524+ f^.exported := exps[i];
525+ f^.pos := poss[i];
526+ f^.val := off;
527+ try Sym.insert(f, t^.scope);
528+ if last = nil then t^.fields := f; else last^.next := f; end;
529+ last := f;
530+ off := off + ft^.size;
531+ end;
532+ if a > maxA then maxA := a; end;
533+ try expect(Scan.sSemicolon);
534+ end;
535+ try expect(Scan.sEnd);
536+ t^.align := maxA;
537+ t^.size := Sym.alignUp(off, maxA);
538+ return t, nil;
539+end;
540+
541+proc variantType: (PType, ERROR);
542+var t, ft: PType; c, lastC, f, lastF: PObj; tag, off, maxSize: I64;
543+begin
544+ try expect(Scan.sVariant);
545+ t := Sym.newType(Sym.fVariant, 8, 8);
546+ tag := 0; maxSize := 8; lastC := nil;
547+ while Scan.tok = Scan.sIdent do
548+ c := Sym.newObj(Sym.oCase, Scan.id, t);
549+ c^.val := tag;
550+ c^.exported := declExported;
551+ try declare(c);
552+ if lastC = nil then t^.fields := c; else lastC^.next := c; end;
553+ lastC := c;
554+ Scan.next;
555+ off := 8;
556+ if Scan.tok = Scan.sLparen then
557+ Scan.next;
558+ lastF := nil;
559+ repeat
560+ repeat
561+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
562+ f := Sym.newObj(Sym.oField, Scan.id, nil);
563+ f^.exported := true;
564+ if lastF = nil then c^.fields := f; else lastF^.next := f; end;
565+ lastF := f;
566+ Scan.next;
567+ if Scan.tok # Scan.sComma then break; end;
568+ Scan.next;
569+ until false;
570+ try expect(Scan.sColon);
571+ ft := try parseType();
572+ f := c^.fields;
573+ while f^.typ # nil do f := f^.next; end;
574+ while f # nil do
575+ f^.typ := ft;
576+ off := Sym.alignUp(off, ft^.align);
577+ f^.val := off;
578+ off := off + ft^.size;
579+ f := f^.next;
580+ end;
581+ if ft^.align > t^.align then t^.align := ft^.align; end;
582+ if Scan.tok # Scan.sSemicolon then break; end;
583+ Scan.next;
584+ until false;
585+ try expect(Scan.sRparen);
586+ end;
587+ if off > maxSize then maxSize := off; end;
588+ try expect(Scan.sSemicolon);
589+ INC(tag);
590+ end;
591+ try expect(Scan.sEnd);
592+ t^.len := tag;
593+ t^.size := Sym.alignUp(maxSize, t^.align);
594+ return t, nil;
595+end;
596+
597+(* Several results: a record of them, laid out as C would, and
598+ returned in rax and rdx if they are two words (inTwoRegs), or else
599+ through a hidden pointer. *)
600+proc results: (PType, ERROR);
601+var t, ft: PType; f, last: PObj; off: I64;
602+begin
603+ Scan.next;
604+ t := Sym.newType(Sym.fRecord, 0, 1);
605+ t^.tuple := true;
606+ off := 0; last := nil;
607+ repeat
608+ ft := try parseType();
609+ off := Sym.alignUp(off, ft^.align);
610+ f := Sym.newObj(Sym.oField, -1, ft);
611+ f^.val := off;
612+ off := off + ft^.size;
613+ if ft^.align > t^.align then t^.align := ft^.align; end;
614+ if last = nil then t^.fields := f; else last^.next := f; end;
615+ last := f;
616+ INC(t^.len);
617+ if Scan.tok # Scan.sComma then break; end;
618+ Scan.next;
619+ until false;
620+ try expect(Scan.sRparen);
621+ t^.size := Sym.alignUp(off, t^.align);
622+ if t^.len = 1 then return t^.fields^.typ, nil; end;
623+ return t, nil;
624+end;
625+
626+proc signature: (PType, ERROR);
627+var
628+ t, pt: PType; p, first, last: PObj; isVar: BOOL; n: INT;
629+begin
630+ t := Sym.newType(Sym.fProc, 8, 8);
631+ last := nil; n := 0;
632+ if Scan.tok = Scan.sLparen then
633+ Scan.next;
634+ if Scan.tok # Scan.sRparen then
635+ repeat
636+ if Scan.tok = Scan.sEllipsis then
637+ if not inExtern then return nil, Scan.mark("... is only for extern procedures"); end;
638+ Scan.next; t^.variadic := true; break;
639+ end;
640+ isVar := Scan.tok = Scan.sVar;
641+ if isVar then Scan.next; end;
642+ first := nil;
643+ repeat
644+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
645+ p := Sym.newObj(Sym.oVar, Scan.id, nil);
646+ p^.isVar := isVar;
647+ p^.lev := 1;
648+ if last = nil then t^.fields := p; else last^.next := p; end;
649+ last := p;
650+ if first = nil then first := p; end;
651+ INC(n);
652+ Scan.next;
653+ if Scan.tok # Scan.sComma then break; end;
654+ Scan.next;
655+ until false;
656+ try expect(Scan.sColon);
657+ pt := try parseType();
658+ while first # nil do first^.typ := pt; first := first^.next; end;
659+ if Scan.tok # Scan.sSemicolon then break; end;
660+ Scan.next;
661+ until false;
662+ end;
663+ try expect(Scan.sRparen);
664+ end;
665+ t^.len := n;
666+ if Scan.tok = Scan.sColon then
667+ Scan.next;
668+ if Scan.tok = Scan.sLparen then t^.base := try results(); else t^.base := try parseType(); end;
669+ end;
670+ return t, nil;
671+end;
672+
673+proc enumType: (PType, ERROR);
674+var t: PType; o, last: PObj; start: Diag.Pos;
675+begin
676+ start := Scan.tokPos();
677+ t := Sym.newType(Sym.fEnum, 1, 1);
678+ last := nil;
679+ repeat
680+ Scan.next;
681+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
682+ o := Sym.newObj(Sym.oConst, Scan.id, t);
683+ o^.val := t^.len;
684+ o^.exported := declExported;
685+ o^.used := true; (* an enumeration's names are its type's, warned of with it *)
686+ try declare(o);
687+ if last = nil then t^.fields := o; else last^.next := o; end;
688+ last := o;
689+ INC(t^.len);
690+ Scan.next;
691+ until Scan.tok # Scan.sComma;
692+ try expect(Scan.sRparen);
693+ if t^.len > 256 then return nil, Scan.markAt(Scan.spanFrom(start), "an enumeration has at most 256 names"); end;
694+ return t, nil;
695+end;
696+
697+proc setOf(e: PType; at: Diag.Pos): (PType, ERROR);
698+var t: PType;
699+begin
700+ if (e^.form # Sym.fEnum) or (e^.len > 64) then
701+ return nil, Scan.markAt(at, say1("a set needs an enumeration of at most 64 names, found {}", Sym.typeName(e)));
702+ end;
703+ t := Sym.newType(Sym.fSet, 8, 8);
704+ if e^.len <= 8 then t^.size := 1;
705+ elsif e^.len <= 16 then t^.size := 2;
706+ elsif e^.len <= 32 then t^.size := 4;
707+ end;
708+ t^.align := t^.size;
709+ t^.base := e;
710+ t^.len := e^.len;
711+ return t, nil;
712+end;
713+
714+proc parseType: (PType, ERROR);
715+var t: PType; o: PObj; n: I64; vol: BOOL; start: Diag.Pos;
716+begin
717+ start := Scan.tokPos();
718+ match Scan.tok of
719+ | sIdent:
720+ o := try qualIdent();
721+ if o^.cls # Sym.oType then
722+ return nil, Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type", nameOf(o^.name)));
723+ end;
724+ t := o^.typ;
725+ | sLbrak:
726+ Scan.next;
727+ if Scan.tok = Scan.sRbrak then
728+ Scan.next;
729+ t := Sym.newType(Sym.fSlice, 16, 8);
730+ t^.base := try parseType();
731+ else
732+ start := Scan.tokPos();
733+ n := try constExpr();
734+ if (n <= 0) or (n > (I64(1) shl 40)) then
735+ return nil, Scan.markAt(Scan.spanFrom(start), Diag.say("an array's length is from 1 to 2^40, found {}", [Fmt.int(n)]));
736+ end;
737+ try expect(Scan.sRbrak);
738+ t := Sym.newType(Sym.fArray, 0, 1);
739+ t^.len := n;
740+ t^.base := try parseType();
741+ t^.size := n * t^.base^.size;
742+ t^.align := t^.base^.align;
743+ end;
744+ | sArrow:
745+ Scan.next;
746+ vol := Scan.tok = Scan.sVolatile;
747+ if vol then Scan.next; end;
748+ if inTypes and (Scan.tok = Scan.sIdent) and (Sym.lookup(Scan.id) = nil) then
749+ (* a type declared later in this section *)
750+ t := newPtr(nil, vol);
751+ t^.fwd := Scan.id;
752+ if numFwd >= MaxFwd then
753+ return nil, Scan.mark(tooMany(MaxFwd, "pointers to types not yet declared"));
754+ end;
755+ fwdTypes[numFwd] := t;
756+ fwdPos[numFwd] := Scan.tokPos();
757+ INC(numFwd);
758+ Scan.next;
759+ else
760+ t := newPtr(try parseType(), vol);
761+ end;
762+ | sPacked, sRecord: t := try recordType();
763+ | sVariant: t := try variantType();
764+ | sProc: Scan.next; t := try signature();
765+ | sLparen: t := try enumType();
766+ | sSet:
767+ Scan.next;
768+ try expect(Scan.sOf);
769+ start := Scan.tokPos();
770+ t := try setOf(try parseType(), start);
771+ | else: return nil, expected("a type");
772+ end;
773+ return t, nil;
774+end;
775+
776+(* Expressions *)
777+
778+proc call(var x: TItem): ERROR;
779+var c: Gen.CallInfo; a: TItem; want: PType;
780+begin
781+ try Item.beginCall(c, x);
782+ try expect(Scan.sLparen);
783+ if Scan.tok # Scan.sRparen then
784+ repeat
785+ if c.param # nil then want := c.param^.typ; else want := nil; end;
786+ try expression(a, want);
787+ try Item.passArg(c, a);
788+ if Scan.tok # Scan.sComma then break; end;
789+ Scan.next;
790+ until false;
791+ end;
792+ try expect(Scan.sRparen);
793+ return Item.endCall(c, x);
794+end;
795+
796+proc atomic(var x: TItem; which: INT): ERROR;
797+var p, a: TItem; t: PType; i, n: INT;
798+begin
799+ try expression(p, nil);
800+ if p.typ^.form # Sym.fPtr then
801+ return Scan.markAt(p.pos, say1("expected a pointer, found {}", Item.what(p)));
802+ end;
803+ t := p.typ^.base;
804+ if not (Item.isWord(t) or ((t^.form = Sym.fPtr) and (which # Sym.bXadd))) then
805+ if which = Sym.bXadd then
806+ return Scan.markAt(p.pos, say1("expected a pointer to an INT or a UINT, found {}", Sym.typeName(p.typ)));
807+ end;
808+ return Scan.markAt(p.pos, say1("expected a pointer to an INT, a UINT or a pointer, found {}", Sym.typeName(p.typ)));
809+ end;
810+ try Item.value(p);
811+ if which = Sym.bCas then n := 2; else n := 1; end;
812+ for i := 1 to n do
813+ try expect(Scan.sComma);
814+ try expression(a, t);
815+ try Item.coerce(a, t);
816+ try Item.value(a);
817+ end;
818+ Gen.atomic(which);
819+ Item.makeConst(x, t, 0);
820+ if which = Sym.bCas then x.typ := Sym.tBool; end;
821+ x.mode := Item.mStack;
822+ return nil;
823+end;
824+
825+(* NEW(p, a): p := a^.alloc(a, SIZE(T), alignment), zeroed if not nil.
826+ a is a ^Mem.Allocator, the one interface the compiler knows. *)
827+proc new_(var x: TItem): ERROR;
828+var y, z: TItem; t: PType; f: PObj; s: I64; c: Gen.CallInfo;
829+begin
830+ try expression(x, nil);
831+ try Item.notReadOnly(x);
832+ if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fPtr) then
833+ return Scan.markAt(x.pos, "NEW needs a pointer variable");
834+ end;
835+ t := x.typ^.base;
836+ try expect(Scan.sComma);
837+ try expression(y, nil);
838+ if (y.typ^.form # Sym.fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.home = nil)
839+ or (nameOf(y.typ^.base^.obj^.name) # "Allocator")
840+ or (nameOf(y.typ^.base^.obj^.home^.name) # "Mem") then
841+ return Scan.markAt(y.pos, say1("NEW needs a ^Mem.Allocator, found {}", Item.what(y)));
842+ end;
843+ f := Sym.find(y.typ^.base^.scope, internName("alloc"));
844+ s := try Item.toSlot(y);
845+ Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord);
846+ Item.makeConst(z, f^.typ, 0);
847+ z.mode := Item.mVar; z.base := Gen.bStack; z.off := f^.val;
848+ try Item.beginCall(c, z);
849+ Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord);
850+ Item.makeConst(z, y.typ, 0);
851+ z.mode := Item.mStack;
852+ try Item.passArg(c, z);
853+ Item.makeConst(z, Sym.tInt, t^.size);
854+ try Item.passArg(c, z);
855+ Item.makeConst(z, Sym.tInt, t^.align);
856+ try Item.passArg(c, z);
857+ try Item.endCall(c, z);
858+ Gen.zeroNew(t^.size);
859+ z.typ := x.typ;
860+ try Item.assign(x, z);
861+ Item.makeConst(x, Sym.tNone, 0);
862+ x.mode := Item.mNone;
863+ return nil;
864+end;
865+
866+proc incOrDec(which: INT): []U8;
867+begin
868+ if which = Sym.bDec then return "DEC"; end;
869+ return "INC";
870+end;
871+
872+proc builtin(var x: TItem): ERROR;
873+var which, n: INT; y: TItem; t: PType;
874+begin
875+ which := INT(x.obj^.val);
876+ if (which = Sym.bFence) or (which = Sym.bArgc) or (which = Sym.bArgv) then
877+ if Scan.tok = Scan.sLparen then Scan.next; try expect(Scan.sRparen); end;
878+ Item.makeConst(x, Sym.tNone, 0);
879+ match which of
880+ | Sym.bFence: Gen.fence(); x.mode := Item.mNone;
881+ | Sym.bArgc:
882+ Gen.pushVar(Item.globalAdr(Gen.argcChunk), 8, false, Gen.kWord);
883+ x.typ := Sym.tInt; x.mode := Item.mStack;
884+ | else:
885+ Gen.pushVar(Item.globalAdr(Gen.argvChunk), 8, false, Gen.kWord);
886+ x.typ := tArgv; x.mode := Item.mStack;
887+ end;
888+ return nil;
889+ end;
890+ try expect(Scan.sLparen);
891+ match which of
892+ | Sym.bSize:
893+ t := try parseType();
894+ Item.makeConst(x, Sym.tConst, t^.size);
895+ | Sym.bAdr:
896+ try expression(y, nil);
897+ try Item.notReadOnly(y);
898+ if (y.mode # Item.mVar) or not y.isVar then return Scan.markAt(y.pos, "ADR needs a variable"); end;
899+ if y.odd then return Scan.markAt(y.pos, "a field of a packed record has no address"); end;
900+ t := newPtr(y.typ, y.vol);
901+ try Item.address(y);
902+ Item.makeConst(x, t, 0);
903+ x.mode := Item.mStack;
904+ | Sym.bLen:
905+ try expression(y, nil);
906+ if y.mode = Item.mStr then
907+ Item.makeConst(x, Sym.tConst, y.val);
908+ elsif y.typ^.form = Sym.fArray then
909+ try Item.discard(y);
910+ Item.makeConst(x, Sym.tConst, y.typ^.len);
911+ elsif (y.typ^.form = Sym.fSlice) and (y.mode = Item.mVar) then
912+ (* its length, the word after its pointer *)
913+ y.off := y.off + 8;
914+ y.typ := Sym.tInt;
915+ try Item.value(y);
916+ x := y;
917+ else
918+ return Scan.markAt(y.pos, say1("LEN needs an array or a slice, found {}", Item.what(y)));
919+ end;
920+ | Sym.bSyscall:
921+ n := 0;
922+ repeat
923+ if n > 0 then Scan.next; end;
924+ try expression(y, nil);
925+ if not (Sym.isScalar(y.typ) and (y.typ^.form # Sym.fReal)) then
926+ return Scan.markAt(y.pos, say1("expected an integer or a pointer, found {}", Item.what(y)));
927+ end;
928+ if y.typ^.form = Sym.fConst then try Item.coerce(y, Sym.tInt); end;
929+ try Item.value(y);
930+ INC(n);
931+ until (Scan.tok # Scan.sComma) or (n = 7);
932+ Gen.sysCall(n);
933+ Item.makeConst(x, Sym.tInt, 0);
934+ x.mode := Item.mStack;
935+ | Sym.bCas, Sym.bXchg, Sym.bXadd: try atomic(x, which);
936+ | Sym.bMsg:
937+ try expression(x, Sym.tError);
938+ try Item.msg(x);
939+ | Sym.bInc, Sym.bDec:
940+ try expression(x, nil);
941+ try Item.notReadOnly(x);
942+ if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fInt) then
943+ return Scan.markAt(x.pos, say1("{} needs an integer variable", incOrDec(which)));
944+ end;
945+ if x.base # Gen.bReg then try Item.address(x); end;
946+ if Scan.tok = Scan.sComma then
947+ Scan.next;
948+ try expression(y, x.typ);
949+ else
950+ Item.makeConst(y, x.typ, 1);
951+ end;
952+ try Item.incDec(x, y, which = Sym.bDec);
953+ Item.makeConst(x, Sym.tNone, 0);
954+ x.mode := Item.mNone;
955+ | Sym.bNew: try new_(x);
956+ | Sym.bCopy:
957+ try expression(x, nil);
958+ try Item.copyDest(x);
959+ try expect(Scan.sComma);
960+ try expression(y, nil);
961+ try Item.copyFrom(x, y);
962+ Item.makeConst(x, Sym.tNone, 0);
963+ x.mode := Item.mNone;
964+ | else:
965+ end;
966+ return expect(Scan.sRparen);
967+end;
968+
969+proc constructCase(var x: TItem; c: PObj; at: Diag.Pos): ERROR;
970+var f: PObj; a: TItem;
971+begin
972+ Item.construct(x, c);
973+ f := c^.fields;
974+ if Scan.tok = Scan.sLparen then
975+ Scan.next;
976+ while f # nil do
977+ try expression(a, f^.typ);
978+ try Item.setField(x, f, a);
979+ f := f^.next;
980+ if f # nil then try expect(Scan.sComma); end;
981+ end;
982+ return expect(Scan.sRparen);
983+ elsif f # nil then
984+ return Scan.markAt(at, say1("{} needs its fields", nameOf(c^.name)));
985+ end;
986+ return nil;
987+end;
988+
989+(* x, before ".", has no fields; tok is what follows. Other languages
990+ write p.f through a pointer and s.len for a length. *)
991+proc fieldOfWhat(x: TItem): ERROR;
992+var msg, f: []U8;
993+begin
994+ msg := say1("expected a record, found {}", Item.what(x));
995+ if Scan.tok = Scan.sIdent then f := nameOf(Scan.id); else f := ""; end;
996+ if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fRecord) then
997+ return Scan.markHelp(x.pos, msg, say2("through a pointer, write {}^.{}", Diag.source(x.pos), f));
998+ elsif ((x.typ^.form = Sym.fArray) or (x.typ^.form = Sym.fSlice))
999+ and ((f = "len") or (f = "length") or (f = "size") or (f = "count")) then
1000+ return Scan.markHelp(x.pos, msg, say1("its length is LEN({})", Diag.source(x.pos)));
1001+ end;
1002+ return Scan.markAt(x.pos, msg);
1003+end;
1004+
1005+(* A designator, with any selectors and calls after it. called tells
1006+ whether the last thing done was a call. *)
1007+proc designator(var x: TItem; var called: BOOL): ERROR;
1008+var o, f: PObj; y, z: TItem; t: PType; start: Diag.Pos;
1009+begin
1010+ start := Scan.tokPos();
1011+ o := try qualIdent();
1012+ called := false;
1013+ if o^.cls = Sym.oModule then
1014+ return Scan.markAt(Scan.spanFrom(start), say1("{} is a module, not a value", nameOf(o^.name)));
1015+ end;
1016+ try Item.makeItem(x, o);
1017+ if x.mode = Item.mBuiltin then
1018+ try builtin(x);
1019+ called := true;
1020+ elsif x.mode = Item.mCase then
1021+ try constructCase(x, o, Scan.spanFrom(start));
1022+ end;
1023+ repeat
1024+ x.pos := Scan.spanFrom(start);
1025+ match Scan.tok of
1026+ | sPeriod:
1027+ Scan.next;
1028+ if (x.mode # Item.mVar) or (x.typ^.form # Sym.fRecord) then return fieldOfWhat(x); end;
1029+ if Scan.tok # Scan.sIdent then return expected("a field"); end;
1030+ f := try fieldOf(x.typ);
1031+ Scan.next;
1032+ try Item.field(x, f);
1033+ called := false;
1034+ | sArrow:
1035+ Scan.next;
1036+ try Item.deref(x);
1037+ called := false;
1038+ | sLbrak:
1039+ Scan.next;
1040+ try Item.indexPrep(x);
1041+ try expression(y, nil);
1042+ if Scan.tok = Scan.sUpto then
1043+ Scan.next;
1044+ try Item.sliceLo(y);
1045+ try expression(z, nil);
1046+ try Item.slice(x, y, z);
1047+ else
1048+ try Item.index(x, y);
1049+ end;
1050+ try expect(Scan.sRbrak);
1051+ called := false;
1052+ | sLparen:
1053+ if x.mode = Item.mType then
1054+ t := x.typ;
1055+ Scan.next;
1056+ try expression(x, nil);
1057+ try expect(Scan.sRparen);
1058+ try Item.convert(x, t);
1059+ else
1060+ if x.mode = Item.mProc then lastCalled := x.obj; else lastCalled := nil; end;
1061+ try call(x);
1062+ called := true;
1063+ end;
1064+ | else: break;
1065+ end;
1066+ until false;
1067+ x.pos := Scan.spanFrom(start);
1068+ Item.nilTest(x);
1069+ return nil;
1070+end;
1071+
1072+proc arrayLiteral(var x: TItem; want: PType): ERROR;
1073+var
1074+ et, at: PType; e: TItem; slots: [MaxElements]I64; n, i: INT;
1075+ off, es: I64; start: Diag.Pos;
1076+begin
1077+ start := Scan.tokPos();
1078+ if (want = nil) or not ((want^.form = Sym.fArray) or (want^.form = Sym.fSlice)) then
1079+ return Scan.mark("an array literal needs a known array or slice type");
1080+ end;
1081+ et := want^.base;
1082+ es := et^.size;
1083+ Scan.next;
1084+ n := 0;
1085+ if Scan.tok # Scan.sRbrak then
1086+ repeat
1087+ if n >= MaxElements then return Scan.mark(tooMany(MaxElements, "elements")); end;
1088+ try expression(e, et);
1089+ try Item.coerce(e, et);
1090+ if Sym.isScalar(et) then
1091+ slots[n] := try Item.toSlot(e);
1092+ else
1093+ if e.isVar or e.vol or (e.mode # Item.mVar) or (e.base # Gen.bFrame) then try Item.copyToTemp(e); end;
1094+ slots[n] := e.off;
1095+ end;
1096+ INC(n);
1097+ if Scan.tok # Scan.sComma then break; end;
1098+ Scan.next;
1099+ until false;
1100+ end;
1101+ try expect(Scan.sRbrak);
1102+ if (want^.form = Sym.fArray) and (I64(n) # want^.len) then
1103+ return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(want^.len), Fmt.int(n)]));
1104+ end;
1105+ if n = 0 then
1106+ Gen.pushConst(Gen.kWord, 0);
1107+ Item.sliceOf(x, want, 0);
1108+ return nil;
1109+ end;
1110+ if want^.form = Sym.fArray then
1111+ at := want;
1112+ off := Gen.allocTemp(at^.size, at^.align);
1113+ else
1114+ at := Sym.newType(Sym.fArray, I64(n) * es, et^.align);
1115+ at^.len := n;
1116+ at^.base := et;
1117+ off := Gen.allocPerm(at^.size, at^.align); (* lives as long as the call *)
1118+ end;
1119+ for i := 0 to n - 1 do
1120+ if Sym.isScalar(et) then
1121+ Gen.pushVar(Item.frameAdr(slots[i]), 8, false, Gen.kindOf(et));
1122+ Gen.popVar(Item.frameAdr(off + I64(i) * es), Item.scalarSize(et));
1123+ else
1124+ Gen.pushAdr(Item.frameAdr(slots[i]));
1125+ Gen.copyTo(Item.frameAdr(off + I64(i) * es), es);
1126+ end;
1127+ end;
1128+ Item.tempItem(x, at, off);
1129+ return nil;
1130+end;
1131+
1132+(* A record literal: a zeroed temporary, with the fields named filled in. *)
1133+proc recordLiteral(var x: TItem; t: PType): ERROR;
1134+var f: PObj; a: TItem; seen: [MaxNames]INT; n, i: INT;
1135+begin
1136+ Scan.next;
1137+ Item.zeroTemp(x, t);
1138+ n := 0;
1139+ if Scan.tok # Scan.sRbrace then
1140+ repeat
1141+ if Scan.tok # Scan.sIdent then return expected("a field"); end;
1142+ f := try fieldOf(t);
1143+ for i := 0 to n - 1 do
1144+ if seen[i] = Scan.id then
1145+ return Scan.mark(say1("field {} is given twice", nameOf(Scan.id)));
1146+ end;
1147+ end;
1148+ if n < MaxNames then seen[n] := Scan.id; INC(n); end;
1149+ Scan.next;
1150+ try expect(Scan.sColon);
1151+ try expression(a, f^.typ);
1152+ try Item.setField(x, f, a);
1153+ if Scan.tok # Scan.sComma then break; end;
1154+ Scan.next;
1155+ until false;
1156+ end;
1157+ return expect(Scan.sRbrace);
1158+end;
1159+
1160+(* A set literal: the bits of the constant names, or'd at run time with
1161+ those of the others. *)
1162+proc setLiteral(var x: TItem; t: PType): ERROR;
1163+var e: TItem; bits, slot: I64; start: Diag.Pos; s: []U8;
1164+begin
1165+ start := Scan.tokPos();
1166+ Scan.next;
1167+ if (t # nil) and (t^.form # Sym.fSet) then
1168+ return Scan.markAt(Scan.spanFrom(start), say1("expected a set type, found {}", Sym.typeName(t)));
1169+ end;
1170+ bits := 0;
1171+ slot := 0;
1172+ if Scan.tok # Scan.sRbrace then
1173+ repeat
1174+ if t = nil then try expression(e, nil); else try expression(e, t^.base); end;
1175+ if t = nil then
1176+ if e.typ^.form # Sym.fEnum then
1177+ return Scan.markAt(e.pos, say1("a set holds names of an enumeration, found {}", Item.what(e)));
1178+ end;
1179+ t := try setOf(e.typ, e.pos);
1180+ end;
1181+ if not Sym.same(e.typ, t^.base) then
1182+ if e.obj # nil then s := nameOf(e.obj^.name); else s := Item.what(e); end;
1183+ return Scan.markAt(e.pos, say2("{} isn't a name of {}", s, Sym.typeName(t^.base)));
1184+ end;
1185+ if e.mode = Item.mConst then
1186+ bits := bits | (I64(1) shl e.val);
1187+ else
1188+ if slot = 0 then
1189+ slot := Gen.allocTemp(8, 8);
1190+ Gen.pushConst(Gen.kWord, 0);
1191+ Gen.popVar(Item.frameAdr(slot), 8);
1192+ end;
1193+ try Item.value(e);
1194+ Gen.pushConst(Gen.kWord, 1);
1195+ Gen.swap();
1196+ Gen.op(Scan.sShl, Gen.kWord, 8, false);
1197+ Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord);
1198+ Gen.op(Scan.sBar, Gen.kWord, 8, false);
1199+ Gen.popVar(Item.frameAdr(slot), 8);
1200+ end;
1201+ if Scan.tok # Scan.sComma then break; end;
1202+ Scan.next;
1203+ until false;
1204+ end;
1205+ try expect(Scan.sRbrace);
1206+ if t = nil then return Scan.markAt(Scan.spanFrom(start), "{} needs a known set type"); end;
1207+ Item.makeConst(x, t, bits);
1208+ if slot # 0 then
1209+ Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord);
1210+ Gen.pushConst(Gen.kWord, bits);
1211+ Gen.op(Scan.sBar, Gen.kWord, 8, false);
1212+ x.mode := Item.mStack;
1213+ end;
1214+ return nil;
1215+end;
1216+
1217+proc runDefers(base: INT); forward;
1218+
1219+(* The type of the last result of t, the results of a procedure: t if
1220+ it has one, else the last of its several. *)
1221+proc lastResult(t: PType): PType;
1222+var f: PObj;
1223+begin
1224+ if not t^.tuple then return t; end;
1225+ f := t^.fields;
1226+ while f^.next # nil do f := f^.next; end;
1227+ return f^.typ;
1228+end;
1229+
1230+(* The results of the tuple t but the last: the same fields, one fewer *)
1231+proc withoutLast(t: PType): PType;
1232+var r: PType;
1233+begin
1234+ r := Sym.newType(Sym.fRecord, t^.size, t^.align);
1235+ r^.tuple := true;
1236+ r^.fields := t^.fields;
1237+ r^.len := t^.len - 1;
1238+ return r;
1239+end;
1240+
1241+(* try c (the report, 7.8): the call c, then the error it returned, its
1242+ last result: if that isn't nil, the procedure returns it, and a zero
1243+ for each of its other results, after running the deferred statements
1244+ in force. x is left c's other results: none (mNone), one (a value) or
1245+ several (a tuple, for a multiple assignment). The error is kept in a
1246+ slot of the frame, and tested there; the code for it, out of line,
1247+ is made with the stack of values as it stands, and leaves it so,
1248+ since what follows is the code for an error that is nil. *)
1249+proc tryCall(var x: TItem): ERROR;
1250+var
1251+ called: BOOL; c: Gen.CallInfo; start, at: Diag.Pos; res: PType; last: PObj; slot: I64; ok: INT;
1252+begin
1253+ start := Scan.tokPos();
1254+ Scan.next;
1255+ if deferring then return Scan.markAt(Scan.spanFrom(start), "try can't leave a deferred statement"); end;
1256+ if curResult = nil then
1257+ return Scan.markAt(Scan.spanFrom(start), "try needs a procedure that ends in an ERROR result, and this returns nothing");
1258+ elsif lastResult(curResult) # Sym.tError then
1259+ return Scan.markAt(Scan.spanFrom(start),
1260+ say1("try needs a procedure that ends in an ERROR result, and this returns {}", Sym.typeName(curResult)));
1261+ end;
1262+ try designator(x, called);
1263+ if not called and ((x.mode = Item.mProc)
1264+ or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc))) then
1265+ (* a procedure without parameters, written without parentheses *)
1266+ at := x.pos;
1267+ try Item.beginCall(c, x);
1268+ try Item.endCall(c, x);
1269+ x.pos := at;
1270+ called := true;
1271+ end;
1272+ if not called then return Scan.markAt(x.pos, say1("try needs a call, found {}", Item.what(x))); end;
1273+ if x.mode = Item.mNone then
1274+ return Scan.markAt(x.pos, "try needs a call that returns an ERROR last, and this returns nothing");
1275+ end;
1276+ if lastResult(x.typ) # Sym.tError then
1277+ return Scan.markAt(x.pos, say1("try needs a call that returns an ERROR last, and this returns {}", Sym.typeName(x.typ)));
1278+ end;
1279+ res := x.typ;
1280+ if x.mode = Item.mStack then
1281+ (* an ERROR alone *)
1282+ slot := Gen.allocTemp(8, 8);
1283+ Gen.popVar(Item.frameAdr(slot), 8);
1284+ x.mode := Item.mNone; x.typ := Sym.tNone;
1285+ elsif x.mode = Item.mWords then
1286+ (* two words, the error on top *)
1287+ slot := Gen.allocTemp(8, 8);
1288+ Gen.popVar(Item.frameAdr(slot), 8);
1289+ x.mode := Item.mStack; x.typ := res^.fields^.typ;
1290+ else
1291+ (* several, in a temporary: the error is where it is *)
1292+ last := res^.fields;
1293+ while last^.next # nil do last := last^.next; end;
1294+ slot := x.off + last^.val;
1295+ if res^.len = 2 then try Item.field(x, res^.fields); else x.typ := withoutLast(res); end;
1296+ end;
1297+ ok := Gen.NoLabel;
1298+ Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord);
1299+ Gen.jumpIf(ok, false);
1300+ if numDefers > 0 then Gen.tryAlign(); end;
1301+ runDefers(0);
1302+ Gen.tryReturn(slot);
1303+ Gen.fix(ok);
1304+ x.pos := Scan.spanFrom(start);
1305+ return nil;
1306+end;
1307+
1308+proc factor(var x: TItem; want: PType): ERROR;
1309+var called, vol, several: BOOL; t: PType; start: Diag.Pos; s: []U8;
1310+begin
1311+ several := passOn;
1312+ passOn := false;
1313+ start := Scan.tokPos();
1314+ match Scan.tok of
1315+ | sInt, sChar:
1316+ (* only a hex number can be above high(I64), and it is a U64 *)
1317+ if Scan.ival < 0 then Item.makeConst(x, Sym.tU64, Scan.ival); else Item.makeConst(x, Sym.tConst, Scan.ival); end;
1318+ Scan.next;
1319+ | sReal:
1320+ Item.makeReal(x, Scan.rval);
1321+ Item.usesReals(Scan.tokPos());
1322+ Scan.next;
1323+ | sString:
1324+ Item.makeStr(x);
1325+ Scan.next;
1326+ | sIdent:
1327+ try designator(x, called);
1328+ if x.mode = Item.mNone then
1329+ if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end;
1330+ return Scan.markAt(x.pos, say1("{} returns nothing", s));
1331+ end;
1332+ if x.typ^.tuple and not several then
1333+ if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end;
1334+ return Scan.markHelp(x.pos, say1("{} returns several results", s),
1335+ say1("they go to variables: a, b := {}(...)", s));
1336+ end;
1337+ | sLparen:
1338+ Scan.next;
1339+ try expression(x, want);
1340+ try expect(Scan.sRparen);
1341+ | sTry:
1342+ try tryCall(x);
1343+ if x.mode = Item.mNone then return Scan.markAt(x.pos, "this try has no value"); end;
1344+ if x.typ^.tuple then
1345+ return Scan.markHelp(x.pos, "this try has several values", "they go to variables: a, b := try f(...)");
1346+ end;
1347+ | sNot:
1348+ Scan.next;
1349+ try factor(x, nil);
1350+ try Item.notOp(x);
1351+ | sTilde:
1352+ Scan.next;
1353+ try factor(x, nil);
1354+ try Item.complement(x);
1355+ | sLbrak: try arrayLiteral(x, want);
1356+ | sLbrace:
1357+ if (want # nil) and (want^.form = Sym.fRecord) then try recordLiteral(x, want);
1358+ else try setLiteral(x, want);
1359+ end;
1360+ | sArrow:
1361+ Scan.next;
1362+ vol := Scan.tok = Scan.sVolatile;
1363+ if vol then Scan.next; end;
1364+ t := try parseType();
1365+ t := newPtr(t, vol);
1366+ try expect(Scan.sLparen);
1367+ try expression(x, nil);
1368+ try expect(Scan.sRparen);
1369+ try Item.convert(x, t);
1370+ (* a conversion is a factor, not a designator: nothing selects from it *)
1371+ if Scan.tok = Scan.sArrow then
1372+ return Scan.markHelp(Scan.tokPos(), "a conversion can't be dereferenced",
1373+ "convert into a pointer variable, then dereference that");
1374+ end;
1375+ | else: return expected("an expression");
1376+ end;
1377+ x.pos := Scan.spanFrom(start);
1378+ return nil;
1379+end;
1380+
1381+proc isMulOp: BOOL;
1382+begin
1383+ match Scan.tok of
1384+ | sTimes, sSlash, sDiv, sMod, sAmp, sShl, sShr: return true;
1385+ | else: return false;
1386+ end;
1387+end;
1388+
1389+proc isAddOp: BOOL;
1390+begin
1391+ match Scan.tok of
1392+ | sPlus, sMinus, sBar, sXor: return true;
1393+ | else: return false;
1394+ end;
1395+end;
1396+
1397+proc isRelOp: BOOL;
1398+begin
1399+ match Scan.tok of
1400+ | sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn: return true;
1401+ | else: return false;
1402+ end;
1403+end;
1404+
1405+proc term(var x: TItem; want: PType): ERROR;
1406+var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos;
1407+begin
1408+ start := Scan.tokPos();
1409+ try factor(x, want);
1410+ while isMulOp() do
1411+ op := Scan.tok;
1412+ Scan.next;
1413+ try Item.op1(op, x, L);
1414+ try factor(y, nil);
1415+ try Item.op2(op, x, y, L);
1416+ x.pos := Scan.spanFrom(start);
1417+ end;
1418+ return nil;
1419+end;
1420+
1421+proc simpleExpr(var x: TItem; want: PType): ERROR;
1422+var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos;
1423+begin
1424+ start := Scan.tokPos();
1425+ if Scan.tok = Scan.sMinus then
1426+ Scan.next;
1427+ try term(x, nil);
1428+ x.pos := Scan.spanFrom(start);
1429+ try Item.neg(x);
1430+ else
1431+ try term(x, want);
1432+ end;
1433+ while isAddOp() do
1434+ op := Scan.tok;
1435+ Scan.next;
1436+ try Item.op1(op, x, L);
1437+ try term(y, nil);
1438+ try Item.op2(op, x, y, L);
1439+ x.pos := Scan.spanFrom(start);
1440+ end;
1441+ return nil;
1442+end;
1443+
1444+proc relation(var x: TItem; want: PType): ERROR;
1445+var op: Scan.Sym; y: TItem; L: INT;
1446+begin
1447+ try simpleExpr(x, want);
1448+ if isRelOp() then
1449+ op := Scan.tok;
1450+ Scan.next;
1451+ try Item.op1(op, x, L);
1452+ if op = Scan.sIn then try simpleExpr(y, nil); else try simpleExpr(y, x.typ); end;
1453+ try Item.op2(op, x, y, L);
1454+ x.pos := Diag.join(x.pos, y.pos);
1455+ end;
1456+ return nil;
1457+end;
1458+
1459+(* and binds tighter than or, and both below the relations *)
1460+proc conjunct(var x: TItem; want: PType): ERROR;
1461+var y: TItem; L: INT; start: Diag.Pos;
1462+begin
1463+ start := Scan.tokPos();
1464+ try relation(x, want);
1465+ while Scan.tok = Scan.sAnd do
1466+ Scan.next;
1467+ try Item.op1(Scan.sAnd, x, L);
1468+ try relation(y, nil);
1469+ try Item.op2(Scan.sAnd, x, y, L);
1470+ x.pos := Scan.spanFrom(start);
1471+ end;
1472+ return nil;
1473+end;
1474+
1475+proc expression(var x: TItem; want: PType): ERROR;
1476+var y: TItem; L: INT; start: Diag.Pos;
1477+begin
1478+ start := Scan.tokPos();
1479+ try conjunct(x, want);
1480+ while Scan.tok = Scan.sOr do
1481+ Scan.next;
1482+ try Item.op1(Scan.sOr, x, L);
1483+ try conjunct(y, nil);
1484+ try Item.op2(Scan.sOr, x, y, L);
1485+ x.pos := Scan.spanFrom(start);
1486+ end;
1487+ return nil;
1488+end;
1489+
1490+(* Statements *)
1491+
1492+proc enterLoop(var lp: Loop; var old: PLoop);
1493+begin
1494+ lp.brk := Gen.NoLabel;
1495+ lp.base := numDefers;
1496+ old := curLoop;
1497+ curLoop := ADR(lp);
1498+end;
1499+
1500+(* Runs the deferred statements in force above base, newest first. *)
1501+proc runDefers(base: INT);
1502+var i: INT;
1503+begin
1504+ for i := numDefers - 1 to base by -1 do Gen.runDefer(defers[i]); end;
1505+end;
1506+
1507+(* Whether what follows "then" is a lone "break;", with no deferred
1508+ statement to run on the way out of the loop: the break must be the
1509+ branch's last statement, so ";" and then end, elsif or else follow. *)
1510+proc loneBreak: BOOL;
1511+var st: Scan.State; lone: BOOL;
1512+begin
1513+ if (Scan.tok # Scan.sBreak) or (curLoop = nil) or (numDefers # curLoop^.base) then return false; end;
1514+ Scan.saveScan(st);
1515+ lone := false;
1516+ Scan.next;
1517+ if Scan.tok = Scan.sSemicolon then
1518+ Scan.next;
1519+ lone := (Scan.tok = Scan.sEnd) or (Scan.tok = Scan.sElsif) or (Scan.tok = Scan.sElse);
1520+ end;
1521+ Scan.restoreScan(st);
1522+ return lone;
1523+end;
1524+
1525+(* The condition x of if or elsif, and the statements it guards, which
1526+ L skips when it is false. "if c then break; end" is one jump out of
1527+ the loop when c holds, not one past a jump out. *)
1528+proc thenPart(var x: TItem; var L: INT): ERROR;
1529+begin
1530+ try expect(Scan.sThen);
1531+ L := Gen.NoLabel; (* stays so with a lone break: there is nothing to skip *)
1532+ if loneBreak() then
1533+ Chunk.noteLine(Scan.curLine(), Scan.curCol()); (* the jump gets the break's line *)
1534+ try Item.condJumpTrue(x, curLoop^.brk);
1535+ Scan.next; Scan.next; (* skip "break" and ";" *)
1536+ ends := true;
1537+ else
1538+ try Item.condJump(x, L);
1539+ try statements();
1540+ end;
1541+ return nil;
1542+end;
1543+
1544+(* if, elsif and else: each condition's jump skips its branch to the
1545+ next; each branch that doesn't end jumps to the end. A branch that
1546+ ends, in return or break, needs no jump past the others, and all of
1547+ them ending is told to the caller in the global ends. *)
1548+proc ifStatement(start: Diag.Pos; ind: INT): ERROR;
1549+var x: TItem; L, endL: INT; all: BOOL;
1550+begin
1551+ Scan.next;
1552+ try expression(x, nil);
1553+ try thenPart(x, L);
1554+ all := ends;
1555+ endL := Gen.NoLabel;
1556+ while Scan.tok = Scan.sElsif do
1557+ if not ends then Gen.jump(endL); end;
1558+ Gen.fix(L);
1559+ Scan.next;
1560+ try expression(x, nil);
1561+ try thenPart(x, L);
1562+ all := all and ends;
1563+ end;
1564+ if Scan.tok = Scan.sElse then
1565+ if not ends then Gen.jump(endL); end;
1566+ Gen.fix(L);
1567+ Scan.next;
1568+ if Scan.tok = Scan.sIf then elseIf := true; end;
1569+ try statements();
1570+ all := all and ends;
1571+ else
1572+ Gen.fix(L);
1573+ all := false;
1574+ end;
1575+ try closeEnd(start, ind);
1576+ Gen.fix(endL);
1577+ ends := all;
1578+ return nil;
1579+end;
1580+
1581+(* while c do s end: the test comes after the body, and the loop jumps to
1582+ it first, so that a round takes one jump, back to the top if c holds:
1583+
1584+ jmp test rather than top: c, jump to out if false
1585+ top: s s
1586+ test: c, jump to top if true jmp top
1587+ out:
1588+
1589+ One pass reads c before s: so c is compiled where it is written, for
1590+ its messages, and its code taken back (rewind); then read again, and
1591+ compiled, after s (saveScan, restoreScan). *)
1592+proc whileStatement(start: Diag.Pos; ind: INT): ERROR;
1593+var
1594+ x: TItem; top, L, test: INT; lp: Loop; old: PLoop; cond, after: Scan.State; m: Gen.CodeMark;
1595+begin
1596+ Scan.next;
1597+ Scan.saveScan(cond);
1598+ Gen.markCode(m);
1599+ try expression(x, nil);
1600+ try Item.discard(x);
1601+ Gen.rewind(m);
1602+ try expect(Scan.sDo);
1603+ test := Gen.NoLabel;
1604+ Gen.jump(test);
1605+ Gen.alignLoop();
1606+ top := Chunk.pc;
1607+ enterLoop(lp, old);
1608+ try statements();
1609+ curLoop := old;
1610+ Scan.saveScan(after);
1611+ Scan.restoreScan(cond);
1612+ Gen.fix(test);
1613+ Chunk.noteLine(Scan.curLine(), Scan.curCol());
1614+ try expression(x, nil);
1615+ ends := (x.mode = Item.mConst) and (x.val # 0) and (lp.brk = Gen.NoLabel); (* while true *)
1616+ if (x.mode = Item.mConst) and (x.typ^.form = Sym.fBool) then
1617+ if x.val # 0 then Gen.jumpBack(top); end;
1618+ else
1619+ L := Gen.NoLabel;
1620+ try Item.condJumpTrue(x, L);
1621+ Gen.fixTo(L, top);
1622+ end;
1623+ Scan.restoreScan(after);
1624+ try closeEnd(start, ind);
1625+ Gen.fix(lp.brk);
1626+ return nil;
1627+end;
1628+
1629+proc repeatStatement: ERROR;
1630+var x: TItem; top, L: INT; lp: Loop; old: PLoop;
1631+begin
1632+ Scan.next;
1633+ top := Chunk.pc;
1634+ enterLoop(lp, old);
1635+ try statements();
1636+ curLoop := old;
1637+ try expect(Scan.sUntil);
1638+ try expression(x, nil);
1639+ ends := (x.mode = Item.mConst) and (x.val = 0) and (lp.brk = Gen.NoLabel); (* until false *)
1640+ L := Gen.NoLabel;
1641+ try Item.condJump(x, L);
1642+ Gen.fixTo(L, top);
1643+ Gen.fix(lp.brk);
1644+ return nil;
1645+end;
1646+
1647+(* for v := a to b by s do ... end, laid out as
1648+ v := a; the limit b, in a slot unless it is a constant
1649+ if v is past b then goto exit
1650+ goto body
1651+ top: v := v + s
1652+ body: the statements
1653+ the end of a round: goto top, or exit (forNext)
1654+ exit:
1655+ so that a round of a loop by 1 takes one compare and one jump. *)
1656+proc forStatement(start: Diag.Pos; ind: INT): ERROR;
1657+var
1658+ o: PObj; v, a, b, s: TItem; step: I64; top, body, bodyL, exitL: INT;
1659+ lp: Loop; old: PLoop; f: Sym.Form; slot: I64;
1660+begin
1661+ Scan.next;
1662+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
1663+ o := Sym.lookup(Scan.id);
1664+ if o = nil then
1665+ notDeclared(Scan.tokPos(), Scan.id);
1666+ return Scan.Failed;
1667+ end;
1668+ named(o);
1669+ if o^.cls # Sym.oVar then return Scan.mark(say1("{} isn't a variable", nameOf(Scan.id))); end;
1670+ f := o^.typ^.form;
1671+ if (f # Sym.fInt) and (f # Sym.fEnum) then
1672+ return Scan.mark(say1("a for loop needs an integer or enumeration variable, found {}", Sym.typeName(o^.typ)));
1673+ end;
1674+ Scan.next;
1675+ try expect(Scan.sBecomes);
1676+ try Item.makeItem(v, o);
1677+ try expression(a, o^.typ);
1678+ try Item.coerceExact(a, o^.typ, "");
1679+ try Item.assign(v, a);
1680+ try expect(Scan.sTo);
1681+ try expression(b, o^.typ);
1682+ try Item.coerceExact(b, o^.typ, "");
1683+ (* the limit, evaluated once: a constant as it is, else in a slot *)
1684+ if b.mode # Item.mConst then
1685+ slot := try Item.toSlot(b);
1686+ Item.tempItem(b, b.typ, slot);
1687+ end;
1688+ step := 1;
1689+ if Scan.tok = Scan.sBy then
1690+ Scan.next;
1691+ try expression(s, nil);
1692+ step := try constValue(s);
1693+ if step = 0 then return Scan.markAt(s.pos, "the step can't be zero"); end;
1694+ end;
1695+ try expect(Scan.sDo);
1696+ exitL := Gen.NoLabel;
1697+ if step > 0 then try Item.forCmp(o, b, Scan.sGtr, exitL); else try Item.forCmp(o, b, Scan.sLss, exitL); end;
1698+ bodyL := Gen.NoLabel;
1699+ Gen.jump(bodyL);
1700+ Gen.alignLoop();
1701+ top := Chunk.pc;
1702+ try Item.forStep(o, step);
1703+ Gen.fix(bodyL);
1704+ body := Chunk.pc;
1705+ enterLoop(lp, old);
1706+ try statements();
1707+ curLoop := old;
1708+ try closeEnd(start, ind);
1709+ try Item.forNext(o, b, step, exitL, top, body);
1710+ Gen.fix(exitL);
1711+ Gen.fix(lp.brk);
1712+ return nil;
1713+end;
1714+
1715+type
1716+ Labels = record
1717+ lo, hi: [MaxLabels]I64; (* the ranges of the labels so far *)
1718+ at: [MaxLabels]INT; (* where the arm of each starts *)
1719+ n: INT;
1720+ end;
1721+
1722+(* a < b, for values of an integer type, unsigned or not *)
1723+proc below(a, b: I64; unsign: BOOL): BOOL;
1724+begin
1725+ if unsign then return U64(a) < U64(b); end;
1726+ return a < b;
1727+end;
1728+
1729+(* An arm of a match on an integer of type t: its labels, each a
1730+ constant or a range, none overlapping another (report section 7.4),
1731+ then its statements. No code tests the labels here; dispatch does,
1732+ after the last arm, for which each label notes where its arm starts. *)
1733+proc intArm(t: PType; var ls: Labels; var endL: INT): ERROR;
1734+var lo, hi: TItem; first, i: INT; u: BOOL; start: Diag.Pos;
1735+begin
1736+ u := not t^.signed;
1737+ first := ls.n;
1738+ repeat
1739+ start := Scan.tokPos();
1740+ try expression(lo, t);
1741+ try Item.coerce(lo, t);
1742+ _ := try constValue(lo);
1743+ hi := lo;
1744+ if Scan.tok = Scan.sUpto then
1745+ Scan.next;
1746+ try expression(hi, t);
1747+ try Item.coerce(hi, t);
1748+ _ := try constValue(hi);
1749+ if below(hi.val, lo.val, u) then return Scan.markAt(Scan.spanFrom(start), "the range is empty"); end;
1750+ end;
1751+ for i := 0 to ls.n - 1 do
1752+ if not below(hi.val, ls.lo[i], u) and not below(ls.hi[i], lo.val, u) then
1753+ if lo.val = hi.val then
1754+ return Scan.markAt(Scan.spanFrom(start), say1("{} is in another label too", Diag.source(Scan.spanFrom(start))));
1755+ end;
1756+ return Scan.markAt(Scan.spanFrom(start), say1("{} overlaps another label", Diag.source(Scan.spanFrom(start))));
1757+ end;
1758+ end;
1759+ if ls.n >= MaxLabels then
1760+ return Scan.markAt(Scan.spanFrom(start), tooMany(MaxLabels, "labels in one match"));
1761+ end;
1762+ ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val;
1763+ INC(ls.n);
1764+ if Scan.tok # Scan.sComma then break; end;
1765+ Scan.next;
1766+ until false;
1767+ try expect(Scan.sColon);
1768+ for i := first to ls.n - 1 do ls.at[i] := Chunk.pc; end;
1769+ try statements();
1770+ Gen.jump(endL);
1771+ return nil;
1772+end;
1773+
1774+const
1775+ MinTable = 4; (* fewer labels are tested one by one *)
1776+ TableDensity = 8; (* a table has at most this many entries to a label *)
1777+
1778+(* The code that picks the arm, after the last one, which the match's
1779+ start jumped to: label by label, as a chain of compares each to its
1780+ arm; or, for four or more labels not far apart, a jump table (jumpTable),
1781+ which takes the same few instructions for any of them. It is here and
1782+ not before the arms, since a table can only be made once every arm's
1783+ place is known; an arm is entered by a jump back to it. elseAt is where
1784+ the else arm starts, or NoLabel. *)
1785+proc dispatch(t: PType; p: I64; var ls: Labels; elseAt: INT; var endL: INT);
1786+var
1787+ lo, hi: I64; i, start, v, body: INT; u: BOOL;
1788+ entry: [MaxLabels]INT;
1789+begin
1790+ u := (t^.form = Sym.fInt) and not t^.signed;
1791+ lo := 0; hi := 0;
1792+ if ls.n > 0 then
1793+ lo := ls.lo[0]; hi := ls.hi[0];
1794+ for i := 1 to ls.n - 1 do
1795+ if below(ls.lo[i], lo, u) then lo := ls.lo[i]; end;
1796+ if below(hi, ls.hi[i], u) then hi := ls.hi[i]; end;
1797+ end;
1798+ end;
1799+ if (ls.n >= MinTable) and (lo >= -2147483648) and (lo <= 2147483647)
1800+ and (U64(hi - lo) < U64(TableDensity * ls.n)) and (hi - lo < MaxLabels) then
1801+ start := Gen.jumpTable(p, lo, INT(hi - lo) + 1, elseAt, endL);
1802+ for v := 0 to INT(hi - lo) do
1803+ if elseAt # Gen.NoLabel then entry[v] := elseAt; else entry[v] := start; end;
1804+ end;
1805+ for i := 0 to ls.n - 1 do
1806+ for v := INT(ls.lo[i] - lo) to INT(ls.hi[i] - lo) do entry[v] := ls.at[i]; end;
1807+ end;
1808+ for v := 0 to INT(hi - lo) do Gen.tableEntry(start, entry[v]); end;
1809+ return;
1810+ end;
1811+ for i := 0 to ls.n - 1 do
1812+ body := Gen.NoLabel;
1813+ Item.matchRange(p, ls.lo[i], ls.hi[i], body);
1814+ Gen.fixTo(body, ls.at[i]);
1815+ end;
1816+ if elseAt # Gen.NoLabel then Gen.jumpBack(elseAt); end;
1817+end;
1818+
1819+proc matchStatement(start: Diag.Pos; ind: INT): ERROR;
1820+var
1821+ x: TItem; t: PType; c, f, o: PObj; p: I64; L, endL, n, first, disp, elseAt: INT;
1822+ seen: [256]BOOL; hasElse, all, byValue: BOOL; endAt: Diag.Pos; ls: Labels;
1823+begin
1824+ Scan.next;
1825+ try expression(x, nil);
1826+ if x.typ^.form = Sym.fConst then try Item.coerce(x, Sym.tI64); end;
1827+ p := try Item.matchBegin(x);
1828+ t := x.typ;
1829+ try expect(Scan.sOf);
1830+ hasElse := false;
1831+ all := true;
1832+ endL := Gen.NoLabel;
1833+ ls.n := 0;
1834+ (* an integer or an enumeration is matched by its value, and the arms
1835+ are picked by dispatch, after them; a variant by its tag, arm by arm *)
1836+ byValue := (t^.form = Sym.fInt) or (t^.form = Sym.fEnum);
1837+ disp := Gen.NoLabel;
1838+ elseAt := Gen.NoLabel;
1839+ if byValue then Gen.jump(disp); end;
1840+ while Scan.tok = Scan.sBar do
1841+ Scan.next;
1842+ if hasElse then return Scan.mark("else must be the last arm"); end;
1843+ if Scan.tok = Scan.sElse then
1844+ Scan.next;
1845+ try expect(Scan.sColon);
1846+ elseAt := Chunk.pc;
1847+ try statements();
1848+ if byValue then Gen.jump(endL); end;
1849+ hasElse := true;
1850+ elsif t^.form = Sym.fInt then
1851+ try intArm(t, ls, endL);
1852+ else
1853+ first := ls.n;
1854+ L := Gen.NoLabel;
1855+ repeat
1856+ if Scan.tok # Scan.sIdent then return expected("a case"); end;
1857+ c := t^.fields;
1858+ while (c # nil) and (c^.name # Scan.id) do c := c^.next; end;
1859+ if c = nil then
1860+ return Scan.mark(say2("{} isn't a case of {}", nameOf(Scan.id), Sym.typeName(t)));
1861+ end;
1862+ if (c^.val <= 255) and seen[c^.val] then
1863+ return Scan.mark(say1("{} has two arms", nameOf(c^.name)));
1864+ end;
1865+ if c^.val <= 255 then seen[c^.val] := true; end;
1866+ Scan.next;
1867+ if t^.form # Sym.fEnum then
1868+ Item.matchTag(p, c^.val, L);
1869+ break;
1870+ end;
1871+ (* an enumeration's arm may name several, which share its place *)
1872+ ls.lo[ls.n] := c^.val; ls.hi[ls.n] := c^.val;
1873+ INC(ls.n);
1874+ if Scan.tok # Scan.sComma then break; end;
1875+ Scan.next;
1876+ until false;
1877+ try Sym.openScope(Sym.newScope());
1878+ if Scan.tok = Scan.sLparen then
1879+ Scan.next;
1880+ f := c^.fields;
1881+ n := 0;
1882+ repeat
1883+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
1884+ if f = nil then
1885+ return Scan.mark(say1("more names than {} has fields", nameOf(c^.name)));
1886+ end;
1887+ o := Sym.newObj(Sym.oVar, Scan.id, f^.typ);
1888+ o^.lev := 1; o^.ind := true; o^.isVar := true;
1889+ o^.val := p; o^.off := f^.val;
1890+ try declare(o);
1891+ f := f^.next;
1892+ INC(n);
1893+ Scan.next;
1894+ if Scan.tok # Scan.sComma then break; end;
1895+ Scan.next;
1896+ until false;
1897+ if f # nil then
1898+ return Scan.mark(say1("name all the fields of {}, or none", nameOf(c^.name)));
1899+ end;
1900+ try expect(Scan.sRparen);
1901+ end;
1902+ try expect(Scan.sColon);
1903+ for n := first to ls.n - 1 do ls.at[n] := Chunk.pc; end;
1904+ try statements();
1905+ Sym.closeScope();
1906+ Gen.jump(endL);
1907+ if t^.form # Sym.fEnum then Gen.fix(L); end;
1908+ end;
1909+ all := all and ends;
1910+ end;
1911+ endAt := Scan.tokPos();
1912+ try closeEnd(start, ind);
1913+ ends := all;
1914+ if (t^.form = Sym.fInt) and not hasElse then
1915+ return Scan.markHelp(endAt, "a match on an integer needs an else arm", "it may be empty: | else:");
1916+ end;
1917+ if not hasElse then
1918+ c := t^.fields;
1919+ while c # nil do
1920+ if (c^.val > 255) or not seen[c^.val] then
1921+ return Scan.markAt(endAt, say1("no arm for {}", nameOf(c^.name)));
1922+ end;
1923+ c := c^.next;
1924+ end;
1925+ end;
1926+ if byValue then
1927+ Gen.fix(disp);
1928+ dispatch(t, p, ls, elseAt, endL);
1929+ end;
1930+ Gen.fix(endL);
1931+ return nil;
1932+end;
1933+
1934+(* What a message calls x: its name n when x is just that name, else what
1935+ it is. *)
1936+proc subject(x: TItem; n: INT): []U8;
1937+begin
1938+ if x.pos.b - x.pos.a = LEN(nameOf(n)) then return nameOf(n); end;
1939+ if x.mode = Item.mConst then return "a constant"; end;
1940+ return "a value";
1941+end;
1942+
1943+(* x, named first n, is a variable the program may assign: not an
1944+ array constant, nor any part of one. *)
1945+proc assignable(x: TItem; n: INT): ERROR;
1946+begin
1947+ if (x.mode = Item.mConst) and (subject(x, n) = nameOf(n)) then
1948+ return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(n)));
1949+ end;
1950+ if (x.mode = Item.mVar) and (x.obj # nil) and (x.obj^.cls = Sym.oConst) then
1951+ return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(x.obj^.name)));
1952+ end;
1953+ if (x.mode # Item.mVar) or not x.isVar then
1954+ return Scan.markAt(x.pos, say1("can't assign to {}", subject(x, n)));
1955+ end;
1956+ return nil;
1957+end;
1958+
1959+(* The designator a statement starts with. A variable named whole
1960+ before := is assigned, not read: naming it there leaves it as unread
1961+ as it was. *)
1962+proc leftSide(var x: TItem; var called: BOOL): ERROR;
1963+var o: PObj; wasRead: BOOL; n: INT;
1964+begin
1965+ n := Scan.id;
1966+ o := Sym.lookup(n);
1967+ wasRead := (o # nil) and o^.read;
1968+ try designator(x, called);
1969+ if ((Scan.tok = Scan.sBecomes) or (Scan.tok = Scan.sComma)) and (x.pos.b - x.pos.a = LEN(nameOf(n))) then
1970+ o^.read := wasRead;
1971+ end;
1972+ return nil;
1973+end;
1974+
1975+(* a, b := f(x): the variables first, left to right, then the call;
1976+ then each result to its variable, in order. x is the first variable,
1977+ first its name, blank whether it is _. *)
1978+proc multiAssign(var x: TItem; first: INT; blank: BOOL): ERROR;
1979+var
1980+ d: [16]TItem; dn: [16]INT; blanks: [16]BOOL;
1981+ y, z: TItem; n, i: INT; called: BOOL; f: PObj;
1982+begin
1983+ n := 0;
1984+ d[0] := x;
1985+ dn[0] := first;
1986+ blanks[0] := blank;
1987+ repeat
1988+ if not blanks[n] then
1989+ try Item.notReadOnly(d[n]);
1990+ try assignable(d[n], dn[n]);
1991+ try Item.pin(d[n]); (* works out the address now, so that the call can't change it *)
1992+ end;
1993+ INC(n);
1994+ if Scan.tok # Scan.sComma then break; end;
1995+ if n > 15 then return Scan.mark(tooMany(16, "variables in one assignment")); end;
1996+ Scan.next;
1997+ blanks[n] := Scan.tok = Scan.sBlank;
1998+ if blanks[n] then
1999+ Scan.next;
2000+ else
2001+ dn[n] := Scan.id;
2002+ try leftSide(d[n], called);
2003+ end;
2004+ until false;
2005+ try expect(Scan.sBecomes);
2006+ if Scan.tok = Scan.sTry then
2007+ try tryCall(y);
2008+ called := true;
2009+ else
2010+ try designator(y, called);
2011+ end;
2012+ if not called or not y.typ^.tuple or (y.typ^.len # I64(n)) then
2013+ return Scan.markAt(y.pos, Diag.say("expected a call with {} results", [Fmt.int(n)]));
2014+ end;
2015+ (* two results on the stack: the first is brought to the top, and each
2016+ is popped into its variable in turn, as one value; else each is
2017+ read from the temporary they came back in *)
2018+ if y.mode = Item.mWords then Gen.swap(); end;
2019+ f := y.typ^.fields;
2020+ for i := 0 to n - 1 do
2021+ z := y;
2022+ if y.mode = Item.mWords then
2023+ z.mode := Item.mStack; z.typ := f^.typ;
2024+ else
2025+ try Item.field(z, f);
2026+ end;
2027+ if blanks[i] then
2028+ try Item.discard(z);
2029+ else
2030+ try Item.coerceExact(z, d[i].typ, "several results go to variables of just their types");
2031+ try Item.assign(d[i], z);
2032+ end;
2033+ f := f^.next;
2034+ end;
2035+ return nil;
2036+end;
2037+
2038+(* return a, b; or return f(x); with f's several results passed on *)
2039+proc returnResults: ERROR;
2040+var f: PObj; x: TItem;
2041+begin
2042+ f := curResult^.fields;
2043+ passOn := true;
2044+ while f # nil do
2045+ try expression(x, f^.typ);
2046+ if x.typ^.tuple then
2047+ if not Sym.same(x.typ, curResult) then
2048+ return Scan.markAt(x.pos, say2("expected the results {}, found {}", Sym.typeName(curResult), Sym.typeName(x.typ)));
2049+ end;
2050+ return Item.returnAll(x);
2051+ end;
2052+ try Item.returnField(f, x);
2053+ f := f^.next;
2054+ if f # nil then try expect(Scan.sComma); end;
2055+ end;
2056+ return nil;
2057+end;
2058+
2059+(* defer s: s is compiled where it stands, as a little subroutine of the
2060+ procedure, jumped over; each way out of the statement list calls it. *)
2061+proc deferStatement: ERROR;
2062+var L, pos, saved: INT; oldLoop: PLoop; oldDeferring: BOOL; start: Diag.Pos;
2063+begin
2064+ start := Scan.tokPos();
2065+ Scan.next;
2066+ if directDefer then return Scan.markAt(Scan.spanFrom(start), "defer can't be deferred"); end;
2067+ if numDefers >= MaxDefers then
2068+ return Scan.markAt(Scan.spanFrom(start), tooMany(MaxDefers, "deferred statements in one procedure"));
2069+ end;
2070+ L := Gen.NoLabel;
2071+ pos, saved := Gen.deferBegin(L);
2072+ oldLoop := curLoop; oldDeferring := deferring;
2073+ curLoop := nil;
2074+ deferring := true;
2075+ directDefer := true;
2076+ try statement();
2077+ directDefer := false;
2078+ curLoop := oldLoop; deferring := oldDeferring;
2079+ Gen.deferEnd(L, saved);
2080+ defers[numDefers] := pos;
2081+ INC(numDefers);
2082+ return nil;
2083+end;
2084+
2085+(* Whether the expression of x := ..., which starts at the current
2086+ symbol, is x changed by adding to it, taking from it or its bits:
2087+ x + e, x - e, x | e or x xor e, with x nowhere in e, so that it can be
2088+ worked out in x's own register, if x is in one (Gen's inPlace). *)
2089+proc changesItself(x: TItem): BOOL;
2090+var st: Scan.State; wasSkipping, changes: BOOL; d: INT;
2091+begin
2092+ if (x.mode # Item.mVar) or (x.base # Gen.bReg) or (x.typ^.form = Sym.fSlice)
2093+ or (Scan.tok # Scan.sIdent) or (Scan.id # x.obj^.name) then
2094+ return false;
2095+ end;
2096+ changes := false;
2097+ Scan.saveScan(st);
2098+ wasSkipping := Scan.skipping;
2099+ Scan.setSkipping(true); (* its slips are told when it is compiled *)
2100+ Scan.next;
2101+ if isAddOp() then
2102+ changes := true;
2103+ d := 0;
2104+ while not ((d = 0) and ((Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEnd))) and (Scan.tok # Scan.sEof) do
2105+ if (Scan.tok = Scan.sIdent) and (Scan.id = x.obj^.name) then changes := false; end;
2106+ match Scan.tok of
2107+ | sLparen, sLbrak, sLbrace: INC(d);
2108+ | sRparen, sRbrak, sRbrace: DEC(d);
2109+ | else:
2110+ end;
2111+ Scan.next;
2112+ end;
2113+ end;
2114+ Scan.restoreScan(st);
2115+ Scan.setSkipping(wasSkipping);
2116+ return changes;
2117+end;
2118+
2119+(* A call standing on its own, which drops the results x holds, if any,
2120+ to be warned of *)
2121+proc noteDrop(x: TItem);
2122+begin
2123+ if (x.mode # Item.mNone) and (numDrops < MaxDrops) then
2124+ drops[numDrops].at := x.pos;
2125+ if x.typ^.tuple then drops[numDrops].n := INT(x.typ^.len); else drops[numDrops].n := 1; end;
2126+ INC(numDrops);
2127+ end;
2128+end;
2129+
2130+proc oneStatement: ERROR;
2131+var
2132+ x, y: TItem; called: BOOL; m: I64; c: Gen.CallInfo; start: Diag.Pos; first, n, i: INT; k: Gen.Kind;
2133+begin
2134+ start := Scan.tokPos();
2135+ first := Scan.id;
2136+ Chunk.noteLine(Scan.curLine(), Scan.curCol());
2137+ m := Gen.tempMark();
2138+ ends := false;
2139+ match Scan.tok of
2140+ | sIdent:
2141+ try leftSide(x, called);
2142+ if Scan.tok = Scan.sBecomes then
2143+ try Item.notReadOnly(x);
2144+ try assignable(x, first);
2145+ Scan.next;
2146+ if changesItself(x) then Gen.setInPlace(x.chunk); end;
2147+ try expression(y, x.typ);
2148+ Gen.setInPlace(-1);
2149+ try Item.assign(x, y);
2150+ elsif Scan.tok = Scan.sComma then
2151+ try multiAssign(x, first, false);
2152+ elsif not called then
2153+ if (x.mode = Item.mProc)
2154+ or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc)) then
2155+ try Item.beginCall(c, x);
2156+ try Item.endCall(c, x);
2157+ try Item.discard(x);
2158+ elsif Scan.tok = Scan.sEql then
2159+ return Scan.markHelp(x.pos, say1("{} isn't a statement", subject(x, first)), "assignment is written :=");
2160+ else
2161+ return Scan.markAt(x.pos, say1("{} isn't a statement", subject(x, first)));
2162+ end;
2163+ else
2164+ noteDrop(x);
2165+ try Item.discard(x);
2166+ end;
2167+ | sBlank:
2168+ Scan.next;
2169+ if Scan.tok = Scan.sComma then
2170+ try multiAssign(x, 0, true);
2171+ else
2172+ try expect(Scan.sBecomes);
2173+ try expression(x, nil);
2174+ (* evaluated and dropped: a single value is loaded, so that a
2175+ volatile one is read *)
2176+ if (x.mode = Item.mType) or (x.mode = Item.mBuiltin) or (x.mode = Item.mNone) or (x.mode = Item.mCase)
2177+ or ((x.mode # Item.mStr) and not Sym.isAggregate(x.typ)) then
2178+ try Item.value(x);
2179+ end;
2180+ try Item.discard(x);
2181+ end;
2182+ | sIf: try ifStatement(start, Scan.indent());
2183+ | sWhile: try whileStatement(start, Scan.indent());
2184+ | sRepeat: try repeatStatement();
2185+ | sFor: try forStatement(start, Scan.indent());
2186+ | sMatch: try matchStatement(start, Scan.indent());
2187+ | sReturn:
2188+ Scan.next;
2189+ if deferring then return Scan.markAt(Scan.spanFrom(start), "return can't leave a deferred statement"); end;
2190+ if Scan.tok = Scan.sSemicolon then
2191+ runDefers(0);
2192+ try Item.returnNone();
2193+ else
2194+ if (curResult # nil) and curResult^.tuple then
2195+ try returnResults();
2196+ else
2197+ try expression(x, curResult);
2198+ try Item.returnValue(x);
2199+ end;
2200+ (* the result, one value or two words on top, waits in the frame
2201+ while the deferred statements run *)
2202+ if (numDefers > 0) and (curResult # nil) and not Sym.behindPointer(curResult) then
2203+ n := 1; k := Gen.kindOf(curResult);
2204+ if Sym.inTwoRegs(curResult) then n := 2; k := Gen.kWord; end;
2205+ if deferSlot = 0 then deferSlot := Gen.allocPerm(16, 8); end;
2206+ for i := n - 1 to 0 by -1 do Gen.popVar(Item.frameAdr(deferSlot + I64(8 * i)), 8); end;
2207+ runDefers(0);
2208+ for i := 0 to n - 1 do Gen.pushVar(Item.frameAdr(deferSlot + I64(8 * i)), 8, false, k); end;
2209+ else
2210+ runDefers(0);
2211+ end;
2212+ Gen.returnJump();
2213+ ends := true;
2214+ end;
2215+ | sBreak:
2216+ Scan.next;
2217+ if curLoop = nil then return Scan.markAt(Scan.spanFrom(start), "break outside a loop"); end;
2218+ runDefers(curLoop^.base);
2219+ Gen.jump(curLoop^.brk);
2220+ | sDefer: try deferStatement();
2221+ | sTry:
2222+ try tryCall(x);
2223+ noteDrop(x);
2224+ try Item.discard(x);
2225+ | sArrow:
2226+ return Scan.markHelp(Scan.tokPos(), "a statement starts with a name",
2227+ "convert into a pointer variable, then assign through that");
2228+ | else:
2229+ if Scan.atLineStart() then
2230+ return endMissing(Scan.missingPos(), say1("expected \"end\", found {}", Scan.found()));
2231+ end;
2232+ return expected("a statement");
2233+ end;
2234+ Gen.releaseTemps(m);
2235+ return nil;
2236+end;
2237+
2238+proc statement: ERROR;
2239+var r: Recover; m: I64; err: ERROR;
2240+begin
2241+ m := Gen.tempMark();
2242+ guard(r);
2243+ err := oneStatement();
2244+ if err = nil then
2245+ skipped := false;
2246+ else
2247+ restore(r);
2248+ (* a statement never starts a line: this is the next declaration *)
2249+ if Scan.atLineStart() or not skipConstruct() then return giveUp(r); end;
2250+ Gen.releaseTemps(m);
2251+ skipped := true;
2252+ end;
2253+ unguard(r);
2254+ return nil;
2255+end;
2256+
2257+proc endsStatements: BOOL;
2258+begin
2259+ match Scan.tok of
2260+ | sEnd, sElse, sElsif, sUntil, sBar, sEof: return true;
2261+ | else: return false;
2262+ end;
2263+end;
2264+
2265+proc statements: ERROR;
2266+var base: INT; old: BOOL;
2267+begin
2268+ base := numDefers;
2269+ old := directDefer;
2270+ directDefer := false;
2271+ ends := false;
2272+ while not endsStatements() do
2273+ try statement();
2274+ if not skipped or (Scan.tok = Scan.sSemicolon) then try expect(Scan.sSemicolon); end;
2275+ end;
2276+ runDefers(base);
2277+ numDefers := base;
2278+ directDefer := old;
2279+ return nil;
2280+end;
2281+
2282+(* Declarations *)
2283+
2284+(* In a file read for its interface only: skip a procedure's body, from
2285+ its local declarations to the end that closes it. *)
2286+proc skipBody: ERROR;
2287+var d: INT; sawBegin: BOOL;
2288+begin
2289+ d := 0;
2290+ sawBegin := false;
2291+ repeat
2292+ match Scan.tok of
2293+ | sBegin:
2294+ if d = 0 then sawBegin := true; end;
2295+ INC(d);
2296+ | sIf, sWhile, sFor, sMatch, sRecord, sVariant: INC(d);
2297+ | sEnd:
2298+ DEC(d);
2299+ if (d = 0) and sawBegin then
2300+ Scan.next;
2301+ return nil;
2302+ end;
2303+ | sEof: return expected("\"end\"");
2304+ | else:
2305+ end;
2306+ Scan.next;
2307+ until false;
2308+ return nil;
2309+end;
2310+
2311+proc declarations(top: BOOL); forward;
2312+
2313+(* How Rt shows a variable of o's type in the trap report: 1 a signed
2314+ integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus
2315+ its size times 16, and 256 if the frame holds its address, or 512
2316+ times 1 + i if it is in register ShownRegs[i]; 0 if it isn't shown. *)
2317+proc varKind(o: PObj): INT;
2318+var k, i, v: INT;
2319+begin
2320+ match o^.typ^.form of
2321+ | fInt: if o^.typ^.signed then k := 1; else k := 2; end;
2322+ | fEnum, fSet: k := 2;
2323+ | fBool: k := 3;
2324+ | fPtr, fProc, fError: k := 4;
2325+ | fReal: k := 5;
2326+ | else: return 0;
2327+ end;
2328+ v := k + INT(o^.typ^.size) * 16;
2329+ if o^.ind then v := v + 256; end;
2330+ for i := 0 to LEN(Gen.ShownRegs) - 1 do
2331+ if o^.reg = Gen.ShownRegs[i] then v := k + INT(o^.typ^.size) * 16 + (i + 1) * 512; end;
2332+ end;
2333+ return v;
2334+end;
2335+
2336+(* Whether variable o could live in registers: a single value, a real
2337+ in an xmm register, or a slice, in two, that isn't C's *)
2338+proc regFit(o: PObj): BOOL;
2339+var f: Sym.Form;
2340+begin
2341+ if (o^.cls # Sym.oVar) or o^.ind or o^.ext then return false; end;
2342+ f := o^.typ^.form;
2343+ return (f = Sym.fInt) or (f = Sym.fBool) or (f = Sym.fEnum) or (f = Sym.fPtr) or (f = Sym.fProc)
2344+ or (f = Sym.fError) or (f = Sym.fSlice) or (f = Sym.fReal)
2345+ or ((f = Sym.fSet) and (o^.typ^.size <= 8));
2346+end;
2347+
2348+(* The first local of the procedure being compiled. Locals are chained
2349+ by chain in the order declared, the module's own first; before is the
2350+ last one declared before the procedure's, or nil if there was none. *)
2351+proc firstLocal(before: PObj): PObj;
2352+begin
2353+ if before = nil then return Sym.curModule^.locals; end;
2354+ return before^.chain;
2355+end;
2356+
2357+const MaxCand = 64; (* variables of a procedure that may go in registers *)
2358+
2359+var
2360+ cand: [MaxCand]PObj; (* chooseRegs's candidates and their weights *)
2361+ weight: [MaxCand]INT;
2362+ numCand: INT;
2363+
2364+proc candidate(n: INT): INT;
2365+var j: INT;
2366+begin
2367+ for j := 0 to numCand - 1 do
2368+ if cand[j]^.name = n then return j; end;
2369+ end;
2370+ return -1;
2371+end;
2372+
2373+proc addCandidate(o: PObj);
2374+begin
2375+ if regFit(o) and (numCand < MaxCand) then
2376+ cand[numCand] := o;
2377+ weight[numCand] := 0;
2378+ INC(numCand);
2379+ end;
2380+end;
2381+
2382+(* Whether naming o may make a call: a procedure, a procedure variable,
2383+ or NEW, SYSCALL or COPY, which use the registers a call would *)
2384+proc calls(o: PObj): BOOL;
2385+begin
2386+ if o = nil then return false; end;
2387+ return (o^.cls = Sym.oProc) or ((o^.cls = Sym.oVar) and (o^.typ^.form = Sym.fProc))
2388+ or ((o^.cls = Sym.oBuiltin) and ((o^.val = Sym.bNew) or (o^.val = Sym.bSyscall) or (o^.val = Sym.bCopy)));
2389+end;
2390+
2391+(* Puts the busiest variables of the procedure, whose parameters are
2392+ params and whose locals follow before, in registers: read ahead from
2393+ its "begin" to its end, a use counts 1, in a loop 4, in two 16, in
2394+ three or more 64, and a variable ADR is taken of can't have one. A register costs a save
2395+ and a restore, so a variable used less than three times keeps its
2396+ place in memory. A slice takes two, its pointer's and its length's;
2397+ a real one of the xmm registers, stored and loaded again around each
2398+ call, as System V keeps none through one. In a procedure that names no procedure, so calls nothing, the
2399+ parameters that arrive in the registers no call needs stay there
2400+ (keepArrived), at no cost. *)
2401+proc chooseRegs(params, before: PObj);
2402+var
2403+ isLoop: [256]BOOL;
2404+ i, k, kx, d, loops, best, need: INT; o, q, qual: PObj; st: Scan.State;
2405+ afterDot, wasSkipping, leaf: BOOL;
2406+begin
2407+ numCand := 0;
2408+ o := params;
2409+ while o # nil do addCandidate(o); o := o^.next; end;
2410+ o := firstLocal(before);
2411+ while o # nil do addCandidate(o); o := o^.chain; end;
2412+ if numCand = 0 then return; end;
2413+ Scan.saveScan(st);
2414+ wasSkipping := Scan.skipping;
2415+ Scan.setSkipping(true); (* its slips are told when it is compiled *)
2416+ d := 0; loops := 0; afterDot := false; leaf := true; qual := nil;
2417+ repeat
2418+ (* a name, or a module's name and one of its exports, that calls *)
2419+ if (Scan.tok = Scan.sIdent) and not afterDot then
2420+ q := Sym.lookup(Scan.id);
2421+ if calls(q) then leaf := false; end;
2422+ qual := nil;
2423+ if (q # nil) and (q^.cls = Sym.oModule) then qual := q; end;
2424+ elsif (Scan.tok = Scan.sIdent) and (qual # nil) then
2425+ if (qual^.home = nil) or calls(Sym.find(qual^.home^.scope, Scan.id)) then leaf := false; end;
2426+ qual := nil;
2427+ end;
2428+ match Scan.tok of
2429+ | sBegin, sIf, sMatch, sWhile, sFor, sRepeat:
2430+ if d < 255 then
2431+ INC(d);
2432+ isLoop[d] := (Scan.tok = Scan.sWhile) or (Scan.tok = Scan.sFor) or (Scan.tok = Scan.sRepeat);
2433+ if isLoop[d] then INC(loops); end;
2434+ end;
2435+ | sEnd, sUntil:
2436+ if isLoop[d] then DEC(loops); end;
2437+ DEC(d);
2438+ | sIdent:
2439+ if Scan.id = nameAdr then
2440+ Scan.next;
2441+ if Scan.tok = Scan.sLparen then Scan.next; end;
2442+ (* a hugely negative weight bars it from a register, whatever
2443+ its uses add *)
2444+ if (Scan.tok = Scan.sIdent) and (candidate(Scan.id) >= 0) then weight[candidate(Scan.id)] := -1073741824; end;
2445+ elsif not afterDot and (candidate(Scan.id) >= 0) then
2446+ k := candidate(Scan.id);
2447+ if loops > 2 then INC(weight[k], 64); else INC(weight[k], 1 shl (2 * loops)); end;
2448+ end;
2449+ | else:
2450+ end;
2451+ afterDot := Scan.tok = Scan.sPeriod; (* a name after a dot is a field, not a variable *)
2452+ if (d > 0) and (Scan.tok # Scan.sEof) then Scan.next; end;
2453+ until (d = 0) or (Scan.tok = Scan.sEof);
2454+ Scan.restoreScan(st);
2455+ Scan.setSkipping(wasSkipping);
2456+ if leaf then
2457+ o := params;
2458+ while o # nil do
2459+ k := candidate(o^.name);
2460+ if (k >= 0) and (weight[k] >= 0) then Gen.keepArrived(o); end; (* a candidate whose ADR isn't taken *)
2461+ o := o^.next;
2462+ end;
2463+ end;
2464+ (* a slice's weight is shared by its two registers *)
2465+ for i := 0 to numCand - 1 do
2466+ if cand[i]^.typ^.form = Sym.fSlice then weight[i] := weight[i] div 2; end;
2467+ end;
2468+ (* the heaviest, each used at least three times a register, take the
2469+ five registers in turn, while there are enough for each, and the
2470+ reals the four xmm registers of XVarRegs *)
2471+ k := 0; kx := 0;
2472+ repeat
2473+ best := -1;
2474+ for i := 0 to numCand - 1 do
2475+ if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i; end;
2476+ end;
2477+ if best < 0 then break; end;
2478+ need := 1;
2479+ if cand[best]^.typ^.form = Sym.fSlice then need := 2; end;
2480+ if cand[best]^.typ^.form = Sym.fReal then
2481+ if kx < 4 then
2482+ cand[best]^.reg := Gen.XVarRegs[kx];
2483+ INC(kx);
2484+ else
2485+ weight[best] := 0;
2486+ end;
2487+ elsif k + need <= 5 then
2488+ cand[best]^.reg := Gen.VarRegs[k];
2489+ if need = 2 then cand[best]^.reg2 := Gen.VarRegs[k + 1]; end;
2490+ INC(k, need);
2491+ else
2492+ weight[best] := 0; (* too big for what is left *)
2493+ end;
2494+ until false;
2495+end;
2496+
2497+(* The registers the variables of the procedure are in, as bits: bit i
2498+ is VarRegs[i], bit XBit + i XVarRegs[i] *)
2499+proc regBits(o: PObj): INT;
2500+var m, k: INT;
2501+begin
2502+ m := 0;
2503+ for k := 0 to 4 do
2504+ if (o^.reg = Gen.VarRegs[k]) or (o^.reg2 = Gen.VarRegs[k]) then m := m | (1 shl k); end;
2505+ end;
2506+ for k := 0 to 3 do
2507+ if o^.reg = Gen.XVarRegs[k] then m := m | (1 shl (Gen.XBit + k)); end;
2508+ end;
2509+ return m;
2510+end;
2511+
2512+proc regsOf(params, before: PObj): INT;
2513+var o: PObj; m: INT;
2514+begin
2515+ m := 0;
2516+ o := params;
2517+ while o # nil do
2518+ m := m | regBits(o);
2519+ o := o^.next;
2520+ end;
2521+ o := firstLocal(before);
2522+ while o # nil do
2523+ if o^.cls = Sym.oVar then m := m | regBits(o); end;
2524+ o := o^.chain;
2525+ end;
2526+ return m;
2527+end;
2528+
2529+(* Gives each local not in a register its slot in the frame, the slots
2530+ the prologue zeroes, and then tells Gen which registers the
2531+ variables are in. A variable in a register has no slot: it starts at
2532+ zero in its register, and the trap report finds it there. *)
2533+proc placeLocals(params, before: PObj);
2534+var o: PObj;
2535+begin
2536+ Gen.resetLocals();
2537+ o := firstLocal(before);
2538+ while o # nil do
2539+ if (o^.cls = Sym.oVar) and (o^.reg = 0) then
2540+ o^.val := Gen.allocPerm(o^.typ^.size, o^.typ^.align);
2541+ elsif (o^.cls = Sym.oVar) and (o^.reg >= Gen.XmmVar) then
2542+ o^.val := Gen.allocPerm(8, 8);
2543+ Gen.xHome(o^.reg, o^.val);
2544+ end;
2545+ o := o^.chain;
2546+ end;
2547+ o := params;
2548+ while o # nil do
2549+ if o^.reg >= Gen.XmmVar then Gen.xHome(o^.reg, o^.val); end;
2550+ o := o^.next;
2551+ end;
2552+ Gen.useRegs(regsOf(params, before));
2553+end;
2554+
2555+proc body(p: PObj; sig: PType; line: INT): ERROR;
2556+var
2557+ q, params, last, o, before: PObj; old: PType; st: Scan.State;
2558+ mark: Gen.CodeMark; drops0, errs: INT;
2559+begin
2560+ try Sym.openScope(Sym.newScope());
2561+ params := nil; last := nil;
2562+ q := sig^.fields;
2563+ while q # nil do
2564+ o := Sym.newObj(Sym.oVar, q^.name, q^.typ);
2565+ o^.pos := q^.pos;
2566+ o^.lev := 1;
2567+ o^.isVar := q^.isVar;
2568+ o^.param := true;
2569+ if last = nil then params := o; else last^.next := o; end;
2570+ last := o;
2571+ q := q^.next;
2572+ end;
2573+ Item.beginProc(sig, params);
2574+ deferSlot := 0;
2575+ o := params;
2576+ while o # nil do
2577+ q := o^.next;
2578+ try declare(o);
2579+ o := q;
2580+ end;
2581+ curProc := p;
2582+ before := Sym.curModule^.lastLocal;
2583+ declarations(false);
2584+ chooseRegs(params, before);
2585+ placeLocals(params, before);
2586+ (* the body, made again if a variable in a register must be in memory *)
2587+ Scan.saveScan(st);
2588+ Gen.markCode(mark); drops0 := numDrops; errs := Diag.errors;
2589+ old := curResult;
2590+ repeat
2591+ Item.setDemoted(false);
2592+ try expect(Scan.sBegin);
2593+ curResult := sig^.base;
2594+ Gen.enterBody(p^.chunk, line);
2595+ stray := false; elseIf := false; deferSlot := 0;
2596+ try statements();
2597+ p^.openEnd := (curResult # nil) and not ends;
2598+ Chunk.noteLine(Scan.curLine(), Scan.curCol());
2599+ try expect(Scan.sEnd);
2600+ if not (Item.demoted or Gen.lost) or (Diag.errors # errs) then break; end;
2601+ (* a parameter kept where it arrived goes to memory: a call or a copy
2602+ wanted its register *)
2603+ if Gen.lost then
2604+ o := params;
2605+ while o # nil do
2606+ if Gen.keptIn(o) then o^.reg := 0; o^.reg2 := 0; end;
2607+ o := o^.next;
2608+ end;
2609+ end;
2610+ numDrops := drops0;
2611+ Gen.redo(mark);
2612+ placeLocals(params, before);
2613+ Scan.restoreScan(st);
2614+ until false;
2615+ try Gen.endProc(p^.chunk, p^.openEnd);
2616+ (* its parameters and variables, for the trap report *)
2617+ o := firstLocal(before);
2618+ q := params;
2619+ while q # nil do
2620+ if varKind(q) # 0 then Chunk.noteVar(p^.chunk, q^.name, INT(q^.val), varKind(q)); end;
2621+ q := q^.next;
2622+ end;
2623+ while o # nil do
2624+ if (o^.cls = Sym.oVar) and (varKind(o) # 0) then Chunk.noteVar(p^.chunk, o^.name, INT(o^.val), varKind(o)); end;
2625+ o := o^.chain;
2626+ end;
2627+ curResult := old;
2628+ curProc := nil;
2629+ Sym.closeScope();
2630+ return nil;
2631+end;
2632+
2633+(* An integer constant in a code procedure, for the assembler: a whole
2634+ expression, or a single factor where an expression would read on
2635+ too far *)
2636+proc asmConst(whole: BOOL): (I64, ERROR);
2637+var x: TItem;
2638+begin
2639+ if whole then return constExpr(); end;
2640+ try factor(x, nil);
2641+ if not Sym.isInt(x.typ) then
2642+ return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x)));
2643+ end;
2644+ return constValue(x);
2645+end;
2646+
2647+proc codeBody(p: PObj; sig: PType; at: Diag.Pos): ERROR;
2648+var q: PObj; ni, nf: INT;
2649+begin
2650+ ni := 0; nf := 0;
2651+ q := sig^.fields;
2652+ while q # nil do
2653+ if not q^.isVar and (q^.typ^.form = Sym.fSlice) then
2654+ INC(ni, 2); (* address, then length *)
2655+ else
2656+ if not q^.isVar and not Sym.isScalar(q^.typ) then
2657+ return Scan.markAt(at, "a code procedure takes integers, BOOL, reals, pointers, procedures and slices");
2658+ end;
2659+ if (q^.typ^.form = Sym.fReal) and not q^.isVar then INC(nf); else INC(ni); end;
2660+ end;
2661+ q := q^.next;
2662+ end;
2663+ if (ni > 6) or (nf > 8) or sig^.variadic then
2664+ return Scan.markAt(at, "too many parameters for a code procedure");
2665+ end;
2666+ if sig^.base # nil then
2667+ if sig^.base^.tuple then
2668+ q := sig^.base^.fields;
2669+ if (sig^.base^.len # 2) or (q^.typ^.size # 8) or (q^.next^.typ^.size # 8)
2670+ or not Sym.isScalar(q^.typ) or not Sym.isScalar(q^.next^.typ)
2671+ or (q^.typ^.form = Sym.fReal) or (q^.next^.typ^.form = Sym.fReal) then
2672+ return Scan.markAt(at, "a code procedure returns two results only in rax and rdx");
2673+ end;
2674+ elsif not Sym.isScalar(sig^.base) and (sig^.base^.form # Sym.fSlice) then
2675+ return Scan.markAt(at, "a code procedure returns a single value");
2676+ end;
2677+ end;
2678+ try Gen.codeProc(p^.chunk, asmConst);
2679+ return expect(Scan.sEnd);
2680+end;
2681+
2682+proc procDecl: ERROR;
2683+var n, line: INT; exp: BOOL; sig: PType; p: PObj; at: Diag.Pos;
2684+begin
2685+ try instancesFor(false);
2686+ line := Scan.curLine();
2687+ Scan.next;
2688+ try identDef(n, exp, at);
2689+ sig := try signature();
2690+ try expect(Scan.sSemicolon);
2691+ p := Sym.find(Sym.topScope(), n);
2692+ if (p # nil) and (p^.cls = Sym.oProc) and p^.fwd then
2693+ if not Sym.same(p^.typ, sig) then
2694+ Diag.error(at, say1("{} doesn't have the signature it was declared forward with", nameOf(n)));
2695+ Diag.note(p^.pos, "the signature is here");
2696+ return Scan.Failed;
2697+ end;
2698+ if Scan.tok = Scan.sForward then return Scan.mark(say1("{} is declared forward twice", nameOf(n))); end;
2699+ p^.exported := p^.exported or exp;
2700+ else
2701+ p := Sym.newObj(Sym.oProc, n, sig);
2702+ p^.pos := at;
2703+ p^.exported := exp;
2704+ if (Sym.curModule^.name = nameRt) and not checkMode and (n = nameFail) then
2705+ p^.chunk := Gen.rtFail;
2706+ else
2707+ p^.chunk := Chunk.newChunk(Chunk.secText, Sym.curModule^.sname, n);
2708+ end;
2709+ try declare(p);
2710+ end;
2711+ if Scan.tok = Scan.sForward then
2712+ Scan.next;
2713+ p^.fwd := true;
2714+ return nil;
2715+ end;
2716+ p^.fwd := false;
2717+ if Scan.tok = Scan.sCode then
2718+ Scan.next;
2719+ p^.isCode := true;
2720+ try codeBody(p, sig, at);
2721+ elsif checkMode then
2722+ try skipBody();
2723+ else
2724+ try body(p, sig, line);
2725+ end;
2726+ if Scan.tok = Scan.sIdent then
2727+ if Scan.id = Sym.curModule^.name then
2728+ return endMissing(Scan.tokPos(), say1("{} has no \"end\": this one closes the module", nameOf(n)));
2729+ elsif Scan.id # n then
2730+ return endMissing(Scan.tokPos(), say2("expected {}, found {}", nameOf(n), nameOf(Scan.id)));
2731+ end;
2732+ Scan.next;
2733+ end;
2734+ return nil;
2735+end;
2736+
2737+(* An extern procedure or variable: C's, reached through the quadword
2738+ that holds its address. *)
2739+proc externDecl: ERROR;
2740+var n: INT; exp: BOOL; o, q: PObj; t: PType; at: Diag.Pos;
2741+begin
2742+ Scan.next;
2743+ Sym.curModule^.usesC := true;
2744+ if Scan.tok = Scan.sProc then
2745+ Scan.next;
2746+ try identDef(n, exp, at);
2747+ willDeclare(n);
2748+ inExtern := true;
2749+ t := try signature();
2750+ inExtern := false;
2751+ q := t^.fields;
2752+ while q # nil do
2753+ if q^.isVar or not Sym.isScalar(q^.typ) then
2754+ return Scan.markAt(at, "C takes integers, BOOL, reals, pointers and procedures");
2755+ end;
2756+ q := q^.next;
2757+ end;
2758+ if (t^.base # nil) and not Sym.isScalar(t^.base) then
2759+ return Scan.markAt(at, "C returns a single value");
2760+ end;
2761+ o := Sym.newObj(Sym.oProc, n, t);
2762+ else
2763+ if Scan.tok # Scan.sVar then return expected("\"proc\" or \"var\""); end;
2764+ Scan.next;
2765+ try identDef(n, exp, at);
2766+ willDeclare(n);
2767+ try expect(Scan.sColon);
2768+ declExported := exp;
2769+ t := try parseType();
2770+ declExported := false;
2771+ o := Sym.newObj(Sym.oVar, n, t);
2772+ end;
2773+ o^.pos := at;
2774+ o^.exported := exp;
2775+ o^.ext := true;
2776+ o^.chunk := Chunk.externChunk(n);
2777+ return declare(o);
2778+end;
2779+
2780+(* An array or record constant: a literal of constants, which become
2781+ the bytes of a read-only chunk, as a string constant's do (report
2782+ section 4). An address in it, of a string, an array constant, a
2783+ procedure or an ERROR, waits in fixes until the chunk is made, then
2784+ is a fixup the linker patches. The bytes are the compiler's own
2785+ machine's, little-endian, as the target's are. *)
2786+var
2787+ constBytes: ^U8;
2788+ fixes: [MaxFixes]record off, chunk: INT; end;
2789+ numFixes: INT;
2790+
2791+proc constFix(off, chunk: INT): ERROR;
2792+begin
2793+ if numFixes >= MaxFixes then
2794+ return Scan.mark(tooMany(MaxFixes, "addresses in one constant"));
2795+ end;
2796+ fixes[numFixes].off := off;
2797+ fixes[numFixes].chunk := chunk;
2798+ INC(numFixes);
2799+ return nil;
2800+end;
2801+
2802+(* The n bytes of v, at off in the constant: little-endian, as the machine is *)
2803+proc putBytes(off, n: INT; v: I64);
2804+var src: ^U8;
2805+begin
2806+ src := ^U8(ADR(v));
2807+ COPY(constBytes[off..off + n], src[0..n]);
2808+end;
2809+
2810+(* The part of type t at offset off of the constant *)
2811+proc constPart(t: PType; off: INT): ERROR;
2812+var e: TItem; f: PObj; k: INT; r: F32; start: Diag.Pos; src: ^U8; st: INT;
2813+begin
2814+ start := Scan.tokPos();
2815+ if (t^.form = Sym.fArray) and (Scan.tok = Scan.sLbrak) then
2816+ Scan.next;
2817+ k := 0;
2818+ if Scan.tok # Scan.sRbrak then
2819+ repeat
2820+ if I64(k) < t^.len then
2821+ try constPart(t^.base, off + k * INT(t^.base^.size));
2822+ else
2823+ try constPart(t^.base, off);
2824+ end;
2825+ INC(k);
2826+ if Scan.tok # Scan.sComma then break; end;
2827+ Scan.next;
2828+ until false;
2829+ end;
2830+ try expect(Scan.sRbrak);
2831+ if I64(k) # t^.len then
2832+ return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(t^.len), Fmt.int(k)]));
2833+ end;
2834+ return nil;
2835+ end;
2836+ if (t^.form = Sym.fRecord) and not t^.tuple and (Scan.tok = Scan.sLbrace) then
2837+ Scan.next;
2838+ if Scan.tok # Scan.sRbrace then
2839+ repeat
2840+ if Scan.tok # Scan.sIdent then return expected("a field"); end;
2841+ f := try fieldOf(t);
2842+ Scan.next;
2843+ try expect(Scan.sColon);
2844+ try constPart(f^.typ, off + INT(f^.val));
2845+ if Scan.tok # Scan.sComma then break; end;
2846+ Scan.next;
2847+ until false;
2848+ end;
2849+ return expect(Scan.sRbrace);
2850+ end;
2851+ try expression(e, t);
2852+ if (e.mode = Item.mStr) and ((t^.form = Sym.fSlice) or (t^.form = Sym.fArray)) and (t^.base = Sym.tU8) then
2853+ if t^.form = Sym.fSlice then
2854+ try constFix(off, e.chunk);
2855+ putBytes(off + 8, 8, e.val);
2856+ elsif e.val > t^.len then
2857+ return Scan.markAt(e.pos, say1("the string is longer than {}", Sym.typeName(t)));
2858+ else
2859+ st := Chunk.chunks[e.chunk].start;
2860+ COPY(constBytes[off..off + INT(e.val)], Chunk.rodata[st..st + INT(e.val)]);
2861+ end;
2862+ elsif t^.form = Sym.fSlice then
2863+ if (e.mode # Item.mVar) or (e.obj = nil) or (e.obj^.cls # Sym.oConst) or (e.typ^.form # Sym.fArray)
2864+ or (e.pos.b - e.pos.a # LEN(nameOf(e.obj^.name))) or not Sym.same(e.typ^.base, t^.base) then
2865+ return Scan.markAt(e.pos, say1("a constant slice is a string or an array constant of its elements, found {}", Item.what(e)));
2866+ end;
2867+ try constFix(off, e.chunk);
2868+ putBytes(off + 8, 8, e.typ^.len);
2869+ elsif t^.form = Sym.fVariant then
2870+ return Scan.markAt(e.pos, "a constant holds no variant");
2871+ elsif (t^.form = Sym.fArray) or (t^.form = Sym.fRecord) then
2872+ return Scan.markAt(e.pos, say1("expected a literal of {}", Sym.typeName(t)));
2873+ else
2874+ try Item.coerce(e, t);
2875+ if (e.mode = Item.mProc) and not e.obj^.ext then
2876+ try constFix(off, e.obj^.chunk);
2877+ elsif e.mode # Item.mConst then
2878+ return Scan.markAt(e.pos, say1("expected a constant, found {}", Item.what(e)));
2879+ elsif (t^.form = Sym.fError) and (e.val > 0) then
2880+ try constFix(off, INT(e.val) - 1);
2881+ elsif (t^.form = Sym.fPtr) and (e.val # 0) then
2882+ return Scan.markAt(e.pos, "a constant pointer is nil");
2883+ elsif (t^.form = Sym.fReal) and (t^.size = 4) then
2884+ r := F32(Item.realOf(e));
2885+ src := ^U8(ADR(r));
2886+ COPY(constBytes[off..off + 4], src[0..4]);
2887+ else
2888+ putBytes(off, INT(t^.size), e.val);
2889+ end;
2890+ end;
2891+ return nil;
2892+end;
2893+
2894+(* The chunk of n, a constant of type t whose literal is next *)
2895+proc aggregateConst(t: PType; n: INT): (INT, ERROR);
2896+var c, i, size: INT;
2897+begin
2898+ size := INT(t^.size);
2899+ constBytes := Scan.grab(size + 8);
2900+ for i := 0 to size + 7 do constBytes[i] := 0; end;
2901+ numFixes := 0;
2902+ try constPart(t, 0);
2903+ c := Chunk.newChunk(Chunk.secRodata, Sym.curModule^.sname, n);
2904+ Chunk.setData(c, constBytes, size, INT(t^.align));
2905+ for i := 0 to numFixes - 1 do Chunk.addDataFixup(c, fixes[i].off, fixes[i].chunk, 0); end;
2906+ return c, nil;
2907+end;
2908+
2909+proc constDecl(top: BOOL): ERROR;
2910+var n, c: INT; exp: BOOL; x: TItem; o: PObj; t: PType; start, at: Diag.Pos;
2911+begin
2912+ try identDef(n, exp, at);
2913+ willDeclare(n);
2914+ t := nil;
2915+ if Scan.tok = Scan.sColon then
2916+ Scan.next;
2917+ start := Scan.tokPos();
2918+ t := try parseType();
2919+ if (t # Sym.tError) and not ((t^.form = Sym.fArray) or ((t^.form = Sym.fRecord) and not t^.tuple)) then
2920+ return Scan.markAt(Scan.spanFrom(start), "only an ERROR, an array or a record constant has a type");
2921+ end;
2922+ end;
2923+ try expect(Scan.sEql);
2924+ if (t # nil) and ((t^.form = Sym.fArray) or (t^.form = Sym.fRecord)) then
2925+ o := Sym.newObj(Sym.oConst, n, t);
2926+ o^.chunk := try aggregateConst(t, n);
2927+ o^.pos := at;
2928+ o^.exported := exp and top;
2929+ try declare(o);
2930+ return expect(Scan.sSemicolon);
2931+ end;
2932+ try expression(x, nil);
2933+ o := Sym.newObj(Sym.oConst, n, x.typ);
2934+ o^.pos := at;
2935+ o^.exported := exp and top;
2936+ if t = Sym.tError then
2937+ o^.typ := Sym.tError;
2938+ c := try Item.errorChunk(x, Sym.curModule^.sname, n);
2939+ o^.val := c + 1;
2940+ elsif x.mode = Item.mStr then
2941+ o^.val := x.val;
2942+ o^.chunk := x.chunk;
2943+ else
2944+ o^.val := try constValue(x);
2945+ end;
2946+ try declare(o);
2947+ return expect(Scan.sSemicolon);
2948+end;
2949+
2950+proc typeDecl(top: BOOL): ERROR;
2951+var n: INT; exp: BOOL; o: PObj; t: PType; at: Diag.Pos;
2952+begin
2953+ try identDef(n, exp, at);
2954+ willDeclare(n);
2955+ try expect(Scan.sEql);
2956+ declExported := exp and top;
2957+ inTypes := true;
2958+ t := try parseType();
2959+ o := Sym.newObj(Sym.oType, n, t);
2960+ o^.pos := at;
2961+ o^.exported := exp and top;
2962+ if t^.obj = nil then t^.obj := o; end;
2963+ try declare(o);
2964+ return expect(Scan.sSemicolon);
2965+end;
2966+
2967+proc varDecl(top: BOOL): ERROR;
2968+var
2969+ i, k: INT; o: PObj; t: PType;
2970+ names: [MaxNames]INT; exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos;
2971+begin
2972+ k := 0;
2973+ repeat
2974+ if k >= MaxNames then return Scan.mark(tooMany(MaxNames, "names in one declaration")); end;
2975+ try identDef(names[k], exps[k], poss[k]);
2976+ willDeclare(names[k]);
2977+ INC(k);
2978+ if Scan.tok # Scan.sComma then break; end;
2979+ Scan.next;
2980+ until false;
2981+ try expect(Scan.sColon);
2982+ declExported := top and exps[0];
2983+ t := try parseType();
2984+ declExported := false;
2985+ for i := 0 to k - 1 do
2986+ o := Sym.newObj(Sym.oVar, names[i], t);
2987+ o^.pos := poss[i];
2988+ o^.exported := exps[i] and top;
2989+ o^.isVar := false;
2990+ if top then
2991+ o^.lev := 0;
2992+ o^.chunk := Chunk.newChunk(Chunk.secBss, Sym.curModule^.sname, names[i]);
2993+ Chunk.setBss(o^.chunk, INT(t^.size), INT(t^.align));
2994+ else
2995+ o^.lev := 1; (* its slot comes from placeLocals, if it needs one *)
2996+ end;
2997+ try declare(o);
2998+ end;
2999+ return expect(Scan.sSemicolon);
3000+end;
3001+
3002+(* After a procedure had an error: its name is poison if it wasn't
3003+ declared, and reading goes on after the "end Name;" that closes it,
3004+ or at the next procedure if that is missing *)
3005+proc skipProc;
3006+var st: Scan.State;
3007+begin
3008+ Scan.next;
3009+ if (Scan.tok = Scan.sIdent) and (Sym.find(Sym.topScope(), Scan.id) = nil) then poison(Scan.id); end;
3010+ repeat
3011+ repeat Scan.next; until Scan.atLineStart() or (Scan.tok = Scan.sEof);
3012+ match Scan.tok of
3013+ | sProc, sExtern, sEof: return;
3014+ | sEnd:
3015+ Scan.saveScan(st);
3016+ Scan.next;
3017+ if Scan.tok = Scan.sIdent then Scan.next; end;
3018+ if Scan.tok = Scan.sSemicolon then
3019+ Scan.next;
3020+ return;
3021+ end;
3022+ Scan.restoreScan(st);
3023+ return;
3024+ | else:
3025+ end;
3026+ until false;
3027+end;
3028+
3029+(* What one declaration, of the kind k, reads *)
3030+proc declarationOf(k: Scan.Sym; top: BOOL): ERROR;
3031+begin
3032+ match k of
3033+ | sConst: return constDecl(top);
3034+ | sType: return typeDecl(top);
3035+ | sVar: return varDecl(top);
3036+ | sProc:
3037+ if not top then return Scan.mark("procedures don't nest"); end;
3038+ try procDecl();
3039+ return expect(Scan.sSemicolon);
3040+ | sExtern:
3041+ if not top then return Scan.mark("extern is only for the top of a module"); end;
3042+ try externDecl();
3043+ return expect(Scan.sSemicolon);
3044+ | else: return nil;
3045+ end;
3046+end;
3047+
3048+(* One declaration, as a recovery point: an error is reported, the
3049+ declaration skipped, and reading goes on after it *)
3050+proc declaration(k: Scan.Sym; top: BOOL);
3051+var r: Recover;
3052+begin
3053+ guard(r);
3054+ numDeclaring := 0;
3055+ if declarationOf(k, top) # nil then
3056+ restore(r);
3057+ if k = Scan.sProc then skipProc(); else skipDeclaration(); end;
3058+ end;
3059+ unguard(r);
3060+end;
3061+
3062+proc declarations(top: BOOL);
3063+var i: INT; o: PObj; k: Scan.Sym;
3064+begin
3065+ repeat
3066+ k := Scan.tok;
3067+ match k of
3068+ | sConst, sVar:
3069+ Scan.next;
3070+ while Scan.tok = Scan.sIdent do declaration(k, top); end;
3071+ | sType:
3072+ Scan.next;
3073+ numFwd := 0;
3074+ while Scan.tok = Scan.sIdent do declaration(Scan.sType, top); end;
3075+ inTypes := false;
3076+ for i := 0 to numFwd - 1 do
3077+ o := Sym.lookup(fwdTypes[i]^.fwd);
3078+ if (o = nil) or (o^.cls # Sym.oType) then
3079+ notDeclared(fwdPos[i], fwdTypes[i]^.fwd);
3080+ fwdTypes[i]^.base := Sym.tPoison;
3081+ else
3082+ fwdTypes[i]^.base := o^.typ;
3083+ named(o);
3084+ end;
3085+ fwdTypes[i]^.fwd := -1;
3086+ end;
3087+ | sProc, sExtern: declaration(k, top);
3088+ | else: return;
3089+ end;
3090+ until false;
3091+end;
3092+
3093+(* Modules *)
3094+
3095+(* Whether m is module n with these arguments. *)
3096+proc isModule(m: PModule; n: INT; args: Sym.Args): BOOL;
3097+var i: INT;
3098+begin
3099+ if (m^.name # n) or (m^.args.n # args.n) then return false; end;
3100+ for i := 0 to args.n - 1 do
3101+ if (m^.args.o[i] # args.o[i]) or not Sym.same(m^.args.t[i], args.t[i]) then return false; end;
3102+ end;
3103+ return true;
3104+end;
3105+
3106+proc findModule(n: INT; args: Sym.Args): PModule;
3107+var m: PModule;
3108+begin
3109+ m := firstModule;
3110+ while (m # nil) and not isModule(m, n, args) do m := m^.next; end;
3111+ return m;
3112+end;
3113+
3114+(* The arguments of an instance: types, or procedures named. *)
3115+proc parseArgs(var args: Sym.Args; mname: []U8): ERROR;
3116+var o: PObj; start: Diag.Pos;
3117+begin
3118+ Scan.next;
3119+ repeat
3120+ if args.n >= 8 then return Scan.mark(say1("too many type arguments for {}", mname)); end;
3121+ args.o[args.n] := nil;
3122+ start := Scan.tokPos();
3123+ if Scan.tok = Scan.sIdent then
3124+ o := try qualIdent();
3125+ if o^.cls = Sym.oProc then
3126+ args.o[args.n] := o;
3127+ elsif o^.cls # Sym.oType then
3128+ return Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type or a procedure", nameOf(o^.name)));
3129+ end;
3130+ args.t[args.n] := o^.typ;
3131+ else
3132+ args.t[args.n] := try parseType();
3133+ end;
3134+ args.pos[args.n] := Scan.spanFrom(start);
3135+ INC(args.n);
3136+ if Scan.tok # Scan.sComma then break; end;
3137+ Scan.next;
3138+ until false;
3139+ return expect(Scan.sRparen);
3140+end;
3141+
3142+(* Past an instance's arguments, to be read when it is made *)
3143+proc skipArgs: ERROR;
3144+var p: INT;
3145+begin
3146+ p := 0;
3147+ repeat
3148+ if Scan.tok = Scan.sLparen then
3149+ INC(p);
3150+ elsif Scan.tok = Scan.sRparen then
3151+ DEC(p);
3152+ elsif (Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEof) then
3153+ return expected("\")\"");
3154+ end;
3155+ Scan.next;
3156+ until p = 0;
3157+ return nil;
3158+end;
3159+
3160+(* A generic module's parameters, bound to the instance's arguments: a
3161+ type parameter names its type, a procedure parameter its procedure.
3162+ The instance's name is the module's with its arguments, List(I64). *)
3163+proc moduleParams(m: PModule): ERROR;
3164+var i: INT; o, a: PObj; sig: PType; s: Buf.Buf; at: Diag.Pos; text: []U8;
3165+begin
3166+ Buf.init(ADR(s), Heap.heap);
3167+ i := 0;
3168+ Buf.str(ADR(s), nameOf(m^.name));
3169+ Buf.add(ADR(s), '(');
3170+ Scan.next;
3171+ repeat
3172+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
3173+ if i >= m^.args.n then
3174+ return Scan.markAt(m^.args.at, say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id)));
3175+ end;
3176+ if m^.args.o[i] # nil then
3177+ return Scan.markAt(m^.args.pos[i], say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id)));
3178+ end;
3179+ o := Sym.newObj(Sym.oType, Scan.id, m^.args.t[i]);
3180+ o^.used := true; (* a parameter of the module, not a declaration *)
3181+ try declare(o);
3182+ Buf.str(ADR(s), Sym.typeName(m^.args.t[i]));
3183+ Buf.add(ADR(s), ',');
3184+ INC(i);
3185+ Scan.next;
3186+ if Scan.tok # Scan.sComma then break; end;
3187+ Scan.next;
3188+ until false;
3189+ while Scan.tok = Scan.sSemicolon do
3190+ Scan.next;
3191+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
3192+ at := Scan.tokPos();
3193+ o := Sym.newObj(Sym.oProc, Scan.id, nil);
3194+ Scan.next;
3195+ try expect(Scan.sColon);
3196+ try expect(Scan.sProc);
3197+ sig := try signature();
3198+ if i >= m^.args.n then
3199+ return Scan.markAt(m^.args.at, say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name)));
3200+ end;
3201+ a := m^.args.o[i];
3202+ if a = nil then
3203+ return Scan.markAt(m^.args.pos[i], say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name)));
3204+ end;
3205+ if not Sym.same(a^.typ, sig) then
3206+ Diag.error(m^.args.pos[i], say2("{} doesn't have the signature of {}", nameOf(a^.name), nameOf(o^.name)));
3207+ Diag.note(at, "the signature is here");
3208+ Diag.finish();
3209+ end;
3210+ o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext;
3211+ o^.used := true;
3212+ try declare(o);
3213+ Buf.str(ADR(s), nameOf(a^.home^.name));
3214+ Buf.add(ADR(s), '.');
3215+ Buf.str(ADR(s), nameOf(a^.name));
3216+ Buf.add(ADR(s), ',');
3217+ INC(i);
3218+ end;
3219+ try expect(Scan.sRparen);
3220+ if i # m^.args.n then
3221+ return Scan.markAt(m^.args.at, say1("too many type arguments for {}", nameOf(m^.name)));
3222+ end;
3223+ text := Buf.bytes(ADR(s));
3224+ text[LEN(text) - 1] := ')';
3225+ m^.sname := internName(text);
3226+ Buf.done(ADR(s));
3227+ return nil;
3228+end;
3229+
3230+(* Warns of o if it is never used, or a variable only assigned. What
3231+ is exported may be used elsewhere, and a name that starts with _ says
3232+ it is meant to go unused. Writing a var parameter, a match's name for
3233+ a field or C's variable is what it is for. *)
3234+proc warn(o: PObj);
3235+var s, t: []U8;
3236+begin
3237+ s := nameOf(o^.name);
3238+ if (o^.cls = Sym.oProc) and o^.openEnd then
3239+ Diag.warning(o^.pos, say1("{} may reach its end without return, and then returns zero", s));
3240+ end;
3241+ if o^.exported or (s[0] = '_') then return; end;
3242+ if o^.used and (o^.read or (o^.cls # Sym.oVar) or o^.isVar or o^.ext) then return; end;
3243+ match o^.cls of
3244+ | oConst: t := say1("constant {}", s);
3245+ | oType: t := say1("type {}", s);
3246+ | oVar:
3247+ if o^.param then t := say1("parameter {}", s); else t := say1("variable {}", s); end;
3248+ | oProc: t := say1("procedure {}", s);
3249+ | oModule: t := say1("module {}", s);
3250+ | else: return;
3251+ end;
3252+ if o^.used then
3253+ Diag.warning(o^.pos, say1("{} is assigned but never read", t));
3254+ elsif o^.cls = Sym.oModule then
3255+ Diag.warning(o^.pos, say1("{} is imported but never used", t));
3256+ else
3257+ Diag.warning(o^.pos, say1("{} is never used", t));
3258+ end;
3259+ if not o^.used and (o^.param or o^.ind) then
3260+ Diag.help(say1("if it must be there, call it _{}", s));
3261+ end;
3262+end;
3263+
3264+(* Warns of the call at p, which drops its n results *)
3265+proc dropped(p: Diag.Pos; n: INT);
3266+var s, blanks: []U8; i: INT;
3267+begin
3268+ s := Diag.source(p);
3269+ i := 0;
3270+ while (i < LEN(s)) and (s[i] # '(') do INC(i); end;
3271+ if i < LEN(s) then s := s[0..i]; end;
3272+ blanks := "_";
3273+ for i := 2 to n do blanks := say1("{}, _", blanks); end;
3274+ if n = 1 then
3275+ Diag.warning(p, say1("the result of {} is dropped", s));
3276+ else
3277+ Diag.warning(p, say1("the results of {} are dropped", s));
3278+ end;
3279+ Diag.help(say2("if that is meant, write {} := {}(...)", blanks, s));
3280+end;
3281+
3282+(* The warnings of module m, by where each declaration is: its own
3283+ declarations and its procedures' are two lists, each in order, and
3284+ firstDrop on are the calls that drop results. The
3285+ instances of a generic module share its text, and so its warnings:
3286+ only the first is warned of. *)
3287+proc warnings(m: PModule; firstDrop: INT);
3288+var a, b: PObj; n: PModule; i: INT;
3289+begin
3290+ n := firstModule;
3291+ while (n # nil) and (n^.name # m^.name) do n := n^.next; end;
3292+ if n # nil then return; end;
3293+ a := m^.first; b := m^.locals;
3294+ i := firstDrop;
3295+ while (a # nil) or (b # nil) or (i < numDrops) do
3296+ if (i < numDrops) and ((a = nil) or (drops[i].at.a < a^.pos.a)) and ((b = nil) or (drops[i].at.a < b^.pos.a)) then
3297+ dropped(drops[i].at, drops[i].n);
3298+ INC(i);
3299+ elsif (b = nil) or ((a # nil) and (a^.pos.a < b^.pos.a)) then
3300+ warn(a);
3301+ a := a^.chain;
3302+ else
3303+ warn(b);
3304+ b := b^.chain;
3305+ end;
3306+ end;
3307+end;
3308+
3309+(* Modules being compiled, not yet finished: for finding a cycle. *)
3310+var
3311+ pending: [MaxPending]PModule;
3312+ numPending: INT;
3313+
3314+proc exists(path: []U8): BOOL;
3315+var info: Sys.Info; err: INT;
3316+begin
3317+ info, err := Sys.info(path);
3318+ return (err = 0) and info.file;
3319+end;
3320+
3321+(* Which file path is, as its device and inode: two names of one file
3322+ have the same. Zero for a file that can't be asked about. *)
3323+proc identity(path: []U8): (INT, INT);
3324+var a: [4096]U8; st: [18]INT; (* struct stat: st_dev, then st_ino *)
3325+begin
3326+ if LEN(path) >= 4096 then return 0, 0; end;
3327+ COPY(a[0..LEN(path)], path);
3328+ a[LEN(path)] := 0;
3329+ if SYSCALL(4, ADR(a[0]), ADR(st)) < 0 then return 0, 0; end;
3330+ return st[0], st[1];
3331+end;
3332+
3333+(* s, in memory that is never freed, for what must outlast the buffer it is in *)
3334+proc keep(s: []U8): []U8;
3335+var p: ^U8;
3336+begin
3337+ if LEN(s) = 0 then return ""; end;
3338+ p := Scan.grab(LEN(s));
3339+ COPY(p[0..LEN(s)], s);
3340+ return p[0..LEN(s)];
3341+end;
3342+
3343+proc importModule(name: INT; args: Sym.Args): (PModule, ERROR); forward;
3344+
3345+(* Compiles module n from path, an instance if args are given, or only
3346+ reads its interface if checkOnly; returns it. An import calls this in
3347+ the middle of reading another file, so it is re-entrant: it saves the
3348+ scanner's state, the open scopes, the current module and file and
3349+ whether checks are on, and puts them back at the end. *)
3350+proc compileFile(path: []U8; n: INT; args: Sym.Args; checkOnly: BOOL): (PModule, ERROR);
3351+var
3352+ st: Scan.State; saved: [Sym.MaxDepth]INT; d: INT;
3353+ oldMod: PModule; oldCheck, oldChecks: BOOL; m: PModule;
3354+ lib: ^Sym.Lib; start: Diag.Pos; alias, mname, line, oldPath: INT; o: PObj; bodyChunk: INT; iargs: Sym.Args;
3355+ generic: BOOL; argsAt: Scan.State; why: []U8; firstDrop: INT;
3356+begin
3357+ firstDrop := numDrops;
3358+ Scan.saveScan(st);
3359+ d := Sym.saveScopes(saved[0..Sym.MaxDepth]);
3360+ oldMod := Sym.curModule; oldCheck := checkMode; oldPath := Chunk.curFilePath(); oldChecks := Item.checks;
3361+ Item.setChecks(true);
3362+ Chunk.setCurFile(internName(path));
3363+ why := Scan.open(path);
3364+ if LEN(why) # 0 then Diag.fatal(say2("can't read {}: {}", path, why)); end;
3365+ NEW(m, Heap.heap);
3366+ m^.name := n;
3367+ m^.sname := n;
3368+ m^.args := args;
3369+ m^.scope := Sym.newScope();
3370+ m^.path := path;
3371+ m^.body := -1;
3372+ m^.checkOnly := checkOnly;
3373+ Sym.setCurModule(m);
3374+ checkMode := checkOnly;
3375+ if not checkOnly then
3376+ if numPending >= MaxPending then
3377+ return nil, Scan.mark(tooMany(MaxPending, "imports nested deep"));
3378+ end;
3379+ pending[numPending] := m;
3380+ INC(numPending);
3381+ end;
3382+ try Sym.openScope(m^.scope);
3383+ Scan.next;
3384+ try expect(Scan.sModule);
3385+ if (Scan.tok # Scan.sIdent) or (Scan.id # n) then
3386+ return nil, Scan.mark(say2("expected module {}, found {}", nameOf(n), Scan.found()));
3387+ end;
3388+ Scan.next;
3389+ (* the module first pending is the one named on the command line,
3390+ which nothing imports, so no arguments come with it *)
3391+ if (Scan.tok = Scan.sLparen) and not checkOnly and (numPending = 1) then
3392+ return nil, Scan.mark(say1("{} is generic: it is compiled where a module imports it", nameOf(n)));
3393+ elsif Scan.tok = Scan.sLparen then
3394+ try moduleParams(m);
3395+ elsif args.n > 0 then
3396+ return nil, Scan.markAt(args.at, say1("{} isn't generic", nameOf(n)));
3397+ end;
3398+ try expect(Scan.sSemicolon);
3399+ while Scan.tok = Scan.sImport do
3400+ Scan.next;
3401+ repeat
3402+ if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end;
3403+ start := Scan.tokPos();
3404+ alias := Scan.id;
3405+ mname := Scan.id;
3406+ iargs.n := 0;
3407+ generic := false;
3408+ Scan.next;
3409+ if Scan.tok = Scan.sBecomes then
3410+ Scan.next;
3411+ if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end;
3412+ mname := Scan.id;
3413+ Scan.next;
3414+ if Scan.tok = Scan.sLparen then
3415+ generic := true;
3416+ Scan.saveScan(argsAt);
3417+ try skipArgs();
3418+ end;
3419+ end;
3420+ iargs.at := Scan.spanFrom(start);
3421+ o := Sym.newObj(Sym.oModule, alias, nil);
3422+ o^.pos := start;
3423+ try declare(o);
3424+ if not generic then
3425+ o^.home := try importModule(mname, iargs);
3426+ addImport(m, o^.home);
3427+ else
3428+ o^.home := nil; (* until the instance is made, at its first use *)
3429+ if numDeferred >= MaxDeferred then
3430+ return nil, Scan.mark(tooMany(MaxDeferred, "generic imports"));
3431+ end;
3432+ deferred[numDeferred].o := o;
3433+ deferred[numDeferred].home := m;
3434+ deferred[numDeferred].mname := mname;
3435+ deferred[numDeferred].args := argsAt;
3436+ deferred[numDeferred].at := iargs.at;
3437+ INC(numDeferred);
3438+ end;
3439+ if Scan.tok # Scan.sComma then break; end;
3440+ Scan.next;
3441+ until false;
3442+ try expect(Scan.sSemicolon);
3443+ end;
3444+ while Scan.tok = Scan.sLink do
3445+ Scan.next;
3446+ if (Scan.tok = Scan.sIdent) and (Scan.id = nameStatic) then
3447+ m^.linkStatic := true;
3448+ elsif Scan.tok = Scan.sString then
3449+ NEW(lib, Heap.heap);
3450+ lib^.name := internName(Scan.strBytes());
3451+ lib^.next := m^.libs;
3452+ m^.libs := lib;
3453+ m^.usesC := true;
3454+ else
3455+ return nil, expected("a library or \"static\"");
3456+ end;
3457+ Scan.next;
3458+ try expect(Scan.sSemicolon);
3459+ end;
3460+ (* check off;: the module's index and slice checks left out; neither
3461+ word is reserved *)
3462+ if (Scan.tok = Scan.sIdent) and (Scan.id = nameCheck) then
3463+ Scan.next;
3464+ if (Scan.tok # Scan.sIdent) or (Scan.id # nameOff) then return nil, expected("\"off\""); end;
3465+ Scan.next;
3466+ try expect(Scan.sSemicolon);
3467+ Item.setChecks(false);
3468+ end;
3469+ declarations(true);
3470+ if Scan.tok = Scan.sBegin then
3471+ if checkMode then
3472+ try skipBody();
3473+ else
3474+ try instancesFor(true);
3475+ line := Scan.curLine();
3476+ Scan.next;
3477+ bodyChunk := Chunk.newChunk(Chunk.secText, m^.sname, nameBody);
3478+ m^.body := bodyChunk;
3479+ Item.beginProc(tBodySig, nil);
3480+ deferSlot := 0;
3481+ curResult := nil;
3482+ Gen.enterBody(bodyChunk, line);
3483+ stray := false; elseIf := false;
3484+ try statements();
3485+ Chunk.noteLine(Scan.curLine(), Scan.curCol());
3486+ try expect(Scan.sEnd);
3487+ try Gen.endProc(bodyChunk, false);
3488+ end;
3489+ else
3490+ try expect(Scan.sEnd);
3491+ end;
3492+ if (Scan.tok # Scan.sIdent) or (Scan.id # n) then
3493+ return nil, endMissing(Scan.missingPos(), say2("expected {}, found {}", nameOf(n), Scan.found()));
3494+ end;
3495+ Scan.next;
3496+ if Scan.tok # Scan.sPeriod then return nil, expected("\".\""); end;
3497+ o := m^.first;
3498+ while o # nil do
3499+ if (o^.cls = Sym.oProc) and o^.fwd then
3500+ Diag.error(Scan.tokPos(), say1("{} is declared forward but never defined", nameOf(o^.name)));
3501+ end;
3502+ o := o^.chain;
3503+ end;
3504+ if (Diag.errors = 0) and not checkOnly then warnings(m, firstDrop); end;
3505+ numDrops := firstDrop;
3506+ if Diag.errors > 0 then Diag.finish(); end; (* a module with errors stops the compiler after it *)
3507+ Sym.closeScope();
3508+ m^.done := true;
3509+ if not checkOnly then
3510+ DEC(numPending);
3511+ if lastModule = nil then firstModule := m; else lastModule^.next := m; end;
3512+ lastModule := m;
3513+ end;
3514+ Sym.setCurModule(oldMod); checkMode := oldCheck; Chunk.setCurFile(oldPath); Item.setChecks(oldChecks);
3515+ Sym.restoreScopes(d, saved[0..Sym.MaxDepth]);
3516+ Scan.restoreScan(st);
3517+ return m, nil;
3518+end;
3519+
3520+(* The interface check: b must export just what a does. *)
3521+proc compareIface(a, b: PModule);
3522+var o, q: PObj;
3523+begin
3524+ o := a^.first;
3525+ while o # nil do
3526+ if o^.exported then
3527+ q := Sym.find(b^.scope, o^.name);
3528+ if (q = nil) or not q^.exported or (Sym.fingerprint(o) # Sym.fingerprint(q)) then
3529+ Diag.fatal(Diag.say("{}: {} isn't exported as in {}", [Fmt.str(b^.path), Fmt.str(nameOf(o^.name)), Fmt.str(a^.path)]));
3530+ end;
3531+ end;
3532+ o := o^.chain;
3533+ end;
3534+ q := b^.first;
3535+ while q # nil do
3536+ o := Sym.find(a^.scope, q^.name);
3537+ if q^.exported and ((o = nil) or not o^.exported) then
3538+ Diag.fatal(Diag.say("{}: {} isn't exported by {}", [Fmt.str(b^.path), Fmt.str(nameOf(q^.name)), Fmt.str(a^.path)]));
3539+ end;
3540+ q := q^.chain;
3541+ end;
3542+end;
3543+
3544+(* Reads every other file of module n in dir, and checks its interface
3545+ against m, compiled from the file named chosen. *)
3546+proc checkSiblings(dir, chosen: []U8; n: INT; m: PModule; args: Sym.Args): ERROR;
3547+var
3548+ dp: Sys.Dir; e, prefix: []U8; i, numOthers: INT; more: BOOL; sib: PModule;
3549+ others: [32][]U8;
3550+begin
3551+ prefix := say1("{}.", nameOf(n));
3552+ numOthers := 0;
3553+ if Sys.openDir(ADR(dp), dir) # 0 then return nil; end;
3554+ repeat
3555+ e, more := Sys.nextEntry(ADR(dp));
3556+ if not more then break; end;
3557+ if (LEN(e) > 4) and Str.hasPrefix(e, prefix) and (e[LEN(e) - 4..LEN(e)] = ".raz")
3558+ and (e # chosen) and (numOthers < 32) then
3559+ others[numOthers] := keep(e);
3560+ INC(numOthers);
3561+ end;
3562+ until false;
3563+ Sys.closeDir(ADR(dp));
3564+ for i := 0 to numOthers - 1 do
3565+ sib := try compileFile(say2("{}/{}", dir, others[i]), n, args, true);
3566+ compareIface(m, sib);
3567+ end;
3568+ return nil;
3569+end;
3570+
3571+(* The directories searched for modules, in order, from -1 to numInc *)
3572+proc searchDir(i: INT): []U8;
3573+begin
3574+ if i = -1 then return mainDir; end;
3575+ if i = numInc then return libDir; end;
3576+ return incDirs[i];
3577+end;
3578+
3579+(* The file of module n in dir that suffix j says: Name.linux-x86_64.raz
3580+ for a file of this target alone, and so on to Name.raz *)
3581+proc fileName(n, j: INT): []U8;
3582+begin
3583+ return Diag.say("{}{}.raz", [Fmt.str(nameOf(n)), Fmt.str(Suffixes[j])]);
3584+end;
3585+
3586+proc moduleFile(n: INT): ([]U8, []U8, BOOL);
3587+var i, j: INT; dir, f: []U8;
3588+begin
3589+ for i := -1 to numInc do
3590+ dir := searchDir(i);
3591+ for j := 0 to 3 do
3592+ f := fileName(n, j);
3593+ if exists(say2("{}/{}", dir, f)) then return dir, f, true; end;
3594+ end;
3595+ end;
3596+ return "", "", false;
3597+end;
3598+
3599+(* A program has one module of each name: module n, found as dir/f,
3600+ must have no files in a later directory, unless dir/f is a link to
3601+ one of them, which chooses it (report, section 3) *)
3602+proc checkOneModule(n: INT; dir, f: []U8; at: Diag.Pos): ERROR;
3603+var
3604+ i, j, dev, ino, mineDev, mineIno: INT; past, chosen: BOOL; g, files, others: []U8;
3605+begin
3606+ mineDev, mineIno := identity(say2("{}/{}", dir, f));
3607+ others := "";
3608+ past := false;
3609+ for i := -1 to numInc do
3610+ if past then
3611+ files := "";
3612+ chosen := false;
3613+ for j := 0 to 3 do
3614+ g := say2("{}/{}", searchDir(i), fileName(n, j));
3615+ if exists(g) then
3616+ files := say2("{} and {}", files, Diag.shownPath(g));
3617+ dev, ino := identity(g);
3618+ chosen := chosen or ((dev = mineDev) and (ino = mineIno));
3619+ end;
3620+ end;
3621+ if not chosen then others := say2("{}{}", others, files); end;
3622+ end;
3623+ past := past or (searchDir(i) = dir);
3624+ end;
3625+ if LEN(others) = 0 then return nil; end;
3626+ Diag.error(at, say3("module {} is in {}{}", nameOf(n), Diag.shownPath(say2("{}/{}", dir, f)), others));
3627+ Diag.help("a program has one module of each name; a symbolic link to one of these files chooses it");
3628+ return Scan.Failed;
3629+end;
3630+
3631+proc importModule(name: INT; args: Sym.Args): (PModule, ERROR);
3632+var m: PModule; i: INT; dir, f, where: []U8; found: BOOL;
3633+begin
3634+ m := findModule(name, args);
3635+ if m # nil then return m, nil; end;
3636+ for i := 0 to numPending - 1 do
3637+ if isModule(pending[i], name, args) then
3638+ return nil, Scan.markAt(args.at, say1("{} imports itself", nameOf(name)));
3639+ end;
3640+ end;
3641+ dir, f, found := moduleFile(name);
3642+ if not found then
3643+ Diag.error(args.at, say1("can't find module {}", nameOf(name)));
3644+ where := Diag.shownPath(searchDir(-1));
3645+ for i := 0 to numInc do where := say2("{}, {}", where, Diag.shownPath(searchDir(i))); end;
3646+ Diag.help(say2("looked for {}.raz in {}", nameOf(name), where));
3647+ return nil, Scan.Failed;
3648+ end;
3649+ try checkOneModule(name, dir, f, args.at);
3650+ m := try compileFile(say2("{}/{}", dir, f), name, args, false);
3651+ try checkSiblings(dir, f, name, m, args);
3652+ return m, nil;
3653+end;
3654+
3655+proc addImport(m, im: PModule);
3656+var imp: ^Sym.Import;
3657+begin
3658+ NEW(imp, Heap.heap);
3659+ imp^.home := im;
3660+ imp^.next := m^.imports;
3661+ m^.imports := imp;
3662+end;
3663+
3664+(* Makes the instance that deferred[i] imports: its arguments are read
3665+ where the import wrote them, and must be declared by now. Compiling
3666+ the instance comes in the middle of a declaration, so what that
3667+ declaration has under way is kept aside meanwhile. *)
3668+proc makeInstance(i: INT; at: Diag.Pos): ERROR;
3669+var
3670+ d: Deferred; st: Scan.State; args: Sym.Args; types, exported, ext, wasQuiet: BOOL; nf, nd: INT;
3671+ ft: [MaxFwd]PType; fp: [MaxFwd]Diag.Pos; decl: [MaxNames]INT;
3672+begin
3673+ d := deferred[i];
3674+ DEC(numDeferred);
3675+ deferred[i] := deferred[numDeferred];
3676+ Scan.saveScan(st);
3677+ Scan.restoreScan(d.args);
3678+ args.n := 0;
3679+ making := true; useAt := at;
3680+ try parseArgs(args, nameOf(d.mname));
3681+ making := false;
3682+ Scan.restoreScan(st);
3683+ args.at := d.at;
3684+ types := inTypes; exported := declExported; ext := inExtern; wasQuiet := Diag.quiet;
3685+ nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring;
3686+ d.o^.home := try importModule(d.mname, args);
3687+ inTypes := types; declExported := exported; inExtern := ext; Diag.setQuiet(wasQuiet);
3688+ numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl;
3689+ addImport(Sym.curModule, d.o^.home);
3690+ return nil;
3691+end;
3692+
3693+proc firstUse(o: PObj; at: Diag.Pos): ERROR;
3694+var i: INT;
3695+begin
3696+ for i := 0 to numDeferred - 1 do
3697+ if deferred[i].o = o then return makeInstance(i, at); end;
3698+ end;
3699+ return Scan.Failed; (* its arguments had an error, already reported *)
3700+end;
3701+
3702+(* An instance can't be compiled in the middle of another procedure's
3703+ code, so before a procedure's code begins, from its "proc" on, or
3704+ the module body's, from its "begin" to the end of the file, this
3705+ reads ahead for the names of imports not yet made, and makes those. *)
3706+proc instancesFor(wholeRest: BOOL): ERROR;
3707+var st: Scan.State; d, i: INT; begun: BOOL;
3708+begin
3709+ if checkMode then return nil; end;
3710+ i := numDeferred - 1;
3711+ while (i >= 0) and (deferred[i].home # Sym.curModule) do DEC(i); end;
3712+ if i < 0 then return nil; end;
3713+ (* The procedure ends at the "end" that closes its first "begin": d
3714+ counts the words still open that "end" or "until" closes, and begun
3715+ says that begin was met, so that a record's end in its declarations
3716+ doesn't stop it. A forward or code procedure has no raz body to
3717+ read, so it stops at that word. The body reads to the end of the
3718+ file, as wholeRest says. *)
3719+ Scan.saveScan(st);
3720+ d := 0; begun := false;
3721+ repeat
3722+ match Scan.tok of
3723+ | sIdent:
3724+ for i := numDeferred - 1 to 0 by -1 do
3725+ if (deferred[i].home = Sym.curModule) and (deferred[i].o^.name = Scan.id) then
3726+ try makeInstance(i, Scan.tokPos());
3727+ end;
3728+ end;
3729+ | sBegin:
3730+ begun := begun or (d = 0);
3731+ INC(d);
3732+ | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d);
3733+ | sEnd, sUntil: DEC(d);
3734+ | else:
3735+ end;
3736+ if not wholeRest and (d = 0) and (begun or (Scan.tok = Scan.sForward) or (Scan.tok = Scan.sCode)) then break; end;
3737+ Scan.next;
3738+ until Scan.tok = Scan.sEof;
3739+ Scan.restoreScan(st);
3740+ return nil;
3741+end;
3742+
3743+(* The main module, from the file at path, and Rt, which every program
3744+ needs, first *)
3745+proc compileMain*(path: []U8): (PModule, ERROR);
3746+var base: []U8; i, n: INT; none: Sym.Args; m: PModule;
3747+begin
3748+ none.n := 0;
3749+ i := LEN(path);
3750+ while (i > 0) and (path[i - 1] # '/') do DEC(i); end;
3751+ if i = 0 then mainDir := "."; else mainDir := path[0..i - 1]; end;
3752+ base := path[i..LEN(path)];
3753+ i := 0;
3754+ while (i < LEN(base)) and (base[i] # '.') do INC(i); end;
3755+ base := base[0..i];
3756+ if LEN(base) = 0 then Diag.fatal(say1("no module in {}", path)); end;
3757+ n := internName(base);
3758+ none.at := Scan.tokPos();
3759+ if n # nameRt then _ := try importModule(nameRt, none); end;
3760+ m := findModule(n, none);
3761+ if m # nil then return m, nil; end;
3762+ return compileFile(path, n, none, false);
3763+end;
3764+
3765+begin
3766+ nameRt := internName("Rt");
3767+ nameFail := internName("fail");
3768+ nameAdr := internName("ADR");
3769+ nameBody := internName("body");
3770+ nameStatic := internName("static");
3771+ nameCheck := internName("check");
3772+ nameOff := internName("off");
3773+ tArgv := newPtr(newPtr(Sym.tU8, false), false);
3774+ tBodySig := Sym.newType(Sym.fProc, 8, 8);
3775+end Parse.

self/README.md modified +41 -0

@@ -39,6 +39,16 @@
3939 run ends at its 20th error, as a compile does). The text its messages
4040 point into is `test/ItemDump.txt`.
4141
42+`Parse` and `Raz`, the last two units, are tested whole: the seed builds
43+`self/Raz.raz` into `build/self/raz.self`, and each compiler, run as
44+`build/cmp/raz` (a program holds the paths it was made from, and the
45+library is found beside the compiler), compiles the library, the
46+examples, the tools, `self/` itself, every test of `test/` and
47+`conform/`, and the 348,025-line program of `test/genbench.py`, with the
48+options each test has. The executable, the messages, and the status
49+must be the same for every file: 409 of them, 289 of which are errors.
50+`make self-bench` gives the speed of both.
51+
4252 `check.sh` builds a dumper for each side, `test/ScanDump.pas` over the
4353 seed's units and `test/ScanDump.raz` over these, and has both read the
4454 library, the examples, every test of the compiler and a file for each
@@ -125,6 +135,32 @@
125135 the speed test of step 4 to say. A `const` parameter (a hint that
126136 the callee won't change it, so that the caller may pass its address)
127137 would be a language change: it goes on the wish list.
138+- **`Parse` and the seed's jumps.** The seed's `Guard`, `setjmp` and
139+ `longjmp` are `guard`, a record of what to put back, and the `ERROR`
140+ that comes up through `try` to the statement or declaration that is
141+ the recovery point (`statement`, `declaration`), which looks at it,
142+ puts the state back (`restore`) and skips ahead, as the seed does.
143+ `giveUp`, the seed's `GiveUp`, returns the error on to the next one,
144+ or ends the compile if there is none (`guards` counts them). A routine
145+ that can't fail has no `ERROR` (`declarations`, `declaration`). The
146+ seed's nested procedures (`ChooseRegs`'s three) are procedures of the
147+ module with its candidates in variables. `defer` and `module` being
148+ words, the seed's `Defer` is `deferStatement`. A message is made
149+ from strings with `Diag.say`, which has no shortstring to add up to.
150+ `Scan.skipping` is exported to be read, and `Scan.strWithZero` gives
151+ `Item.makeStr` a pointer to a string that may be empty: the seed's
152+ `@sbuf` indexed nothing, and `ADR(Scan.strBytes()[0])`, which the
153+ port of `Item` had, stopped on `""`.
154+- **`Raz`.** The program is `proc main*: INT`. Where it is, for the
155+ library beside it, it reads from `/proc/self/exe` as FPC's `ParamStr(0)`
156+ does: `Files.arg(0)` is what the shell was typed, and `./raz` made the
157+ library `./lib`, so the same program held other paths in its file.
158+ `raz run` writes the memfd with `Elf.writeElf` and executes it with
159+ the system call, `execve`, which `Sys` has no procedure for. The
160+ version is the module `Version`, which `check.sh` makes in
161+ `build/self/` from `build/version.inc`, as the seed's `{$I}` is.
162+ Two names of a file, for a module found in two places, are told by
163+ the device and inode `SYSCALL` `stat` gives, which `Sys.info` lacks.
128164 - **Sets of `Scan.Sym`.** It has 76 names and a set holds 64, so the
129165 operators a rule names are chains of `=` or the helpers `oneOf` and
130166 `isRel`. (A `match` arm with several names, which the seed's `case`
@@ -140,6 +176,11 @@
140176 bytes of a name (84), and one for the symbols that are a byte each
141177 (75). What is left for the code generator, which would help every
142178 module: the slice comparison is slower than the loop it stands for.
179+ On the whole compiler, the same 348,025 lines take 427 ms with the
180+ seed's and 770 with this one (452,000 lines a second, over the 400,000
181+ the budget wants): `Scan.tokPos`, a record of three words returned
182+ through a pointer, is 9% of it, and the rest is spread thin; the
183+ `const` parameter of `Item` isn't what stands out.
143184 (The seed's `match` on an integer was a chain of compares, each
144185 loading the selector from the frame and jumping over a `jmp`, where
145186 FPC makes a jump table; now it makes one too.)

self/Raz.raz added +273 -0

@@ -0,0 +1,273 @@
1+(* Raz: the command line.
2+
3+ raz [-I dir]... [-o file] [-Werror] [-S] Main.raz
4+ raz run [-I dir]... Main.raz [arg]...
5+ raz --version
6+
7+ Compiles the main module and every module it imports, writes the
8+ entry point, links what it reaches, and writes the executable: by
9+ default the main module's file without its .raz; with -S, it lists
10+ the main module's code instead. raz run writes it to a memfd
11+ instead, a file that lives only in memory, and executes it in raz's
12+ place with the arguments after Main.raz, so its status is the
13+ program's; its argv[0] is Main.raz.
14+
15+ The program starts by saving argc and argv, runs every module's body
16+ (those of the modules the program imports, imported modules first),
17+ then the main module's main, and ends with Rt.exit and main's
18+ status. A static program does this from its entry point. One that
19+ uses C starts through the C library, __libc_start_main, which sets
20+ C up and calls this as C's main; first it gives Rt C's exit, which
21+ Rt.exit then ends the program with.
22+
23+ Depends on: everything else, and Version, a module the build makes
24+ (build/self/Version.raz) from what git describe says, as the seed's
25+ build/version.inc is.
26+ Leaves out: the work itself; the other units compile, link and
27+ write, and this only reads the command line and runs them in order. *)
28+module Raz;
29+import Sys, Out, Version, Files, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf;
30+
31+const
32+ Report = "2026-10.21"; (* the version of doc/raz.md it follows *)
33+ MemfdCreate = 319; (* the system call *)
34+ MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *)
35+ Execve = 59;
36+
37+var
38+ links: [4]Gen.Link;
39+ numLinks: INT;
40+
41+proc say1(f, a: []U8): []U8;
42+begin
43+ return Diag.say(f, [Fmt.str(a)]);
44+end;
45+
46+(* The number of the name s *)
47+proc internStr(s: []U8): INT;
48+begin
49+ return Scan.intern(ADR(s[0]), LEN(s));
50+end;
51+
52+(* The modules the program uses: the main module, Rt, and every module
53+ they import. A module read only for the interface check is not. *)
54+proc use(m: ^Sym.Module);
55+var i: ^Sym.Import;
56+begin
57+ if m^.used then return; end;
58+ m^.used := true;
59+ i := m^.imports;
60+ while i # nil do
61+ use(i^.home);
62+ i := i^.next;
63+ end;
64+end;
65+
66+(* Whether the program uses C: if so, the libraries it needs go to
67+ Elf, the C library first. *)
68+proc usesC: BOOL;
69+var m, st, c: ^Sym.Module; l: ^Sym.Lib;
70+begin
71+ st := nil; c := nil;
72+ Elf.noLibs();
73+ _ := Elf.needLib(internStr("libc.so.6"));
74+ m := Parse.firstModule;
75+ while m # nil do
76+ if m^.used and m^.linkStatic then st := m; end;
77+ if m^.used and m^.usesC then c := m; end;
78+ l := m^.libs;
79+ while m^.used and (l # nil) do
80+ if not Elf.needLib(l^.name) then Diag.fatal("more than 32 libraries"); end;
81+ l := l^.next;
82+ end;
83+ m := m^.next;
84+ end;
85+ if (st # nil) and (c # nil) then
86+ Diag.fatal(Diag.say("{} says link static, but {} uses C", [Fmt.str(Scan.nameOf(st^.name)), Fmt.str(Scan.nameOf(c^.name))]));
87+ end;
88+ if c = nil then Elf.noLibs(); end;
89+ return c # nil;
90+end;
91+
92+(* What raz -h says *)
93+proc usage;
94+begin
95+ Out.str("usage: raz [option]... Main.raz compiles Main.raz and the modules it imports\n");
96+ Out.str(" raz run [option]... Main.raz [arg]... compiles it and runs it, with the args\n");
97+ Out.str("options:\n");
98+ Out.str(" -o file the program's file, Main without .raz if left out\n");
99+ Out.str(" -I dir looks for imported modules in dir too, after Main.raz's own\n");
100+ Out.str(" -Werror a warning counts as an error\n");
101+ Out.str(" -S lists the main module's code, under each line of source\n");
102+ Out.str(" -s strips symbols, line numbers, the places a failure is told\n");
103+ Out.str(" by and the profiler: a failure says only its address\n");
104+ Out.str(" -noprofile leaves out the profiler, which RAZ_PROFILE turns on\n");
105+ Out.str(" -h, --help says this\n");
106+ Out.str(" --version says the version, and the report it follows\n");
107+ Out.str("see raz(1), and the report, doc/raz.md\n");
108+ Out.flush();
109+end;
110+
111+proc rtObj(rt: ^Sym.Module; n: []U8): ^Sym.Obj;
112+var o: ^Sym.Obj;
113+begin
114+ o := Sym.find(rt^.scope, internStr(n));
115+ if o = nil then Diag.fatal(say1("Rt has no {}", n)); end;
116+ return o;
117+end;
118+
119+(* Rt is given the address of chunk, in its variable v *)
120+proc addLink(chunk: INT; v: ^Sym.Obj);
121+begin
122+ links[numLinks].chunk := chunk;
123+ links[numLinks].into := v^.chunk;
124+ INC(numLinks);
125+end;
126+
127+(* s as a C string, in memory that is never freed *)
128+proc cstr(s: []U8): ^U8;
129+var p: ^U8;
130+begin
131+ p := Scan.grab(LEN(s) + 1);
132+ if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end;
133+ p[LEN(s)] := 0;
134+ return p;
135+end;
136+
137+proc main*: INT;
138+var
139+ path, outPath, s: []U8; dir: []U8;
140+ i, first, entry, fd, last, errno: INT;
141+ m, rt: ^Sym.Module; mainObj: ^Sym.Obj;
142+ run, noProfile, listing: BOOL; err: ERROR;
143+begin
144+ path := "";
145+ outPath := "";
146+ noProfile := false;
147+ listing := false;
148+ run := (ARGC() >= 2) and (Files.arg(1) = "run");
149+ if run then i := 2; else i := 1; end;
150+ while i < ARGC() do
151+ s := Files.arg(i);
152+ if s = "-I" then
153+ INC(i);
154+ if Parse.numInc > 15 then Diag.fatal("more than 16 -I directories"); end;
155+ Parse.addIncDir(Files.arg(i));
156+ elsif s = "-o" then
157+ INC(i);
158+ outPath := Files.arg(i);
159+ elsif s = "-Werror" then
160+ Diag.setWerror(true);
161+ elsif s = "-S" then
162+ listing := true;
163+ X64.setListing(true);
164+ elsif s = "-s" then
165+ Elf.setStripped(true);
166+ elsif s = "-noprofile" then
167+ noProfile := true;
168+ elsif (s = "-h") or (s = "--help") then
169+ usage();
170+ return 0;
171+ elsif s = "--version" then
172+ Out.str(Diag.say("raz {}, report {}\n", [Fmt.str(Version.Text), Fmt.str(Report)]));
173+ Out.flush();
174+ return 0;
175+ elsif (LEN(s) > 0) and (s[0] = '-') then
176+ Diag.fatal(say1("unknown option {}", s));
177+ else
178+ path := s;
179+ first := i;
180+ if run then break; end; (* the rest are the program's *)
181+ end;
182+ INC(i);
183+ end;
184+ if LEN(path) = 0 then
185+ usage();
186+ return 1;
187+ end;
188+ if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end;
189+ (* where raz is, as the system says, for the library beside it *)
190+ dir, errno := Sys.readLink("/proc/self/exe");
191+ if errno # 0 then dir := Files.arg(0); end;
192+ i := LEN(dir);
193+ while (i > 0) and (dir[i - 1] # '/') do DEC(i); end;
194+ if i = 0 then Parse.setLibDir("lib"); else Parse.setLibDir(say1("{}lib", dir[0..i])); end;
195+ if LEN(outPath) = 0 then
196+ outPath := path;
197+ last := LEN(outPath);
198+ if (last >= 4) and (outPath[last - 4..last] = ".raz") then
199+ outPath := outPath[0..last - 4];
200+ else
201+ outPath := say1("{}.out", outPath);
202+ end;
203+ end;
204+
205+ m, err := Parse.compileMain(path);
206+ if err # nil then
207+ Diag.finish();
208+ return 1;
209+ end;
210+ if Diag.errors > 0 then Diag.finish(); end;
211+
212+ use(m);
213+ rt := Parse.firstModule;
214+ while (rt # nil) and (Scan.nameOf(rt^.name) # "Rt") do rt := rt^.next; end;
215+ if rt # nil then use(rt); end;
216+
217+ mainObj := Sym.find(m^.scope, internStr("main"));
218+ if mainObj # nil then
219+ if (mainObj^.cls # Sym.oProc) or not mainObj^.exported then
220+ Diag.error(mainObj^.pos, "main must be an exported procedure");
221+ elsif (mainObj^.typ^.len # 0) or ((mainObj^.typ^.base # nil) and (mainObj^.typ^.base # Sym.tInt)) then
222+ Diag.error(mainObj^.pos, "main must be proc main* or proc main*: INT");
223+ end;
224+ if Diag.errors > 0 then Diag.finish(); end;
225+ end;
226+ Diag.finish();
227+
228+ if rt = nil then Diag.fatal("can't find module Rt"); end;
229+ (* what Rt is given: the places, which the linker makes, for Rt to say
230+ where a failed check or a signal was (place), and the calls under
231+ way then (calls); and the profiler, which needs them too. raz -s
232+ gives none, -noprofile no profiler. *)
233+ numLinks := 0;
234+ if not Elf.stripped then
235+ Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1));
236+ Chunk.setData(Link.placesChunk, nil, 0, 8);
237+ addLink(Link.placesChunk, rtObj(rt, "places"));
238+ addLink(rtObj(rt, "calls")^.chunk, rtObj(rt, "teller"));
239+ addLink(rtObj(rt, "place")^.chunk, rtObj(rt, "placer"));
240+ if not noProfile then addLink(rtObj(rt, "startProfile")^.chunk, rtObj(rt, "profiler")); end;
241+ end;
242+ entry := Gen.entryPoint(usesC(), Parse.firstModule, mainObj, rtObj(rt, "cExit")^.chunk,
243+ rtObj(rt, "exit")^.chunk, links[0..numLinks], numLinks);
244+
245+ Link.markLive(entry);
246+ if not Parse.HasReals then
247+ for i := 0 to Chunk.numChunks - 1 do
248+ if Chunk.chunks[i].live and Chunk.chunks[i].reals then
249+ Diag.error(Chunk.chunks[i].realsAt, "this target has no reals");
250+ end;
251+ end;
252+ end;
253+ if Diag.errors > 0 then Diag.finish(); end;
254+ if listing then
255+ X64.list(m^.sname);
256+ return 0;
257+ end;
258+
259+ Elf.setMainPath(path);
260+ if run then
261+ (* argv from Main.raz on is the program's, ending in nil as it must *)
262+ fd := SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec);
263+ if fd < 0 then Diag.fatal("can't create a memfd"); end;
264+ outPath := Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]);
265+ Elf.writeElf(outPath, entry);
266+ _ := SYSCALL(Execve, cstr(outPath), ARGV() + first, ARGV() + (ARGC() + 1));
267+ Diag.fatal(say1("can't run {}", path));
268+ end;
269+ Elf.writeElf(outPath, entry);
270+ return 0;
271+end;
272+
273+end Raz.

self/Scan.raz modified +8 -1

@@ -76,7 +76,7 @@
7676
7777 (* The parser is skipping what it has read once already, after an
7878 error, so slips in it aren't reported again. *)
79- skipping: BOOL;
79+ skipping*: BOOL;
8080
8181 (* Whether a byte may be in a name: a letter, a digit or _. A table,
8282 since the loop that reads a name asks it of every byte. *)
@@ -109,6 +109,13 @@
109109 proc strBytes*: []U8;
110110 begin
111111 return sbuf[0..slen];
112+end;
113+
114+(* The string just read and the zero after it, for the code that makes a
115+ chunk of it: an empty string has bytes to point at, though none to index *)
116+proc strWithZero*: ^U8;
117+begin
118+ return ADR(sbuf[0]);
112119 end;
113120
114121 (* Memory, or the end of the compile when there is none *)

self/bench.sh modified +16 -0

@@ -16,3 +16,19 @@
1616 done
1717 echo "$t: $best ms"
1818 done
19+
20+# The whole compiler's speed, the seed's and this one's, on the same
21+# program: the best of five runs of each, as build/cmp/raz, which finds
22+# the library beside it.
23+mkdir -p build/cmp/bench
24+ln -sfn ../../lib build/cmp/lib
25+cp $b/Bench.raz build/cmp/bench/Bench.raz
26+for t in seed self; do
27+ if [ $t = seed ]; then cp raz build/cmp/raz; else cp $b/raz.self build/cmp/raz; fi
28+ best=0
29+ for i in 1 2 3 4 5; do
30+ s=$(date +%s%N); build/cmp/raz -o build/cmp/bench/Bench.$t build/cmp/bench/Bench.raz; e=$(date +%s%N)
31+ d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi
32+ done
33+ echo "compile, $t: $best ms"
34+done

self/check.sh modified +55 -0

@@ -123,3 +123,58 @@
123123 done
124124 echo "item: $n scripts, $bad differ"
125125 test $bad = 0
126+
127+# Parse and Raz: the compiler this makes, built by the seed, compiles
128+# what the seed compiles, to the same file, with the same messages and
129+# status: every example, test and tool, and the library, with each
130+# one's own options. Both sides run as build/cmp/raz, since a program
131+# holds the paths it was made from and the library is found beside the
132+# compiler.
133+printf 'module Version;\nconst Text* = "%s";\nend Version.\n' "$(tr -d "'" < build/version.inc)" >$b/Version.raz
134+./raz -Werror -I self -I $b -o $b/raz.self self/Raz.raz
135+c=build/cmp
136+mkdir -p $c
137+ln -sfn ../../lib $c/lib
138+# and the big program that times the compiler, 348,025 lines
139+mkdir -p $c/bench
140+python3 test/genbench.py 12000 >$c/bench/Bench.raz
141+files=
142+for f in $c/bench/Bench.raz lib/*.raz examples/*.raz tools/*.raz self/*.raz test/run/*.raz test/libc/*.raz test/bench/*.raz \
143+ conform/run/*.raz test/err/*.raz conform/err/*.raz; do
144+ files="$files $f"
145+done
146+for side in seed self; do
147+ rm -rf $c/$side
148+ mkdir -p $c/$side
149+ if [ $side = seed ]; then cp raz $c/raz; else cp $b/raz.self $c/raz; fi
150+ for f in $files; do
151+ dir=$(dirname $f); name=$(basename $f .raz); x=$(echo $dir | tr / _).$name
152+ flags=
153+ case $dir in
154+ examples|tools|lib|self) flags=-Werror ;;
155+ esac
156+ [ -f $dir/$name.args ] && [ $dir = test/err ] && flags="$flags $(cat $dir/$name.args)"
157+ case $dir in
158+ lib) opts= ;;
159+ self|tools) opts="-I self -I build/self" ;;
160+ test/err) opts="-I test/err/mods -I test/run/mods" ;;
161+ *) opts="-I $dir/mods" ;;
162+ esac
163+ s=0
164+ $c/raz $flags $opts -o $c/$side/$x $f >$c/$side/$x.out 2>$c/$side/$x.err || s=$?
165+ echo $s >$c/$side/$x.status
166+ done
167+done
168+n=0; bad=0
169+for f in $files; do
170+ x=$(dirname $f | tr / _).$(basename $f .raz)
171+ n=$((n + 1))
172+ for e in "" .out .err .status; do
173+ [ -f $c/seed/$x$e ] || [ -f $c/self/$x$e ] || continue
174+ if ! cmp -s $c/seed/$x$e $c/self/$x$e; then
175+ echo "differs: $f ($x$e)"; bad=$((bad + 1)); break
176+ fi
177+ done
178+done
179+echo "raz: $n files, $bad differ"
180+test $bad = 0

self/test/ItemDump.raz modified +7 -7

@@ -289,13 +289,13 @@
289289 | 6: Item.makeConst(x, Sym.tNil, 0);
290290 | 7: return Item.makeItem(x, procs[rnd(6)]);
291291 | 8: if rnd(4) = 0 then
292- match rnd(3) of
293- | 0: return Item.makeItem(x, typeObj);
294- | 1: return Item.makeItem(x, builtinObj);
295- | else: return Item.makeItem(x, caseObj);
296- end;
297- end;
298- return Item.makeItem(x, arrConst);
292+ match rnd(3) of
293+ | 0: return Item.makeItem(x, typeObj);
294+ | 1: return Item.makeItem(x, builtinObj);
295+ | else: return Item.makeItem(x, caseObj);
296+ end;
297+ end;
298+ return Item.makeItem(x, arrConst);
299299 | 13: try Item.makeItem(x, vars[rnd(NumT)]); return Item.value(x);
300300 | else: return varItem(x, ty[rnd(NumT)]);
301301 end;