raz / commit 82a614f3

commit
82a614f3a1cb9f1db197ef4e84364c827aa21962
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
8c6df0ee
Step 10: generic modules; Str, Buf, Fmt, List, Map

A generic module is compiled once per distinct list of arguments,
from its source, with each type parameter naming its argument and
each procedure parameter its procedure, whose signature must match.
Two imports with the same arguments share the instance; its symbols
are named after it, List(I64).push. A string constant can be indexed
and sliced.

lib: Str (cmp, eq, hash, find, hasPrefix), Buf (a growable buffer),
Fmt (print and write with {} and a slice of Arg), List(T) and
Map(K, V; hash, eq). examples/Words.jed counts words with them. make
bench takes the best of three runs, since one is noisy.

patch · log

25 files changed, +602 -33

Makefile (history) modified +9 -6

@@ -27,14 +27,17 @@
2727 check: jed
2828 test/check.sh
2929
30-# the compiler's speed, on a generated program of about 350,000 lines;
31-# fails below 400,000 lines a second
30+# the compiler's speed, on a generated program of about 350,000 lines,
31+# the best of three runs; fails below 400,000 lines a second
3232 bench: jed | build
3333 python3 test/genbench.py 12000 > build/Bench.jed
34- @lines=$$(wc -l < build/Bench.jed); \
35- start=$$(date +%s%N); ./jed build/Bench.jed || exit 1; end=$$(date +%s%N); \
36- rate=$$((lines * 1000000000 / (end - start))); \
37- echo "$$lines lines in $$(((end - start) / 1000000)) ms: $$rate lines a second"; \
34+ @lines=$$(wc -l < build/Bench.jed); best=0; \
35+ for i in 1 2 3; do \
36+ start=$$(date +%s%N); ./jed build/Bench.jed || exit 1; end=$$(date +%s%N); \
37+ t=$$((end - start)); if [ $$best = 0 ] || [ $$t -lt $$best ]; then best=$$t; fi; \
38+ done; \
39+ rate=$$((lines * 1000000000 / best)); \
40+ echo "$$lines lines in $$((best / 1000000)) ms: $$rate lines a second"; \
3841 test $$rate -ge 400000
3942
4043 # lines of the compiler: all of them, and those that aren't blank or comments

PLAN.md (history) modified +1 -1

@@ -95,7 +95,7 @@
9595 - [x] 7. Multiple results and errors; `INC` and `DEC`.
9696 - [x] 8. Enumerations and sets, record literals, `defer`; examples.
9797 - [x] 9. `NEW`; `lib/Mem.jed`, `lib/Arena.jed`, `lib/Heap.jed`.
98-- [ ] 10. Generic modules, with type and procedure arguments;
98+- [x] 10. Generic modules, with type and procedure arguments;
9999 `lib/Str.jed`, `lib/Buf.jed`, `lib/Fmt.jed`; examples.
100100
101101 Stage 3: calling C

doc/jed.md modified +2 -1

@@ -759,8 +759,9 @@
759759 | `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator |
760760 | `Str` | operations on `[]U8` strings |
761761 | `Buf` | a growable byte buffer |
762-| `Fmt` | formatted output: `Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)])` |
762+| `Fmt` | formatted output: `Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)])`, or into a `Buf` with `Fmt.write` |
763763 | `List` | a generic singly linked list, `List(T)` |
764+| `Map` | a generic hash map, `Map(K, V; hash, eq)` |
764765
765766 ```
766767 module Mem;

examples/Words added (executable)

Binary file; the patch has it.

examples/Words.expect (history) added +6 -0

@@ -0,0 +1,6 @@
1+the 3
2+cat 1
3+and 2
4+hat 1
5+bat 1
6+8 words, 5 different

examples/Words.jed added +37 -0

