raz / commit 03224cab

commit
03224cab4dd40daacaca3abd55dca46ecaeadbf2
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
39a17b57
Step 8: enumerations and sets, record literals, defer

An enumeration is a byte; its names are constants in the scope around
it, and it works with relations, for and match. A set is the smallest
word with a bit per name; + * - are or, and, and-not, <= and >= test
subsets, in tests a bit. Record and set literals take their type from
where they are used; a set literal of constants is a constant.

A deferred statement is compiled where it stands as a little
subroutine of the procedure, jumped over, and called at each way out
of its statement list: the end, return (after the result is computed
and kept) and break. Its temporaries stay reserved until it runs.

patch · log

21 files changed, +548 -48

PLAN.md (history) modified +1 -1

@@ -93,7 +93,7 @@
9393 Stage 2: the rest of the language
9494
9595 - [x] 7. Multiple results and errors; `INC` and `DEC`.
96-- [ ] 8. Enumerations and sets, record literals, `defer`; examples.
96+- [x] 8. Enumerations and sets, record literals, `defer`; examples.
9797 - [ ] 9. `NEW`; `lib/Mem.jed`, `lib/Arena.jed`, `lib/Heap.jed`.
9898 - [ ] 10. Generic modules, with type and procedure arguments;
9999 `lib/Str.jed`, `lib/Buf.jed`, `lib/Fmt.jed`; examples.

examples/Flags added (executable)

Binary file; the patch has it.

examples/Flags.expect (history) added +2 -0

@@ -0,0 +1,2 @@
1+[rwxr-xr-- octal 754]
2+[rw-r-x---]

examples/Flags.jed added +44 -0

@@ -0,0 +1,44 @@
1+(* Enumerations, sets, record literals and defer: Unix permissions as
2+ sets, which are their bits, and a report that closes its brackets
3+ however it leaves. *)
4+module Flags;
5+import Out;
6+
7+type
8+ Perm = (x, w, r); (* bits 0, 1, 2, as chmod has them *)
9+ Perms = set of Perm;
10+ Mode = record user, group, other: Perms; end;
11+
12+proc digit(p: Perms): I64;
13+begin
14+ return I64(U8(p));
15+end;
16+
17+proc show(p: Perms);
18+begin
19+ if r in p then Out.str("r"); else Out.str("-"); end;
20+ if w in p then Out.str("w"); else Out.str("-"); end;
21+ if x in p then Out.str("x"); else Out.str("-"); end;
22+end;
23+
24+proc report(m: Mode);
25+begin
26+ Out.str("[");
27+ defer Out.str("]\n");
28+ show(m.user); show(m.group); show(m.other);
29+ if m.other = {} then return; end;
30+ Out.str(" octal ");
31+ Out.int(digit(m.user)); Out.int(digit(m.group)); Out.int(digit(m.other));
32+end;
33+
34+proc main*;
35+var m: Mode;
36+begin
37+ m := {user: {r, w, x}, group: {r, x}, other: {r}};
38+ report(m);
39+ m.user := m.user - {x};
40+ m.other := {};
41+ report(m);
42+end;
43+
44+end Flags.

src/gen.pas modified +78 -13

