raz / commit 80d65028

commit
80d65028dccc91d53596a339b2ddd81109289280
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
d16c846a
Self step 3b: Item in raz, tested against the seed's

self/Item.raz, the operands and their types: every routine that can
find an error returns an ERROR for try to pass up. test/ItemDump.{pas,raz}
drive both sides with 60 scripts of operations with mistakes among them
(constants, variables of every placement, selectors, calls, match, for,
return, COPY, variants); what each step gave, the messages, the bytes,
fixups, line notes and listing are the same. README lists what the port
found, among it the missing const parameter (on the wish list).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

patch · log

7 files changed, +3186 -1

PLAN.md (history) modified +8 -1

@@ -33,7 +33,8 @@
3333 if the cost is too high, mend the code generator first.
3434 2. `chunk`, `sym` (2a, done); `link`, `elf`, `x64` (2b, done).
3535 3. `gen` (3a, done: `Gen.raz`, tested by `test/GenDump`, a script of
36- calls whose bytes and listing are the same), `item` (3b).
36+ calls whose bytes and listing are the same), `item` (3b, done: `Item.raz`, tested by
37+ `test/ItemDump`, 60 scripts of operations with mistakes in them).
3738 4. `parse`, `raz`: the first compiler that builds.
3839 5. Fixpoint: the seed builds `self`, that builds `self`, that builds
3940 `self` again, and the last two are byte for byte the same. Then
@@ -83,3 +84,9 @@
8384 early returns and procedures without results, is several times the
8485 size; the same 12% is a few lines in rat. Revisit only if more
8586 programs show it.
87+- **A `const` parameter.** `proc what(const x: Item): []U8;`: the callee
88+ may not change `x` (nor take its address), so the caller may pass the
89+ address of a record or array without a copy, and the program means the
90+ 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.

self/Item.raz added +1740 -0