@@ -0,0 +1,37 @@
1+(* Generic modules: counts the words of a text in a Map from []U8 to
2+ I64, hashed and compared by Str's procedures, keeps them in order of
3+ first sight in a List([]U8), and prints them with Fmt. *)
4+module Words;
5+import Fmt, Str, Heap, Count := Map([]U8, I64, Str.hash, Str.eq), Names := List([]U8);
6+
7+const Text = "the cat and the hat and the bat";
8+
9+proc main*;
10+var
11+ counts: Count.Map; order: Names.List; n: ^Names.Node;
12+ i, start, k, total: I64; found, ok: BOOL; w: []U8;
13+begin
14+ Count.init(ADR(counts), Heap.heap);
15+ Names.init(ADR(order), Heap.heap);
16+ start := 0;
17+ for i := 0 to LEN(Text) do
18+ if (i = LEN(Text)) or (Text[i] = ' ') then
19+ w := Text[start..i];
20+ INC(total);
21+ k, found := Count.get(ADR(counts), w);
22+ if not found then ok := Names.push(ADR(order), w); end;
23+ ok := Count.put(ADR(counts), w, k + 1);
24+ start := i + 1;
25+ end;
26+ end;
27+ Names.reverse(ADR(order));
28+ n := order.head;
29+ while n # nil do
30+ k, found := Count.get(ADR(counts), n^.val);
31+ Fmt.print("{} {}\n", [Fmt.str(n^.val), Fmt.int(k)]);
32+ n := n^.next;
33+ end;
34+ Fmt.print("{} words, {} different\n", [Fmt.int(total), Fmt.int(counts.len)]);
35+end;
36+
37+end Words.

lib/Buf.jed added +71 -0

@@ -0,0 +1,71 @@
1+(* A growable byte buffer, its memory from an allocator. *)
2+module Buf;
3+import Mem;
4+
5+type
6+ Buf* = record
7+ a: ^Mem.Allocator;
8+ data: ^U8;
9+ len*, cap: I64;
10+ end;
11+
12+proc init*(b: ^Buf; a: ^Mem.Allocator);
13+begin
14+ b^ := {a: a};
15+end;
16+
17+(* Room for n more bytes; false if the allocator has none. *)
18+proc room*(b: ^Buf; n: I64): BOOL;
19+var cap, i: I64; p: ^U8;
20+begin
21+ if b^.len + n <= b^.cap then return true; end;
22+ cap := b^.cap * 2;
23+ if cap < 64 then cap := 64; end;
24+ while cap < b^.len + n do cap := cap * 2; end;
25+ p := Mem.alloc(b^.a, cap, 1);
26+ if p = nil then return false; end;
27+ for i := 0 to b^.len - 1 do p[i] := b^.data[i]; end;
28+ if b^.data # nil then Mem.free(b^.a, b^.data); end;
29+ b^.data := p;
30+ b^.cap := cap;
31+ return true;
32+end;
33+
34+proc add*(b: ^Buf; c: U8);
35+begin
36+ if room(b, 1) then
37+ b^.data[b^.len] := c;
38+ INC(b^.len);
39+ end;
40+end;
41+
42+proc str*(b: ^Buf; s: []U8);
43+var i: I64;
44+begin
45+ if room(b, LEN(s)) then
46+ for i := 0 to LEN(s) - 1 do b^.data[b^.len + i] := s[i]; end;
47+ INC(b^.len, LEN(s));
48+ end;
49+end;
50+
51+(* What the buffer holds, until it next grows. *)
52+proc bytes*(b: ^Buf): []U8;
53+begin
54+ if b^.len = 0 then return ""; end;
55+ return b^.data[0..b^.len];
56+end;
57+
58+proc reset*(b: ^Buf);
59+begin
60+ b^.len := 0;
61+end;
62+
63+proc done*(b: ^Buf);
64+begin
65+ if b^.data # nil then Mem.free(b^.a, b^.data); end;
66+ b^.data := nil;
67+ b^.len := 0;
68+ b^.cap := 0;
69+end;
70+
71+end Buf.

lib/Fmt.jed added +90 -0