@@ -92,10 +92,11 @@
9292 procedure PassArg(var c: TCall; var a: TItem);
9393 procedure EndCall(var c: TCall; var x: TItem);
9494
95+procedure ZeroTemp(var x: TItem; t: PType);
9596 procedure Construct(var x: TItem; c: PObj);
9697 procedure SetField(const x: TItem; f: PObj; var a: TItem);
9798 function MatchBegin(var x: TItem): int64;
98-procedure MatchTag(p: int64; tag: int64; var L: longint);
99+procedure MatchTag(p: int64; tag: int64; var L: longint; isEnum: boolean);
99100 procedure CondJump(var x: TItem; var L: longint);
100101
101102 procedure SliceOf(var x: TItem; t: PType; len: int64);
@@ -107,6 +108,7 @@
107108 function AllocPerm(size, align: int64): int64;
108109 function TempMark: int64;
109110 procedure ReleaseTemps(m: int64);
111+procedure KeepTemps;
110112
111113 procedure BeginProc(sig: PType; params: PObj);
112114 procedure EnterBody(c: longint);
@@ -341,6 +343,14 @@
341343 begin
342344 if m < permTop then m := permTop;
343345 frameTop := m;
346+end;
347+
348+{ Every slot used so far stays reserved for the rest of the procedure:
349+ a deferred statement's temporaries live until it runs. }
350+procedure KeepTemps;
351+begin
352+ frameTop := frameMax;
353+ permTop := frameMax;
344354 end;
345355
346356 procedure TempItem(var x: TItem; t: PType; off: int64);
@@ -715,7 +725,7 @@
715725 CcSigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccL, ccLE, ccG, ccGE);
716726 CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE);
717727 var
718- xt, yt, t: PType; r: TItem; scale, sh: longint; isPtr, unsign: boolean;
728+ xt, yt, t: PType; r: TItem; scale, sh: longint; isPtr, unsign: boolean; a, b: int64;
719729 begin
720730 xt := x.typ; yt := y.typ;
721731 if y.mode in [mType, mBuiltin, mNone, mCase] then Mark('not a value');
@@ -783,7 +793,15 @@
783793 if not ((xt^.form = fPtr) and (yt^.form = fPtr) and Same(xt^.base, yt^.base)) then
784794 Mark('different pointer types');
785795 t := tU64;
786- end else
796+ end else if (xt^.form = fEnum) and Same(xt, yt) then begin
797+ if not (op in Rel) then Mark('enumerations only compare');
798+ t := xt;
799+ end else if (xt^.form = fSet) and Same(xt, yt) then begin
800+ if not (op in [sPlus, sTimes, sMinus, sEql, sNeq, sLeq, sGeq]) then Mark('not a set operator');
801+ t := xt;
802+ end else if (op = sIn) and (yt^.form = fSet) and Same(xt, yt^.base) then
803+ t := yt
804+ else
787805 Mark('can''t combine ' + TypeName(xt) + ' and ' + TypeName(yt));
788806 unsign := (t^.form = fInt) and not t^.signed;
789807
@@ -792,6 +810,17 @@
792810 if t^.form = fReal then begin
793811 if not FoldReal(op, x, y, r) then Mark('not an F64 operator');
794812 x := r;
813+ end else if t^.form = fSet then begin
814+ a := x.val; b := y.val;
815+ case op of
816+ sPlus: MakeConst(x, t, a or b);
817+ sTimes: MakeConst(x, t, a and b);
818+ sMinus: MakeConst(x, t, a and not b);
819+ sIn: MakeConst(x, tBool, (b shr a) and 1);
820+ sLeq: MakeConst(x, tBool, ord(a and not b = 0));
821+ sGeq: MakeConst(x, tBool, ord(b and not a = 0));
822+ else MakeConst(x, tBool, ord((a = b) = (op = sEql)));
823+ end;
795824 end else if op in Rel then
796825 MakeConst(x, tBool, FoldInt(op, x.val, y.val, t))
797826 else
@@ -825,6 +854,24 @@
825854 sGeq: begin Ucomisd(0, 1); SetCC(ccAE, RAX) end;
826855 end;
827856 if not (op in Rel) then MovqRX(RAX, 0);
857+ end else if t^.form = fSet then begin
858+ case op of
859+ sPlus: Alu(aluOr, RAX, RCX);
860+ sTimes: Alu(aluAnd, RAX, RCX);
861+ sMinus: begin Unary(2, RCX); Alu(aluAnd, RAX, RCX) end;
862+ sLeq, sGeq: begin
863+ if op = sLeq then Unary(2, RCX) else Unary(2, RAX);
864+ Alu(aluAnd, RAX, RCX);
865+ TestRR(RAX, RAX);
866+ SetCC(ccE, RAX);
867+ end;
868+ sIn: begin
869+ MovRR(RDX, RCX); MovRR(RCX, RAX); MovRR(RAX, RDX);
870+ Shift(shShr, RAX);
871+ AluI(aluAnd, RAX, 1);
872+ end;
873+ else Alu(aluCmp, RAX, RCX); SetCC(CcUnsigned[op], RAX);
874+ end;
828875 end else if op in Rel then begin
829876 Alu(aluCmp, RAX, RCX);
830877 if (t^.form = fInt) and t^.signed or (t^.form = fConst) then SetCC(CcSigned[op], RAX)
@@ -857,7 +904,7 @@
857904 Norm(t);
858905 end;
859906 x.mode := mReg;
860- if op in Rel then x.typ := tBool else x.typ := t;
907+ if op in Rel + [sIn] then x.typ := tBool else x.typ := t;
861908 end;
862909
863910 procedure Convert(var x: TItem; t: PType);
@@ -866,9 +913,20 @@
866913 s := x.typ;
867914 if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then Mark('can''t convert this');
868915 if Same(s, t) then exit;
869- if IsInt(s) and (t^.form = fInt) then begin
916+ if (IsInt(s) or (s^.form in [fEnum, fSet])) and (t^.form = fInt) then begin
870917 if x.mode = mConst then x.val := Cut(x.val, t)
871918 else begin Value(x); Norm(t) end;
919+ end else if IsInt(s) and (t^.form = fEnum) then begin
920+ if x.mode = mConst then begin
921+ if (x.val < 0) or (x.val >= t^.len) then Mark('not a position of ' + TypeName(t))
922+ end else begin Value(x); CmpI(RAX, t^.len); Check(ccB) end;
923+ end else if IsInt(s) and (t^.form = fSet) then begin
924+ if x.mode = mConst then begin
925+ if t^.len < 64 then x.val := x.val and ((int64(1) shl t^.len) - 1)
926+ end else begin
927+ Value(x);
928+ if t^.len < 64 then begin MovRI(RCX, (int64(1) shl t^.len) - 1); Alu(aluAnd, RAX, RCX) end;
929+ end;
872930 end else if IsInt(s) and (t^.form = fReal) then begin
873931 if x.mode = mConst then begin
874932 if (s^.form = fInt) and not s^.signed then r := qword(x.val) else r := x.val;
@@ -1018,20 +1076,25 @@
10181076
10191077 { Variants }
10201078
1021-procedure Construct(var x: TItem; c: PObj);
1022-var t: PType; tmp: int64;
1079+{ A temporary of type t, all zero: for variants and record literals. }
1080+procedure ZeroTemp(var x: TItem; t: PType);
1081+var tmp: int64;
10231082 begin
1024- t := c^.typ;
10251083 tmp := AllocTemp(t^.size, t^.align);
10261084 Lea(RDI, Mem(RBP, tmp));
10271085 MovRI(RCX, t^.size);
10281086 MovRI(RAX, 0);
10291087 RepStosb;
1030- MovRI(RAX, c^.val);
1031- Store(Mem(RBP, tmp), RAX, 8);
10321088 TempItem(x, t, tmp);
10331089 end;
10341090
1091+procedure Construct(var x: TItem; c: PObj);
1092+begin
1093+ ZeroTemp(x, c^.typ);
1094+ MovRI(RAX, c^.val);
1095+ Store(Mem(RBP, x.off), RAX, 8);
1096+end;
1097+
10351098 procedure SetField(const x: TItem; f: PObj; var a: TItem);
10361099 begin
10371100 Coerce(a, f^.typ);
@@ -1046,20 +1109,22 @@
10461109 end;
10471110 end;
10481111
1112+{ The slot match tests: a variant's address, or an enumeration's value. }
10491113 function MatchBegin(var x: TItem): int64;
10501114 var p: int64;
10511115 begin
1052- if (x.mode <> mVar) or (x.typ^.form <> fVariant) then Mark('match needs a variant');
1116+ if x.typ^.form = fEnum then exit(ToSlot(x));
1117+ if (x.mode <> mVar) or (x.typ^.form <> fVariant) then Mark('match needs a variant or an enumeration');
10531118 Address(x, RAX);
10541119 p := AllocTemp(8, 8);
10551120 Store(Mem(RBP, p), RAX, 8);
10561121 MatchBegin := p;
10571122 end;
10581123
1059-procedure MatchTag(p: int64; tag: int64; var L: longint);
1124+procedure MatchTag(p: int64; tag: int64; var L: longint; isEnum: boolean);
10601125 begin
10611126 Load(RAX, Mem(RBP, p), 8, false);
1062- Load(RAX, Mem(RAX, 0), 8, false);
1127+ if not isEnum then Load(RAX, Mem(RAX, 0), 8, false);
10631128 CmpI(RAX, tag);
10641129 Jcc(ccNE, L);
10651130 end;

