(* Item: operands, their types, and what they mean. The parser describes each operand as an item, as in Wirth's compilers: a constant, a variable at an address it can name, a value on Gen's stack, a procedure, a string. The routines here check the items' types, fold constants, and have Gen make the code, as calls of its stack machine; nothing here knows the machine. Depends on: Scan for errors, Sym for types, Chunk for data, Gen for code. Leaves out: the language's syntax, which is Parse; the machine, which is Gen. An error the seed's `Mark` ended in a jump back to the parser's recovery point. Here the routine that finds it shows it and returns `Scan.Failed`, and every routine that calls one passes it up with `try`, to where the parser reads on: what has been made by then is what the seed had made when it jumped. So most routines here return an ERROR, as the last of their results. The seed's `Mismatch` of two operands is `mismatchOps` (raz has no overloading), and what the parser sets, `demoted` and `checks`, has a setter each, as an exported variable is read-only outside its module. The seed's `TItem` is `Item` and `TMode` is `Mode`; its procedures begin in lower case. *) module Item; import Fmt, Diag, Scan, Sym, Chunk, Gen; import SYSTEM; type Mode* = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond, mWords); (* two results of a call, on the stack, the first under the second *) Item* = record mode*: Mode; typ*: ^Sym.Type; rel*: Scan.Sym; (* mCond: the comparison of the two integers on the stack, not yet made, as Wirth's compilers keep a condition *) relSigned*: BOOL; fj*, tj*: INT; (* mCond: the chains of jumps already made that are taken when the whole condition is false, and when it is true, not yet given a place (and, or and not make them); see Gen's jumpOut *) val*: I64; (* mConst: the value, an F64's bits; mStr: its length *) base*: Gen.Base; (* mVar: what the address is relative to *) chunk*: INT; (* mVar with bGlobal, mStr: the chunk; bSlot: the slot; bPtr: the register *) off*: I64; (* mVar: added to the base *) vol*: BOOL; (* mVar: reached through ^VOLATILE *) isVar*: BOOL; (* mVar: a variable of the program, not a temporary *) odd*: BOOL; (* mVar: in a packed record, so maybe misaligned *) view*: BOOL; (* mVar: a view, v.(T), or part of one: maybe misaligned, and with no address *) ro*: BOOL; (* mVar: another module's exported variable, or part of one, which only that module changes *) elemRo*: BOOL; (* mVar: an element of a []const slice, or part of one, read through it and not written *) viewOver*: BOOL; (* a view over a variable that holds more than integers and reals, written only in a module that imports SYSTEM *) deref*: BOOL; (* mVar: at an address from a pointer, which may be nil and isn't tested yet (nilTest) *) obj*: ^Sym.Obj; (* mProc, mBuiltin, mCase; mVar: the variable named *) frame*: BOOL; (* a slice: points into the procedure's own frame, which returnValue refuses (report section 7.3); anything else: lies in that frame, a local, a value parameter or a temporary, or part of one *) pos*: Diag.Pos; (* where it is in the source, for messages *) made*: BOOL; (* an integer an operator gave, computed in its own type, where it may have wrapped: a U8 made so doesn't widen to INT (report section 5.10) *) end; const (* the comparison that holds when the one at the same place doesn't, for integers *) NegatedOps: [6]Scan.Sym = [Scan.sNeq, Scan.sEql, Scan.sGeq, Scan.sGtr, Scan.sLeq, Scan.sLss]; const MaxI64 = 9223372036854775807; MinI64 = -9223372036854775807 - 1; var demoted*: BOOL; (* address wanted a register variable's address: its procedure is compiled again, the variable in memory *) checks*: BOOL; (* the module's index and slice checks are made: it doesn't say check off *) result: ^Sym.Type; (* the result of the procedure being compiled, or nil *) passing: ^Sym.Obj; (* the parameter the argument at passingAt goes to *) passingAt: Diag.Pos; proc setDemoted*(yes: BOOL); begin demoted := yes; end; proc setChecks*(yes: BOOL); begin checks := yes; end; (* The comparison that holds when op doesn't *) proc negated(op: Scan.Sym): Scan.Sym; begin return NegatedOps[INT(op) - INT(Scan.sEql)]; end; proc isRel(op: Scan.Sym): BOOL; begin return (op >= Scan.sEql) and (op <= Scan.sGeq); end; (* Whether op is one of the list: Scan.Sym has too many names for a set *) proc oneOf(op: Scan.Sym; list: []Scan.Sym): BOOL; var i: INT; begin for i := 0 to LEN(list) - 1 do if list[i] = op then return true; end; end; return false; end; proc bit(f: BOOL): I64; begin if f then return 1; end; return 0; end; (* A message, from a format and the strings that fill it *) proc say1(f, a: []const U8): []const U8; begin return Diag.say(f, [Fmt.str(a)]); end; (* What reaches memory other than through a variable, what, is refused at pos in a module that doesn't import SYSTEM (report 3) *) proc needSystem*(pos: Diag.Pos; what: []const U8): ERROR; begin if not Sym.curModule^.system then return Scan.markHelp(pos, say1("{} needs import SYSTEM", what), "it reaches memory other than through a variable: say import SYSTEM after the module's imports"); end; return nil; end; proc say2(f, a, b: []const U8): []const U8; begin return Diag.say(f, [Fmt.str(a), Fmt.str(b)]); end; (* Items *) proc makeConst*(var x: Item; t: ^Sym.Type; v: I64); var p: Diag.Pos; begin p := x.pos; x := {}; x.pos := p; x.mode := mConst; x.typ := t; x.val := v; end; (* A real constant: untyped, unless typed later. Its value is an F64, which for an F32 is one an F32 can hold. *) proc makeReal*(var x: Item; r: F64); var p: ^F64; begin makeConst(x, Sym.tRConst, 0); p := ^F64(SYSTEM.ADR(x.val)); p^ := r; end; proc isF32(t: ^Sym.Type): BOOL; begin return (t^.form = Sym.fReal) and (t^.size = 4); end; proc realOf*(const x: Item): F64; var v: I64; p: ^F64; begin v := x.val; p := ^F64(SYSTEM.ADR(v)); return p^; end; (* Gives a real constant the real type t, rounded to it. *) proc realTo(var x: Item; t: ^Sym.Type); var r: F64; begin r := realOf(x); if isF32(t) then makeReal(x, F64(F32(r))); else makeReal(x, r); end; x.typ := t; end; (* The current string literal, as an item of its own chunk. *) proc makeStr*(var x: Item); begin x := {}; x.mode := mStr; x.typ := Sym.tStr; x.val := Scan.slen; x.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1); Chunk.setData(x.chunk, Scan.strWithZero(), Scan.slen + 1, 1); end; proc frameAdr*(off: I64): Gen.Adr; begin return {base: Gen.bFrame, chunk: -1, off: off, hi: 0}; end; proc globalAdr*(c: INT): Gen.Adr; begin return {base: Gen.bGlobal, chunk: c, off: 0, hi: 0}; end; (* Where the variable x is, for Gen; a slice in registers has two. x is a var parameter only so as not to be copied, as it is a whole Item. *) proc adrOf*(const x: Item): Gen.Adr; var hi: INT; begin hi := 0; if x.base = Gen.bReg then hi := x.obj^.reg2; end; return {base: x.base, chunk: x.chunk, off: x.off, hi: hi}; end; (* An item for "found ...": a constant without a type of its own as it is written, so that "found 1.5" says what is wrong; else its type. *) proc what*(x: Item): []const U8; begin if (x.mode = mConst) and ((x.typ = Sym.tConst) or (x.typ = Sym.tRConst)) then return Diag.source(x.pos); end; return Sym.typeName(x.typ); end; (* Two operands of different types. Numbers convert, so say how. *) proc mismatchOps(x, y: Item; xt, yt: ^Sym.Type): ERROR; var text: []const U8; begin text := say2("{} and {} are different types", Sym.typeName(xt), Sym.typeName(yt)); (* the help converts the narrower integer to the wider, which loses nothing; else the right operand to the left one's type *) if Sym.isInt(xt) and Sym.isInt(yt) and (xt^.size < yt^.size) and (xt # Sym.tConst) then return Scan.markHelp(Diag.join(x.pos, y.pos), text, say2("convert one to the other's type, as in {}({})", Sym.typeName(yt), Diag.source(x.pos))); end; if (Sym.isInt(xt) or (xt^.form = Sym.fReal)) and (Sym.isInt(yt) or (yt^.form = Sym.fReal)) and (xt # Sym.tConst) and (xt # Sym.tRConst) then return Scan.markHelp(Diag.join(x.pos, y.pos), text, say2("convert one to the other's type, as in {}({})", Sym.typeName(xt), Diag.source(y.pos))); end; return Scan.markAt(Diag.join(x.pos, y.pos), text); end; (* An item that is not a value, by what it is. *) proc notValue(x: Item): ERROR; begin match x.mode of | mType: return Scan.markAt(x.pos, say1("{} is a type, not a value", Sym.typeName(x.typ))); | mBuiltin: return Scan.markAt(x.pos, say1("{} is a built-in procedure, not a value", Scan.nameOf(x.obj^.name))); | mCase: return Scan.markAt(x.pos, say1("{} is a case, not a value", Scan.nameOf(x.obj^.name))); | mNone: if x.obj # nil then return Scan.markAt(x.pos, say1("{} returns nothing", Scan.nameOf(x.obj^.name))); end; return Scan.markAt(x.pos, "the procedure returns nothing"); | else: return Scan.markAt(x.pos, "a string can't be an operand"); end; end; proc makeItem*(var x: Item; o: ^Sym.Obj): ERROR; begin x := {}; x.typ := o^.typ; x.obj := o; match o^.cls of | oConst: if o^.typ = Sym.tStr then x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk; elsif o^.typ^.form in {Sym.fArray, Sym.fRecord, Sym.fSlice, Sym.fVariant} then (* an array, record, variant or empty slice constant: a variable in read-only data, not one of the program's, so nothing can change it *) x.mode := mVar; x.base := Gen.bGlobal; x.chunk := o^.chunk; else x.mode := mConst; x.val := o^.val; end; | oVar: x.mode := mVar; (* another module's variable, and a const parameter, are only read *) x.ro := ((o^.lev = 0) and (o^.home # Sym.curModule)) or o^.isConst; x.isVar := not x.ro; if o^.ext then Gen.pushVar(globalAdr(o^.chunk), 8, false, Gen.kWord); x.base := Gen.bStack; elsif o^.lev = 0 then x.base := Gen.bGlobal; x.chunk := o^.chunk; elsif o^.ind and (o^.reg # 0) then x.base := Gen.bPtr; x.chunk := o^.reg; x.off := o^.off; elsif o^.ind then x.base := Gen.bSlot; x.chunk := INT(o^.val); x.off := o^.off; elsif o^.reg # 0 then x.base := Gen.bReg; x.chunk := o^.reg; else x.base := Gen.bFrame; x.off := o^.val; end; (* a value parameter passed by address (ind) is a copy all the same *) x.frame := (o^.lev > 0) and not o^.isVar and (o^.typ^.form # Sym.fSlice); | oProc: x.mode := mProc; | oType: x.mode := mType; | oBuiltin: x.mode := mBuiltin; | oCase: x.mode := mCase; | else: return Scan.mark(say1("{} is not a value", Scan.nameOf(o^.name))); end; return nil; end; proc scalarSize*(t: ^Sym.Type): INT; begin if t^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then return INT(t^.size); end; return 8; end; (* The width an operation on t is brought back to, and whether signed *) proc intSize(t: ^Sym.Type): INT; begin if t^.form = Sym.fInt then return INT(t^.size); end; return 8; end; proc signed(t: ^Sym.Type): BOOL; begin return ((t^.form = Sym.fInt) and t^.signed) or (t^.form = Sym.fConst); end; proc cut(v: I64; t: ^Sym.Type): I64; begin if t^.form # Sym.fInt then return v; end; match t^.size of | 1: if t^.signed then return I64(I8(v)); end; return I64(U8(v)); | 2: if t^.signed then return I64(I16(v)); end; return I64(U16(v)); | 4: if t^.signed then return I64(I32(v)); end; return I64(U32(v)); | else: return v; end; end; (* Code computing with a real is noted on its chunk, at the first place, for a target without reals (report 5.1) to refuse if the chunk turns out to be used. A real moved whole, as a record's bytes are copied, needs nothing the target lacks, and isn't noted. *) proc usesReals*(p: Diag.Pos); begin if (Gen.codeChunk >= 0) and not Chunk.chunks[Gen.codeChunk].reals then Chunk.setReals(Gen.codeChunk, p); end; end; (* x, at an address from a pointer, is about to be used: Gen tests the address for nil where the machine wouldn't stop at it (report section 10), from its offset to its end. *) proc nilTest*(var x: Item); begin if (x.mode = mVar) and x.deref then Gen.checkNil(x.off + x.typ^.size, x.pos); end; x.deref := false; end; (* x's value, on top of the stack *) proc value*(var x: Item): ERROR; var f: F32; p: ^U32; begin if x.mode = mCond then if (x.fj = Gen.NoLabel) and (x.tj = Gen.NoLabel) then Gen.compare(x.rel, Gen.kWord, x.relSigned); else Gen.condValue(negated(x.rel), x.relSigned, x.fj, x.tj); end; x.mode := mStack; return nil; end; if x.typ^.form = Sym.fReal then usesReals(x.pos); end; nilTest(x); match x.mode of | mConst: if (x.typ^.form = Sym.fError) and (x.val > 0) then Gen.pushAdr(globalAdr(INT(x.val) - 1)); elsif isF32(x.typ) then f := F32(realOf(x)); p := ^U32(SYSTEM.ADR(f)); Gen.pushConst(Gen.kF32, I64(p^)); else Gen.pushConst(Gen.kindOf(x.typ), x.val); end; | mVar: if not Sym.isScalar(x.typ) then return Scan.markAt(x.pos, say1("expected a single value, found {}", what(x))); end; Gen.pushVar(adrOf(x), scalarSize(x.typ), (x.typ^.form = Sym.fInt) and x.typ^.signed, Gen.kindOf(x.typ)); | mStack: x.mode := mStack; | mProc: if x.obj^.isCode and (x.obj^.typ^.base # nil) and x.obj^.typ^.base^.tuple then return Scan.markAt(x.pos, "a code procedure with two results can only be called"); end; Gen.pushProc(x.obj^.chunk, x.obj^.ext); | else: return notValue(x); end; x.mode := mStack; return nil; end; (* x, a variable kept in a register, is wanted in memory after all, for its address or a view of its bytes: the procedure is compiled again with the variable in memory; till then, this code is thrown away *) proc demote(var x: Item); begin if (x.mode = mVar) and (x.base = Gen.bReg) then x.obj^.reg := 0; x.obj^.reg2 := 0; demoted := true; x.base := Gen.bFrame; x.off := x.obj^.val; end; end; (* The address of the variable or string x, on top of the stack *) proc address*(var x: Item): ERROR; begin nilTest(x); demote(x); if x.mode = mStr then Gen.pushAdr(globalAdr(x.chunk)); elsif x.mode = mVar then Gen.pushAdr(adrOf(x)); x.base := Gen.bStack; x.off := 0; else return Scan.markAt(x.pos, "expected a variable"); end; return nil; end; (* x isn't wanted: what it has on the stack is dropped *) proc discard*(const x: Item): ERROR; var y: Item; begin if x.mode = mCond then y := x; try value(y); Gen.drop(); return nil; end; if (x.mode = mStack) or ((x.mode = mVar) and (x.base = Gen.bStack)) then Gen.drop(); end; if x.mode = mWords then Gen.drop(); Gen.drop(); end; return nil; end; (* Frames *) proc tempItem*(var x: Item; t: ^Sym.Type; off: I64); var p: Diag.Pos; begin p := x.pos; x := {}; x.pos := p; x.mode := mVar; x.typ := t; x.base := Gen.bFrame; x.off := off; x.frame := t^.form # Sym.fSlice; (* a slice made here says where it points *) end; proc toSlot*(var x: Item): (I64, ERROR); var s: I64; begin try value(x); s := Gen.allocTemp(8, 8); Gen.popVar(frameAdr(s), 8); return s, nil; end; (* Copying *) (* x, copied to a temporary *) proc copyToTemp*(var x: Item): ERROR; var t: I64; f, g: ^Sym.Obj; a: Gen.Adr; begin if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; t := Gen.allocTemp(x.typ^.size, x.typ^.align); if (x.mode = mVar) and (x.base = Gen.bReg) then (* a slice in registers, which has no address: its words stored *) a := adrOf(x); Gen.pushVar(a, 8, false, Gen.kWord); Gen.popVar(frameAdr(t), 8); a.off := 8; Gen.pushVar(a, 8, false, Gen.kWord); Gen.popVar(frameAdr(t + 8), 8); tempItem(x, x.typ, t); return nil; end; if x.mode = mWords then (* the second result is on top, so it is popped first *) f := x.typ^.fields; g := f^.next; Gen.popVar(frameAdr(t + g^.val), scalarSize(g^.typ)); Gen.popVar(frameAdr(t + f^.val), scalarSize(f^.typ)); tempItem(x, x.typ, t); return nil; end; try address(x); Gen.copyTo(frameAdr(t), x.typ^.size); tempItem(x, x.typ, t); return nil; end; (* A slice made from an address on the stack and a length. *) proc sliceOf*(var x: Item; t: ^Sym.Type; len: I64); var s: I64; begin s := Gen.allocTemp(16, 8); Gen.popVar(frameAdr(s), 8); Gen.pushConst(Gen.kWord, len); Gen.popVar(frameAdr(s + 8), 8); tempItem(x, t, s); end; (* An INT goes silently into an I64, and a UINT into a U64, losing nothing on any target, wherever its value goes to one (report section 5.10). *) proc widens*(s, t: ^Sym.Type): BOOL; begin return ((s = Sym.tInt) and Sym.same(t, Sym.tI64)) or ((s = Sym.tUInt) and Sym.same(t, Sym.tU64)); end; (* A U8, I8 or I16 goes silently into an INT, and a U8 or U16 into a UINT: an INT or a UINT holds every value of theirs on any target, since it is at least 16 bits (report sections 5.1 and 5.10). Only one step: a U8 doesn't go into an I64. On the stack of values an integer is kept extended to 64 bits as its type says (Gen), so the value a U8 loads as is already the INT; only the type changes. *) proc smallWidens*(s, t: ^Sym.Type): BOOL; begin if Sym.same(t, Sym.tInt) then return Sym.same(s, Sym.tU8) or Sym.same(s, Sym.tI8) or Sym.same(s, Sym.tI16); elsif Sym.same(t, Sym.tUInt) then return Sym.same(s, Sym.tU8) or Sym.same(s, Sym.tU16); end; return false; end; (* An error at x, a U8, I8, I16 or U16 an operator made, which would otherwise widen to t: the operator worked in x's type, and its result may have wrapped, so the program says where to widen. *) proc madeNarrow(x: Item; t: ^Sym.Type): ERROR; begin return Scan.markHelp(x.pos, Diag.say("can't use {} as {}: an operator made it, in {}, where it may have wrapped", [Fmt.str(Sym.typeName(x.typ)), Fmt.str(Sym.typeName(t)), Fmt.str(Sym.typeName(x.typ))]), say1("convert an operand to {} first, so that the operator works in it", Sym.typeName(t))); end; (* Whether the several results s may be passed on as t: as many, each of the same type or one that widens to it, as in return f(x) (report section 5.10). An INT and an I64 have one layout here, so the values pass as they are. *) proc resultsFit*(s, t: ^Sym.Type): BOOL; var f, g: ^Sym.Obj; begin if not s^.tuple or not t^.tuple or (s^.len # t^.len) then return false; end; f := s^.fields; g := t^.fields; while f # nil do if not Sym.same(f^.typ, g^.typ) and not widens(f^.typ, g^.typ) then return false; end; f := f^.next; g := g^.next; end; return true; end; (* x is only read: a const parameter, a part of one, or a name a match gives a field of one, or of a constant (report sections 7.4 and 8). A part reached through a pointer or a slice in it isn't: what they point at is the caller's to change, as through a value parameter's. *) proc onlyRead*(const x: Item): BOOL; begin return (x.mode = mVar) and x.ro and (x.obj # nil) and x.obj^.isConst; end; (* Whether x is a constant, or part of one, held in read-only data *) proc ofConst(const x: Item): BOOL; begin return (x.mode = mVar) and (x.obj # nil) and (x.obj^.cls = Sym.oConst); end; (* Another module's exported variable can be read, not changed, nor handed to anything that could change it (report section 3); nor can what is only read, above. *) proc notReadOnly*(const x: Item): ERROR; begin if x.elemRo then return Scan.markHelp(x.pos, say1("{} is read through a []const slice, and can't be changed", Diag.source(x.pos)), "a []const slice's elements are only read: write them through a []T"); end; if x.view and x.viewOver then try needSystem(x.pos, "writing a view over what holds more than integers and reals"); end; if onlyRead(x) then return Scan.markHelp(x.pos, say1("{} is only read here, and can't be changed", Diag.source(x.pos)), "a const parameter, a constant, and the names a match gives their fields, are only read: take a var parameter to change it"); end; if x.ro then return Scan.markAt(x.pos, Diag.say("{} is {}'s, and can't be changed outside it", [Fmt.str(Diag.source(x.pos)), Fmt.str(Scan.nameOf(x.obj^.home^.name))])); end; return nil; end; (* An error in x's type, with help that says what to write instead unless hint is empty; if x is an argument, a note at the parameter it goes to. *) proc mismatchHelp(x: Item; text, hint: []const U8): ERROR; begin Diag.error(x.pos, text); if LEN(hint) > 0 then Diag.help(hint); end; if (passing # nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then Diag.note(passing^.pos, say1("it goes to {}, declared here", Scan.nameOf(passing^.name))); end; return Scan.Failed; end; proc mismatch(x: Item; text: []const U8): ERROR; begin return mismatchHelp(x, text, ""); end; (* An error at x, which is a view, or part of one, and so has no address: text, and help that says what to do instead. *) proc noAddress*(x: Item; text: []const U8): ERROR; begin return Scan.markHelp(x.pos, text, "a view has no address, since it may be misaligned: copy it to a variable"); end; (* The []const T of the slice type t, for a message *) proc constOf(t: ^Sym.Type): ^Sym.Type; var c: ^Sym.Type; begin c := Sym.newType(Sym.fSlice, 16, 8); c^.base := t^.base; c^.rdonly := true; return c; end; proc coerce*(var x: Item; t: ^Sym.Type): ERROR; var s: ^Sym.Type; tmp: I64; inFrame: BOOL; hint: []const U8; begin if x.mode = mCond then try value(x); end; s := x.typ; if x.mode = mStr then if (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) and not t^.rdonly then return mismatchHelp(x, say1("a string is a []const U8, not {}", Sym.typeName(t)), "its bytes are constant: take a []const U8 where they are only read, or copy them"); end; if (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then try address(x); sliceOf(x, t, x.val); elsif (t^.form = Sym.fPtr) and (t^.base = Sym.tU8) then try needSystem(x.pos, "a string as a ^U8"); try address(x); x.mode := mStack; x.typ := t; elsif (t^.form = Sym.fArray) and (t^.base = Sym.tU8) and (t^.len >= x.val) then tmp := Gen.allocTemp(t^.size, 1); try address(x); Gen.copyTo(frameAdr(tmp), x.val); if t^.len > x.val then Gen.zeroVar(frameAdr(tmp + x.val), t^.len - x.val); end; tempItem(x, t, tmp); else return mismatch(x, say1("can't use a string as {}", Sym.typeName(t))); end; return nil; end; if x.mode in {mType, mBuiltin, mNone, mCase} then return notValue(x); end; if Sym.same(s, t) then return nil; end; if widens(s, t) then x.typ := t; (* the same bits, on a 64-bit target *) elsif smallWidens(s, t) then if x.made then return madeNarrow(x, t); end; if x.mode # mConst then try value(x); end; (* loaded as s, extended *) x.typ := t; elsif (s = Sym.tRConst) and (t^.form = Sym.fReal) then realTo(x, t); elsif (s^.form = Sym.fConst) and (t^.form = Sym.fInt) then if (x.mode = mConst) and not Sym.fits(x.val, t) then return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))])); end; x.typ := t; elsif (s^.form = Sym.fNil) and (t^.form in {Sym.fPtr, Sym.fProc, Sym.fError}) then x.typ := t; elsif (s^.form = Sym.fPtr) and (t^.form = Sym.fPtr) and t^.vol and not s^.vol and Sym.same(s^.base, t^.base) then x.typ := t; elsif (s^.form = Sym.fSlice) and (t^.form = Sym.fSlice) and t^.rdonly and Sym.same(s^.base, t^.base) then x.typ := t; (* a []T is a []const T as it is: its elements only read *) elsif (s^.form = Sym.fSlice) and (t^.form = Sym.fSlice) and s^.rdonly and Sym.same(s^.base, t^.base) then return mismatchHelp(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)), "its elements are only read, and a []T could write them"); elsif (s^.form = Sym.fArray) and (t^.form = Sym.fSlice) and Sym.same(s^.base, t^.base) then (* a slice of what is only read, a constant or a const parameter, another module's array, or one read through a []const, is made only as a []const *) if (onlyRead(x) or ofConst(x)) and not t^.rdonly then return mismatchHelp(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)), say1("{} is only read: a slice of it is a []const", Diag.source(x.pos))); end; if x.ro and not onlyRead(x) and not t^.rdonly then return Scan.markHelp(x.pos, Diag.say("{} is {}'s, and can't be changed outside it", [Fmt.str(Diag.source(x.pos)), Fmt.str(Scan.nameOf(x.obj^.home^.name))]), say1("it may be read as a {}", Sym.typeName(constOf(t)))); end; if not t^.rdonly then try notReadOnly(x); end; if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end; if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end; if x.view then return noAddress(x, "can't make a slice of a view"); end; inFrame := x.frame; try address(x); sliceOf(x, t, s^.len); x.frame := inFrame; elsif (x.mode = mProc) and (t^.form # Sym.fProc) and (s^.base = nil) then return Scan.markAt(x.pos, say1("{} is a procedure, and returns nothing", Diag.source(x.pos))); elsif (x.mode = mProc) and (t^.form # Sym.fProc) then return Scan.markHelp(x.pos, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)), say1("to call it, write {}()", Diag.source(x.pos))); elsif (widens(Sym.tInt, t) and smallWidens(s, Sym.tInt)) or (widens(Sym.tUInt, t) and smallWidens(s, Sym.tUInt)) then (* a U8 widens one step, to INT, not on to an I64 *) return Scan.markHelp(x.pos, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)), Diag.say("{} widens to {} only as written, {}({})", [Fmt.str(Sym.typeName(s)), Fmt.str(Sym.typeName(t)), Fmt.str(Sym.typeName(t)), Fmt.str(Diag.source(x.pos))])); elsif (s^.form in {Sym.fSlice, Sym.fArray}) and (t^.form = Sym.fPtr) and Sym.same(s^.base, t^.base) then (* the pointer and the length of a slice are two things *) return mismatchHelp(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)), Diag.say("PTR({}) is the address it starts at, a {}, and LEN({}) how many it has", [Fmt.str(Diag.source(x.pos)), Fmt.str(Sym.typeName(t)), Fmt.str(Diag.source(x.pos))])); elsif (s^.form = Sym.fPtr) and (t^.form = Sym.fSlice) and Sym.same(s^.base, t^.base) then if x.mode = mVar then hint := say1("{}[0..n]", Diag.source(x.pos)); else hint := "p[0..n], for a pointer p,"; end; return mismatchHelp(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)), say1("a pointer has no length: {} is the slice of the n elements it starts", hint)); elsif widens(t, s) then (* the other way, an I64 into an INT, is written: it may drop bits *) return Scan.markHelp(x.pos, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)), Diag.say("{} becomes {} only as written, {}({})", [Fmt.str(Sym.typeName(s)), Fmt.str(Sym.typeName(t)), Fmt.str(Sym.typeName(t)), Fmt.str(Diag.source(x.pos))])); else return mismatch(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t))); end; return nil; end; (* dst := src. The address of dst, if it has to be computed, is on the stack already, under src's. *) proc assign*(var dst, src: Item): ERROR; begin try coerce(src, dst.typ); if Sym.isScalar(dst.typ) then try value(src); Gen.popVar(adrOf(dst), scalarSize(dst.typ)); else if dst.vol or src.vol then return Scan.markAt(src.pos, "can't copy through a volatile pointer"); end; if (src.mode = mVar) and (src.base = Gen.bReg) then try copyToTemp(src); end; (* a slice in registers *) try address(src); if dst.base = Gen.bStack then Gen.copyBlock(dst.typ^.size, dst.off); else Gen.copyTo(adrOf(dst), dst.typ^.size); end; end; return nil; end; (* t's name, ending in a zero byte, for Rt.fail *) proc nameChunk(t: ^Sym.Type): INT; var s: []const U8; p: ^U8; n, c: INT; begin s := Sym.typeName(t); n := LEN(s); p := Scan.grab(n + 1); COPY(p[0..n], s); p[n] := 0; c := Chunk.newChunk(Chunk.secRodata, -1, -1); Chunk.setData(c, p, n + 1, 1); return c; end; (* Selectors *) proc deref*(var x: Item): ERROR; var t: ^Sym.Type; begin t := x.typ; if t^.form # Sym.fPtr then return Scan.markAt(x.pos, say1("expected a pointer, found {}", Sym.typeName(t))); end; if t^.base = nil then return Scan.markAt(x.pos, say1("{} points to a type never declared", Sym.typeName(t))); end; try value(x); x.mode := mVar; x.base := Gen.bStack; x.off := 0; x.deref := true; x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; x.elemRo := false; x.view := false; x.frame := false; return nil; end; (* A field of a packed record, of more than one byte's alignment, may sit anywhere; it is read and written, but has no address and no volatile access, which a machine that can't reach a misaligned word couldn't make one access (report section 5.5). *) proc field*(var x: Item; f: ^Sym.Obj): ERROR; begin if x.typ^.packd and (f^.typ^.align > 1) then if x.vol then return Scan.markAt(x.pos, "a field of a packed record can't be volatile"); end; x.odd := true; end; x.off := x.off + f^.val; x.typ := f^.typ; if x.typ^.form = Sym.fSlice then x.frame := false; end; (* a slice kept here points anywhere *) return nil; end; proc indexPrep*(var x: Item): ERROR; begin nilTest(x); if x.mode = mStr then try coerce(x, Sym.tConstBytes); end; if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fArray) then return Scan.markAt(x.pos, "a pointer to an array is indexed as p^[i]"); end; if x.typ^.form = Sym.fPtr then try value(x); elsif not ((x.mode = mVar) and (x.typ^.form in {Sym.fArray, Sym.fSlice})) then return Scan.markAt(x.pos, say1("expected an array, a slice or a pointer, found {}", what(x))); end; return nil; end; (* The index on top, times the size of an element *) proc scaleBy(s: I64); begin if s # 1 then Gen.pushConst(Gen.kWord, s); Gen.op(Scan.sTimes, Gen.kWord, 8, true); end; end; proc index*(var x, y: Item): ERROR; var t: ^Sym.Type; s: I64; isConst: BOOL; begin t := x.typ; s := t^.base^.size; if not Sym.isInt(y.typ) then return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y))); end; if t^.form = Sym.fPtr then try needSystem(Diag.join(x.pos, y.pos), "indexing through a pointer"); isConst := y.mode = mConst; try value(y); if isConst or not ((s = 1) or (s = 2) or (s = 4) or (s = 8)) then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false); else Gen.indexPtr(s); end; x.mode := mVar; x.base := Gen.bStack; x.off := 0; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; x.view := false; x.elemRo := false; elsif (t^.form = Sym.fArray) and (y.mode = mConst) then if (y.val < 0) or (y.val >= t^.len) then return Scan.markAt(y.pos, Diag.say("index {} is out of range for a length of {}", [Fmt.int(y.val), Fmt.int(t^.len)])); end; x.off := x.off + y.val * s; elsif t^.form = Sym.fArray then try value(y); if checks then Gen.checkIndex(t^.len, y.pos); end; if x.base = Gen.bStack then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false); else Gen.indexArray(adrOf(x), s); x.off := 0; end; x.base := Gen.bStack; else try value(y); Gen.indexSlice(adrOf(x), s, 0, checks, y.pos); x.base := Gen.bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false; x.elemRo := t^.rdonly; end; x.typ := t^.base; (* an element of an array lies where the array does; one of a slice or through a pointer, and a slice kept in an element, anywhere *) if (t^.form # Sym.fArray) or (x.typ^.form = Sym.fSlice) then x.frame := false; end; return nil; end; proc sliceLo*(var lo: Item): ERROR; begin if not Sym.isInt(lo.typ) then return Scan.markAt(lo.pos, say1("an index is an integer, found {}", what(lo))); end; return value(lo); end; proc slice*(var x, lo, hi: Item): ERROR; var t, st: ^Sym.Type; tmp: I64; inFrame, roSlice: BOOL; begin t := x.typ; if not Sym.isInt(hi.typ) then return Scan.markAt(hi.pos, say1("an index is an integer, found {}", what(hi))); end; if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end; if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end; if x.view then return noAddress(x, "can't make a slice of a view"); end; (* a slice of another module's array, or of one read through a []const, is a []const; of a const parameter's, a slice to read *) roSlice := (t^.form = Sym.fSlice) and t^.rdonly; if t^.form = Sym.fArray then roSlice := x.ro or x.elemRo or ofConst(x); (* x.ro: another module's, or a const parameter's *) end; if t^.form = Sym.fPtr then try needSystem(x.pos, "a slice of a pointer"); end; try value(hi); inFrame := x.frame and (t^.form # Sym.fPtr); tmp := Gen.allocTemp(16, 8); if t^.form = Sym.fPtr then Gen.slicePtr(t^.base^.size, tmp, checks, lo.pos); else Gen.slice(adrOf(x), t^.form = Sym.fArray, t^.len, t^.base^.size, tmp, checks, lo.pos); end; st := Sym.newType(Sym.fSlice, 16, 8); st^.base := t^.base; st^.rdonly := roSlice; tempItem(x, st, tmp); x.frame := inFrame; return nil; end; (* PTR(x), the address the slice x starts at, as the pointer type t (report section 6.8). Of a slice it is its first word, read with no check, so that an empty one gives what it holds, nil or an end, where ADR(x[0]) would stop the program: PTR(s) s's first word, as LEN(s) is its second Of an array or a string it is the address of its first element, and may be taken where slice above would make a slice of all of it. *) proc startOf*(var x: Item; t: ^Sym.Type): ERROR; begin if x.typ^.form = Sym.fSlice then if x.mode = mWords then Gen.drop(); (* a call's two words: the length, on top, goes *) x.mode := mStack; else if x.mode # mVar then try copyToTemp(x); end; x.typ := t; try value(x); end; x.typ := t; x.frame := false; return nil; end; if x.vol then return Scan.markHelp(x.pos, "PTR can't take an array through a volatile pointer", Diag.say("ADR({}[0]) is the address of its first element, a ^VOLATILE {}", [Fmt.str(Diag.source(x.pos)), Fmt.str(Sym.typeName(t^.base))])); end; if x.odd then return Scan.markAt(x.pos, "PTR can't take a field of a packed record, which has no address"); end; if x.view then return noAddress(x, "PTR can't take a view"); end; if x.ro and not onlyRead(x) then (* as in slice: another module's array isn't lent to be written *) _ := notReadOnly(x); Diag.help("a pointer to it could change it, as a slice of it could: copy it to a variable here first"); return Scan.Failed; end; try address(x); x.mode := mStack; x.typ := t; x.frame := false; return nil; end; (* Views, v.(T): the bytes of the variable v read and written as a T (report section 6.9). A view is the item of v with T for its type: the same place, so nothing is copied or computed to make one. What is left is to check the type, and that T's bytes lie where v's room is; and to mark the item a view, which may be misaligned, as a field of a packed record may, so that nothing takes its address. *) (* Any bytes at all are a value of an integer, a real or a pointer, and of a record or array made of them alone. A BOOL, an enumeration or a set has bytes that are none of its values, and a slice, variant, procedure or ERROR holds more than bytes can say. The type in t that isn't plain data, or nil if all of it is. *) proc notPlain(t: ^Sym.Type): ^Sym.Type; var f: ^Sym.Obj; u: ^Sym.Type; begin match t^.form of | fInt, fReal, fPtr: return nil; | fArray: return notPlain(t^.base); | fRecord: if t^.tuple then return t; end; f := t^.fields; while f # nil do u := notPlain(f^.typ); if u # nil then return u; end; f := f^.next; end; return nil; | else: return t; end; end; (* What x must be to have a view made of it, as a T: a variable, not volatile, and T a type of plain data. *) proc viewable(x: Item; t: ^Sym.Type): ERROR; var u: ^Sym.Type; text: []const U8; begin (* another module's variable, ro, is one too, read and not written *) if (x.mode # mVar) or not (x.isVar or x.ro) then return Scan.markHelp(x.pos, "a view needs a variable", "a constant, or the result of a call or an operator, has no bytes to view: copy it to a variable"); end; if x.vol then return Scan.markHelp(x.pos, "can't make a view of a volatile variable", "a view may be misaligned, which can't be one access: reach a device through a ^VOLATILE pointer to a record"); end; u := notPlain(t); if u = nil then if not Sym.isPlain(t) then try needSystem(x.pos, say1("a view as {}, which holds an address,", Sym.typeName(t))); end; return nil; end; if u # t then text := say2("can't view bytes as {}, which holds {}", Sym.typeName(t), Sym.typeName(u)); else text := say1("can't view bytes as {}", Sym.typeName(t)); end; if u^.form = Sym.fBool then return Scan.markHelp(x.pos, text, "some bytes are no BOOL: view an integer, and compare it with 0"); elsif u^.form in {Sym.fEnum, Sym.fSet} then return Scan.markHelp(x.pos, text, say1("some bytes are no {}: view an integer, and convert it", Sym.typeName(u))); end; return Scan.markHelp(x.pos, text, "a view is an integer, a real or a pointer, or a record or array made of them"); end; (* What BYTES(x) refuses of its type, t, or of a slice's elements, t: a type a view may not take (report section 6.8), since bytes written through the slice must still be a value of it. In a record, the help names the field that holds it. *) proc bytesType(x: Item; t: ^Sym.Type): ERROR; var u: ^Sym.Type; f: ^Sym.Obj; text, hint: []const U8; begin u := notPlain(t); if u = nil then return nil; end; if u # x.typ then text := say2("BYTES can't take {}, which holds {}", Sym.typeName(x.typ), Sym.typeName(u)); else text := say1("BYTES can't take {}", Sym.typeName(u)); end; hint := say1("some bytes are no {}: BYTES takes integers, reals and pointers, and records and arrays of them", Sym.typeName(u)); if t^.form = Sym.fRecord then f := t^.fields; while (f # nil) and (notPlain(f^.typ) = nil) do f := f^.next; end; if f # nil then hint := Diag.say("its field {} is of type {}, and some bytes are no {}", [Fmt.str(Scan.nameOf(f^.name)), Fmt.str(Sym.typeName(f^.typ)), Fmt.str(Sym.typeName(u))]); end; end; return Scan.markHelp(x.pos, text, hint); end; (* BYTES(x), the bytes of x as a []const U8 (report section 6.8), made as a slice of x is, refused where one is, and keeping x's frame mark, so that returnValue refuses the bytes of a local as a slice of one: BYTES(s) {PTR(s), LEN(s) * SIZE(T)} for a slice s: []T BYTES(v) {ADR(v), SIZE(T)} for v: T, anything else A slice's words are read as PTR and LEN read them, once it is where both can be read: a call's two words, or a slice reached through an address on the stack, go to a temporary first. *) proc bytesOf*(var x: Item): ERROR; var t, bt: ^Sym.Type; inFrame: BOOL; y: Item; s: I64; begin if x.mode = mStr then return Scan.markHelp(x.pos, "BYTES can't take a string constant", "a string constant is only read: where a []U8 is wanted, the string itself will do"); end; t := x.typ; inFrame := x.frame; if t^.form = Sym.fSlice then try bytesType(x, t^.base); if not t^.rdonly and not Sym.isPlain(t^.base) then try needSystem(x.pos, "BYTES of what holds an address"); end; if (x.mode # mVar) or (x.base = Gen.bStack) then try copyToTemp(x); end; y := x; y.typ := Sym.tInt; try value(y); (* its first word, where it starts *) x.off := x.off + 8; x.typ := Sym.tInt; try value(x); (* its second, the number of elements *) scaleBy(t^.base^.size); s := Gen.allocTemp(16, 8); Gen.popVar(frameAdr(s + 8), 8); Gen.popVar(frameAdr(s), 8); if t^.rdonly then (* the bytes of a []const T are only read too: a []const U8 *) bt := Sym.newType(Sym.fSlice, 16, 8); bt^.base := Sym.tU8; bt^.rdonly := true; tempItem(x, bt, s); else tempItem(x, Sym.tBytes, s); end; x.frame := inFrame; return nil; end; try notReadOnly(x); if (x.mode # mVar) or not x.isVar then return Scan.markHelp(x.pos, "BYTES needs a variable", "a constant, or the result of a call or an operator, has no bytes of its own: copy it to a variable"); end; if x.vol then return Scan.markHelp(x.pos, "BYTES can't take a volatile variable", "reading and writing its bytes through a slice wouldn't be volatile accesses"); end; if x.odd then return Scan.markAt(x.pos, "BYTES can't take a field of a packed record, which has no address"); end; if x.view then return noAddress(x, "BYTES can't take a view"); end; try bytesType(x, t); if not Sym.isPlain(t) then try needSystem(x.pos, "BYTES of what holds an address"); end; try address(x); sliceOf(x, Sym.tBytes, t^.size); x.frame := inFrame; return nil; end; (* x becomes the view of itself as a T, its type changed and nothing else: the bytes are where x's are. A variable in a register has no bytes to view, so it goes to memory. *) proc becomeView(var x: Item; t: ^Sym.Type); begin demote(x); x.typ := t; x.view := true; end; (* v.(T), where v is not an element: T must fit in v itself. *) proc view*(var x: Item; t: ^Sym.Type): ERROR; var over: BOOL; begin try viewable(x, t); over := not Sym.isPlain(x.typ); if t^.size > x.typ^.size then return Scan.markAt(x.pos, Diag.say("a view of {} bytes doesn't fit in {}, of {}", [Fmt.int(t^.size), Fmt.str(Sym.typeName(x.typ)), Fmt.int(x.typ^.size)])); end; becomeView(x, t); x.viewOver := over; return nil; end; (* The number of elements of size s that n bytes reach into, at least one: those of a[i] up to a[i + k - 1]. *) proc elementsFor(n, s: I64): I64; begin if (s = 0) or (n <= s) then return 1; end; return (n + s - 1) div s; end; (* a[i].(T): x is the array, slice or pointer, y the index. T must lie from a[i] to a's end: in an array of n elements, k of them from i on, so i is below n - k + 1; a slice's length is known only as the program runs, which checks that length - i, at least 1 since i is below it, is at least k. Through a pointer, no check: p[i] has none (report section 6.9). *) proc indexView*(var x, y: Item; t: ^Sym.Type): ERROR; var at: ^Sym.Type; s, k: I64; over: BOOL; begin at := x.typ; s := at^.base^.size; k := elementsFor(t^.size, s); if not Sym.isInt(y.typ) then return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y))); end; if (at^.form = Sym.fArray) and (k > at^.len) then return Scan.markAt(Diag.join(x.pos, y.pos), Diag.say("a view of {} bytes doesn't fit in {}, of {}", [Fmt.int(t^.size), Fmt.str(Sym.typeName(at)), Fmt.int(at^.size)])); end; if (at^.form = Sym.fArray) and (y.mode = mConst) then if (y.val < 0) or (y.val > at^.len - k) then return Scan.markAt(y.pos, Diag.say("a view of {} bytes at index {} runs past a length of {}", [Fmt.int(t^.size), Fmt.int(y.val), Fmt.int(at^.len)])); end; try index(x, y); elsif (at^.form = Sym.fArray) and checks then (* as index does, with the view's check in place of i < n *) try value(y); Gen.checkView(at^.len, at^.len - k + 1, y.pos); if x.base = Gen.bStack then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false); else Gen.indexArray(adrOf(x), s); x.off := 0; end; x.base := Gen.bStack; x.typ := at^.base; elsif at^.form = Sym.fSlice then try value(y); Gen.indexSlice(adrOf(x), s, k - 1, checks, y.pos); x.base := Gen.bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false; x.elemRo := at^.rdonly; x.typ := at^.base; else try index(x, y); end; try viewable(x, t); over := not Sym.isPlain(x.typ); (* the element's *) becomeView(x, t); x.viewOver := over; return nil; end; (* Operators *) proc neg*(var x: Item): ERROR; begin if x.typ^.form = Sym.fReal then if x.mode = mConst then x.val := x.val xor MinI64; else try value(x); Gen.neg(Gen.kindOf(x.typ), 8, false); end; elsif Sym.isInt(x.typ) then if (x.mode = mConst) and (x.typ^.form = Sym.fConst) and (x.val = MinI64) then return Scan.markAt(x.pos, "the constant is too big for I64"); elsif x.mode = mConst then x.val := cut(-x.val, x.typ); else try value(x); Gen.neg(Gen.kWord, intSize(x.typ), signed(x.typ)); end; x.made := true; else return Scan.markAt(x.pos, say1("can't negate {}", Sym.typeName(x.typ))); end; return nil; end; proc notOp*(var x: Item): ERROR; var L: INT; begin if Sym.isInt(x.typ) then return Scan.markHelp(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)), "the bits of an integer flip with ~"); end; if x.typ^.form # Sym.fBool then return Scan.markAt(x.pos, say1("\"not\" needs a BOOL, found {}", what(x))); end; if x.mode = mConst then x.val := 1 - x.val; elsif x.mode = mCond then x.rel := negated(x.rel); L := x.fj; x.fj := x.tj; x.tj := L; else try value(x); Gen.notBool(); end; return nil; end; proc complement*(var x: Item): ERROR; begin if x.typ^.form = Sym.fBool then return Scan.markHelp(x.pos, say1("\"~\" needs an integer, found {}", what(x)), "a BOOL is negated with not"); end; if not Sym.isInt(x.typ) then return Scan.markAt(x.pos, say1("\"~\" needs an integer, found {}", what(x))); end; if x.mode = mConst then x.val := cut(~x.val, x.typ); else try value(x); Gen.complement(intSize(x.typ), signed(x.typ)); end; x.made := true; return nil; end; (* Arrays, slices and strings, which = and # compare element by element *) proc isSeq(t: ^Sym.Type): BOOL; begin return t^.form in {Sym.fStr, Sym.fArray, Sym.fSlice}; end; proc elemOf(t: ^Sym.Type): ^Sym.Type; begin if t^.form = Sym.fStr then return Sym.tU8; end; return t^.base; end; (* An array, slice or string as a slice in a temporary, for comparing. *) proc seqSlice(var x: Item): ERROR; var t: ^Sym.Type; begin t := Sym.newType(Sym.fSlice, 16, 8); t^.base := elemOf(x.typ); if x.typ^.form = Sym.fSlice then (* a temporary, as a slice just cut is, nothing else can change *) if (x.mode # mVar) or (x.base # Gen.bFrame) or x.isVar or (x.obj # nil) then try copyToTemp(x); end; x.typ := t; elsif x.mode = mStr then try address(x); sliceOf(x, t, x.val); else if x.vol then return Scan.markAt(x.pos, "can't compare through a volatile pointer"); end; try address(x); sliceOf(x, t, x.typ^.len); end; return nil; end; (* x, a BOOL, as a condition: a value compared with 0 if it isn't one *) proc makeCond(var x: Item): ERROR; begin if x.mode = mCond then return nil; end; try value(x); Gen.pushConst(Gen.kWord, 0); x.mode := mCond; x.rel := Scan.sNeq; x.relSigned := false; x.fj := Gen.NoLabel; x.tj := Gen.NoLabel; return nil; end; proc op1*(op: Scan.Sym; var x: Item; var L: INT): ERROR; begin L := Gen.NoLabel; if ((op = Scan.sAnd) or (op = Scan.sOr)) and (x.typ^.form = Sym.fBool) then if x.mode = mConst then (* false and y, true or y: y isn't evaluated, so its code, about to be made, is jumped over to L, which op2 places *) if (x.val = 1) # (op = Scan.sAnd) then Gen.jump(L); end; return nil; (* folded by op2 *) end; try makeCond(x); if op = Scan.sAnd then Gen.jumpOut(negated(x.rel), x.relSigned, x.fj); Gen.fix(x.tj); x.tj := Gen.NoLabel; else Gen.jumpOut(x.rel, x.relSigned, x.tj); Gen.fix(x.fj); x.fj := Gen.NoLabel; end; elsif ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(x.typ) then try seqSlice(x); elsif (op = Scan.sPlus) and (x.mode = mStr) then (* two string constants to be joined: nothing to compute *) elsif (op = Scan.sPlus) and isSeq(x.typ) then return Scan.markHelp(x.pos, say1("+ doesn't join {}", what(x)), "strings are joined in a Buf: Buf.str(b, s)"); elsif x.mode in {mType, mBuiltin, mNone, mCase, mStr} then return notValue(x); elsif x.mode # mConst then try value(x); end; return nil; end; proc log2(v: I64): INT; var n: INT; begin n := 0; while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end; if v # 1 then n := -1; end; return n; end; (* Whether a op b, for + - *, overflows an I64: an untyped constant doesn't wrap, it is an error (report section 4). *) proc overflows(op: Scan.Sym; a, b: I64): BOOL; begin match op of | sPlus: return ((b > 0) and (a > MaxI64 - b)) or ((b < 0) and (a < MinI64 - b)); | sMinus: return ((b < 0) and (a > MaxI64 + b)) or ((b > 0) and (a < MinI64 + b)); | sTimes: if (a = 0) or (b = 0) then return false; end; if a = -1 then return b = MinI64; end; if b = -1 then return a = MinI64; end; return (a * b) div b # a; | else: return false; end; end; (* A type's width in bits; an untyped constant's is an I64's *) proc bits(t: ^Sym.Type): I64; begin return t^.size * 8; end; proc foldInt(op: Scan.Sym; a, b: I64; t: ^Sym.Type; p: Diag.Pos): (I64, ERROR); var u: BOOL; begin u := (t^.form = Sym.fInt) and not t^.signed; if (t^.form = Sym.fConst) and overflows(op, a, b) then return 0, Scan.markAt(p, "the constant is too big for I64"); end; match op of | sPlus: return a + b, nil; | sMinus: return a - b, nil; | sTimes: return a * b, nil; | sDiv, sMod: if b = 0 then return 0, Scan.markAt(p, "division by zero"); end; if u then if op = Scan.sDiv then return I64(U64(a) div U64(b)), nil; end; return I64(U64(a) mod U64(b)), nil; end; if (b = -1) and (a = I64(-1) shl (bits(t) - 1)) then return 0, Scan.markAt(p, "division overflows"); end; if op = Scan.sDiv then return a div b, nil; end; return a mod b, nil; | sAmp: return a & b, nil; | sBar: return a | b, nil; | sXor: return a xor b, nil; | sShl: return a shl (b & (bits(t) - 1)), nil; | sShr: if u then return I64(U64(a) shr (b & (bits(t) - 1))), nil; end; return a shr (b & (bits(t) - 1)), nil; | sEql: return bit(a = b), nil; | sNeq: return bit(a # b), nil; | sLss: if u then return bit(U64(a) < U64(b)), nil; end; return bit(a < b), nil; | sLeq: if u then return bit(U64(a) <= U64(b)), nil; end; return bit(a <= b), nil; | sGtr: if u then return bit(U64(a) > U64(b)), nil; end; return bit(a > b), nil; | sGeq: if u then return bit(U64(a) >= U64(b)), nil; end; return bit(a >= b), nil; | else: return 0, Scan.markAt(p, "bad operator"); end; end; (* Folds x op y, of the real type t: an F32 rounded at each step, as the machine would. *) proc foldReal(op: Scan.Sym; x, y: Item; t: ^Sym.Type; var r: Item): BOOL; var a, b: F64; ok: BOOL; begin a := realOf(x); b := realOf(y); ok := true; match op of | sPlus: makeReal(r, a + b); | sMinus: makeReal(r, a - b); | sTimes: makeReal(r, a * b); | sSlash: makeReal(r, a / b); | sEql: makeConst(r, Sym.tBool, bit(a = b)); | sNeq: makeConst(r, Sym.tBool, bit(a # b)); | sLss: makeConst(r, Sym.tBool, bit(a < b)); | sLeq: makeConst(r, Sym.tBool, bit(a <= b)); | sGtr: makeConst(r, Sym.tBool, bit(a > b)); | sGeq: makeConst(r, Sym.tBool, bit(a >= b)); | else: ok := false; end; if r.typ^.form = Sym.fReal then realTo(r, t); end; return ok; end; (* and, or and not are for BOOLs; &, |, xor and ~ for the bits of integers: x is the wrong kind for op, and the message names the operator it may have meant *) proc wrongLogic(op: Scan.Sym; var x: Item): ERROR; var bitsOf: []const U8; begin bitsOf := "the bits of integers take "; if (op = Scan.sAnd) and Sym.isInt(x.typ) then return Scan.markHelp(x.pos, say1("\"and\" needs BOOLs, found {}", what(x)), say1("{}&", bitsOf)); elsif (op = Scan.sOr) and Sym.isInt(x.typ) then return Scan.markHelp(x.pos, say1("\"or\" needs BOOLs, found {}", what(x)), say1("{}|", bitsOf)); elsif op = Scan.sAmp then return Scan.markHelp(x.pos, say1("\"&\" needs integers, found {}", what(x)), "BOOLs take and"); elsif op = Scan.sBar then return Scan.markHelp(x.pos, say1("\"|\" needs integers, found {}", what(x)), "BOOLs take or"); elsif op = Scan.sXor then return Scan.markHelp(x.pos, say1("\"xor\" needs integers, found {}", what(x)), "BOOLs that differ are #"); end; return Scan.markAt(x.pos, say2("{} needs BOOLs, found {}", Scan.symText(op), what(x))); end; (* x + y, of two string constants: one string, in a chunk of its own (report section 4) *) proc joinStr(var x, y: Item): ERROR; var p: ^U8; c, xs, ys, xl, yl: INT; begin if y.mode # mStr then return Scan.markAt(y.pos, say1("\"+\" joins two strings, found {}", what(y))); end; xs := Chunk.chunks[x.chunk].start; ys := Chunk.chunks[y.chunk].start; xl := INT(x.val); yl := INT(y.val); p := Scan.grab(xl + yl + 1); COPY(p[0..xl], Chunk.rodata[xs..xs + xl]); COPY(p[xl..xl + yl + 1], Chunk.rodata[ys..ys + yl + 1]); c := Chunk.newChunk(Chunk.secRodata, -1, -1); Chunk.setData(c, p, xl + yl + 1, 1); x.chunk := c; x.val := x.val + y.val; return nil; end; (* A set's operations, as operations on its bits: the two values on top *) proc setOp(op: Scan.Sym); begin match op of | sPlus: Gen.op(Scan.sBar, Gen.kWord, 8, false); | sTimes: Gen.op(Scan.sAmp, Gen.kWord, 8, false); | sMinus: Gen.complement(8, false); Gen.op(Scan.sAmp, Gen.kWord, 8, false); | sLeq, sGeq: (* x <= y has no bit of x outside y *) if op = Scan.sGeq then Gen.swap(); end; Gen.complement(8, false); Gen.op(Scan.sAmp, Gen.kWord, 8, false); Gen.pushConst(Gen.kWord, 0); Gen.compare(Scan.sEql, Gen.kWord, false); | sIn: Gen.swap(); Gen.op(Scan.sShr, Gen.kWord, 8, false); Gen.pushConst(Gen.kWord, 1); Gen.op(Scan.sAmp, Gen.kWord, 8, false); | else: Gen.compare(op, Gen.kWord, false); end; end; (* The operators the arithmetic of integers, of reals and of sets stand for, and the comparisons *) proc intOp(op: Scan.Sym): BOOL; begin return isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod, Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr]); end; proc doesntApply(op: Scan.Sym; x, y: Item; t: ^Sym.Type): ERROR; begin return Scan.markAt(Diag.join(x.pos, y.pos), say2("{} doesn't apply to {}", Scan.symText(op), Sym.typeName(t))); end; proc op2*(op: Scan.Sym; var x, y: Item; L: INT): ERROR; var xt, yt, t, e: ^Sym.Type; r: Item; scale: INT; isPtr: BOOL; a, b, v: I64; begin xt := x.typ; yt := y.typ; if y.mode in {mType, mBuiltin, mNone, mCase} then return notValue(y); end; if (op = Scan.sPlus) and (x.mode = mStr) then return joinStr(x, y); end; if (op = Scan.sAnd) or (op = Scan.sOr) then if xt^.form # Sym.fBool then return wrongLogic(op, x); end; if yt^.form # Sym.fBool then return wrongLogic(op, y); end; if (x.mode = mConst) and (y.mode = mConst) then if op = Scan.sAnd then x.val := x.val & y.val; else x.val := x.val | y.val; end; Gen.fix(L); (* op1's jump, if it made one, over no code *) elsif x.mode = mConst then (* true and y, false or y: y; else x, and y's code, which op1's jump to L passes over, is never run *) if (x.val = 1) = (op = Scan.sAnd) then x := y; else try discard(y); Gen.fix(L); end; else try makeCond(y); if op = Scan.sAnd then x.fj := Gen.joinJumps(x.fj, y.fj); x.tj := y.tj; else x.tj := Gen.joinJumps(x.tj, y.tj); x.fj := y.fj; end; x.rel := y.rel; x.relSigned := y.relSigned; end; return nil; end; if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (xt^.form = Sym.fBool) then return wrongLogic(op, x); end; if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (yt^.form = Sym.fBool) then return wrongLogic(op, y); end; (* the lengths, then the bytes, LEN * SIZE(T) of them: the elements are of types whose bytes say all there is to their values *) if ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(xt) then e := elemOf(xt); if not isSeq(yt) then return Scan.markAt(Diag.join(x.pos, y.pos), say1("can't compare an array with {}", Sym.typeName(yt))); elsif not Sym.same(e, elemOf(yt)) then return Scan.markAt(Diag.join(x.pos, y.pos), say2("can't compare an array of {} with one of {}", Sym.typeName(e), Sym.typeName(elemOf(yt)))); end; if e^.form = Sym.fReal then return Scan.markHelp(Diag.join(x.pos, y.pos), say1("can't compare arrays of reals with {}", Scan.symText(op)), "-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop"); elsif not (e^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fPtr}) then return Scan.markHelp(Diag.join(x.pos, y.pos), say2("can't compare arrays of {} with {}", Sym.typeName(e), Scan.symText(op)), "write a loop"); end; try seqSlice(y); Gen.compareSeq(x.off, y.off, log2(e^.size), op = Scan.sEql); makeConst(x, Sym.tBool, 0); x.mode := mStack; return nil; end; (* the type of the result, and the checks *) t := nil; scale := 1; isPtr := false; if Sym.isInt(xt) and Sym.isInt(yt) then if op = Scan.sSlash then return Scan.markHelp(Diag.join(x.pos, y.pos), "\"/\" divides reals, not integers", say2("to divide integers, write {} div {}", Diag.source(x.pos), Diag.source(y.pos))); end; if (op = Scan.sShl) or (op = Scan.sShr) then if xt^.form = Sym.fConst then t := Sym.tConst; else t := xt; end; elsif (xt^.form = Sym.fConst) and (yt^.form = Sym.fConst) then t := Sym.tConst; elsif xt^.form = Sym.fConst then if (x.mode = mConst) and not Sym.fits(x.val, yt) then return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(yt))])); end; t := yt; elsif yt^.form = Sym.fConst then if (y.mode = mConst) and not Sym.fits(y.val, xt) then return Scan.markAt(y.pos, Diag.say("{} doesn't fit {}", [Fmt.int(y.val), Fmt.str(Sym.typeName(xt))])); end; t := xt; elsif Sym.same(xt, yt) then t := xt; elsif widens(xt, yt) or widens(yt, xt) then (* an INT meeting an I64 widens to it, a UINT to a U64 (report section 6.1): the same 64 bits here, so only the type changes *) if widens(xt, yt) then t := yt; else t := xt; end; elsif smallWidens(xt, yt) or smallWidens(yt, xt) then (* a U8, I8 or I16 meeting an INT widens to it, unless an operator made it (report section 6.1); each operand is loaded as its own type, extended, so t is all that changes *) if x.made and smallWidens(xt, yt) then return madeNarrow(x, yt); end; if y.made and smallWidens(yt, xt) then return madeNarrow(y, xt); end; if smallWidens(xt, yt) then t := yt; else t := xt; end; else return mismatchOps(x, y, xt, yt); end; if not intOp(op) then return doesntApply(op, x, y, t); end; elsif (xt^.form = Sym.fReal) and (yt^.form = Sym.fReal) then if not (isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash])) then return doesntApply(op, x, y, xt); end; if xt = Sym.tRConst then t := yt; elsif (yt = Sym.tRConst) or Sym.same(xt, yt) then t := xt; else return mismatchOps(x, y, xt, yt); end; if (x.mode = mConst) and (x.typ # t) then realTo(x, t); end; if (y.mode = mConst) and (y.typ # t) then realTo(y, t); end; elsif (xt^.form = Sym.fBool) and (yt^.form = Sym.fBool) then if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end; t := Sym.tBool; elsif (xt^.form = Sym.fPtr) and Sym.isInt(yt) and ((op = Scan.sPlus) or (op = Scan.sMinus)) then try needSystem(Diag.join(x.pos, y.pos), "a pointer's arithmetic"); t := xt; scale := INT(xt^.base^.size); isPtr := true; if y.mode = mConst then y.typ := Sym.tInt; end; elsif (xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and (op = Scan.sMinus) then if not Sym.same(xt, yt) then return mismatchOps(x, y, xt, yt); end; t := Sym.tInt; scale := INT(xt^.base^.size); isPtr := true; 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 if not isRel(op) then return doesntApply(op, x, y, xt); end; if (xt^.form in {Sym.fProc, Sym.fError}) or (yt^.form in {Sym.fProc, Sym.fError}) then if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end; end; if (xt^.form # Sym.fNil) and (yt^.form # Sym.fNil) and not Sym.same(xt, yt) then if not ((xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and Sym.same(xt^.base, yt^.base)) then return mismatchOps(x, y, xt, yt); end; end; t := Sym.tU64; elsif (xt^.form = Sym.fEnum) and Sym.same(xt, yt) then if not isRel(op) then return doesntApply(op, x, y, xt); end; t := xt; elsif (xt^.form = Sym.fSet) and Sym.same(xt, yt) then if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sMinus, Scan.sEql, Scan.sNeq, Scan.sLeq, Scan.sGeq]) then return doesntApply(op, x, y, xt); end; t := xt; elsif (op = Scan.sIn) and (yt^.form = Sym.fSet) and Sym.same(xt, yt^.base) then t := yt; else return mismatchOps(x, y, xt, yt); end; (* constants *) if (x.mode = mConst) and (y.mode = mConst) and not isPtr then if t^.form = Sym.fReal then if not foldReal(op, x, y, t, r) then return doesntApply(op, x, y, xt); end; x := r; elsif t^.form = Sym.fSet then a := x.val; b := y.val; match op of | sPlus: makeConst(x, t, a | b); | sTimes: makeConst(x, t, a & b); | sMinus: makeConst(x, t, a & ~b); | sIn: makeConst(x, Sym.tBool, (b shr a) & 1); | sLeq: makeConst(x, Sym.tBool, bit((a & ~b) = 0)); | sGeq: makeConst(x, Sym.tBool, bit((b & ~a) = 0)); | else: makeConst(x, Sym.tBool, bit((a = b) = (op = Scan.sEql))); end; elsif isRel(op) then v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos)); makeConst(x, Sym.tBool, v); else v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos)); makeConst(x, t, cut(v, t)); x.made := true; end; return nil; end; (* x and y on the stack, x under y; a constant x goes on after y, and is left on top where the order doesn't matter, as Gen takes a constant best on the right: 0.25 * e is mulsd xmm8, [0.25] *) try value(y); if x.mode = mConst then try value(x); if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sAmp, Scan.sBar, Scan.sXor]) or isPtr then Gen.swap(); end; end; if t^.form = Sym.fReal then if isRel(op) then Gen.compare(op, Gen.kindOf(t), false); else Gen.op(op, Gen.kindOf(t), 8, false); end; elsif t^.form = Sym.fSet then setOp(op); elsif isRel(op) then x.mode := mCond; x.rel := op; x.relSigned := signed(t); x.fj := Gen.NoLabel; x.tj := Gen.NoLabel; x.typ := Sym.tBool; return nil; elsif isPtr then if t # Sym.tInt then scaleBy(scale); end; Gen.op(op, Gen.kWord, 8, false); if (t = Sym.tInt) and (scale # 1) then Gen.pushConst(Gen.kWord, scale); Gen.op(Scan.sDiv, Gen.kWord, 8, true); end; else Gen.op(op, Gen.kindOf(t), intSize(t), signed(t)); end; x.mode := mStack; if isRel(op) or (op = Scan.sIn) then x.typ := Sym.tBool; else x.typ := t; end; x.made := true; return nil; end; (* INT and UINT, the integers as big as an address, through which integers and pointers convert (report section 6.7) *) proc isWord*(t: ^Sym.Type): BOOL; begin return Sym.same(t, Sym.tInt) or Sym.same(t, Sym.tUInt); end; (* The x of ROL(x, n), left, or ROR(x, n), checked: of an unsigned integer type, since a rotation goes round within a width, which an untyped constant hasn't (report section 6.1). It is loaded, unless a constant, before n is read, as the left of an operator is by op1. *) proc rotand*(var x: Item; left: BOOL): ERROR; var name, s: []const U8; begin if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then return notValue(x); end; if left then name := "ROL"; else name := "ROR"; end; s := say2("{} needs an unsigned integer, found {}", name, what(x)); if x.typ = Sym.tConst then return Scan.markHelp(x.pos, s, say1("an untyped constant has no width to rotate in: give it a type, as in U32({})", Diag.source(x.pos))); end; if (x.typ^.form # Sym.fInt) or x.typ^.signed then return Scan.markAt(x.pos, s); end; if x.mode # mConst then try value(x); end; return nil; end; (* ROL(x, n), left, or ROR(x, n): x, of rotand, rotated by n modulo its width. Of two constants it is folded: right by k is left by w - k, and left by k is x shl k | x shr (w - k), cut to the width. *) proc rotate*(var x, n: Item; left: BOOL): ERROR; var w, k: I64; v: U64; begin if n.mode in {mType, mBuiltin, mNone, mCase, mStr} then return notValue(n); end; if not Sym.isInt(n.typ) then return Scan.markAt(n.pos, say1("expected an integer, found {}", what(n))); end; x.made := false; (* a built-in's result, not an operator's: it widens *) if (x.mode = mConst) and (n.mode = mConst) then w := bits(x.typ); k := n.val & (w - 1); if not left then k := (w - k) & (w - 1); end; v := U64(x.val); if k # 0 then v := v shl k | v shr (w - k); end; x.val := cut(I64(v), x.typ); return nil; end; try value(n); if x.mode = mConst then (* x goes on after n, which rotand didn't load, and under it *) try value(x); Gen.swap(); end; Gen.rotate(left, intSize(x.typ)); x.mode := mStack; return nil; end; (* ABS(x): x without its sign, of x's type, an integer or a real (report section 6.1). A signed integer's smallest value gives itself, as -x does, with no check, as -x has none; an untyped constant's, whose result would be beyond the I64s, is an error, as it is for -x. An unsigned integer is itself. Of a constant it is folded: a real's sign bit, the top one of the F64 it is held as, cleared. *) proc absolute*(var x: Item): ERROR; begin if x.mode in {mType, mBuiltin, mNone, mCase} then return notValue(x); end; if (x.mode = mStr) or not (Sym.isInt(x.typ) or (x.typ^.form = Sym.fReal)) then return Scan.markAt(x.pos, say1("ABS needs an integer or a real, found {}", what(x))); end; if x.mode = mConst then if x.typ^.form = Sym.fReal then x.val := x.val & MaxI64; elsif (x.typ^.form = Sym.fConst) and (x.val = MinI64) then return Scan.markAt(x.pos, "the constant is too big for I64"); elsif signed(x.typ) and (x.val < 0) then x.val := cut(-x.val, x.typ); end; else try value(x); if signed(x.typ) or (x.typ^.form = Sym.fReal) then Gen.abs(Gen.kindOf(x.typ), intSize(x.typ)); end; end; x.made := false; (* a built-in's result, not an operator's *) return nil; end; (* CLZ, CTZ or POPCOUNT, which, of v, a value w bits wide, folded *) proc countOf(which: INT; v: U64; w: I64): I64; var n, i: I64; begin n := 0; if which = Sym.bPopcount then for i := 0 to w - 1 do n := n + I64((v shr i) & 1); end; elsif which = Sym.bClz then while (n < w) and (((v shr (w - 1 - n)) & 1) = 0) do INC(n); end; else while (n < w) and (((v shr n) & 1) = 0) do INC(n); end; end; return n; end; (* CLZ(x), CTZ(x) or POPCOUNT(x), which: the zero bits of x above its highest one, below its lowest, or its one bits, an INT (report section 6.1). x is of an unsigned integer type, whose width is what 0 counts, or for POPCOUNT a set; an untyped constant has no width. Of a constant the count is folded. *) proc countBits*(var x: Item; which: INT): ERROR; var name, s: []const U8; ok: BOOL; begin if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then return notValue(x); end; if which = Sym.bClz then name := "CLZ"; elsif which = Sym.bCtz then name := "CTZ"; else name := "POPCOUNT"; end; if which = Sym.bPopcount then s := say2("{} needs an unsigned integer or a set, found {}", name, what(x)); else s := say2("{} needs an unsigned integer, found {}", name, what(x)); end; if x.typ = Sym.tConst then return Scan.markHelp(x.pos, s, say1("an untyped constant has no width to count in: give it a type, as in U32({})", Diag.source(x.pos))); end; ok := (x.typ^.form = Sym.fInt) and not x.typ^.signed; if (x.typ^.form = Sym.fSet) and (which = Sym.bPopcount) then ok := true; end; if not ok then return Scan.markAt(x.pos, s); end; if x.mode = mConst then makeConst(x, Sym.tInt, countOf(which, U64(x.val), bits(x.typ))); return nil; end; try value(x); if which = Sym.bPopcount then Gen.popCount(); else Gen.countZeros(which = Sym.bClz, intSize(x.typ)); end; x.typ := Sym.tInt; x.mode := mStack; x.made := false; (* a built-in's result, not an operator's *) return nil; end; (* MIN(T), or MAX(T) if max: the smallest or the largest value of the integer type t, an untyped constant (report section 6.1); p is where T is written. MAX(U64) and MAX(UINT) are above high(I64), where the untyped constants end, so they keep their type, as a hexadecimal number above it is a U64 (report section 3). *) proc limit*(var x: Item; t: ^Sym.Type; max: BOOL; p: Diag.Pos): ERROR; var name: []const U8; ones: U64; v: I64; begin if t^.form # Sym.fInt then if max then name := "MAX"; else name := "MIN"; end; return Scan.markAt(p, say2("{} needs an integer type, found {}", name, Sym.typeName(t))); end; ones := (~U64(0)) shr (64 - bits(t)); (* as many ones as t has bits *) if t^.signed then ones := ones shr 1; end; if max then v := I64(ones); elsif t^.signed then v := -I64(ones) - 1; else v := 0; end; if max and (v < 0) then makeConst(x, t, v); else makeConst(x, Sym.tConst, v); end; return nil; end; proc convert*(var x: Item; t: ^Sym.Type): ERROR; var s: ^Sym.Type; r: F64; begin s := x.typ; if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then if x.mode = mStr then return Scan.markAt(x.pos, "can't convert a string"); end; return notValue(x); end; x.made := false; (* what a conversion gives widens, U8(a + b) too *) if Sym.same(s, t) then return nil; end; (* a BOOL is 0 or 1, as a comparison's value is, so it converts as an integer does *) if (Sym.isInt(s) or (s^.form in {Sym.fEnum, Sym.fSet, Sym.fBool})) and (t^.form = Sym.fInt) then if x.mode = mConst then x.val := cut(x.val, t); else try value(x); Gen.narrow(INT(t^.size), t^.signed); end; elsif Sym.isInt(s) and (t^.form = Sym.fEnum) then if x.mode = mConst then if (x.val < 0) or (x.val >= t^.len) then return Scan.markAt(x.pos, Diag.say("{} isn't a position of {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))])); end; else try value(x); Gen.checkEnum(t^.len, nameChunk(t), x.pos); end; elsif Sym.isInt(s) and (t^.form = Sym.fSet) then if x.mode = mConst then if t^.len < 64 then x.val := x.val & ((I64(1) shl t^.len) - 1); end; else try value(x); if t^.len < 64 then Gen.pushConst(Gen.kWord, (I64(1) shl t^.len) - 1); Gen.op(Scan.sAmp, Gen.kWord, 8, false); end; end; elsif Sym.isInt(s) and (t^.form = Sym.fReal) then if x.mode = mConst then if (s^.form = Sym.fInt) and not s^.signed then r := F64(U64(x.val)); else r := F64(x.val); end; makeReal(x, r); realTo(x, t); else try value(x); Gen.intToReal(Gen.kindOf(t), (s^.form = Sym.fInt) and not s^.signed and (s^.size = 8)); end; elsif (s^.form = Sym.fReal) and (t^.form = Sym.fReal) then (* F32 to F64, F64 to F32, or a real constant to either *) if x.mode = mConst then realTo(x, t); else try value(x); Gen.realToReal(Gen.kindOf(s)); end; elsif (s^.form = Sym.fReal) and (t^.form = Sym.fInt) then if x.mode = mConst then r := realOf(x); (* NaN or out of range folds to low(int64), the "integer indefinite" cvttsd2si gives at run time *) if (r # r) or (r >= 9.2233720368547758E18) or (r < -9.2233720368547758E18) then x.val := cut(MinI64, t); else x.val := cut(I64(r), t); end; else try value(x); Gen.realToInt(Gen.kindOf(s)); Gen.narrow(INT(t^.size), t^.signed); end; elsif (isWord(s) or (s^.form in {Sym.fConst, Sym.fPtr, Sym.fProc, Sym.fNil})) and (t^.form in {Sym.fPtr, Sym.fProc}) then if s^.form # Sym.fNil then try needSystem(x.pos, say1("a conversion to {}", Sym.typeName(t))); end; if x.mode # mConst then try value(x); end; elsif (s^.form in {Sym.fPtr, Sym.fProc}) and isWord(t) then try needSystem(x.pos, say1("a conversion of a pointer to {}", Sym.typeName(t))); try value(x); elsif Sym.isInt(s) and (t^.form = Sym.fBool) then return Scan.markHelp(x.pos, say1("can't convert {} to BOOL", Sym.typeName(s)), say1("a comparison says it: {} # 0", Diag.source(x.pos))); else return Scan.markAt(x.pos, say2("can't convert {} to {}", Sym.typeName(s), Sym.typeName(t))); end; x.typ := t; return nil; end; (* Calls *) proc beginCall*(var c: Gen.CallInfo; var x: Item): ERROR; begin if x.mode = mProc then c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0; c.obj := x.obj; c.ext := x.obj^.ext; else c.obj := nil; c.ext := false; if x.typ^.form # Sym.fProc then return Scan.markAt(x.pos, say1("expected a procedure, found {}", what(x))); end; c.sig := x.typ; c.chunk := -1; c.target := try toSlot(x); end; c.param := c.sig^.fields; c.n := 0; return nil; end; (* Too many arguments or too few, at p *) proc wrongCount(var c: Gen.CallInfo; p: Diag.Pos; text: []const U8): ERROR; begin if c.obj = nil then return Scan.markAt(p, text); end; Diag.error(p, Diag.say("{}: {} takes {}", [Fmt.str(text), Fmt.str(Scan.nameOf(c.obj^.name)), Fmt.int(c.sig^.len)])); if c.obj^.home # nil then Diag.note(c.obj^.pos, "the signature is here"); end; return Scan.Failed; end; (* Pushes the two words of x, a slice or two results (inTwoRegs), read from memory now, so that what comes after can't change them. *) proc pushWords(var x: Item): ERROR; var adr: Gen.Adr; f: ^Sym.Obj; begin if x.mode = mWords then return nil; end; (* there already *) (* copied to a temporary unless its two words are in memory at a place that a later argument can't change *) if (x.mode # mVar) or x.vol or not (x.base in {Gen.bFrame, Gen.bGlobal, Gen.bSlot, Gen.bReg, Gen.bPtr}) then try copyToTemp(x); end; adr := adrOf(x); if x.typ^.form = Sym.fSlice then Gen.pushVar(adr, 8, false, Gen.kWord); INC(adr.off, 8); Gen.pushVar(adr, 8, false, Gen.kWord); else f := x.typ^.fields; while f # nil do adr.off := adrOf(x).off + f^.val; Gen.pushVar(adr, scalarSize(f^.typ), signed(f^.typ), Gen.kindOf(f^.typ)); f := f^.next; end; end; return nil; end; (* An address given where a var or const parameter of its type wants the variable itself, as ADR(b) for var b: Buf: an error that says what to write instead, b for SYSTEM.ADR(b) or ADR(b), and p^ for a pointer p. Mostly met in programs written before the library took var (report 2026-10.33). *) proc givenAddress(const a: Item; p: ^Sym.Obj): ERROR; var s, kind: []const U8; k: INT; begin if (a.typ^.form # Sym.fPtr) or (a.typ^.base = nil) or not Sym.same(a.typ^.base, p^.typ) then return nil; end; if p^.isConst then kind := "const"; else kind := "var"; end; s := Diag.source(a.pos); k := 0; (* past SYSTEM., as ADR is written in a module that imports it *) if (LEN(s) > 7) and (s[0..7] = "SYSTEM.") then k := 7; end; if (LEN(s) > k + 5) and (s[k..k + 4] = "ADR(") and (s[LEN(s) - 1] = ')') then s := Diag.say("write {} for {}: the parameter is the variable itself, not its address", [Fmt.str(s[k + 4..LEN(s) - 1]), Fmt.str(s)]); else s := Diag.say("write {}^ for {}: the parameter is the variable itself, not a pointer to it", [Fmt.str(s), Fmt.str(s)]); end; return Scan.markHelp(a.pos, say2("a {} parameter takes {}, found its address", kind, Sym.typeName(p^.typ)), s); end; (* A const parameter's argument that isn't a variable, or is one with no address of its own (a packed record's field, a view, through ^VOLATILE), in a temporary of the statement, or of the procedure if it holds an array, whose address then goes (report section 8): a slice's two words, a record or an array copied, or a single value stored. *) proc constTemp(var x: Item): ERROR; var t: I64; begin if x.typ^.form = Sym.fSlice then try pushWords(x); t := Gen.allocTemp(16, 8); Gen.popVar(frameAdr(t + 8), 8); (* the length, on top *) Gen.popVar(frameAdr(t), 8); elsif Sym.isAggregate(x.typ) then if x.view then return noAddress(x, "a view of a record or an array can't be a const parameter"); end; if not Sym.holdsArray(x.typ) then return copyToTemp(x); end; (* a slice of it may come back and be kept to the end of the procedure (report 8), so its slot lasts as long *) if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; try address(x); t := Gen.allocPerm(x.typ^.size, x.typ^.align); Gen.copyTo(frameAdr(t), x.typ^.size); else try value(x); t := Gen.allocTemp(x.typ^.size, x.typ^.align); Gen.popVar(frameAdr(t), scalarSize(x.typ)); end; tempItem(x, x.typ, t); return nil; end; proc passArg*(var c: Gen.CallInfo; var a: Item): ERROR; var p: ^Sym.Obj; begin p := c.param; if c.n >= LEN(c.isF) - 1 then return Scan.markAt(a.pos, "too many arguments"); end; if p = nil then (* past the parameters of a C procedure that ends in ...: a string goes as a C string, an integer constant as an INT, a real constant as an F64; C takes no F32 there *) if not c.sig^.variadic then return wrongCount(c, a.pos, "too many arguments"); end; if a.mode = mStr then try coerce(a, Sym.tPtrU8); elsif a.typ^.form = Sym.fConst then try coerce(a, Sym.tInt); elsif a.typ = Sym.tRConst then try coerce(a, Sym.tReal); elsif isF32(a.typ) then return Scan.markAt(a.pos, "an F32 goes to ... as F64(x)"); elsif not Sym.isScalar(a.typ) then return Scan.markAt(a.pos, "only a single value goes to ..."); end; c.isF[c.n] := a.typ^.form = Sym.fReal; c.pair[c.n] := false; try value(a); INC(c.n); return nil; end; c.isF[c.n] := (p^.typ^.form = Sym.fReal) and not p^.isVar; passing := p; passingAt := a.pos; if p^.isConst then (* by address, as var, but any expression of the type: a variable, or a constant in read-only data, in place; anything else in a temporary. Before: value parameter, a record: copied to a temporary, its address goes after, for const: its own address goes; nothing is copied *) try givenAddress(a, p); try coerce(a, p^.typ); if (a.mode # mVar) or a.odd or a.view or a.vol then try constTemp(a); end; try address(a); elsif p^.isVar then try givenAddress(a, p); try notReadOnly(a); if (a.mode # mVar) or not a.isVar then return Scan.markAt(a.pos, "a var parameter needs a variable"); end; if a.odd then return Scan.markAt(a.pos, "a field of a packed record can't be a var parameter"); end; if a.view then return noAddress(a, "a view can't be a var parameter"); end; if not Sym.same(a.typ, p^.typ) then return mismatch(a, say2("a var parameter needs exactly {}, found {}", Sym.typeName(p^.typ), what(a))); end; if a.vol then return Scan.markAt(a.pos, "can't pass through a volatile pointer to a var parameter"); end; try address(a); elsif p^.typ^.form = Sym.fSlice then try coerce(a, p^.typ); try pushWords(a); c.pair[c.n] := true; INC(c.n); c.isF[c.n] := false; elsif Sym.isAggregate(p^.typ) then try coerce(a, p^.typ); if a.isVar or a.vol or (a.base # Gen.bFrame) then try copyToTemp(a); end; try address(a); else try coerce(a, p^.typ); try value(a); end; c.pair[c.n] := false; INC(c.n); c.param := p^.next; return nil; end; (* The call c made, with x its result as an item: none; a temporary, for a slice or a record; two results on Gen's stack (mWords); else one value on the stack. *) proc endCall*(var c: Gen.CallInfo; var x: Item): ERROR; var res: ^Sym.Type; begin if c.param # nil then try wrongCount(c, Scan.tokPos(), "too few arguments"); end; if (c.obj # nil) and (c.obj^.inl # 0) then Gen.realInPlace(c.obj^.inl); (* Math.sqrt: an instruction, no call *) else Gen.call(c); end; res := c.sig^.base; x := {}; if res = nil then x.mode := mNone; x.typ := Sym.tNone; x.obj := c.obj; elsif c.ret # 0 then tempItem(x, res, c.ret); else x.mode := mStack; x.typ := res; if res^.tuple then x.mode := mWords; end; end; return nil; end; (* Variants *) (* Whether the record literal about to be parsed is the whole of a return (see zeroTemp): Parse says so, and clears it after the expression. *) var inResult: BOOL; proc literalInResult*(yes: BOOL); begin inResult := yes; end; (* A temporary of type t, not cleared: where a record literal is made, which clears only what its fields leave (zeroRange). With literalInResult it is behind the hidden pointer, so that return {...} makes the record where the caller wants it, not in a temporary copied there after. *) proc tempOf*(var x: Item; t: ^Sym.Type); var tmp: I64; p: Diag.Pos; begin if inResult and (t = result) then inResult := false; p := x.pos; x := {}; x.pos := p; x.mode := mVar; x.typ := t; x.base := Gen.bSlot; x.chunk := INT(Gen.resultSlot()); return; end; tmp := Gen.allocTemp(t^.size, t^.align); tempItem(x, t, tmp); end; (* A temporary of type t, all zero: for variants. *) proc zeroTemp*(var x: Item; t: ^Sym.Type); begin tempOf(x, t); Gen.zeroVar(adrOf(x), t^.size); end; (* size bytes, off bytes into the variable x, cleared *) proc zeroRange*(const x: Item; off, size: I64); var a: Gen.Adr; begin a := adrOf(x); a.off := a.off + off; Gen.zeroVar(a, size); end; proc construct*(var x: Item; c: ^Sym.Obj); begin zeroTemp(x, c^.typ); Gen.pushConst(Gen.kWord, c^.val); Gen.popVar(frameAdr(x.off), 8); end; proc setField*(const x: Item; f: ^Sym.Obj; var a: Item): ERROR; var at: Gen.Adr; begin at := adrOf(x); at.off := at.off + f^.val; try coerce(a, f^.typ); if Sym.isScalar(f^.typ) then try value(a); Gen.popVar(at, scalarSize(f^.typ)); else if a.vol then return Scan.markAt(a.pos, "can't copy through a volatile pointer"); end; try address(a); Gen.copyTo(at, f^.typ^.size); end; return nil; end; (* The slot match tests: a variant's address, an enumeration's or an integer's value, or a string's slice, which x then is. *) proc matchBegin*(var x: Item): (I64, ERROR); var p: I64; begin if x.typ^.form in {Sym.fEnum, Sym.fInt} then return toSlot(x); end; if isSeq(x.typ) and Sym.same(elemOf(x.typ), Sym.tU8) then try seqSlice(x); return x.off, nil; end; if (x.mode # mVar) or (x.typ^.form # Sym.fVariant) then return 0, Scan.markAt(x.pos, say1("match needs a variant, an enumeration, an integer or a string, found {}", what(x))); end; (* another module's variable: its arms' names stand for a copy's fields; what is only read is matched in place, its names only read too *) if x.ro and not onlyRead(x) then try copyToTemp(x); end; try address(x); p := Gen.allocTemp(8, 8); Gen.popVar(frameAdr(p), 8); return p, nil; end; (* To L unless the tag of the variant whose address is in slot p is tag *) proc matchTag*(p: I64; tag: I64; var L: INT); var a: Gen.Adr; begin Gen.pushVar(frameAdr(p), 8, false, Gen.kWord); a.base := Gen.bStack; a.chunk := -1; a.off := 0; a.hi := 0; Gen.pushVar(a, 8, false, Gen.kWord); Gen.pushConst(Gen.kWord, tag); Gen.jumpCmp(Scan.sNeq, false, L); end; (* For a label s of a match on the string whose slice is in slot p: to body if they are equal, or, for the arm's last label, to L if they aren't. *) proc matchStr*(p: I64; var s: Item; last: BOOL; var L, body: INT): ERROR; begin try seqSlice(s); Gen.compareSeq(p, s.off, 0, true); if last then Gen.jumpIf(L, false); else Gen.jumpIf(body, true); end; return nil; end; (* To body if the integer in slot p is from lo to hi: less its lo, it is then at most hi - lo, compared unsigned, which holds for a signed type or not, with no second jump. *) proc matchRange*(p, lo, hi: I64; var body: INT); begin Gen.pushVar(frameAdr(p), 8, false, Gen.kWord); if lo = hi then Gen.pushConst(Gen.kWord, lo); Gen.jumpCmp(Scan.sEql, false, body); return; end; if lo # 0 then Gen.pushConst(Gen.kWord, lo); Gen.op(Scan.sMinus, Gen.kWord, 8, false); end; Gen.pushConst(Gen.kWord, hi - lo); Gen.jumpCmp(Scan.sLeq, false, body); end; (* A for loop's variable o, stepped by step, wrapping as its type does *) proc forStep*(o: ^Sym.Obj; step: I64): ERROR; var v, w: Item; begin try makeItem(v, o); if v.base = Gen.bReg then (* a variable in a register is stepped in it *) Gen.pushConst(Gen.kWord, step); Gen.incDecReg(v.chunk, intSize(o^.typ), signed(o^.typ), false); return nil; end; try makeItem(w, o); try value(w); Gen.pushConst(Gen.kWord, step); Gen.op(Scan.sPlus, Gen.kWord, intSize(o^.typ), signed(o^.typ)); return assign(v, w); end; (* For a for loop: pushes the variable o and the limit lim, a constant or the slot it was put in, and jumps to L if the one is op the other, as the type of o compares *) proc forCmp*(o: ^Sym.Obj; const lim: Item; op: Scan.Sym; var L: INT): ERROR; var v, b: Item; begin try makeItem(v, o); try value(v); b := lim; try value(b); Gen.jumpCmp(op, o^.typ^.signed, L); return nil; end; (* The end of a round of a for loop, for a positive step s, as the report has it: if v <= b and b - v < s, the loop ends; otherwise v becomes v + s and the loop goes on while v <= b. Counting the distance left, rather than comparing after the step, can't be fooled by v wrapping around. A negative step is the same the other way round: before, past and within are chosen by up, whether the step is positive. For a step of 1: v < b goes on to top, where v is stepped; v = b ends; otherwise the body moved v past b. For another step: v past b goes to past; else b - v (unsigned, as v <= b) >= |step| goes on to top, and else the loop ends. Past: v is stepped here and tested, going to body if within b. *) proc forNext*(o: ^Sym.Obj; const lim: Item; step: I64; var exitL: INT; top, body: INT): ERROR; var v, b: Item; L, pastL: INT; up: BOOL; before, past, within: Scan.Sym; a: I64; begin up := step > 0; (* by a negative step, by a positive *) if up then before := Scan.sLss; past := Scan.sGtr; within := Scan.sLeq; else before := Scan.sGtr; past := Scan.sLss; within := Scan.sGeq; end; a := step; if a < 0 then a := -a; end; L := Gen.NoLabel; pastL := Gen.NoLabel; if a = 1 then try forCmp(o, lim, before, L); Gen.fixTo(L, top); try forCmp(o, lim, Scan.sEql, exitL); else try forCmp(o, lim, past, pastL); try makeItem(v, o); b := lim; if up then try value(b); try value(v); else try value(v); try value(b); end; Gen.op(Scan.sMinus, Gen.kWord, 8, false); Gen.pushConst(Gen.kWord, a); Gen.jumpCmp(Scan.sGeq, false, L); Gen.fixTo(L, top); Gen.jump(exitL); end; Gen.fix(pastL); try forStep(o, step); L := Gen.NoLabel; try forCmp(o, lim, within, L); Gen.fixTo(L, body); return nil; end; (* Jumps to L if the condition x is false. The jumps waiting in x.fj join L; those in x.tj are placed here, as x is true past this. *) proc condJump*(var x: Item; var L: INT): ERROR; begin if x.typ^.form # Sym.fBool then return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x))); end; if x.mode = mCond then Gen.jumpCmp(negated(x.rel), x.relSigned, L); L := Gen.joinJumps(L, x.fj); Gen.fix(x.tj); return nil; end; try value(x); Gen.jumpIf(L, false); return nil; end; (* As condJump, but the jump to L is taken where the condition is true; x.tj joins L and x.fj is placed here *) proc condJumpTrue*(var x: Item; var L: INT): ERROR; begin if x.typ^.form # Sym.fBool then return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x))); end; if x.mode = mCond then Gen.jumpCmp(x.rel, x.relSigned, L); L := Gen.joinJumps(L, x.tj); Gen.fix(x.fj); return nil; end; try value(x); Gen.jumpIf(L, true); return nil; end; (* Procedures *) proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj); begin result := sig^.base; Gen.beginProc(sig, params); end; (* The result of return x: a value on top, a slice's two words on top, or one copied behind the hidden pointer *) (* A slice returned must not point into the procedure's own frame, which is gone once it returns (report section 7.3). Only what can be seen in the expression is caught: a local array, a value parameter that is one, an array literal or a temporary, or a slice of one, a field or an element of one included; x.frame says so, set where the variable is named and kept through fields, elements and slices. *) proc notOfFrame(const x: Item; t: ^Sym.Type): ERROR; begin if (t^.form = Sym.fSlice) and x.frame then return Scan.markHelp(x.pos, "can't return a slice of the procedure's own frame", "it is gone once the procedure returns: take the array as a var parameter, or fill a buffer the caller gives"); end; return nil; end; proc returnValue*(var x: Item): ERROR; begin if result = nil then return Scan.markAt(x.pos, "this procedure returns nothing"); end; try coerce(x, result); try notOfFrame(x, result); if Sym.inTwoRegs(result) then try pushWords(x); elsif Sym.isAggregate(result) then (* a record literal made behind the hidden pointer is there already *) if (x.base = Gen.bSlot) and (x.chunk = INT(Gen.resultSlot())) and (x.off = 0) then return nil; end; if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; try address(x); Gen.copyResult(0, result^.size); else try value(x); end; return nil; end; (* One of several results: of two words, a value left on top for returnJump to put in rax or rdx; else into its place behind the hidden pointer. *) proc returnField*(f: ^Sym.Obj; var x: Item): ERROR; begin try coerce(x, f^.typ); try notOfFrame(x, f^.typ); if Sym.inTwoRegs(result) then try value(x); elsif Sym.isScalar(f^.typ) then try value(x); Gen.resultTo(f^.val, scalarSize(f^.typ)); else if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; try address(x); Gen.copyResult(f^.val, f^.typ^.size); end; return nil; end; (* Several results at once, the call's that return f(x) passes on. *) proc returnAll*(var x: Item): ERROR; begin if Sym.inTwoRegs(result) then try pushWords(x); else try address(x); Gen.copyResult(0, result^.size); end; return nil; end; proc returnNone*: ERROR; begin if result # nil then return Scan.mark(say1("return needs a result of {}", Sym.typeName(result))); end; Gen.returnJump(); return nil; end; (* Keeps a variable's address in a frame slot, rather than on the stack, while other code runs. *) proc pin*(var x: Item): ERROR; var s: I64; begin if (x.mode = mVar) and (x.base = Gen.bStack) then try address(x); s := Gen.allocTemp(8, 8); Gen.popVar(frameAdr(s), 8); x.base := Gen.bSlot; x.chunk := INT(s); end; return nil; end; (* INC(v, k) or DEC: v's address is on the stack, from address. *) proc incDec*(var v, k: Item; dec: BOOL): ERROR; begin try coerce(k, v.typ); try value(k); if v.base = Gen.bReg then Gen.incDecReg(v.chunk, scalarSize(v.typ), v.typ^.signed, dec); else Gen.incDec(scalarSize(v.typ), v.typ^.signed, dec); end; return nil; end; (* COPY(d, s) or FILL(d, x): d, an array variable or a slice, as a slice in the frame, before s or x is read; text says what the built-in writes into, for an error *) proc destSlice(var d: Item; text: []const U8): ERROR; begin if (d.typ^.form = Sym.fArray) and (d.mode = mVar) then try notReadOnly(d); end; if (d.typ^.form = Sym.fSlice) and d.typ^.rdonly then return Scan.markHelp(d.pos, say1("{} is a []const slice, whose elements can't be changed", Diag.source(d.pos)), "write them through a []T"); end; if not isSeq(d.typ) or (d.mode = mStr) or ((d.typ^.form = Sym.fArray) and ((d.mode # mVar) or not d.isVar)) then return Scan.markAt(d.pos, say1(text, what(d))); end; return seqSlice(d); end; proc copyDest*(var d: Item): ERROR; begin return destSlice(d, "COPY copies into an array variable or a slice, found {}"); end; proc fillDest*(var d: Item): ERROR; begin return destSlice(d, "FILL fills an array variable or a slice, found {}"); end; (* ... and each of its elements set to x, as by :=; t is d's type as it was written, so that an array's length is known *) proc fillWith*(var d, x: Item; t: ^Sym.Type): ERROR; var e: ^Sym.Type; n: I64; begin e := d.typ^.base; try coerce(x, e); if Sym.isScalar(e) then try value(x); else if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; if (x.mode = mVar) and (x.base = Gen.bReg) then try copyToTemp(x); end; (* a slice in registers *) try address(x); end; n := -1; if t^.form = Sym.fArray then n := t^.len; end; Gen.fillSlice(d.off, e^.size, n, Sym.isScalar(e)); return nil; end; (* ... and the elements of s copied to its start *) proc copyFrom*(var d, s: Item): ERROR; begin if not isSeq(s.typ) or not Sym.same(elemOf(s.typ), d.typ^.base) then return Scan.markAt(s.pos, say2("COPY copies elements of {}, found {}", Sym.typeName(d.typ^.base), what(s))); end; try seqSlice(s); Gen.copySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos); return nil; end; (* An error is the address of its length, followed by its message. *) proc errorChunk*(var x: Item; home, name: INT): (INT, ERROR); var c, xs, xl: INT; p: ^U8; q: ^I64; begin if x.mode # mStr then return 0, Scan.markHelp(x.pos, say1("an error is made from a string, found {}", what(x)), "or from another ERROR constant, which is the same error"); end; xl := INT(x.val); p := Scan.grab(xl + 8); q := ^I64(p); q^ := x.val; xs := Chunk.chunks[x.chunk].start; COPY(p[8..8 + xl], Chunk.rodata[xs..xs + xl]); c := Chunk.newChunk(Chunk.secRodata, home, name); Chunk.setData(c, p, xl + 8, 8); return c, nil; end; proc msg*(var x: Item): ERROR; var s: I64; begin try coerce(x, Sym.tError); try value(x); s := Gen.allocTemp(16, 8); Gen.errorText(s); tempItem(x, Sym.tConstBytes, s); (* the message is constant *) return nil; end; end Item.