@@ -0,0 +1,90 @@
1+(* Formatted output. Each {} in the format takes the next argument:
2+ Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]);
3+ {{ and }} stand for { and }. print writes to standard output,
4+ write appends to a Buf. *)
5+module Fmt;
6+import Out, Buf;
7+
8+type
9+ Arg* = variant
10+ int(i: I64);
11+ uint(u: U64);
12+ hex(h: U64);
13+ str(s: []U8);
14+ char(c: U8);
15+ bool(b: BOOL);
16+ end;
17+
18+(* The digits of u in base, at the end of the array: it and where they start. *)
19+proc digits(u: U64; base: U64): ([24]U8, I64);
20+var d: [24]U8; i: I64; v: U8;
21+begin
22+ i := 24;
23+ repeat
24+ DEC(i);
25+ v := U8(u mod base);
26+ if v < 10 then d[i] := v + '0'; else d[i] := v - 10 + 'A'; end;
27+ u := u div base;
28+ until u = 0;
29+ return d, i;
30+end;
31+
32+(* Where the pieces go: to b, or to standard output if b is nil. *)
33+proc put(b: ^Buf.Buf; s: []U8);
34+begin
35+ if b = nil then Out.str(s); else Buf.str(b, s); end;
36+end;
37+
38+proc arg(b: ^Buf.Buf; a: Arg);
39+var d: [24]U8; at: I64; one: [1]U8;
40+begin
41+ match a of
42+ | int(i):
43+ if i < 0 then
44+ put(b, "-");
45+ d, at := digits(0 - U64(i), 10);
46+ else
47+ d, at := digits(U64(i), 10);
48+ end;
49+ put(b, d[at..24]);
50+ | uint(u): d, at := digits(u, 10); put(b, d[at..24]);
51+ | hex(h): d, at := digits(h, 16); put(b, d[at..24]);
52+ | str(s): put(b, s);
53+ | char(c): one[0] := c; put(b, one);
54+ | bool(t): if t then put(b, "true"); else put(b, "false"); end;
55+ end;
56+end;
57+
58+proc format(b: ^Buf.Buf; f: []U8; args: []Arg);
59+var i, start, n: I64;
60+begin
61+ i := 0; start := 0; n := 0;
62+ while i < LEN(f) do
63+ if (f[i] = '{') or (f[i] = '}') then
64+ put(b, f[start..i]);
65+ if (i + 1 < LEN(f)) and (f[i + 1] = f[i]) then
66+ put(b, f[i..i + 1]);
67+ INC(i);
68+ elsif (f[i] = '{') and (i + 1 < LEN(f)) and (f[i + 1] = '}') then
69+ if n < LEN(args) then arg(b, args[n]); end;
70+ INC(n);
71+ INC(i);
72+ end;
73+ start := i + 1;
74+ end;
75+ INC(i);
76+ end;
77+ put(b, f[start..LEN(f)]);
78+end;
79+
80+proc print*(f: []U8; args: []Arg);
81+begin
82+ format(nil, f, args);
83+end;
84+
85+proc write*(b: ^Buf.Buf; f: []U8; args: []Arg);
86+begin
87+ format(b, f, args);
88+end;
89+
90+end Fmt.

lib/List.jed added +68 -0

@@ -0,0 +1,68 @@
1+(* A singly linked list of T, its nodes from an allocator. *)
2+module List(T);
3+import Mem;
4+
5+type
6+ Node* = record
7+ next*: ^Node;
8+ val*: T;
9+ end;
10+ List* = record
11+ head*: ^Node;
12+ len*: I64;
13+ a: ^Mem.Allocator;
14+ end;
15+
16+proc init*(l: ^List; a: ^Mem.Allocator);
17+begin
18+ l^ := {a: a};
19+end;
20+
21+(* v at the front; false if the allocator has no room. *)
22+proc push*(l: ^List; v: T): BOOL;
23+var n: ^Node;
24+begin
25+ NEW(n, l^.a);
26+ if n = nil then return false; end;
27+ n^.val := v;
28+ n^.next := l^.head;
29+ l^.head := n;
30+ INC(l^.len);
31+ return true;
32+end;
33+
34+(* The front value, taken off; false if the list is empty. *)
35+proc pop*(l: ^List): (T, BOOL);
36+var n: ^Node; v: T;
37+begin
38+ n := l^.head;
39+ if n = nil then return v, false; end;
40+ v := n^.val;
41+ l^.head := n^.next;
42+ DEC(l^.len);
43+ Mem.free(l^.a, ^U8(n));
44+ return v, true;
45+end;
46+
47+(* The list backwards. *)
48+proc reverse*(l: ^List);
49+var p, q, next: ^Node;
50+begin
51+ p := l^.head;
52+ q := nil;
53+ while p # nil do
54+ next := p^.next;
55+ p^.next := q;
56+ q := p;
57+ p := next;
58+ end;
59+ l^.head := q;
60+end;
61+
62+proc clear*(l: ^List);
63+var ok: BOOL; v: T;
64+begin
65+ while l^.head # nil do v, ok := pop(l); end;
66+end;
67+
68+end List.

lib/Map.jed added +81 -0

