raz / src / Item.raz

2553 lines · 99.3 KiB · raw · history · last change 4402a682

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. *)
26module Item;
27import Fmt, Diag, Scan, Sym, Chunk, Gen;
28import SYSTEM;
29
30type
31 Mode* = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond,
32 mWords); (* two results of a call, on the stack, the first under the second *)
33
34 Item* = record
35 mode*: Mode;
36 typ*: ^Sym.Type;
37 rel*: Scan.Sym; (* mCond: the comparison of the two integers on
38 the stack, not yet made, as Wirth's compilers
39 keep a condition *)
40 relSigned*: BOOL;
41 fj*, tj*: INT; (* mCond: the chains of jumps already made that are
42 taken when the whole condition is false, and when
43 it is true, not yet given a place (and, or and
44 not make them); see Gen's jumpOut *)
45 val*: I64; (* mConst: the value, an F64's bits; mStr: its length *)
46 base*: Gen.Base; (* mVar: what the address is relative to *)
47 chunk*: INT; (* mVar with bGlobal, mStr: the chunk; bSlot: the slot; bPtr: the register *)
48 off*: I64; (* mVar: added to the base *)
49 vol*: BOOL; (* mVar: reached through ^VOLATILE *)
50 isVar*: BOOL; (* mVar: a variable of the program, not a temporary *)
51 odd*: BOOL; (* mVar: in a packed record, so maybe misaligned *)
52 view*: BOOL; (* mVar: a view, v.(T), or part of one: maybe
53 misaligned, and with no address *)
54 ro*: BOOL; (* mVar: another module's exported variable, or part
55 of one, which only that module changes *)
56 elemRo*: BOOL; (* mVar: an element of a []const slice, or part of
57 one, read through it and not written *)
58 viewOver*: BOOL; (* a view over a variable that holds more than
59 integers and reals, written only in a
60 module that imports SYSTEM *)
61 deref*: BOOL; (* mVar: at an address from a pointer, which may be
62 nil and isn't tested yet (nilTest) *)
63 obj*: ^Sym.Obj; (* mProc, mBuiltin, mCase; mVar: the variable named *)
64 frame*: BOOL; (* a slice: points into the procedure's own frame,
65 which returnValue refuses (report section 7.3);
66 anything else: lies in that frame, a local, a
67 value parameter or a temporary, or part of one *)
68 pos*: Diag.Pos; (* where it is in the source, for messages *)
69 made*: BOOL; (* an integer an operator gave, computed in its own
70 type, where it may have wrapped: a U8 made so
71 doesn't widen to INT (report section 5.10) *)
72 end;
73
74const
75 (* the comparison that holds when the one at the same place doesn't, for integers *)
76 NegatedOps: [6]Scan.Sym = [Scan.sNeq, Scan.sEql, Scan.sGeq, Scan.sGtr, Scan.sLeq, Scan.sLss];
77
78const
79 MaxI64 = 9223372036854775807;
80 MinI64 = -9223372036854775807 - 1;
81
82var
83 demoted*: BOOL; (* address wanted a register variable's address: its
84 procedure is compiled again, the variable in memory *)
85 checks*: BOOL; (* the module's index and slice checks are made: it
86 doesn't say check off *)
87 result: ^Sym.Type; (* the result of the procedure being compiled, or nil *)
88 passing: ^Sym.Obj; (* the parameter the argument at passingAt goes to *)
89 passingAt: Diag.Pos;
90
91proc setDemoted*(yes: BOOL);
92begin
93 demoted := yes;
94end;
95
96proc setChecks*(yes: BOOL);
97begin
98 checks := yes;
99end;
100
101(* The comparison that holds when op doesn't *)
102proc negated(op: Scan.Sym): Scan.Sym;
103begin
104 return NegatedOps[INT(op) - INT(Scan.sEql)];
105end;
106
107proc isRel(op: Scan.Sym): BOOL;
108begin
109 return (op >= Scan.sEql) and (op <= Scan.sGeq);
110end;
111
112(* Whether op is one of the list: Scan.Sym has too many names for a set *)
113proc oneOf(op: Scan.Sym; list: []Scan.Sym): BOOL;
114var i: INT;
115begin
116 for i := 0 to LEN(list) - 1 do
117 if list[i] = op then return true; end;
118 end;
119 return false;
120end;
121
122proc bit(f: BOOL): I64;
123begin
124 if f then return 1; end;
125 return 0;
126end;
127
128(* A message, from a format and the strings that fill it *)
129proc say1(f, a: []const U8): []const U8;
130begin
131 return Diag.say(f, [Fmt.str(a)]);
132end;
133
134(* What reaches memory other than through a variable, what, is refused
135 at pos in a module that doesn't import SYSTEM (report 3) *)
136proc needSystem*(pos: Diag.Pos; what: []const U8): ERROR;
137begin
138 if not Sym.curModule^.system then
139 return Scan.markHelp(pos, say1("{} needs import SYSTEM", what),
140 "it reaches memory other than through a variable: say import SYSTEM after the module's imports");
141 end;
142 return nil;
143end;
144
145proc say2(f, a, b: []const U8): []const U8;
146begin
147 return Diag.say(f, [Fmt.str(a), Fmt.str(b)]);
148end;
149
150(* Items *)
151
152proc makeConst*(var x: Item; t: ^Sym.Type; v: I64);
153var p: Diag.Pos;
154begin
155 p := x.pos;
156 x := {};
157 x.pos := p;
158 x.mode := mConst;
159 x.typ := t;
160 x.val := v;
161end;
162
163(* A real constant: untyped, unless typed later. Its value is an F64,
164 which for an F32 is one an F32 can hold. *)
165proc makeReal*(var x: Item; r: F64);
166var p: ^F64;
167begin
168 makeConst(x, Sym.tRConst, 0);
169 p := ^F64(SYSTEM.ADR(x.val));
170 p^ := r;
171end;
172
173proc isF32(t: ^Sym.Type): BOOL;
174begin
175 return (t^.form = Sym.fReal) and (t^.size = 4);
176end;
177
178proc realOf*(const x: Item): F64;
179var v: I64; p: ^F64;
180begin
181 v := x.val;
182 p := ^F64(SYSTEM.ADR(v));
183 return p^;
184end;
185
186(* Gives a real constant the real type t, rounded to it. *)
187proc realTo(var x: Item; t: ^Sym.Type);
188var r: F64;
189begin
190 r := realOf(x);
191 if isF32(t) then makeReal(x, F64(F32(r))); else makeReal(x, r); end;
192 x.typ := t;
193end;
194
195(* The current string literal, as an item of its own chunk. *)
196proc makeStr*(var x: Item);
197begin
198 x := {};
199 x.mode := mStr;
200 x.typ := Sym.tStr;
201 x.val := Scan.slen;
202 x.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1);
203 Chunk.setData(x.chunk, Scan.strWithZero(), Scan.slen + 1, 1);
204end;
205
206proc frameAdr*(off: I64): Gen.Adr;
207begin
208 return {base: Gen.bFrame, chunk: -1, off: off, hi: 0};
209end;
210
211proc globalAdr*(c: INT): Gen.Adr;
212begin
213 return {base: Gen.bGlobal, chunk: c, off: 0, hi: 0};
214end;
215
216(* Where the variable x is, for Gen; a slice in registers has two. x is
217 a var parameter only so as not to be copied, as it is a whole Item. *)
218proc adrOf*(const x: Item): Gen.Adr;
219var hi: INT;
220begin
221 hi := 0;
222 if x.base = Gen.bReg then hi := x.obj^.reg2; end;
223 return {base: x.base, chunk: x.chunk, off: x.off, hi: hi};
224end;
225
226(* An item for "found ...": a constant without a type of its own as it
227 is written, so that "found 1.5" says what is wrong; else its type. *)
228proc what*(x: Item): []const U8;
229begin
230 if (x.mode = mConst) and ((x.typ = Sym.tConst) or (x.typ = Sym.tRConst)) then
231 return Diag.source(x.pos);
232 end;
233 return Sym.typeName(x.typ);
234end;
235
236(* Two operands of different types. Numbers convert, so say how. *)
237proc mismatchOps(x, y: Item; xt, yt: ^Sym.Type): ERROR;
238var text: []const U8;
239begin
240 text := say2("{} and {} are different types", Sym.typeName(xt), Sym.typeName(yt));
241 (* the help converts the narrower integer to the wider, which loses
242 nothing; else the right operand to the left one's type *)
243 if Sym.isInt(xt) and Sym.isInt(yt) and (xt^.size < yt^.size) and (xt # Sym.tConst) then
244 return Scan.markHelp(Diag.join(x.pos, y.pos), text,
245 say2("convert one to the other's type, as in {}({})", Sym.typeName(yt), Diag.source(x.pos)));
246 end;
247 if (Sym.isInt(xt) or (xt^.form = Sym.fReal)) and (Sym.isInt(yt) or (yt^.form = Sym.fReal))
248 and (xt # Sym.tConst) and (xt # Sym.tRConst) then
249 return Scan.markHelp(Diag.join(x.pos, y.pos), text,
250 say2("convert one to the other's type, as in {}({})", Sym.typeName(xt), Diag.source(y.pos)));
251 end;
252 return Scan.markAt(Diag.join(x.pos, y.pos), text);
253end;
254
255(* An item that is not a value, by what it is. *)
256proc notValue(x: Item): ERROR;
257begin
258 match x.mode of
259 | mType: return Scan.markAt(x.pos, say1("{} is a type, not a value", Sym.typeName(x.typ)));
260 | mBuiltin: return Scan.markAt(x.pos, say1("{} is a built-in procedure, not a value", Scan.nameOf(x.obj^.name)));
261 | mCase: return Scan.markAt(x.pos, say1("{} is a case, not a value", Scan.nameOf(x.obj^.name)));
262 | mNone:
263 if x.obj # nil then return Scan.markAt(x.pos, say1("{} returns nothing", Scan.nameOf(x.obj^.name))); end;
264 return Scan.markAt(x.pos, "the procedure returns nothing");
265 | else: return Scan.markAt(x.pos, "a string can't be an operand");
266 end;
267end;
268
269proc makeItem*(var x: Item; o: ^Sym.Obj): ERROR;
270begin
271 x := {};
272 x.typ := o^.typ;
273 x.obj := o;
274 match o^.cls of
275 | oConst:
276 if o^.typ = Sym.tStr then
277 x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk;
278 elsif o^.typ^.form in {Sym.fArray, Sym.fRecord, Sym.fSlice, Sym.fVariant} then
279 (* an array, record, variant or empty slice constant: a variable in
280 read-only data, not one of the program's, so nothing can change it *)
281 x.mode := mVar; x.base := Gen.bGlobal; x.chunk := o^.chunk;
282 else
283 x.mode := mConst; x.val := o^.val;
284 end;
285 | oVar:
286 x.mode := mVar;
287 (* another module's variable, and a const parameter, are only read *)
288 x.ro := ((o^.lev = 0) and (o^.home # Sym.curModule)) or o^.isConst;
289 x.isVar := not x.ro;
290 if o^.ext then
291 Gen.pushVar(globalAdr(o^.chunk), 8, false, Gen.kWord);
292 x.base := Gen.bStack;
293 elsif o^.lev = 0 then
294 x.base := Gen.bGlobal; x.chunk := o^.chunk;
295 elsif o^.ind and (o^.reg # 0) then
296 x.base := Gen.bPtr; x.chunk := o^.reg; x.off := o^.off;
297 elsif o^.ind then
298 x.base := Gen.bSlot; x.chunk := INT(o^.val); x.off := o^.off;
299 elsif o^.reg # 0 then
300 x.base := Gen.bReg; x.chunk := o^.reg;
301 else
302 x.base := Gen.bFrame; x.off := o^.val;
303 end;
304 (* a value parameter passed by address (ind) is a copy all the same *)
305 x.frame := (o^.lev > 0) and not o^.isVar and (o^.typ^.form # Sym.fSlice);
306 | oProc: x.mode := mProc;
307 | oType: x.mode := mType;
308 | oBuiltin: x.mode := mBuiltin;
309 | oCase: x.mode := mCase;
310 | else: return Scan.mark(say1("{} is not a value", Scan.nameOf(o^.name)));
311 end;
312 return nil;
313end;
314
315proc scalarSize*(t: ^Sym.Type): INT;
316begin
317 if t^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then return INT(t^.size); end;
318 return 8;
319end;
320
321(* The width an operation on t is brought back to, and whether signed *)
322proc intSize(t: ^Sym.Type): INT;
323begin
324 if t^.form = Sym.fInt then return INT(t^.size); end;
325 return 8;
326end;
327
328proc signed(t: ^Sym.Type): BOOL;
329begin
330 return ((t^.form = Sym.fInt) and t^.signed) or (t^.form = Sym.fConst);
331end;
332
333proc cut(v: I64; t: ^Sym.Type): I64;
334begin
335 if t^.form # Sym.fInt then return v; end;
336 match t^.size of
337 | 1: if t^.signed then return I64(I8(v)); end; return I64(U8(v));
338 | 2: if t^.signed then return I64(I16(v)); end; return I64(U16(v));
339 | 4: if t^.signed then return I64(I32(v)); end; return I64(U32(v));
340 | else: return v;
341 end;
342end;
343
344(* Code computing with a real is noted on its chunk, at the first place,
345 for a target without reals (report 5.1) to refuse if the chunk turns
346 out to be used. A real moved whole, as a record's bytes are copied,
347 needs nothing the target lacks, and isn't noted. *)
348proc usesReals*(p: Diag.Pos);
349begin
350 if (Gen.codeChunk >= 0) and not Chunk.chunks[Gen.codeChunk].reals then
351 Chunk.setReals(Gen.codeChunk, p);
352 end;
353end;
354
355(* x, at an address from a pointer, is about to be used: Gen tests the
356 address for nil where the machine wouldn't stop at it (report section
357 10), from its offset to its end. *)
358proc nilTest*(var x: Item);
359begin
360 if (x.mode = mVar) and x.deref then Gen.checkNil(x.off + x.typ^.size, x.pos); end;
361 x.deref := false;
362end;
363
364(* x's value, on top of the stack *)
365proc value*(var x: Item): ERROR;
366var f: F32; p: ^U32;
367begin
368 if x.mode = mCond then
369 if (x.fj = Gen.NoLabel) and (x.tj = Gen.NoLabel) then Gen.compare(x.rel, Gen.kWord, x.relSigned);
370 else Gen.condValue(negated(x.rel), x.relSigned, x.fj, x.tj); end;
371 x.mode := mStack;
372 return nil;
373 end;
374 if x.typ^.form = Sym.fReal then usesReals(x.pos); end;
375 nilTest(x);
376 match x.mode of
377 | mConst:
378 if (x.typ^.form = Sym.fError) and (x.val > 0) then Gen.pushAdr(globalAdr(INT(x.val) - 1));
379 elsif isF32(x.typ) then
380 f := F32(realOf(x));
381 p := ^U32(SYSTEM.ADR(f));
382 Gen.pushConst(Gen.kF32, I64(p^));
383 else Gen.pushConst(Gen.kindOf(x.typ), x.val); end;
384 | mVar:
385 if not Sym.isScalar(x.typ) then
386 return Scan.markAt(x.pos, say1("expected a single value, found {}", what(x)));
387 end;
388 Gen.pushVar(adrOf(x), scalarSize(x.typ), (x.typ^.form = Sym.fInt) and x.typ^.signed, Gen.kindOf(x.typ));
389 | mStack: x.mode := mStack;
390 | mProc:
391 if x.obj^.isCode and (x.obj^.typ^.base # nil) and x.obj^.typ^.base^.tuple then
392 return Scan.markAt(x.pos, "a code procedure with two results can only be called");
393 end;
394 Gen.pushProc(x.obj^.chunk, x.obj^.ext);
395 | else: return notValue(x);
396 end;
397 x.mode := mStack;
398 return nil;
399end;
400
401(* x, a variable kept in a register, is wanted in memory after all, for
402 its address or a view of its bytes: the procedure is compiled again
403 with the variable in memory; till then, this code is thrown away *)
404proc demote(var x: Item);
405begin
406 if (x.mode = mVar) and (x.base = Gen.bReg) then
407 x.obj^.reg := 0;
408 x.obj^.reg2 := 0;
409 demoted := true;
410 x.base := Gen.bFrame;
411 x.off := x.obj^.val;
412 end;
413end;
414
415(* The address of the variable or string x, on top of the stack *)
416proc address*(var x: Item): ERROR;
417begin
418 nilTest(x);
419 demote(x);
420 if x.mode = mStr then Gen.pushAdr(globalAdr(x.chunk));
421 elsif x.mode = mVar then
422 Gen.pushAdr(adrOf(x));
423 x.base := Gen.bStack; x.off := 0;
424 else return Scan.markAt(x.pos, "expected a variable"); end;
425 return nil;
426end;
427
428(* x isn't wanted: what it has on the stack is dropped *)
429proc discard*(const x: Item): ERROR;
430var y: Item;
431begin
432 if x.mode = mCond then
433 y := x;
434 try value(y);
435 Gen.drop();
436 return nil;
437 end;
438 if (x.mode = mStack) or ((x.mode = mVar) and (x.base = Gen.bStack)) then Gen.drop(); end;
439 if x.mode = mWords then Gen.drop(); Gen.drop(); end;
440 return nil;
441end;
442
443(* Frames *)
444
445proc tempItem*(var x: Item; t: ^Sym.Type; off: I64);
446var p: Diag.Pos;
447begin
448 p := x.pos;
449 x := {};
450 x.pos := p;
451 x.mode := mVar; x.typ := t; x.base := Gen.bFrame; x.off := off;
452 x.frame := t^.form # Sym.fSlice; (* a slice made here says where it points *)
453end;
454
455proc toSlot*(var x: Item): (I64, ERROR);
456var s: I64;
457begin
458 try value(x);
459 s := Gen.allocTemp(8, 8);
460 Gen.popVar(frameAdr(s), 8);
461 return s, nil;
462end;
463
464(* Copying *)
465
466(* x, copied to a temporary *)
467proc copyToTemp*(var x: Item): ERROR;
468var t: I64; f, g: ^Sym.Obj; a: Gen.Adr;
469begin
470 if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
471 t := Gen.allocTemp(x.typ^.size, x.typ^.align);
472 if (x.mode = mVar) and (x.base = Gen.bReg) then
473 (* a slice in registers, which has no address: its words stored *)
474 a := adrOf(x);
475 Gen.pushVar(a, 8, false, Gen.kWord);
476 Gen.popVar(frameAdr(t), 8);
477 a.off := 8;
478 Gen.pushVar(a, 8, false, Gen.kWord);
479 Gen.popVar(frameAdr(t + 8), 8);
480 tempItem(x, x.typ, t);
481 return nil;
482 end;
483 if x.mode = mWords then
484 (* the second result is on top, so it is popped first *)
485 f := x.typ^.fields; g := f^.next;
486 Gen.popVar(frameAdr(t + g^.val), scalarSize(g^.typ));
487 Gen.popVar(frameAdr(t + f^.val), scalarSize(f^.typ));
488 tempItem(x, x.typ, t);
489 return nil;
490 end;
491 try address(x);
492 Gen.copyTo(frameAdr(t), x.typ^.size);
493 tempItem(x, x.typ, t);
494 return nil;
495end;
496
497(* A slice made from an address on the stack and a length. *)
498proc sliceOf*(var x: Item; t: ^Sym.Type; len: I64);
499var s: I64;
500begin
501 s := Gen.allocTemp(16, 8);
502 Gen.popVar(frameAdr(s), 8);
503 Gen.pushConst(Gen.kWord, len);
504 Gen.popVar(frameAdr(s + 8), 8);
505 tempItem(x, t, s);
506end;
507
508(* An INT goes silently into an I64, and a UINT into a U64, losing
509 nothing on any target, wherever its value goes to one (report
510 section 5.10). *)
511proc widens*(s, t: ^Sym.Type): BOOL;
512begin
513 return ((s = Sym.tInt) and Sym.same(t, Sym.tI64)) or ((s = Sym.tUInt) and Sym.same(t, Sym.tU64));
514end;
515
516(* A U8, I8 or I16 goes silently into an INT, and a U8 or U16 into a
517 UINT: an INT or a UINT holds every value of theirs on any target,
518 since it is at least 16 bits (report sections 5.1 and 5.10). Only
519 one step: a U8 doesn't go into an I64. On the stack of values an
520 integer is kept extended to 64 bits as its type says (Gen), so the
521 value a U8 loads as is already the INT; only the type changes. *)
522proc smallWidens*(s, t: ^Sym.Type): BOOL;
523begin
524 if Sym.same(t, Sym.tInt) then
525 return Sym.same(s, Sym.tU8) or Sym.same(s, Sym.tI8) or Sym.same(s, Sym.tI16);
526 elsif Sym.same(t, Sym.tUInt) then
527 return Sym.same(s, Sym.tU8) or Sym.same(s, Sym.tU16);
528 end;
529 return false;
530end;
531
532(* An error at x, a U8, I8, I16 or U16 an operator made, which would
533 otherwise widen to t: the operator worked in x's type, and its
534 result may have wrapped, so the program says where to widen. *)
535proc madeNarrow(x: Item; t: ^Sym.Type): ERROR;
536begin
537 return Scan.markHelp(x.pos,
538 Diag.say("can't use {} as {}: an operator made it, in {}, where it may have wrapped",
539 [Fmt.str(Sym.typeName(x.typ)), Fmt.str(Sym.typeName(t)), Fmt.str(Sym.typeName(x.typ))]),
540 say1("convert an operand to {} first, so that the operator works in it", Sym.typeName(t)));
541end;
542
543(* Whether the several results s may be passed on as t: as many, each
544 of the same type or one that widens to it, as in return f(x) (report
545 section 5.10). An INT and an I64 have one layout here, so the values
546 pass as they are. *)
547proc resultsFit*(s, t: ^Sym.Type): BOOL;
548var f, g: ^Sym.Obj;
549begin
550 if not s^.tuple or not t^.tuple or (s^.len # t^.len) then return false; end;
551 f := s^.fields; g := t^.fields;
552 while f # nil do
553 if not Sym.same(f^.typ, g^.typ) and not widens(f^.typ, g^.typ) then return false; end;
554 f := f^.next; g := g^.next;
555 end;
556 return true;
557end;
558
559(* x is only read: a const parameter, a part of one, or a name a match
560 gives a field of one, or of a constant (report sections 7.4 and 8). A
561 part reached through a pointer or a slice in it isn't: what they point
562 at is the caller's to change, as through a value parameter's. *)
563proc onlyRead*(const x: Item): BOOL;
564begin
565 return (x.mode = mVar) and x.ro and (x.obj # nil) and x.obj^.isConst;
566end;
567
568(* Whether x is a constant, or part of one, held in read-only data *)
569proc ofConst(const x: Item): BOOL;
570begin
571 return (x.mode = mVar) and (x.obj # nil) and (x.obj^.cls = Sym.oConst);
572end;
573
574(* Another module's exported variable can be read, not changed, nor
575 handed to anything that could change it (report section 3); nor can
576 what is only read, above. *)
577proc notReadOnly*(const x: Item): ERROR;
578begin
579 if x.elemRo then
580 return Scan.markHelp(x.pos, say1("{} is read through a []const slice, and can't be changed", Diag.source(x.pos)),
581 "a []const slice's elements are only read: write them through a []T");
582 end;
583 if x.view and x.viewOver then try needSystem(x.pos, "writing a view over what holds more than integers and reals"); end;
584 if onlyRead(x) then
585 return Scan.markHelp(x.pos, say1("{} is only read here, and can't be changed", Diag.source(x.pos)),
586 "a const parameter, a constant, and the names a match gives their fields, are only read: take a var parameter to change it");
587 end;
588 if x.ro then
589 return Scan.markAt(x.pos, Diag.say("{} is {}'s, and can't be changed outside it",
590 [Fmt.str(Diag.source(x.pos)), Fmt.str(Scan.nameOf(x.obj^.home^.name))]));
591 end;
592 return nil;
593end;
594
595(* An error in x's type, with help that says what to write instead
596 unless hint is empty; if x is an argument, a note at the parameter it
597 goes to. *)
598proc mismatchHelp(x: Item; text, hint: []const U8): ERROR;
599begin
600 Diag.error(x.pos, text);
601 if LEN(hint) > 0 then Diag.help(hint); end;
602 if (passing # nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then
603 Diag.note(passing^.pos, say1("it goes to {}, declared here", Scan.nameOf(passing^.name)));
604 end;
605 return Scan.Failed;
606end;
607
608proc mismatch(x: Item; text: []const U8): ERROR;
609begin
610 return mismatchHelp(x, text, "");
611end;
612
613(* An error at x, which is a view, or part of one, and so has no
614 address: text, and help that says what to do instead. *)
615proc noAddress*(x: Item; text: []const U8): ERROR;
616begin
617 return Scan.markHelp(x.pos, text, "a view has no address, since it may be misaligned: copy it to a variable");
618end;
619
620(* The []const T of the slice type t, for a message *)
621proc constOf(t: ^Sym.Type): ^Sym.Type;
622var c: ^Sym.Type;
623begin
624 c := Sym.newType(Sym.fSlice, 16, 8);
625 c^.base := t^.base;
626 c^.rdonly := true;
627 return c;
628end;
629
630proc coerce*(var x: Item; t: ^Sym.Type): ERROR;
631var s: ^Sym.Type; tmp: I64; inFrame: BOOL; hint: []const U8;
632begin
633 if x.mode = mCond then try value(x); end;
634 s := x.typ;
635 if x.mode = mStr then
636 if (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) and not t^.rdonly then
637 return mismatchHelp(x, say1("a string is a []const U8, not {}", Sym.typeName(t)),
638 "its bytes are constant: take a []const U8 where they are only read, or copy them");
639 end;
640 if (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then
641 try address(x); sliceOf(x, t, x.val);
642 elsif (t^.form = Sym.fPtr) and (t^.base = Sym.tU8) then
643 try needSystem(x.pos, "a string as a ^U8");
644 try address(x); x.mode := mStack; x.typ := t;
645 elsif (t^.form = Sym.fArray) and (t^.base = Sym.tU8) and (t^.len >= x.val) then
646 tmp := Gen.allocTemp(t^.size, 1);
647 try address(x);
648 Gen.copyTo(frameAdr(tmp), x.val);
649 if t^.len > x.val then Gen.zeroVar(frameAdr(tmp + x.val), t^.len - x.val); end;
650 tempItem(x, t, tmp);
651 else return mismatch(x, say1("can't use a string as {}", Sym.typeName(t))); end;
652 return nil;
653 end;
654 if x.mode in {mType, mBuiltin, mNone, mCase} then return notValue(x); end;
655 if Sym.same(s, t) then return nil; end;
656 if widens(s, t) then x.typ := t; (* the same bits, on a 64-bit target *)
657 elsif smallWidens(s, t) then
658 if x.made then return madeNarrow(x, t); end;
659 if x.mode # mConst then try value(x); end; (* loaded as s, extended *)
660 x.typ := t;
661 elsif (s = Sym.tRConst) and (t^.form = Sym.fReal) then realTo(x, t);
662 elsif (s^.form = Sym.fConst) and (t^.form = Sym.fInt) then
663 if (x.mode = mConst) and not Sym.fits(x.val, t) then
664 return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))]));
665 end;
666 x.typ := t;
667 elsif (s^.form = Sym.fNil) and (t^.form in {Sym.fPtr, Sym.fProc, Sym.fError}) then
668 x.typ := t;
669 elsif (s^.form = Sym.fPtr) and (t^.form = Sym.fPtr) and t^.vol and not s^.vol
670 and Sym.same(s^.base, t^.base) then
671 x.typ := t;
672 elsif (s^.form = Sym.fSlice) and (t^.form = Sym.fSlice) and t^.rdonly and Sym.same(s^.base, t^.base) then
673 x.typ := t; (* a []T is a []const T as it is: its elements only read *)
674 elsif (s^.form = Sym.fSlice) and (t^.form = Sym.fSlice) and s^.rdonly and Sym.same(s^.base, t^.base) then
675 return mismatchHelp(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
676 "its elements are only read, and a []T could write them");
677 elsif (s^.form = Sym.fArray) and (t^.form = Sym.fSlice) and Sym.same(s^.base, t^.base) then
678 (* a slice of what is only read, a constant or a const parameter,
679 another module's array, or one read through a []const, is made
680 only as a []const *)
681 if (onlyRead(x) or ofConst(x)) and not t^.rdonly then
682 return mismatchHelp(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
683 say1("{} is only read: a slice of it is a []const", Diag.source(x.pos)));
684 end;
685 if x.ro and not onlyRead(x) and not t^.rdonly then
686 return Scan.markHelp(x.pos, Diag.say("{} is {}'s, and can't be changed outside it",
687 [Fmt.str(Diag.source(x.pos)), Fmt.str(Scan.nameOf(x.obj^.home^.name))]),
688 say1("it may be read as a {}", Sym.typeName(constOf(t))));
689 end;
690 if not t^.rdonly then try notReadOnly(x); end;
691 if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end;
692 if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end;
693 if x.view then return noAddress(x, "can't make a slice of a view"); end;
694 inFrame := x.frame;
695 try address(x);
696 sliceOf(x, t, s^.len);
697 x.frame := inFrame;
698 elsif (x.mode = mProc) and (t^.form # Sym.fProc) and (s^.base = nil) then
699 return Scan.markAt(x.pos, say1("{} is a procedure, and returns nothing", Diag.source(x.pos)));
700 elsif (x.mode = mProc) and (t^.form # Sym.fProc) then
701 return Scan.markHelp(x.pos,
702 say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
703 say1("to call it, write {}()", Diag.source(x.pos)));
704 elsif (widens(Sym.tInt, t) and smallWidens(s, Sym.tInt)) or (widens(Sym.tUInt, t) and smallWidens(s, Sym.tUInt)) then
705 (* a U8 widens one step, to INT, not on to an I64 *)
706 return Scan.markHelp(x.pos, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
707 Diag.say("{} widens to {} only as written, {}({})", [Fmt.str(Sym.typeName(s)),
708 Fmt.str(Sym.typeName(t)), Fmt.str(Sym.typeName(t)), Fmt.str(Diag.source(x.pos))]));
709 elsif (s^.form in {Sym.fSlice, Sym.fArray}) and (t^.form = Sym.fPtr) and Sym.same(s^.base, t^.base) then
710 (* the pointer and the length of a slice are two things *)
711 return mismatchHelp(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
712 Diag.say("PTR({}) is the address it starts at, a {}, and LEN({}) how many it has",
713 [Fmt.str(Diag.source(x.pos)), Fmt.str(Sym.typeName(t)), Fmt.str(Diag.source(x.pos))]));
714 elsif (s^.form = Sym.fPtr) and (t^.form = Sym.fSlice) and Sym.same(s^.base, t^.base) then
715 if x.mode = mVar then hint := say1("{}[0..n]", Diag.source(x.pos)); else hint := "p[0..n], for a pointer p,"; end;
716 return mismatchHelp(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
717 say1("a pointer has no length: {} is the slice of the n elements it starts", hint));
718 elsif widens(t, s) then
719 (* the other way, an I64 into an INT, is written: it may drop bits *)
720 return Scan.markHelp(x.pos, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
721 Diag.say("{} becomes {} only as written, {}({})", [Fmt.str(Sym.typeName(s)),
722 Fmt.str(Sym.typeName(t)), Fmt.str(Sym.typeName(t)), Fmt.str(Diag.source(x.pos))]));
723 else
724 return mismatch(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)));
725 end;
726 return nil;
727end;
728
729(* dst := src. The address of dst, if it has to be computed, is on the
730 stack already, under src's. *)
731proc assign*(var dst, src: Item): ERROR;
732begin
733 try coerce(src, dst.typ);
734 if Sym.isScalar(dst.typ) then
735 try value(src);
736 Gen.popVar(adrOf(dst), scalarSize(dst.typ));
737 else
738 if dst.vol or src.vol then return Scan.markAt(src.pos, "can't copy through a volatile pointer"); end;
739 if (src.mode = mVar) and (src.base = Gen.bReg) then try copyToTemp(src); end; (* a slice in registers *)
740 try address(src);
741 if dst.base = Gen.bStack then Gen.copyBlock(dst.typ^.size, dst.off);
742 else Gen.copyTo(adrOf(dst), dst.typ^.size); end;
743 end;
744 return nil;
745end;
746
747(* t's name, ending in a zero byte, for Rt.fail *)
748proc nameChunk(t: ^Sym.Type): INT;
749var s: []const U8; p: ^U8; n, c: INT;
750begin
751 s := Sym.typeName(t);
752 n := LEN(s);
753 p := Scan.grab(n + 1);
754 COPY(p[0..n], s);
755 p[n] := 0;
756 c := Chunk.newChunk(Chunk.secRodata, -1, -1);
757 Chunk.setData(c, p, n + 1, 1);
758 return c;
759end;
760
761(* Selectors *)
762
763proc deref*(var x: Item): ERROR;
764var t: ^Sym.Type;
765begin
766 t := x.typ;
767 if t^.form # Sym.fPtr then
768 return Scan.markAt(x.pos, say1("expected a pointer, found {}", Sym.typeName(t)));
769 end;
770 if t^.base = nil then
771 return Scan.markAt(x.pos, say1("{} points to a type never declared", Sym.typeName(t)));
772 end;
773 try value(x);
774 x.mode := mVar; x.base := Gen.bStack; x.off := 0; x.deref := true;
775 x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; x.elemRo := false;
776 x.view := false; x.frame := false;
777 return nil;
778end;
779
780(* A field of a packed record, of more than one byte's alignment, may
781 sit anywhere; it is read and written, but has no address and no
782 volatile access, which a machine that can't reach a misaligned word
783 couldn't make one access (report section 5.5). *)
784proc field*(var x: Item; f: ^Sym.Obj): ERROR;
785begin
786 if x.typ^.packd and (f^.typ^.align > 1) then
787 if x.vol then return Scan.markAt(x.pos, "a field of a packed record can't be volatile"); end;
788 x.odd := true;
789 end;
790 x.off := x.off + f^.val;
791 x.typ := f^.typ;
792 if x.typ^.form = Sym.fSlice then x.frame := false; end; (* a slice kept here points anywhere *)
793 return nil;
794end;
795
796proc indexPrep*(var x: Item): ERROR;
797begin
798 nilTest(x);
799 if x.mode = mStr then
800 try coerce(x, Sym.tConstBytes);
801 end;
802 if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fArray) then
803 return Scan.markAt(x.pos, "a pointer to an array is indexed as p^[i]");
804 end;
805 if x.typ^.form = Sym.fPtr then try value(x);
806 elsif not ((x.mode = mVar) and (x.typ^.form in {Sym.fArray, Sym.fSlice})) then
807 return Scan.markAt(x.pos, say1("expected an array, a slice or a pointer, found {}", what(x)));
808 end;
809 return nil;
810end;
811
812(* The index on top, times the size of an element *)
813proc scaleBy(s: I64);
814begin
815 if s # 1 then
816 Gen.pushConst(Gen.kWord, s);
817 Gen.op(Scan.sTimes, Gen.kWord, 8, true);
818 end;
819end;
820
821proc index*(var x, y: Item): ERROR;
822var t: ^Sym.Type; s: I64; isConst: BOOL;
823begin
824 t := x.typ;
825 s := t^.base^.size;
826 if not Sym.isInt(y.typ) then
827 return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y)));
828 end;
829 if t^.form = Sym.fPtr then
830 try needSystem(Diag.join(x.pos, y.pos), "indexing through a pointer");
831 isConst := y.mode = mConst;
832 try value(y);
833 if isConst or not ((s = 1) or (s = 2) or (s = 4) or (s = 8)) then
834 scaleBy(s);
835 Gen.op(Scan.sPlus, Gen.kWord, 8, false);
836 else Gen.indexPtr(s); end;
837 x.mode := mVar; x.base := Gen.bStack; x.off := 0;
838 x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; x.view := false;
839 x.elemRo := false;
840 elsif (t^.form = Sym.fArray) and (y.mode = mConst) then
841 if (y.val < 0) or (y.val >= t^.len) then
842 return Scan.markAt(y.pos, Diag.say("index {} is out of range for a length of {}", [Fmt.int(y.val), Fmt.int(t^.len)]));
843 end;
844 x.off := x.off + y.val * s;
845 elsif t^.form = Sym.fArray then
846 try value(y);
847 if checks then Gen.checkIndex(t^.len, y.pos); end;
848 if x.base = Gen.bStack then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false);
849 else Gen.indexArray(adrOf(x), s); x.off := 0; end;
850 x.base := Gen.bStack;
851 else
852 try value(y);
853 Gen.indexSlice(adrOf(x), s, 0, checks, y.pos);
854 x.base := Gen.bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false;
855 x.elemRo := t^.rdonly;
856 end;
857 x.typ := t^.base;
858 (* an element of an array lies where the array does; one of a slice or
859 through a pointer, and a slice kept in an element, anywhere *)
860 if (t^.form # Sym.fArray) or (x.typ^.form = Sym.fSlice) then x.frame := false; end;
861 return nil;
862end;
863
864proc sliceLo*(var lo: Item): ERROR;
865begin
866 if not Sym.isInt(lo.typ) then
867 return Scan.markAt(lo.pos, say1("an index is an integer, found {}", what(lo)));
868 end;
869 return value(lo);
870end;
871
872proc slice*(var x, lo, hi: Item): ERROR;
873var t, st: ^Sym.Type; tmp: I64; inFrame, roSlice: BOOL;
874begin
875 t := x.typ;
876 if not Sym.isInt(hi.typ) then
877 return Scan.markAt(hi.pos, say1("an index is an integer, found {}", what(hi)));
878 end;
879 if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end;
880 if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end;
881 if x.view then return noAddress(x, "can't make a slice of a view"); end;
882 (* a slice of another module's array, or of one read through a
883 []const, is a []const; of a const parameter's, a slice to read *)
884 roSlice := (t^.form = Sym.fSlice) and t^.rdonly;
885 if t^.form = Sym.fArray then
886 roSlice := x.ro or x.elemRo or ofConst(x); (* x.ro: another module's, or a const parameter's *)
887 end;
888 if t^.form = Sym.fPtr then try needSystem(x.pos, "a slice of a pointer"); end;
889 try value(hi);
890 inFrame := x.frame and (t^.form # Sym.fPtr);
891 tmp := Gen.allocTemp(16, 8);
892 if t^.form = Sym.fPtr then Gen.slicePtr(t^.base^.size, tmp, checks, lo.pos);
893 else Gen.slice(adrOf(x), t^.form = Sym.fArray, t^.len, t^.base^.size, tmp, checks, lo.pos); end;
894 st := Sym.newType(Sym.fSlice, 16, 8);
895 st^.base := t^.base;
896 st^.rdonly := roSlice;
897 tempItem(x, st, tmp);
898 x.frame := inFrame;
899 return nil;
900end;
901
902(* PTR(x), the address the slice x starts at, as the pointer type t
903 (report section 6.8). Of a slice it is its first word, read with no
904 check, so that an empty one gives what it holds, nil or an end, where
905 ADR(x[0]) would stop the program:
906
907 PTR(s) s's first word, as LEN(s) is its second
908
909 Of an array or a string it is the address of its first element, and
910 may be taken where slice above would make a slice of all of it. *)
911proc startOf*(var x: Item; t: ^Sym.Type): ERROR;
912begin
913 if x.typ^.form = Sym.fSlice then
914 if x.mode = mWords then
915 Gen.drop(); (* a call's two words: the length, on top, goes *)
916 x.mode := mStack;
917 else
918 if x.mode # mVar then try copyToTemp(x); end;
919 x.typ := t;
920 try value(x);
921 end;
922 x.typ := t;
923 x.frame := false;
924 return nil;
925 end;
926 if x.vol then
927 return Scan.markHelp(x.pos, "PTR can't take an array through a volatile pointer",
928 Diag.say("ADR({}[0]) is the address of its first element, a ^VOLATILE {}",
929 [Fmt.str(Diag.source(x.pos)), Fmt.str(Sym.typeName(t^.base))]));
930 end;
931 if x.odd then return Scan.markAt(x.pos, "PTR can't take a field of a packed record, which has no address"); end;
932 if x.view then return noAddress(x, "PTR can't take a view"); end;
933 if x.ro and not onlyRead(x) then
934 (* as in slice: another module's array isn't lent to be written *)
935 _ := notReadOnly(x);
936 Diag.help("a pointer to it could change it, as a slice of it could: copy it to a variable here first");
937 return Scan.Failed;
938 end;
939 try address(x);
940 x.mode := mStack;
941 x.typ := t;
942 x.frame := false;
943 return nil;
944end;
945
946(* Views, v.(T): the bytes of the variable v read and written as a T
947 (report section 6.9). A view is the item of v with T for its type:
948 the same place, so nothing is copied or computed to make one. What
949 is left is to check the type, and that T's bytes lie where v's room
950 is; and to mark the item a view, which may be misaligned, as a field
951 of a packed record may, so that nothing takes its address. *)
952
953(* Any bytes at all are a value of an integer, a real or a pointer,
954 and of a record or array made of them alone. A BOOL, an enumeration
955 or a set has bytes that are none of its values, and a slice,
956 variant, procedure or ERROR holds more than bytes can say. The type
957 in t that isn't plain data, or nil if all of it is. *)
958proc notPlain(t: ^Sym.Type): ^Sym.Type;
959var f: ^Sym.Obj; u: ^Sym.Type;
960begin
961 match t^.form of
962 | fInt, fReal, fPtr: return nil;
963 | fArray: return notPlain(t^.base);
964 | fRecord:
965 if t^.tuple then return t; end;
966 f := t^.fields;
967 while f # nil do
968 u := notPlain(f^.typ);
969 if u # nil then return u; end;
970 f := f^.next;
971 end;
972 return nil;
973 | else: return t;
974 end;
975end;
976
977(* What x must be to have a view made of it, as a T: a variable, not
978 volatile, and T a type of plain data. *)
979proc viewable(x: Item; t: ^Sym.Type): ERROR;
980var u: ^Sym.Type; text: []const U8;
981begin
982 (* another module's variable, ro, is one too, read and not written *)
983 if (x.mode # mVar) or not (x.isVar or x.ro) then
984 return Scan.markHelp(x.pos, "a view needs a variable",
985 "a constant, or the result of a call or an operator, has no bytes to view: copy it to a variable");
986 end;
987 if x.vol then
988 return Scan.markHelp(x.pos, "can't make a view of a volatile variable",
989 "a view may be misaligned, which can't be one access: reach a device through a ^VOLATILE pointer to a record");
990 end;
991 u := notPlain(t);
992 if u = nil then
993 if not Sym.isPlain(t) then try needSystem(x.pos, say1("a view as {}, which holds an address,", Sym.typeName(t))); end;
994 return nil;
995 end;
996 if u # t then
997 text := say2("can't view bytes as {}, which holds {}", Sym.typeName(t), Sym.typeName(u));
998 else
999 text := say1("can't view bytes as {}", Sym.typeName(t));
1000 end;
1001 if u^.form = Sym.fBool then
1002 return Scan.markHelp(x.pos, text, "some bytes are no BOOL: view an integer, and compare it with 0");
1003 elsif u^.form in {Sym.fEnum, Sym.fSet} then
1004 return Scan.markHelp(x.pos, text,
1005 say1("some bytes are no {}: view an integer, and convert it", Sym.typeName(u)));
1006 end;
1007 return Scan.markHelp(x.pos, text, "a view is an integer, a real or a pointer, or a record or array made of them");
1008end;
1009
1010(* What BYTES(x) refuses of its type, t, or of a slice's elements, t:
1011 a type a view may not take (report section 6.8), since bytes written
1012 through the slice must still be a value of it. In a record, the help
1013 names the field that holds it. *)
1014proc bytesType(x: Item; t: ^Sym.Type): ERROR;
1015var u: ^Sym.Type; f: ^Sym.Obj; text, hint: []const U8;
1016begin
1017 u := notPlain(t);
1018 if u = nil then return nil; end;
1019 if u # x.typ then
1020 text := say2("BYTES can't take {}, which holds {}", Sym.typeName(x.typ), Sym.typeName(u));
1021 else
1022 text := say1("BYTES can't take {}", Sym.typeName(u));
1023 end;
1024 hint := say1("some bytes are no {}: BYTES takes integers, reals and pointers, and records and arrays of them",
1025 Sym.typeName(u));
1026 if t^.form = Sym.fRecord then
1027 f := t^.fields;
1028 while (f # nil) and (notPlain(f^.typ) = nil) do f := f^.next; end;
1029 if f # nil then
1030 hint := Diag.say("its field {} is of type {}, and some bytes are no {}",
1031 [Fmt.str(Scan.nameOf(f^.name)), Fmt.str(Sym.typeName(f^.typ)), Fmt.str(Sym.typeName(u))]);
1032 end;
1033 end;
1034 return Scan.markHelp(x.pos, text, hint);
1035end;
1036
1037(* BYTES(x), the bytes of x as a []const U8 (report section 6.8), made as a
1038 slice of x is, refused where one is, and keeping x's frame mark, so
1039 that returnValue refuses the bytes of a local as a slice of one:
1040
1041 BYTES(s) {PTR(s), LEN(s) * SIZE(T)} for a slice s: []T
1042 BYTES(v) {ADR(v), SIZE(T)} for v: T, anything else
1043
1044 A slice's words are read as PTR and LEN read them, once it is where
1045 both can be read: a call's two words, or a slice reached through an
1046 address on the stack, go to a temporary first. *)
1047proc bytesOf*(var x: Item): ERROR;
1048var t, bt: ^Sym.Type; inFrame: BOOL; y: Item; s: I64;
1049begin
1050 if x.mode = mStr then
1051 return Scan.markHelp(x.pos, "BYTES can't take a string constant",
1052 "a string constant is only read: where a []U8 is wanted, the string itself will do");
1053 end;
1054 t := x.typ;
1055 inFrame := x.frame;
1056 if t^.form = Sym.fSlice then
1057 try bytesType(x, t^.base);
1058 if not t^.rdonly and not Sym.isPlain(t^.base) then try needSystem(x.pos, "BYTES of what holds an address"); end;
1059 if (x.mode # mVar) or (x.base = Gen.bStack) then try copyToTemp(x); end;
1060 y := x;
1061 y.typ := Sym.tInt;
1062 try value(y); (* its first word, where it starts *)
1063 x.off := x.off + 8;
1064 x.typ := Sym.tInt;
1065 try value(x); (* its second, the number of elements *)
1066 scaleBy(t^.base^.size);
1067 s := Gen.allocTemp(16, 8);
1068 Gen.popVar(frameAdr(s + 8), 8);
1069 Gen.popVar(frameAdr(s), 8);
1070 if t^.rdonly then
1071 (* the bytes of a []const T are only read too: a []const U8 *)
1072 bt := Sym.newType(Sym.fSlice, 16, 8);
1073 bt^.base := Sym.tU8;
1074 bt^.rdonly := true;
1075 tempItem(x, bt, s);
1076 else
1077 tempItem(x, Sym.tBytes, s);
1078 end;
1079 x.frame := inFrame;
1080 return nil;
1081 end;
1082 try notReadOnly(x);
1083 if (x.mode # mVar) or not x.isVar then
1084 return Scan.markHelp(x.pos, "BYTES needs a variable",
1085 "a constant, or the result of a call or an operator, has no bytes of its own: copy it to a variable");
1086 end;
1087 if x.vol then
1088 return Scan.markHelp(x.pos, "BYTES can't take a volatile variable",
1089 "reading and writing its bytes through a slice wouldn't be volatile accesses");
1090 end;
1091 if x.odd then return Scan.markAt(x.pos, "BYTES can't take a field of a packed record, which has no address"); end;
1092 if x.view then return noAddress(x, "BYTES can't take a view"); end;
1093 try bytesType(x, t);
1094 if not Sym.isPlain(t) then try needSystem(x.pos, "BYTES of what holds an address"); end;
1095 try address(x);
1096 sliceOf(x, Sym.tBytes, t^.size);
1097 x.frame := inFrame;
1098 return nil;
1099end;
1100
1101(* x becomes the view of itself as a T, its type changed and nothing
1102 else: the bytes are where x's are. A variable in a register has no
1103 bytes to view, so it goes to memory. *)
1104proc becomeView(var x: Item; t: ^Sym.Type);
1105begin
1106 demote(x);
1107 x.typ := t;
1108 x.view := true;
1109end;
1110
1111(* v.(T), where v is not an element: T must fit in v itself. *)
1112proc view*(var x: Item; t: ^Sym.Type): ERROR;
1113var over: BOOL;
1114begin
1115 try viewable(x, t);
1116 over := not Sym.isPlain(x.typ);
1117 if t^.size > x.typ^.size then
1118 return Scan.markAt(x.pos, Diag.say("a view of {} bytes doesn't fit in {}, of {}",
1119 [Fmt.int(t^.size), Fmt.str(Sym.typeName(x.typ)), Fmt.int(x.typ^.size)]));
1120 end;
1121 becomeView(x, t);
1122 x.viewOver := over;
1123 return nil;
1124end;
1125
1126(* The number of elements of size s that n bytes reach into, at least
1127 one: those of a[i] up to a[i + k - 1]. *)
1128proc elementsFor(n, s: I64): I64;
1129begin
1130 if (s = 0) or (n <= s) then return 1; end;
1131 return (n + s - 1) div s;
1132end;
1133
1134(* a[i].(T): x is the array, slice or pointer, y the index. T must lie
1135 from a[i] to a's end: in an array of n elements, k of them from i on,
1136 so i is below n - k + 1; a slice's length is known only as the
1137 program runs, which checks that length - i, at least 1 since i is
1138 below it, is at least k. Through a pointer, no check: p[i] has none
1139 (report section 6.9). *)
1140proc indexView*(var x, y: Item; t: ^Sym.Type): ERROR;
1141var at: ^Sym.Type; s, k: I64; over: BOOL;
1142begin
1143 at := x.typ;
1144 s := at^.base^.size;
1145 k := elementsFor(t^.size, s);
1146 if not Sym.isInt(y.typ) then
1147 return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y)));
1148 end;
1149 if (at^.form = Sym.fArray) and (k > at^.len) then
1150 return Scan.markAt(Diag.join(x.pos, y.pos), Diag.say("a view of {} bytes doesn't fit in {}, of {}",
1151 [Fmt.int(t^.size), Fmt.str(Sym.typeName(at)), Fmt.int(at^.size)]));
1152 end;
1153 if (at^.form = Sym.fArray) and (y.mode = mConst) then
1154 if (y.val < 0) or (y.val > at^.len - k) then
1155 return Scan.markAt(y.pos, Diag.say("a view of {} bytes at index {} runs past a length of {}",
1156 [Fmt.int(t^.size), Fmt.int(y.val), Fmt.int(at^.len)]));
1157 end;
1158 try index(x, y);
1159 elsif (at^.form = Sym.fArray) and checks then
1160 (* as index does, with the view's check in place of i < n *)
1161 try value(y);
1162 Gen.checkView(at^.len, at^.len - k + 1, y.pos);
1163 if x.base = Gen.bStack then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false);
1164 else Gen.indexArray(adrOf(x), s); x.off := 0; end;
1165 x.base := Gen.bStack;
1166 x.typ := at^.base;
1167 elsif at^.form = Sym.fSlice then
1168 try value(y);
1169 Gen.indexSlice(adrOf(x), s, k - 1, checks, y.pos);
1170 x.base := Gen.bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false;
1171 x.elemRo := at^.rdonly;
1172 x.typ := at^.base;
1173 else
1174 try index(x, y);
1175 end;
1176 try viewable(x, t);
1177 over := not Sym.isPlain(x.typ); (* the element's *)
1178 becomeView(x, t);
1179 x.viewOver := over;
1180 return nil;
1181end;
1182
1183(* Operators *)
1184
1185proc neg*(var x: Item): ERROR;
1186begin
1187 if x.typ^.form = Sym.fReal then
1188 if x.mode = mConst then x.val := x.val xor MinI64;
1189 else try value(x); Gen.neg(Gen.kindOf(x.typ), 8, false); end;
1190 elsif Sym.isInt(x.typ) then
1191 if (x.mode = mConst) and (x.typ^.form = Sym.fConst) and (x.val = MinI64) then
1192 return Scan.markAt(x.pos, "the constant is too big for I64");
1193 elsif x.mode = mConst then x.val := cut(-x.val, x.typ);
1194 else try value(x); Gen.neg(Gen.kWord, intSize(x.typ), signed(x.typ)); end;
1195 x.made := true;
1196 else return Scan.markAt(x.pos, say1("can't negate {}", Sym.typeName(x.typ))); end;
1197 return nil;
1198end;
1199
1200proc notOp*(var x: Item): ERROR;
1201var L: INT;
1202begin
1203 if Sym.isInt(x.typ) then
1204 return Scan.markHelp(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)), "the bits of an integer flip with ~");
1205 end;
1206 if x.typ^.form # Sym.fBool then
1207 return Scan.markAt(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)));
1208 end;
1209 if x.mode = mConst then x.val := 1 - x.val;
1210 elsif x.mode = mCond then
1211 x.rel := negated(x.rel);
1212 L := x.fj; x.fj := x.tj; x.tj := L;
1213 else try value(x); Gen.notBool(); end;
1214 return nil;
1215end;
1216
1217proc complement*(var x: Item): ERROR;
1218begin
1219 if x.typ^.form = Sym.fBool then
1220 return Scan.markHelp(x.pos, say1("\"~\" needs an integer, found {}", what(x)), "a BOOL is negated with not");
1221 end;
1222 if not Sym.isInt(x.typ) then
1223 return Scan.markAt(x.pos, say1("\"~\" needs an integer, found {}", what(x)));
1224 end;
1225 if x.mode = mConst then x.val := cut(~x.val, x.typ);
1226 else try value(x); Gen.complement(intSize(x.typ), signed(x.typ)); end;
1227 x.made := true;
1228 return nil;
1229end;
1230
1231(* Arrays, slices and strings, which = and # compare element by element *)
1232proc isSeq(t: ^Sym.Type): BOOL;
1233begin
1234 return t^.form in {Sym.fStr, Sym.fArray, Sym.fSlice};
1235end;
1236
1237proc elemOf(t: ^Sym.Type): ^Sym.Type;
1238begin
1239 if t^.form = Sym.fStr then return Sym.tU8; end;
1240 return t^.base;
1241end;
1242
1243(* An array, slice or string as a slice in a temporary, for comparing. *)
1244proc seqSlice(var x: Item): ERROR;
1245var t: ^Sym.Type;
1246begin
1247 t := Sym.newType(Sym.fSlice, 16, 8);
1248 t^.base := elemOf(x.typ);
1249 if x.typ^.form = Sym.fSlice then
1250 (* a temporary, as a slice just cut is, nothing else can change *)
1251 if (x.mode # mVar) or (x.base # Gen.bFrame) or x.isVar or (x.obj # nil) then try copyToTemp(x); end;
1252 x.typ := t;
1253 elsif x.mode = mStr then
1254 try address(x); sliceOf(x, t, x.val);
1255 else
1256 if x.vol then return Scan.markAt(x.pos, "can't compare through a volatile pointer"); end;
1257 try address(x); sliceOf(x, t, x.typ^.len);
1258 end;
1259 return nil;
1260end;
1261
1262(* x, a BOOL, as a condition: a value compared with 0 if it isn't one *)
1263proc makeCond(var x: Item): ERROR;
1264begin
1265 if x.mode = mCond then return nil; end;
1266 try value(x);
1267 Gen.pushConst(Gen.kWord, 0);
1268 x.mode := mCond;
1269 x.rel := Scan.sNeq;
1270 x.relSigned := false;
1271 x.fj := Gen.NoLabel;
1272 x.tj := Gen.NoLabel;
1273 return nil;
1274end;
1275
1276proc op1*(op: Scan.Sym; var x: Item; var L: INT): ERROR;
1277begin
1278 L := Gen.NoLabel;
1279 if ((op = Scan.sAnd) or (op = Scan.sOr)) and (x.typ^.form = Sym.fBool) then
1280 if x.mode = mConst then
1281 (* false and y, true or y: y isn't evaluated, so its code,
1282 about to be made, is jumped over to L, which op2 places *)
1283 if (x.val = 1) # (op = Scan.sAnd) then Gen.jump(L); end;
1284 return nil; (* folded by op2 *)
1285 end;
1286 try makeCond(x);
1287 if op = Scan.sAnd then
1288 Gen.jumpOut(negated(x.rel), x.relSigned, x.fj);
1289 Gen.fix(x.tj);
1290 x.tj := Gen.NoLabel;
1291 else
1292 Gen.jumpOut(x.rel, x.relSigned, x.tj);
1293 Gen.fix(x.fj);
1294 x.fj := Gen.NoLabel;
1295 end;
1296 elsif ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(x.typ) then
1297 try seqSlice(x);
1298 elsif (op = Scan.sPlus) and (x.mode = mStr) then
1299 (* two string constants to be joined: nothing to compute *)
1300 elsif (op = Scan.sPlus) and isSeq(x.typ) then
1301 return Scan.markHelp(x.pos, say1("+ doesn't join {}", what(x)), "strings are joined in a Buf: Buf.str(b, s)");
1302 elsif x.mode in {mType, mBuiltin, mNone, mCase, mStr} then
1303 return notValue(x);
1304 elsif x.mode # mConst then
1305 try value(x);
1306 end;
1307 return nil;
1308end;
1309
1310proc log2(v: I64): INT;
1311var n: INT;
1312begin
1313 n := 0;
1314 while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end;
1315 if v # 1 then n := -1; end;
1316 return n;
1317end;
1318
1319(* Whether a op b, for + - *, overflows an I64: an untyped constant
1320 doesn't wrap, it is an error (report section 4). *)
1321proc overflows(op: Scan.Sym; a, b: I64): BOOL;
1322begin
1323 match op of
1324 | sPlus: return ((b > 0) and (a > MaxI64 - b)) or ((b < 0) and (a < MinI64 - b));
1325 | sMinus: return ((b < 0) and (a > MaxI64 + b)) or ((b > 0) and (a < MinI64 + b));
1326 | sTimes:
1327 if (a = 0) or (b = 0) then return false; end;
1328 if a = -1 then return b = MinI64; end;
1329 if b = -1 then return a = MinI64; end;
1330 return (a * b) div b # a;
1331 | else: return false;
1332 end;
1333end;
1334
1335(* A type's width in bits; an untyped constant's is an I64's *)
1336proc bits(t: ^Sym.Type): I64;
1337begin
1338 return t^.size * 8;
1339end;
1340
1341proc foldInt(op: Scan.Sym; a, b: I64; t: ^Sym.Type; p: Diag.Pos): (I64, ERROR);
1342var u: BOOL;
1343begin
1344 u := (t^.form = Sym.fInt) and not t^.signed;
1345 if (t^.form = Sym.fConst) and overflows(op, a, b) then
1346 return 0, Scan.markAt(p, "the constant is too big for I64");
1347 end;
1348 match op of
1349 | sPlus: return a + b, nil;
1350 | sMinus: return a - b, nil;
1351 | sTimes: return a * b, nil;
1352 | sDiv, sMod:
1353 if b = 0 then return 0, Scan.markAt(p, "division by zero"); end;
1354 if u then
1355 if op = Scan.sDiv then return I64(U64(a) div U64(b)), nil; end;
1356 return I64(U64(a) mod U64(b)), nil;
1357 end;
1358 if (b = -1) and (a = I64(-1) shl (bits(t) - 1)) then return 0, Scan.markAt(p, "division overflows"); end;
1359 if op = Scan.sDiv then return a div b, nil; end;
1360 return a mod b, nil;
1361 | sAmp: return a & b, nil;
1362 | sBar: return a | b, nil;
1363 | sXor: return a xor b, nil;
1364 | sShl: return a shl (b & (bits(t) - 1)), nil;
1365 | sShr:
1366 if u then return I64(U64(a) shr (b & (bits(t) - 1))), nil; end;
1367 return a shr (b & (bits(t) - 1)), nil;
1368 | sEql: return bit(a = b), nil;
1369 | sNeq: return bit(a # b), nil;
1370 | sLss:
1371 if u then return bit(U64(a) < U64(b)), nil; end;
1372 return bit(a < b), nil;
1373 | sLeq:
1374 if u then return bit(U64(a) <= U64(b)), nil; end;
1375 return bit(a <= b), nil;
1376 | sGtr:
1377 if u then return bit(U64(a) > U64(b)), nil; end;
1378 return bit(a > b), nil;
1379 | sGeq:
1380 if u then return bit(U64(a) >= U64(b)), nil; end;
1381 return bit(a >= b), nil;
1382 | else: return 0, Scan.markAt(p, "bad operator");
1383 end;
1384end;
1385
1386(* Folds x op y, of the real type t: an F32 rounded at each step, as
1387 the machine would. *)
1388proc foldReal(op: Scan.Sym; x, y: Item; t: ^Sym.Type; var r: Item): BOOL;
1389var a, b: F64; ok: BOOL;
1390begin
1391 a := realOf(x); b := realOf(y);
1392 ok := true;
1393 match op of
1394 | sPlus: makeReal(r, a + b);
1395 | sMinus: makeReal(r, a - b);
1396 | sTimes: makeReal(r, a * b);
1397 | sSlash: makeReal(r, a / b);
1398 | sEql: makeConst(r, Sym.tBool, bit(a = b));
1399 | sNeq: makeConst(r, Sym.tBool, bit(a # b));
1400 | sLss: makeConst(r, Sym.tBool, bit(a < b));
1401 | sLeq: makeConst(r, Sym.tBool, bit(a <= b));
1402 | sGtr: makeConst(r, Sym.tBool, bit(a > b));
1403 | sGeq: makeConst(r, Sym.tBool, bit(a >= b));
1404 | else: ok := false;
1405 end;
1406 if r.typ^.form = Sym.fReal then realTo(r, t); end;
1407 return ok;
1408end;
1409
1410(* and, or and not are for BOOLs; &, |, xor and ~ for the bits of
1411 integers: x is the wrong kind for op, and the message names the
1412 operator it may have meant *)
1413proc wrongLogic(op: Scan.Sym; var x: Item): ERROR;
1414var bitsOf: []const U8;
1415begin
1416 bitsOf := "the bits of integers take ";
1417 if (op = Scan.sAnd) and Sym.isInt(x.typ) then
1418 return Scan.markHelp(x.pos, say1("\"and\" needs BOOLs, found {}", what(x)), say1("{}&", bitsOf));
1419 elsif (op = Scan.sOr) and Sym.isInt(x.typ) then
1420 return Scan.markHelp(x.pos, say1("\"or\" needs BOOLs, found {}", what(x)), say1("{}|", bitsOf));
1421 elsif op = Scan.sAmp then
1422 return Scan.markHelp(x.pos, say1("\"&\" needs integers, found {}", what(x)), "BOOLs take and");
1423 elsif op = Scan.sBar then
1424 return Scan.markHelp(x.pos, say1("\"|\" needs integers, found {}", what(x)), "BOOLs take or");
1425 elsif op = Scan.sXor then
1426 return Scan.markHelp(x.pos, say1("\"xor\" needs integers, found {}", what(x)), "BOOLs that differ are #");
1427 end;
1428 return Scan.markAt(x.pos, say2("{} needs BOOLs, found {}", Scan.symText(op), what(x)));
1429end;
1430
1431(* x + y, of two string constants: one string, in a chunk of its own
1432 (report section 4) *)
1433proc joinStr(var x, y: Item): ERROR;
1434var p: ^U8; c, xs, ys, xl, yl: INT;
1435begin
1436 if y.mode # mStr then
1437 return Scan.markAt(y.pos, say1("\"+\" joins two strings, found {}", what(y)));
1438 end;
1439 xs := Chunk.chunks[x.chunk].start;
1440 ys := Chunk.chunks[y.chunk].start;
1441 xl := INT(x.val);
1442 yl := INT(y.val);
1443 p := Scan.grab(xl + yl + 1);
1444 COPY(p[0..xl], Chunk.rodata[xs..xs + xl]);
1445 COPY(p[xl..xl + yl + 1], Chunk.rodata[ys..ys + yl + 1]);
1446 c := Chunk.newChunk(Chunk.secRodata, -1, -1);
1447 Chunk.setData(c, p, xl + yl + 1, 1);
1448 x.chunk := c;
1449 x.val := x.val + y.val;
1450 return nil;
1451end;
1452
1453(* A set's operations, as operations on its bits: the two values on top *)
1454proc setOp(op: Scan.Sym);
1455begin
1456 match op of
1457 | sPlus: Gen.op(Scan.sBar, Gen.kWord, 8, false);
1458 | sTimes: Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1459 | sMinus: Gen.complement(8, false); Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1460 | sLeq, sGeq:
1461 (* x <= y has no bit of x outside y *)
1462 if op = Scan.sGeq then Gen.swap(); end;
1463 Gen.complement(8, false);
1464 Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1465 Gen.pushConst(Gen.kWord, 0);
1466 Gen.compare(Scan.sEql, Gen.kWord, false);
1467 | sIn:
1468 Gen.swap();
1469 Gen.op(Scan.sShr, Gen.kWord, 8, false);
1470 Gen.pushConst(Gen.kWord, 1);
1471 Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1472 | else: Gen.compare(op, Gen.kWord, false);
1473 end;
1474end;
1475
1476(* The operators the arithmetic of integers, of reals and of sets
1477 stand for, and the comparisons *)
1478proc intOp(op: Scan.Sym): BOOL;
1479begin
1480 return isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod,
1481 Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr]);
1482end;
1483
1484proc doesntApply(op: Scan.Sym; x, y: Item; t: ^Sym.Type): ERROR;
1485begin
1486 return Scan.markAt(Diag.join(x.pos, y.pos), say2("{} doesn't apply to {}", Scan.symText(op), Sym.typeName(t)));
1487end;
1488
1489proc op2*(op: Scan.Sym; var x, y: Item; L: INT): ERROR;
1490var xt, yt, t, e: ^Sym.Type; r: Item; scale: INT; isPtr: BOOL; a, b, v: I64;
1491begin
1492 xt := x.typ; yt := y.typ;
1493 if y.mode in {mType, mBuiltin, mNone, mCase} then return notValue(y); end;
1494 if (op = Scan.sPlus) and (x.mode = mStr) then return joinStr(x, y); end;
1495
1496 if (op = Scan.sAnd) or (op = Scan.sOr) then
1497 if xt^.form # Sym.fBool then return wrongLogic(op, x); end;
1498 if yt^.form # Sym.fBool then return wrongLogic(op, y); end;
1499 if (x.mode = mConst) and (y.mode = mConst) then
1500 if op = Scan.sAnd then x.val := x.val & y.val; else x.val := x.val | y.val; end;
1501 Gen.fix(L); (* op1's jump, if it made one, over no code *)
1502 elsif x.mode = mConst then
1503 (* true and y, false or y: y; else x, and y's code, which op1's
1504 jump to L passes over, is never run *)
1505 if (x.val = 1) = (op = Scan.sAnd) then x := y;
1506 else try discard(y); Gen.fix(L); end;
1507 else
1508 try makeCond(y);
1509 if op = Scan.sAnd then x.fj := Gen.joinJumps(x.fj, y.fj); x.tj := y.tj;
1510 else x.tj := Gen.joinJumps(x.tj, y.tj); x.fj := y.fj; end;
1511 x.rel := y.rel;
1512 x.relSigned := y.relSigned;
1513 end;
1514 return nil;
1515 end;
1516
1517 if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (xt^.form = Sym.fBool) then return wrongLogic(op, x); end;
1518 if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (yt^.form = Sym.fBool) then return wrongLogic(op, y); end;
1519
1520 (* the lengths, then the bytes, LEN * SIZE(T) of them: the elements
1521 are of types whose bytes say all there is to their values *)
1522 if ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(xt) then
1523 e := elemOf(xt);
1524 if not isSeq(yt) then
1525 return Scan.markAt(Diag.join(x.pos, y.pos), say1("can't compare an array with {}", Sym.typeName(yt)));
1526 elsif not Sym.same(e, elemOf(yt)) then
1527 return Scan.markAt(Diag.join(x.pos, y.pos),
1528 say2("can't compare an array of {} with one of {}", Sym.typeName(e), Sym.typeName(elemOf(yt))));
1529 end;
1530 if e^.form = Sym.fReal then
1531 return Scan.markHelp(Diag.join(x.pos, y.pos),
1532 say1("can't compare arrays of reals with {}", Scan.symText(op)),
1533 "-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop");
1534 elsif not (e^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fPtr}) then
1535 return Scan.markHelp(Diag.join(x.pos, y.pos),
1536 say2("can't compare arrays of {} with {}", Sym.typeName(e), Scan.symText(op)), "write a loop");
1537 end;
1538 try seqSlice(y);
1539 Gen.compareSeq(x.off, y.off, log2(e^.size), op = Scan.sEql);
1540 makeConst(x, Sym.tBool, 0);
1541 x.mode := mStack;
1542 return nil;
1543 end;
1544
1545 (* the type of the result, and the checks *)
1546 t := nil; scale := 1; isPtr := false;
1547 if Sym.isInt(xt) and Sym.isInt(yt) then
1548 if op = Scan.sSlash then
1549 return Scan.markHelp(Diag.join(x.pos, y.pos), "\"/\" divides reals, not integers",
1550 say2("to divide integers, write {} div {}", Diag.source(x.pos), Diag.source(y.pos)));
1551 end;
1552 if (op = Scan.sShl) or (op = Scan.sShr) then
1553 if xt^.form = Sym.fConst then t := Sym.tConst; else t := xt; end;
1554 elsif (xt^.form = Sym.fConst) and (yt^.form = Sym.fConst) then t := Sym.tConst;
1555 elsif xt^.form = Sym.fConst then
1556 if (x.mode = mConst) and not Sym.fits(x.val, yt) then
1557 return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(yt))]));
1558 end;
1559 t := yt;
1560 elsif yt^.form = Sym.fConst then
1561 if (y.mode = mConst) and not Sym.fits(y.val, xt) then
1562 return Scan.markAt(y.pos, Diag.say("{} doesn't fit {}", [Fmt.int(y.val), Fmt.str(Sym.typeName(xt))]));
1563 end;
1564 t := xt;
1565 elsif Sym.same(xt, yt) then t := xt;
1566 elsif widens(xt, yt) or widens(yt, xt) then
1567 (* an INT meeting an I64 widens to it, a UINT to a U64 (report
1568 section 6.1): the same 64 bits here, so only the type changes *)
1569 if widens(xt, yt) then t := yt; else t := xt; end;
1570 elsif smallWidens(xt, yt) or smallWidens(yt, xt) then
1571 (* a U8, I8 or I16 meeting an INT widens to it, unless an
1572 operator made it (report section 6.1); each operand is
1573 loaded as its own type, extended, so t is all that changes *)
1574 if x.made and smallWidens(xt, yt) then return madeNarrow(x, yt); end;
1575 if y.made and smallWidens(yt, xt) then return madeNarrow(y, xt); end;
1576 if smallWidens(xt, yt) then t := yt; else t := xt; end;
1577 else return mismatchOps(x, y, xt, yt); end;
1578 if not intOp(op) then return doesntApply(op, x, y, t); end;
1579 elsif (xt^.form = Sym.fReal) and (yt^.form = Sym.fReal) then
1580 if not (isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash])) then
1581 return doesntApply(op, x, y, xt);
1582 end;
1583 if xt = Sym.tRConst then t := yt;
1584 elsif (yt = Sym.tRConst) or Sym.same(xt, yt) then t := xt;
1585 else return mismatchOps(x, y, xt, yt); end;
1586 if (x.mode = mConst) and (x.typ # t) then realTo(x, t); end;
1587 if (y.mode = mConst) and (y.typ # t) then realTo(y, t); end;
1588 elsif (xt^.form = Sym.fBool) and (yt^.form = Sym.fBool) then
1589 if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end;
1590 t := Sym.tBool;
1591 elsif (xt^.form = Sym.fPtr) and Sym.isInt(yt) and ((op = Scan.sPlus) or (op = Scan.sMinus)) then
1592 try needSystem(Diag.join(x.pos, y.pos), "a pointer's arithmetic");
1593 t := xt; scale := INT(xt^.base^.size); isPtr := true;
1594 if y.mode = mConst then y.typ := Sym.tInt; end;
1595 elsif (xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and (op = Scan.sMinus) then
1596 if not Sym.same(xt, yt) then return mismatchOps(x, y, xt, yt); end;
1597 t := Sym.tInt; scale := INT(xt^.base^.size); isPtr := true;
1598 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
1599 if not isRel(op) then return doesntApply(op, x, y, xt); end;
1600 if (xt^.form in {Sym.fProc, Sym.fError}) or (yt^.form in {Sym.fProc, Sym.fError}) then
1601 if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end;
1602 end;
1603 if (xt^.form # Sym.fNil) and (yt^.form # Sym.fNil) and not Sym.same(xt, yt) then
1604 if not ((xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and Sym.same(xt^.base, yt^.base)) then
1605 return mismatchOps(x, y, xt, yt);
1606 end;
1607 end;
1608 t := Sym.tU64;
1609 elsif (xt^.form = Sym.fEnum) and Sym.same(xt, yt) then
1610 if not isRel(op) then return doesntApply(op, x, y, xt); end;
1611 t := xt;
1612 elsif (xt^.form = Sym.fSet) and Sym.same(xt, yt) then
1613 if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sMinus, Scan.sEql, Scan.sNeq, Scan.sLeq, Scan.sGeq]) then
1614 return doesntApply(op, x, y, xt);
1615 end;
1616 t := xt;
1617 elsif (op = Scan.sIn) and (yt^.form = Sym.fSet) and Sym.same(xt, yt^.base) then
1618 t := yt;
1619 else
1620 return mismatchOps(x, y, xt, yt);
1621 end;
1622
1623 (* constants *)
1624 if (x.mode = mConst) and (y.mode = mConst) and not isPtr then
1625 if t^.form = Sym.fReal then
1626 if not foldReal(op, x, y, t, r) then return doesntApply(op, x, y, xt); end;
1627 x := r;
1628 elsif t^.form = Sym.fSet then
1629 a := x.val; b := y.val;
1630 match op of
1631 | sPlus: makeConst(x, t, a | b);
1632 | sTimes: makeConst(x, t, a & b);
1633 | sMinus: makeConst(x, t, a & ~b);
1634 | sIn: makeConst(x, Sym.tBool, (b shr a) & 1);
1635 | sLeq: makeConst(x, Sym.tBool, bit((a & ~b) = 0));
1636 | sGeq: makeConst(x, Sym.tBool, bit((b & ~a) = 0));
1637 | else: makeConst(x, Sym.tBool, bit((a = b) = (op = Scan.sEql)));
1638 end;
1639 elsif isRel(op) then
1640 v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos));
1641 makeConst(x, Sym.tBool, v);
1642 else
1643 v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos));
1644 makeConst(x, t, cut(v, t));
1645 x.made := true;
1646 end;
1647 return nil;
1648 end;
1649
1650 (* x and y on the stack, x under y; a constant x goes on after y, and
1651 is left on top where the order doesn't matter, as Gen takes a
1652 constant best on the right: 0.25 * e is mulsd xmm8, [0.25] *)
1653 try value(y);
1654 if x.mode = mConst then
1655 try value(x);
1656 if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sAmp, Scan.sBar, Scan.sXor]) or isPtr then Gen.swap(); end;
1657 end;
1658
1659 if t^.form = Sym.fReal then
1660 if isRel(op) then Gen.compare(op, Gen.kindOf(t), false);
1661 else Gen.op(op, Gen.kindOf(t), 8, false); end;
1662 elsif t^.form = Sym.fSet then
1663 setOp(op);
1664 elsif isRel(op) then
1665 x.mode := mCond;
1666 x.rel := op;
1667 x.relSigned := signed(t);
1668 x.fj := Gen.NoLabel;
1669 x.tj := Gen.NoLabel;
1670 x.typ := Sym.tBool;
1671 return nil;
1672 elsif isPtr then
1673 if t # Sym.tInt then scaleBy(scale); end;
1674 Gen.op(op, Gen.kWord, 8, false);
1675 if (t = Sym.tInt) and (scale # 1) then
1676 Gen.pushConst(Gen.kWord, scale);
1677 Gen.op(Scan.sDiv, Gen.kWord, 8, true);
1678 end;
1679 else
1680 Gen.op(op, Gen.kindOf(t), intSize(t), signed(t));
1681 end;
1682 x.mode := mStack;
1683 if isRel(op) or (op = Scan.sIn) then x.typ := Sym.tBool; else x.typ := t; end;
1684 x.made := true;
1685 return nil;
1686end;
1687
1688(* INT and UINT, the integers as big as an address, through which
1689 integers and pointers convert (report section 6.7) *)
1690proc isWord*(t: ^Sym.Type): BOOL;
1691begin
1692 return Sym.same(t, Sym.tInt) or Sym.same(t, Sym.tUInt);
1693end;
1694
1695(* The x of ROL(x, n), left, or ROR(x, n), checked: of an unsigned
1696 integer type, since a rotation goes round within a width, which an
1697 untyped constant hasn't (report section 6.1). It is loaded, unless a
1698 constant, before n is read, as the left of an operator is by op1. *)
1699proc rotand*(var x: Item; left: BOOL): ERROR;
1700var name, s: []const U8;
1701begin
1702 if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then return notValue(x); end;
1703 if left then name := "ROL"; else name := "ROR"; end;
1704 s := say2("{} needs an unsigned integer, found {}", name, what(x));
1705 if x.typ = Sym.tConst then
1706 return Scan.markHelp(x.pos, s,
1707 say1("an untyped constant has no width to rotate in: give it a type, as in U32({})", Diag.source(x.pos)));
1708 end;
1709 if (x.typ^.form # Sym.fInt) or x.typ^.signed then return Scan.markAt(x.pos, s); end;
1710 if x.mode # mConst then try value(x); end;
1711 return nil;
1712end;
1713
1714(* ROL(x, n), left, or ROR(x, n): x, of rotand, rotated by n modulo its
1715 width. Of two constants it is folded: right by k is left by w - k,
1716 and left by k is x shl k | x shr (w - k), cut to the width. *)
1717proc rotate*(var x, n: Item; left: BOOL): ERROR;
1718var w, k: I64; v: U64;
1719begin
1720 if n.mode in {mType, mBuiltin, mNone, mCase, mStr} then return notValue(n); end;
1721 if not Sym.isInt(n.typ) then return Scan.markAt(n.pos, say1("expected an integer, found {}", what(n))); end;
1722 x.made := false; (* a built-in's result, not an operator's: it widens *)
1723 if (x.mode = mConst) and (n.mode = mConst) then
1724 w := bits(x.typ);
1725 k := n.val & (w - 1);
1726 if not left then k := (w - k) & (w - 1); end;
1727 v := U64(x.val);
1728 if k # 0 then v := v shl k | v shr (w - k); end;
1729 x.val := cut(I64(v), x.typ);
1730 return nil;
1731 end;
1732 try value(n);
1733 if x.mode = mConst then
1734 (* x goes on after n, which rotand didn't load, and under it *)
1735 try value(x);
1736 Gen.swap();
1737 end;
1738 Gen.rotate(left, intSize(x.typ));
1739 x.mode := mStack;
1740 return nil;
1741end;
1742
1743(* ABS(x): x without its sign, of x's type, an integer or a real (report
1744 section 6.1). A signed integer's smallest value gives itself, as -x
1745 does, with no check, as -x has none; an untyped constant's, whose
1746 result would be beyond the I64s, is an error, as it is for -x. An
1747 unsigned integer is itself. Of a constant it is folded: a real's
1748 sign bit, the top one of the F64 it is held as, cleared. *)
1749proc absolute*(var x: Item): ERROR;
1750begin
1751 if x.mode in {mType, mBuiltin, mNone, mCase} then return notValue(x); end;
1752 if (x.mode = mStr) or not (Sym.isInt(x.typ) or (x.typ^.form = Sym.fReal)) then
1753 return Scan.markAt(x.pos, say1("ABS needs an integer or a real, found {}", what(x)));
1754 end;
1755 if x.mode = mConst then
1756 if x.typ^.form = Sym.fReal then
1757 x.val := x.val & MaxI64;
1758 elsif (x.typ^.form = Sym.fConst) and (x.val = MinI64) then
1759 return Scan.markAt(x.pos, "the constant is too big for I64");
1760 elsif signed(x.typ) and (x.val < 0) then
1761 x.val := cut(-x.val, x.typ);
1762 end;
1763 else
1764 try value(x);
1765 if signed(x.typ) or (x.typ^.form = Sym.fReal) then Gen.abs(Gen.kindOf(x.typ), intSize(x.typ)); end;
1766 end;
1767 x.made := false; (* a built-in's result, not an operator's *)
1768 return nil;
1769end;
1770
1771(* CLZ, CTZ or POPCOUNT, which, of v, a value w bits wide, folded *)
1772proc countOf(which: INT; v: U64; w: I64): I64;
1773var n, i: I64;
1774begin
1775 n := 0;
1776 if which = Sym.bPopcount then
1777 for i := 0 to w - 1 do n := n + I64((v shr i) & 1); end;
1778 elsif which = Sym.bClz then
1779 while (n < w) and (((v shr (w - 1 - n)) & 1) = 0) do INC(n); end;
1780 else
1781 while (n < w) and (((v shr n) & 1) = 0) do INC(n); end;
1782 end;
1783 return n;
1784end;
1785
1786(* CLZ(x), CTZ(x) or POPCOUNT(x), which: the zero bits of x above its
1787 highest one, below its lowest, or its one bits, an INT (report
1788 section 6.1). x is of an unsigned integer type, whose width is what
1789 0 counts, or for POPCOUNT a set; an untyped constant has no width.
1790 Of a constant the count is folded. *)
1791proc countBits*(var x: Item; which: INT): ERROR;
1792var name, s: []const U8; ok: BOOL;
1793begin
1794 if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then return notValue(x); end;
1795 if which = Sym.bClz then name := "CLZ"; elsif which = Sym.bCtz then name := "CTZ"; else name := "POPCOUNT"; end;
1796 if which = Sym.bPopcount then
1797 s := say2("{} needs an unsigned integer or a set, found {}", name, what(x));
1798 else
1799 s := say2("{} needs an unsigned integer, found {}", name, what(x));
1800 end;
1801 if x.typ = Sym.tConst then
1802 return Scan.markHelp(x.pos, s,
1803 say1("an untyped constant has no width to count in: give it a type, as in U32({})", Diag.source(x.pos)));
1804 end;
1805 ok := (x.typ^.form = Sym.fInt) and not x.typ^.signed;
1806 if (x.typ^.form = Sym.fSet) and (which = Sym.bPopcount) then ok := true; end;
1807 if not ok then return Scan.markAt(x.pos, s); end;
1808 if x.mode = mConst then
1809 makeConst(x, Sym.tInt, countOf(which, U64(x.val), bits(x.typ)));
1810 return nil;
1811 end;
1812 try value(x);
1813 if which = Sym.bPopcount then Gen.popCount(); else Gen.countZeros(which = Sym.bClz, intSize(x.typ)); end;
1814 x.typ := Sym.tInt;
1815 x.mode := mStack;
1816 x.made := false; (* a built-in's result, not an operator's *)
1817 return nil;
1818end;
1819
1820(* MIN(T), or MAX(T) if max: the smallest or the largest value of the
1821 integer type t, an untyped constant (report section 6.1); p is where
1822 T is written. MAX(U64) and MAX(UINT) are above high(I64), where the
1823 untyped constants end, so they keep their type, as a hexadecimal
1824 number above it is a U64 (report section 3). *)
1825proc limit*(var x: Item; t: ^Sym.Type; max: BOOL; p: Diag.Pos): ERROR;
1826var name: []const U8; ones: U64; v: I64;
1827begin
1828 if t^.form # Sym.fInt then
1829 if max then name := "MAX"; else name := "MIN"; end;
1830 return Scan.markAt(p, say2("{} needs an integer type, found {}", name, Sym.typeName(t)));
1831 end;
1832 ones := (~U64(0)) shr (64 - bits(t)); (* as many ones as t has bits *)
1833 if t^.signed then ones := ones shr 1; end;
1834 if max then v := I64(ones);
1835 elsif t^.signed then v := -I64(ones) - 1;
1836 else v := 0; end;
1837 if max and (v < 0) then makeConst(x, t, v); else makeConst(x, Sym.tConst, v); end;
1838 return nil;
1839end;
1840
1841proc convert*(var x: Item; t: ^Sym.Type): ERROR;
1842var s: ^Sym.Type; r: F64;
1843begin
1844 s := x.typ;
1845 if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then
1846 if x.mode = mStr then return Scan.markAt(x.pos, "can't convert a string"); end;
1847 return notValue(x);
1848 end;
1849 x.made := false; (* what a conversion gives widens, U8(a + b) too *)
1850 if Sym.same(s, t) then return nil; end;
1851 (* a BOOL is 0 or 1, as a comparison's value is, so it converts as an integer does *)
1852 if (Sym.isInt(s) or (s^.form in {Sym.fEnum, Sym.fSet, Sym.fBool})) and (t^.form = Sym.fInt) then
1853 if x.mode = mConst then x.val := cut(x.val, t);
1854 else try value(x); Gen.narrow(INT(t^.size), t^.signed); end;
1855 elsif Sym.isInt(s) and (t^.form = Sym.fEnum) then
1856 if x.mode = mConst then
1857 if (x.val < 0) or (x.val >= t^.len) then
1858 return Scan.markAt(x.pos, Diag.say("{} isn't a position of {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))]));
1859 end;
1860 else try value(x); Gen.checkEnum(t^.len, nameChunk(t), x.pos); end;
1861 elsif Sym.isInt(s) and (t^.form = Sym.fSet) then
1862 if x.mode = mConst then
1863 if t^.len < 64 then x.val := x.val & ((I64(1) shl t^.len) - 1); end;
1864 else
1865 try value(x);
1866 if t^.len < 64 then
1867 Gen.pushConst(Gen.kWord, (I64(1) shl t^.len) - 1);
1868 Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1869 end;
1870 end;
1871 elsif Sym.isInt(s) and (t^.form = Sym.fReal) then
1872 if x.mode = mConst then
1873 if (s^.form = Sym.fInt) and not s^.signed then r := F64(U64(x.val)); else r := F64(x.val); end;
1874 makeReal(x, r);
1875 realTo(x, t);
1876 else
1877 try value(x);
1878 Gen.intToReal(Gen.kindOf(t), (s^.form = Sym.fInt) and not s^.signed and (s^.size = 8));
1879 end;
1880 elsif (s^.form = Sym.fReal) and (t^.form = Sym.fReal) then
1881 (* F32 to F64, F64 to F32, or a real constant to either *)
1882 if x.mode = mConst then realTo(x, t);
1883 else try value(x); Gen.realToReal(Gen.kindOf(s)); end;
1884 elsif (s^.form = Sym.fReal) and (t^.form = Sym.fInt) then
1885 if x.mode = mConst then
1886 r := realOf(x);
1887 (* NaN or out of range folds to low(int64), the "integer
1888 indefinite" cvttsd2si gives at run time *)
1889 if (r # r) or (r >= 9.2233720368547758E18) or (r < -9.2233720368547758E18) then
1890 x.val := cut(MinI64, t);
1891 else x.val := cut(I64(r), t); end;
1892 else
1893 try value(x); Gen.realToInt(Gen.kindOf(s)); Gen.narrow(INT(t^.size), t^.signed);
1894 end;
1895 elsif (isWord(s) or (s^.form in {Sym.fConst, Sym.fPtr, Sym.fProc, Sym.fNil})) and (t^.form in {Sym.fPtr, Sym.fProc}) then
1896 if s^.form # Sym.fNil then try needSystem(x.pos, say1("a conversion to {}", Sym.typeName(t))); end;
1897 if x.mode # mConst then try value(x); end;
1898 elsif (s^.form in {Sym.fPtr, Sym.fProc}) and isWord(t) then
1899 try needSystem(x.pos, say1("a conversion of a pointer to {}", Sym.typeName(t)));
1900 try value(x);
1901 elsif Sym.isInt(s) and (t^.form = Sym.fBool) then
1902 return Scan.markHelp(x.pos, say1("can't convert {} to BOOL", Sym.typeName(s)),
1903 say1("a comparison says it: {} # 0", Diag.source(x.pos)));
1904 else
1905 return Scan.markAt(x.pos, say2("can't convert {} to {}", Sym.typeName(s), Sym.typeName(t)));
1906 end;
1907 x.typ := t;
1908 return nil;
1909end;
1910
1911(* Calls *)
1912
1913proc beginCall*(var c: Gen.CallInfo; var x: Item): ERROR;
1914begin
1915 if x.mode = mProc then
1916 c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0;
1917 c.obj := x.obj; c.ext := x.obj^.ext;
1918 else
1919 c.obj := nil; c.ext := false;
1920 if x.typ^.form # Sym.fProc then
1921 return Scan.markAt(x.pos, say1("expected a procedure, found {}", what(x)));
1922 end;
1923 c.sig := x.typ; c.chunk := -1;
1924 c.target := try toSlot(x);
1925 end;
1926 c.param := c.sig^.fields;
1927 c.n := 0;
1928 return nil;
1929end;
1930
1931(* Too many arguments or too few, at p *)
1932proc wrongCount(var c: Gen.CallInfo; p: Diag.Pos; text: []const U8): ERROR;
1933begin
1934 if c.obj = nil then return Scan.markAt(p, text); end;
1935 Diag.error(p, Diag.say("{}: {} takes {}", [Fmt.str(text), Fmt.str(Scan.nameOf(c.obj^.name)), Fmt.int(c.sig^.len)]));
1936 if c.obj^.home # nil then Diag.note(c.obj^.pos, "the signature is here"); end;
1937 return Scan.Failed;
1938end;
1939
1940(* Pushes the two words of x, a slice or two results (inTwoRegs), read
1941 from memory now, so that what comes after can't change them. *)
1942proc pushWords(var x: Item): ERROR;
1943var adr: Gen.Adr; f: ^Sym.Obj;
1944begin
1945 if x.mode = mWords then return nil; end; (* there already *)
1946 (* copied to a temporary unless its two words are in memory at a place
1947 that a later argument can't change *)
1948 if (x.mode # mVar) or x.vol or not (x.base in {Gen.bFrame, Gen.bGlobal, Gen.bSlot, Gen.bReg, Gen.bPtr}) then
1949 try copyToTemp(x);
1950 end;
1951 adr := adrOf(x);
1952 if x.typ^.form = Sym.fSlice then
1953 Gen.pushVar(adr, 8, false, Gen.kWord);
1954 INC(adr.off, 8);
1955 Gen.pushVar(adr, 8, false, Gen.kWord);
1956 else
1957 f := x.typ^.fields;
1958 while f # nil do
1959 adr.off := adrOf(x).off + f^.val;
1960 Gen.pushVar(adr, scalarSize(f^.typ), signed(f^.typ), Gen.kindOf(f^.typ));
1961 f := f^.next;
1962 end;
1963 end;
1964 return nil;
1965end;
1966
1967(* An address given where a var or const parameter of its type wants the
1968 variable itself, as ADR(b) for var b: Buf: an error that says what to
1969 write instead, b for SYSTEM.ADR(b) or ADR(b), and p^ for a pointer p. Mostly met in
1970 programs written before the library took var (report 2026-10.33). *)
1971proc givenAddress(const a: Item; p: ^Sym.Obj): ERROR;
1972var s, kind: []const U8; k: INT;
1973begin
1974 if (a.typ^.form # Sym.fPtr) or (a.typ^.base = nil) or not Sym.same(a.typ^.base, p^.typ) then
1975 return nil;
1976 end;
1977 if p^.isConst then kind := "const"; else kind := "var"; end;
1978 s := Diag.source(a.pos);
1979 k := 0; (* past SYSTEM., as ADR is written in a module that imports it *)
1980 if (LEN(s) > 7) and (s[0..7] = "SYSTEM.") then k := 7; end;
1981 if (LEN(s) > k + 5) and (s[k..k + 4] = "ADR(") and (s[LEN(s) - 1] = ')') then
1982 s := Diag.say("write {} for {}: the parameter is the variable itself, not its address",
1983 [Fmt.str(s[k + 4..LEN(s) - 1]), Fmt.str(s)]);
1984 else
1985 s := Diag.say("write {}^ for {}: the parameter is the variable itself, not a pointer to it",
1986 [Fmt.str(s), Fmt.str(s)]);
1987 end;
1988 return Scan.markHelp(a.pos, say2("a {} parameter takes {}, found its address", kind, Sym.typeName(p^.typ)), s);
1989end;
1990
1991(* A const parameter's argument that isn't a variable, or is one with no
1992 address of its own (a packed record's field, a view, through ^VOLATILE),
1993 in a temporary of the statement, or of the procedure if it holds an
1994 array, whose address then goes (report section 8): a slice's two words, a record or an array copied, or a
1995 single value stored. *)
1996proc constTemp(var x: Item): ERROR;
1997var t: I64;
1998begin
1999 if x.typ^.form = Sym.fSlice then
2000 try pushWords(x);
2001 t := Gen.allocTemp(16, 8);
2002 Gen.popVar(frameAdr(t + 8), 8); (* the length, on top *)
2003 Gen.popVar(frameAdr(t), 8);
2004 elsif Sym.isAggregate(x.typ) then
2005 if x.view then return noAddress(x, "a view of a record or an array can't be a const parameter"); end;
2006 if not Sym.holdsArray(x.typ) then return copyToTemp(x); end;
2007 (* a slice of it may come back and be kept to the end of the
2008 procedure (report 8), so its slot lasts as long *)
2009 if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
2010 try address(x);
2011 t := Gen.allocPerm(x.typ^.size, x.typ^.align);
2012 Gen.copyTo(frameAdr(t), x.typ^.size);
2013 else
2014 try value(x);
2015 t := Gen.allocTemp(x.typ^.size, x.typ^.align);
2016 Gen.popVar(frameAdr(t), scalarSize(x.typ));
2017 end;
2018 tempItem(x, x.typ, t);
2019 return nil;
2020end;
2021
2022proc passArg*(var c: Gen.CallInfo; var a: Item): ERROR;
2023var p: ^Sym.Obj;
2024begin
2025 p := c.param;
2026 if c.n >= LEN(c.isF) - 1 then return Scan.markAt(a.pos, "too many arguments"); end;
2027 if p = nil then
2028 (* past the parameters of a C procedure that ends in ...: a string
2029 goes as a C string, an integer constant as an INT, a real
2030 constant as an F64; C takes no F32 there *)
2031 if not c.sig^.variadic then return wrongCount(c, a.pos, "too many arguments"); end;
2032 if a.mode = mStr then try coerce(a, Sym.tPtrU8);
2033 elsif a.typ^.form = Sym.fConst then try coerce(a, Sym.tInt);
2034 elsif a.typ = Sym.tRConst then try coerce(a, Sym.tReal);
2035 elsif isF32(a.typ) then return Scan.markAt(a.pos, "an F32 goes to ... as F64(x)");
2036 elsif not Sym.isScalar(a.typ) then return Scan.markAt(a.pos, "only a single value goes to ..."); end;
2037 c.isF[c.n] := a.typ^.form = Sym.fReal;
2038 c.pair[c.n] := false;
2039 try value(a);
2040 INC(c.n);
2041 return nil;
2042 end;
2043 c.isF[c.n] := (p^.typ^.form = Sym.fReal) and not p^.isVar;
2044 passing := p;
2045 passingAt := a.pos;
2046 if p^.isConst then
2047 (* by address, as var, but any expression of the type: a variable,
2048 or a constant in read-only data, in place; anything else in a
2049 temporary. Before:
2050 value parameter, a record: copied to a temporary, its address goes
2051 after, for const:
2052 its own address goes; nothing is copied *)
2053 try givenAddress(a, p);
2054 try coerce(a, p^.typ);
2055 if (a.mode # mVar) or a.odd or a.view or a.vol then try constTemp(a); end;
2056 try address(a);
2057 elsif p^.isVar then
2058 try givenAddress(a, p);
2059 try notReadOnly(a);
2060 if (a.mode # mVar) or not a.isVar then return Scan.markAt(a.pos, "a var parameter needs a variable"); end;
2061 if a.odd then return Scan.markAt(a.pos, "a field of a packed record can't be a var parameter"); end;
2062 if a.view then return noAddress(a, "a view can't be a var parameter"); end;
2063 if not Sym.same(a.typ, p^.typ) then
2064 return mismatch(a, say2("a var parameter needs exactly {}, found {}", Sym.typeName(p^.typ), what(a)));
2065 end;
2066 if a.vol then return Scan.markAt(a.pos, "can't pass through a volatile pointer to a var parameter"); end;
2067 try address(a);
2068 elsif p^.typ^.form = Sym.fSlice then
2069 try coerce(a, p^.typ);
2070 try pushWords(a);
2071 c.pair[c.n] := true;
2072 INC(c.n);
2073 c.isF[c.n] := false;
2074 elsif Sym.isAggregate(p^.typ) then
2075 try coerce(a, p^.typ);
2076 if a.isVar or a.vol or (a.base # Gen.bFrame) then try copyToTemp(a); end;
2077 try address(a);
2078 else
2079 try coerce(a, p^.typ);
2080 try value(a);
2081 end;
2082 c.pair[c.n] := false;
2083 INC(c.n);
2084 c.param := p^.next;
2085 return nil;
2086end;
2087
2088(* The call c made, with x its result as an item: none; a temporary, for a
2089 slice or a record; two results on Gen's stack (mWords); else one value
2090 on the stack. *)
2091proc endCall*(var c: Gen.CallInfo; var x: Item): ERROR;
2092var res: ^Sym.Type;
2093begin
2094 if c.param # nil then try wrongCount(c, Scan.tokPos(), "too few arguments"); end;
2095 if (c.obj # nil) and (c.obj^.inl # 0) then
2096 Gen.realInPlace(c.obj^.inl); (* Math.sqrt: an instruction, no call *)
2097 else
2098 Gen.call(c);
2099 end;
2100 res := c.sig^.base;
2101 x := {};
2102 if res = nil then
2103 x.mode := mNone; x.typ := Sym.tNone; x.obj := c.obj;
2104 elsif c.ret # 0 then
2105 tempItem(x, res, c.ret);
2106 else
2107 x.mode := mStack; x.typ := res;
2108 if res^.tuple then x.mode := mWords; end;
2109 end;
2110 return nil;
2111end;
2112
2113(* Variants *)
2114
2115(* Whether the record literal about to be parsed is the whole of a return
2116 (see zeroTemp): Parse says so, and clears it after the expression. *)
2117var inResult: BOOL;
2118
2119proc literalInResult*(yes: BOOL);
2120begin
2121 inResult := yes;
2122end;
2123
2124(* A temporary of type t, not cleared: where a record literal is made,
2125 which clears only what its fields leave (zeroRange). With
2126 literalInResult it is behind the hidden pointer, so that return {...}
2127 makes the record where the caller wants it, not in a temporary copied
2128 there after. *)
2129proc tempOf*(var x: Item; t: ^Sym.Type);
2130var tmp: I64; p: Diag.Pos;
2131begin
2132 if inResult and (t = result) then
2133 inResult := false;
2134 p := x.pos;
2135 x := {};
2136 x.pos := p;
2137 x.mode := mVar; x.typ := t; x.base := Gen.bSlot; x.chunk := INT(Gen.resultSlot());
2138 return;
2139 end;
2140 tmp := Gen.allocTemp(t^.size, t^.align);
2141 tempItem(x, t, tmp);
2142end;
2143
2144(* A temporary of type t, all zero: for variants. *)
2145proc zeroTemp*(var x: Item; t: ^Sym.Type);
2146begin
2147 tempOf(x, t);
2148 Gen.zeroVar(adrOf(x), t^.size);
2149end;
2150
2151(* size bytes, off bytes into the variable x, cleared *)
2152proc zeroRange*(const x: Item; off, size: I64);
2153var a: Gen.Adr;
2154begin
2155 a := adrOf(x);
2156 a.off := a.off + off;
2157 Gen.zeroVar(a, size);
2158end;
2159
2160proc construct*(var x: Item; c: ^Sym.Obj);
2161begin
2162 zeroTemp(x, c^.typ);
2163 Gen.pushConst(Gen.kWord, c^.val);
2164 Gen.popVar(frameAdr(x.off), 8);
2165end;
2166
2167proc setField*(const x: Item; f: ^Sym.Obj; var a: Item): ERROR;
2168var at: Gen.Adr;
2169begin
2170 at := adrOf(x);
2171 at.off := at.off + f^.val;
2172 try coerce(a, f^.typ);
2173 if Sym.isScalar(f^.typ) then
2174 try value(a);
2175 Gen.popVar(at, scalarSize(f^.typ));
2176 else
2177 if a.vol then return Scan.markAt(a.pos, "can't copy through a volatile pointer"); end;
2178 try address(a);
2179 Gen.copyTo(at, f^.typ^.size);
2180 end;
2181 return nil;
2182end;
2183
2184(* The slot match tests: a variant's address, an enumeration's or an
2185 integer's value, or a string's slice, which x then is. *)
2186proc matchBegin*(var x: Item): (I64, ERROR);
2187var p: I64;
2188begin
2189 if x.typ^.form in {Sym.fEnum, Sym.fInt} then return toSlot(x); end;
2190 if isSeq(x.typ) and Sym.same(elemOf(x.typ), Sym.tU8) then
2191 try seqSlice(x);
2192 return x.off, nil;
2193 end;
2194 if (x.mode # mVar) or (x.typ^.form # Sym.fVariant) then
2195 return 0, Scan.markAt(x.pos, say1("match needs a variant, an enumeration, an integer or a string, found {}", what(x)));
2196 end;
2197 (* another module's variable: its arms' names stand for a copy's fields;
2198 what is only read is matched in place, its names only read too *)
2199 if x.ro and not onlyRead(x) then try copyToTemp(x); end;
2200 try address(x);
2201 p := Gen.allocTemp(8, 8);
2202 Gen.popVar(frameAdr(p), 8);
2203 return p, nil;
2204end;
2205
2206(* To L unless the tag of the variant whose address is in slot p is tag *)
2207proc matchTag*(p: I64; tag: I64; var L: INT);
2208var a: Gen.Adr;
2209begin
2210 Gen.pushVar(frameAdr(p), 8, false, Gen.kWord);
2211 a.base := Gen.bStack; a.chunk := -1; a.off := 0; a.hi := 0;
2212 Gen.pushVar(a, 8, false, Gen.kWord);
2213 Gen.pushConst(Gen.kWord, tag);
2214 Gen.jumpCmp(Scan.sNeq, false, L);
2215end;
2216
2217(* For a label s of a match on the string whose slice is in slot p:
2218 to body if they are equal, or, for the arm's last label, to L if
2219 they aren't. *)
2220proc matchStr*(p: I64; var s: Item; last: BOOL; var L, body: INT): ERROR;
2221begin
2222 try seqSlice(s);
2223 Gen.compareSeq(p, s.off, 0, true);
2224 if last then Gen.jumpIf(L, false); else Gen.jumpIf(body, true); end;
2225 return nil;
2226end;
2227
2228(* To body if the integer in slot p is from lo to hi: less its lo, it is
2229 then at most hi - lo, compared unsigned, which holds for a signed type
2230 or not, with no second jump. *)
2231proc matchRange*(p, lo, hi: I64; var body: INT);
2232begin
2233 Gen.pushVar(frameAdr(p), 8, false, Gen.kWord);
2234 if lo = hi then
2235 Gen.pushConst(Gen.kWord, lo);
2236 Gen.jumpCmp(Scan.sEql, false, body);
2237 return;
2238 end;
2239 if lo # 0 then
2240 Gen.pushConst(Gen.kWord, lo);
2241 Gen.op(Scan.sMinus, Gen.kWord, 8, false);
2242 end;
2243 Gen.pushConst(Gen.kWord, hi - lo);
2244 Gen.jumpCmp(Scan.sLeq, false, body);
2245end;
2246
2247(* A for loop's variable o, stepped by step, wrapping as its type does *)
2248proc forStep*(o: ^Sym.Obj; step: I64): ERROR;
2249var v, w: Item;
2250begin
2251 try makeItem(v, o);
2252 if v.base = Gen.bReg then
2253 (* a variable in a register is stepped in it *)
2254 Gen.pushConst(Gen.kWord, step);
2255 Gen.incDecReg(v.chunk, intSize(o^.typ), signed(o^.typ), false);
2256 return nil;
2257 end;
2258 try makeItem(w, o);
2259 try value(w);
2260 Gen.pushConst(Gen.kWord, step);
2261 Gen.op(Scan.sPlus, Gen.kWord, intSize(o^.typ), signed(o^.typ));
2262 return assign(v, w);
2263end;
2264
2265(* For a for loop: pushes the variable o and the limit lim, a constant or
2266 the slot it was put in, and jumps to L if the one is op the other, as
2267 the type of o compares *)
2268proc forCmp*(o: ^Sym.Obj; const lim: Item; op: Scan.Sym; var L: INT): ERROR;
2269var v, b: Item;
2270begin
2271 try makeItem(v, o);
2272 try value(v);
2273 b := lim;
2274 try value(b);
2275 Gen.jumpCmp(op, o^.typ^.signed, L);
2276 return nil;
2277end;
2278
2279(* The end of a round of a for loop, for a positive step s, as the report
2280 has it: if v <= b and b - v < s, the loop ends; otherwise v becomes
2281 v + s and the loop goes on while v <= b. Counting the distance left,
2282 rather than comparing after the step, can't be fooled by v wrapping
2283 around. A negative step is the same the other way round: before, past
2284 and within are chosen by up, whether the step is positive.
2285 For a step of 1: v < b goes on to top, where v is stepped; v = b
2286 ends; otherwise the body moved v past b.
2287 For another step: v past b goes to past; else b - v (unsigned, as
2288 v <= b) >= |step| goes on to top, and else the loop ends.
2289 Past: v is stepped here and tested, going to body if within b. *)
2290proc forNext*(o: ^Sym.Obj; const lim: Item; step: I64; var exitL: INT; top, body: INT): ERROR;
2291var v, b: Item; L, pastL: INT; up: BOOL; before, past, within: Scan.Sym; a: I64;
2292begin
2293 up := step > 0;
2294 (* by a negative step, by a positive *)
2295 if up then before := Scan.sLss; past := Scan.sGtr; within := Scan.sLeq;
2296 else before := Scan.sGtr; past := Scan.sLss; within := Scan.sGeq; end;
2297 a := step;
2298 if a < 0 then a := -a; end;
2299 L := Gen.NoLabel;
2300 pastL := Gen.NoLabel;
2301 if a = 1 then
2302 try forCmp(o, lim, before, L);
2303 Gen.fixTo(L, top);
2304 try forCmp(o, lim, Scan.sEql, exitL);
2305 else
2306 try forCmp(o, lim, past, pastL);
2307 try makeItem(v, o);
2308 b := lim;
2309 if up then try value(b); try value(v);
2310 else try value(v); try value(b); end;
2311 Gen.op(Scan.sMinus, Gen.kWord, 8, false);
2312 Gen.pushConst(Gen.kWord, a);
2313 Gen.jumpCmp(Scan.sGeq, false, L);
2314 Gen.fixTo(L, top);
2315 Gen.jump(exitL);
2316 end;
2317 Gen.fix(pastL);
2318 try forStep(o, step);
2319 L := Gen.NoLabel;
2320 try forCmp(o, lim, within, L);
2321 Gen.fixTo(L, body);
2322 return nil;
2323end;
2324
2325(* Jumps to L if the condition x is false. The jumps waiting in x.fj join
2326 L; those in x.tj are placed here, as x is true past this. *)
2327proc condJump*(var x: Item; var L: INT): ERROR;
2328begin
2329 if x.typ^.form # Sym.fBool then
2330 return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x)));
2331 end;
2332 if x.mode = mCond then
2333 Gen.jumpCmp(negated(x.rel), x.relSigned, L);
2334 L := Gen.joinJumps(L, x.fj);
2335 Gen.fix(x.tj);
2336 return nil;
2337 end;
2338 try value(x);
2339 Gen.jumpIf(L, false);
2340 return nil;
2341end;
2342
2343(* As condJump, but the jump to L is taken where the condition is true;
2344 x.tj joins L and x.fj is placed here *)
2345proc condJumpTrue*(var x: Item; var L: INT): ERROR;
2346begin
2347 if x.typ^.form # Sym.fBool then
2348 return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x)));
2349 end;
2350 if x.mode = mCond then
2351 Gen.jumpCmp(x.rel, x.relSigned, L);
2352 L := Gen.joinJumps(L, x.tj);
2353 Gen.fix(x.fj);
2354 return nil;
2355 end;
2356 try value(x);
2357 Gen.jumpIf(L, true);
2358 return nil;
2359end;
2360
2361(* Procedures *)
2362
2363proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj);
2364begin
2365 result := sig^.base;
2366 Gen.beginProc(sig, params);
2367end;
2368
2369(* The result of return x: a value on top, a slice's two words on top,
2370 or one copied behind the hidden pointer *)
2371(* A slice returned must not point into the procedure's own frame,
2372 which is gone once it returns (report section 7.3). Only what can be
2373 seen in the expression is caught: a local array, a value parameter
2374 that is one, an array literal or a temporary, or a slice of one, a
2375 field or an element of one included; x.frame says so, set where the
2376 variable is named and kept through fields, elements and slices. *)
2377proc notOfFrame(const x: Item; t: ^Sym.Type): ERROR;
2378begin
2379 if (t^.form = Sym.fSlice) and x.frame then
2380 return Scan.markHelp(x.pos, "can't return a slice of the procedure's own frame",
2381 "it is gone once the procedure returns: take the array as a var parameter, or fill a buffer the caller gives");
2382 end;
2383 return nil;
2384end;
2385
2386proc returnValue*(var x: Item): ERROR;
2387begin
2388 if result = nil then return Scan.markAt(x.pos, "this procedure returns nothing"); end;
2389 try coerce(x, result);
2390 try notOfFrame(x, result);
2391 if Sym.inTwoRegs(result) then try pushWords(x);
2392 elsif Sym.isAggregate(result) then
2393 (* a record literal made behind the hidden pointer is there already *)
2394 if (x.base = Gen.bSlot) and (x.chunk = INT(Gen.resultSlot())) and (x.off = 0) then return nil; end;
2395 if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
2396 try address(x);
2397 Gen.copyResult(0, result^.size);
2398 else try value(x); end;
2399 return nil;
2400end;
2401
2402(* One of several results: of two words, a value left on top for
2403 returnJump to put in rax or rdx; else into its place behind the
2404 hidden pointer. *)
2405proc returnField*(f: ^Sym.Obj; var x: Item): ERROR;
2406begin
2407 try coerce(x, f^.typ);
2408 try notOfFrame(x, f^.typ);
2409 if Sym.inTwoRegs(result) then try value(x);
2410 elsif Sym.isScalar(f^.typ) then
2411 try value(x);
2412 Gen.resultTo(f^.val, scalarSize(f^.typ));
2413 else
2414 if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
2415 try address(x);
2416 Gen.copyResult(f^.val, f^.typ^.size);
2417 end;
2418 return nil;
2419end;
2420
2421(* Several results at once, the call's that return f(x) passes on. *)
2422proc returnAll*(var x: Item): ERROR;
2423begin
2424 if Sym.inTwoRegs(result) then try pushWords(x);
2425 else
2426 try address(x);
2427 Gen.copyResult(0, result^.size);
2428 end;
2429 return nil;
2430end;
2431
2432proc returnNone*: ERROR;
2433begin
2434 if result # nil then
2435 return Scan.mark(say1("return needs a result of {}", Sym.typeName(result)));
2436 end;
2437 Gen.returnJump();
2438 return nil;
2439end;
2440
2441(* Keeps a variable's address in a frame slot, rather than on the stack,
2442 while other code runs. *)
2443proc pin*(var x: Item): ERROR;
2444var s: I64;
2445begin
2446 if (x.mode = mVar) and (x.base = Gen.bStack) then
2447 try address(x);
2448 s := Gen.allocTemp(8, 8);
2449 Gen.popVar(frameAdr(s), 8);
2450 x.base := Gen.bSlot;
2451 x.chunk := INT(s);
2452 end;
2453 return nil;
2454end;
2455
2456(* INC(v, k) or DEC: v's address is on the stack, from address. *)
2457proc incDec*(var v, k: Item; dec: BOOL): ERROR;
2458begin
2459 try coerce(k, v.typ);
2460 try value(k);
2461 if v.base = Gen.bReg then Gen.incDecReg(v.chunk, scalarSize(v.typ), v.typ^.signed, dec);
2462 else Gen.incDec(scalarSize(v.typ), v.typ^.signed, dec); end;
2463 return nil;
2464end;
2465
2466(* COPY(d, s) or FILL(d, x): d, an array variable or a slice, as a slice
2467 in the frame, before s or x is read; text says what the built-in
2468 writes into, for an error *)
2469proc destSlice(var d: Item; text: []const U8): ERROR;
2470begin
2471 if (d.typ^.form = Sym.fArray) and (d.mode = mVar) then try notReadOnly(d); end;
2472 if (d.typ^.form = Sym.fSlice) and d.typ^.rdonly then
2473 return Scan.markHelp(d.pos, say1("{} is a []const slice, whose elements can't be changed", Diag.source(d.pos)),
2474 "write them through a []T");
2475 end;
2476 if not isSeq(d.typ) or (d.mode = mStr) or ((d.typ^.form = Sym.fArray) and ((d.mode # mVar) or not d.isVar)) then
2477 return Scan.markAt(d.pos, say1(text, what(d)));
2478 end;
2479 return seqSlice(d);
2480end;
2481
2482proc copyDest*(var d: Item): ERROR;
2483begin
2484 return destSlice(d, "COPY copies into an array variable or a slice, found {}");
2485end;
2486
2487proc fillDest*(var d: Item): ERROR;
2488begin
2489 return destSlice(d, "FILL fills an array variable or a slice, found {}");
2490end;
2491
2492(* ... and each of its elements set to x, as by :=; t is d's type as it
2493 was written, so that an array's length is known *)
2494proc fillWith*(var d, x: Item; t: ^Sym.Type): ERROR;
2495var e: ^Sym.Type; n: I64;
2496begin
2497 e := d.typ^.base;
2498 try coerce(x, e);
2499 if Sym.isScalar(e) then
2500 try value(x);
2501 else
2502 if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
2503 if (x.mode = mVar) and (x.base = Gen.bReg) then try copyToTemp(x); end; (* a slice in registers *)
2504 try address(x);
2505 end;
2506 n := -1;
2507 if t^.form = Sym.fArray then n := t^.len; end;
2508 Gen.fillSlice(d.off, e^.size, n, Sym.isScalar(e));
2509 return nil;
2510end;
2511
2512(* ... and the elements of s copied to its start *)
2513proc copyFrom*(var d, s: Item): ERROR;
2514begin
2515 if not isSeq(s.typ) or not Sym.same(elemOf(s.typ), d.typ^.base) then
2516 return Scan.markAt(s.pos, say2("COPY copies elements of {}, found {}", Sym.typeName(d.typ^.base), what(s)));
2517 end;
2518 try seqSlice(s);
2519 Gen.copySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos);
2520 return nil;
2521end;
2522
2523(* An error is the address of its length, followed by its message. *)
2524proc errorChunk*(var x: Item; home, name: INT): (INT, ERROR);
2525var c, xs, xl: INT; p: ^U8; q: ^I64;
2526begin
2527 if x.mode # mStr then
2528 return 0, Scan.markHelp(x.pos, say1("an error is made from a string, found {}", what(x)),
2529 "or from another ERROR constant, which is the same error");
2530 end;
2531 xl := INT(x.val);
2532 p := Scan.grab(xl + 8);
2533 q := ^I64(p);
2534 q^ := x.val;
2535 xs := Chunk.chunks[x.chunk].start;
2536 COPY(p[8..8 + xl], Chunk.rodata[xs..xs + xl]);
2537 c := Chunk.newChunk(Chunk.secRodata, home, name);
2538 Chunk.setData(c, p, xl + 8, 8);
2539 return c, nil;
2540end;
2541
2542proc msg*(var x: Item): ERROR;
2543var s: I64;
2544begin
2545 try coerce(x, Sym.tError);
2546 try value(x);
2547 s := Gen.allocTemp(16, 8);
2548 Gen.errorText(s);
2549 tempItem(x, Sym.tConstBytes, s); (* the message is constant *)
2550 return nil;
2551end;
2552
2553end Item.