src/parse.pas modified +210 -32

@@ -41,13 +41,25 @@
4141
4242 uses BaseUnix;
4343
44+type
45+ PLoop = ^TLoop;
46+ TLoop = record
47+ brk: longint; { the chain of its breaks }
48+ base: longint; { the deferred statements in force outside it }
49+ end;
50+
4451 var
4552 checkMode: boolean; { reading a file only for its interface }
4653 inTypes: boolean; { in a type section: ^T may name a later type }
4754 fwdTypes: array[0..255] of PType;
4855 numFwd: longint;
4956 declExported: boolean; { the export mark of the declaration being read }
50- curBreak: PLongint; { the break chain of the innermost loop, or nil }
57+ curLoop: PLoop; { the innermost loop, or nil }
58+ defers: array[0..63] of longint; { the deferred statements in force }
59+ numDefers: longint;
60+ deferring: boolean; { compiling a deferred statement }
61+ directDefer: boolean; { ... as the statement itself, not in a list }
62+ deferSlot: int64; { keeps a result while deferred statements run }
5163 curResult: PType; { the result type of the procedure being compiled }
5264 tArgv, tBodySig: PType;
5365 nameRt, nameFail, nameEq, nameMain, nameBody: longint;
@@ -55,6 +67,7 @@
5567 procedure Expression(var x: TItem; want: PType); forward;
5668 function ParseType: PType; forward;
5769 procedure Statements; forward;
70+procedure Statement; forward;
5871
5972 { Little helpers }
6073
@@ -306,6 +319,42 @@
306319 Signature := t;
307320 end;
308321
322+function EnumType: PType;
323+var t: PType; o, last: PObj;
324+begin
325+ t := NewType(fEnum, 1, 1);
326+ last := nil;
327+ repeat
328+ Next;
329+ if tok <> sIdent then Mark('name expected');
330+ o := NewObj(oConst, id, t);
331+ o^.val := t^.len;
332+ o^.exported := declExported;
333+ Declare(o);
334+ if last = nil then t^.fields := o else last^.next := o;
335+ last := o;
336+ inc(t^.len);
337+ Next;
338+ until tok <> sComma;
339+ Expect(sRparen, ')');
340+ if t^.len > 256 then Mark('more than 256 names');
341+ EnumType := t;
342+end;
343+
344+function SetOf(e: PType): PType;
345+var t: PType;
346+begin
347+ if (e^.form <> fEnum) or (e^.len > 64) then Mark('a set is of an enumeration of at most 64 names');
348+ t := NewType(fSet, 8, 8);
349+ if e^.len <= 8 then t^.size := 1
350+ else if e^.len <= 16 then t^.size := 2
351+ else if e^.len <= 32 then t^.size := 4;
352+ t^.align := t^.size;
353+ t^.base := e;
354+ t^.len := e^.len;
355+ SetOf := t;
356+end;
357+
309358 function ParseType: PType;
310359 var t: PType; o: PObj; n: int64; vol: boolean;
311360 begin
@@ -350,7 +399,12 @@
350399 sPacked, sRecord: t := RecordType;
351400 sVariant: t := VariantType;
352401 sProc: begin Next; t := Signature end;
353- sLparen, sSet: Mark('enumerations and sets come in stage 2');
402+ sLparen: t := EnumType;
403+ sSet: begin
404+ Next;
405+ Expect(sOf, 'of');
406+ t := SetOf(ParseType());
407+ end;
354408 else Mark('type expected');
355409 end;
356410 ParseType := t;
@@ -626,6 +680,76 @@
626680 TempItem(x, at, off);
627681 end;
628682
683+{ A record literal: a zeroed temporary, with the fields named filled in. }
684+procedure RecordLiteral(var x: TItem; t: PType);
685+var f: PObj; a: TItem; seen: array[0..63] of longint; n, i: longint;
686+begin
687+ Next;
688+ ZeroTemp(x, t);
689+ n := 0;
690+ if tok <> sRbrace then
691+ repeat
692+ if tok <> sIdent then Mark('field expected');
693+ f := Find(t^.scope, id);
694+ if f = nil then Mark('no field ' + NameOf(id));
695+ if not f^.exported and (t^.module <> curModule) then Mark('field ' + NameOf(id) + ' isn''t exported');
696+ for i := 0 to n - 1 do if seen[i] = id then Mark(NameOf(id) + ' twice');
697+ if n <= High(seen) then begin seen[n] := id; inc(n) end;
698+ Next;
699+ Expect(sColon, ':');
700+ Expression(a, f^.typ);
701+ SetField(x, f, a);
702+ if tok <> sComma then break;
703+ Next;
704+ until false;
705+ Expect(sRbrace, '}');
706+end;
707+
708+{ A set literal: the bits of the constant names, or'd at run time with
709+ those of the others. }
710+procedure SetLiteral(var x: TItem; t: PType);
711+var e: TItem; bits, slot: int64;
712+begin
713+ Next;
714+ if (t <> nil) and (t^.form <> fSet) then Mark('a set literal needs a set type');
715+ bits := 0;
716+ slot := 0;
717+ if tok <> sRbrace then
718+ repeat
719+ if t = nil then Expression(e, nil) else Expression(e, t^.base);
720+ if t = nil then begin
721+ if e.typ^.form <> fEnum then Mark('a set holds names of an enumeration');
722+ t := SetOf(e.typ);
723+ end;
724+ if not Same(e.typ, t^.base) then Mark('not a name of ' + TypeName(t^.base));
725+ if e.mode = mConst then bits := bits or (int64(1) shl e.val)
726+ else begin
727+ if slot = 0 then begin
728+ slot := AllocTemp(8, 8);
729+ MovRI(RAX, 0);
730+ Store(Mem(RBP, slot), RAX, 8);
731+ end;
732+ Value(e);
733+ MovRR(RCX, RAX);
734+ MovRI(RAX, 1);
735+ Shift(shShl, RAX);
736+ AluM(aluOr, RAX, Mem(RBP, slot));
737+ Store(Mem(RBP, slot), RAX, 8);
738+ end;
739+ if tok <> sComma then break;
740+ Next;
741+ until false;
742+ Expect(sRbrace, '}');
743+ if t = nil then Mark('{} needs a known set type');
744+ MakeConst(x, t, bits);
745+ if slot <> 0 then begin
746+ Load(RAX, Mem(RBP, slot), 8, false);
747+ MovRI(RCX, bits);
748+ Alu(aluOr, RAX, RCX);
749+ x.mode := mReg;
750+ end;
751+end;
752+
629753 procedure Factor(var x: TItem; want: PType);
630754 var called, vol: boolean; t: PType;
631755 begin
@@ -645,7 +769,8 @@
645769 sLparen: begin Next; Expression(x, want); Expect(sRparen, ')') end;
646770 sNot: begin Next; Factor(x, nil); NotOp(x) end;
647771 sLbrak: ArrayLiteral(x, want);
648- sLbrace: Mark('record and set literals come in stage 2');
772+ sLbrace: if (want <> nil) and (want^.form = fRecord) then RecordLiteral(x, want)
773+ else SetLiteral(x, want);
649774 sArrow: begin
650775 Next;
651776 vol := tok = sVolatile;
@@ -694,22 +819,30 @@
694819 var op: TSym; y: TItem; L: longint;
695820 begin
696821 SimpleExpr(x, want);
697- if tok in [sEql, sNeq, sLss, sLeq, sGtr, sGeq] then begin
822+ if tok in [sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn] then begin
698823 op := tok;
699824 Next;
700825 Op1(op, x, L);
701- SimpleExpr(y, nil);
826+ if op = sIn then SimpleExpr(y, nil) else SimpleExpr(y, x.typ);
702827 Op2(op, x, y, L);
703- end else if tok = sIn then Mark('sets come in stage 2');
828+ end;
704829 end;
705830
706831 { Statements }
707832
708-procedure Loop(var brk: longint; var old: PLongint);
833+procedure Loop(var lp: TLoop; var old: PLoop);
834+begin
835+ lp.brk := NoLabel;
836+ lp.base := numDefers;
837+ old := curLoop;
838+ curLoop := @lp;
839+end;
840+
841+{ Runs the deferred statements in force above base, newest first. }
842+procedure RunDefers(base: longint);
843+var i: longint;
709844 begin
710- brk := NoLabel;
711- old := curBreak;
712- curBreak := @brk;
845+ for i := numDefers - 1 downto base do CallBack(defers[i]);
713846 end;
714847
715848 procedure IfStatement;
@@ -743,7 +876,7 @@
743876 end;
744877
745878 procedure WhileStatement;
746-var x: TItem; top, L, brk: longint; old: PLongint;
879+var x: TItem; top, L: longint; lp: TLoop; old: PLoop;
747880 begin
748881 Next;
749882 top := pc;
@@ -751,41 +884,41 @@
751884 Expect(sDo, 'do');
752885 L := NoLabel;
753886 CondJump(x, L);
754- Loop(brk, old);
887+ Loop(lp, old);
755888 Statements;
756889 JmpBack(top);
757890 Expect(sEnd, 'end');
758891 FixLink(L);
759- FixLink(brk);
760- curBreak := old;
892+ FixLink(lp.brk);
893+ curLoop := old;
761894 end;
762895
763896 procedure RepeatStatement;
764-var x: TItem; top, L, brk: longint; old: PLongint;
897+var x: TItem; top, L: longint; lp: TLoop; old: PLoop;
765898 begin
766899 Next;
767900 top := pc;
768- Loop(brk, old);
901+ Loop(lp, old);
769902 Statements;
770- curBreak := old;
903+ curLoop := old;
771904 Expect(sUntil, 'until');
772905 Expression(x, nil);
773906 L := NoLabel;
774907 CondJump(x, L);
775908 FixLinkTo(L, top);
776- FixLink(brk);
909+ FixLink(lp.brk);
777910 end;
778911
779912 procedure ForStatement;
780913 var
781- o: PObj; v, a, b, s: TItem; bslot, step: int64; top, exitL, brk: longint;
782- old: PLongint;
914+ o: PObj; v, a, b, s: TItem; bslot, step: int64; top, exitL: longint;
915+ lp: TLoop; old: PLoop;
783916 begin
784917 Next;
785918 if tok <> sIdent then Mark('name expected');
786919 o := Lookup(id);
787- if (o = nil) or (o^.cls <> oVar) or (o^.typ^.form <> fInt) then
788- Mark('a for loop needs an integer variable');
920+ if (o = nil) or (o^.cls <> oVar) or not (o^.typ^.form in [fInt, fEnum]) then
921+ Mark('a for loop needs an integer or enumeration variable');
789922 Next;
790923 Expect(sBecomes, ':=');
791924 MakeItem(v, o);
@@ -815,13 +948,13 @@
815948 end else begin
816949 if step > 0 then Jcc(ccA, exitL) else Jcc(ccB, exitL)
817950 end;
818- Loop(brk, old);
951+ Loop(lp, old);
819952 Statements;
820- curBreak := old;
953+ curLoop := old;
821954 Expect(sEnd, 'end');
822955 ForNext(o, bslot, step, exitL, top);
823956 FixLink(exitL);
824- FixLink(brk);
957+ FixLink(lp.brk);
825958 end;
826959
827960 procedure MatchStatement;
@@ -854,7 +987,7 @@
854987 if c^.val <= High(seen) then seen[c^.val] := true;
855988 Next;
856989 L := NoLabel;
857- MatchTag(p, c^.val, L);
990+ MatchTag(p, c^.val, L, t^.form = fEnum);
858991 OpenScope(NewScope);
859992 if tok = sLparen then begin
860993 Next;
@@ -935,6 +1068,32 @@
9351068 end;
9361069 end;
9371070
1071+{ defer s: s is compiled where it stands, as a little subroutine of the
1072+ procedure, jumped over; each way out of the statement list calls it. }
1073+procedure Defer;
1074+var L, pos, oldDepth: longint; oldLoop: PLoop; oldDeferring: boolean;
1075+begin
1076+ Next;
1077+ if directDefer then Mark('defer can''t be deferred');
1078+ if numDefers > High(defers) then Mark('too many deferred statements');
1079+ L := NoLabel;
1080+ Jmp(L);
1081+ pos := pc;
1082+ oldDepth := depth; oldLoop := curLoop; oldDeferring := deferring;
1083+ depth := 1; { the return address }
1084+ curLoop := nil;
1085+ deferring := true;
1086+ directDefer := true;
1087+ Statement;
1088+ directDefer := false;
1089+ KeepTemps;
1090+ depth := oldDepth; curLoop := oldLoop; deferring := oldDeferring;
1091+ Ret;
1092+ FixLink(L);
1093+ defers[numDefers] := pos;
1094+ inc(numDefers);
1095+end;
1096+
9381097 procedure Statement;
9391098 var x, y: TItem; called: boolean; m: int64; c: TCall;
9401099 begin
@@ -964,33 +1123,50 @@
9641123 sMatch: MatchStatement;
9651124 sReturn: begin
9661125 Next;
967- if tok = sSemicolon then ReturnNone
968- else begin
1126+ if deferring then Mark('return can''t leave a deferred statement');
1127+ if tok = sSemicolon then begin
1128+ RunDefers(0);
1129+ ReturnNone;
1130+ end else begin
9691131 if (curResult <> nil) and curResult^.tuple then ReturnResults
9701132 else begin
9711133 Expression(x, curResult);
9721134 ReturnValue(x);
9731135 end;
1136+ if numDefers > 0 then begin
1137+ if deferSlot = 0 then deferSlot := AllocPerm(8, 8);
1138+ Store(Mem(RBP, deferSlot), RAX, 8);
1139+ RunDefers(0);
1140+ Load(RAX, Mem(RBP, deferSlot), 8, false);
1141+ end;
9741142 ReturnJump;
9751143 end;
9761144 end;
9771145 sBreak: begin
9781146 Next;
979- if curBreak = nil then Mark('break outside a loop');
980- Jmp(curBreak^);
1147+ if curLoop = nil then Mark('break outside a loop');
1148+ RunDefers(curLoop^.base);
1149+ Jmp(curLoop^.brk);
9811150 end;
982- sDefer: Mark('defer comes in stage 2');
1151+ sDefer: Defer;
9831152 else Mark('statement expected');
9841153 end;
9851154 ReleaseTemps(m);
9861155 end;
9871156
9881157 procedure Statements;
1158+var base: longint; old: boolean;
9891159 begin
1160+ base := numDefers;
1161+ old := directDefer;
1162+ directDefer := false;
9901163 while not (tok in [sEnd, sElse, sElsif, sUntil, sBar, sEof]) do begin
9911164 Statement;
9921165 Expect(sSemicolon, ';');
9931166 end;
1167+ RunDefers(base);
1168+ numDefers := base;
1169+ directDefer := old;
9941170 end;
9951171
9961172 { Declarations }
@@ -1033,6 +1209,7 @@
10331209 q := q^.next;
10341210 end;
10351211 BeginProc(sig, params);
1212+ deferSlot := 0;
10361213 o := params;
10371214 while o <> nil do begin
10381215 q := o^.next;
@@ -1308,6 +1485,7 @@
13081485 body := NewChunk(secText, n, nameBody);
13091486 m^.body := body;
13101487 BeginProc(tBodySig, nil);
1488+ deferSlot := 0;
13111489 curResult := nil;
13121490 EnterBody(body);
13131491 Statements;
@@ -1445,7 +1623,7 @@
14451623 SetBss(argvChunk, 8, 8);
14461624 tArgv := NewPtr(NewPtr(tU8, false), false);
14471625 tBodySig := NewType(fProc, 8, 8);
1448- curBreak := nil;
1626+ curLoop := nil;
14491627 numPending := 0;
14501628 firstModule := nil;
14511629 lastModule := nil;