@@ -0,0 +1,81 @@
1+(* A hash map from K to V, by open addressing; it hashes and compares
2+ keys with the procedures it is given:
3+ import Count := Map([]U8, I64, Str.hash, Str.eq); *)
4+module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
5+import Mem;
6+
7+type
8+ Entry = record
9+ key: K;
10+ val: V;
11+ used: BOOL;
12+ end;
13+ Map* = record
14+ a: ^Mem.Allocator;
15+ slots: ^Entry;
16+ cap: I64; (* a power of two, or 0 *)
17+ len*: I64;
18+ end;
19+
20+proc init*(m: ^Map; a: ^Mem.Allocator);
21+begin
22+ m^ := {a: a};
23+end;
24+
25+(* The slot of k, or of the empty slot where it would go. *)
26+proc slot(m: ^Map; k: K): I64;
27+var i: I64;
28+begin
29+ i := I64(hash(k) and U64(m^.cap - 1));
30+ while m^.slots[i].used and not eq(m^.slots[i].key, k) do
31+ i := (i + 1) and (m^.cap - 1);
32+ end;
33+ return i;
34+end;
35+
36+proc grow(m: ^Map): BOOL;
37+var old: ^Entry; n, i, j: I64;
38+begin
39+ old := m^.slots;
40+ n := m^.cap;
41+ if n = 0 then m^.cap := 16; else m^.cap := n * 2; end;
42+ m^.slots := ^Entry(Mem.alloc(m^.a, m^.cap * SIZE(Entry), 8));
43+ if m^.slots = nil then m^.slots := old; m^.cap := n; return false; end;
44+ for i := 0 to m^.cap - 1 do m^.slots[i].used := false; end;
45+ for i := 0 to n - 1 do
46+ if old[i].used then
47+ j := slot(m, old[i].key);
48+ m^.slots[j] := old[i];
49+ end;
50+ end;
51+ if old # nil then Mem.free(m^.a, ^U8(old)); end;
52+ return true;
53+end;
54+
55+(* k now maps to v; false if there was no room. *)
56+proc put*(m: ^Map; k: K; v: V): BOOL;
57+var i: I64;
58+begin
59+ if (m^.len + 1) * 4 > m^.cap * 3 then
60+ if not grow(m) then return false; end;
61+ end;
62+ i := slot(m, k);
63+ if not m^.slots[i].used then
64+ m^.slots[i] := {key: k, used: true};
65+ INC(m^.len);
66+ end;
67+ m^.slots[i].val := v;
68+ return true;
69+end;
70+
71+(* What k maps to, and whether it maps to anything. *)
72+proc get*(m: ^Map; k: K): (V, BOOL);
73+var i: I64; none: V;
74+begin
75+ if m^.cap = 0 then return none, false; end;
76+ i := slot(m, k);
77+ if not m^.slots[i].used then return none, false; end;
78+ return m^.slots[i].val, true;
79+end;
80+
81+end Map.

lib/Str.jed added +53 -0

@@ -0,0 +1,53 @@
1+(* Operations on strings, which are []U8. = and # compare them; this
2+ module orders, searches and hashes them. *)
3+module Str;
4+
5+(* -1, 0 or 1 as a sorts before, with or after b, byte by byte. *)
6+proc cmp*(a, b: []U8): I64;
7+var i, n: I64;
8+begin
9+ n := LEN(a);
10+ if LEN(b) < n then n := LEN(b); end;
11+ for i := 0 to n - 1 do
12+ if a[i] # b[i] then
13+ if a[i] < b[i] then return -1; end;
14+ return 1;
15+ end;
16+ end;
17+ if LEN(a) < LEN(b) then return -1; end;
18+ if LEN(a) > LEN(b) then return 1; end;
19+ return 0;
20+end;
21+
22+proc eq*(a, b: []U8): BOOL;
23+begin
24+ return a = b;
25+end;
26+
27+(* FNV-1a, 64 bits. *)
28+proc hash*(s: []U8): U64;
29+var h: U64; i: I64;
30+begin
31+ h := 0CBF29CE484222325H;
32+ for i := 0 to LEN(s) - 1 do
33+ h := (h xor U64(s[i])) * 100000001B3H;
34+ end;
35+ return h;
36+end;
37+
38+(* Where sub first starts in s, or -1. *)
39+proc find*(s, sub: []U8): I64;
40+var i: I64;
41+begin
42+ for i := 0 to LEN(s) - LEN(sub) do
43+ if s[i..i + LEN(sub)] = sub then return i; end;
44+ end;
45+ return -1;
46+end;
47+
48+proc hasPrefix*(s, p: []U8): BOOL;
49+begin
50+ return (LEN(s) >= LEN(p)) and (s[0..LEN(p)] = p);
51+end;
52+
53+end Str.

src/gen.pas modified +1 -0

