raz / commit 043eac0a

commit
043eac0aec2b1644a42fb5f79be3f57ccad30190
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
bc22ce64
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.

patch · log

15 files changed, +233 -18

PLAN.md (history) modified +1 -1

@@ -448,7 +448,7 @@
448448 report's examples, and `test/genbench.py`; each `and` or `or`
449449 between relations is checked by hand, since its meaning may
450450 change without an error. `make bench` must still pass.
451-- [ ] 46. Generic instances on first use: the import keeps its
451+- [x] 46. Generic instances on first use: the import keeps its
452452 arguments unresolved, and the instance is made, and its body
453453 queued to run before the importer's, the first time the import's
454454 name is used; an argument not declared by then is an error at

doc/compiler.md (history) modified +10 -4

@@ -13,7 +13,7 @@
1313 | `src/sym.pas` | 593 | 493 | Types, objects, scopes, layout |
1414 | `src/x64.pas` | 693 | 556 | Code buffer, chunks, fixups, places, instruction encoder |
1515 | `src/gen.pas` | 1,596 | 1,378 | Items: loading, storing, copying, frames, calls |
16-| `src/parse.pas` | 2,323 | 2,098 | Declarations, statements, expressions, built-ins, recovery, warnings |
16+| `src/parse.pas` | 2,443 | 2,201 | Declarations, statements, expressions, built-ins, recovery, warnings |
1717 | `src/link.pas` | 180 | 138 | Tree shaking, layout, patching, the places |
1818 | `src/elf.pas` | 425 | 351 | Static and dynamic ELF, symbol table, line numbers |
1919 | `src/raz.pas` | 227 | 178 | The command line, the entry points |
@@ -338,9 +338,15 @@
338338 of its files there; `CheckSiblings` then reads the files for other
339339 targets beside it, declarations only, and `CompareIface` holds them
340340 to the same exports by their fingerprints. A generic module is
341-compiled once per distinct list of arguments: `ParseArgs` reads
342-them at the import, `Params` binds them to the module's parameters, and
343-`IsModule` decides whether an instance already exists.
341+compiled once per distinct list of arguments, where it is first used.
342+The import only notes where its arguments are (`SkipArgs`, `deferred`);
343+`FirstUse`, from `QualIdent`, has `MakeInstance` go back there, where
344+`ParseArgs` reads them, then compile the instance. `Params` binds them
345+to the module's parameters, and `IsModule` decides whether an instance
346+already exists. An instance can't be compiled in the middle of another
347+procedure's code, since the code buffer is one run of bytes, so
348+`InstancesFor` reads ahead through a procedure, or the module's body,
349+before its code begins, and makes the instances it names.
344350
345351 **Recovery.** After an error the parser carries on, so that one run
346352 reports them all. `Guard` notes, at the start of a statement or

src/parse.pas modified +133 -13

