From 4b0b6390f78165dea1f7e80eb32f7d7c99afe036 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:27:52 +0100 Subject: [PATCH] Self step 2a: Chunk and Sym in raz, tested against the seeds --- diff --git a/PLAN.md b/PLAN.md index e33afd8..09e6a33 100644 --- a/PLAN.md +++ b/PLAN.md @@ -31,7 +31,7 @@ 1. `diag` and `scan` (done): the trial. Measure `scan`'s speed against the seed's and list what `Sys` and the library lacked. Stop for review: if the cost is too high, mend the code generator first. -2. `chunk`, `sym`, `link`, `elf`, `x64`. +2. `chunk`, `sym` (2a, done); `link`, `elf`, `x64` (2b). 3. `gen`, `item`. 4. `parse`, `raz`: the first compiler that builds. 5. Fixpoint: the seed builds `self`, that builds `self`, that builds diff --git a/self/Chunk.raz b/self/Chunk.raz new file mode 100644 index 0000000..a83cdaa --- /dev/null +++ b/self/Chunk.raz @@ -0,0 +1,364 @@ +(* Chunk: the compiled program, before it is linked. + + The code of a program is a set of chunks: one per procedure, module + variable and string. A chunk's bytes go in one of three sections: + text (code), rodata (strings and other constants), bss (variables, + which are all zero). A reference from code to another chunk (a call, + or an address) is a fixup, patched once the linker has placed every + chunk. Line notes say which place in the source the code from each + point on is for. + + Nothing here depends on the machine: text is bytes, written by the + encoder for the target (X64). + + Depends on: Scan, for names and memory; Diag, for positions. + Leaves out: the instructions; that is X64. + + Exported variables can't be set from outside, so the setters at the + end do what the seed's other units do to these. *) +module Chunk; +import Mem, Heap, Fmt, Diag, Scan; + +type + Section* = (secText, secRodata, secBss); + + Chunk* = record + sec*: Section; + start*, size*, align*: INT; (* in its section's buffer *) + firstFix*, numFix*: INT; (* its fixups: text's in fixups, rodata's in dataFixups *) + home*, name*: INT; (* its module and its name, for the symbol table; -1 if none *) + adr*: I64; (* its address, set by the linker *) + live*: BOOL; (* reached from the entry point *) + ext*: BOOL; (* bss: the address of a C symbol, its name *) + reals*: BOOL; (* code: computes with reals, first at realsAt *) + realsAt*: Diag.Pos; + saveMask*: INT; (* code: the registers of variables it saves, as bits of Gen's VarRegs *) + saveAt*: INT; (* ... at this offset from the frame, one quadword each *) + end; + + (* A place in the source whose code starts at a place in text: for + gdb, and for Rt to say where a failed check or a signal was *) + Line* = record + at*, chunk*: INT; (* the place in text, and its chunk *) + path*, line*, col*: INT; (* the file's path, interned, the line and column *) + end; + + (* A variable of a procedure, for the trap report: Rt shows it, by + kind, from its place in the frame *) + VarNote* = record + chunk*, name*: INT; + off*: INT; (* from the frame pointer *) + kind*: INT; (* how Rt shows it: see Link *) + end; + + Fixup* = record + at*: INT; (* the 32-bit field, as an offset in text; in + dataFixups, the 64-bit one, from its chunk's start *) + chunk*: INT; (* the chunk it refers to *) + addend*: INT; (* added to the chunk's address *) + end; + +var + text*: ^U8; (* text *) + pc*: INT; (* its length *) + rodata*: ^U8; + rolen*: INT; + chunks*: ^Chunk; + numChunks*: INT; + fixups*: ^Fixup; + numFixups*: INT; + (* 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*: ^Fixup; + numDataFixups*: INT; + lines*: ^Line; + numLines*: INT; + curFile: INT; (* the file being compiled, for noteLine *) + curChunk*: INT; (* the chunk of code being written *) + varNotes*: ^VarNote; + numVarNotes*: INT; + + codeCap, roCap, chunkCap, fixCap, dataFixCap, lineCap, noteCap: INT; + +(* p, which holds used bytes, moved to a block of size bytes *) +proc grown(p: ^U8; used, size: INT): ^U8; +var q: ^U8; +begin + q := Scan.grab(size); + COPY(q[0..used], p[0..used]); + Mem.free(Heap.heap, p); + return q; +end; + +(* Room for n more bytes of code *) +proc room(n: INT); +begin + if pc + n > codeCap then + text := grown(text, pc, codeCap * 2 + n); + codeCap := codeCap * 2 + n; + end; +end; + +proc put1*(b: INT); +begin + if pc + 16 > codeCap then room(16); end; + text[pc] := U8(b & 0FFH); + INC(pc); +end; + +(* The low 32 bits of v, least significant byte first *) +proc put4*(v: INT); +var i: INT; +begin + if pc + 16 > codeCap then room(16); end; + for i := 0 to 3 do text[pc + i] := U8((v shr (8 * i)) & 0FFH); end; + INC(pc, 4); +end; + +proc put4At*(at, v: INT); +var i: INT; +begin + for i := 0 to 3 do text[at + i] := U8((v shr (8 * i)) & 0FFH); end; +end; + +(* The 32 bits at at, as a signed number *) +proc get4At*(at: INT): INT; +var u, i: INT; +begin + u := 0; + for i := 0 to 3 do u := u * 256 + INT(text[at + 3 - i]); end; + if u >= 80000000H then u := u - 100000000H; end; + return u; +end; + +(* The last n bytes of code taken back. A line noted past the new end + now starts there, in place of one noted there before, as noteLine + would have it. *) +proc takeBack*(n: INT); +begin + DEC(pc, n); + if (numLines > 0) and (lines[numLines - 1].at > pc) then + lines[numLines - 1].at := pc; + if (numLines > 1) and (lines[numLines - 2].at = pc) then + lines[numLines - 2] := lines[numLines - 1]; + DEC(numLines); + end; + end; +end; + +proc put8*(v: I64); +begin + put4(INT(v & 0FFFFFFFFH)); + put4(INT((v shr 32) & 0FFFFFFFFH)); +end; + +proc newChunk*(sec: Section; home, name: INT): INT; +var c: ^Chunk; +begin + if numChunks = chunkCap then + chunks := ^Chunk(grown(^U8(chunks), numChunks * SIZE(Chunk), chunkCap * 2 * SIZE(Chunk))); + chunkCap := chunkCap * 2; + end; + c := ADR(chunks[numChunks]); + c^ := {}; + c^.sec := sec; + c^.home := home; + c^.name := name; + c^.align := 1; + c^.size := -1; (* not yet defined *) + INC(numChunks); + return numChunks - 1; +end; + +proc beginChunk*(c: INT); +begin + (* code is aligned to 32 bytes, the windows in which x86 fetches and + caches it, so that a procedure's loops sit in them the same way + whatever comes before: rat ran 5% slower at 16, by where its loops + fell. Padded with CC, x86's int3: a trap if it were ever run *) + while pc & 31 # 0 do put1(0CCH); end; + curChunk := c; + chunks[c].start := pc; + chunks[c].align := 32; + chunks[c].firstFix := numFixups; +end; + +proc endChunk*(c: INT); +begin + chunks[c].size := pc - chunks[c].start; + chunks[c].numFix := numFixups - chunks[c].firstFix; +end; + +(* The n bytes at p are the data of rodata chunk c *) +proc setData*(c: INT; p: ^U8; n, align: INT); +begin + if rolen + n > roCap then + rodata := grown(rodata, rolen, roCap * 2 + n); + roCap := roCap * 2 + n; + end; + COPY(rodata[rolen..rolen + n], p[0..n]); + chunks[c].firstFix := numDataFixups; + chunks[c].numFix := 0; + chunks[c].start := rolen; + chunks[c].size := n; + chunks[c].align := align; + INC(rolen, n); +end; + +proc setBss*(c: INT; size, align: INT); +begin + chunks[c].size := size; + chunks[c].align := align; +end; + +(* The code from here on is for line and column of the current file. A + place with no code of its own gives way to the next. *) +proc noteLine*(line, col: INT); +begin + if (numLines > 0) and (lines[numLines - 1].at = pc) then DEC(numLines); end; + if (numLines > 0) and (lines[numLines - 1].chunk = curChunk) and (lines[numLines - 1].line = line) + and (lines[numLines - 1].col = col) and (lines[numLines - 1].path = curFile) then + return; + end; + if numLines = lineCap then + lines := ^Line(grown(^U8(lines), numLines * SIZE(Line), lineCap * 2 * SIZE(Line))); + lineCap := lineCap * 2; + end; + lines[numLines].at := pc; + lines[numLines].chunk := curChunk; + lines[numLines].path := curFile; + lines[numLines].line := line; + lines[numLines].col := col; + INC(numLines); +end; + +(* The quadword that holds the address of C's symbol name, filled in + when the program starts; one for each name. *) +proc externChunk*(name: INT): INT; +var c: INT; +begin + for c := 0 to numChunks - 1 do + if chunks[c].ext and (chunks[c].name = name) then return c; end; + end; + c := newChunk(secBss, -1, name); + setBss(c, 8, 8); + chunks[c].ext := true; + return c; +end; + +proc addFixup*(at, chunk, addend: INT); +begin + if numFixups = fixCap then + fixups := ^Fixup(grown(^U8(fixups), numFixups * SIZE(Fixup), fixCap * 2 * SIZE(Fixup))); + fixCap := fixCap * 2; + end; + fixups[numFixups].at := at; + 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. *) +proc addDataFixup*(c, at, chunk, addend: INT); +begin + if numDataFixups = dataFixCap then + dataFixups := ^Fixup(grown(^U8(dataFixups), numDataFixups * SIZE(Fixup), dataFixCap * 2 * SIZE(Fixup))); + dataFixCap := dataFixCap * 2; + end; + dataFixups[numDataFixups].at := at; + dataFixups[numDataFixups].chunk := chunk; + dataFixups[numDataFixups].addend := addend; + INC(numDataFixups); + INC(chunks[c].numFix); +end; + +proc noteVar*(chunk, name, off, kind: INT); +begin + if numVarNotes = noteCap then + varNotes := ^VarNote(grown(^U8(varNotes), numVarNotes * SIZE(VarNote), noteCap * 2 * SIZE(VarNote))); + noteCap := noteCap * 2; + end; + varNotes[numVarNotes].chunk := chunk; + varNotes[numVarNotes].name := name; + varNotes[numVarNotes].off := off; + varNotes[numVarNotes].kind := kind; + INC(numVarNotes); +end; + +(* The name of chunk c: its module's and its own, or literal and its + number for a literal *) +proc chunkName*(c: INT): []U8; +begin + if chunks[c].name < 0 then return Diag.say("literal{}", [Fmt.int(c)]); end; + if chunks[c].home < 0 then return Scan.nameOf(chunks[c].name); end; + return Diag.say("{}.{}", [Fmt.str(Scan.nameOf(chunks[c].home)), Fmt.str(Scan.nameOf(chunks[c].name))]); +end; + +(* What Gen's Redo and Rewind put back: the code, fixups and lines made + since are forgotten *) +proc rewindTo*(atPc, atFixups, atLines: INT); +begin + pc := atPc; + numFixups := atFixups; + numLines := atLines; +end; + +(* The file the code is being made from, as its path interned *) +proc setCurFile*(path: INT); +begin + curFile := path; +end; + +proc curFilePath*: INT; +begin + return curFile; +end; + +proc setLive*(c: INT); +begin + chunks[c].live := true; +end; + +proc setAdr*(c: INT; a: I64); +begin + chunks[c].adr := a; +end; + +(* Chunk c computes with reals, the first of them at p *) +proc setReals*(c: INT; p: Diag.Pos); +begin + chunks[c].reals := true; + chunks[c].realsAt := p; +end; + +proc setSaves*(c, mask, at: INT); +begin + chunks[c].saveMask := mask; + chunks[c].saveAt := at; +end; + +begin + codeCap := 1 shl 20; + text := Scan.grab(codeCap); + pc := 0; + roCap := 1 shl 16; + rodata := Scan.grab(roCap); + rolen := 0; + chunkCap := 1 shl 10; + chunks := ^Chunk(Scan.grab(chunkCap * SIZE(Chunk))); + numChunks := 0; + fixCap := 1 shl 12; + fixups := ^Fixup(Scan.grab(fixCap * SIZE(Fixup))); + numFixups := 0; + dataFixCap := 1 shl 8; + dataFixups := ^Fixup(Scan.grab(dataFixCap * SIZE(Fixup))); + numDataFixups := 0; + lineCap := 1 shl 12; + lines := ^Line(Scan.grab(lineCap * SIZE(Line))); + numLines := 0; + noteCap := 1 shl 8; + varNotes := ^VarNote(Scan.grab(noteCap * SIZE(VarNote))); + numVarNotes := 0; +end Chunk. diff --git a/self/README.md b/self/README.md index 5e9e660..1eb0893 100644 --- a/self/README.md +++ b/self/README.md @@ -10,6 +10,13 @@ make self # each unit against the seed's, on the same files make self-bench # the scanner's speed against the seed's +`Chunk` and `Sym` have no input files to read, so each has a dumper +pair, `test/ChunkDump` and `test/SymDump`, that runs one fixed +pseudo-random script of calls on its side and prints all it made or +answered (`Sym` also ends, as an argument says, in the error of a name +declared twice or of too many scopes): the output, the messages and +the status must be the same. + `check.sh` builds a dumper for each side, `test/ScanDump.pas` over the seed's units and `test/ScanDump.raz` over these, and has both read the library, the examples, every test of the compiler and a file for each @@ -40,6 +47,18 @@ which keeps what it makes: messages are made only to be shown. A name from `nameOf` stays valid, since names are kept in chunks that are never moved; the seed's was a copy. +- **Reserved words as names.** The seed's `code` (the text buffer of + `Chunk`) is `text`; `module` (a record's, an import's) is `home`; an + object's `link` is `chain`. A seed type `TName` is `Name`, and the + procedures begin in lower case, as `Scan`'s do. +- **Errors in `Sym`.** `insert` (a name declared twice) and `openScope` + (too many scopes) show the error and return `Scan.Failed`, as `mark` + does, for the parser to pass up with `try`. `saveScopes` returns what + the seed's `var d` gave. +- **Setters.** What other units set in `Chunk` has one each (`setLive`, + `setAdr`, `setReals`, `setSaves`, `setCurFile`, and `rewindTo` for + gen's `Redo` and `Rewind`), and `Sym` has `setCurModule`. `Scan.grab` + is exported for the memory they all take. - **No bit cast.** A real's bits and back go through a pointer. - **Speed.** On the 348,025 lines of `test/genbench.py`, 7.6 MB, the seed's scanner takes 75 ms and this one 74. It took 121 at first. diff --git a/self/Scan.raz b/self/Scan.raz index d484b71..570b8d4 100644 --- a/self/Scan.raz +++ b/self/Scan.raz @@ -112,7 +112,7 @@ end; (* Memory, or the end of the compile when there is none *) -proc grab(size: INT): ^U8; +proc grab*(size: INT): ^U8; var p: ^U8; begin p := Mem.alloc(Heap.heap, size, 8); diff --git a/self/Sym.raz b/self/Sym.raz new file mode 100644 index 0000000..b57cd96 --- /dev/null +++ b/self/Sym.raz @@ -0,0 +1,684 @@ +(* Sym: types, objects and scopes. + + Every name the program declares becomes an object (Obj): a constant, + type, variable, procedure, module, record field, variant case or + built-in. Every type is a Type. Objects are found through one hash + table keyed by scope and name, so a lookup costs the same however + big a module grows. A scope is just a number: the universe is 0, + and each module, procedure, record and match arm gets a fresh one. + + Depends on: Scan, for names and errors; Diag, for positions. + Leaves out: code. Where a variable lives is decided here (frame + offsets, chunk numbers), but nothing is emitted. + + Exported variables can't be set from outside, so setCurModule is + how the parser says which module it is in. A name that holds a + reserved word of raz is spelled otherwise: a record's `module` is + its `home`, an object's `link` its `chain`. *) +module Sym; +import Mem, Heap, Buf, Fmt, Diag, Scan; + +type + Form* = (fNone, fBool, fInt, fReal, fConst, fNil, fStr, fPtr, fArray, + fSlice, fRecord, fVariant, fProc, fEnum, fSet, fError); + (* fConst is the type of an untyped integer constant; fStr of a string + literal, whose length the literal carries. F32 and F64 are fReal, + told apart by size, and so is tRConst, an untyped real constant. *) + + Class* = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin); + + Type* = record + form*: Form; + size*, align*: I64; + signed*: BOOL; (* fInt *) + vol*: BOOL; (* fPtr: ^VOLATILE *) + packd*: BOOL; (* fRecord *) + variadic*: BOOL; (* fProc: ends in ... *) + tuple*: BOOL; (* fRecord: the results of a procedure that has several *) + base*: ^Type; (* fPtr, fArray, fSlice: what it holds; fProc: result *) + len*: I64; (* fArray: elements; fProc: parameters; fVariant: cases; a tuple: results *) + fields*: ^Obj; (* fRecord: fields; fVariant: cases; fProc: parameters *) + scope*: INT; (* fRecord: the scope of its fields *) + fwd*: INT; (* fPtr whose base isn't declared yet: its name, else -1 *) + obj*: ^Obj; (* the declaration that names it, or nil *) + home*: ^Module; (* the module that built it *) + end; + + Obj* = record + cls*: Class; + name*: INT; + exported*: BOOL; + typ*: ^Type; + next*: ^Obj; (* the next in its list: scope, fields, parameters *) + scope*: INT; (* where it is declared *) + pos*: Diag.Pos; (* where its name is declared, for messages *) + val*: I64; (* oConst: value; oBuiltin: which; oCase: tag; + oField: offset; oVar: frame offset *) + chunk*: INT; (* global oVar, oProc, string oConst: its chunk *) + lev*: INT; (* oVar: 0 for a module variable, 1 for a local *) + ind*: BOOL; (* oVar: the frame slot holds the variable's address *) + off*: I64; (* oVar with ind: added to that address *) + isVar*: BOOL; (* a var parameter *) + param*: BOOL; (* oVar: a parameter *) + used*: BOOL; (* named somewhere but in its own body *) + read*: BOOL; (* oVar: named other than as what := assigns *) + fwd*: BOOL; (* oProc: declared forward, no body yet *) + isCode*: BOOL; (* oProc: a code procedure *) + openEnd*: BOOL; (* oProc: has results, and may reach its end *) + reg*: INT; (* oVar: the register it lives in, or 0 if in memory; + for a slice, the one its pointer is in *) + reg2*: INT; (* oVar: a slice in registers: the one its length is in *) + ext*: BOOL; (* oProc, oVar: C's, reached through its chunk, which + holds its address *) + fields*: ^Obj; (* oCase: its fields *) + home*: ^Module; (* oModule: the module; others: where declared *) + chain*: ^Obj; (* the next declaration of its module, top-level or + local *) + end; + + (* The arguments of a generic module's instance: a type, or a + procedure (o) and its type. *) + Args* = record + n*: INT; + t*: [8]^Type; + o*: [8]^Obj; + pos*: [8]Diag.Pos; (* where each argument is, for messages *) + at*: Diag.Pos; (* where the import is *) + end; + + Import* = record + home*: ^Module; + next*: ^Import; + end; + + (* A library a module links, by its name, as interned *) + Lib* = record + name*: INT; + next*: ^Lib; + end; + + Module* = record + name*: INT; + sname*: INT; (* the name of its symbols: List(I64) for an instance *) + args*: Args; + scope*: INT; + path*: []U8; + first*, last*: ^Obj; (* its top-level declarations, in order *) + locals*, lastLocal*: ^Obj; (* its procedures' declarations, in order *) + imports*: ^Import; + body*: INT; (* the chunk of its body, or -1 *) + done*: BOOL; (* compiled to the end *) + checkOnly*: BOOL; (* read only to check another file's interface *) + used*: BOOL; (* imported, through others, by the main module *) + usesC*: BOOL; (* has an extern, or links a library *) + linkStatic*: BOOL; (* says link static *) + libs*: ^Lib; (* the libraries it links *) + next*: ^Module; (* modules in the order they were finished *) + end; + +const + (* built-in procedures *) + bSize* = 0; bAdr* = 1; bLen* = 2; bNew* = 3; bMsg* = 4; bSyscall* = 5; + bFence* = 6; bCas* = 7; bXchg* = 8; bXadd* = 9; bArgc* = 10; bArgv* = 11; + bInc* = 12; bDec* = 13; bCopy* = 14; + + MaxDepth* = 64; (* scopes open at once *) + +var + tI8*, tI16*, tI32*, tI64*, tU8*, tU16*, tU32*, tU64*: ^Type; + tInt*, tUInt*: ^Type; (* INT and UINT, as big as an address: 8 bytes here *) + tBool*, tF32*, tReal*, tRConst*, tError*, tConst*, tNil*, tStr*, tNone*, tPtrU8*, tBytes*: ^Type; + tPoison*: ^Type; (* of a name reported as not declared *) + curModule*: ^Module; + + scopes: [MaxDepth]INT; + depth: INT; + nextScope: INT; + hashTab: ^^Obj; + hashMask, hashCount: INT; + +proc setCurModule*(m: ^Module); +begin + curModule := m; +end; + +proc newType*(form: Form; size, align: I64): ^Type; +var t: ^Type; +begin + NEW(t, Heap.heap); + if t = nil then Diag.fatal("out of memory"); end; + t^.form := form; + t^.size := size; + t^.align := align; + t^.fwd := -1; + t^.home := curModule; + return t; +end; + +proc newObj*(cls: Class; name: INT; typ: ^Type): ^Obj; +var o: ^Obj; +begin + NEW(o, Heap.heap); + if o = nil then Diag.fatal("out of memory"); end; + o^.cls := cls; + o^.name := name; + o^.typ := typ; + o^.chunk := -1; + o^.home := curModule; + o^.pos := Scan.tokPos(); + return o; +end; + +(* Scopes *) + +proc newScope*: INT; +begin + INC(nextScope); + return nextScope; +end; + +proc openScope*(s: INT): ERROR; +begin + if depth = MaxDepth then + return Scan.mark(Diag.say("scopes nested more than {} deep", [Fmt.int(MaxDepth)])); + end; + scopes[depth] := s; + INC(depth); + return nil; +end; + +proc closeScope*; +begin + DEC(depth); +end; + +(* An imported module is compiled in the middle of another, and must + see only the universe and itself. The scopes open are kept in saved, + and their number is the result. *) +proc saveScopes*(saved: []INT): INT; +var i, d: INT; +begin + d := depth; + for i := 0 to depth - 1 do saved[i] := scopes[i]; end; + depth := 1; + return d; +end; + +proc restoreScopes*(d: INT; saved: []INT); +var i: INT; +begin + depth := d; + for i := 0 to depth - 1 do scopes[i] := saved[i]; end; +end; + +proc scopeDepth*: INT; +begin + return depth; +end; + +(* Closes the scopes opened since there were d, after an error *) +proc cutScopes*(d: INT); +begin + depth := d; +end; + +proc topScope*: INT; +begin + return scopes[depth - 1]; +end; + +(* Where the search for name in scope s starts in the hash table: each + number is multiplied by an odd constant near 2^32 or 2^16 over the + golden ratio (Knuth's multiplicative hashing), which spreads the low + bits the mask keeps. *) +proc slot(s, name: INT): INT; +begin + return INT(((U32(s & 0FFFFFFFFH) * 2654435761) xor (U32(name & 0FFFFFFFFH) * 40503)) & U32(hashMask)); +end; + +(* A table of n slots, all empty *) +proc emptyTable(n: INT): ^^Obj; +var t: ^^Obj; i: INT; +begin + t := ^^Obj(Scan.grab(n * SIZE(^Obj))); + for i := 0 to n - 1 do t[i] := nil; end; + return t; +end; + +(* Doubles the table, which insert keeps at most half full so that the + linear probing stays short, and puts every entry in its new slot. *) +proc rehash; +var old: ^^Obj; n, i, j: INT; +begin + old := hashTab; + n := hashMask + 1; + hashMask := n * 2 - 1; + hashTab := emptyTable(n * 2); + for i := 0 to n - 1 do + if old[i] # nil then + j := slot(old[i]^.scope, old[i]^.name); + while hashTab[j] # nil do j := (j + 1) & hashMask; end; + hashTab[j] := old[i]; + end; + end; + Mem.free(Heap.heap, ^U8(old)); +end; + +proc insert*(obj: ^Obj; s: INT): ERROR; +var i: INT; o: ^Obj; +begin + i := slot(s, obj^.name); + o := hashTab[i]; + while o # nil do + if (o^.scope = s) and (o^.name = obj^.name) then + Diag.error(obj^.pos, Diag.say("{} is declared twice", [Fmt.str(Scan.nameOf(obj^.name))])); + Diag.note(o^.pos, "the first one is here"); + return Scan.Failed; + end; + i := (i + 1) & hashMask; + o := hashTab[i]; + end; + obj^.scope := s; + hashTab[i] := obj; + INC(hashCount); + if hashCount * 2 > hashMask then rehash; end; + return nil; +end; + +proc find*(s, name: INT): ^Obj; +var i: INT; o: ^Obj; +begin + i := slot(s, name); + o := hashTab[i]; + while o # nil do + if (o^.scope = s) and (o^.name = name) then return o; end; + i := (i + 1) & hashMask; + o := hashTab[i]; + end; + return nil; +end; + +proc lookup*(name: INT): ^Obj; +var i: INT; o: ^Obj; +begin + for i := depth - 1 to 0 by -1 do + o := find(scopes[i], name); + if o # nil then return o; end; + end; + return nil; +end; + +proc min(a, b: INT): INT; +begin + if a < b then return a; end; + return b; +end; + +(* c, in capitals if it is a letter *) +proc up(c: U8): U8; +begin + if (c >= 97) and (c <= 122) then return c - 32; end; + return c; +end; + +(* How far apart two names are: the edits, a character put in, taken out, + changed or swapped with the next, that make one the other, ignoring + case. *) +proc distance(a, b: []U8): INT; +var d: [Scan.MaxIdent + 2][Scan.MaxIdent + 2]INT; i, j, c: INT; +begin + for i := 0 to LEN(a) do d[i][0] := i; end; + for j := 0 to LEN(b) do d[0][j] := j; end; + for i := 1 to LEN(a) do + for j := 1 to LEN(b) do + c := 1; + if up(a[i - 1]) = up(b[j - 1]) then c := 0; end; + d[i][j] := min(min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + c); + if (i > 1) and (j > 1) and (up(a[i - 1]) = up(b[j - 2])) + and (up(a[i - 2]) = up(b[j - 1])) then + d[i][j] := min(d[i][j], d[i - 2][j - 2] + 1); + end; + end; + end; + return d[LEN(a)][LEN(b)]; +end; + +(* The name spelled most like name, for "did you mean": in scope s, if + it can be reached from here, or in the scopes in reach if s < 0; nil + if none is within an edit for every three characters. Only after an + error, so it looks at every object. *) +proc closest*(name, s: INT): ^Obj; +var i, j, d, best: INT; o, found: ^Obj; n: []U8; reach: BOOL; +begin + n := Scan.nameOf(name); + best := LEN(n) div 3 + 1; + found := nil; + for i := 0 to hashMask do + o := hashTab[i]; + if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then + reach := false; + elsif s >= 0 then + reach := (o^.scope = s) and (o^.exported or (o^.home = curModule)); + else + reach := false; + for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]); end; + end; + if reach then + d := distance(n, Scan.nameOf(o^.name)); + if d < best then best := d; found := o; end; + end; + end; + return found; +end; + +(* Types *) + +proc alignUp*(x, a: I64): I64; +begin + return (x + a - 1) div a * a; +end; + +proc isInt*(t: ^Type): BOOL; +begin + return t^.form in {fInt, fConst}; +end; + +proc isScalar*(t: ^Type): BOOL; +begin + return t^.form in {fBool, fInt, fReal, fConst, fNil, fPtr, fProc, fEnum, fSet, fError}; +end; + +proc isAggregate*(t: ^Type): BOOL; +begin + return t^.form in {fArray, fSlice, fRecord, fVariant}; +end; + +(* Whether a result field f is a single value of at most a word, not a real *) +proc oneWord(f: ^Obj): BOOL; +begin + return isScalar(f^.typ) and (f^.typ^.form # fReal) and (f^.typ^.size <= 8); +end; + +(* Whether a procedure's result t is two words, which come back in rax + and rdx, as System V returns a struct of two integers: a slice (its + pointer, then its length), or two results that are each a single + value of 8 bytes at most and not a real. *) +proc inTwoRegs*(t: ^Type): BOOL; +begin + if t^.form = fSlice then return true; end; + return t^.tuple and (t^.len = 2) and oneWord(t^.fields) and oneWord(t^.fields^.next); +end; + +(* Whether a procedure's result t comes back in memory the caller + provides, whose address the caller passes as a hidden first argument, + in rdi: any result that is neither one value, in rax or xmm0, nor two + words, in rax and rdx. *) +proc behindPointer*(t: ^Type): BOOL; +begin + return isAggregate(t) and not inTwoRegs(t); +end; + +proc fits*(v: I64; t: ^Type): BOOL; +begin + if t^.form # fInt then return t^.form = fConst; end; + match t^.size of + | 1: + if t^.signed then return (v >= -128) and (v <= 127); end; + return (v >= 0) and (v <= 255); + | 2: + if t^.signed then return (v >= -32768) and (v <= 32767); end; + return (v >= 0) and (v <= 65535); + | 4: + if t^.signed then return (v >= -2147483648) and (v <= 2147483647); end; + return (v >= 0) and (v <= 4294967295); + | else: return t^.signed or (v >= 0); + end; +end; + +proc same*(a, b: ^Type): BOOL; forward; + +(* Whether two procedure types, or two tuples, are alike: the same + results and parameters, in the same modes *) +proc alikeShape(a, b: ^Type): BOOL; +var p, q: ^Obj; +begin + (* a record is the same only as itself, but for several results *) + if (a^.form = fRecord) and not (a^.tuple and b^.tuple) then return false; end; + if (a^.len # b^.len) or (a^.variadic # b^.variadic) then return false; end; + if (a^.base = nil) # (b^.base = nil) then return false; end; + if (a^.base # nil) and not same(a^.base, b^.base) then return false; end; + p := a^.fields; q := b^.fields; + while p # nil do + if (p^.isVar # q^.isVar) or not same(p^.typ, q^.typ) then return false; end; + p := p^.next; q := q^.next; + end; + return true; +end; + +(* Structural sameness of two types. Named types are the same only if + they are one declaration; a type with no name is the same as another + built alike. *) +proc alike(a, b: ^Type): BOOL; +begin + if a = b then return true; end; + if a^.form # b^.form then return false; end; + match a^.form of + | fPtr: return (a^.vol = b^.vol) and same(a^.base, b^.base); + | fArray: return (a^.len = b^.len) and same(a^.base, b^.base); + | fSlice: return same(a^.base, b^.base); + | fSet: return same(a^.base, b^.base); + | fProc: return alikeShape(a, b); + | fRecord: return alikeShape(a, b); + | else: return false; + end; +end; + +proc same*(a, b: ^Type): BOOL; +begin + if a = b then return true; end; + if (a = nil) or (b = nil) then return false; end; + if (a^.obj # nil) and (b^.obj # nil) then return false; end; + return alike(a, b); +end; + +(* What a type is called, added to b: the names a program gives it, else + what it is made of *) +proc typeText(b: ^Buf.Buf; t: ^Type); +var f: ^Obj; +begin + if t = nil then Buf.str(b, "nothing"); return; end; + if t^.obj # nil then + if (t^.obj^.home # nil) and (t^.obj^.home # curModule) then + Buf.str(b, Scan.nameOf(t^.obj^.home^.sname)); + Buf.str(b, "."); + end; + Buf.str(b, Scan.nameOf(t^.obj^.name)); + return; + end; + match t^.form of + | fConst: Buf.str(b, "an integer constant"); + | fReal: Buf.str(b, "a real constant"); + | fNil: Buf.str(b, "nil"); + | fStr: Buf.str(b, "a string"); + | fPtr: + if t^.vol then Buf.str(b, "^VOLATILE "); else Buf.str(b, "^"); end; + typeText(b, t^.base); + | fArray: + Fmt.write(b, "[{}]", [Fmt.int(t^.len)]); + typeText(b, t^.base); + | fSlice: + Buf.str(b, "[]"); + typeText(b, t^.base); + | fRecord: + if not t^.tuple then + Buf.str(b, "record"); + else + Buf.str(b, "("); + f := t^.fields; + while f # nil do + typeText(b, f^.typ); + f := f^.next; + if f # nil then Buf.str(b, ", "); end; + end; + Buf.str(b, ")"); + end; + | fVariant: Buf.str(b, "variant"); + | fProc: + Buf.str(b, "proc("); + f := t^.fields; + while f # nil do + if f^.isVar then Buf.str(b, "var "); end; + typeText(b, f^.typ); + f := f^.next; + if f # nil then Buf.str(b, ", "); end; + end; + Buf.str(b, ")"); + if t^.base # nil then + Buf.str(b, ": "); + typeText(b, t^.base); + end; + | else: Buf.str(b, "?"); + end; +end; + +(* A name for t, kept for good, as every message is *) +proc typeName*(t: ^Type): []U8; +var b: ^Buf.Buf; +begin + b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf))); + Buf.init(b, Heap.heap); + typeText(b, t); + return Buf.bytes(b); +end; + +(* A fingerprint of what a declaration exports, for the interface + check: two files of one module export the same thing when their + fingerprints agree. A named type counts by its name, so that a type + declared in each file stands for the other's. *) +proc mix(var h: U64; v: I64); +begin + h := (h xor U64(v)) * 1099511628211; (* FNV-1a's 64-bit prime *) +end; + +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +proc shape(var h: U64; t: ^Type; top: BOOL); +var f, g: ^Obj; +begin + if t = nil then mix(h, -1); return; end; + if (t^.obj # nil) and not top then + mix(h, t^.obj^.name); + if t^.obj^.home # nil then mix(h, t^.obj^.home^.sname); end; + return; + end; + mix(h, INT(t^.form)); + mix(h, bit(t^.vol) + 2 * bit(t^.variadic)); + mix(h, t^.len); + if t^.form in {fPtr, fArray, fSlice, fProc, fSet} then shape(h, t^.base, false); end; + f := t^.fields; + while f # nil do + if (t^.form # fRecord) or f^.exported then + mix(h, f^.name); + mix(h, bit(f^.isVar)); + shape(h, f^.typ, false); + g := f^.fields; + while g # nil do shape(h, g^.typ, false); g := g^.next; end; + end; + f := f^.next; + end; +end; + +proc fingerprint*(o: ^Obj): U64; +var h: U64; f: ^Obj; +begin + h := 0CBF29CE484222325H; (* FNV-1a's 64-bit offset basis *) + mix(h, INT(o^.cls)); + if o^.cls = oCase then + mix(h, o^.val); + f := o^.fields; + while f # nil do shape(h, f^.typ, false); f := f^.next; end; + else + shape(h, o^.typ, o^.cls = oType); + end; + return h; +end; + +(* The universe *) + +proc basic(name: []U8; form: Form; size: I64; signed: BOOL): ^Type; +var t: ^Type; o: ^Obj; +begin + t := newType(form, size, size); + t^.signed := signed; + o := newObj(oType, Scan.intern(ADR(name[0]), LEN(name)), t); + o^.exported := true; + t^.obj := o; + _ := insert(o, 0); + return t; +end; + +proc enter(name: []U8; cls: Class; t: ^Type; v: I64); +var o: ^Obj; +begin + o := newObj(cls, Scan.intern(ADR(name[0]), LEN(name)), t); + o^.val := v; + o^.exported := true; + _ := insert(o, 0); +end; + +begin + hashMask := (1 shl 14) - 1; + hashTab := emptyTable(hashMask + 1); + depth := 1; + scopes[0] := 0; + nextScope := 0; + curModule := nil; + tI8 := basic("I8", fInt, 1, true); + tI16 := basic("I16", fInt, 2, true); + tI32 := basic("I32", fInt, 4, true); + tI64 := basic("I64", fInt, 8, true); + tU8 := basic("U8", fInt, 1, false); + tU16 := basic("U16", fInt, 2, false); + tU32 := basic("U32", fInt, 4, false); + tU64 := basic("U64", fInt, 8, false); + tInt := basic("INT", fInt, 8, true); + tUInt := basic("UINT", fInt, 8, false); + tBool := basic("BOOL", fBool, 1, false); + tF32 := basic("F32", fReal, 4, false); + tReal := basic("F64", fReal, 8, false); + tRConst := newType(fReal, 8, 8); + tError := basic("ERROR", fError, 8, false); + tConst := newType(fConst, 8, 8); + tConst^.signed := true; + tNil := newType(fNil, 8, 8); + tStr := newType(fStr, 0, 1); + tNone := newType(fNone, 0, 1); + tPtrU8 := newType(fPtr, 8, 8); + tPtrU8^.base := tU8; + tBytes := newType(fSlice, 16, 8); + tBytes^.base := tU8; + tPoison := newType(fInt, 8, 8); + tPoison^.signed := true; + enter("true", oConst, tBool, 1); + enter("false", oConst, tBool, 0); + enter("nil", oConst, tNil, 0); + enter("SIZE", oBuiltin, nil, bSize); + enter("ADR", oBuiltin, nil, bAdr); + enter("LEN", oBuiltin, nil, bLen); + enter("NEW", oBuiltin, nil, bNew); + enter("MSG", oBuiltin, nil, bMsg); + enter("SYSCALL", oBuiltin, nil, bSyscall); + enter("FENCE", oBuiltin, nil, bFence); + enter("CAS", oBuiltin, nil, bCas); + enter("XCHG", oBuiltin, nil, bXchg); + enter("XADD", oBuiltin, nil, bXadd); + enter("ARGC", oBuiltin, nil, bArgc); + enter("ARGV", oBuiltin, nil, bArgv); + enter("INC", oBuiltin, nil, bInc); + enter("DEC", oBuiltin, nil, bDec); + enter("COPY", oBuiltin, nil, bCopy); +end Sym. diff --git a/self/check.sh b/self/check.sh index 02b3ac9..2bd1d07 100755 --- a/self/check.sh +++ b/self/check.sh @@ -33,3 +33,24 @@ printf 'a bad b bad bad c\nd bad\n' >$b/rec.raz r=$($b/recover $b/rec.raz 2>/dev/null) || test $? = 1 test "$r" = "8 names, 4 failed, 4 errors" && echo "recover ok" + +# Chunk and Sym: a fixed pseudo-random script each, run by both sides, +# which print all they have made or answered; Sym also ends, as the +# argument says, in an error, whose message and status must agree +for u in Chunk Sym; do + l=$(echo $u | tr A-Z a-z) + fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/${l}dump.seed self/test/${u}Dump.pas >/dev/null + ./raz -Werror -I self -o $b/${l}dump.self self/test/${u}Dump.raz +done +for a in "" dup deep; do + for s in seed self; do + t=0; $b/chunkdump.$s >$b/chunk.$s 2>/dev/null || t=$? + t2=0; $b/symdump.$s $a >$b/sym.$s.out 2>$b/sym.$s.err || t2=$? + echo "$t $t2" >$b/status.$s + done + cmp $b/status.seed $b/status.self + cmp $b/chunk.seed $b/chunk.self + cmp $b/sym.seed.out $b/sym.self.out + cmp $b/sym.seed.err $b/sym.self.err +done +echo "chunk and sym ok" diff --git a/self/test/ChunkDump.pas b/self/test/ChunkDump.pas new file mode 100644 index 0000000..9200df4 --- /dev/null +++ b/self/test/ChunkDump.pas @@ -0,0 +1,89 @@ +{ Makes a program of chunks by a fixed pseudo-random script and prints + all of it: the seed's side of a test of self/Chunk.raz, whose + ChunkDump.raz does the same and prints the same. } +program chunkdump; +{$mode objfpc}{$H-} +uses diag, scan, chunk; +var + seed: int64; + names: array[0..7] of longint; + i, k, n, op, c, sum, open, x, y, z: longint; + b: array[0..63] of byte; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +begin + seed := 7; + for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end; + open := -1; + sum := 0; + for k := 1 to 30000 do begin + op := Rnd(16); + case op of + 0..3: Put1(Rnd(256)); + 4: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put4(x - y) end; + 5: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put8(int64(x) * 4096 - y) end; + 6: begin + if open >= 0 then EndChunk(open); + x := Rnd(5); y := Rnd(9); + open := NewChunk(secText, x - 1, y - 1); + BeginChunk(open); + end; + 7: begin x := Rnd(8); curFile := names[x]; x := Rnd(300); y := Rnd(80); NoteLine(x, y) end; + 8: if numChunks > 0 then begin x := Rnd(numChunks); y := Rnd(100); AddFixup(pc, x, y - 50) end; + 9: if (open >= 0) and (pc - chunks^[open].start > 8) then begin x := Rnd(6); TakeBack(x) end; + 10: begin + x := Rnd(5); y := Rnd(9); + c := NewChunk(secRodata, x - 1, y - 1); + n := Rnd(64); + for i := 0 to n - 1 do b[i] := Rnd(256); + x := Rnd(4); + SetData(c, @b[0], n, 1 shl x); + n := Rnd(4); + for i := 1 to n do begin x := Rnd(8); y := Rnd(numChunks); z := Rnd(10); AddDataFixup(c, x * 8, y, z) end; + end; + 11: begin + x := Rnd(5); y := Rnd(9); + c := NewChunk(secBss, x - 1, y - 1); + x := Rnd(100); y := Rnd(4); + SetBss(c, x, 1 shl y); + end; + 12: begin x := Rnd(8); c := ExternChunk(names[x]) end; + 13: if numChunks > 0 then begin + x := Rnd(numChunks); y := Rnd(8); z := Rnd(200); n := Rnd(5); + NoteVar(x, names[y], z - 100, n); + end; + 14: if pc >= 8 then begin + x := Rnd(1 shl 30); y := Rnd(1 shl 30); + Put4At(pc - 8, x - y); + sum := (sum + Get4At(pc - 8)) and $FFFFFF; + end; + 15: if numChunks > 0 then begin + x := Rnd(numChunks); chunks^[x].live := true; + x := Rnd(numChunks); y := Rnd(1 shl 30); chunks^[x].adr := y; + end; + end; + end; + if open >= 0 then EndChunk(open); + writeln('sum ', sum, ' pc ', pc, ' rolen ', rolen); + for i := 0 to numChunks - 1 do + with chunks^[i] do + writeln('C ', i, ' ', ord(sec), ' ', start, ' ', size, ' ', align, ' ', firstFix, ' ', numFix, ' ', + module, ' ', name, ' ', adr, ' ', ord(live), ' ', ord(ext), ' ', ChunkName(i)); + for i := 0 to numFixups - 1 do + writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); + for i := 0 to numDataFixups - 1 do + writeln('D ', dataFixups^[i].at, ' ', dataFixups^[i].chunk, ' ', dataFixups^[i].addend); + for i := 0 to numLines - 1 do + writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].path, ' ', lines^[i].line, ' ', lines^[i].col); + for i := 0 to numVarNotes - 1 do + writeln('V ', varNotes[i].chunk, ' ', varNotes[i].name, ' ', varNotes[i].off, ' ', varNotes[i].kind); + for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); + writeln; + for i := 0 to rolen - 1 do write(HexStr(rodata^[i], 2)); + writeln; +end. diff --git a/self/test/ChunkDump.raz b/self/test/ChunkDump.raz new file mode 100644 index 0000000..dc52cee --- /dev/null +++ b/self/test/ChunkDump.raz @@ -0,0 +1,118 @@ +(* Makes a program of chunks by a fixed pseudo-random script and prints + all of it: self/Chunk.raz's side of a test against the seed's, + ChunkDump.pas, which prints the same. *) +module ChunkDump; +import Out, Fmt, Scan, Chunk; + +var seed: I64; + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +(* a flag, as the number the seed's side prints for it *) +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +proc main*; +var + names: [8]INT; b: [64]U8; + i, k, n, op, c, sum, open, x, y, z: INT; +begin + seed := 7; + for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end; + open := -1; + sum := 0; + for k := 1 to 30000 do + op := rnd(16); + match op of + | 0..3: Chunk.put1(rnd(256)); + | 4: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put4(x - y); + | 5: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put8(I64(x) * 4096 - I64(y)); + | 6: + if open >= 0 then Chunk.endChunk(open); end; + x := rnd(5); y := rnd(9); + open := Chunk.newChunk(Chunk.secText, x - 1, y - 1); + Chunk.beginChunk(open); + | 7: + x := rnd(8); Chunk.setCurFile(names[x]); + x := rnd(300); y := rnd(80); Chunk.noteLine(x, y); + | 8: + if Chunk.numChunks > 0 then + x := rnd(Chunk.numChunks); y := rnd(100); Chunk.addFixup(Chunk.pc, x, y - 50); + end; + | 9: + if (open >= 0) and (Chunk.pc - Chunk.chunks[open].start > 8) then + x := rnd(6); Chunk.takeBack(x); + end; + | 10: + x := rnd(5); y := rnd(9); + c := Chunk.newChunk(Chunk.secRodata, x - 1, y - 1); + n := rnd(64); + for i := 0 to n - 1 do b[i] := U8(rnd(256)); end; + x := rnd(4); + Chunk.setData(c, ADR(b[0]), n, 1 shl x); + n := rnd(4); + for i := 1 to n do + x := rnd(8); y := rnd(Chunk.numChunks); z := rnd(10); + Chunk.addDataFixup(c, x * 8, y, z); + end; + | 11: + x := rnd(5); y := rnd(9); + c := Chunk.newChunk(Chunk.secBss, x - 1, y - 1); + x := rnd(100); y := rnd(4); + Chunk.setBss(c, x, 1 shl y); + | 12: x := rnd(8); c := Chunk.externChunk(names[x]); + | 13: + if Chunk.numChunks > 0 then + x := rnd(Chunk.numChunks); y := rnd(8); z := rnd(200); n := rnd(5); + Chunk.noteVar(x, names[y], z - 100, n); + end; + | 14: + if Chunk.pc >= 8 then + x := rnd(1 shl 30); y := rnd(1 shl 30); + Chunk.put4At(Chunk.pc - 8, x - y); + sum := (sum + Chunk.get4At(Chunk.pc - 8)) & 0FFFFFFH; + end; + | else: + if Chunk.numChunks > 0 then + x := rnd(Chunk.numChunks); Chunk.setLive(x); + x := rnd(Chunk.numChunks); y := rnd(1 shl 30); Chunk.setAdr(x, y); + end; + end; + end; + if open >= 0 then Chunk.endChunk(open); end; + Fmt.print("sum {} pc {} rolen {}\n", [Fmt.int(sum), Fmt.int(Chunk.pc), Fmt.int(Chunk.rolen)]); + for i := 0 to Chunk.numChunks - 1 do + Fmt.print("C {} {} {} {} {} {} {} {} {} {} {} {} {}\n", [Fmt.int(i), Fmt.int(INT(Chunk.chunks[i].sec)), + Fmt.int(Chunk.chunks[i].start), Fmt.int(Chunk.chunks[i].size), Fmt.int(Chunk.chunks[i].align), + Fmt.int(Chunk.chunks[i].firstFix), Fmt.int(Chunk.chunks[i].numFix), Fmt.int(Chunk.chunks[i].home), + Fmt.int(Chunk.chunks[i].name), Fmt.int(Chunk.chunks[i].adr), + Fmt.int(bit(Chunk.chunks[i].live)), Fmt.int(bit(Chunk.chunks[i].ext)), Fmt.str(Chunk.chunkName(i))]); + end; + for i := 0 to Chunk.numFixups - 1 do + Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); + end; + for i := 0 to Chunk.numDataFixups - 1 do + Fmt.print("D {} {} {}\n", [Fmt.int(Chunk.dataFixups[i].at), Fmt.int(Chunk.dataFixups[i].chunk), Fmt.int(Chunk.dataFixups[i].addend)]); + end; + for i := 0 to Chunk.numLines - 1 do + Fmt.print("L {} {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk), + Fmt.int(Chunk.lines[i].path), Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]); + end; + for i := 0 to Chunk.numVarNotes - 1 do + Fmt.print("V {} {} {} {}\n", [Fmt.int(Chunk.varNotes[i].chunk), Fmt.int(Chunk.varNotes[i].name), + Fmt.int(Chunk.varNotes[i].off), Fmt.int(Chunk.varNotes[i].kind)]); + end; + for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; + Out.ln; + for i := 0 to Chunk.rolen - 1 do Out.hex(U64(Chunk.rodata[i]), 2); end; + Out.ln; +end; + +end ChunkDump. diff --git a/self/test/SymDump.pas b/self/test/SymDump.pas new file mode 100644 index 0000000..eb58ef7 --- /dev/null +++ b/self/test/SymDump.pas @@ -0,0 +1,185 @@ +{ Builds types and objects by a fixed pseudo-random script, asks of them + what the parser asks of sym, and prints the answers: the seed's side + of a test of self/Sym.raz, whose SymDump.raz does the same and prints + the same. With the argument dup or deep it ends in the error of a name + declared twice, or of too many scopes. } +program symdump; +{$mode objfpc}{$H-} +uses diag, scan, sym; +const + Words: array[0..19] of string = ('alpha', 'alpho', 'beta', 'bet', 'gamma', 'gama', 'delta', 'Delta', + 'eps', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi'); +var + seed: int64; + names: array[0..19] of longint; + mods: array[0..2] of PModule; + base: array[0..11] of PType; + pool: array[0..299] of PType; + objs: array[0..299] of PObj; + numPool, numObjs, i, k, n, op, x, y, z: longint; + t, o2: PType; + o: PObj; + saved: array[0..MaxDepth - 1] of longint; + d: longint; + v: int64; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +function Fields(m: longint; allowVar: boolean): PObj; +var f, first, last: PObj; j, x, y, z: longint; +begin + first := nil; last := nil; + for j := 1 to m do begin + x := Rnd(20); y := Rnd(numPool); + f := NewObj(oField, names[x], pool[y]); + z := Rnd(2); f^.exported := z = 0; + z := Rnd(3); f^.isVar := allowVar and (z = 0); + f^.val := j * 8; + if first = nil then first := f else last^.next := f; + last := f; + end; + Fields := first; +end; + +procedure Add(t: PType); +begin + if numPool <= High(pool) then begin pool[numPool] := t; inc(numPool) end; +end; + +procedure MakeType; +var t: PType; r, m, x: longint; f: PObj; +begin + r := Rnd(11); + case r of + 0: t := NewType(fPtr, 8, 8); + 1: t := NewType(fArray, 0, 1); + 2: t := NewType(fSlice, 16, 8); + 3: t := NewType(fRecord, 0, 8); + 4: t := NewType(fProc, 8, 8); + 5: t := NewType(fSet, 8, 8); + 6: t := NewType(fVariant, 16, 8); + 7: t := NewType(fEnum, 1, 1); + 8: t := NewType(fRecord, 16, 8); + 9: t := NewType(fProc, 8, 8); + else t := NewType(fPtr, 8, 8); + end; + x := Rnd(numPool); t^.base := pool[x]; + t^.len := Rnd(5); + x := Rnd(4); t^.vol := x = 0; + x := Rnd(4); t^.variadic := (t^.form = fProc) and (x = 0); + x := Rnd(2); t^.tuple := (t^.form = fRecord) and (x = 0); + if t^.form in [fRecord, fProc, fVariant] then begin + m := Rnd(4); + t^.fields := Fields(m, t^.form = fProc); + t^.len := m; + if t^.form = fRecord then t^.base := nil; + x := Rnd(2); + if (t^.form = fProc) and (x = 0) then t^.base := nil; + if t^.form = fVariant then begin + f := t^.fields; + while f <> nil do begin f^.cls := oCase; x := Rnd(3); f^.fields := Fields(x, false); f := f^.next end; + end; + end; + x := Rnd(3); + if x = 0 then begin + x := Rnd(20); t^.obj := NewObj(oType, names[x], t); + x := Rnd(3); t^.obj^.module := mods[x]; + end; + Add(t); +end; + +begin + seed := 11; + for i := 0 to 19 do names[i] := Intern(@Words[i][1], length(Words[i])); + for i := 0 to 2 do begin + New(mods[i]); FillChar(mods[i]^, SizeOf(TModule), 0); + mods[i]^.sname := names[i * 5]; + end; + curModule := mods[0]; + base[0] := tI8; base[1] := tI16; base[2] := tI32; base[3] := tI64; base[4] := tU8; + base[5] := tU16; base[6] := tU32; base[7] := tU64; base[8] := tBool; base[9] := tF32; + base[10] := tReal; base[11] := tInt; + for i := 0 to 11 do Add(base[i]); + if ParamCount >= 1 then begin if Open('lib/Rt.raz') <> '' then Fatal('no file'); Next; Next end; + numObjs := 0; + for k := 1 to 4000 do begin + op := Rnd(14); + case op of + 0, 1, 2: MakeType; + 3, 4: if numObjs <= High(objs) then begin + x := Rnd(8); y := Rnd(20); + if Find(x, names[y]) = nil then begin + z := Rnd(8); n := Rnd(numPool); + o := NewObj(TClass(z), names[y], pool[n]); + z := Rnd(2); o^.exported := z = 0; + z := Rnd(3); o^.module := mods[z]; + Insert(o, x); + objs[numObjs] := o; inc(numObjs); + writeln('I ', x, ' ', NameOf(names[y]), ' ', o^.scope); + end; + end; + 5: begin x := Rnd(8); y := Rnd(20); o := Find(x, names[y]); + write('F ', x, ' ', NameOf(names[y]), ' '); + if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope); + end; + 6: begin + x := Rnd(8); y := Rnd(20); + if ScopeDepth < 6 then OpenScope(x); + o := Lookup(names[y]); + write('L ', ScopeDepth, ' ', NameOf(names[y]), ' '); + if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope); + z := Rnd(2); + if (ScopeDepth > 1) and (z = 0) then CloseScope; + end; + 7: begin + y := Rnd(20); x := Rnd(9) - 1; z := Rnd(3); curModule := mods[z]; + o := Closest(names[y], x); + write('C ', NameOf(names[y]), ' ', x, ' '); + if o = nil then writeln('-') else writeln(NameOf(o^.name), ' ', o^.scope); + end; + 8: begin + x := Rnd(numPool); z := Rnd(3); curModule := mods[z]; + writeln('T ', TypeName(pool[x])); + end; + 9: begin + x := Rnd(numPool); y := Rnd(numPool); + writeln('S ', ord(Same(pool[x], pool[y])), ' ', ord(Same(pool[x], pool[x]))); + t := NewType(fPtr, 8, 8); t^.base := pool[x]; + o2 := t; t := NewType(fPtr, 8, 8); t^.base := pool[x]; + writeln('S ', ord(Same(o2, t))); + end; + 10: if numObjs > 0 then begin x := Rnd(numObjs); writeln('P ', HexStr(Fingerprint(objs[x]), 16)) end; + 11: begin + x := Rnd(numPool); y := Rnd(1 shl 20); z := Rnd(2); n := Rnd(2); + v := int64(y) * 4096 * z - y * n; + t := pool[x]; + writeln('B ', ord(Fits(v, t)), ' ', ord(IsInt(t)), ' ', ord(IsScalar(t)), ' ', ord(IsAggregate(t)), ' ', + ord(InTwoRegs(t)), ' ', ord(BehindPointer(t)), ' ', AlignUp(y, 1 shl z)); + end; + 12: if (ScopeDepth > 1) and (ScopeDepth < 6) then begin + d := ScopeDepth; SaveScopes(d, saved); + writeln('V ', ScopeDepth, ' ', TopScope); + RestoreScopes(d, saved); + writeln('V ', ScopeDepth, ' ', TopScope); + x := NewScope; writeln('N ', x); + end; + 13: begin x := ScopeDepth; if x > 3 then CutScopes(2); writeln('X ', x, ' ', ScopeDepth) end; + end; + end; + { the universe, and the sizes it made } + for i := 0 to 11 do writeln('U ', ord(base[i]^.form), ' ', base[i]^.size, ' ', ord(base[i]^.signed), ' ', NameOf(base[i]^.obj^.name)); + if ParamCount >= 1 then begin + if ParamStr(1) = 'dup' then begin + o := NewObj(oVar, names[3], tI8); + Insert(o, 100); Insert(o, 100); + end; + if ParamStr(1) = 'deep' then begin + CutScopes(1); + for i := 1 to MaxDepth + 1 do OpenScope(i); + end; + end; +end. diff --git a/self/test/SymDump.raz b/self/test/SymDump.raz new file mode 100644 index 0000000..9d3610a --- /dev/null +++ b/self/test/SymDump.raz @@ -0,0 +1,225 @@ +(* Builds types and objects by a fixed pseudo-random script, asks of them + what the parser asks of Sym, and prints the answers: self/Sym.raz's + side of a test against the seed's, SymDump.pas, which prints the same. + With the argument dup or deep it ends in the error of a name declared + twice, or of too many scopes. *) +module SymDump; +import Out, Fmt, Files, Heap, Diag, Scan, Sym; + +const + Words: [20][]U8 = ["alpha", "alpho", "beta", "bet", "gamma", "gama", "delta", "Delta", + "eps", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi"]; + +var + seed: I64; + names: [20]INT; + mods: [3]^Sym.Module; + base: [12]^Sym.Type; + pool: [300]^Sym.Type; + objs: [300]^Sym.Obj; + classes: [8]Sym.Class; + numPool, numObjs: INT; + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +proc nm(i: INT): []U8; +begin + return Scan.nameOf(names[i]); +end; + +(* The result of a call that must succeed *) +proc ok(e: ERROR); +begin + if e # nil then Diag.finish; end; +end; + +proc fields(m: INT; allowVar: BOOL): ^Sym.Obj; +var f, first, last: ^Sym.Obj; j, x, y, z: INT; +begin + first := nil; last := nil; + for j := 1 to m do + x := rnd(20); y := rnd(numPool); + f := Sym.newObj(Sym.oField, names[x], pool[y]); + z := rnd(2); f^.exported := z = 0; + z := rnd(3); f^.isVar := allowVar and (z = 0); + f^.val := j * 8; + if first = nil then first := f; else last^.next := f; end; + last := f; + end; + return first; +end; + +proc add(t: ^Sym.Type); +begin + if numPool < 300 then pool[numPool] := t; INC(numPool); end; +end; + +proc makeType; +var t: ^Sym.Type; r, m, x: INT; f: ^Sym.Obj; +begin + r := rnd(11); + match r of + | 0: t := Sym.newType(Sym.fPtr, 8, 8); + | 1: t := Sym.newType(Sym.fArray, 0, 1); + | 2: t := Sym.newType(Sym.fSlice, 16, 8); + | 3: t := Sym.newType(Sym.fRecord, 0, 8); + | 4: t := Sym.newType(Sym.fProc, 8, 8); + | 5: t := Sym.newType(Sym.fSet, 8, 8); + | 6: t := Sym.newType(Sym.fVariant, 16, 8); + | 7: t := Sym.newType(Sym.fEnum, 1, 1); + | 8: t := Sym.newType(Sym.fRecord, 16, 8); + | 9: t := Sym.newType(Sym.fProc, 8, 8); + | else: t := Sym.newType(Sym.fPtr, 8, 8); + end; + x := rnd(numPool); t^.base := pool[x]; + t^.len := rnd(5); + x := rnd(4); t^.vol := x = 0; + x := rnd(4); t^.variadic := (t^.form = Sym.fProc) and (x = 0); + x := rnd(2); t^.tuple := (t^.form = Sym.fRecord) and (x = 0); + if (t^.form = Sym.fRecord) or (t^.form = Sym.fProc) or (t^.form = Sym.fVariant) then + m := rnd(4); + t^.fields := fields(m, t^.form = Sym.fProc); + t^.len := m; + if t^.form = Sym.fRecord then t^.base := nil; end; + x := rnd(2); + if (t^.form = Sym.fProc) and (x = 0) then t^.base := nil; end; + if t^.form = Sym.fVariant then + f := t^.fields; + while f # nil do + f^.cls := Sym.oCase; + x := rnd(3); f^.fields := fields(x, false); + f := f^.next; + end; + end; + end; + x := rnd(3); + if x = 0 then + x := rnd(20); t^.obj := Sym.newObj(Sym.oType, names[x], t); + x := rnd(3); t^.obj^.home := mods[x]; + end; + add(t); +end; + +proc main*; +var + i, k, op, x, y, z, n, d: INT; t, o2: ^Sym.Type; o: ^Sym.Obj; v: I64; + saved: [Sym.MaxDepth]INT; arg: []U8; +begin + seed := 11; + classes := [Sym.oConst, Sym.oType, Sym.oVar, Sym.oProc, Sym.oModule, Sym.oField, Sym.oCase, Sym.oBuiltin]; + for i := 0 to 19 do names[i] := Scan.intern(ADR(Words[i][0]), LEN(Words[i])); end; + for i := 0 to 2 do + NEW(mods[i], Heap.heap); + mods[i]^.sname := names[i * 5]; + end; + Sym.setCurModule(mods[0]); + base[0] := Sym.tI8; base[1] := Sym.tI16; base[2] := Sym.tI32; base[3] := Sym.tI64; base[4] := Sym.tU8; + base[5] := Sym.tU16; base[6] := Sym.tU32; base[7] := Sym.tU64; base[8] := Sym.tBool; base[9] := Sym.tF32; + base[10] := Sym.tReal; base[11] := Sym.tInt; + for i := 0 to 11 do add(base[i]); end; + arg := ""; + if ARGC > 1 then arg := Files.arg(1); end; + if LEN(arg) > 0 then + if LEN(Scan.open("lib/Rt.raz")) # 0 then Diag.fatal("no file"); end; + Scan.next; Scan.next; + end; + numObjs := 0; + for k := 1 to 4000 do + op := rnd(14); + match op of + | 0, 1, 2: makeType; + | 3, 4: + if numObjs < 300 then + x := rnd(8); y := rnd(20); + if Sym.find(x, names[y]) = nil then + z := rnd(8); n := rnd(numPool); + o := Sym.newObj(classes[z], names[y], pool[n]); + z := rnd(2); o^.exported := z = 0; + z := rnd(3); o^.home := mods[z]; + ok(Sym.insert(o, x)); + objs[numObjs] := o; INC(numObjs); + Fmt.print("I {} {} {}\n", [Fmt.int(x), Fmt.str(nm(y)), Fmt.int(o^.scope)]); + end; + end; + | 5: + x := rnd(8); y := rnd(20); o := Sym.find(x, names[y]); + Fmt.print("F {} {} ", [Fmt.int(x), Fmt.str(nm(y))]); + if o = nil then Out.str("-\n"); + else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end; + | 6: + x := rnd(8); y := rnd(20); + if Sym.scopeDepth() < 6 then ok(Sym.openScope(x)); end; + o := Sym.lookup(names[y]); + Fmt.print("L {} {} ", [Fmt.int(Sym.scopeDepth()), Fmt.str(nm(y))]); + if o = nil then Out.str("-\n"); + else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end; + z := rnd(2); + if (Sym.scopeDepth() > 1) and (z = 0) then Sym.closeScope; end; + | 7: + y := rnd(20); x := rnd(9) - 1; z := rnd(3); Sym.setCurModule(mods[z]); + o := Sym.closest(names[y], x); + Fmt.print("C {} {} ", [Fmt.str(nm(y)), Fmt.int(x)]); + if o = nil then Out.str("-\n"); + else Fmt.print("{} {}\n", [Fmt.str(Scan.nameOf(o^.name)), Fmt.int(o^.scope)]); end; + | 8: + x := rnd(numPool); z := rnd(3); Sym.setCurModule(mods[z]); + Fmt.print("T {}\n", [Fmt.str(Sym.typeName(pool[x]))]); + | 9: + x := rnd(numPool); y := rnd(numPool); + Fmt.print("S {} {}\n", [Fmt.int(bit(Sym.same(pool[x], pool[y]))), Fmt.int(bit(Sym.same(pool[x], pool[x])))]); + t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x]; + o2 := t; t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x]; + Fmt.print("S {}\n", [Fmt.int(bit(Sym.same(o2, t)))]); + | 10: + if numObjs > 0 then + x := rnd(numObjs); + Out.str("P "); Out.hex(Sym.fingerprint(objs[x]), 16); Out.ln; + end; + | 11: + x := rnd(numPool); y := rnd(1 shl 20); z := rnd(2); n := rnd(2); + v := I64(y) * 4096 * I64(z) - I64(y) * I64(n); + t := pool[x]; + Fmt.print("B {} {} {} {} {} {} {}\n", [Fmt.int(bit(Sym.fits(v, t))), Fmt.int(bit(Sym.isInt(t))), + Fmt.int(bit(Sym.isScalar(t))), Fmt.int(bit(Sym.isAggregate(t))), Fmt.int(bit(Sym.inTwoRegs(t))), + Fmt.int(bit(Sym.behindPointer(t))), Fmt.int(Sym.alignUp(y, 1 shl z))]); + | 12: + if (Sym.scopeDepth() > 1) and (Sym.scopeDepth() < 6) then + d := Sym.saveScopes(saved); + Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]); + Sym.restoreScopes(d, saved); + Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]); + x := Sym.newScope(); + Fmt.print("N {}\n", [Fmt.int(x)]); + end; + | else: + x := Sym.scopeDepth(); + if x > 3 then Sym.cutScopes(2); end; + Fmt.print("X {} {}\n", [Fmt.int(x), Fmt.int(Sym.scopeDepth())]); + end; + end; + for i := 0 to 11 do + Fmt.print("U {} {} {} {}\n", [Fmt.int(INT(base[i]^.form)), Fmt.int(base[i]^.size), + Fmt.int(bit(base[i]^.signed)), Fmt.str(Scan.nameOf(base[i]^.obj^.name))]); + end; + if arg = "dup" then + o := Sym.newObj(Sym.oVar, names[3], Sym.tI8); + ok(Sym.insert(o, 100)); + ok(Sym.insert(o, 100)); + end; + if arg = "deep" then + Sym.cutScopes(1); + for i := 1 to Sym.MaxDepth + 1 do ok(Sym.openScope(i)); end; + end; +end; + +end SymDump.