@@ -496,6 +496,7 @@
496496
497497 procedure IndexPrep(var x: TItem);
498498 begin
499+ if x.mode = mStr then Coerce(x, tBytes);
499500 if (x.typ^.form = fPtr) and (x.typ^.base^.form = fArray) then
500501 Mark('a pointer to an array is indexed as p^[i]');
501502 if x.typ^.form = fPtr then begin

src/parse.pas modified +101 -23

@@ -35,7 +35,7 @@
3535 firstModule, lastModule: PModule; { in the order they were finished }
3636
3737 function CompileMain(const path: shortstring): PModule;
38-function ImportModule(name: longint): PModule;
38+function ImportModule(name: longint; const args: TArgs): PModule;
3939
4040 implementation
4141
@@ -1322,7 +1322,7 @@
13221322 p^.exported := exp;
13231323 if (curModule^.name = nameRt) and not checkMode and (n = nameFail) then p^.chunk := rtFail
13241324 else if (curModule^.name = nameRt) and not checkMode and (n = nameEq) then p^.chunk := rtEq
1325- else p^.chunk := NewChunk(secText, curModule^.name, n);
1325+ else p^.chunk := NewChunk(secText, curModule^.sname, n);
13261326 Declare(p);
13271327 end;
13281328 if tok = sForward then begin
@@ -1367,7 +1367,7 @@
13671367 o^.exported := exp and top;
13681368 if t = tError then begin
13691369 o^.typ := tError;
1370- o^.val := ErrorChunk(x, curModule^.name, n) + 1;
1370+ o^.val := ErrorChunk(x, curModule^.sname, n) + 1;
13711371 end else if x.mode = mStr then begin o^.val := x.val; o^.chunk := x.chunk end
13721372 else o^.val := ConstValue(x);
13731373 Declare(o);
@@ -1419,7 +1419,7 @@
14191419 o^.isVar := false;
14201420 if top then begin
14211421 o^.lev := 0;
1422- o^.chunk := NewChunk(secBss, curModule^.name, names[i]);
1422+ o^.chunk := NewChunk(secBss, curModule^.sname, names[i]);
14231423 SetBss(o^.chunk, t^.size, t^.align);
14241424 end else begin
14251425 o^.lev := 1;
@@ -1443,14 +1443,87 @@
14431443
14441444 { Modules }
14451445
1446-function FindModule(n: longint): PModule;
1446+{ Whether m is module n with these arguments. }
1447+function IsModule(m: PModule; n: longint; const args: TArgs): boolean;
1448+var i: longint;
1449+begin
1450+ IsModule := false;
1451+ if (m^.name <> n) or (m^.args.n <> args.n) then exit;
1452+ for i := 0 to args.n - 1 do
1453+ if (m^.args.o[i] <> args.o[i]) or not Same(m^.args.t[i], args.t[i]) then exit;
1454+ IsModule := true;
1455+end;
1456+
1457+function FindModule(n: longint; const args: TArgs): PModule;
14471458 var m: PModule;
14481459 begin
14491460 m := firstModule;
1450- while (m <> nil) and (m^.name <> n) do m := m^.next;
1461+ while (m <> nil) and not IsModule(m, n, args) do m := m^.next;
14511462 FindModule := m;
14521463 end;
14531464
1465+{ The arguments of an instance: types, or procedures named. }
1466+procedure ParseArgs(var args: TArgs);
1467+var o: PObj;
1468+begin
1469+ Next;
1470+ repeat
1471+ if args.n > High(args.t) then Mark('too many arguments');
1472+ args.o[args.n] := nil;
1473+ if tok = sIdent then begin
1474+ o := QualIdent;
1475+ if o^.cls = oProc then args.o[args.n] := o
1476+ else if o^.cls <> oType then Mark('a type or a procedure expected');
1477+ args.t[args.n] := o^.typ;
1478+ end else args.t[args.n] := ParseType;
1479+ inc(args.n);
1480+ if tok <> sComma then break;
1481+ Next;
1482+ until false;
1483+ Expect(sRparen, ')');
1484+end;
1485+
1486+{ A generic module's parameters, bound to the instance's arguments: a
1487+ type parameter names its type, a procedure parameter its procedure. }
1488+procedure Params(m: PModule);
1489+var i: longint; o, a: PObj; sig: PType; s: shortstring;
1490+begin
1491+ i := 0;
1492+ s := NameOf(m^.name) + '(';
1493+ Next;
1494+ repeat
1495+ if (tok <> sIdent) or (i >= m^.args.n) or (m^.args.o[i] <> nil) then
1496+ Mark('needs a type for each type parameter');
1497+ Declare(NewObj(oType, id, m^.args.t[i]));
1498+ s := s + TypeName(m^.args.t[i]) + ',';
1499+ inc(i);
1500+ Next;
1501+ if tok <> sComma then break;
1502+ Next;
1503+ until false;
1504+ while tok = sSemicolon do begin
1505+ Next;
1506+ if tok <> sIdent then Mark('name expected');
1507+ o := NewObj(oProc, id, nil);
1508+ Next;
1509+ Expect(sColon, ':');
1510+ Expect(sProc, 'proc');
1511+ sig := Signature;
1512+ if i >= m^.args.n then Mark('needs a procedure for ' + NameOf(o^.name));
1513+ a := m^.args.o[i];
1514+ if (a = nil) or not Same(a^.typ, sig) then
1515+ Mark('needs a procedure with the signature of ' + NameOf(o^.name));
1516+ o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode;
1517+ Declare(o);
1518+ s := s + NameOf(a^.module^.name) + '.' + NameOf(a^.name) + ',';
1519+ inc(i);
1520+ end;
1521+ Expect(sRparen, ')');
1522+ if i <> m^.args.n then Mark('too many arguments');
1523+ s[length(s)] := ')';
1524+ m^.sname := Name(s);
1525+end;
1526+
14541527 { Modules being compiled, not yet finished: for finding a cycle. }
14551528 var
14561529 pending: array[0..63] of PModule;
@@ -1463,11 +1536,11 @@
14631536 Exists := (FpStat(@p[1], st) = 0) and ((st.st_mode and S_IFMT) = S_IFREG);
14641537 end;
14651538
1466-function CompileFile(const path: shortstring; n: longint; checkOnly: boolean): PModule;
1539+function CompileFile(const path: shortstring; n: longint; const args: TArgs; checkOnly: boolean): PModule;
14671540 var
14681541 st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint;
14691542 oldMod: PModule; oldFile: longint; oldCheck: boolean; m, im: PModule;
1470- imp: PImport; alias, mname: longint; o: PObj; body: longint;
1543+ imp: PImport; alias, mname: longint; o: PObj; body: longint; iargs: TArgs;
14711544 begin
14721545 SaveScan(st);
14731546 SaveScopes(d, saved);
@@ -1476,6 +1549,8 @@
14761549 New(m);
14771550 FillChar(m^, SizeOf(TModule), 0);
14781551 m^.name := n;
1552+ m^.sname := n;
1553+ m^.args := args;
14791554 m^.scope := NewScope;
14801555 m^.path := path;
14811556 m^.body := -1;
@@ -1493,7 +1568,8 @@
14931568 Expect(sModule, 'module');
14941569 if (tok <> sIdent) or (id <> n) then Mark('this file must hold module ' + NameOf(n));
14951570 Next;
1496- if tok = sLparen then Mark('generic modules come in stage 2');
1571+ if tok = sLparen then Params(m)
1572+ else if args.n > 0 then Mark(NameOf(n) + ' isn''t generic');
14971573 Expect(sSemicolon, ';');
14981574 while tok = sImport do begin
14991575 Next;
@@ -1501,15 +1577,16 @@
15011577 if tok <> sIdent then Mark('module name expected');
15021578 alias := id;
15031579 mname := id;
1580+ iargs.n := 0;
15041581 Next;
15051582 if tok = sBecomes then begin
15061583 Next;
15071584 if tok <> sIdent then Mark('module name expected');
15081585 mname := id;
15091586 Next;
1510- if tok = sLparen then Mark('generic modules come in stage 2');
1587+ if tok = sLparen then ParseArgs(iargs);
15111588 end;
1512- im := ImportModule(mname);
1589+ im := ImportModule(mname, iargs);
15131590 o := NewObj(oModule, alias, nil);
15141591 o^.module := im;
15151592 Declare(o);
@@ -1528,7 +1605,7 @@
15281605 if checkMode then SkipBody
15291606 else begin
15301607 Next;
1531- body := NewChunk(secText, n, nameBody);
1608+ body := NewChunk(secText, m^.sname, nameBody);
15321609 m^.body := body;
15331610 BeginProc(tBodySig, nil);
15341611 deferSlot := 0;
@@ -1584,7 +1661,7 @@
15841661
15851662 { Reads every other file of module n in dir, and checks its interface
15861663 against m, compiled from the file named chosen. }
1587-procedure CheckSiblings(const dir, chosen: shortstring; n: longint; m: PModule);
1664+procedure CheckSiblings(const dir, chosen: shortstring; n: longint; m: PModule; const args: TArgs);
15881665 var
15891666 dp: pDir; e: pDirent; f, prefix: shortstring; i: longint;
15901667 others: array[0..31] of shortstring; numOthers: longint;
@@ -1611,17 +1688,17 @@
16111688 until false;
16121689 FpCloseDir(dp^);
16131690 for i := 0 to numOthers - 1 do
1614- CompareIface(m, CompileFile(dir + '/' + others[i], n, true));
1691+ CompareIface(m, CompileFile(dir + '/' + others[i], n, args, true));
16151692 end;
16161693
1617-function ImportModule(name: longint): PModule;
1694+function ImportModule(name: longint; const args: TArgs): PModule;
16181695 const Suffixes: array[0..3] of string[16] = ('.' + Target, '.' + TargetOS, '.' + TargetArch, '');
16191696 var m: PModule; i, j: longint; dir, f: shortstring;
16201697 begin
1621- m := FindModule(name);
1698+ m := FindModule(name, args);
16221699 if m <> nil then exit(m);
16231700 for i := 0 to numPending - 1 do
1624- if pending[i]^.name = name then Mark(NameOf(name) + ' imports itself');
1701+ if IsModule(pending[i], name, args) then Mark(NameOf(name) + ' imports itself');
16251702 for i := -1 to numInc do begin
16261703 if i = -1 then dir := mainDir
16271704 else if i = numInc then dir := libDir
@@ -1629,8 +1706,8 @@
16291706 for j := 0 to 3 do begin
16301707 f := NameOf(name) + Suffixes[j] + '.jed';
16311708 if Exists(dir + '/' + f) then begin
1632- m := CompileFile(dir + '/' + f, name, false);
1633- CheckSiblings(dir, f, name, m);
1709+ m := CompileFile(dir + '/' + f, name, args, false);
1710+ CheckSiblings(dir, f, name, m, args);
16341711 exit(m);
16351712 end;
16361713 end;
@@ -1640,8 +1717,9 @@
16401717 end;
16411718
16421719 function CompileMain(const path: shortstring): PModule;
1643-var base: shortstring; i, n: longint;
1720+var base: shortstring; i, n: longint; none: TArgs;
16441721 begin
1722+ none.n := 0;
16451723 i := length(path);
16461724 while (i > 0) and (path[i] <> '/') do dec(i);
16471725 if i = 0 then mainDir := '.' else mainDir := copy(path, 1, i - 1);
@@ -1650,9 +1728,9 @@
16501728 if i > 0 then base := copy(base, 1, i - 1);
16511729 if base = '' then Fatal('no module in ' + path);
16521730 n := Name(base);
1653- if n <> nameRt then ImportModule(nameRt);
1654- if FindModule(n) <> nil then CompileMain := FindModule(n)
1655- else CompileMain := CompileFile(path, n, false);
1731+ if n <> nameRt then ImportModule(nameRt, none);
1732+ if FindModule(n, none) <> nil then CompileMain := FindModule(n, none)
1733+ else CompileMain := CompileFile(path, n, none, false);
16561734 end;
16571735
16581736 initialization

