From 6089fb3ba15c23b4964d5f9b2c006a165a591ea0 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:09:05 +0100 Subject: [PATCH] Record constants, constant tables, and Str.copy Report 2026-10.16. AggregateConst reads an array or record constant part by part (ConstPart) into a rodata chunk: numbers, sets and the like as before, a string into a []U8 or a [n]U8, an array constant into a slice, procedures, ERRORs and nil. An address in it is a data fixup (chunk.pas's AddDataFixup), a 64-bit field the linker fills with the chunk's address; MarkLive follows them. MakeItem makes a record constant a read-only variable, as an array constant is. Str.copy copies a slice into memory from an allocator. conform/run/RecordConst; conform/err/ArrayConstElem now refuses a variant. 7,891 lines of code. --- diff --git a/CLAUDE.md b/CLAUDE.md index 5bb5d2e..bfb9334 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -86,12 +86,13 @@ defect, and the library grows only by what breaks no program written for it. A wish for more, the owner's or yours, goes on the list in `PLAN.md`, for a later thaw; it isn't built. v0.6.0 was such a thaw, -by the owner's word: report 2026-10.12; the compiler follows 2026-10.15, +by the owner's word: report 2026-10.12; the compiler follows 2026-10.16, whose `Sys` writes without waiting, for rat's pastes (10.13), and whose blank, `_ := f(x)`, drops a result that is otherwise warned of (10.14), and whose `Math` has `pow`, the logarithms to 2 and 10, -rounding and the inverse functions, and `Sys` `space` (10.15), also -by the owner's word. Its parser +rounding and the inverse functions, and `Sys` `space` (10.15), and +whose constants may be records and tables of them, with `Str.copy` +(10.16), also by the owner's word. Its parser reaches the machine only through `gen.pas`; its steps 5 to 10 await the owner's review, and git has them. Keep `doc/compiler.md`'s table of lines and its routine names true when the diff --git a/conform/err/ArrayConstElem.raz b/conform/err/ArrayConstElem.raz index da1aabe..352662d 100644 --- a/conform/err/ArrayConstElem.raz +++ b/conform/err/ArrayConstElem.raz @@ -1,4 +1,4 @@ module ArrayConstElem; -type R = record a: I64; end; -const P: [1]R = [{a: 1}]; +type S = variant a; b; end; +const P: [1]S = [a]; end ArrayConstElem. diff --git a/conform/run/RecordConst.expect b/conform/run/RecordConst.expect new file mode 100644 index 0000000..662a8bb --- /dev/null +++ b/conform/run/RecordConst.expect @@ -0,0 +1,9 @@ +firefox 2 +mpv 0 float + 0 +30 +home7 +3 +bye113 +hello 5 +nil run diff --git a/conform/run/RecordConst.raz b/conform/run/RecordConst.raz new file mode 100644 index 0000000..9e4bdda --- /dev/null +++ b/conform/run/RecordConst.raz @@ -0,0 +1,34 @@ +module RecordConst; +import Out; +type + Act = (quit, focus, spawn); + Rule = record cls: []U8; tag: INT; float: BOOL; end; + Key = record mods: U8; sym: U32; act: Act; arg: [8]U8; run: proc(n: INT); end; +const + Rules: [3]Rule = [{cls: "firefox", tag: 2}, {cls: "mpv", float: true}, {}]; + Nums: [3]I64 = [10, 20, 30]; + Lists: [2][]I64 = [Nums, Nums]; + Home: Rule = {cls: "home", tag: 7}; + Grid: [2][2]U8 = [[1, 2], [3, 4]]; +proc hello(n: INT); +begin + Out.str("hello "); Out.int(n); Out.ln; +end; +const Keys: [2]Key = [{mods: 4, sym: 113, act: quit, arg: "bye", run: hello}, {act: spawn, run: nil}]; +proc main*; +var i: INT; r: Rule; +begin + for i := 0 to LEN(Rules) - 1 do + Out.str(Rules[i].cls); Out.str(" "); Out.int(Rules[i].tag); Out.str(" "); + if Rules[i].float then Out.str("float"); end; + Out.ln; + end; + Out.int(Lists[1][2]); Out.ln; + r := Home; + Out.str(r.cls); Out.int(Home.tag); Out.ln; + Out.int(I64(Grid[1][0])); Out.ln; + Out.str(Keys[0].arg[0..3]); Out.int(INT(Keys[0].sym)); Out.ln; + Keys[0].run(5); + if Keys[1].run = nil then Out.str("nil run"); Out.ln; end; +end; +end RecordConst. diff --git a/doc/compiler.md b/doc/compiler.md index 2fcbe2d..275be04 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -11,12 +11,12 @@ | `src/diag.pas` | 310 | 229 | Messages: positions, source excerpts, colour, counts | | `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions | | `src/sym.pas` | 615 | 510 | Types, objects, scopes, layout | -| `src/chunk.pas` | 276 | 217 | The compiled program: chunks, fixups, line notes | +| `src/chunk.pas` | 298 | 232 | The compiled program: chunks, fixups, line notes | | `src/x64.pas` | 1,039 | 870 | The instruction encoder, jumps within a procedure, the assembler | | `src/gen.pas` | 1,332 | 1,039 | The stack machine, for x86-64: values, operations, checks, calls, frames | | `src/item.pas` | 1,342 | 1,118 | Items: types, constants, variables, operators, conversions, calls | -| `src/parse.pas` | 2,712 | 2,407 | Declarations, statements, expressions, built-ins, recovery, warnings | -| `src/link.pas` | 234 | 180 | Tree shaking, layout, patching, the places | +| `src/parse.pas` | 2,771 | 2,459 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/link.pas` | 243 | 188 | Tree shaking, layout, patching, the places | | `src/elf.pas` | 435 | 352 | Static and dynamic ELF, symbol table, line numbers | | `src/raz.pas` | 197 | 147 | The command line | @@ -219,7 +219,10 @@ A *fixup* (`TFixup`) is a 32-bit field in the code that will hold the distance to another chunk: a call's target, or a rip-relative address. -`AddFixup` records one; `link.pas` fills them in. `NoteLine` records +`AddFixup` records one; `link.pas` fills them in. A constant's +addresses are *data fixups*, `AddDataFixup`'s: 64-bit fields in +rodata that will hold a chunk's address itself, since the executable is +loaded where the linker placed it. `NoteLine` records which line and column of the source the code from `pc` on belongs to, for gdb and for the places. `ExternChunk` makes, once per C symbol, the quadword the dynamic loader will fill with that symbol's address. @@ -380,9 +383,11 @@ variable into an item for part of it, mostly by adding to `off`. An item for another module's exported variable, or part of it, is `ro`: it isn't a variable (`isVar`), and `NotReadOnly` says why where one is -wanted; what it points at is. An array constant is a variable too, in -read-only data: `ArrayConst` (`parse.pas`) reads its literal into the -bytes of a chunk, as a string constant's are, and `MakeItem` makes it +wanted; what it points at is. An array or record constant is a +variable too, in read-only data: `AggregateConst` (`parse.pas`) reads +its literal, part by part in `ConstPart`, into the bytes of a chunk, +as a string constant's are; an address in it, of a string, an array +constant, a procedure or an `ERROR`, becomes a data fixup. `MakeItem` makes it an `mVar` there that isn't `isVar`, so it is read, indexed, sliced and passed, never changed. `Index` and `Slice` have gen make the bounds checks, unless the module says `check off;` (`checks`, which @@ -505,11 +510,12 @@ ## link.pas: tree shaking and layout `MarkLive` starts from the entry chunk and follows fixups, marking each -chunk it reaches; nothing else goes into the executable. `LinkAll` +chunk it reaches, through the data fixups of constants too; nothing +else goes into the executable. `LinkAll` places the live chunks section by section (`Place`), each at its alignment, then copies their bytes into the images of text and rodata, patching every fixup with the distance from the end of its field to its -target. +target, and every data fixup with its target's address. Between placing text and placing rodata, `MakePlaces` writes the places, a rodata chunk: for each line note in live code, its address, diff --git a/lib/Str.raz b/lib/Str.raz index 022e252..2804abd 100644 --- a/lib/Str.raz +++ b/lib/Str.raz @@ -1,11 +1,23 @@ (* Operations on strings, which are []U8. = and # compare them; this module orders, searches and hashes them, reads and writes their - UTF-8, and reads a number from one. *) + UTF-8, reads a number from one, and copies one to keep. *) module Str; -import Rt; +import Mem, Heap, Rt; const least = -9223372036854775807 - 1; (* the smallest I64 *) +(* s's bytes, copied into memory from a, to keep after s's own are + gone; "" and false if a has no room. *) +proc copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL); +var p: ^U8; i: INT; +begin + if LEN(s) = 0 then return "", true; end; + p := Mem.alloc(a, LEN(s), 1); + if p = nil then return "", false; end; + for i := 0 to LEN(s) - 1 do p[i] := s[i]; end; + return p[0..LEN(s)], true; +end; + (* -1, 0 or 1 as a sorts before, with or after b, byte by byte. *) proc cmp*(a, b: []U8): INT; var i, n: INT; @@ -258,7 +270,12 @@ (* The module's test: stops the program if something is wrong. *) proc main*; +var buf: [3]U8; t: []U8; ok: BOOL; begin + buf := "abc"; + t, ok := copy(Heap.heap, buf); + buf[0] := 'x'; + if not ok or (t # "abc") then Rt.stop("Str.copy"); end; if (cmp("a", "b") # -1) or (cmp("b", "a") # 1) or (cmp("ab", "ab") # 0) or (cmp("a", "ab") # -1) or (cmp("", "") # 0) then Rt.stop("Str.cmp"); end; if not eq("x", "x") or eq("x", "y") then Rt.stop("Str.eq"); end; diff --git a/src/chunk.pas b/src/chunk.pas index dd30556..8e191fa 100644 --- a/src/chunk.pas +++ b/src/chunk.pas @@ -28,7 +28,7 @@ TChunk = record sec: TSection; start, size, align: longint; { in its section's buffer } - firstFix, numFix: longint; { its fixups, text chunks only } + firstFix, numFix: longint; { its fixups: text's in fixups, rodata's in dataFixups } module, name: longint; { for the symbol table; -1 if none } adr: int64; { its address, set by the linker } live: boolean; { reached from the entry point } @@ -53,7 +53,8 @@ end; TFixup = record - at: longint; { the 32-bit field, as an offset in text } + at: longint; { the 32-bit field, as an offset in text; in + dataFixups, the 64-bit one, from its chunk's start } chunk: longint; { the chunk it refers to } addend: longint; { added to the chunk's address } end; @@ -74,6 +75,11 @@ numChunks: longint; fixups: PFixups; numFixups: longint; + { Addresses in read-only data, as in an array constant of strings: + each 8 bytes, the chunk's absolute address, since the executable + is loaded where the linker placed it } + dataFixups: PFixups; + numDataFixups: longint; lines: PLines; numLines: longint; curFile: longint; { the file being compiled, for NoteLine } @@ -89,6 +95,7 @@ function ExternChunk(name: longint): longint; procedure NoteLine(line, col: longint); procedure AddFixup(at, chunk, addend: longint); +procedure AddDataFixup(c, at, chunk, addend: longint); procedure NoteVar(chunk, name, off, kind: longint); function ChunkName(c: longint): shortstring; @@ -181,6 +188,8 @@ rodata := ReAllocMem(rodata, roCap); end; Move(p^, rodata^[rolen], n); + chunks^[c].firstFix := numDataFixups; + chunks^[c].numFix := 0; chunks^[c].start := rolen; chunks^[c].size := n; chunks^[c].align := align; @@ -235,6 +244,19 @@ fixups^[numFixups].chunk := chunk; fixups^[numFixups].addend := addend; inc(numFixups); +end; + +{ The address of chunk, plus addend, at offset at of rodata chunk c, + whose data is set: its fixups follow one another. } +procedure AddDataFixup(c, at, chunk, addend: longint); +begin + if numDataFixups and 255 = 0 then + dataFixups := ReAllocMem(dataFixups, (numDataFixups + 256) * SizeOf(TFixup)); + dataFixups^[numDataFixups].at := at; + dataFixups^[numDataFixups].chunk := chunk; + dataFixups^[numDataFixups].addend := addend; + inc(numDataFixups); + inc(chunks^[c].numFix); end; procedure NoteVar(chunk, name, off, kind: longint); diff --git a/src/item.pas b/src/item.pas index 631835b..e3d9302 100644 --- a/src/item.pas +++ b/src/item.pas @@ -230,8 +230,8 @@ oConst: if o^.typ = tStr then begin x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk - end else if o^.typ^.form = fArray then begin - { an array constant: a variable in read-only data, not one of + end else if o^.typ^.form in [fArray, fRecord] then begin + { an array or record constant: a variable in read-only data, not one of the program's, so nothing can change it } x.mode := mVar; x.base := bGlobal; x.chunk := o^.chunk end else begin diff --git a/src/link.pas b/src/link.pas index 9b623c5..d262e00 100644 --- a/src/link.pas +++ b/src/link.pas @@ -42,7 +42,7 @@ { Marks live each chunk reached from entry through the fixups. } procedure MarkLive(entry: longint); -var stack: PLongs; sp, c, f, t: longint; +var stack: PLongs; sp, c, f, t: longint; fx: PFixups; begin stack := GetMem(numChunks * 4); sp := 0; @@ -53,10 +53,15 @@ dec(sp); c := stack^[sp]; if chunks^[c].size < 0 then Fatal(ChunkName(c) + ' is declared but never defined'); - { only code has fixups: data holds no addresses, so it uses nothing } - if chunks^[c].sec <> secText then continue; + { code and constants have fixups; variables start at zero, holding + no addresses } + case chunks^[c].sec of + secText: fx := fixups; + secRodata: fx := dataFixups; + else continue; + end; for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin - t := fixups^[f].chunk; + t := fx^[f].chunk; if not chunks^[t].live then begin chunks^[t].live := true; stack^[sp] := t; @@ -225,9 +230,13 @@ PLongint(@textImg^[p + at])^ := longint(v); end; end; - secRodata: - Move(rodata^[chunks^[c].start], roImg^[chunks^[c].adr - (Base + roOff)], - chunks^[c].size); + secRodata: begin + p := chunks^[c].adr - (Base + roOff); + Move(rodata^[chunks^[c].start], roImg^[p], chunks^[c].size); + for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do + PInt64(@roImg^[p + dataFixups^[f].at])^ := + chunks^[dataFixups^[f].chunk].adr + dataFixups^[f].addend; + end; end; end; diff --git a/src/parse.pas b/src/parse.pas index 4c40d0e..89cfd2c 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -1918,39 +1918,100 @@ Declare(o); end; -{ The value of n, an array constant of type t: an array literal of - constants, which become the bytes of a read-only chunk, as a string - constant's do (report section 4). The bytes are the compiler's own +{ An array or record constant: a literal of constants, which become + the bytes of a read-only chunk, as a string constant's do (report + section 4). An address in it, of a string, an array constant, a + procedure or an ERROR, waits in fixes until the chunk is made, then + is a fixup the linker patches. The bytes are the compiler's own machine's, little-endian, as the target's are. } -function ArrayConst(t: PType; n: longint): longint; -var et: PType; e: TItem; p: PBytes; k, es: int64; f: single; c: longint; start: TPos; +var + constBytes: PBytes; + fixes: array[0..4095] of record off: int64; chunk: longint; end; + numFixes: longint; + +procedure ConstFix(off: int64; chunk: longint); +begin + if numFixes > High(fixes) then MarkAt(TokPos, 'more than ' + IntStr(High(fixes) + 1) + ' addresses in one constant'); + fixes[numFixes].off := off; + fixes[numFixes].chunk := chunk; + inc(numFixes); +end; + +{ The part of type t at offset off of the constant } +procedure ConstPart(t: PType; off: int64); +var e: TItem; f: PObj; k: int64; r: single; start: TPos; begin - et := t^.base; - es := et^.size; start := TokPos; - if tok <> sLbrak then Expected('an array literal'); - Next; - p := nil; k := 0; - if tok <> sRbrak then - repeat - Expression(e, et); - Coerce(e, et); - if e.mode <> mConst then MarkAt(e.pos, 'expected a constant, found ' + What(e)); - ReAllocMem(p, (k + 1) * es); - if (et^.form = fReal) and (es = 4) then begin - f := RealOf(e); - Move(f, p^[k * es], 4); - end else Move(e.val, p^[k * es], es); - inc(k); - if tok <> sComma then break; - Next; - until false; - Expect(sRbrak); - if k <> t^.len then MarkAt(SpanFrom(start), 'expected ' + IntStr(t^.len) + ' elements, found ' + IntStr(k)); + if (t^.form = fArray) and (tok = sLbrak) then begin + Next; + k := 0; + if tok <> sRbrak then + repeat + if k < t^.len then ConstPart(t^.base, off + k * t^.base^.size) + else ConstPart(t^.base, off); + inc(k); + if tok <> sComma then break; + Next; + until false; + Expect(sRbrak); + if k <> t^.len then MarkAt(SpanFrom(start), 'expected ' + IntStr(t^.len) + ' elements, found ' + IntStr(k)); + exit; + end; + if (t^.form = fRecord) and not t^.tuple and (tok = sLbrace) then begin + Next; + if tok <> sRbrace then + repeat + if tok <> sIdent then Expected('a field'); + f := FieldOf(t); + Next; + Expect(sColon); + ConstPart(f^.typ, off + f^.val); + if tok <> sComma then break; + Next; + until false; + Expect(sRbrace); + exit; + end; + Expression(e, t); + if (e.mode = mStr) and ((t^.form = fSlice) or (t^.form = fArray)) and (t^.base = tU8) then begin + if t^.form = fSlice then begin + ConstFix(off, e.chunk); + Move(e.val, constBytes^[off + 8], 8); + end else if e.val > t^.len then MarkAt(e.pos, 'the string is longer than ' + TypeName(t)) + else Move(rodata^[chunks^[e.chunk].start], constBytes^[off], e.val); + end else if t^.form = fSlice then begin + if (e.mode <> mVar) or (e.obj = nil) or (e.obj^.cls <> oConst) or (e.typ^.form <> fArray) + or (e.pos.b - e.pos.a <> length(NameOf(e.obj^.name))) or not Same(e.typ^.base, t^.base) then + MarkAt(e.pos, 'a constant slice is a string or an array constant of its elements, found ' + What(e)); + ConstFix(off, e.chunk); + Move(e.typ^.len, constBytes^[off + 8], 8); + end else if t^.form = fVariant then MarkAt(e.pos, 'a constant holds no variant') + else if t^.form in [fArray, fRecord] then MarkAt(e.pos, 'expected a literal of ' + TypeName(t)) + else begin + Coerce(e, t); + if (e.mode = mProc) and not e.obj^.ext then ConstFix(off, e.obj^.chunk) + else if e.mode <> mConst then MarkAt(e.pos, 'expected a constant, found ' + What(e)) + else if (t^.form = fError) and (e.val > 0) then ConstFix(off, e.val - 1) + else if (t^.form = fPtr) and (e.val <> 0) then MarkAt(e.pos, 'a constant pointer is nil') + else if (t^.form = fReal) and (t^.size = 4) then begin + r := RealOf(e); + Move(r, constBytes^[off], 4); + end else Move(e.val, constBytes^[off], t^.size); + end; +end; + +{ The chunk of n, a constant of type t whose literal is next } +function AggregateConst(t: PType; n: longint): longint; +var c, i: longint; +begin + constBytes := AllocMem(t^.size + 8); + numFixes := 0; + ConstPart(t, 0); c := NewChunk(secRodata, curModule^.sname, n); - SetData(c, p, t^.size, t^.align); - FreeMem(p); - ArrayConst := c; + SetData(c, constBytes, t^.size, t^.align); + for i := 0 to numFixes - 1 do AddDataFixup(c, fixes[i].off, fixes[i].chunk, 0); + FreeMem(constBytes); + AggregateConst := c; end; procedure ConstDecl(top: boolean); @@ -1963,15 +2024,13 @@ Next; start := TokPos; t := ParseType; - if (t^.form = fArray) and not (t^.base^.form in [fInt, fReal, fBool, fEnum, fSet]) then - MarkAt(SpanFrom(start), 'an array constant holds integers, reals, BOOLs, enumerations or sets, found ' + TypeName(t^.base)) - else if (t <> tError) and (t^.form <> fArray) then - MarkAt(SpanFrom(start), 'only an ERROR or an array constant has a type'); + if (t <> tError) and not ((t^.form = fArray) or (t^.form = fRecord) and not t^.tuple) then + MarkAt(SpanFrom(start), 'only an ERROR, an array or a record constant has a type'); end; Expect(sEql); - if (t <> nil) and (t^.form = fArray) then begin + if (t <> nil) and (t^.form in [fArray, fRecord]) then begin o := NewObj(oConst, n, t); - o^.chunk := ArrayConst(t, n); + o^.chunk := AggregateConst(t, n); o^.pos := at; o^.exported := exp and top; Declare(o); diff --git a/src/raz.pas b/src/raz.pas index ef331e9..c13126e 100644 --- a/src/raz.pas +++ b/src/raz.pas @@ -34,7 +34,7 @@ { what git describe says, made by make: 0.3.0 at the tag v0.3.0, 0.3.0-5-g38d29a8 five commits past it } Version = {$I version.inc}; - Report = '2026-10.15'; { the version of doc/raz.md it follows } + Report = '2026-10.16'; { the version of doc/raz.md it follows } MemfdCreate = 319; { the system call; FPC 3.2.2 has no name for it } MfdCloexec = 1; { an ELF still executes: the kernel opens it first } diff --git a/test/doc/Str.expect b/test/doc/Str.expect index dabc054..5720a2c 100644 --- a/test/doc/Str.expect +++ b/test/doc/Str.expect @@ -1,7 +1,11 @@ module Str; Operations on strings, which are []U8. = and # compare them; this module orders, searches and hashes them, reads and writes their - UTF-8, and reads a number from one. + UTF-8, reads a number from one, and copies one to keep. + +proc copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL); + s's bytes, copied into memory from a, to keep after s's own are + gone; "" and false if a has no room. proc cmp*(a, b: []U8): INT; -1, 0 or 1 as a sorts before, with or after b, byte by byte. diff --git a/test/msg/ArrayConstElem.err b/test/msg/ArrayConstElem.err index 11fc7bb..c957086 100644 --- a/test/msg/ArrayConstElem.err +++ b/test/msg/ArrayConstElem.err @@ -1,4 +1,4 @@ -conform/err/ArrayConstElem.raz:3:10: error: an array constant holds integers, reals, BOOLs, enumerations or sets, found R - 3 | const P: [1]R = [{a: 1}]; - | ^^^^ +conform/err/ArrayConstElem.raz:3:18: error: a constant holds no variant + 3 | const P: [1]S = [a]; + | ^ raz: 1 error diff --git a/test/msg/StmtErrType.err b/test/msg/StmtErrType.err index c7f0fbd..bd38fbc 100644 --- a/test/msg/StmtErrType.err +++ b/test/msg/StmtErrType.err @@ -1,4 +1,4 @@ -conform/err/StmtErrType.raz:2:10: error: only an ERROR or an array constant has a type +conform/err/StmtErrType.raz:2:10: error: only an ERROR, an array or a record constant has a type 2 | const k: I64 = "a"; | ^^^ raz: 1 error