@@ -48,6 +48,15 @@
4848 base: longint; { the deferred statements in force outside it }
4949 end;
5050
51+ { A generic module's import whose instance isn't made yet }
52+ TDeferred = record
53+ o: PObj; { the name it imports as }
54+ m: PModule; { the module that imports it }
55+ mname: longint; { the generic module }
56+ args: TScanState; { at the "(" of its arguments }
57+ at: TPos; { the import }
58+ end;
59+
5160 var
5261 checkMode: boolean; { reading a file only for its interface }
5362 inTypes: boolean; { in a type section: ^T may name a later type }
@@ -71,6 +80,10 @@
7180 declaring: array[0..63] of longint; { the names the declaration being read declares }
7281 numDeclaring: longint;
7382 skipped: boolean; { the last statement had an error and was skipped }
83+ deferred: array[0..63] of TDeferred;
84+ numDeferred: longint;
85+ making: boolean; { reading an instance's arguments, at its first use }
86+ useAt: TPos; { ... which is here }
7487
7588 procedure Expression(var x: TItem; want: PType); forward;
7689 function ParseType: PType; forward;
@@ -194,7 +207,7 @@
194207 CutScopes(r.scopes); depth := r.depth; numDefers := r.numDefers;
195208 curLoop := r.loop; curResult := r.result;
196209 deferring := r.deferring; directDefer := r.directDefer;
197- inTypes := false; declExported := false; inExtern := false;
210+ inTypes := false; declExported := false; inExtern := false; making := false;
198211 end;
199212
200213 { Gives up the construct r is for, and the one around it }
@@ -290,22 +303,29 @@
290303 else if (NameOf(n) = 'elif') or (NameOf(n) = 'elseif') then Help('raz writes elsif')
291304 else DidYouMean(Closest(n, -1));
292305 end;
306+
307+procedure FirstUse(o: PObj; const at: TPos); forward;
308+procedure InstancesFor(wholeRest: boolean); forward;
309+procedure AddImport(m, im: PModule); forward;
293310
294311 function QualIdent: PObj;
295-var o: PObj; m: PModule;
312+var o: PObj; m: PModule; at: TPos;
296313 begin
297314 if tok <> sIdent then Expected('a name');
315+ at := TokPos;
298316 o := Lookup(id);
299317 if o = nil then begin
300- Poison(id);
318+ if not making then Poison(id); { it may yet be declared }
301319 quiet := false;
302- NotDeclared(TokPos, id);
320+ NotDeclared(at, id);
321+ if making then Note(useAt, 'the instance is made here, where it is first used');
303322 Fail;
304323 end;
305324 if o^.typ = tPoison then quiet := true;
306325 Named(o);
307326 Next;
308327 if o^.cls = oModule then begin
328+ if o^.module = nil then FirstUse(o, at);
309329 Expect(sPeriod);
310330 if tok <> sIdent then Expected('a name');
311331 m := o^.module;
@@ -1643,6 +1663,7 @@
16431663 procedure ProcDecl;
16441664 var n, line: longint; exp: boolean; sig: PType; p: PObj; at: TPos;
16451665 begin
1666+ InstancesFor(false);
16461667 line := CurLine;
16471668 Next;
16481669 IdentDef(n, exp, at);
@@ -1932,6 +1953,19 @@
19321953 Expect(sRparen);
19331954 end;
19341955
1956+{ Past an instance's arguments, to be read when it is made }
1957+procedure SkipArgs;
1958+var p: longint;
1959+begin
1960+ p := 0;
1961+ repeat
1962+ if tok = sLparen then inc(p)
1963+ else if tok = sRparen then dec(p)
1964+ else if tok in [sSemicolon, sEof] then Expected('")"');
1965+ Next;
1966+ until p = 0;
1967+end;
1968+
19351969 { A generic module's parameters, bound to the instance's arguments: a
19361970 type parameter names its type, a procedure parameter its procedure. }
19371971 procedure Params(m: PModule);
@@ -2043,8 +2077,9 @@
20432077 function CompileFile(const path: shortstring; n: longint; const args: TArgs; checkOnly: boolean): PModule;
20442078 var
20452079 st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint;
2046- oldMod: PModule; oldCheck: boolean; m, im: PModule;
2047- imp: PImport; lib: PLib; start: TPos; alias, mname, line, oldPath: longint; o: PObj; body: longint; iargs: TArgs;
2080+ oldMod: PModule; oldCheck: boolean; m: PModule;
2081+ lib: PLib; start: TPos; alias, mname, line, oldPath: longint; o: PObj; body: longint; iargs: TArgs;
2082+ generic: boolean; argsAt: TScanState;
20482083 begin
20492084 SaveScan(st);
20502085 SaveScopes(d, saved);
@@ -2083,24 +2118,36 @@
20832118 alias := id;
20842119 mname := id;
20852120 iargs.n := 0;
2121+ generic := false;
20862122 Next;
20872123 if tok = sBecomes then begin
20882124 Next;
20892125 if tok <> sIdent then Expected('a module name');
20902126 mname := id;
20912127 Next;
2092- if tok = sLparen then ParseArgs(iargs, NameOf(mname));
2128+ if tok = sLparen then begin
2129+ generic := true;
2130+ SaveScan(argsAt);
2131+ SkipArgs;
2132+ end;
20932133 end;
20942134 iargs.at := SpanFrom(start);
2095- im := ImportModule(mname, iargs);
20962135 o := NewObj(oModule, alias, nil);
20972136 o^.pos := start;
2098- o^.module := im;
20992137 Declare(o);
2100- New(imp);
2101- imp^.module := im;
2102- imp^.next := m^.imports;
2103- m^.imports := imp;
2138+ if not generic then begin
2139+ o^.module := ImportModule(mname, iargs);
2140+ AddImport(m, o^.module);
2141+ end else begin
2142+ o^.module := nil; { until the instance is made, at its first use }
2143+ if numDeferred > High(deferred) then Mark('more than ' + IntStr(High(deferred) + 1) + ' generic imports');
2144+ deferred[numDeferred].o := o;
2145+ deferred[numDeferred].m := m;
2146+ deferred[numDeferred].mname := mname;
2147+ deferred[numDeferred].args := argsAt;
2148+ deferred[numDeferred].at := iargs.at;
2149+ inc(numDeferred);
2150+ end;
21042151 if tok <> sComma then break;
21052152 Next;
21062153 until false;
@@ -2123,6 +2170,7 @@
21232170 if tok = sBegin then begin
21242171 if checkMode then SkipBody
21252172 else begin
2173+ InstancesFor(true);
21262174 line := CurLine;
21272175 Next;
21282176 body := NewChunk(secText, m^.sname, nameBody);
@@ -2283,6 +2331,78 @@
22832331 m := CompileFile(dir + '/' + f, name, args, false);
22842332 CheckSiblings(dir, f, name, m, args);
22852333 ImportModule := m;
2334+end;
2335+
2336+procedure AddImport(m, im: PModule);
2337+var imp: PImport;
2338+begin
2339+ New(imp);
2340+ imp^.module := im;
2341+ imp^.next := m^.imports;
2342+ m^.imports := imp;
2343+end;
2344+
2345+{ Makes the instance that deferred[i] imports: its arguments are read
2346+ where the import wrote them, and must be declared by now. Compiling
2347+ the instance comes in the middle of a declaration, so what that
2348+ declaration has under way is kept aside meanwhile. }
2349+procedure MakeInstance(i: longint; const at: TPos);
2350+var
2351+ d: TDeferred; st: TScanState; args: TArgs; types, exported, ext, wasQuiet: boolean; nf, nd: longint;
2352+ ft: array[0..255] of PType; fp: array[0..255] of TPos; decl: array[0..63] of longint;
2353+begin
2354+ d := deferred[i];
2355+ dec(numDeferred);
2356+ deferred[i] := deferred[numDeferred];
2357+ SaveScan(st);
2358+ RestoreScan(d.args);
2359+ args.n := 0;
2360+ making := true; useAt := at;
2361+ ParseArgs(args, NameOf(d.mname));
2362+ making := false;
2363+ RestoreScan(st);
2364+ args.at := d.at;
2365+ types := inTypes; exported := declExported; ext := inExtern; wasQuiet := quiet;
2366+ nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring;
2367+ d.o^.module := ImportModule(d.mname, args);
2368+ inTypes := types; declExported := exported; inExtern := ext; quiet := wasQuiet;
2369+ numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl;
2370+ AddImport(curModule, d.o^.module);
2371+end;
2372+
2373+procedure FirstUse(o: PObj; const at: TPos);
2374+var i: longint;
2375+begin
2376+ for i := 0 to numDeferred - 1 do
2377+ if deferred[i].o = o then begin MakeInstance(i, at); exit end;
2378+ Fail; { its arguments had an error, already reported }
2379+end;
2380+
2381+{ An instance can't be compiled in the middle of another procedure's
2382+ code, so before a procedure's code begins, from its "proc" on, or
2383+ the module body's, from its "begin" to the end of the file, this
2384+ reads ahead for the names of imports not yet made, and makes those. }
2385+procedure InstancesFor(wholeRest: boolean);
2386+var st: TScanState; d, i: longint; begun: boolean;
2387+begin
2388+ if checkMode then exit;
2389+ i := numDeferred - 1;
2390+ while (i >= 0) and (deferred[i].m <> curModule) do dec(i);
2391+ if i < 0 then exit;
2392+ SaveScan(st);
2393+ d := 0; begun := false;
2394+ repeat
2395+ case tok of
2396+ sIdent: for i := numDeferred - 1 downto 0 do
2397+ if (deferred[i].m = curModule) and (deferred[i].o^.name = id) then MakeInstance(i, TokPos);
2398+ sBegin: begin begun := begun or (d = 0); inc(d) end;
2399+ sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: inc(d);
2400+ sEnd, sUntil: dec(d);
2401+ end;
2402+ if not wholeRest and (d = 0) and (begun or (tok in [sForward, sCode])) then break;
2403+ Next;
2404+ until tok = sEof;
2405+ RestoreScan(st);
22862406 end;
22872407
22882408 function CompileMain(const path: shortstring): PModule;

test/err/BadProc.raz modified +3 -0

@@ -1,3 +1,6 @@
11 module BadProc;
22 import Str, M := Map([]U8, I64, Str.cmp, Str.eq);
3+
4+var m: M.Map;
5+
36 end BadProc.

test/err/FirstUseLate.err added +7 -0

@@ -0,0 +1,7 @@
1+test/err/FirstUseLate.raz:2:18: error: Later isn't declared
2+ 2 | import L := List(Later);
3+ | ^^^^^
4+test/err/FirstUseLate.raz:4:8: note: the instance is made here, where it is first used
5+ 4 | var l: L.List; (* made here, before Later is declared *)
6+ | ^
7+raz: 1 error

test/err/FirstUseLate.raz added +8 -0

@@ -0,0 +1,8 @@
1+module FirstUseLate;
2+import L := List(Later);
3+
4+var l: L.List; (* made here, before Later is declared *)
5+
6+type Later = I64;
7+
8+end FirstUseLate.

test/err/NotGeneric.raz modified +6 -0

@@ -1,3 +1,9 @@
11 module NotGeneric;
22 import S := Str(I64);
3+
4+proc f(a, b: []U8): I64;
5+begin
6+ return S.cmp(a, b);
7+end;
8+
39 end NotGeneric.

test/err/StmtArgKind.raz modified +3 -0

@@ -1,3 +1,6 @@
11 module StmtArgKind;
22 import Mem, L := List(Mem.Page);
3+
4+var l: L.List;
5+
36 end StmtArgKind.

test/err/StmtManyTypeArgs.raz modified +3 -0

@@ -1,3 +1,6 @@
11 module StmtManyTypeArgs;
22 import L := List(I64, I64);
3+
4+var l: L.List;
5+
36 end StmtManyTypeArgs.

test/err/StmtNeedProc.raz modified +3 -0

@@ -1,3 +1,6 @@
11 module StmtNeedProc;
22 import Str, M := Map([]U8, I64, I64, Str.eq);
3+
4+var m: M.Map;
5+
36 end StmtNeedProc.

test/err/StmtNeedType.raz modified +3 -0

@@ -1,3 +1,6 @@
11 module StmtNeedType;
22 import Str, M := Map(Str.cmp, I64, Str.cmp, Str.eq);
3+
4+var m: M.Map;
5+
36 end StmtNeedType.

test/err/StmtParamName.raz modified +3 -0

@@ -1,3 +1,6 @@
11 module StmtParamName;
22 import L := StmtParam(I64);
3+
4+var l: L.T;
5+
36 end StmtParamName.

test/run/FirstUse.expect added +6 -0

@@ -0,0 +1,6 @@
1+an instance of Loud, of size 1
2+an empty list
3+in main, Ones has size 1
4+sky not red
5+rose red
6+grass -

test/run/FirstUse.raz added +34 -0

@@ -0,0 +1,34 @@
1+module FirstUse;
2+import Out, Str, Heap, Table := Map([]U8, Colour, Str.hash, Str.eq),
3+ Ints := List(I64), More := List(I64), Never := Loud(I64), Ones := Loud(U8);
4+
5+type Colour = (red, green, blue);
6+
7+var names: Table.Map; (* Table is made here, after Colour *)
8+
9+proc show(k: []U8);
10+var c: Colour; found: BOOL;
11+begin
12+ c, found := Table.get(ADR(names), k);
13+ Out.str(k);
14+ if not found then Out.str(" -"); elsif c = red then Out.str(" red"); else Out.str(" not red"); end;
15+ Out.ln;
16+end;
17+
18+(* Ones is first used in a procedure, and made before its code *)
19+proc main*;
20+var a: Ints.List; b: More.List;
21+begin
22+ a := b; (* two imports, one instance *)
23+ if a.head = nil then Out.str("an empty list\n"); end;
24+ Out.str("in main, Ones has size "); Out.int(Ones.size); Out.ln;
25+ show("sky");
26+ show("rose");
27+ show("grass");
28+end;
29+
30+begin
31+ Table.init(ADR(names), Heap.heap);
32+ Table.put(ADR(names), "rose", red);
33+ Table.put(ADR(names), "sky", blue);
34+end FirstUse.

test/run/mods/Loud.raz added +10 -0

@@ -0,0 +1,10 @@
1+(* A generic module with a body, which runs once for each instance *)
2+module Loud(T);
3+import Out;
4+
5+var size*: I64;
6+
7+begin
8+ size := SIZE(T);
9+ Out.str("an instance of Loud, of size "); Out.int(size); Out.ln;
10+end Loud.