src/sym.pas modified +12 -2

@@ -70,6 +70,14 @@
7070 link: PObj; { the next top-level declaration of its module }
7171 end;
7272
73+ { The arguments of a generic module's instance: a type, or a
74+ procedure (o) and its type. }
75+ TArgs = record
76+ n: longint;
77+ t: array[0..7] of PType;
78+ o: array[0..7] of PObj;
79+ end;
80+
7381 TImport = record
7482 module: PModule;
7583 next: PImport;
@@ -77,6 +85,8 @@
7785
7886 TModule = record
7987 name: longint;
88+ sname: longint; { the name of its symbols: List(I64) for an instance }
89+ args: TArgs;
8090 scope: longint;
8191 path: shortstring;
8292 first, last: PObj; { its top-level declarations, in order }
@@ -345,7 +355,7 @@
345355 if t = nil then exit('nothing');
346356 if t^.obj <> nil then begin
347357 if (t^.obj^.module <> nil) and (t^.obj^.module <> curModule) then
348- exit(NameOf(t^.obj^.module^.name) + '.' + NameOf(t^.obj^.name));
358+ exit(NameOf(t^.obj^.module^.sname) + '.' + NameOf(t^.obj^.name));
349359 exit(NameOf(t^.obj^.name));
350360 end;
351361 case t^.form of
@@ -378,7 +388,7 @@
378388 if t = nil then begin Mix(h, -1); exit end;
379389 if (t^.obj <> nil) and not top then begin
380390 Mix(h, t^.obj^.name);
381- if t^.obj^.module <> nil then Mix(h, t^.obj^.module^.name);
391+ if t^.obj^.module <> nil then Mix(h, t^.obj^.module^.sname);
382392 exit;
383393 end;
384394 Mix(h, ord(t^.form));