@@ -0,0 +1,1740 @@
1+(* Item: operands, their types, and what they mean.
2+
3+ The parser describes each operand as an item, as in Wirth's
4+ compilers: a constant, a variable at an address it can name, a value
5+ on Gen's stack, a procedure, a string. The routines here check the
6+ items' types, fold constants, and have Gen make the code, as calls of
7+ its stack machine; nothing here knows the machine.
8+
9+ Depends on: Scan for errors, Sym for types, Chunk for data, Gen for
10+ code.
11+ Leaves out: the language's syntax, which is Parse; the machine, which
12+ is Gen.
13+
14+ An error the seed's `Mark` ended in a jump back to the parser's
15+ recovery point. Here the routine that finds it shows it and returns
16+ `Scan.Failed`, and every routine that calls one passes it up with
17+ `try`, to where the parser reads on: what has been made by then is
18+ what the seed had made when it jumped. So most routines here return an
19+ ERROR, as the last of their results.
20+
21+ The seed's `Mismatch` of two operands is `mismatchOps` (raz has no
22+ overloading), and what the parser sets, `demoted` and `checks`, has a
23+ setter each, as an exported variable is read-only outside its module.
24+ The seed's `TItem` is `Item` and `TMode` is `Mode`; its procedures begin
25+ in lower case. *)
26+module Item;
27+import Fmt, Diag, Scan, Sym, Chunk, Gen;
28+
29+type
30+ Mode* = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond,
31+ mWords); (* two results of a call, on the stack, the first under the second *)
32+
33+ Item* = record
34+ mode*: Mode;
35+ typ*: ^Sym.Type;
36+ rel*: Scan.Sym; (* mCond: the comparison of the two integers on
37+ the stack, not yet made, as Wirth's compilers
38+ keep a condition *)
39+ relSigned*: BOOL;
40+ fj*, tj*: INT; (* mCond: the chains of jumps already made that are
41+ taken when the whole condition is false, and when
42+ it is true, not yet given a place (and, or and
43+ not make them); see Gen's jumpOut *)
44+ val*: I64; (* mConst: the value, an F64's bits; mStr: its length *)
45+ base*: Gen.Base; (* mVar: what the address is relative to *)
46+ chunk*: INT; (* mVar with bGlobal, mStr: the chunk; bSlot: the slot *)
47+ off*: I64; (* mVar: added to the base *)
48+ vol*: BOOL; (* mVar: reached through ^VOLATILE *)
49+ isVar*: BOOL; (* mVar: a variable of the program, not a temporary *)
50+ odd*: BOOL; (* mVar: in a packed record, so maybe misaligned *)
51+ ro*: BOOL; (* mVar: another module's exported variable, or part
52+ of one, which only that module changes *)
53+ deref*: BOOL; (* mVar: at an address from a pointer, which may be
54+ nil and isn't tested yet (nilTest) *)
55+ obj*: ^Sym.Obj; (* mProc, mBuiltin, mCase; mVar: the variable named *)
56+ pos*: Diag.Pos; (* where it is in the source, for messages *)
57+ end;
58+
59+const
60+ (* the comparison that holds when the one at the same place doesn't, for integers *)
61+ NegatedOps: [6]Scan.Sym = [Scan.sNeq, Scan.sEql, Scan.sGeq, Scan.sGtr, Scan.sLeq, Scan.sLss];
62+
63+const
64+ MaxI64 = 9223372036854775807;
65+ MinI64 = -9223372036854775807 - 1;
66+
67+var
68+ demoted*: BOOL; (* address wanted a register variable's address: its
69+ procedure is compiled again, the variable in memory *)
70+ checks*: BOOL; (* the module's index and slice checks are made: it
71+ doesn't say check off *)
72+ result: ^Sym.Type; (* the result of the procedure being compiled, or nil *)
73+ passing: ^Sym.Obj; (* the parameter the argument at passingAt goes to *)
74+ passingAt: Diag.Pos;
75+
76+proc setDemoted*(yes: BOOL);
77+begin
78+ demoted := yes;
79+end;
80+
81+proc setChecks*(yes: BOOL);
82+begin
83+ checks := yes;
84+end;
85+
86+(* The comparison that holds when op doesn't *)
87+proc negated(op: Scan.Sym): Scan.Sym;
88+begin
89+ return NegatedOps[INT(op) - INT(Scan.sEql)];
90+end;
91+
92+proc isRel(op: Scan.Sym): BOOL;
93+begin
94+ return (op >= Scan.sEql) and (op <= Scan.sGeq);
95+end;
96+
97+(* Whether op is one of the list: Scan.Sym has too many names for a set *)
98+proc oneOf(op: Scan.Sym; list: []Scan.Sym): BOOL;
99+var i: INT;
100+begin
101+ for i := 0 to LEN(list) - 1 do
102+ if list[i] = op then return true; end;
103+ end;
104+ return false;
105+end;
106+
107+proc bit(f: BOOL): I64;
108+begin
109+ if f then return 1; end;
110+ return 0;
111+end;
112+
113+(* A message, from a format and the strings that fill it *)
114+proc say1(f, a: []U8): []U8;
115+begin
116+ return Diag.say(f, [Fmt.str(a)]);
117+end;
118+
119+proc say2(f, a, b: []U8): []U8;
120+begin
121+ return Diag.say(f, [Fmt.str(a), Fmt.str(b)]);
122+end;
123+
124+(* Items *)
125+
126+proc makeConst*(var x: Item; t: ^Sym.Type; v: I64);
127+var p: Diag.Pos;
128+begin
129+ p := x.pos;
130+ x := {};
131+ x.pos := p;
132+ x.mode := mConst;
133+ x.typ := t;
134+ x.val := v;
135+end;
136+
137+(* A real constant: untyped, unless typed later. Its value is an F64,
138+ which for an F32 is one an F32 can hold. *)
139+proc makeReal*(var x: Item; r: F64);
140+var p: ^F64;
141+begin
142+ makeConst(x, Sym.tRConst, 0);
143+ p := ^F64(ADR(x.val));
144+ p^ := r;
145+end;
146+
147+proc isF32(t: ^Sym.Type): BOOL;
148+begin
149+ return (t^.form = Sym.fReal) and (t^.size = 4);
150+end;
151+
152+proc realOf*(x: Item): F64;
153+var v: I64; p: ^F64;
154+begin
155+ v := x.val;
156+ p := ^F64(ADR(v));
157+ return p^;
158+end;
159+
160+(* Gives a real constant the real type t, rounded to it. *)
161+proc realTo(var x: Item; t: ^Sym.Type);
162+var r: F64;
163+begin
164+ r := realOf(x);
165+ if isF32(t) then makeReal(x, F64(F32(r))); else makeReal(x, r); end;
166+ x.typ := t;
167+end;
168+
169+(* The current string literal, as an item of its own chunk. *)
170+proc makeStr*(var x: Item);
171+begin
172+ x := {};
173+ x.mode := mStr;
174+ x.typ := Sym.tStr;
175+ x.val := Scan.slen;
176+ x.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1);
177+ Chunk.setData(x.chunk, ADR(Scan.strBytes()[0]), Scan.slen + 1, 1);
178+end;
179+
180+proc frameAdr*(off: I64): Gen.Adr;
181+var a: Gen.Adr;
182+begin
183+ a.base := Gen.bFrame;
184+ a.chunk := -1;
185+ a.off := off;
186+ a.hi := 0;
187+ return a;
188+end;
189+
190+proc globalAdr*(c: INT): Gen.Adr;
191+var a: Gen.Adr;
192+begin
193+ a.base := Gen.bGlobal;
194+ a.chunk := c;
195+ a.off := 0;
196+ a.hi := 0;
197+ return a;
198+end;
199+
200+(* Where the variable x is, for Gen; a slice in registers has two *)
201+proc adrOf*(x: Item): Gen.Adr;
202+var a: Gen.Adr;
203+begin
204+ a.base := x.base;
205+ a.chunk := x.chunk;
206+ a.off := x.off;
207+ a.hi := 0;
208+ if x.base = Gen.bReg then a.hi := x.obj^.reg2; end;
209+ return a;
210+end;
211+
212+(* An item for "found ...": a constant without a type of its own as it
213+ is written, so that "found 1.5" says what is wrong; else its type. *)
214+proc what*(x: Item): []U8;
215+begin
216+ if (x.mode = mConst) and ((x.typ = Sym.tConst) or (x.typ = Sym.tRConst)) then
217+ return Diag.source(x.pos);
218+ end;
219+ return Sym.typeName(x.typ);
220+end;
221+
222+(* Two operands of different types. Numbers convert, so say how. *)
223+proc mismatchOps(x, y: Item; xt, yt: ^Sym.Type): ERROR;
224+var text: []U8;
225+begin
226+ text := say2("{} and {} are different types", Sym.typeName(xt), Sym.typeName(yt));
227+ if (Sym.isInt(xt) or (xt^.form = Sym.fReal)) and (Sym.isInt(yt) or (yt^.form = Sym.fReal))
228+ and (xt # Sym.tConst) and (xt # Sym.tRConst) then
229+ return Scan.markHelp(Diag.join(x.pos, y.pos), text,
230+ say2("convert one to the other's type, as in {}({})", Sym.typeName(xt), Diag.source(y.pos)));
231+ end;
232+ return Scan.markAt(Diag.join(x.pos, y.pos), text);
233+end;
234+
235+(* An item that is not a value, by what it is. *)
236+proc notValue(x: Item): ERROR;
237+begin
238+ match x.mode of
239+ | mType: return Scan.markAt(x.pos, say1("{} is a type, not a value", Sym.typeName(x.typ)));
240+ | mBuiltin: return Scan.markAt(x.pos, say1("{} is a built-in procedure, not a value", Scan.nameOf(x.obj^.name)));
241+ | mCase: return Scan.markAt(x.pos, say1("{} is a case, not a value", Scan.nameOf(x.obj^.name)));
242+ | mNone:
243+ if x.obj # nil then return Scan.markAt(x.pos, say1("{} returns nothing", Scan.nameOf(x.obj^.name))); end;
244+ return Scan.markAt(x.pos, "the procedure returns nothing");
245+ | else: return Scan.markAt(x.pos, "a string can't be an operand");
246+ end;
247+end;
248+
249+proc makeItem*(var x: Item; o: ^Sym.Obj): ERROR;
250+begin
251+ x := {};
252+ x.typ := o^.typ;
253+ x.obj := o;
254+ match o^.cls of
255+ | oConst:
256+ if o^.typ = Sym.tStr then
257+ x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk;
258+ elsif o^.typ^.form in {Sym.fArray, Sym.fRecord} then
259+ (* an array or record constant: a variable in read-only data, not one of
260+ the program's, so nothing can change it *)
261+ x.mode := mVar; x.base := Gen.bGlobal; x.chunk := o^.chunk;
262+ else
263+ x.mode := mConst; x.val := o^.val;
264+ end;
265+ | oVar:
266+ x.mode := mVar;
267+ x.ro := (o^.lev = 0) and (o^.home # Sym.curModule);
268+ x.isVar := not x.ro;
269+ if o^.ext then
270+ Gen.pushVar(globalAdr(o^.chunk), 8, false, Gen.kWord);
271+ x.base := Gen.bStack;
272+ elsif o^.lev = 0 then
273+ x.base := Gen.bGlobal; x.chunk := o^.chunk;
274+ elsif o^.ind then
275+ x.base := Gen.bSlot; x.chunk := INT(o^.val); x.off := o^.off;
276+ elsif o^.reg # 0 then
277+ x.base := Gen.bReg; x.chunk := o^.reg;
278+ else
279+ x.base := Gen.bFrame; x.off := o^.val;
280+ end;
281+ | oProc: x.mode := mProc;
282+ | oType: x.mode := mType;
283+ | oBuiltin: x.mode := mBuiltin;
284+ | oCase: x.mode := mCase;
285+ | else: return Scan.mark(say1("{} is not a value", Scan.nameOf(o^.name)));
286+ end;
287+ return nil;
288+end;
289+
290+proc scalarSize*(t: ^Sym.Type): INT;
291+begin
292+ if t^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then return INT(t^.size); end;
293+ return 8;
294+end;
295+
296+(* The width an operation on t is brought back to, and whether signed *)
297+proc intSize(t: ^Sym.Type): INT;
298+begin
299+ if t^.form = Sym.fInt then return INT(t^.size); end;
300+ return 8;
301+end;
302+
303+proc signed(t: ^Sym.Type): BOOL;
304+begin
305+ return ((t^.form = Sym.fInt) and t^.signed) or (t^.form = Sym.fConst);
306+end;
307+
308+proc cut(v: I64; t: ^Sym.Type): I64;
309+begin
310+ if t^.form # Sym.fInt then return v; end;
311+ match t^.size of
312+ | 1: if t^.signed then return I64(I8(v)); end; return I64(U8(v));
313+ | 2: if t^.signed then return I64(I16(v)); end; return I64(U16(v));
314+ | 4: if t^.signed then return I64(I32(v)); end; return I64(U32(v));
315+ | else: return v;
316+ end;
317+end;
318+
319+(* Code computing with a real is noted on its chunk, at the first place,
320+ for a target without reals (report 5.1) to refuse if the chunk turns
321+ out to be used. A real moved whole, as a record's bytes are copied,
322+ needs nothing the target lacks, and isn't noted. *)
323+proc usesReals*(p: Diag.Pos);
324+begin
325+ if (Gen.codeChunk >= 0) and not Chunk.chunks[Gen.codeChunk].reals then
326+ Chunk.setReals(Gen.codeChunk, p);
327+ end;
328+end;
329+
330+(* x, at an address from a pointer, is about to be used: Gen tests the
331+ address for nil where the machine wouldn't stop at it (report section
332+ 10), from its offset to its end. *)
333+proc nilTest*(var x: Item);
334+begin
335+ if (x.mode = mVar) and x.deref then Gen.checkNil(x.off + x.typ^.size, x.pos); end;
336+ x.deref := false;
337+end;
338+
339+(* x's value, on top of the stack *)
340+proc value*(var x: Item): ERROR;
341+var f: F32; p: ^U32;
342+begin
343+ if x.mode = mCond then
344+ if (x.fj = Gen.NoLabel) and (x.tj = Gen.NoLabel) then Gen.compare(x.rel, Gen.kWord, x.relSigned);
345+ else Gen.condValue(negated(x.rel), x.relSigned, x.fj, x.tj); end;
346+ x.mode := mStack;
347+ return nil;
348+ end;
349+ if x.typ^.form = Sym.fReal then usesReals(x.pos); end;
350+ nilTest(x);
351+ match x.mode of
352+ | mConst:
353+ if (x.typ^.form = Sym.fError) and (x.val > 0) then Gen.pushAdr(globalAdr(INT(x.val) - 1));
354+ elsif isF32(x.typ) then
355+ f := F32(realOf(x));
356+ p := ^U32(ADR(f));
357+ Gen.pushConst(Gen.kF32, I64(p^));
358+ else Gen.pushConst(Gen.kindOf(x.typ), x.val); end;
359+ | mVar:
360+ if not Sym.isScalar(x.typ) then
361+ return Scan.markAt(x.pos, say1("expected a single value, found {}", what(x)));
362+ end;
363+ Gen.pushVar(adrOf(x), scalarSize(x.typ), (x.typ^.form = Sym.fInt) and x.typ^.signed, Gen.kindOf(x.typ));
364+ | mStack: x.mode := mStack;
365+ | mProc:
366+ if x.obj^.isCode and (x.obj^.typ^.base # nil) and x.obj^.typ^.base^.tuple then
367+ return Scan.markAt(x.pos, "a code procedure with two results can only be called");
368+ end;
369+ Gen.pushProc(x.obj^.chunk, x.obj^.ext);
370+ | else: return notValue(x);
371+ end;
372+ x.mode := mStack;
373+ return nil;
374+end;
375+
376+(* The address of the variable or string x, on top of the stack *)
377+proc address*(var x: Item): ERROR;
378+begin
379+ nilTest(x);
380+ if (x.mode = mVar) and (x.base = Gen.bReg) then
381+ (* its address is wanted after all: the procedure is compiled again
382+ with the variable in memory; till then, this code is thrown away *)
383+ x.obj^.reg := 0;
384+ x.obj^.reg2 := 0;
385+ demoted := true;
386+ x.base := Gen.bFrame;
387+ x.off := x.obj^.val;
388+ end;
389+ if x.mode = mStr then Gen.pushAdr(globalAdr(x.chunk));
390+ elsif x.mode = mVar then
391+ Gen.pushAdr(adrOf(x));
392+ x.base := Gen.bStack; x.off := 0;
393+ else return Scan.markAt(x.pos, "expected a variable"); end;
394+ return nil;
395+end;
396+
397+(* x isn't wanted: what it has on the stack is dropped *)
398+proc discard*(x: Item): ERROR;
399+var y: Item;
400+begin
401+ if x.mode = mCond then
402+ y := x;
403+ try value(y);
404+ Gen.drop();
405+ return nil;
406+ end;
407+ if (x.mode = mStack) or ((x.mode = mVar) and (x.base = Gen.bStack)) then Gen.drop(); end;
408+ if x.mode = mWords then Gen.drop(); Gen.drop(); end;
409+ return nil;
410+end;
411+
412+(* Frames *)
413+
414+proc tempItem*(var x: Item; t: ^Sym.Type; off: I64);
415+var p: Diag.Pos;
416+begin
417+ p := x.pos;
418+ x := {};
419+ x.pos := p;
420+ x.mode := mVar; x.typ := t; x.base := Gen.bFrame; x.off := off;
421+end;
422+
423+proc toSlot*(var x: Item): (I64, ERROR);
424+var s: I64;
425+begin
426+ try value(x);
427+ s := Gen.allocTemp(8, 8);
428+ Gen.popVar(frameAdr(s), 8);
429+ return s, nil;
430+end;
431+
432+(* Copying *)
433+
434+(* x, copied to a temporary *)
435+proc copyToTemp*(var x: Item): ERROR;
436+var t: I64; f, g: ^Sym.Obj; a: Gen.Adr;
437+begin
438+ if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
439+ t := Gen.allocTemp(x.typ^.size, x.typ^.align);
440+ if (x.mode = mVar) and (x.base = Gen.bReg) then
441+ (* a slice in registers, which has no address: its words stored *)
442+ a := adrOf(x);
443+ Gen.pushVar(a, 8, false, Gen.kWord);
444+ Gen.popVar(frameAdr(t), 8);
445+ a.off := 8;
446+ Gen.pushVar(a, 8, false, Gen.kWord);
447+ Gen.popVar(frameAdr(t + 8), 8);
448+ tempItem(x, x.typ, t);
449+ return nil;
450+ end;
451+ if x.mode = mWords then
452+ (* the second result is on top, so it is popped first *)
453+ f := x.typ^.fields; g := f^.next;
454+ Gen.popVar(frameAdr(t + g^.val), scalarSize(g^.typ));
455+ Gen.popVar(frameAdr(t + f^.val), scalarSize(f^.typ));
456+ tempItem(x, x.typ, t);
457+ return nil;
458+ end;
459+ try address(x);
460+ Gen.copyTo(frameAdr(t), x.typ^.size);
461+ tempItem(x, x.typ, t);
462+ return nil;
463+end;
464+
465+(* A slice made from an address on the stack and a length. *)
466+proc sliceOf*(var x: Item; t: ^Sym.Type; len: I64);
467+var s: I64;
468+begin
469+ s := Gen.allocTemp(16, 8);
470+ Gen.popVar(frameAdr(s), 8);
471+ Gen.pushConst(Gen.kWord, len);
472+ Gen.popVar(frameAdr(s + 8), 8);
473+ tempItem(x, t, s);
474+end;
475+
476+(* An INT goes silently into an I64, and a UINT into a U64, losing
477+ nothing on any target (report section 5.10). *)
478+proc widens(s, t: ^Sym.Type): BOOL;
479+begin
480+ return ((s = Sym.tInt) and Sym.same(t, Sym.tI64)) or ((s = Sym.tUInt) and Sym.same(t, Sym.tU64));
481+end;
482+
483+(* Another module's exported variable can be read, not changed, nor
484+ handed to anything that could change it (report section 3). *)
485+proc notReadOnly*(x: Item): ERROR;
486+begin
487+ if x.ro then
488+ return Scan.markAt(x.pos, Diag.say("{} is {}'s, and can't be changed outside it",
489+ [Fmt.str(Diag.source(x.pos)), Fmt.str(Scan.nameOf(x.obj^.home^.name))]));
490+ end;
491+ return nil;
492+end;
493+
494+(* An error in x's type; if x is an argument, a note at the parameter
495+ it goes to. *)
496+proc mismatch(x: Item; text: []U8): ERROR;
497+begin
498+ Diag.error(x.pos, text);
499+ if (passing # nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then
500+ Diag.note(passing^.pos, say1("it goes to {}, declared here", Scan.nameOf(passing^.name)));
501+ end;
502+ return Scan.Failed;
503+end;
504+
505+proc coerce*(var x: Item; t: ^Sym.Type): ERROR;
506+var s: ^Sym.Type; tmp: I64;
507+begin
508+ if x.mode = mCond then try value(x); end;
509+ s := x.typ;
510+ if x.mode = mStr then
511+ if (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then
512+ try address(x); sliceOf(x, t, x.val);
513+ elsif (t^.form = Sym.fPtr) and (t^.base = Sym.tU8) then
514+ try address(x); x.mode := mStack; x.typ := t;
515+ elsif (t^.form = Sym.fArray) and (t^.base = Sym.tU8) and (t^.len >= x.val) then
516+ tmp := Gen.allocTemp(t^.size, 1);
517+ try address(x);
518+ Gen.copyTo(frameAdr(tmp), x.val);
519+ if t^.len > x.val then Gen.zeroVar(frameAdr(tmp + x.val), t^.len - x.val); end;
520+ tempItem(x, t, tmp);
521+ else return mismatch(x, say1("can't use a string as {}", Sym.typeName(t))); end;
522+ return nil;
523+ end;
524+ if x.mode in {mType, mBuiltin, mNone, mCase} then return notValue(x); end;
525+ if Sym.same(s, t) then return nil; end;
526+ if widens(s, t) then x.typ := t; (* the same bits, on a 64-bit target *)
527+ elsif (s = Sym.tRConst) and (t^.form = Sym.fReal) then realTo(x, t);
528+ elsif (s^.form = Sym.fConst) and (t^.form = Sym.fInt) then
529+ if (x.mode = mConst) and not Sym.fits(x.val, t) then
530+ return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))]));
531+ end;
532+ x.typ := t;
533+ elsif (s^.form = Sym.fNil) and (t^.form in {Sym.fPtr, Sym.fProc, Sym.fError}) then
534+ x.typ := t;
535+ elsif (s^.form = Sym.fPtr) and (t^.form = Sym.fPtr) and t^.vol and not s^.vol
536+ and Sym.same(s^.base, t^.base) then
537+ x.typ := t;
538+ elsif (s^.form = Sym.fArray) and (t^.form = Sym.fSlice) and Sym.same(s^.base, t^.base) then
539+ try notReadOnly(x);
540+ if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end;
541+ if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end;
542+ try address(x);
543+ sliceOf(x, t, s^.len);
544+ elsif (x.mode = mProc) and (t^.form # Sym.fProc) and (s^.base = nil) then
545+ return Scan.markAt(x.pos, say1("{} is a procedure, and returns nothing", Diag.source(x.pos)));
546+ elsif (x.mode = mProc) and (t^.form # Sym.fProc) then
547+ return Scan.markHelp(x.pos,
548+ say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
549+ say1("to call it, write {}()", Diag.source(x.pos)));
550+ else
551+ return mismatch(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)));
552+ end;
553+ return nil;
554+end;
555+
556+(* coerce where the types must be the same, as in a for loop, INC and
557+ several results, which don't widen an INT to an I64 (report sections
558+ 5.10, 6.1 and 7.2); help, if not empty, says why. *)
559+proc coerceExact*(var x: Item; t: ^Sym.Type; help: []U8): ERROR;
560+var h: []U8;
561+begin
562+ if widens(x.typ, t) then
563+ h := help;
564+ if LEN(h) = 0 then
565+ h := say2("they don't mix here: write {}({})", Sym.typeName(t), Diag.source(x.pos));
566+ end;
567+ return Scan.markHelp(x.pos, say2("expected {}, found {}", Sym.typeName(t), what(x)), h);
568+ end;
569+ return coerce(x, t);
570+end;
571+
572+(* dst := src. The address of dst, if it has to be computed, is on the
573+ stack already, under src's. *)
574+proc assign*(var dst, src: Item): ERROR;
575+begin
576+ try coerce(src, dst.typ);
577+ if Sym.isScalar(dst.typ) then
578+ try value(src);
579+ Gen.popVar(adrOf(dst), scalarSize(dst.typ));
580+ else
581+ if dst.vol or src.vol then return Scan.markAt(src.pos, "can't copy through a volatile pointer"); end;
582+ if (src.mode = mVar) and (src.base = Gen.bReg) then try copyToTemp(src); end; (* a slice in registers *)
583+ try address(src);
584+ if dst.base = Gen.bStack then Gen.copyBlock(dst.typ^.size, dst.off);
585+ else Gen.copyTo(adrOf(dst), dst.typ^.size); end;
586+ end;
587+ return nil;
588+end;
589+
590+(* t's name, ending in a zero byte, for Rt.fail *)
591+proc nameChunk(t: ^Sym.Type): INT;
592+var s: []U8; p: ^U8; n, c: INT;
593+begin
594+ s := Sym.typeName(t);
595+ n := LEN(s);
596+ p := Scan.grab(n + 1);
597+ COPY(p[0..n], s);
598+ p[n] := 0;
599+ c := Chunk.newChunk(Chunk.secRodata, -1, -1);
600+ Chunk.setData(c, p, n + 1, 1);
601+ return c;
602+end;
603+
604+(* Selectors *)
605+
606+proc deref*(var x: Item): ERROR;
607+var t: ^Sym.Type;
608+begin
609+ t := x.typ;
610+ if t^.form # Sym.fPtr then
611+ return Scan.markAt(x.pos, say1("expected a pointer, found {}", Sym.typeName(t)));
612+ end;
613+ if t^.base = nil then
614+ return Scan.markAt(x.pos, say1("{} points to a type never declared", Sym.typeName(t)));
615+ end;
616+ try value(x);
617+ x.mode := mVar; x.base := Gen.bStack; x.off := 0; x.deref := true;
618+ x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
619+ return nil;
620+end;
621+
622+(* A field of a packed record, of more than one byte's alignment, may
623+ sit anywhere; it is read and written, but has no address and no
624+ volatile access, which a machine that can't reach a misaligned word
625+ couldn't make one access (report section 5.5). *)
626+proc field*(var x: Item; f: ^Sym.Obj): ERROR;
627+begin
628+ if x.typ^.packd and (f^.typ^.align > 1) then
629+ if x.vol then return Scan.markAt(x.pos, "a field of a packed record can't be volatile"); end;
630+ x.odd := true;
631+ end;
632+ x.off := x.off + f^.val;
633+ x.typ := f^.typ;
634+ return nil;
635+end;
636+
637+proc indexPrep*(var x: Item): ERROR;
638+begin
639+ nilTest(x);
640+ if x.mode = mStr then try coerce(x, Sym.tBytes); end;
641+ if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fArray) then
642+ return Scan.markAt(x.pos, "a pointer to an array is indexed as p^[i]");
643+ end;
644+ if x.typ^.form = Sym.fPtr then try value(x);
645+ elsif not ((x.mode = mVar) and (x.typ^.form in {Sym.fArray, Sym.fSlice})) then
646+ return Scan.markAt(x.pos, say1("expected an array, a slice or a pointer, found {}", what(x)));
647+ end;
648+ return nil;
649+end;
650+
651+(* The index on top, times the size of an element *)
652+proc scaleBy(s: I64);
653+begin
654+ if s # 1 then
655+ Gen.pushConst(Gen.kWord, s);
656+ Gen.op(Scan.sTimes, Gen.kWord, 8, true);
657+ end;
658+end;
659+
660+proc index*(var x, y: Item): ERROR;
661+var t: ^Sym.Type; s: I64;
662+begin
663+ t := x.typ;
664+ s := t^.base^.size;
665+ if not Sym.isInt(y.typ) then
666+ return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y)));
667+ end;
668+ if t^.form = Sym.fPtr then
669+ try value(y);
670+ scaleBy(s);
671+ Gen.op(Scan.sPlus, Gen.kWord, 8, false);
672+ x.mode := mVar; x.base := Gen.bStack; x.off := 0;
673+ x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
674+ elsif (t^.form = Sym.fArray) and (y.mode = mConst) then
675+ if (y.val < 0) or (y.val >= t^.len) then
676+ return Scan.markAt(y.pos, Diag.say("index {} is out of range for a length of {}", [Fmt.int(y.val), Fmt.int(t^.len)]));
677+ end;
678+ x.off := x.off + y.val * s;
679+ elsif t^.form = Sym.fArray then
680+ try value(y);
681+ if checks then Gen.checkIndex(t^.len, y.pos); end;
682+ if x.base = Gen.bStack then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false);
683+ else Gen.indexArray(adrOf(x), s); x.off := 0; end;
684+ x.base := Gen.bStack;
685+ else
686+ try value(y);
687+ Gen.indexSlice(adrOf(x), s, checks, y.pos);
688+ x.base := Gen.bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false;
689+ end;
690+ x.typ := t^.base;
691+ return nil;
692+end;
693+
694+proc sliceLo*(var lo: Item): ERROR;
695+begin
696+ if not Sym.isInt(lo.typ) then
697+ return Scan.markAt(lo.pos, say1("an index is an integer, found {}", what(lo)));
698+ end;
699+ return value(lo);
700+end;
701+
702+proc slice*(var x, lo, hi: Item): ERROR;
703+var t, st: ^Sym.Type; tmp: I64;
704+begin
705+ t := x.typ;
706+ if not Sym.isInt(hi.typ) then
707+ return Scan.markAt(hi.pos, say1("an index is an integer, found {}", what(hi)));
708+ end;
709+ if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end;
710+ if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end;
711+ if t^.form = Sym.fArray then try notReadOnly(x); end;
712+ try value(hi);
713+ tmp := Gen.allocTemp(16, 8);
714+ if t^.form = Sym.fPtr then Gen.slicePtr(t^.base^.size, tmp, checks, lo.pos);
715+ else Gen.slice(adrOf(x), t^.form = Sym.fArray, t^.len, t^.base^.size, tmp, checks, lo.pos); end;
716+ st := Sym.newType(Sym.fSlice, 16, 8);
717+ st^.base := t^.base;
718+ tempItem(x, st, tmp);
719+ return nil;
720+end;
721+
722+(* Operators *)
723+
724+proc neg*(var x: Item): ERROR;
725+begin
726+ if x.typ^.form = Sym.fReal then
727+ if x.mode = mConst then x.val := x.val xor MinI64;
728+ else try value(x); Gen.neg(Gen.kindOf(x.typ), 8, false); end;
729+ elsif Sym.isInt(x.typ) then
730+ if (x.mode = mConst) and (x.typ^.form = Sym.fConst) and (x.val = MinI64) then
731+ return Scan.markAt(x.pos, "the constant is too big for I64");
732+ elsif x.mode = mConst then x.val := cut(-x.val, x.typ);
733+ else try value(x); Gen.neg(Gen.kWord, intSize(x.typ), signed(x.typ)); end;
734+ else return Scan.markAt(x.pos, say1("can't negate {}", Sym.typeName(x.typ))); end;
735+ return nil;
736+end;
737+
738+proc notOp*(var x: Item): ERROR;
739+var L: INT;
740+begin
741+ if Sym.isInt(x.typ) then
742+ return Scan.markHelp(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)), "the bits of an integer flip with ~");
743+ end;
744+ if x.typ^.form # Sym.fBool then
745+ return Scan.markAt(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)));
746+ end;
747+ if x.mode = mConst then x.val := 1 - x.val;
748+ elsif x.mode = mCond then
749+ x.rel := negated(x.rel);
750+ L := x.fj; x.fj := x.tj; x.tj := L;
751+ else try value(x); Gen.notBool(); end;
752+ return nil;
753+end;
754+
755+proc complement*(var x: Item): ERROR;
756+begin
757+ if x.typ^.form = Sym.fBool then
758+ return Scan.markHelp(x.pos, say1("\"~\" needs an integer, found {}", what(x)), "a BOOL is negated with not");
759+ end;
760+ if not Sym.isInt(x.typ) then
761+ return Scan.markAt(x.pos, say1("\"~\" needs an integer, found {}", what(x)));
762+ end;
763+ if x.mode = mConst then x.val := cut(~x.val, x.typ);
764+ else try value(x); Gen.complement(intSize(x.typ), signed(x.typ)); end;
765+ return nil;
766+end;
767+
768+(* Arrays, slices and strings, which = and # compare element by element *)
769+proc isSeq(t: ^Sym.Type): BOOL;
770+begin
771+ return t^.form in {Sym.fStr, Sym.fArray, Sym.fSlice};
772+end;
773+
774+proc elemOf(t: ^Sym.Type): ^Sym.Type;
775+begin
776+ if t^.form = Sym.fStr then return Sym.tU8; end;
777+ return t^.base;
778+end;
779+
780+(* An array, slice or string as a slice in a temporary, for comparing. *)
781+proc seqSlice(var x: Item): ERROR;
782+var t: ^Sym.Type;
783+begin
784+ t := Sym.newType(Sym.fSlice, 16, 8);
785+ t^.base := elemOf(x.typ);
786+ if x.typ^.form = Sym.fSlice then
787+ x.typ := t; try copyToTemp(x);
788+ elsif x.mode = mStr then
789+ try address(x); sliceOf(x, t, x.val);
790+ else
791+ if x.vol then return Scan.markAt(x.pos, "can't compare through a volatile pointer"); end;
792+ try address(x); sliceOf(x, t, x.typ^.len);
793+ end;
794+ return nil;
795+end;
796+
797+(* x, a BOOL, as a condition: a value compared with 0 if it isn't one *)
798+proc makeCond(var x: Item): ERROR;
799+begin
800+ if x.mode = mCond then return nil; end;
801+ try value(x);
802+ Gen.pushConst(Gen.kWord, 0);
803+ x.mode := mCond;
804+ x.rel := Scan.sNeq;
805+ x.relSigned := false;
806+ x.fj := Gen.NoLabel;
807+ x.tj := Gen.NoLabel;
808+ return nil;
809+end;
810+
811+proc op1*(op: Scan.Sym; var x: Item; var L: INT): ERROR;
812+begin
813+ L := Gen.NoLabel;
814+ if ((op = Scan.sAnd) or (op = Scan.sOr)) and (x.typ^.form = Sym.fBool) then
815+ if x.mode = mConst then return nil; end; (* folded by op2 *)
816+ try makeCond(x);
817+ if op = Scan.sAnd then
818+ Gen.jumpOut(negated(x.rel), x.relSigned, x.fj);
819+ Gen.fix(x.tj);
820+ x.tj := Gen.NoLabel;
821+ else
822+ Gen.jumpOut(x.rel, x.relSigned, x.tj);
823+ Gen.fix(x.fj);
824+ x.fj := Gen.NoLabel;
825+ end;
826+ elsif ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(x.typ) then
827+ try seqSlice(x);
828+ elsif (op = Scan.sPlus) and (x.mode = mStr) then
829+ (* two string constants to be joined: nothing to compute *)
830+ elsif (op = Scan.sPlus) and isSeq(x.typ) then
831+ return Scan.markHelp(x.pos, say1("+ doesn't join {}", what(x)), "strings are joined in a Buf: Buf.str(b, s)");
832+ elsif x.mode in {mType, mBuiltin, mNone, mCase, mStr} then
833+ return notValue(x);
834+ elsif x.mode # mConst then
835+ try value(x);
836+ end;
837+ return nil;
838+end;
839+
840+proc log2(v: I64): INT;
841+var n: INT;
842+begin
843+ n := 0;
844+ while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end;
845+ if v # 1 then n := -1; end;
846+ return n;
847+end;
848+
849+(* Whether a op b, for + - *, overflows an I64: an untyped constant
850+ doesn't wrap, it is an error (report section 4). *)
851+proc overflows(op: Scan.Sym; a, b: I64): BOOL;
852+begin
853+ match op of
854+ | sPlus: return ((b > 0) and (a > MaxI64 - b)) or ((b < 0) and (a < MinI64 - b));
855+ | sMinus: return ((b < 0) and (a > MaxI64 + b)) or ((b > 0) and (a < MinI64 + b));
856+ | sTimes:
857+ if (a = 0) or (b = 0) then return false; end;
858+ if a = -1 then return b = MinI64; end;
859+ if b = -1 then return a = MinI64; end;
860+ return (a * b) div b # a;
861+ | else: return false;
862+ end;
863+end;
864+
865+(* A type's width in bits; an untyped constant's is an I64's *)
866+proc bits(t: ^Sym.Type): I64;
867+begin
868+ return t^.size * 8;
869+end;
870+
871+(* a div b and a mod b, of type t *)
872+proc foldDiv(op: Scan.Sym; a, b: I64; t: ^Sym.Type; p: Diag.Pos): (I64, ERROR);
873+begin
874+ if b = 0 then return 0, Scan.markAt(p, "division by zero"); end;
875+ if (t^.form = Sym.fInt) and not t^.signed then
876+ if op = Scan.sDiv then return I64(U64(a) div U64(b)), nil; end;
877+ return I64(U64(a) mod U64(b)), nil;
878+ end;
879+ if (b = -1) and (a = I64(-1) shl (bits(t) - 1)) then return 0, Scan.markAt(p, "division overflows"); end;
880+ if op = Scan.sDiv then return a div b, nil; end;
881+ return a mod b, nil;
882+end;
883+
884+proc foldInt(op: Scan.Sym; a, b: I64; t: ^Sym.Type; p: Diag.Pos): (I64, ERROR);
885+var u: BOOL;
886+begin
887+ u := (t^.form = Sym.fInt) and not t^.signed;
888+ if (t^.form = Sym.fConst) and overflows(op, a, b) then
889+ return 0, Scan.markAt(p, "the constant is too big for I64");
890+ end;
891+ match op of
892+ | sPlus: return a + b, nil;
893+ | sMinus: return a - b, nil;
894+ | sTimes: return a * b, nil;
895+ | sDiv: return foldDiv(op, a, b, t, p);
896+ | sMod: return foldDiv(op, a, b, t, p);
897+ | sAmp: return a & b, nil;
898+ | sBar: return a | b, nil;
899+ | sXor: return a xor b, nil;
900+ | sShl: return a shl (b & (bits(t) - 1)), nil;
901+ | sShr:
902+ if u then return I64(U64(a) shr (b & (bits(t) - 1))), nil; end;
903+ return a shr (b & (bits(t) - 1)), nil;
904+ | sEql: return bit(a = b), nil;
905+ | sNeq: return bit(a # b), nil;
906+ | sLss:
907+ if u then return bit(U64(a) < U64(b)), nil; end;
908+ return bit(a < b), nil;
909+ | sLeq:
910+ if u then return bit(U64(a) <= U64(b)), nil; end;
911+ return bit(a <= b), nil;
912+ | sGtr:
913+ if u then return bit(U64(a) > U64(b)), nil; end;
914+ return bit(a > b), nil;
915+ | sGeq:
916+ if u then return bit(U64(a) >= U64(b)), nil; end;
917+ return bit(a >= b), nil;
918+ | else: return 0, Scan.markAt(p, "bad operator");
919+ end;
920+end;
921+
922+(* Folds x op y, of the real type t: an F32 rounded at each step, as
923+ the machine would. *)
924+proc foldReal(op: Scan.Sym; x, y: Item; t: ^Sym.Type; var r: Item): BOOL;
925+var a, b: F64; ok: BOOL;
926+begin
927+ a := realOf(x); b := realOf(y);
928+ ok := true;
929+ match op of
930+ | sPlus: makeReal(r, a + b);
931+ | sMinus: makeReal(r, a - b);
932+ | sTimes: makeReal(r, a * b);
933+ | sSlash: makeReal(r, a / b);
934+ | sEql: makeConst(r, Sym.tBool, bit(a = b));
935+ | sNeq: makeConst(r, Sym.tBool, bit(a # b));
936+ | sLss: makeConst(r, Sym.tBool, bit(a < b));
937+ | sLeq: makeConst(r, Sym.tBool, bit(a <= b));
938+ | sGtr: makeConst(r, Sym.tBool, bit(a > b));
939+ | sGeq: makeConst(r, Sym.tBool, bit(a >= b));
940+ | else: ok := false;
941+ end;
942+ if r.typ^.form = Sym.fReal then realTo(r, t); end;
943+ return ok;
944+end;
945+
946+(* and, or and not are for BOOLs; &, |, xor and ~ for the bits of
947+ integers: x is the wrong kind for op, and the message names the
948+ operator it may have meant *)
949+proc wrongLogic(op: Scan.Sym; var x: Item): ERROR;
950+var bitsOf: []U8;
951+begin
952+ bitsOf := "the bits of integers take ";
953+ if (op = Scan.sAnd) and Sym.isInt(x.typ) then
954+ return Scan.markHelp(x.pos, say1("\"and\" needs BOOLs, found {}", what(x)), say1("{}&", bitsOf));
955+ elsif (op = Scan.sOr) and Sym.isInt(x.typ) then
956+ return Scan.markHelp(x.pos, say1("\"or\" needs BOOLs, found {}", what(x)), say1("{}|", bitsOf));
957+ elsif op = Scan.sAmp then
958+ return Scan.markHelp(x.pos, say1("\"&\" needs integers, found {}", what(x)), "BOOLs take and");
959+ elsif op = Scan.sBar then
960+ return Scan.markHelp(x.pos, say1("\"|\" needs integers, found {}", what(x)), "BOOLs take or");
961+ elsif op = Scan.sXor then
962+ return Scan.markHelp(x.pos, say1("\"xor\" needs integers, found {}", what(x)), "BOOLs that differ are #");
963+ end;
964+ return Scan.markAt(x.pos, say2("{} needs BOOLs, found {}", Scan.symText(op), what(x)));
965+end;
966+
967+(* x + y, of two string constants: one string, in a chunk of its own
968+ (report section 4) *)
969+proc joinStr(var x, y: Item): ERROR;
970+var p: ^U8; c, xs, ys, xl, yl: INT;
971+begin
972+ if y.mode # mStr then
973+ return Scan.markAt(y.pos, say1("\"+\" joins two strings, found {}", what(y)));
974+ end;
975+ xs := Chunk.chunks[x.chunk].start;
976+ ys := Chunk.chunks[y.chunk].start;
977+ xl := INT(x.val);
978+ yl := INT(y.val);
979+ p := Scan.grab(xl + yl + 1);
980+ COPY(p[0..xl], Chunk.rodata[xs..xs + xl]);
981+ COPY(p[xl..xl + yl + 1], Chunk.rodata[ys..ys + yl + 1]);
982+ c := Chunk.newChunk(Chunk.secRodata, -1, -1);
983+ Chunk.setData(c, p, xl + yl + 1, 1);
984+ x.chunk := c;
985+ x.val := x.val + y.val;
986+ return nil;
987+end;
988+
989+(* x <= y has no bit of x outside y; x >= y is y <= x *)
990+proc setSubset(op: Scan.Sym);
991+begin
992+ if op = Scan.sGeq then Gen.swap(); end;
993+ Gen.complement(8, false);
994+ Gen.op(Scan.sAmp, Gen.kWord, 8, false);
995+ Gen.pushConst(Gen.kWord, 0);
996+ Gen.compare(Scan.sEql, Gen.kWord, false);
997+end;
998+
999+(* A set's operations, as operations on its bits: the two values on top *)
1000+proc setOp(op: Scan.Sym);
1001+begin
1002+ match op of
1003+ | sPlus: Gen.op(Scan.sBar, Gen.kWord, 8, false);
1004+ | sTimes: Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1005+ | sMinus: Gen.complement(8, false); Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1006+ | sLeq: setSubset(op);
1007+ | sGeq: setSubset(op);
1008+ | sIn:
1009+ Gen.swap();
1010+ Gen.op(Scan.sShr, Gen.kWord, 8, false);
1011+ Gen.pushConst(Gen.kWord, 1);
1012+ Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1013+ | else: Gen.compare(op, Gen.kWord, false);
1014+ end;
1015+end;
1016+
1017+(* The operators the arithmetic of integers, of reals and of sets
1018+ stand for, and the comparisons *)
1019+proc intOp(op: Scan.Sym): BOOL;
1020+begin
1021+ return isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod,
1022+ Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr]);
1023+end;
1024+
1025+proc doesntApply(op: Scan.Sym; x, y: Item; t: ^Sym.Type): ERROR;
1026+begin
1027+ return Scan.markAt(Diag.join(x.pos, y.pos), say2("{} doesn't apply to {}", Scan.symText(op), Sym.typeName(t)));
1028+end;
1029+
1030+proc op2*(op: Scan.Sym; var x, y: Item; _L: INT): ERROR;
1031+var xt, yt, t, e: ^Sym.Type; r: Item; scale: INT; isPtr: BOOL; a, b, v: I64;
1032+begin
1033+ xt := x.typ; yt := y.typ;
1034+ if y.mode in {mType, mBuiltin, mNone, mCase} then return notValue(y); end;
1035+ if (op = Scan.sPlus) and (x.mode = mStr) then return joinStr(x, y); end;
1036+
1037+ if (op = Scan.sAnd) or (op = Scan.sOr) then
1038+ if xt^.form # Sym.fBool then return wrongLogic(op, x); end;
1039+ if yt^.form # Sym.fBool then return wrongLogic(op, y); end;
1040+ if (x.mode = mConst) and (y.mode = mConst) then
1041+ if op = Scan.sAnd then x.val := x.val & y.val; else x.val := x.val | y.val; end;
1042+ elsif x.mode = mConst then
1043+ (* true and y, false or y: y; else x, y computed and dropped *)
1044+ if (x.val = 1) = (op = Scan.sAnd) then x := y;
1045+ else try discard(y); end;
1046+ else
1047+ try makeCond(y);
1048+ if op = Scan.sAnd then x.fj := Gen.joinJumps(x.fj, y.fj); x.tj := y.tj;
1049+ else x.tj := Gen.joinJumps(x.tj, y.tj); x.fj := y.fj; end;
1050+ x.rel := y.rel;
1051+ x.relSigned := y.relSigned;
1052+ end;
1053+ return nil;
1054+ end;
1055+
1056+ if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (xt^.form = Sym.fBool) then return wrongLogic(op, x); end;
1057+ if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (yt^.form = Sym.fBool) then return wrongLogic(op, y); end;
1058+
1059+ (* the lengths, then the bytes, LEN * SIZE(T) of them: the elements
1060+ are of types whose bytes say all there is to their values *)
1061+ if ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(xt) then
1062+ e := elemOf(xt);
1063+ if not isSeq(yt) then
1064+ return Scan.markAt(Diag.join(x.pos, y.pos), say1("can't compare an array with {}", Sym.typeName(yt)));
1065+ elsif not Sym.same(e, elemOf(yt)) then
1066+ return Scan.markAt(Diag.join(x.pos, y.pos),
1067+ say2("can't compare an array of {} with one of {}", Sym.typeName(e), Sym.typeName(elemOf(yt))));
1068+ end;
1069+ if e^.form = Sym.fReal then
1070+ return Scan.markHelp(Diag.join(x.pos, y.pos),
1071+ say1("can't compare arrays of reals with {}", Scan.symText(op)),
1072+ "-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop");
1073+ elsif not (e^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fPtr}) then
1074+ return Scan.markHelp(Diag.join(x.pos, y.pos),
1075+ say2("can't compare arrays of {} with {}", Sym.typeName(e), Scan.symText(op)), "write a loop");
1076+ end;
1077+ try seqSlice(y);
1078+ Gen.compareSeq(x.off, y.off, log2(e^.size), op = Scan.sEql);
1079+ makeConst(x, Sym.tBool, 0);
1080+ x.mode := mStack;
1081+ return nil;
1082+ end;
1083+
1084+ (* the type of the result, and the checks *)
1085+ t := nil; scale := 1; isPtr := false;
1086+ if Sym.isInt(xt) and Sym.isInt(yt) then
1087+ if op = Scan.sSlash then
1088+ return Scan.markHelp(Diag.join(x.pos, y.pos), "\"/\" divides reals, not integers",
1089+ say2("to divide integers, write {} div {}", Diag.source(x.pos), Diag.source(y.pos)));
1090+ end;
1091+ if (op = Scan.sShl) or (op = Scan.sShr) then
1092+ if xt^.form = Sym.fConst then t := Sym.tConst; else t := xt; end;
1093+ elsif (xt^.form = Sym.fConst) and (yt^.form = Sym.fConst) then t := Sym.tConst;
1094+ elsif xt^.form = Sym.fConst then
1095+ if (x.mode = mConst) and not Sym.fits(x.val, yt) then
1096+ return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(yt))]));
1097+ end;
1098+ t := yt;
1099+ elsif yt^.form = Sym.fConst then
1100+ if (y.mode = mConst) and not Sym.fits(y.val, xt) then
1101+ return Scan.markAt(y.pos, Diag.say("{} doesn't fit {}", [Fmt.int(y.val), Fmt.str(Sym.typeName(xt))]));
1102+ end;
1103+ t := xt;
1104+ elsif Sym.same(xt, yt) then t := xt;
1105+ else return mismatchOps(x, y, xt, yt); end;
1106+ if not intOp(op) then return doesntApply(op, x, y, t); end;
1107+ elsif (xt^.form = Sym.fReal) and (yt^.form = Sym.fReal) then
1108+ if not (isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash])) then
1109+ return doesntApply(op, x, y, xt);
1110+ end;
1111+ if xt = Sym.tRConst then t := yt;
1112+ elsif (yt = Sym.tRConst) or Sym.same(xt, yt) then t := xt;
1113+ else return mismatchOps(x, y, xt, yt); end;
1114+ if (x.mode = mConst) and (x.typ # t) then realTo(x, t); end;
1115+ if (y.mode = mConst) and (y.typ # t) then realTo(y, t); end;
1116+ elsif (xt^.form = Sym.fBool) and (yt^.form = Sym.fBool) then
1117+ if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end;
1118+ t := Sym.tBool;
1119+ elsif (xt^.form = Sym.fPtr) and Sym.isInt(yt) and ((op = Scan.sPlus) or (op = Scan.sMinus)) then
1120+ t := xt; scale := INT(xt^.base^.size); isPtr := true;
1121+ if y.mode = mConst then y.typ := Sym.tInt; end;
1122+ elsif (xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and (op = Scan.sMinus) then
1123+ if not Sym.same(xt, yt) then return mismatchOps(x, y, xt, yt); end;
1124+ t := Sym.tInt; scale := INT(xt^.base^.size); isPtr := true;
1125+ elsif (xt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) and (yt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) then
1126+ if not isRel(op) then return doesntApply(op, x, y, xt); end;
1127+ if (xt^.form in {Sym.fProc, Sym.fError}) or (yt^.form in {Sym.fProc, Sym.fError}) then
1128+ if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end;
1129+ end;
1130+ if (xt^.form # Sym.fNil) and (yt^.form # Sym.fNil) and not Sym.same(xt, yt) then
1131+ if not ((xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and Sym.same(xt^.base, yt^.base)) then
1132+ return mismatchOps(x, y, xt, yt);
1133+ end;
1134+ end;
1135+ t := Sym.tU64;
1136+ elsif (xt^.form = Sym.fEnum) and Sym.same(xt, yt) then
1137+ if not isRel(op) then return doesntApply(op, x, y, xt); end;
1138+ t := xt;
1139+ elsif (xt^.form = Sym.fSet) and Sym.same(xt, yt) then
1140+ if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sMinus, Scan.sEql, Scan.sNeq, Scan.sLeq, Scan.sGeq]) then
1141+ return doesntApply(op, x, y, xt);
1142+ end;
1143+ t := xt;
1144+ elsif (op = Scan.sIn) and (yt^.form = Sym.fSet) and Sym.same(xt, yt^.base) then
1145+ t := yt;
1146+ else
1147+ return mismatchOps(x, y, xt, yt);
1148+ end;
1149+
1150+ (* constants *)
1151+ if (x.mode = mConst) and (y.mode = mConst) and not isPtr then
1152+ if t^.form = Sym.fReal then
1153+ if not foldReal(op, x, y, t, r) then return doesntApply(op, x, y, xt); end;
1154+ x := r;
1155+ elsif t^.form = Sym.fSet then
1156+ a := x.val; b := y.val;
1157+ match op of
1158+ | sPlus: makeConst(x, t, a | b);
1159+ | sTimes: makeConst(x, t, a & b);
1160+ | sMinus: makeConst(x, t, a & ~b);
1161+ | sIn: makeConst(x, Sym.tBool, (b shr a) & 1);
1162+ | sLeq: makeConst(x, Sym.tBool, bit((a & ~b) = 0));
1163+ | sGeq: makeConst(x, Sym.tBool, bit((b & ~a) = 0));
1164+ | else: makeConst(x, Sym.tBool, bit((a = b) = (op = Scan.sEql)));
1165+ end;
1166+ elsif isRel(op) then
1167+ v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos));
1168+ makeConst(x, Sym.tBool, v);
1169+ else
1170+ v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos));
1171+ makeConst(x, t, cut(v, t));
1172+ end;
1173+ return nil;
1174+ end;
1175+
1176+ (* x and y on the stack, x under y; a constant x goes on after y, and
1177+ is left on top where the order doesn't matter, as Gen takes a
1178+ constant best on the right: 0.25 * e is mulsd xmm8, [0.25] *)
1179+ try value(y);
1180+ if x.mode = mConst then
1181+ try value(x);
1182+ if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sAmp, Scan.sBar, Scan.sXor]) or isPtr then Gen.swap(); end;
1183+ end;
1184+
1185+ if t^.form = Sym.fReal then
1186+ if isRel(op) then Gen.compare(op, Gen.kindOf(t), false);
1187+ else Gen.op(op, Gen.kindOf(t), 8, false); end;
1188+ elsif t^.form = Sym.fSet then
1189+ setOp(op);
1190+ elsif isRel(op) then
1191+ x.mode := mCond;
1192+ x.rel := op;
1193+ x.relSigned := signed(t);
1194+ x.fj := Gen.NoLabel;
1195+ x.tj := Gen.NoLabel;
1196+ x.typ := Sym.tBool;
1197+ return nil;
1198+ elsif isPtr then
1199+ if t # Sym.tInt then scaleBy(scale); end;
1200+ Gen.op(op, Gen.kWord, 8, false);
1201+ if (t = Sym.tInt) and (scale # 1) then
1202+ Gen.pushConst(Gen.kWord, scale);
1203+ Gen.op(Scan.sDiv, Gen.kWord, 8, true);
1204+ end;
1205+ else
1206+ Gen.op(op, Gen.kindOf(t), intSize(t), signed(t));
1207+ end;
1208+ x.mode := mStack;
1209+ if isRel(op) or (op = Scan.sIn) then x.typ := Sym.tBool; else x.typ := t; end;
1210+ return nil;
1211+end;
1212+
1213+(* INT and UINT, the integers as big as an address, through which
1214+ integers and pointers convert (report section 6.7) *)
1215+proc isWord*(t: ^Sym.Type): BOOL;
1216+begin
1217+ return Sym.same(t, Sym.tInt) or Sym.same(t, Sym.tUInt);
1218+end;
1219+
1220+proc convert*(var x: Item; t: ^Sym.Type): ERROR;
1221+var s: ^Sym.Type; r: F64;
1222+begin
1223+ s := x.typ;
1224+ if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then
1225+ if x.mode = mStr then return Scan.markAt(x.pos, "can't convert a string"); end;
1226+ return notValue(x);
1227+ end;
1228+ if Sym.same(s, t) then return nil; end;
1229+ if (Sym.isInt(s) or (s^.form in {Sym.fEnum, Sym.fSet})) and (t^.form = Sym.fInt) then
1230+ if x.mode = mConst then x.val := cut(x.val, t);
1231+ else try value(x); Gen.narrow(INT(t^.size), t^.signed); end;
1232+ elsif Sym.isInt(s) and (t^.form = Sym.fEnum) then
1233+ if x.mode = mConst then
1234+ if (x.val < 0) or (x.val >= t^.len) then
1235+ return Scan.markAt(x.pos, Diag.say("{} isn't a position of {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))]));
1236+ end;
1237+ else try value(x); Gen.checkEnum(t^.len, nameChunk(t), x.pos); end;
1238+ elsif Sym.isInt(s) and (t^.form = Sym.fSet) then
1239+ if x.mode = mConst then
1240+ if t^.len < 64 then x.val := x.val & ((I64(1) shl t^.len) - 1); end;
1241+ else
1242+ try value(x);
1243+ if t^.len < 64 then
1244+ Gen.pushConst(Gen.kWord, (I64(1) shl t^.len) - 1);
1245+ Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1246+ end;
1247+ end;
1248+ elsif Sym.isInt(s) and (t^.form = Sym.fReal) then
1249+ if x.mode = mConst then
1250+ if (s^.form = Sym.fInt) and not s^.signed then r := F64(U64(x.val)); else r := F64(x.val); end;
1251+ makeReal(x, r);
1252+ realTo(x, t);
1253+ else
1254+ try value(x);
1255+ Gen.intToReal(Gen.kindOf(t), (s^.form = Sym.fInt) and not s^.signed and (s^.size = 8));
1256+ end;
1257+ elsif (s^.form = Sym.fReal) and (t^.form = Sym.fReal) then
1258+ (* F32 to F64, F64 to F32, or a real constant to either *)
1259+ if x.mode = mConst then realTo(x, t);
1260+ else try value(x); Gen.realToReal(Gen.kindOf(s)); end;
1261+ elsif (s^.form = Sym.fReal) and (t^.form = Sym.fInt) then
1262+ if x.mode = mConst then
1263+ r := realOf(x);
1264+ (* NaN or out of range folds to low(int64), the "integer
1265+ indefinite" cvttsd2si gives at run time *)
1266+ if (r # r) or (r >= 9.2233720368547758E18) or (r < -9.2233720368547758E18) then
1267+ x.val := cut(MinI64, t);
1268+ else x.val := cut(I64(r), t); end;
1269+ else
1270+ try value(x); Gen.realToInt(Gen.kindOf(s)); Gen.narrow(INT(t^.size), t^.signed);
1271+ end;
1272+ elsif (isWord(s) or (s^.form in {Sym.fConst, Sym.fPtr, Sym.fProc, Sym.fNil})) and (t^.form in {Sym.fPtr, Sym.fProc}) then
1273+ if x.mode # mConst then try value(x); end;
1274+ elsif (s^.form in {Sym.fPtr, Sym.fProc}) and isWord(t) then
1275+ try value(x);
1276+ else
1277+ return Scan.markAt(x.pos, say2("can't convert {} to {}", Sym.typeName(s), Sym.typeName(t)));
1278+ end;
1279+ x.typ := t;
1280+ return nil;
1281+end;
1282+
1283+(* Calls *)
1284+
1285+proc beginCall*(var c: Gen.CallInfo; var x: Item): ERROR;
1286+begin
1287+ if x.mode = mProc then
1288+ c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0;
1289+ c.obj := x.obj; c.ext := x.obj^.ext;
1290+ else
1291+ c.obj := nil; c.ext := false;
1292+ if x.typ^.form # Sym.fProc then
1293+ return Scan.markAt(x.pos, say1("expected a procedure, found {}", what(x)));
1294+ end;
1295+ c.sig := x.typ; c.chunk := -1;
1296+ c.target := try toSlot(x);
1297+ end;
1298+ c.param := c.sig^.fields;
1299+ c.n := 0;
1300+ return nil;
1301+end;
1302+
1303+(* Too many arguments or too few, at p *)
1304+proc wrongCount(var c: Gen.CallInfo; p: Diag.Pos; text: []U8): ERROR;
1305+begin
1306+ if c.obj = nil then return Scan.markAt(p, text); end;
1307+ Diag.error(p, Diag.say("{}: {} takes {}", [Fmt.str(text), Fmt.str(Scan.nameOf(c.obj^.name)), Fmt.int(c.sig^.len)]));
1308+ if c.obj^.home # nil then Diag.note(c.obj^.pos, "the signature is here"); end;
1309+ return Scan.Failed;
1310+end;
1311+
1312+(* Pushes the two words of x, a slice or two results (inTwoRegs), read
1313+ from memory now, so that what comes after can't change them. *)
1314+proc pushWords(var x: Item): ERROR;
1315+var adr: Gen.Adr; f: ^Sym.Obj;
1316+begin
1317+ if x.mode = mWords then return nil; end; (* there already *)
1318+ (* copied to a temporary unless its two words are in memory at a place
1319+ that a later argument can't change *)
1320+ if (x.mode # mVar) or x.vol or not (x.base in {Gen.bFrame, Gen.bGlobal, Gen.bSlot, Gen.bReg}) then
1321+ try copyToTemp(x);
1322+ end;
1323+ adr := adrOf(x);
1324+ if x.typ^.form = Sym.fSlice then
1325+ Gen.pushVar(adr, 8, false, Gen.kWord);
1326+ INC(adr.off, 8);
1327+ Gen.pushVar(adr, 8, false, Gen.kWord);
1328+ else
1329+ f := x.typ^.fields;
1330+ while f # nil do
1331+ adr.off := adrOf(x).off + f^.val;
1332+ Gen.pushVar(adr, scalarSize(f^.typ), signed(f^.typ), Gen.kindOf(f^.typ));
1333+ f := f^.next;
1334+ end;
1335+ end;
1336+ return nil;
1337+end;
1338+
1339+proc passArg*(var c: Gen.CallInfo; var a: Item): ERROR;
1340+var p: ^Sym.Obj;
1341+begin
1342+ p := c.param;
1343+ if c.n >= LEN(c.isF) - 1 then return Scan.markAt(a.pos, "too many arguments"); end;
1344+ if p = nil then
1345+ (* past the parameters of a C procedure that ends in ...: a string
1346+ goes as a C string, an integer constant as an INT, a real
1347+ constant as an F64; C takes no F32 there *)
1348+ if not c.sig^.variadic then return wrongCount(c, a.pos, "too many arguments"); end;
1349+ if a.mode = mStr then try coerce(a, Sym.tPtrU8);
1350+ elsif a.typ^.form = Sym.fConst then try coerce(a, Sym.tInt);
1351+ elsif a.typ = Sym.tRConst then try coerce(a, Sym.tReal);
1352+ elsif isF32(a.typ) then return Scan.markAt(a.pos, "an F32 goes to ... as F64(x)");
1353+ elsif not Sym.isScalar(a.typ) then return Scan.markAt(a.pos, "only a single value goes to ..."); end;
1354+ c.isF[c.n] := a.typ^.form = Sym.fReal;
1355+ c.pair[c.n] := false;
1356+ try value(a);
1357+ INC(c.n);
1358+ return nil;
1359+ end;
1360+ c.isF[c.n] := (p^.typ^.form = Sym.fReal) and not p^.isVar;
1361+ passing := p;
1362+ passingAt := a.pos;
1363+ if p^.isVar then
1364+ try notReadOnly(a);
1365+ if (a.mode # mVar) or not a.isVar then return Scan.markAt(a.pos, "a var parameter needs a variable"); end;
1366+ if a.odd then return Scan.markAt(a.pos, "a field of a packed record can't be a var parameter"); end;
1367+ if not Sym.same(a.typ, p^.typ) then
1368+ return mismatch(a, say2("a var parameter needs exactly {}, found {}", Sym.typeName(p^.typ), what(a)));
1369+ end;
1370+ if a.vol then return Scan.markAt(a.pos, "can't pass through a volatile pointer to a var parameter"); end;
1371+ try address(a);
1372+ elsif p^.typ^.form = Sym.fSlice then
1373+ try coerce(a, p^.typ);
1374+ try pushWords(a);
1375+ c.pair[c.n] := true;
1376+ INC(c.n);
1377+ c.isF[c.n] := false;
1378+ elsif Sym.isAggregate(p^.typ) then
1379+ try coerce(a, p^.typ);
1380+ if a.isVar or a.vol or (a.base # Gen.bFrame) then try copyToTemp(a); end;
1381+ try address(a);
1382+ else
1383+ try coerce(a, p^.typ);
1384+ try value(a);
1385+ end;
1386+ c.pair[c.n] := false;
1387+ INC(c.n);
1388+ c.param := p^.next;
1389+ return nil;
1390+end;
1391+
1392+(* The call c made, with x its result as an item: none; a temporary, for a
1393+ slice or a record; two results on Gen's stack (mWords); else one value
1394+ on the stack. *)
1395+proc endCall*(var c: Gen.CallInfo; var x: Item): ERROR;
1396+var res: ^Sym.Type;
1397+begin
1398+ if c.param # nil then try wrongCount(c, Scan.tokPos(), "too few arguments"); end;
1399+ Gen.call(c);
1400+ res := c.sig^.base;
1401+ x := {};
1402+ if res = nil then
1403+ x.mode := mNone; x.typ := Sym.tNone; x.obj := c.obj;
1404+ elsif c.ret # 0 then
1405+ tempItem(x, res, c.ret);
1406+ else
1407+ x.mode := mStack; x.typ := res;
1408+ if res^.tuple then x.mode := mWords; end;
1409+ end;
1410+ return nil;
1411+end;
1412+
1413+(* Variants *)
1414+
1415+(* A temporary of type t, all zero: for variants and record literals. *)
1416+proc zeroTemp*(var x: Item; t: ^Sym.Type);
1417+var tmp: I64;
1418+begin
1419+ tmp := Gen.allocTemp(t^.size, t^.align);
1420+ Gen.zeroVar(frameAdr(tmp), t^.size);
1421+ tempItem(x, t, tmp);
1422+end;
1423+
1424+proc construct*(var x: Item; c: ^Sym.Obj);
1425+begin
1426+ zeroTemp(x, c^.typ);
1427+ Gen.pushConst(Gen.kWord, c^.val);
1428+ Gen.popVar(frameAdr(x.off), 8);
1429+end;
1430+
1431+proc setField*(x: Item; f: ^Sym.Obj; var a: Item): ERROR;
1432+begin
1433+ try coerce(a, f^.typ);
1434+ if Sym.isScalar(f^.typ) then
1435+ try value(a);
1436+ Gen.popVar(frameAdr(x.off + f^.val), scalarSize(f^.typ));
1437+ else
1438+ if a.vol then return Scan.markAt(a.pos, "can't copy through a volatile pointer"); end;
1439+ try address(a);
1440+ Gen.copyTo(frameAdr(x.off + f^.val), f^.typ^.size);
1441+ end;
1442+ return nil;
1443+end;
1444+
1445+(* The slot match tests: a variant's address, or an enumeration's or an
1446+ integer's value. *)
1447+proc matchBegin*(var x: Item): (I64, ERROR);
1448+var p: I64;
1449+begin
1450+ if x.typ^.form in {Sym.fEnum, Sym.fInt} then return toSlot(x); end;
1451+ if (x.mode # mVar) or (x.typ^.form # Sym.fVariant) then
1452+ return 0, Scan.markAt(x.pos, say1("match needs a variant, an enumeration or an integer, found {}", what(x)));
1453+ end;
1454+ if x.ro then try copyToTemp(x); end; (* its arms' names stand for a copy's fields *)
1455+ try address(x);
1456+ p := Gen.allocTemp(8, 8);
1457+ Gen.popVar(frameAdr(p), 8);
1458+ return p, nil;
1459+end;
1460+
1461+(* To L unless the tag of the variant whose address is in slot p is tag *)
1462+proc matchTag*(p: I64; tag: I64; var L: INT);
1463+var a: Gen.Adr;
1464+begin
1465+ Gen.pushVar(frameAdr(p), 8, false, Gen.kWord);
1466+ a.base := Gen.bStack; a.chunk := -1; a.off := 0; a.hi := 0;
1467+ Gen.pushVar(a, 8, false, Gen.kWord);
1468+ Gen.pushConst(Gen.kWord, tag);
1469+ Gen.jumpCmp(Scan.sNeq, false, L);
1470+end;
1471+
1472+(* To body if the integer in slot p is from lo to hi: less its lo, it is
1473+ then at most hi - lo, compared unsigned, which holds for a signed type
1474+ or not, with no second jump. *)
1475+proc matchRange*(p, lo, hi: I64; var body: INT);
1476+begin
1477+ Gen.pushVar(frameAdr(p), 8, false, Gen.kWord);
1478+ if lo = hi then
1479+ Gen.pushConst(Gen.kWord, lo);
1480+ Gen.jumpCmp(Scan.sEql, false, body);
1481+ return;
1482+ end;
1483+ if lo # 0 then
1484+ Gen.pushConst(Gen.kWord, lo);
1485+ Gen.op(Scan.sMinus, Gen.kWord, 8, false);
1486+ end;
1487+ Gen.pushConst(Gen.kWord, hi - lo);
1488+ Gen.jumpCmp(Scan.sLeq, false, body);
1489+end;
1490+
1491+(* A for loop's variable o, stepped by step, wrapping as its type does *)
1492+proc forStep*(o: ^Sym.Obj; step: I64): ERROR;
1493+var v, w: Item;
1494+begin
1495+ try makeItem(v, o);
1496+ if v.base = Gen.bReg then
1497+ (* a variable in a register is stepped in it *)
1498+ Gen.pushConst(Gen.kWord, step);
1499+ Gen.incDecReg(v.chunk, intSize(o^.typ), signed(o^.typ), false);
1500+ return nil;
1501+ end;
1502+ try makeItem(w, o);
1503+ try value(w);
1504+ Gen.pushConst(Gen.kWord, step);
1505+ Gen.op(Scan.sPlus, Gen.kWord, intSize(o^.typ), signed(o^.typ));
1506+ return assign(v, w);
1507+end;
1508+
1509+(* For a for loop: pushes the variable o and the limit lim, a constant or
1510+ the slot it was put in, and jumps to L if the one is op the other, as
1511+ the type of o compares *)
1512+proc forCmp*(o: ^Sym.Obj; lim: Item; op: Scan.Sym; var L: INT): ERROR;
1513+var v, b: Item;
1514+begin
1515+ try makeItem(v, o);
1516+ try value(v);
1517+ b := lim;
1518+ try value(b);
1519+ Gen.jumpCmp(op, o^.typ^.signed, L);
1520+ return nil;
1521+end;
1522+
1523+(* The end of a round of a for loop, for a positive step s, as the report
1524+ has it: if v <= b and b - v < s, the loop ends; otherwise v becomes
1525+ v + s and the loop goes on while v <= b. Counting the distance left,
1526+ rather than comparing after the step, can't be fooled by v wrapping
1527+ around. A negative step is the same the other way round: before, past
1528+ and within are chosen by up, whether the step is positive.
1529+ For a step of 1: v < b goes on to top, where v is stepped; v = b
1530+ ends; otherwise the body moved v past b.
1531+ For another step: v past b goes to past; else b - v (unsigned, as
1532+ v <= b) >= |step| goes on to top, and else the loop ends.
1533+ Past: v is stepped here and tested, going to body if within b. *)
1534+proc forNext*(o: ^Sym.Obj; lim: Item; step: I64; var exitL: INT; top, body: INT): ERROR;
1535+var v, b: Item; L, pastL: INT; up: BOOL; before, past, within: Scan.Sym; a: I64;
1536+begin
1537+ up := step > 0;
1538+ (* by a negative step, by a positive *)
1539+ if up then before := Scan.sLss; past := Scan.sGtr; within := Scan.sLeq;
1540+ else before := Scan.sGtr; past := Scan.sLss; within := Scan.sGeq; end;
1541+ a := step;
1542+ if a < 0 then a := -a; end;
1543+ L := Gen.NoLabel;
1544+ pastL := Gen.NoLabel;
1545+ if a = 1 then
1546+ try forCmp(o, lim, before, L);
1547+ Gen.fixTo(L, top);
1548+ try forCmp(o, lim, Scan.sEql, exitL);
1549+ else
1550+ try forCmp(o, lim, past, pastL);
1551+ try makeItem(v, o);
1552+ b := lim;
1553+ if up then try value(b); try value(v);
1554+ else try value(v); try value(b); end;
1555+ Gen.op(Scan.sMinus, Gen.kWord, 8, false);
1556+ Gen.pushConst(Gen.kWord, a);
1557+ Gen.jumpCmp(Scan.sGeq, false, L);
1558+ Gen.fixTo(L, top);
1559+ Gen.jump(exitL);
1560+ end;
1561+ Gen.fix(pastL);
1562+ try forStep(o, step);
1563+ L := Gen.NoLabel;
1564+ try forCmp(o, lim, within, L);
1565+ Gen.fixTo(L, body);
1566+ return nil;
1567+end;
1568+
1569+(* Jumps to L if the condition x is false. The jumps waiting in x.fj join
1570+ L; those in x.tj are placed here, as x is true past this. *)
1571+proc condJump*(var x: Item; var L: INT): ERROR;
1572+begin
1573+ if x.typ^.form # Sym.fBool then
1574+ return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x)));
1575+ end;
1576+ if x.mode = mCond then
1577+ Gen.jumpCmp(negated(x.rel), x.relSigned, L);
1578+ L := Gen.joinJumps(L, x.fj);
1579+ Gen.fix(x.tj);
1580+ return nil;
1581+ end;
1582+ try value(x);
1583+ Gen.jumpIf(L, false);
1584+ return nil;
1585+end;
1586+
1587+(* As condJump, but the jump to L is taken where the condition is true;
1588+ x.tj joins L and x.fj is placed here *)
1589+proc condJumpTrue*(var x: Item; var L: INT): ERROR;
1590+begin
1591+ if x.typ^.form # Sym.fBool then
1592+ return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x)));
1593+ end;
1594+ if x.mode = mCond then
1595+ Gen.jumpCmp(x.rel, x.relSigned, L);
1596+ L := Gen.joinJumps(L, x.tj);
1597+ Gen.fix(x.fj);
1598+ return nil;
1599+ end;
1600+ try value(x);
1601+ Gen.jumpIf(L, true);
1602+ return nil;
1603+end;
1604+
1605+(* Procedures *)
1606+
1607+proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj);
1608+begin
1609+ result := sig^.base;
1610+ Gen.beginProc(sig, params);
1611+end;
1612+
1613+(* The result of return x: a value on top, a slice's two words on top,
1614+ or one copied behind the hidden pointer *)
1615+proc returnValue*(var x: Item): ERROR;
1616+begin
1617+ if result = nil then return Scan.markAt(x.pos, "this procedure returns nothing"); end;
1618+ try coerce(x, result);
1619+ if Sym.inTwoRegs(result) then try pushWords(x);
1620+ elsif Sym.isAggregate(result) then
1621+ if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
1622+ try address(x);
1623+ Gen.copyResult(0, result^.size);
1624+ else try value(x); end;
1625+ return nil;
1626+end;
1627+
1628+(* One of several results: of two words, a value left on top for
1629+ returnJump to put in rax or rdx; else into its place behind the
1630+ hidden pointer. *)
1631+proc returnField*(f: ^Sym.Obj; var x: Item): ERROR;
1632+begin
1633+ try coerce(x, f^.typ);
1634+ if Sym.inTwoRegs(result) then try value(x);
1635+ elsif Sym.isScalar(f^.typ) then
1636+ try value(x);
1637+ Gen.resultTo(f^.val, scalarSize(f^.typ));
1638+ else
1639+ if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
1640+ try address(x);
1641+ Gen.copyResult(f^.val, f^.typ^.size);
1642+ end;
1643+ return nil;
1644+end;
1645+
1646+(* Several results at once, the call's that return f(x) passes on. *)
1647+proc returnAll*(var x: Item): ERROR;
1648+begin
1649+ if Sym.inTwoRegs(result) then try pushWords(x);
1650+ else
1651+ try address(x);
1652+ Gen.copyResult(0, result^.size);
1653+ end;
1654+ return nil;
1655+end;
1656+
1657+proc returnNone*: ERROR;
1658+begin
1659+ if result # nil then
1660+ return Scan.mark(say1("return needs a result of {}", Sym.typeName(result)));
1661+ end;
1662+ Gen.returnJump();
1663+ return nil;
1664+end;
1665+
1666+(* Keeps a variable's address in a frame slot, rather than on the stack,
1667+ while other code runs. *)
1668+proc pin*(var x: Item): ERROR;
1669+var s: I64;
1670+begin
1671+ if (x.mode = mVar) and (x.base = Gen.bStack) then
1672+ try address(x);
1673+ s := Gen.allocTemp(8, 8);
1674+ Gen.popVar(frameAdr(s), 8);
1675+ x.base := Gen.bSlot;
1676+ x.chunk := INT(s);
1677+ end;
1678+ return nil;
1679+end;
1680+
1681+(* INC(v, k) or DEC: v's address is on the stack, from address. *)
1682+proc incDec*(var v, k: Item; dec: BOOL): ERROR;
1683+begin
1684+ try coerceExact(k, v.typ, "");
1685+ try value(k);
1686+ if v.base = Gen.bReg then Gen.incDecReg(v.chunk, scalarSize(v.typ), v.typ^.signed, dec);
1687+ else Gen.incDec(scalarSize(v.typ), v.typ^.signed, dec); end;
1688+ return nil;
1689+end;
1690+
1691+(* COPY(d, s): d, an array variable or a slice, as a slice in the frame,
1692+ before s is read *)
1693+proc copyDest*(var d: Item): ERROR;
1694+begin
1695+ if not isSeq(d.typ) or (d.mode = mStr) or ((d.typ^.form = Sym.fArray) and ((d.mode # mVar) or not d.isVar)) then
1696+ return Scan.markAt(d.pos, say1("COPY copies into an array variable or a slice, found {}", what(d)));
1697+ end;
1698+ if d.typ^.form = Sym.fArray then try notReadOnly(d); end;
1699+ return seqSlice(d);
1700+end;
1701+
1702+(* ... and the elements of s copied to its start *)
1703+proc copyFrom*(var d, s: Item): ERROR;
1704+begin
1705+ if not isSeq(s.typ) or not Sym.same(elemOf(s.typ), d.typ^.base) then
1706+ return Scan.markAt(s.pos, say2("COPY copies elements of {}, found {}", Sym.typeName(d.typ^.base), what(s)));
1707+ end;
1708+ try seqSlice(s);
1709+ Gen.copySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos);
1710+ return nil;
1711+end;
1712+
1713+(* An error is the address of its length, followed by its message. *)
1714+proc errorChunk*(var x: Item; home, name: INT): (INT, ERROR);
1715+var c, xs, xl: INT; p: ^U8; q: ^I64;
1716+begin
1717+ if x.mode # mStr then return 0, Scan.markAt(x.pos, "an error is made from a string"); end;
1718+ xl := INT(x.val);
1719+ p := Scan.grab(xl + 8);
1720+ q := ^I64(p);
1721+ q^ := x.val;
1722+ xs := Chunk.chunks[x.chunk].start;
1723+ COPY(p[8..8 + xl], Chunk.rodata[xs..xs + xl]);
1724+ c := Chunk.newChunk(Chunk.secRodata, home, name);
1725+ Chunk.setData(c, p, xl + 8, 8);
1726+ return c, nil;
1727+end;
1728+
1729+proc msg*(var x: Item): ERROR;
1730+var s: I64;
1731+begin
1732+ try coerce(x, Sym.tError);
1733+ try value(x);
1734+ s := Gen.allocTemp(16, 8);
1735+ Gen.errorText(s);
1736+ tempItem(x, Sym.tBytes, s);
1737+ return nil;
1738+end;
1739+
1740+end Item.

self/README.md modified +34 -0

@@ -28,6 +28,16 @@
2828 with every kind of expression, statement, call, check, frame and defer,
2929 and the entry point, static and dynamic: the bytes, fixups, line notes
3030 and listing must be the same.
31+`Item` is tested by `test/ItemDump`, a script of operands and operations
32+with mistakes among them (a constant, a variable in the frame, a
33+register, a slot, another module's or C's, a string, a procedure, a
34+selector through a pointer, a field, an element or a slice, a call, a
35+`match`, a `for`, `return`, `COPY`, a variant): each step shows what
36+it gave, or its message, and goes on, as the parser does after an
37+error. What each step gave, the messages, and the bytes, fixups, line
38+notes and listing of the code must be the same, over 60 scripts (a
39+run ends at its 20th error, as a compile does). The text its messages
40+point into is `test/ItemDump.txt`.
3141
3242 `check.sh` builds a dumper for each side, `test/ScanDump.pas` over the
3343 seed's units and `test/ScanDump.raz` over these, and has both read the
@@ -98,6 +108,30 @@
98108 `Link`. A `match` on an enumeration takes one name to an arm, and a
99109 set holds at most 64 names, so `Scan.Sym` (over 64) has none: the
100110 seed's sets of its names are chains of `=`.
111+- **`Item`.** The seed's `Mark` ended in a jump, so here every
112+ routine that can find an error returns an `ERROR` as its last result
113+ and the ones that call it pass it up with `try`; `Item` shows the
114+ message and returns what the seed jumped out of, so a script that
115+ goes on after an error sees the same state. The seed's `Mismatch` of
116+ two operands is `mismatchOps`, `demoted` and `checks` have setters,
117+ and `matchBegin`, `toSlot` and `errorChunk` return their value and
118+ the error. `op2` has a parameter it never read, now `_L`. A message
119+ is made by `Diag.say` from strings, with no `shortstring` to add up.
120+ A `Mark` with no place is at the scanner's, as in the seed.
121+- **No `const` parameter.** The seed's `const x: TItem` is a value
122+ parameter here, so an item of about 130 bytes is copied at each call
123+ of `what`, `adrOf`, `notValue` and the others. The result is the
124+ same; whether the compiler built from this is slower for it is for
125+ the speed test of step 4 to say. A `const` parameter (a hint that
126+ the callee won't change it, so that the caller may pass its address)
127+ would be a language change: it goes on the wish list.
128+- **Sets of `Scan.Sym`.** The operators a rule names are chains of `=`
129+ or the helpers `oneOf` and `isRel`; the arms of a `match` on them
130+ take one name each, so those with two names call a procedure of
131+ their own (`foldDiv`, `setSubset`).
132+- **Strings made by the compiler.** A joined string (`"a" + "b"`) and
133+ an error's text are built in memory from `Scan.grab`, which is never
134+ freed, in place of `GetMem` and `FreeMem`; the compiler runs once.
101135 - **No bit cast.** A real's bits and back go through a pointer.
102136 - **Speed.** On the 348,025 lines of `test/genbench.py`, 7.6 MB, the
103137 seed's scanner takes 75 ms and this one 74. It took 121 at first.

self/check.sh modified +19 -0

@@ -104,3 +104,22 @@
104104 cmp $b/gen.seed $b/gen.self
105105 done
106106 echo "gen ok"
107+
108+# Item: operands and operations driven by a script with mistakes in it,
109+# which show their messages and go on; what each step gave, the code
110+# made and the messages must be the same. A run ends at the 20th error,
111+# as a compile does, so the script changes with each argument.
112+fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/itemdump.seed self/test/ItemDump.pas >/dev/null
113+./raz -Werror -I self -o $b/itemdump.self self/test/ItemDump.raz
114+n=0; bad=0
115+for a in $(seq 0 59); do
116+ s1=0; s2=0
117+ $b/itemdump.seed $a >$b/seed.out 2>$b/seed.err || s1=$?
118+ $b/itemdump.self $a >$b/self.out 2>$b/self.err || s2=$?
119+ n=$((n + 1))
120+ if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then
121+ echo "differs: item script $a (status $s1 and $s2)"; bad=$((bad + 1))
122+ fi
123+done
124+echo "item: $n scripts, $bad differ"
125+test $bad = 0

self/test/ItemDump.pas added +665 -0

@@ -0,0 +1,665 @@
1+{ Drives item with a fixed pseudo-random script of operands and
2+ operations, with mistakes among them, and prints what each step gave
3+ (the item, or that it failed, whose message goes to standard error),
4+ then the bytes, fixups, line notes and listing (raz -S) of the code
5+ it made: the seed's side of a test of self/Item.raz, whose
6+ ItemDump.raz does and prints the same. The argument, a number,
7+ changes the script. A run ends at the 20th error, as a compile does,
8+ so several scripts are run. }
9+program itemdump;
10+{$mode objfpc}{$H-}
11+uses diag, scan, sym, chunk, x64, gen, item;
12+
13+const
14+ FirstProc = 3;
15+ NumProcs = 30;
16+ FirstGlob = FirstProc + NumProcs;
17+ NumGlobs = 4;
18+ Steps = 14;
19+ YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7;
20+ YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14;
21+ YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20;
22+ YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25;
23+ YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29;
24+ NumT = 30;
25+ IntTypes: array[0..7] of longint = (YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8);
26+ Ops: array[0..19] of TSym = (sPlus, sMinus, sTimes, sDiv, sMod,
27+ sAmp, sBar, sXor, sShl, sShr,
28+ sEql, sNeq, sLss, sLeq, sGtr, sGeq,
29+ sSlash, sIn, sPlus, sMinus);
30+ Cmps: array[0..5] of TSym = (sEql, sNeq, sLss, sLeq, sGtr, sGeq);
31+
32+var
33+ Letters: string[9];
34+ seed: int64;
35+ ty: array[0..NumT - 1] of PType;
36+ vars: array[0..NumT - 1] of PObj;
37+ procs: array[0..5] of PObj;
38+ strs: array[0..2] of PObj;
39+ arrConst, typeObj, builtinObj, caseObj: PObj;
40+ mod0, mod1: PModule;
41+ tuple2, record3, packedR, variantT: PType;
42+ results: array[0..8] of PType;
43+ curRes: longint;
44+ call: TCall;
45+ jb: jmp_buf;
46+ gK: longint;
47+ gX: TItem;
48+ gOk: boolean;
49+
50+function Rnd(n: longint): longint;
51+begin
52+ seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
53+ Rnd := (seed shr 8) mod n;
54+end;
55+
56+function Flag: boolean;
57+begin
58+ Flag := Rnd(2) = 0;
59+end;
60+
61+function Bit(f: boolean): longint;
62+begin
63+ if f then Bit := 1 else Bit := 0;
64+end;
65+
66+function Pos: TPos;
67+var p: TPos;
68+begin
69+ p.f := 0; p.a := Rnd(400); p.b := p.a + 1 + Rnd(12);
70+ Pos := p;
71+end;
72+
73+function ConstVal: int64;
74+var x: longint; r: int64;
75+begin
76+ x := Rnd(1 shl 30);
77+ case Rnd(7) of
78+ 0: r := x mod 10;
79+ 1: r := -(x mod 100);
80+ 2: r := int64(1) shl (x mod 20);
81+ 3: r := x;
82+ 4: r := int64(x) * 4096 * 4096 * 9 - 7;
83+ 5: r := -int64(x) * 8;
84+ else r := x mod 1000 - 500;
85+ end;
86+ ConstVal := r;
87+end;
88+
89+function InternStr(const s: shortstring): longint;
90+begin
91+ InternStr := Intern(@s[1], length(s));
92+end;
93+
94+{ A name v00, v01, ... , interned }
95+function NameOf(i: longint): longint;
96+var s: string[3];
97+begin
98+ s := 'v' + chr(48 + i div 10) + chr(48 + i mod 10);
99+ NameOf := Intern(@s[1], 3);
100+end;
101+
102+function NewObjs(cls: TClass; t: PType; n: longint; step: int64; at: longint): PObj;
103+var first, o, last: PObj; i: longint;
104+begin
105+ first := nil; last := nil;
106+ for i := 0 to n - 1 do begin
107+ o := NewObj(cls, NameOf(at + i), t);
108+ o^.val := step * i;
109+ if last = nil then first := o else last^.next := o;
110+ last := o;
111+ end;
112+ NewObjs := first;
113+end;
114+
115+function ProcType(res: PType; params: PObj; n: longint): PType;
116+var t: PType;
117+begin
118+ t := NewType(fProc, 8, 8);
119+ t^.base := res;
120+ t^.fields := params;
121+ t^.len := n;
122+ ProcType := t;
123+end;
124+
125+function Param(t: PType; isVar: boolean; at: longint): PObj;
126+var o: PObj;
127+begin
128+ o := NewObj(oVar, NameOf(at), t);
129+ o^.param := true;
130+ o^.isVar := isVar;
131+ Param := o;
132+end;
133+
134+procedure MakeTypes;
135+var t: PType; p, q, r: PObj; i: longint;
136+begin
137+ ty[YInt] := tInt; ty[YI64] := tI64; ty[YI32] := tI32; ty[YU8] := tU8;
138+ ty[YU16] := tU16; ty[YU32] := tU32; ty[YU64] := tU64; ty[YBool] := tBool;
139+ ty[YReal] := tReal; ty[YF32] := tF32; ty[YI8] := tI8; ty[YErr] := tError;
140+ ty[YBytes] := tBytes;
141+ t := NewType(fEnum, 1, 1); t^.len := 5; ty[YEnum] := t;
142+ t := NewType(fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t;
143+ t := NewType(fPtr, 8, 8); t^.base := tI64; ty[YPtr] := t;
144+ t := NewType(fPtr, 8, 8); t^.base := tI64; t^.vol := true; ty[YVptr] := t;
145+ t := NewType(fArray, 48, 8); t^.base := tI64; t^.len := 6; ty[YArr] := t;
146+ t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t;
147+ t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t;
148+ t := NewType(fArray, 8, 1); t^.base := tU8; t^.len := 8; ty[YArrU8] := t;
149+ t := NewType(fSlice, 16, 8); t^.base := tI64; ty[YSlice] := t;
150+ record3 := NewType(fRecord, 24, 8);
151+ p := NewObj(oField, NameOf(40), tI64); p^.val := 0;
152+ q := NewObj(oField, NameOf(41), tReal); q^.val := 8; p^.next := q;
153+ r := NewObj(oField, NameOf(42), tI32); r^.val := 16; q^.next := r;
154+ record3^.fields := p;
155+ ty[YRec] := record3;
156+ t := NewType(fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t;
157+ t := NewType(fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t;
158+ packedR := NewType(fRecord, 53, 1);
159+ packedR^.packd := true;
160+ p := NewObj(oField, NameOf(43), tU8); p^.val := 0;
161+ q := NewObj(oField, NameOf(44), tI32); q^.val := 1; p^.next := q;
162+ r := NewObj(oField, NameOf(46), ty[YArr]); r^.val := 5; q^.next := r;
163+ packedR^.fields := p;
164+ ty[YPacked] := packedR;
165+ variantT := NewType(fVariant, 16, 8);
166+ ty[YVariant] := variantT;
167+ tuple2 := NewType(fRecord, 16, 8);
168+ tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := NewObjs(oVar, tInt, 2, 8, 45);
169+ p := Param(tInt, false, 46); p^.next := Param(tReal, false, 47);
170+ ty[YProc0] := ProcType(tInt, p, 2);
171+ ty[YProc1] := ProcType(nil, nil, 0);
172+ p := Param(tI64, true, 48); p^.next := Param(ty[YSlice], false, 49);
173+ ty[YProc2] := ProcType(tuple2, p, 2);
174+ results[0] := nil; results[1] := tInt; results[2] := tReal; results[3] := ty[YSlice];
175+ results[4] := tuple2; results[5] := record3; results[6] := tF32; results[7] := tI16;
176+ results[8] := ty[YBytes];
177+ for i := 0 to NumT - 1 do
178+ if ty[i] = nil then Fatal('a type is missing');
179+end;
180+
181+procedure MakeObjs;
182+var i, c: longint; o: PObj;
183+begin
184+ New(mod0); mod0^.name := InternStr('Zero');
185+ New(mod1); mod1^.name := InternStr('Other');
186+ curModule := mod0;
187+ for i := 0 to 5 do begin
188+ o := NewObj(oProc, NameOf(50 + i), ty[YProc0 + i mod 3]);
189+ o^.chunk := FirstProc + Rnd(NumProcs);
190+ o^.ext := i >= 4;
191+ o^.isCode := i = 3;
192+ procs[i] := o;
193+ end;
194+ for i := 0 to 2 do begin
195+ o := NewObj(oConst, NameOf(60 + i), tStr);
196+ o^.val := 2 + 3 * i;
197+ c := NewChunk(secRodata, -1, -1);
198+ SetData(c, @Letters[1], o^.val + 1, 1);
199+ o^.chunk := c;
200+ strs[i] := o;
201+ end;
202+ arrConst := NewObj(oConst, NameOf(63), ty[YArr]);
203+ arrConst^.chunk := NewChunk(secRodata, -1, -1);
204+ SetData(arrConst^.chunk, @Letters[1], 8, 8);
205+ typeObj := NewObj(oType, NameOf(64), ty[YRec]);
206+ builtinObj := NewObj(oBuiltin, NameOf(65), tNone);
207+ caseObj := NewObj(oCase, NameOf(66), variantT);
208+ caseObj^.val := 3;
209+ caseObj^.fields := NewObjs(oField, tInt, 2, 8, 67);
210+ caseObj^.fields^.val := 8;
211+end;
212+
213+procedure MakeVars;
214+var i, k: longint; o: PObj; t: PType;
215+begin
216+ for i := 0 to NumT - 1 do begin
217+ t := ty[i];
218+ o := NewObj(oVar, NameOf(i), t);
219+ o^.lev := 1;
220+ k := Rnd(9);
221+ if k = 2 then begin
222+ o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs);
223+ end else if k = 3 then begin
224+ o^.ind := true; o^.val := AllocPerm(8, 8); o^.off := 8 * Rnd(3);
225+ end else if k = 4 then begin
226+ if (t^.form in [fInt, fPtr]) and (t^.size = 8) then
227+ o^.reg := VarRegs[Rnd(5)]
228+ else if t^.form = fReal then
229+ o^.reg := XVarRegs[Rnd(4)]
230+ else if t^.form = fSlice then begin
231+ o^.reg := VarRegs[Rnd(3)]; o^.reg2 := VarRegs[3 + Rnd(2)];
232+ end;
233+ if o^.reg = 0 then o^.val := AllocPerm(t^.size, 8);
234+ end else if k = 5 then begin
235+ o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.module := mod1;
236+ end else if k = 6 then begin
237+ o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.ext := true;
238+ end else
239+ o^.val := AllocPerm(t^.size + 8, 8);
240+ vars[i] := o;
241+ end;
242+end;
243+
244+{ Operands }
245+
246+function IntType: PType;
247+begin
248+ IntType := ty[IntTypes[Rnd(8)]];
249+end;
250+
251+procedure VarItem(var x: TItem; t: PType);
252+var i, k: longint;
253+begin
254+ k := Rnd(NumT);
255+ for i := 0 to NumT - 1 do
256+ if ty[i] = t then k := i;
257+ FillChar(x, SizeOf(x), 0);
258+ x.pos := Pos;
259+ MakeItem(x, vars[k]);
260+end;
261+
262+procedure Operand(var x: TItem; t: PType);
263+var k: longint; r: double; v: int64;
264+begin
265+ FillChar(x, SizeOf(x), 0);
266+ x.pos := Pos;
267+ if t = nil then begin
268+ case Rnd(14) of
269+ 0: MakeConst(x, tConst, ConstVal);
270+ 1: MakeConst(x, tConst, ConstVal mod 200);
271+ 2: begin t := IntType; v := ConstVal mod 100; MakeConst(x, t, v) end;
272+ 3: begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r) end;
273+ 4: MakeConst(x, tBool, Rnd(2));
274+ 5: MakeItem(x, strs[Rnd(3)]);
275+ 6: MakeConst(x, tNil, 0);
276+ 7: MakeItem(x, procs[Rnd(6)]);
277+ 8: begin
278+ if Rnd(4) = 0 then begin
279+ case Rnd(3) of
280+ 0: MakeItem(x, typeObj);
281+ 1: MakeItem(x, builtinObj);
282+ else MakeItem(x, caseObj);
283+ end;
284+ end else
285+ MakeItem(x, arrConst);
286+ end;
287+ 13: begin MakeItem(x, vars[Rnd(NumT)]); Value(x) end;
288+ else VarItem(x, ty[Rnd(NumT)]);
289+ end;
290+ exit;
291+ end;
292+ k := Rnd(10);
293+ if IsInt(t) then begin
294+ if k < 3 then begin MakeConst(x, tConst, ConstVal mod 100); exit end;
295+ if k = 3 then begin MakeConst(x, t, ConstVal mod 100); exit end;
296+ end else if t^.form = fReal then begin
297+ if k < 3 then begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r); exit end;
298+ end else if t^.form = fBool then begin
299+ if k < 3 then begin MakeConst(x, tBool, Rnd(2)); exit end;
300+ end else if t^.form = fPtr then begin
301+ if k < 2 then begin MakeConst(x, tNil, 0); exit end;
302+ end else if (t^.form = fSlice) and (t^.base = tU8) then begin
303+ if k < 3 then begin MakeItem(x, strs[Rnd(3)]); exit end;
304+ end;
305+ VarItem(x, t);
306+end;
307+
308+procedure CondItem(var x: TItem);
309+var y: TItem; L: longint; op: TSym; t: PType;
310+begin
311+ t := IntType;
312+ op := Cmps[Rnd(6)];
313+ Operand(x, t);
314+ Op1(op, x, L);
315+ Operand(y, t);
316+ Op2(op, x, y, L);
317+end;
318+
319+procedure Place(var x: TItem);
320+var i, k: longint; f: PObj; y, lo, hi: TItem;
321+begin
322+ VarItem(x, ty[Rnd(NumT)]);
323+ for i := 1 to 3 do begin
324+ if Rnd(3) <> 0 then begin
325+ k := Rnd(6);
326+ if (k = 0) or (x.typ^.form = fPtr) then
327+ Deref(x)
328+ else if x.typ^.form = fRecord then begin
329+ f := x.typ^.fields;
330+ k := Rnd(3);
331+ while (k > 0) and (f^.next <> nil) do begin f := f^.next; dec(k) end;
332+ Field(x, f);
333+ end else if x.typ^.form in [fArray, fSlice, fStr] then begin
334+ IndexPrep(x);
335+ if k < 4 then begin
336+ Operand(y, IntType);
337+ Index(x, y);
338+ end else begin
339+ Operand(lo, IntType);
340+ SliceLo(lo);
341+ Operand(hi, IntType);
342+ Slice(x, lo, hi);
343+ end;
344+ end;
345+ end;
346+ end;
347+end;
348+
349+procedure Dump(var x: TItem);
350+var name: shortstring; flags: longint;
351+begin
352+ name := '-';
353+ if x.typ <> nil then name := TypeName(x.typ);
354+ flags := Bit(x.vol) + 2 * Bit(x.isVar) + 4 * Bit(x.odd) + 8 * Bit(x.ro) + 16 * Bit(x.deref);
355+ write('I ', ord(x.mode), ' ', name, ' ', ord(x.rel), ' ', Bit(x.relSigned), ' ', x.fj, ' ', x.tj, ' ', x.val);
356+ writeln(' ', ord(x.base), ' ', x.chunk, ' ', x.off, ' ', flags, ' depth ', depth, ' pushed ', pushed);
357+end;
358+
359+procedure DoCall(var x: TItem);
360+var f, a: TItem; p: PObj; n: longint;
361+begin
362+ FillChar(f, SizeOf(f), 0);
363+ f.pos := Pos;
364+ if Rnd(5) = 0 then MakeItem(f, vars[YProc0 + Rnd(3)])
365+ else MakeItem(f, procs[Rnd(6)]);
366+ BeginCall(call, f);
367+ p := call.param;
368+ n := Rnd(4) - 1;
369+ while (p <> nil) or (n > 0) do begin
370+ if p <> nil then begin
371+ if p^.isVar and (Rnd(2) = 0) then begin
372+ VarItem(a, ty[YVptr]);
373+ Deref(a);
374+ end else if Rnd(6) = 0 then Operand(a, nil)
375+ else Operand(a, p^.typ);
376+ p := p^.next;
377+ end else begin
378+ Operand(a, nil);
379+ n := n - 1;
380+ end;
381+ PassArg(call, a);
382+ if (p = nil) and (n < 0) then n := 0;
383+ if (p <> nil) and (n < 0) and (Rnd(4) = 0) then begin p := nil; n := 0 end;
384+ end;
385+ EndCall(call, x);
386+end;
387+
388+procedure Binary(var x: TItem);
389+var y: TItem; L, M: longint; op: TSym; t: PType;
390+begin
391+ L := NoLabel;
392+ M := NoLabel;
393+ op := Ops[Rnd(20)];
394+ case Rnd(8) of
395+ 0, 1: t := IntType;
396+ 2: t := ty[YReal + Rnd(2)];
397+ 3: t := ty[YBool];
398+ 4: t := ty[YEnum + Rnd(2)];
399+ else t := ty[Rnd(NumT)];
400+ end;
401+ if Rnd(6) = 0 then begin
402+ if Flag then op := sAnd else op := sOr;
403+ CondItem(x);
404+ Op1(op, x, L);
405+ CondItem(y);
406+ end else if op = sIn then begin
407+ Operand(x, ty[YEnum]);
408+ Op1(op, x, L);
409+ Operand(y, ty[YSet]);
410+ end else begin
411+ Operand(x, t);
412+ Op1(op, x, L);
413+ if Rnd(5) = 0 then Operand(y, nil) else Operand(y, t);
414+ end;
415+ Op2(op, x, y, L);
416+ if (x.mode = mCond) and (Rnd(3) <> 0) then begin
417+ if Flag then CondJump(x, M) else CondJumpTrue(x, M);
418+ Fix(M);
419+ x.mode := mNone;
420+ end;
421+end;
422+
423+procedure Unary(var x: TItem);
424+begin
425+ Operand(x, nil);
426+ case Rnd(3) of
427+ 0: Neg(x);
428+ 1: NotOp(x);
429+ else Complement(x);
430+ end;
431+end;
432+
433+procedure DoMatch(var x: TItem);
434+var p, lo, hi: int64; L: longint;
435+begin
436+ L := NoLabel;
437+ case Rnd(3) of
438+ 0: VarItem(x, ty[YVariant]);
439+ 1: VarItem(x, ty[YEnum]);
440+ else Operand(x, nil);
441+ end;
442+ p := MatchBegin(x);
443+ MatchTag(p, ConstVal mod 10, L);
444+ lo := ConstVal mod 10;
445+ hi := ConstVal mod 10 + 10;
446+ MatchRange(p, lo, hi, L);
447+ MatchRange(p, 3, 3, L);
448+ Fix(L);
449+end;
450+
451+procedure DoFor(var x: TItem);
452+var o: PObj; lim: TItem; step: int64; exitL: longint;
453+begin
454+ o := vars[IntTypes[Rnd(8)]];
455+ step := ConstVal mod 5;
456+ if step = 0 then step := 1;
457+ if Rnd(2) = 0 then step := -step;
458+ FillChar(lim, SizeOf(lim), 0);
459+ lim.pos := Pos;
460+ MakeConst(lim, o^.typ, ConstVal mod 50);
461+ exitL := NoLabel;
462+ ForStep(o, step);
463+ ForNext(o, lim, step, exitL, pc, pc);
464+ Fix(exitL);
465+ x := lim;
466+end;
467+
468+procedure DoMisc(var x: TItem);
469+var y: TItem;
470+begin
471+ case Rnd(5) of
472+ 0: begin
473+ Place(x);
474+ Address(x);
475+ Operand(y, x.typ);
476+ IncDec(x, y, Flag);
477+ end;
478+ 1: begin
479+ Place(x);
480+ Pin(x);
481+ end;
482+ 2: begin
483+ Place(x);
484+ CopyDest(x);
485+ Place(y);
486+ CopyFrom(x, y);
487+ end;
488+ 3: begin
489+ Operand(x, nil);
490+ MakeStr(y);
491+ Coerce(y, ty[YBytes]);
492+ end;
493+ else begin
494+ Operand(x, nil);
495+ NilTest(x);
496+ UsesReals(x.pos);
497+ Discard(x);
498+ end;
499+ end;
500+end;
501+
502+procedure DoTemp(var x: TItem);
503+var a: TItem; c, h, n: longint; f: PObj;
504+begin
505+ FillChar(x, SizeOf(x), 0);
506+ x.pos := Pos;
507+ case Rnd(5) of
508+ 0: ZeroTemp(x, ty[YVariant]);
509+ 1: begin
510+ Construct(x, caseObj);
511+ f := caseObj^.fields;
512+ Operand(a, f^.typ);
513+ SetField(x, f, a);
514+ end;
515+ 2: begin
516+ ZeroTemp(x, ty[YRec]);
517+ f := ty[YRec]^.fields;
518+ if Flag then f := f^.next;
519+ Operand(a, f^.typ);
520+ SetField(x, f, a);
521+ end;
522+ 3: begin
523+ Operand(a, nil);
524+ h := Rnd(3) - 1;
525+ n := Rnd(3) - 1;
526+ c := ErrorChunk(a, h, n);
527+ MakeConst(x, tError, int64(c) + 1);
528+ end;
529+ else begin
530+ Operand(x, ty[YErr]);
531+ Msg(x);
532+ end;
533+ end;
534+end;
535+
536+procedure DoReturn(var x: TItem);
537+var f: PObj;
538+begin
539+ if (curRes = 4) and Flag then begin
540+ f := tuple2^.fields;
541+ if Flag then f := f^.next;
542+ if Flag then begin
543+ Operand(x, f^.typ);
544+ ReturnField(f, x);
545+ exit;
546+ end;
547+ DoCall(x);
548+ ReturnAll(x);
549+ exit;
550+ end;
551+ if Rnd(4) = 0 then begin ReturnNone; exit end;
552+ Operand(x, results[curRes]);
553+ ReturnValue(x);
554+end;
555+
556+procedure Step(k: longint; var x: TItem);
557+var y: TItem;
558+begin
559+ FillChar(x, SizeOf(x), 0);
560+ case k of
561+ 0: begin Operand(x, nil); Value(x) end;
562+ 1: begin Operand(x, nil); Address(x) end;
563+ 2: begin Operand(x, nil); Coerce(x, ty[Rnd(NumT)]) end;
564+ 3: begin Operand(x, nil); CoerceExact(x, IntType, '') end;
565+ 4: begin
566+ Place(x);
567+ Operand(y, x.typ);
568+ Assign(x, y);
569+ end;
570+ 5: Unary(x);
571+ 6: Binary(x);
572+ 7: begin Operand(x, nil); Convert(x, ty[Rnd(NumT)]) end;
573+ 8: Place(x);
574+ 9: DoCall(x);
575+ 10: DoMatch(x);
576+ 11: DoFor(x);
577+ 12: DoMisc(x);
578+ 13: DoTemp(x);
579+ 14: DoReturn(x);
580+ else Binary(x);
581+ end;
582+end;
583+
584+{ A step, and what it leaves, each a recovery point as the parser's
585+ statements are }
586+procedure RunStep;
587+begin
588+ gOk := false;
589+ recovery := @jb;
590+ if setjmp(jb) = 0 then begin
591+ Step(gK, gX);
592+ gOk := true;
593+ end;
594+ recovery := nil;
595+end;
596+
597+procedure RunDiscard;
598+begin
599+ recovery := @jb;
600+ if setjmp(jb) = 0 then Discard(gX);
601+ recovery := nil;
602+end;
603+
604+procedure GenProc(c: longint);
605+var sig: PType; i, line: longint;
606+begin
607+ curRes := Rnd(9);
608+ sig := ProcType(results[curRes], nil, 0);
609+ BeginProc(sig, nil);
610+ for i := 0 to 5 do AllocPerm(8, 8);
611+ MakeVars;
612+ checks := Flag;
613+ line := 1 + Rnd(40);
614+ EnterBody(c, line);
615+ for i := 1 to Steps do begin
616+ if errors >= 19 then break;
617+ gK := Rnd(17);
618+ demoted := false;
619+ RunStep;
620+ if not gOk then
621+ writeln('S ', c, ' ', gK, ' failed')
622+ else begin
623+ writeln('S ', c, ' ', gK, ' ok');
624+ Dump(gX);
625+ if (gK < 4) or ((gK >= 5) and (gK <= 9)) then RunDiscard;
626+ end;
627+ writeln('demoted ', Bit(demoted));
628+ ResetStack(0, 0);
629+ end;
630+ EndProc(c, sig^.base <> nil);
631+end;
632+
633+function ChunkNameOf(i: longint): longint;
634+var s: string;
635+begin
636+ s := 'p' + chr(48 + i div 10) + chr(48 + i mod 10);
637+ ChunkNameOf := Intern(@s[1], 3);
638+end;
639+
640+var
641+ i, c: longint; path: string;
642+begin
643+ seed := 5;
644+ for i := 1 to length(ParamStr(1)) do seed := seed * 10 + ord(ParamStr(1)[i]) - 48;
645+ Letters := 'abcdefgh' + #0;
646+ path := 'self/test/ItemDump.txt';
647+ if Open(path) <> '' then Fatal('no file');
648+ Next;
649+ listing := true;
650+ curFile := Intern(@path[1], length(path));
651+ for i := 0 to NumProcs - 1 do begin c := NewChunk(secText, -1, ChunkNameOf(i)); chunks^[c].live := true end;
652+ for i := 0 to NumGlobs - 1 do begin
653+ c := NewChunk(secBss, -1, ChunkNameOf(NumProcs + i));
654+ SetBss(c, 64, 8);
655+ end;
656+ MakeTypes;
657+ MakeObjs;
658+ for i := 0 to NumProcs - 1 do GenProc(FirstProc + i);
659+ writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount);
660+ for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
661+ writeln;
662+ for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend);
663+ for i := 0 to numLines - 1 do writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].line, ' ', lines^[i].col);
664+ List(-1);
665+end.

self/test/ItemDump.raz added +679 -0

@@ -0,0 +1,679 @@
1+(* Drives Item with a fixed pseudo-random script of operands and
2+ operations, with mistakes among them, and prints what each step gave
3+ (the item, or that it failed, whose message goes to standard error),
4+ then the bytes, fixups, line notes and listing (raz -S) of the code
5+ it made: self/Item.raz's side of a test against the seed's,
6+ ItemDump.pas, which does and prints the same. The argument, a digit,
7+ changes the script. A run ends at the 20th error, as a compile does,
8+ so several scripts are run. *)
9+module ItemDump;
10+import Out, Fmt, Files, Heap, Diag, Scan, Sym, Chunk, X := X64, Gen, Item;
11+
12+const
13+ FirstProc = 3; (* chunks 0 to 2 are Gen's own *)
14+ NumProcs = 30;
15+ FirstGlob = FirstProc + NumProcs;
16+ NumGlobs = 4;
17+ Steps = 14;
18+ (* the types of the script, by number *)
19+ YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7;
20+ YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14;
21+ YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20;
22+ YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25;
23+ YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29;
24+ NumT = 30;
25+ IntTypes: [8]INT = [YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8];
26+ Ops: [20]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod,
27+ Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr,
28+ Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq,
29+ Scan.sSlash, Scan.sIn, Scan.sPlus, Scan.sMinus];
30+ Cmps: [6]Scan.Sym = [Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq];
31+
32+var
33+ Letters: []U8;
34+ seed: I64;
35+ ty: [NumT]^Sym.Type;
36+ vars: [NumT]^Sym.Obj; (* a variable of each type, placed anew for each procedure *)
37+ procs: [6]^Sym.Obj;
38+ strs: [3]^Sym.Obj;
39+ arrConst, typeObj, builtinObj, caseObj: ^Sym.Obj;
40+ mod0, mod1: ^Sym.Module;
41+ tuple2, record3, packedR, variantT: ^Sym.Type;
42+ results: [9]^Sym.Type;
43+ curRes: INT; (* the result of the procedure, an index of results *)
44+ call: Gen.CallInfo;
45+
46+proc rnd(n: INT): INT;
47+begin
48+ seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
49+ return INT((seed shr 8) mod I64(n));
50+end;
51+
52+proc flag: BOOL;
53+begin
54+ return rnd(2) = 0;
55+end;
56+
57+proc bit(f: BOOL): INT;
58+begin
59+ if f then return 1; end;
60+ return 0;
61+end;
62+
63+proc pos: Diag.Pos;
64+var p: Diag.Pos;
65+begin
66+ p.f := 0; p.a := rnd(400); p.b := p.a + 1 + rnd(12);
67+ return p;
68+end;
69+
70+proc constVal: I64;
71+var x: INT; r: I64;
72+begin
73+ x := rnd(1 shl 30);
74+ match rnd(7) of
75+ | 0: r := x mod 10;
76+ | 1: r := -(x mod 100);
77+ | 2: r := I64(1) shl (x mod 20);
78+ | 3: r := x;
79+ | 4: r := I64(x) * 4096 * 4096 * 9 - 7;
80+ | 5: r := -I64(x) * 8;
81+ | else: r := x mod 1000 - 500;
82+ end;
83+ return r;
84+end;
85+
86+(* A name, interned *)
87+proc intern(s: []U8): INT;
88+begin
89+ return Scan.intern(ADR(s[0]), LEN(s));
90+end;
91+
92+(* A name v00, v01, ... , interned *)
93+proc nameOf(i: INT): INT;
94+var s: [3]U8;
95+begin
96+ s[0] := 'v'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10);
97+ return Scan.intern(ADR(s[0]), 3);
98+end;
99+
100+proc newObjs(cls: Sym.Class; t: ^Sym.Type; n: INT; step: I64; at: INT): ^Sym.Obj;
101+var first, o, last: ^Sym.Obj; i: INT;
102+begin
103+ first := nil; last := nil;
104+ for i := 0 to n - 1 do
105+ o := Sym.newObj(cls, nameOf(at + i), t);
106+ o^.val := step * I64(i);
107+ if last = nil then first := o; else last^.next := o; end;
108+ last := o;
109+ end;
110+ return first;
111+end;
112+
113+proc newType(form: Sym.Form; size, align: I64): ^Sym.Type;
114+begin
115+ return Sym.newType(form, size, align);
116+end;
117+
118+proc procType(res: ^Sym.Type; params: ^Sym.Obj; n: INT): ^Sym.Type;
119+var t: ^Sym.Type;
120+begin
121+ t := newType(Sym.fProc, 8, 8);
122+ t^.base := res;
123+ t^.fields := params;
124+ t^.len := n;
125+ return t;
126+end;
127+
128+proc param(t: ^Sym.Type; isVar: BOOL; at: INT): ^Sym.Obj;
129+var o: ^Sym.Obj;
130+begin
131+ o := Sym.newObj(Sym.oVar, nameOf(at), t);
132+ o^.param := true;
133+ o^.isVar := isVar;
134+ return o;
135+end;
136+
137+proc makeTypes;
138+var t: ^Sym.Type; p, q, r: ^Sym.Obj; i: INT;
139+begin
140+ ty[YInt] := Sym.tInt; ty[YI64] := Sym.tI64; ty[YI32] := Sym.tI32; ty[YU8] := Sym.tU8;
141+ ty[YU16] := Sym.tU16; ty[YU32] := Sym.tU32; ty[YU64] := Sym.tU64; ty[YBool] := Sym.tBool;
142+ ty[YReal] := Sym.tReal; ty[YF32] := Sym.tF32; ty[YI8] := Sym.tI8; ty[YErr] := Sym.tError;
143+ ty[YBytes] := Sym.tBytes;
144+ t := newType(Sym.fEnum, 1, 1); t^.len := 5; ty[YEnum] := t;
145+ t := newType(Sym.fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t;
146+ t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; ty[YPtr] := t;
147+ t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; t^.vol := true; ty[YVptr] := t;
148+ t := newType(Sym.fArray, 48, 8); t^.base := Sym.tI64; t^.len := 6; ty[YArr] := t;
149+ t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t;
150+ t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t;
151+ t := newType(Sym.fArray, 8, 1); t^.base := Sym.tU8; t^.len := 8; ty[YArrU8] := t;
152+ t := newType(Sym.fSlice, 16, 8); t^.base := Sym.tI64; ty[YSlice] := t;
153+ (* a record of an I64, an F64 and an I32 *)
154+ record3 := newType(Sym.fRecord, 24, 8);
155+ p := Sym.newObj(Sym.oField, nameOf(40), Sym.tI64); p^.val := 0;
156+ q := Sym.newObj(Sym.oField, nameOf(41), Sym.tReal); q^.val := 8; p^.next := q;
157+ r := Sym.newObj(Sym.oField, nameOf(42), Sym.tI32); r^.val := 16; q^.next := r;
158+ record3^.fields := p;
159+ ty[YRec] := record3;
160+ t := newType(Sym.fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t;
161+ t := newType(Sym.fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t;
162+ (* a packed record: a byte, then an I32 that may be misaligned *)
163+ packedR := newType(Sym.fRecord, 53, 1);
164+ packedR^.packd := true;
165+ p := Sym.newObj(Sym.oField, nameOf(43), Sym.tU8); p^.val := 0;
166+ q := Sym.newObj(Sym.oField, nameOf(44), Sym.tI32); q^.val := 1; p^.next := q;
167+ r := Sym.newObj(Sym.oField, nameOf(46), ty[YArr]); r^.val := 5; q^.next := r;
168+ packedR^.fields := p;
169+ ty[YPacked] := packedR;
170+ variantT := newType(Sym.fVariant, 16, 8);
171+ ty[YVariant] := variantT;
172+ tuple2 := newType(Sym.fRecord, 16, 8);
173+ tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := newObjs(Sym.oVar, Sym.tInt, 2, 8, 45);
174+ (* procedures: (I64, F64) I64; (); (var I64, []I64) of two results *)
175+ p := param(Sym.tInt, false, 46); p^.next := param(Sym.tReal, false, 47);
176+ ty[YProc0] := procType(Sym.tInt, p, 2);
177+ ty[YProc1] := procType(nil, nil, 0);
178+ p := param(Sym.tI64, true, 48); p^.next := param(ty[YSlice], false, 49);
179+ ty[YProc2] := procType(tuple2, p, 2);
180+ results[0] := nil; results[1] := Sym.tInt; results[2] := Sym.tReal; results[3] := ty[YSlice];
181+ results[4] := tuple2; results[5] := record3; results[6] := Sym.tF32; results[7] := Sym.tI16;
182+ results[8] := ty[YBytes];
183+ for i := 0 to NumT - 1 do
184+ if ty[i] = nil then Diag.fatal("a type is missing"); end;
185+ end;
186+end;
187+
188+(* The objects named by the script: procedures, strings, constants of
189+ an array, a type, a built-in, a case of a variant *)
190+proc makeObjs;
191+var i, c: INT; o: ^Sym.Obj;
192+begin
193+ NEW(mod0, Heap.heap); mod0^.name := intern("Zero");
194+ NEW(mod1, Heap.heap); mod1^.name := intern("Other");
195+ Sym.setCurModule(mod0);
196+ for i := 0 to 5 do
197+ o := Sym.newObj(Sym.oProc, nameOf(50 + i), ty[YProc0 + i mod 3]);
198+ o^.chunk := FirstProc + rnd(NumProcs);
199+ o^.ext := i >= 4;
200+ o^.isCode := i = 3;
201+ procs[i] := o;
202+ end;
203+ for i := 0 to 2 do
204+ o := Sym.newObj(Sym.oConst, nameOf(60 + i), Sym.tStr);
205+ o^.val := 2 + 3 * i;
206+ c := Chunk.newChunk(Chunk.secRodata, -1, -1);
207+ Chunk.setData(c, ADR(Letters[0]), INT(o^.val) + 1, 1);
208+ o^.chunk := c;
209+ strs[i] := o;
210+ end;
211+ arrConst := Sym.newObj(Sym.oConst, nameOf(63), ty[YArr]);
212+ arrConst^.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1);
213+ Chunk.setData(arrConst^.chunk, ADR(Letters[0]), 8, 8);
214+ typeObj := Sym.newObj(Sym.oType, nameOf(64), ty[YRec]);
215+ builtinObj := Sym.newObj(Sym.oBuiltin, nameOf(65), Sym.tNone);
216+ caseObj := Sym.newObj(Sym.oCase, nameOf(66), variantT);
217+ caseObj^.val := 3;
218+ caseObj^.fields := newObjs(Sym.oField, Sym.tInt, 2, 8, 67);
219+ caseObj^.fields^.val := 8;
220+end;
221+
222+(* The variable of each type, in the frame, a chunk, a slot, a register,
223+ another module or C's, as the procedure compiled has them *)
224+proc makeVars;
225+var i, k: INT; o: ^Sym.Obj; t: ^Sym.Type;
226+begin
227+ for i := 0 to NumT - 1 do
228+ t := ty[i];
229+ o := Sym.newObj(Sym.oVar, nameOf(i), t);
230+ o^.lev := 1;
231+ k := rnd(9);
232+ if k = 2 then
233+ o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs);
234+ elsif k = 3 then
235+ o^.ind := true; o^.val := Gen.allocPerm(8, 8); o^.off := 8 * rnd(3);
236+ elsif k = 4 then
237+ if (t^.form in {Sym.fInt, Sym.fPtr}) and (t^.size = 8) then
238+ o^.reg := Gen.VarRegs[rnd(5)];
239+ elsif t^.form = Sym.fReal then
240+ o^.reg := Gen.XVarRegs[rnd(4)];
241+ elsif t^.form = Sym.fSlice then
242+ o^.reg := Gen.VarRegs[rnd(3)]; o^.reg2 := Gen.VarRegs[3 + rnd(2)];
243+ end;
244+ if o^.reg = 0 then o^.val := Gen.allocPerm(t^.size, 8); end;
245+ elsif k = 5 then
246+ o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.home := mod1;
247+ elsif k = 6 then
248+ o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.ext := true;
249+ else
250+ o^.val := Gen.allocPerm(t^.size + 8, 8);
251+ end;
252+ vars[i] := o;
253+ end;
254+end;
255+
256+(* Operands *)
257+
258+proc intType: ^Sym.Type;
259+begin
260+ return ty[IntTypes[rnd(8)]];
261+end;
262+
263+proc varItem(var x: Item.Item; t: ^Sym.Type): ERROR;
264+var i, k: INT;
265+begin
266+ k := rnd(NumT);
267+ for i := 0 to NumT - 1 do
268+ if ty[i] = t then k := i; end;
269+ end;
270+ x := {};
271+ x.pos := pos();
272+ return Item.makeItem(x, vars[k]);
273+end;
274+
275+(* An operand of type t, or of any if t is nil *)
276+proc operand(var x: Item.Item; t: ^Sym.Type): ERROR;
277+var k: INT; r: F64; v: I64;
278+begin
279+ x := {};
280+ x.pos := pos();
281+ if t = nil then
282+ match rnd(14) of
283+ | 0: Item.makeConst(x, Sym.tConst, constVal());
284+ | 1: Item.makeConst(x, Sym.tConst, constVal() mod 200);
285+ | 2: t := intType(); v := constVal() mod 100; Item.makeConst(x, t, v);
286+ | 3: r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r);
287+ | 4: Item.makeConst(x, Sym.tBool, I64(rnd(2)));
288+ | 5: return Item.makeItem(x, strs[rnd(3)]);
289+ | 6: Item.makeConst(x, Sym.tNil, 0);
290+ | 7: return Item.makeItem(x, procs[rnd(6)]);
291+ | 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);
299+ | 13: try Item.makeItem(x, vars[rnd(NumT)]); return Item.value(x);
300+ | else: return varItem(x, ty[rnd(NumT)]);
301+ end;
302+ return nil;
303+ end;
304+ k := rnd(10);
305+ if Sym.isInt(t) then
306+ if k < 3 then Item.makeConst(x, Sym.tConst, constVal() mod 100); return nil; end;
307+ if k = 3 then Item.makeConst(x, t, constVal() mod 100); return nil; end;
308+ elsif t^.form = Sym.fReal then
309+ if k < 3 then r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r); return nil; end;
310+ elsif t^.form = Sym.fBool then
311+ if k < 3 then Item.makeConst(x, Sym.tBool, I64(rnd(2))); return nil; end;
312+ elsif t^.form = Sym.fPtr then
313+ if k < 2 then Item.makeConst(x, Sym.tNil, 0); return nil; end;
314+ elsif (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then
315+ if k < 3 then return Item.makeItem(x, strs[rnd(3)]); end;
316+ end;
317+ return varItem(x, t);
318+end;
319+
320+(* A condition, left as one: a comparison of two integers *)
321+proc condItem(var x: Item.Item): ERROR;
322+var y: Item.Item; L: INT; op: Scan.Sym; t: ^Sym.Type;
323+begin
324+ t := intType();
325+ op := Cmps[rnd(6)];
326+ try operand(x, t);
327+ try Item.op1(op, x, L);
328+ try operand(y, t);
329+ return Item.op2(op, x, y, L);
330+end;
331+
332+(* A variable, or part of one: through a pointer, a field, an element, a slice *)
333+proc place(var x: Item.Item): ERROR;
334+var i, k: INT; f: ^Sym.Obj; y, lo, hi: Item.Item;
335+begin
336+ try varItem(x, ty[rnd(NumT)]);
337+ for i := 1 to 3 do
338+ if rnd(3) # 0 then
339+ k := rnd(6);
340+ if (k = 0) or (x.typ^.form = Sym.fPtr) then
341+ try Item.deref(x);
342+ elsif x.typ^.form = Sym.fRecord then
343+ f := x.typ^.fields;
344+ k := rnd(3);
345+ while (k > 0) and (f^.next # nil) do f := f^.next; DEC(k); end;
346+ try Item.field(x, f);
347+ elsif (x.typ^.form in {Sym.fArray, Sym.fSlice, Sym.fStr}) then
348+ try Item.indexPrep(x);
349+ if k < 4 then
350+ try operand(y, intType());
351+ try Item.index(x, y);
352+ else
353+ try operand(lo, intType());
354+ try Item.sliceLo(lo);
355+ try operand(hi, intType());
356+ try Item.slice(x, lo, hi);
357+ end;
358+ end;
359+ end;
360+ end;
361+ return nil;
362+end;
363+
364+(* The state of an item *)
365+proc dump(var x: Item.Item);
366+var name: []U8; flags: INT;
367+begin
368+ name := "-";
369+ if x.typ # nil then name := Sym.typeName(x.typ); end;
370+ flags := bit(x.vol) + 2 * bit(x.isVar) + 4 * bit(x.odd) + 8 * bit(x.ro) + 16 * bit(x.deref);
371+ Fmt.print("I {} {} {} {} {} {} {}", [Fmt.int(INT(x.mode)), Fmt.str(name), Fmt.int(INT(x.rel)),
372+ Fmt.int(bit(x.relSigned)), Fmt.int(x.fj), Fmt.int(x.tj), Fmt.int(x.val)]);
373+ Fmt.print(" {} {} {} {} depth {} pushed {}\n", [Fmt.int(INT(x.base)), Fmt.int(x.chunk), Fmt.int(x.off),
374+ Fmt.int(flags), Fmt.int(Gen.depth), Fmt.int(Gen.pushed)]);
375+end;
376+
377+(* A call: of a procedure of the script or a variable of a procedure
378+ type, with arguments that mostly fit its parameters *)
379+proc doCall(var x: Item.Item): ERROR;
380+var f, a: Item.Item; p: ^Sym.Obj; n: INT;
381+begin
382+ f := {};
383+ f.pos := pos();
384+ if rnd(5) = 0 then try Item.makeItem(f, vars[YProc0 + rnd(3)]);
385+ else try Item.makeItem(f, procs[rnd(6)]); end;
386+ try Item.beginCall(call, f);
387+ p := call.param;
388+ n := rnd(4) - 1;
389+ while (p # nil) or (n > 0) do
390+ if p # nil then
391+ if p^.isVar and (rnd(2) = 0) then
392+ try varItem(a, ty[YVptr]);
393+ try Item.deref(a);
394+ elsif rnd(6) = 0 then try operand(a, nil);
395+ else try operand(a, p^.typ); end;
396+ p := p^.next;
397+ else
398+ try operand(a, nil);
399+ n := n - 1;
400+ end;
401+ try Item.passArg(call, a);
402+ if (p = nil) and (n < 0) then n := 0; end;
403+ if (p # nil) and (n < 0) and (rnd(4) = 0) then p := nil; n := 0; end;
404+ end;
405+ return Item.endCall(call, x);
406+end;
407+
408+(* A binary operation, with a condition's jumps made after it, sometimes *)
409+proc binary(var x: Item.Item): ERROR;
410+var y: Item.Item; L, M: INT; op: Scan.Sym; t: ^Sym.Type;
411+begin
412+ L := Gen.NoLabel;
413+ M := Gen.NoLabel;
414+ op := Ops[rnd(20)];
415+ match rnd(8) of
416+ | 0, 1: t := intType();
417+ | 2: t := ty[YReal + rnd(2)];
418+ | 3: t := ty[YBool];
419+ | 4: t := ty[YEnum + rnd(2)];
420+ | else: t := ty[rnd(NumT)];
421+ end;
422+ if rnd(6) = 0 then
423+ (* and, or *)
424+ if flag() then op := Scan.sAnd; else op := Scan.sOr; end;
425+ try condItem(x);
426+ try Item.op1(op, x, L);
427+ try condItem(y);
428+ elsif op = Scan.sIn then
429+ try operand(x, ty[YEnum]);
430+ try Item.op1(op, x, L);
431+ try operand(y, ty[YSet]);
432+ else
433+ try operand(x, t);
434+ try Item.op1(op, x, L);
435+ if rnd(5) = 0 then try operand(y, nil); else try operand(y, t); end;
436+ end;
437+ try Item.op2(op, x, y, L);
438+ if (x.mode = Item.mCond) and (rnd(3) # 0) then
439+ if flag() then try Item.condJump(x, M); else try Item.condJumpTrue(x, M); end;
440+ Gen.fix(M);
441+ x.mode := Item.mNone; (* its values are used *)
442+ end;
443+ return nil;
444+end;
445+
446+proc unary(var x: Item.Item): ERROR;
447+begin
448+ try operand(x, nil);
449+ match rnd(3) of
450+ | 0: return Item.neg(x);
451+ | 1: return Item.notOp(x);
452+ | else: return Item.complement(x);
453+ end;
454+end;
455+
456+(* match: the slot of a variant, an enumeration or an integer, and
457+ tests of it *)
458+proc doMatch(var x: Item.Item): ERROR;
459+var p, lo, hi: I64; L: INT;
460+begin
461+ L := Gen.NoLabel;
462+ match rnd(3) of
463+ | 0: try varItem(x, ty[YVariant]);
464+ | 1: try varItem(x, ty[YEnum]);
465+ | else: try operand(x, nil);
466+ end;
467+ p := try Item.matchBegin(x);
468+ Item.matchTag(p, constVal() mod 10, L);
469+ lo := constVal() mod 10;
470+ hi := constVal() mod 10 + 10;
471+ Item.matchRange(p, lo, hi, L);
472+ Item.matchRange(p, 3, 3, L);
473+ Gen.fix(L);
474+ return nil;
475+end;
476+
477+(* A for loop's variable stepped and tested *)
478+proc doFor(var x: Item.Item): ERROR;
479+var o: ^Sym.Obj; lim: Item.Item; step: I64; exitL: INT;
480+begin
481+ o := vars[IntTypes[rnd(8)]];
482+ step := constVal() mod 5;
483+ if step = 0 then step := 1; end;
484+ if rnd(2) = 0 then step := -step; end;
485+ lim := {};
486+ lim.pos := pos();
487+ Item.makeConst(lim, o^.typ, constVal() mod 50);
488+ exitL := Gen.NoLabel;
489+ try Item.forStep(o, step);
490+ try Item.forNext(o, lim, step, exitL, Chunk.pc, Chunk.pc);
491+ Gen.fix(exitL);
492+ x := lim;
493+ return nil;
494+end;
495+
496+(* INC and DEC, pin, COPY *)
497+proc doMisc(var x: Item.Item): ERROR;
498+var y: Item.Item;
499+begin
500+ match rnd(5) of
501+ | 0:
502+ try place(x);
503+ try Item.address(x);
504+ try operand(y, x.typ);
505+ return Item.incDec(x, y, flag());
506+ | 1:
507+ try place(x);
508+ return Item.pin(x);
509+ | 2:
510+ try place(x);
511+ try Item.copyDest(x);
512+ try place(y);
513+ return Item.copyFrom(x, y);
514+ | 3:
515+ try operand(x, nil);
516+ Item.makeStr(y);
517+ return Item.coerce(y, ty[YBytes]);
518+ | else:
519+ try operand(x, nil);
520+ Item.nilTest(x);
521+ Item.usesReals(x.pos);
522+ return Item.discard(x);
523+ end;
524+end;
525+
526+(* A variant, a record's fields, an error's chunk, the message of one *)
527+proc doTemp(var x: Item.Item): ERROR;
528+var a: Item.Item; c, h, n: INT; f: ^Sym.Obj;
529+begin
530+ x := {};
531+ x.pos := pos();
532+ match rnd(5) of
533+ | 0: Item.zeroTemp(x, ty[YVariant]);
534+ | 1:
535+ Item.construct(x, caseObj);
536+ f := caseObj^.fields;
537+ try operand(a, f^.typ);
538+ return Item.setField(x, f, a);
539+ | 2:
540+ Item.zeroTemp(x, ty[YRec]);
541+ f := ty[YRec]^.fields;
542+ if flag() then f := f^.next; end;
543+ try operand(a, f^.typ);
544+ return Item.setField(x, f, a);
545+ | 3:
546+ try operand(a, nil);
547+ h := rnd(3) - 1;
548+ n := rnd(3) - 1;
549+ c := try Item.errorChunk(a, h, n);
550+ Item.makeConst(x, Sym.tError, I64(c) + 1);
551+ return nil;
552+ | else:
553+ try operand(x, ty[YErr]);
554+ return Item.msg(x);
555+ end;
556+ return nil;
557+end;
558+
559+proc doReturn(var x: Item.Item): ERROR;
560+var f: ^Sym.Obj;
561+begin
562+ if (curRes = 4) and flag() then
563+ (* several results *)
564+ f := tuple2^.fields;
565+ if flag() then f := f^.next; end;
566+ if flag() then
567+ try operand(x, f^.typ);
568+ return Item.returnField(f, x);
569+ end;
570+ try doCall(x);
571+ return Item.returnAll(x);
572+ end;
573+ if rnd(4) = 0 then return Item.returnNone(); end;
574+ try operand(x, results[curRes]);
575+ return Item.returnValue(x);
576+end;
577+
578+(* One step of the script, whose item is x *)
579+proc step(k: INT; var x: Item.Item): ERROR;
580+var y: Item.Item;
581+begin
582+ x := {};
583+ match k of
584+ | 0: try operand(x, nil); return Item.value(x);
585+ | 1: try operand(x, nil); return Item.address(x);
586+ | 2: try operand(x, nil); return Item.coerce(x, ty[rnd(NumT)]);
587+ | 3: try operand(x, nil); return Item.coerceExact(x, intType(), "");
588+ | 4:
589+ try place(x);
590+ try operand(y, x.typ);
591+ return Item.assign(x, y);
592+ | 5: return unary(x);
593+ | 6: return binary(x);
594+ | 7: try operand(x, nil); return Item.convert(x, ty[rnd(NumT)]);
595+ | 8: return place(x);
596+ | 9: return doCall(x);
597+ | 10: return doMatch(x);
598+ | 11: return doFor(x);
599+ | 12: return doMisc(x);
600+ | 13: return doTemp(x);
601+ | 14: return doReturn(x);
602+ | else: return binary(x);
603+ end;
604+end;
605+
606+(* One procedure of Steps steps *)
607+proc genProc(c: INT);
608+var
609+ sig: ^Sym.Type; i, k, line: INT; x: Item.Item; err: ERROR;
610+begin
611+ curRes := rnd(9);
612+ sig := procType(results[curRes], nil, 0);
613+ Item.beginProc(sig, nil);
614+ for i := 0 to 5 do _ := Gen.allocPerm(8, 8); end;
615+ makeVars();
616+ Item.setChecks(flag());
617+ line := 1 + rnd(40);
618+ Gen.enterBody(c, line);
619+ for i := 1 to Steps do
620+ if Diag.errors >= 19 then break; end; (* the 20th would end the run *)
621+ k := rnd(17);
622+ Item.setDemoted(false);
623+ err := step(k, x);
624+ if err # nil then
625+ Fmt.print("S {} {} failed\n", [Fmt.int(c), Fmt.int(k)]);
626+ else
627+ Fmt.print("S {} {} ok\n", [Fmt.int(c), Fmt.int(k)]);
628+ dump(x);
629+ (* the items of these steps are as an operand is, on the stack *)
630+ if (k < 4) or ((k >= 5) and (k <= 9)) then _ := Item.discard(x); end;
631+ end;
632+ Fmt.print("demoted {}\n", [Fmt.int(bit(Item.demoted))]);
633+ Gen.resetStack(0, 0);
634+ end;
635+ _ := Gen.endProc(c, sig^.base # nil);
636+end;
637+
638+proc chunkNameOf(i: INT): INT;
639+var s: [3]U8;
640+begin
641+ s[0] := 'p'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10);
642+ return Scan.intern(ADR(s[0]), 3);
643+end;
644+
645+proc main*;
646+var i, c: INT; path: []U8; arg: []U8;
647+begin
648+ arg := Files.arg(1);
649+ seed := 5;
650+ for i := 0 to LEN(arg) - 1 do seed := seed * 10 + I64(arg[i]) - 48; end;
651+ Letters := "abcdefgh\0";
652+ path := "self/test/ItemDump.txt";
653+ if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end;
654+ Scan.next; (* the string the file starts with *)
655+ X.setListing(true);
656+ Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path)));
657+ for i := 0 to NumProcs - 1 do c := Chunk.newChunk(Chunk.secText, -1, chunkNameOf(i)); Chunk.setLive(c); end;
658+ for i := 0 to NumGlobs - 1 do
659+ c := Chunk.newChunk(Chunk.secBss, -1, chunkNameOf(NumProcs + i));
660+ Chunk.setBss(c, 64, 8);
661+ end;
662+ makeTypes();
663+ makeObjs();
664+ for i := 0 to NumProcs - 1 do genProc(FirstProc + i); end;
665+ Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc),
666+ Fmt.int(Chunk.numFixups), Fmt.int(Chunk.numLines), Fmt.int(X.saidCount())]);
667+ for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
668+ Out.ln;
669+ for i := 0 to Chunk.numFixups - 1 do
670+ Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]);
671+ end;
672+ for i := 0 to Chunk.numLines - 1 do
673+ Fmt.print("L {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk),
674+ Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]);
675+ end;
676+ X.list(-1);
677+end;
678+
679+end ItemDump.

self/test/ItemDump.txt added +41 -0

@@ -0,0 +1,41 @@
1+"item test"
2+ x value sum alpha beta;
3+ next beta items len alpha next count alpha beta;
4+ value beta count beta next value;
5+ len beta count;
6+ sum len alpha len len value alpha count;
7+ next x n;
8+ x next beta len n next;
9+ sum x beta len len sum count items beta;
10+ tmp beta len alpha len count p;
11+ next value items p len p items n;
12+ x tmp count beta;
13+ n next p items tmp p n;
14+ beta beta next value x items x;
15+ value alpha sum beta next len;
16+ items items tmp items len p len p beta;
17+ beta n p tmp sum beta alpha tmp tmp;
18+ sum len sum p n;
19+ value sum items alpha p items x len;
20+ p alpha count;
21+ n x tmp count value value p beta x;
22+ value next n x value next;
23+ tmp value items sum value;
24+ x beta x x;
25+ sum count alpha p;
26+ len x n n alpha x value next items;
27+ len items x tmp next len sum;
28+ tmp alpha p sum next value value value;
29+ beta p sum value alpha count;
30+ count p x;
31+ items len alpha;
32+ alpha len x;
33+ beta items len alpha beta count len;
34+ x sum n items len items;
35+ beta beta p p p p;
36+ beta x beta tmp items;
37+ n p tmp x next alpha count next;
38+ x tmp next alpha next;
39+ sum beta tmp n next;
40+ x items count next next;
41+ next items sum count len count count value tmp;