src/sym.pas modified +2 -2

@@ -313,7 +313,7 @@
313313 case a^.form of
314314 fPtr: Alike := (a^.vol = b^.vol) and Same(a^.base, b^.base);
315315 fArray: Alike := (a^.len = b^.len) and Same(a^.base, b^.base);
316- fSlice: Alike := Same(a^.base, b^.base);
316+ fSlice, fSet: Alike := Same(a^.base, b^.base);
317317 fProc, fRecord: begin
318318 { a record is the same only as itself, but for several results }
319319 if (a^.form = fRecord) and not (a^.tuple and b^.tuple) then exit(false);
@@ -384,7 +384,7 @@
384384 Mix(h, ord(t^.form));
385385 Mix(h, ord(t^.vol) + 2 * ord(t^.variadic));
386386 Mix(h, t^.len);
387- if t^.form in [fPtr, fArray, fSlice, fProc] then Shape(h, t^.base, false);
387+ if t^.form in [fPtr, fArray, fSlice, fProc, fSet] then Shape(h, t^.base, false);
388388 f := t^.fields;
389389 while f <> nil do begin
390390 if (t^.form <> fRecord) or f^.exported then begin

src/x64.pas modified +7 -0

@@ -116,6 +116,7 @@
116116 procedure Push(r: longint);
117117 procedure Pop(r: longint);
118118 procedure CallChunk(c: longint);
119+procedure CallBack(target: longint);
119120 procedure CallR(r: longint);
120121 procedure Ret;
121122 procedure Leave;
@@ -474,6 +475,12 @@
474475 Put1($E8);
475476 AddFixup(pc, c, 0);
476477 Put4(0);
478+end;
479+
480+procedure CallBack(target: longint);
481+begin
482+ Put1($E8);
483+ Put4(target - (pc + 4));
477484 end;
478485
479486 procedure CallR(r: longint);

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

