From 043eac0aec2b1644a42fb5f79be3f57ccad30190 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sun, 11 Oct 2026 11:47:09 +0100 Subject: [PATCH] Generic instances made where first used Report 2026-10.3, section 3. An import with arguments only notes where they are; the first use of its name reads them there and makes the instance, so they may name types declared after the imports. The code buffer is one run of bytes, so an instance can't be compiled in the middle of a procedure's code: InstancesFor reads ahead through a procedure, or the module body, before its code begins, and makes the instances it names. An argument not declared by then is an error at the import, with a note at the use; an import never used makes no instance. The error tests of generic imports now use them. test/run/FirstUse: a type after the import, two imports of one instance, one never used (Loud's body never runs), one first used in a procedure; test/err/FirstUseLate. --- diff --git a/PLAN.md b/PLAN.md index 3057968..17e0539 100644 --- a/PLAN.md +++ b/PLAN.md @@ -448,7 +448,7 @@ report's examples, and `test/genbench.py`; each `and` or `or` between relations is checked by hand, since its meaning may change without an error. `make bench` must still pass. -- [ ] 46. Generic instances on first use: the import keeps its +- [x] 46. Generic instances on first use: the import keeps its arguments unresolved, and the instance is made, and its body queued to run before the importer's, the first time the import's name is used; an argument not declared by then is an error at diff --git a/doc/compiler.md b/doc/compiler.md index 9b5c1f7..f9a4427 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -13,7 +13,7 @@ | `src/sym.pas` | 593 | 493 | Types, objects, scopes, layout | | `src/x64.pas` | 693 | 556 | Code buffer, chunks, fixups, places, instruction encoder | | `src/gen.pas` | 1,596 | 1,378 | Items: loading, storing, copying, frames, calls | -| `src/parse.pas` | 2,323 | 2,098 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/parse.pas` | 2,443 | 2,201 | Declarations, statements, expressions, built-ins, recovery, warnings | | `src/link.pas` | 180 | 138 | Tree shaking, layout, patching, the places | | `src/elf.pas` | 425 | 351 | Static and dynamic ELF, symbol table, line numbers | | `src/raz.pas` | 227 | 178 | The command line, the entry points | @@ -338,9 +338,15 @@ of its files there; `CheckSiblings` then reads the files for other targets beside it, declarations only, and `CompareIface` holds them to the same exports by their fingerprints. A generic module is -compiled once per distinct list of arguments: `ParseArgs` reads -them at the import, `Params` binds them to the module's parameters, and -`IsModule` decides whether an instance already exists. +compiled once per distinct list of arguments, where it is first used. +The import only notes where its arguments are (`SkipArgs`, `deferred`); +`FirstUse`, from `QualIdent`, has `MakeInstance` go back there, where +`ParseArgs` reads them, then compile the instance. `Params` binds them +to the module's parameters, and `IsModule` decides whether an instance +already exists. An instance can't be compiled in the middle of another +procedure's code, since the code buffer is one run of bytes, so +`InstancesFor` reads ahead through a procedure, or the module's body, +before its code begins, and makes the instances it names. **Recovery.** After an error the parser carries on, so that one run reports them all. `Guard` notes, at the start of a statement or diff --git a/src/parse.pas b/src/parse.pas index 5779a32..b5d8c24 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -48,6 +48,15 @@ base: longint; { the deferred statements in force outside it } end; + { A generic module's import whose instance isn't made yet } + TDeferred = record + o: PObj; { the name it imports as } + m: PModule; { the module that imports it } + mname: longint; { the generic module } + args: TScanState; { at the "(" of its arguments } + at: TPos; { the import } + end; + var checkMode: boolean; { reading a file only for its interface } inTypes: boolean; { in a type section: ^T may name a later type } @@ -71,6 +80,10 @@ declaring: array[0..63] of longint; { the names the declaration being read declares } numDeclaring: longint; skipped: boolean; { the last statement had an error and was skipped } + deferred: array[0..63] of TDeferred; + numDeferred: longint; + making: boolean; { reading an instance's arguments, at its first use } + useAt: TPos; { ... which is here } procedure Expression(var x: TItem; want: PType); forward; function ParseType: PType; forward; @@ -194,7 +207,7 @@ CutScopes(r.scopes); depth := r.depth; numDefers := r.numDefers; curLoop := r.loop; curResult := r.result; deferring := r.deferring; directDefer := r.directDefer; - inTypes := false; declExported := false; inExtern := false; + inTypes := false; declExported := false; inExtern := false; making := false; end; { Gives up the construct r is for, and the one around it } @@ -290,22 +303,29 @@ else if (NameOf(n) = 'elif') or (NameOf(n) = 'elseif') then Help('raz writes elsif') else DidYouMean(Closest(n, -1)); end; + +procedure FirstUse(o: PObj; const at: TPos); forward; +procedure InstancesFor(wholeRest: boolean); forward; +procedure AddImport(m, im: PModule); forward; function QualIdent: PObj; -var o: PObj; m: PModule; +var o: PObj; m: PModule; at: TPos; begin if tok <> sIdent then Expected('a name'); + at := TokPos; o := Lookup(id); if o = nil then begin - Poison(id); + if not making then Poison(id); { it may yet be declared } quiet := false; - NotDeclared(TokPos, id); + NotDeclared(at, id); + if making then Note(useAt, 'the instance is made here, where it is first used'); Fail; end; if o^.typ = tPoison then quiet := true; Named(o); Next; if o^.cls = oModule then begin + if o^.module = nil then FirstUse(o, at); Expect(sPeriod); if tok <> sIdent then Expected('a name'); m := o^.module; @@ -1643,6 +1663,7 @@ procedure ProcDecl; var n, line: longint; exp: boolean; sig: PType; p: PObj; at: TPos; begin + InstancesFor(false); line := CurLine; Next; IdentDef(n, exp, at); @@ -1932,6 +1953,19 @@ Expect(sRparen); end; +{ Past an instance's arguments, to be read when it is made } +procedure SkipArgs; +var p: longint; +begin + p := 0; + repeat + if tok = sLparen then inc(p) + else if tok = sRparen then dec(p) + else if tok in [sSemicolon, sEof] then Expected('")"'); + Next; + until p = 0; +end; + { A generic module's parameters, bound to the instance's arguments: a type parameter names its type, a procedure parameter its procedure. } procedure Params(m: PModule); @@ -2043,8 +2077,9 @@ function CompileFile(const path: shortstring; n: longint; const args: TArgs; checkOnly: boolean): PModule; var st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint; - oldMod: PModule; oldCheck: boolean; m, im: PModule; - imp: PImport; lib: PLib; start: TPos; alias, mname, line, oldPath: longint; o: PObj; body: longint; iargs: TArgs; + oldMod: PModule; oldCheck: boolean; m: PModule; + lib: PLib; start: TPos; alias, mname, line, oldPath: longint; o: PObj; body: longint; iargs: TArgs; + generic: boolean; argsAt: TScanState; begin SaveScan(st); SaveScopes(d, saved); @@ -2083,24 +2118,36 @@ alias := id; mname := id; iargs.n := 0; + generic := false; Next; if tok = sBecomes then begin Next; if tok <> sIdent then Expected('a module name'); mname := id; Next; - if tok = sLparen then ParseArgs(iargs, NameOf(mname)); + if tok = sLparen then begin + generic := true; + SaveScan(argsAt); + SkipArgs; + end; end; iargs.at := SpanFrom(start); - im := ImportModule(mname, iargs); o := NewObj(oModule, alias, nil); o^.pos := start; - o^.module := im; Declare(o); - New(imp); - imp^.module := im; - imp^.next := m^.imports; - m^.imports := imp; + if not generic then begin + o^.module := ImportModule(mname, iargs); + AddImport(m, o^.module); + end else begin + o^.module := nil; { until the instance is made, at its first use } + if numDeferred > High(deferred) then Mark('more than ' + IntStr(High(deferred) + 1) + ' generic imports'); + deferred[numDeferred].o := o; + deferred[numDeferred].m := m; + deferred[numDeferred].mname := mname; + deferred[numDeferred].args := argsAt; + deferred[numDeferred].at := iargs.at; + inc(numDeferred); + end; if tok <> sComma then break; Next; until false; @@ -2123,6 +2170,7 @@ if tok = sBegin then begin if checkMode then SkipBody else begin + InstancesFor(true); line := CurLine; Next; body := NewChunk(secText, m^.sname, nameBody); @@ -2283,6 +2331,78 @@ m := CompileFile(dir + '/' + f, name, args, false); CheckSiblings(dir, f, name, m, args); ImportModule := m; +end; + +procedure AddImport(m, im: PModule); +var imp: PImport; +begin + New(imp); + imp^.module := im; + imp^.next := m^.imports; + m^.imports := imp; +end; + +{ Makes the instance that deferred[i] imports: its arguments are read + where the import wrote them, and must be declared by now. Compiling + the instance comes in the middle of a declaration, so what that + declaration has under way is kept aside meanwhile. } +procedure MakeInstance(i: longint; const at: TPos); +var + d: TDeferred; st: TScanState; args: TArgs; types, exported, ext, wasQuiet: boolean; nf, nd: longint; + ft: array[0..255] of PType; fp: array[0..255] of TPos; decl: array[0..63] of longint; +begin + d := deferred[i]; + dec(numDeferred); + deferred[i] := deferred[numDeferred]; + SaveScan(st); + RestoreScan(d.args); + args.n := 0; + making := true; useAt := at; + ParseArgs(args, NameOf(d.mname)); + making := false; + RestoreScan(st); + args.at := d.at; + types := inTypes; exported := declExported; ext := inExtern; wasQuiet := quiet; + nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring; + d.o^.module := ImportModule(d.mname, args); + inTypes := types; declExported := exported; inExtern := ext; quiet := wasQuiet; + numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl; + AddImport(curModule, d.o^.module); +end; + +procedure FirstUse(o: PObj; const at: TPos); +var i: longint; +begin + for i := 0 to numDeferred - 1 do + if deferred[i].o = o then begin MakeInstance(i, at); exit end; + Fail; { its arguments had an error, already reported } +end; + +{ An instance can't be compiled in the middle of another procedure's + code, so before a procedure's code begins, from its "proc" on, or + the module body's, from its "begin" to the end of the file, this + reads ahead for the names of imports not yet made, and makes those. } +procedure InstancesFor(wholeRest: boolean); +var st: TScanState; d, i: longint; begun: boolean; +begin + if checkMode then exit; + i := numDeferred - 1; + while (i >= 0) and (deferred[i].m <> curModule) do dec(i); + if i < 0 then exit; + SaveScan(st); + d := 0; begun := false; + repeat + case tok of + sIdent: for i := numDeferred - 1 downto 0 do + if (deferred[i].m = curModule) and (deferred[i].o^.name = id) then MakeInstance(i, TokPos); + sBegin: begin begun := begun or (d = 0); inc(d) end; + sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: inc(d); + sEnd, sUntil: dec(d); + end; + if not wholeRest and (d = 0) and (begun or (tok in [sForward, sCode])) then break; + Next; + until tok = sEof; + RestoreScan(st); end; function CompileMain(const path: shortstring): PModule; diff --git a/test/err/BadProc.raz b/test/err/BadProc.raz index 97268d2..0930581 100644 --- a/test/err/BadProc.raz +++ b/test/err/BadProc.raz @@ -1,3 +1,6 @@ module BadProc; import Str, M := Map([]U8, I64, Str.cmp, Str.eq); + +var m: M.Map; + end BadProc. diff --git a/test/err/FirstUseLate.err b/test/err/FirstUseLate.err new file mode 100644 index 0000000..7672f1b --- /dev/null +++ b/test/err/FirstUseLate.err @@ -0,0 +1,7 @@ +test/err/FirstUseLate.raz:2:18: error: Later isn't declared + 2 | import L := List(Later); + | ^^^^^ +test/err/FirstUseLate.raz:4:8: note: the instance is made here, where it is first used + 4 | var l: L.List; (* made here, before Later is declared *) + | ^ +raz: 1 error diff --git a/test/err/FirstUseLate.raz b/test/err/FirstUseLate.raz new file mode 100644 index 0000000..13f88da --- /dev/null +++ b/test/err/FirstUseLate.raz @@ -0,0 +1,8 @@ +module FirstUseLate; +import L := List(Later); + +var l: L.List; (* made here, before Later is declared *) + +type Later = I64; + +end FirstUseLate. diff --git a/test/err/NotGeneric.raz b/test/err/NotGeneric.raz index 547e417..5229919 100644 --- a/test/err/NotGeneric.raz +++ b/test/err/NotGeneric.raz @@ -1,3 +1,9 @@ module NotGeneric; import S := Str(I64); + +proc f(a, b: []U8): I64; +begin + return S.cmp(a, b); +end; + end NotGeneric. diff --git a/test/err/StmtArgKind.raz b/test/err/StmtArgKind.raz index 741c5a1..c88e4ba 100644 --- a/test/err/StmtArgKind.raz +++ b/test/err/StmtArgKind.raz @@ -1,3 +1,6 @@ module StmtArgKind; import Mem, L := List(Mem.Page); + +var l: L.List; + end StmtArgKind. diff --git a/test/err/StmtManyTypeArgs.raz b/test/err/StmtManyTypeArgs.raz index f82d04e..e9847cb 100644 --- a/test/err/StmtManyTypeArgs.raz +++ b/test/err/StmtManyTypeArgs.raz @@ -1,3 +1,6 @@ module StmtManyTypeArgs; import L := List(I64, I64); + +var l: L.List; + end StmtManyTypeArgs. diff --git a/test/err/StmtNeedProc.raz b/test/err/StmtNeedProc.raz index 338680c..01f87bc 100644 --- a/test/err/StmtNeedProc.raz +++ b/test/err/StmtNeedProc.raz @@ -1,3 +1,6 @@ module StmtNeedProc; import Str, M := Map([]U8, I64, I64, Str.eq); + +var m: M.Map; + end StmtNeedProc. diff --git a/test/err/StmtNeedType.raz b/test/err/StmtNeedType.raz index 0b77b4b..a3d751e 100644 --- a/test/err/StmtNeedType.raz +++ b/test/err/StmtNeedType.raz @@ -1,3 +1,6 @@ module StmtNeedType; import Str, M := Map(Str.cmp, I64, Str.cmp, Str.eq); + +var m: M.Map; + end StmtNeedType. diff --git a/test/err/StmtParamName.raz b/test/err/StmtParamName.raz index 60023c1..f306e96 100644 --- a/test/err/StmtParamName.raz +++ b/test/err/StmtParamName.raz @@ -1,3 +1,6 @@ module StmtParamName; import L := StmtParam(I64); + +var l: L.T; + end StmtParamName. diff --git a/test/run/FirstUse.expect b/test/run/FirstUse.expect new file mode 100644 index 0000000..457fe55 --- /dev/null +++ b/test/run/FirstUse.expect @@ -0,0 +1,6 @@ +an instance of Loud, of size 1 +an empty list +in main, Ones has size 1 +sky not red +rose red +grass - diff --git a/test/run/FirstUse.raz b/test/run/FirstUse.raz new file mode 100644 index 0000000..03163b0 --- /dev/null +++ b/test/run/FirstUse.raz @@ -0,0 +1,34 @@ +module FirstUse; +import Out, Str, Heap, Table := Map([]U8, Colour, Str.hash, Str.eq), + Ints := List(I64), More := List(I64), Never := Loud(I64), Ones := Loud(U8); + +type Colour = (red, green, blue); + +var names: Table.Map; (* Table is made here, after Colour *) + +proc show(k: []U8); +var c: Colour; found: BOOL; +begin + c, found := Table.get(ADR(names), k); + Out.str(k); + if not found then Out.str(" -"); elsif c = red then Out.str(" red"); else Out.str(" not red"); end; + Out.ln; +end; + +(* Ones is first used in a procedure, and made before its code *) +proc main*; +var a: Ints.List; b: More.List; +begin + a := b; (* two imports, one instance *) + if a.head = nil then Out.str("an empty list\n"); end; + Out.str("in main, Ones has size "); Out.int(Ones.size); Out.ln; + show("sky"); + show("rose"); + show("grass"); +end; + +begin + Table.init(ADR(names), Heap.heap); + Table.put(ADR(names), "rose", red); + Table.put(ADR(names), "sky", blue); +end FirstUse. diff --git a/test/run/mods/Loud.raz b/test/run/mods/Loud.raz new file mode 100644 index 0000000..ea812e4 --- /dev/null +++ b/test/run/mods/Loud.raz @@ -0,0 +1,10 @@ +(* A generic module with a body, which runs once for each instance *) +module Loud(T); +import Out; + +var size*: I64; + +begin + size := SIZE(T); + Out.str("an instance of Loud, of size "); Out.int(size); Out.ln; +end Loud.