test/err/BadProc.err added +1 -0

@@ -0,0 +1 @@
1+needs a procedure with the signature of hash

test/err/BadProc.jed added +3 -0

@@ -0,0 +1,3 @@
1+module BadProc;
2+import Str, M := Map([]U8, I64, Str.cmp, Str.eq);
3+end BadProc.

test/err/NoArgs.err added +1 -0

@@ -0,0 +1 @@
1+needs a type for each type parameter

test/err/NoArgs.jed added +3 -0

@@ -0,0 +1,3 @@
1+module NoArgs;
2+import List;
3+end NoArgs.

test/err/NotGeneric.err added +1 -0

@@ -0,0 +1 @@
1+Str isn't generic

test/err/NotGeneric.jed added +3 -0

@@ -0,0 +1,3 @@
1+module NotGeneric;
2+import S := Str(I64);
3+end NotGeneric.

test/err/TwoTypes.err added +1 -0

@@ -0,0 +1 @@
1+can't use List(I32).List as List(I64).List

test/err/TwoTypes.jed added +8 -0

@@ -0,0 +1,8 @@
1+module TwoTypes;
2+import A := List(I64), B := List(I32);
3+proc main*;
4+var a: A.List; b: B.List;
5+begin
6+ a := b;
7+end;
8+end TwoTypes.

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