@@ -0,0 +1 @@
1+break outside a loop

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

@@ -0,0 +1,8 @@
1+module DeferBreak;
2+proc f;
3+begin
4+ while true do
5+ defer break;
6+ end;
7+end;
8+end DeferBreak.

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

@@ -0,0 +1 @@
1+defer can't be deferred

test/err/DeferDefer.jed added +6 -0

@@ -0,0 +1,6 @@
1+module DeferDefer;
2+proc f;
3+begin
4+ defer defer f;
5+end;
6+end DeferDefer.

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

@@ -0,0 +1 @@
1+return can't leave a deferred statement

test/err/DeferReturn.jed added +7 -0

@@ -0,0 +1,7 @@
1+module DeferReturn;
2+proc f: I64;
3+begin
4+ defer return 1;
5+ return 0;
6+end;
7+end DeferReturn.

test/run/Defers added (executable)

Binary file; the patch has it.

test/run/Defers.expect added +5 -0

@@ -0,0 +1,5 @@
1+body body done
2+()30
3+56
4+[...*][...+**]
5+0

test/run/Defers.jed added +71 -0

@@ -0,0 +1,71 @@
1+module Defers;
2+import Out;
3+
4+type Pair = record a, b: I64; end;
5+
6+var depth: I64;
7+
8+proc enter(s: []U8);
9+begin
10+ Out.str(s); INC(depth);
11+end;
12+
13+proc leave(s: []U8);
14+begin
15+ Out.str(s); DEC(depth);
16+end;
17+
18+proc real(x: F64): F64;
19+begin
20+ enter("(");
21+ defer leave(")");
22+ return x * 2.0;
23+end;
24+
25+proc pair(n: I64): Pair;
26+var p: Pair;
27+begin
28+ defer p.a := 99;
29+ p.a := n; p.b := n + 1;
30+ return p;
31+end;
32+
33+proc begin_end(i: I64);
34+var k: I64;
35+begin
36+ defer for k := 1 to i do Out.str("*"); end;
37+ if i = 1 then return; end;
38+ Out.str("+");
39+end;
40+
41+proc nested;
42+var i, j: I64;
43+begin
44+ for i := 1 to 2 do
45+ enter("[");
46+ defer leave("]");
47+ defer begin_end(i);
48+ j := 0;
49+ while true do
50+ defer Out.str(".");
51+ INC(j);
52+ if j = 3 then break; end;
53+ end;
54+ end;
55+end;
56+
57+proc main*;
58+var p: Pair;
59+begin
60+ Out.int(I64(real(1.5) * 10.0)); Out.ln;
61+ p := pair(5);
62+ Out.int(p.a); Out.int(p.b); Out.ln;
63+ nested;
64+ Out.ln;
65+ Out.int(depth); Out.ln;
66+end;
67+
68+begin
69+ defer Out.str("body done\n");
70+ Out.str("body ");
71+end Defers.