@@ -0,0 +1,6 @@
1+8 2 true
2+8 1
3+abtrue
4+[] false
5+157 152 -1
6+{ BEEF } x18446744073709551615

test/run/Generic.jed added +30 -0

@@ -0,0 +1,30 @@
1+module Generic;
2+import Fmt, Buf, Str, Heap, Stack, Ints := List(I64), More := List(I64), Strs := List([]U8);
3+
4+proc twice(x: I64): I64; begin return x * 2; end;
5+
6+proc main*;
7+var l: Strs.List; v: I64; s: []U8; ok: BOOL; b: Buf.Buf; n: ^Ints.Node;
8+begin
9+ ok := Ints.push(ADR(Stack.s), 7);
10+ ok := More.push(ADR(Stack.s), 8);
11+ Fmt.print("{} {} {}\n", [Fmt.int(Stack.top()), Fmt.int(Stack.s.len), Fmt.bool(ok)]);
12+ n := Stack.s.head;
13+ v, ok := Ints.pop(ADR(Stack.s));
14+ Fmt.print("{} {}\n", [Fmt.int(v), Fmt.int(Stack.s.len)]);
15+ Strs.init(ADR(l), Heap.heap);
16+ ok := Strs.push(ADR(l), "b");
17+ ok := Strs.push(ADR(l), "a");
18+ s, ok := Strs.pop(ADR(l));
19+ Fmt.print("{}{}{}\n", [Fmt.str(s), Fmt.str(l.head^.val), Fmt.bool(ok)]);
20+ s, ok := Strs.pop(ADR(l));
21+ s, ok := Strs.pop(ADR(l));
22+ Fmt.print("[{}] {}\n", [Fmt.str(s), Fmt.bool(ok)]);
23+ Buf.init(ADR(b), Heap.heap);
24+ for v := 1 to 40 do Fmt.write(ADR(b), "{},", [Fmt.int(v * v)]); end;
25+ Fmt.print("{} {} {}\n", [Fmt.int(b.len), Fmt.int(Str.find(Buf.bytes(ADR(b)), "1600")), Fmt.int(Str.cmp("ab", "b"))]);
26+ Buf.done(ADR(b));
27+ Fmt.print("{{ {} }} {}{}\n", [Fmt.hex(48879), Fmt.char('x'), Fmt.uint(0FFFFFFFFFFFFFFFFH)]);
28+end;
29+
30+end Generic.

test/run/mods/Stack.jed added +13 -0

@@ -0,0 +1,13 @@
1+module Stack;
2+import Ints := List(I64), Heap;
3+
4+var s*: Ints.List;
5+
6+proc top*(): I64;
7+begin
8+ return s.head^.val;
9+end;
10+
11+begin
12+ Ints.init(ADR(s), Heap.heap);
13+end Stack.