test/run/Kinds added (executable)

Binary file; the patch has it.

test/run/Kinds.expect added +8 -0

@@ -0,0 +1,8 @@
1+023 2 0 in out sub sup ne eq
2+13 10 1 2 lt green other
3+120 0 2
4+47mid
5+24
6+50 LLCBA
7+-1 LLDBA
8+3
\ No newline at end of file

test/run/Kinds.jed added +95 -0

@@ -0,0 +1,95 @@
1+module Kinds;
2+import Out;
3+
4+type
5+ Color* = (red, green, blue, black);
6+ Colors* = set of Color;
7+ Cell = record ch: U8; attr: U8; fg: Color; end;
8+ Point = record x, y: I64; name: []U8; end;
9+ Line = record a, b: Point; end;
10+
11+var log: [8]U8; nlog: I64;
12+
13+proc note(c: U8);
14+begin
15+ log[nlog] := c;
16+ INC(nlog);
17+end;
18+
19+proc show(s: Colors);
20+var c: Color;
21+begin
22+ for c := red to black do
23+ if c in s then Out.int(I64(c)); end;
24+ end;
25+ Out.str(" ");
26+end;
27+
28+proc name(c: Color): []U8;
29+begin
30+ match c of
31+ | red: return "red";
32+ | green: return "green";
33+ | else: return "other";
34+ end;
35+end;
36+
37+proc deferred(n: I64): I64;
38+var i: I64;
39+begin
40+ defer note('A');
41+ defer note('B');
42+ for i := 1 to 3 do
43+ defer note('L');
44+ if i = 2 then break; end;
45+ end;
46+ if n > 0 then
47+ defer note('C');
48+ return n * 10;
49+ end;
50+ note('D');
51+ return -1;
52+end;
53+
54+proc mid(a, b: Point): Point;
55+begin
56+ return {x: (a.x + b.x) div 2, y: (a.y + b.y) div 2, name: "mid"};
57+end;
58+
59+proc main*;
60+var s, t: Colors; c: Color; cell: Cell; p: Point; l: Line; r: I64; one: Colors;
61+begin
62+ s := {red, blue};
63+ t := {blue, black};
64+ show(s + t); show(s * t); show(s - t); show({});
65+ if red in s then Out.str("in "); end;
66+ if not (green in s) then Out.str("out "); end;
67+ if s * t <= t then Out.str("sub "); end;
68+ if s + t >= s then Out.str("sup "); end;
69+ if s # t then Out.str("ne "); end;
70+ if s = {blue, red} then Out.str("eq"); end;
71+ Out.ln;
72+ c := green;
73+ one := {c, black};
74+ show(one);
75+ Out.int(I64(U8(one))); Out.str(" ");
76+ Out.int(SIZE(Colors)); Out.str(" ");
77+ Out.int(I64(Color(2))); Out.str(" ");
78+ if c < blue then Out.str("lt "); end;
79+ Out.str(name(c)); Out.str(" "); Out.str(name(black)); Out.ln;
80+ cell := {ch: 'x', fg: blue};
81+ Out.int(I64(cell.ch)); Out.str(" "); Out.int(I64(cell.attr)); Out.str(" "); Out.int(I64(cell.fg)); Out.ln;
82+ p := mid({x: 2, y: 4}, {y: 10, x: 6});
83+ Out.int(p.x); Out.int(p.y); Out.str(p.name); Out.ln;
84+ l := {a: {x: 1, y: 2}, b: p};
85+ Out.int(l.a.y); Out.int(l.b.x); Out.ln;
86+ r := deferred(5);
87+ Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln;
88+ nlog := 0;
89+ r := deferred(0);
90+ Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln;
91+ Out.int(I64(Color(I64(c) + 2)));
92+ c := Color(nlog);
93+end;
94+
95+end Kinds.

test/run/Kinds.status added +1 -0

@@ -0,0 +1 @@
1+2