raz / doc / raz-tutorial.7

1415 lines · 29.5 KiB · raw · history · last change 264716cb

1.\" raz-tutorial(7) - a tour of raz
2.\" Every whole module in a literal block here is a program that make
3.\" check compiles and runs, against test/man/Name.expect; see
4.\" tools/Doc.raz.
5.Dd October 15, 2026
6.Dt RAZ-TUTORIAL 7
7.Os
8.Sh NAME
9.Nm raz-tutorial
10.Nd a tour of the raz language
11.Sh DESCRIPTION
12This tour is for someone who has programmed in Pascal or C and has
13never seen raz.
14Each section is one idea, with a program to run.
15The programs are whole: save one under its module's name and run it.
16.Pp
17The language is defined by the report,
18.Pa doc/raz.md
19in raz's sources; where this page is short, the report says it all.
20.Xr raz 7
21is the language at a glance,
22.Xr raz-lib 3
23the library, and
24.Xr raz 1
25the compiler.
26.Sh 1. HELLO, WORLD
27.Bd -literal -offset indent
28module Hello;
29import Out;
30
31proc main*;
32begin
33 Out.str("hello, world\en");
34end;
35
36end Hello.
37.Ed
38.Pp
39Saved as
40.Pa Hello.raz ,
41it is compiled and run with
42.Bd -literal -offset indent
43raz Hello.raz && ./Hello
44raz run Hello.raz
45.Ed
46.Pp
47the second without writing a file.
48A module lives in a file of its own name, and its name comes again
49after its last
50.Cm end .
51.Cm import Out
52lets it use what the module
53.Cm Out
54exports, as
55.Cm Out.str .
56The
57.Cm *
58after
59.Cm main
60exports it; the program starts at the
61.Cm main
62of the module named on the command line.
63Every statement ends in
64.Cm \&; ,
65even one that ends in
66.Cm end .
67.Sh 2. MODULES
68A program is a set of modules.
69Here is one, saved as
70.Pa Greet.raz :
71.Bd -literal -offset indent
72module Greet;
73import Out;
74
75var count*: INT; (* the greetings so far *)
76
77proc hello*(name: []const U8);
78begin
79 Out.str("hello, ");
80 Out.str(name);
81 Out.ln;
82 INC(count);
83end;
84
85begin
86 Out.str("Greet is ready\en");
87end Greet.
88.Ed
89.Pp
90and a program beside it that uses it:
91.Bd -literal -offset indent
92module Twice;
93import Out, G := Greet;
94
95proc main*;
96begin
97 G.hello("world");
98 G.hello("raz");
99 Out.int(G.count);
100 Out.str(" greetings\en");
101end;
102
103end Twice.
104.Ed
105.Bd -literal -offset indent
106Greet is ready
107hello, world
108hello, raz
1092 greetings
110.Ed
111.Pp
112A name with
113.Cm *
114is exported; any other is the module's own.
115.Cm "G := Greet"
116imports
117.Cm Greet
118under a shorter name.
119Another module may read
120.Cm G.count ,
121but only
122.Cm Greet
123may change it.
124The statements after a module's last
125.Cm begin
126are its body, which runs once, before
127.Cm main ,
128after the bodies of the modules it imports.
129.Pp
130The compiler finds
131.Cm Greet
132beside the main module, then in each directory given with
133.Fl I ,
134then in the library.
135The library's module names, such as
136.Cm Out , Str
137and
138.Cm Map ,
139are kept for it: a program doesn't name a module of its own so.
140.Sh 3. VALUES, TYPES AND CONVERSIONS
141.Bd -literal -offset indent
142module Values;
143import Fmt;
144
145const Max = 100; (* untyped: it takes the type it meets *)
146
147proc main*;
148var n: INT; b: U8; big: I64; x: F64; c: I32; ok: BOOL;
149begin
150 n := Max * 3;
151 b := 250;
152 b := b + 10; (* wraps, in a U8: 4 *)
153 big := n; (* an INT goes into an I64 *)
154 x := F64(n) / 7.0; (* nothing else converts unasked *)
155 c := '\eu{E9}'; (* a character is its code point *)
156 ok := (n > Max) and (b # 0);
157 Fmt.print("{} {} {} {} {} {}\en", [Fmt.int(n), Fmt.int(I64(b)),
158 Fmt.int(big), Fmt.real(x, 3), Fmt.int(I64(c)),
159 Fmt.bool(ok)]);
160end;
161
162end Values.
163.Ed
164.Bd -literal -offset indent
165300 4 300 42.857 233 true
166.Ed
167.Pp
168The integers are
169.Cm I8 , I16 , I32 , I64
170and
171.Cm U8 , U16 , U32 , U64 ,
172and
173.Cm INT
174and
175.Cm UINT ,
176as big as an address.
177.Cm INT
178is the everyday one: lengths, indexes and counts are
179.Cm INT Ns s .
180The reals are
181.Cm F32
182and
183.Cm F64 .
184Arithmetic wraps at the type's width, and never stops the program,
185except dividing by zero.
186.Pp
187Two types never mix but where nothing can be lost:
188.Cm INT
189goes into
190.Cm I64 ,
191wherever the one meets the other, so with
192.Cm "big: I64" ,
193.Cm "big + n"
194is an
195.Cm I64 ;
196and
197.Cm U8 , I8
198and
199.Cm I16 ,
200which an
201.Cm INT
202holds on any machine, go into
203.Cm INT ,
204so a digit's value is
205.Cm "n := n * 10 + s[i] - '0'" .
206What an operator made in a small type doesn't, since it may have
207wrapped there: with
208.Cm "a, b: U8" ,
209.Cm "n := a + b"
210is an error, and
211.Cm "INT(a) + b"
212the sum.
213With
214.Cm "c: I32" ,
215.Cm "c < n"
216is an error.
217A type's name converts, as
218.Cm F64(n)
219and
220.Cm I64(b)
221do above; an
222.Cm I64
223becomes an
224.Cm INT
225only so, as
226.Cm INT(big) ,
227since an
228.Cm INT
229may be smaller on another machine.
230A number written in the program is untyped until it meets a type;
231.Cm 0FFH
232is hexadecimal, and
233.Cm 1.5
234a real, which an integer never becomes without a conversion.
235.Pp
236.Cm # ,
237not
238.Cm <> ,
239is
240.Dq different .
241.Cm and , or
242and
243.Cm not
244are for
245.Cm BOOL Ns s ,
246and bind below the relations, so
247.Cm "i < n and a[i] # 0"
248needs no parentheses;
249.Cm & , | , xor
250and
251.Cm ~
252are for the bits of integers.
253Every variable starts at zero.
254.Sh 4. PROCEDURES AND SEVERAL RESULTS
255.Bd -literal -offset indent
256module Procs;
257import Out;
258
259proc divmod(a, b: INT): (INT, INT);
260begin
261 return a div b, a mod b;
262end;
263
264proc swap(var a, b: INT);
265var t: INT;
266begin
267 t := a;
268 a := b;
269 b := t;
270end;
271
272proc square(n: INT): INT;
273begin
274 return n * n;
275end;
276
277proc twice(f: proc(n: INT): INT; n: INT): INT;
278begin
279 return f(f(n));
280end;
281
282proc main*;
283var q, r, x, y: INT;
284begin
285 q, r := divmod(17, 5);
286 x := 1;
287 y := 2;
288 swap(x, y);
289 Out.int(q); Out.char(' '); Out.int(r); Out.ln;
290 Out.int(x); Out.char(' '); Out.int(y); Out.ln;
291 Out.int(twice(square, 3)); Out.ln;
292 _, r := divmod(-7, 2);
293 Out.int(r); Out.ln;
294end;
295
296end Procs.
297.Ed
298.Bd -literal -offset indent
2993 2
3002 1
30181
302-1
303.Ed
304.Pp
305A parameter is a copy, unless it is
306.Cm var ,
307when it is the caller's variable itself.
308A procedure may return several results, which a multiple assignment
309takes apart; the blank,
310.Cm _ ,
311drops one.
312A procedure is a value too, of a procedure type, as
313.Cm f
314is in
315.Cm twice .
316A procedure without parameters leaves out the parentheses, as
317.Cm Out.ln
318does.
319Procedures don't nest, and a name is declared before it is used.
320.Pp
321A call that drops a result, as
322.Cm "Sys.write(fd, s);"
323does, is warned of;
324.Cm "_ := Sys.write(fd, s);"
325says it is meant.
326.Pp
327A record or an array that a procedure only reads goes as
328.Cm const :
329the caller's variable itself, read in place with nothing copied, which
330the procedure can't change.
331.Bd -literal -offset indent
332module Grids;
333import Out;
334
335type Grid = record cells: [64]INT; w, h: INT; end;
336
337proc fill(var g: Grid; v: INT); (* changes g *)
338var i: INT;
339begin
340 for i := 0 to g.w * g.h - 1 do g.cells[i] := v; end;
341end;
342
343proc sum(const g: Grid): INT; (* reads g in place *)
344var i, s: INT;
345begin
346 s := 0;
347 for i := 0 to g.w * g.h - 1 do s := s + g.cells[i]; end;
348 return s;
349end;
350
351proc main*;
352var g: Grid;
353begin
354 g.w := 4;
355 g.h := 2;
356 fill(g, 3);
357 Out.int(sum(g)); Out.ln;
358end;
359
360end Grids.
361.Ed
362.Bd -literal -offset indent
36324
364.Ed
365.Pp
366So a heading says what a procedure does with what it is given: a value
367for a single value or a slice it reads,
368.Cm const
369for a record or an array it reads,
370.Cm var
371for what it changes, and a pointer only for what it keeps past the
372call.
373.Sh 5. ARRAYS, SLICES AND STRINGS
374.Bd -literal -offset indent
375module Slices;
376import Out, Str;
377
378proc sum(s: []INT): INT;
379var i, t: INT;
380begin
381 t := 0;
382 for i := 0 to LEN(s) - 1 do t := t + s[i]; end;
383 return t;
384end;
385
386proc main*;
387var a: [5]INT; i: INT; s, val: []const U8; name: [8]U8; ok: BOOL;
388begin
389 for i := 0 to 4 do a[i] := i * i; end;
390 Out.int(sum(a)); Out.ln; (* the array, as a slice *)
391 Out.int(sum(a[1..3])); Out.ln; (* a[1] and a[2] *)
392 s := "hello, world";
393 Out.str(s[7..LEN(s)]); Out.ln;
394 if s[0..5] = "hello" then Out.str("it says hello\en"); end;
395 Out.int(Str.find(s, "world")); Out.ln;
396 _, val, ok := Str.cut(" size = 42 ", "=");
397 if ok then Out.str(Str.trim(val)); Out.ln; end;
398 name := "raz"; (* a copy, the program's own *)
399 name[0] := 'R';
400 Out.str(name[0..3]); Out.ln;
401 Out.str(\(ga
402 C:\etmp\e "as it stands"
403 over lines
404 \(ga);
405end;
406
407end Slices.
408.Ed
409.Bd -literal -offset indent
41030
4115
412world
413it says hello
4147
41542
416Raz
417C:\etmp\e "as it stands"
418 over lines
419.Ed
420.Pp
421.Cm [5]INT
422is an array: five
423.Cm INT Ns s
424in a row, copied when it is assigned.
425.Cm []INT
426is a slice: a pointer to elements that live elsewhere, and their
427number,
428.Cm LEN(s) .
429.Cm a[lo..hi]
430is the slice of the elements from
431.Cm lo
432up to, but not including,
433.Cm hi ,
434and an array goes silently where a slice is wanted.
435A slice of a local array is good only while its procedure runs, so
436returning one is an error: take the array as a
437.Cm var
438parameter instead.
439.Pp
440A string is a slice of bytes,
441.Cm []U8 ,
442in UTF-8, and its bytes are constant;
443.Cm [8]U8
444made from one is a copy.
445Arrays and slices of integers compare with
446.Cm =
447and
448.Cm # ;
449.Cm Str
450has the rest: ordering, finding, trimming, cutting a string into
451parts, which are slices of it, UTF-8, and numbers to and from text.
452.Pp
453A string between backquotes is raw: no escapes, and it may run over
454lines.
455When the opening backquote ends its line and the closing one has
456only blanks before it, those blanks come off every line, so the text
457stands at the indent of the code around it.
458.Pp
459A
460.Cm for
461loop takes its bounds once, and never steps past the last: with an
462empty slice,
463.Cm "0 to LEN(s) - 1"
464doesn't run at all.
465.Cm break
466leaves a loop, and
467.Cm continue
468ends its round: a
469.Cm for
470steps, and a
471.Cm while
472tests again; so a
473.Cm while
474moves on, as
475.Cm "i := i + n" ,
476before it can
477.Cm continue .
478.Sh 6. RECORDS AND POINTERS
479.Bd -literal -offset indent
480module Boxes;
481import Fmt, SYSTEM;
482
483type
484 Point = record x, y: INT; end;
485 Box = record lo, hi: Point; end;
486
487proc area(b: Box): INT;
488begin
489 return (b.hi.x - b.lo.x) * (b.hi.y - b.lo.y);
490end;
491
492proc grow(b: ^Box; n: INT);
493begin
494 DEC(b^.lo.x, n);
495 DEC(b^.lo.y, n);
496 INC(b^.hi.x, n);
497 INC(b^.hi.y, n);
498end;
499
500proc main*;
501var b: Box; p: ^Point;
502begin
503 b := {lo: {x: 1, y: 1}, hi: {x: 4, y: 3}};
504 Fmt.print("{}\en", [Fmt.int(area(b))]);
505 grow(SYSTEM.ADR(b), 1);
506 p := SYSTEM.ADR(b.hi);
507 p^.x := 10;
508 Fmt.print("{} {}\en", [Fmt.int(area(b)), Fmt.int(b.hi.x)]);
509end;
510
511end Boxes.
512.Ed
513.Bd -literal -offset indent
5146
51540 10
516.Ed
517.Pp
518A record is laid out as C lays out a struct.
519.Cm "{lo: ..., hi: ...}"
520builds one, naming its fields; the ones it leaves out are zero.
521.Cm ^Box
522is a pointer to a
523.Cm Box ,
524.Cm SYSTEM.ADR(b)
525the address of
526.Cm b ,
527and
528.Cm b^
529what a pointer points at.
530A pointer is never the record:
531.Cm b^.lo ,
532never
533.Cm b.lo .
534.Pp
535A slice is a pointer and a length, and a record can keep the two
536apart, as an interpreter keeps a string, or as C wants them:
537.Bd -literal -offset indent
538module Spans;
539import Out, SYSTEM;
540
541type Span = record p: ^U8; n: INT; end;
542
543proc spanOf(s: []const U8): Span;
544begin
545 return {p: SYSTEM.PTR(s), n: LEN(s)};
546end;
547
548proc text(sp: Span): []U8;
549begin
550 return sp.p[0..sp.n];
551end;
552
553proc main*;
554var words: [3]Span; i: INT;
555begin
556 words := [spanOf("one"), spanOf(""), spanOf("three")];
557 for i := 0 to 2 do
558 Out.int(words[i].n); Out.char(' ');
559 Out.str(text(words[i])); Out.ln;
560 end;
561end;
562
563end Spans.
564.Ed
565.Bd -literal -offset indent
5663 one
5670
5685 three
569.Ed
570.Pp
571.Cm LEN(s)
572is the length, and
573.Cm SYSTEM.PTR(s)
574the pointer, a
575.Cm ^U8
576for a
577.Cm []U8 ,
578with no check.
579.Cm SYSTEM.ADR(s[0])
580looks the same, and passes every test but the one with an empty
581string: there
582.Cm s[0]
583is out of range, and the program stops.
584.Cm SYSTEM.PTR
585of an empty slice is what the slice holds, which is
586.Cm nil
587for one never set, so nothing needs testing first.
588.Cm sp.p[0..sp.n]
589is the slice again, empty when
590.Cm sp.n
591is 0, whatever
592.Cm sp.p
593is.
594Of an array,
595.Cm SYSTEM.PTR(a)
596is the address of its first element.
597.Sh 7. BYTES AND VIEWS
598A file, a network packet or a device hands a program bytes, and the
599program wants numbers and records out of them.
600A
601.Em view
602reads and writes bytes as another type.
603.Bd -literal -offset indent
604module Packet;
605import Out;
606
607type Header = record kind: U16; flags: U16; size: U32; end;
608
609var buf: [16]U8;
610
611proc main*;
612var i: INT; n: I64; h: Header; x: F64;
613begin
614 buf[0].(I64) := 258; (* buf[0] to buf[7] now hold 258 *)
615 for i := 0 to 7 do Out.int(I64(buf[i])); Out.char(' '); end;
616 Out.ln;
617 n := buf[0].(I64); (* and give it back *)
618 Out.int(n); Out.ln;
619
620 buf[8].(Header) := {kind: 1, size: 4096};
621 h := buf[8].(Header);
622 Out.int(I64(h.size)); Out.ln;
623 INC(buf[8].(Header).size, 4);
624 Out.int(I64(buf[8].(Header).size)); Out.ln;
625
626 x := 1.0;
627 Out.hex(x.(U64), 16); Out.ln; (* the bits of 1.0 *)
628 Out.int(I64(x)); Out.ln; (* the number 1.0 *)
629end;
630
631end Packet.
632.Ed
633.Bd -literal -offset indent
6342 1 0 0 0 0 0 0
635258
6364096
6374100
6383FF0000000000000
6391
640.Ed
641.Pp
642Read
643.Cm buf[0].(I64)
644as
645.Dq "the I64 whose bytes start at buf[0]" .
646An
647.Cm I64
648is 8 bytes, so the view is made of
649.Cm buf[0]
650to
651.Cm buf[7] :
652.Bd -literal -offset indent
653buf: [0] [1] [2] [3] [4] [5] [6] [7] [8] ...
654 2 1 0 0 0 0 0 0
655 \e______ buf[0].(I64) = 258 ______/
656.Ed
657.Pp
658Nothing is copied to make a view: it
659.Em is
660those bytes, as
661.Cm p^
662is the variable
663.Cm p
664points at.
665Assigning it writes them, and so changes
666.Cm buf ;
667reading it reads them.
668So a view goes wherever a variable goes: on the left of
669.Cm := ,
670in
671.Cm INC ,
672and with a field or an index after it, as
673.Cm buf[8].(Header).size
674is the
675.Cm size
676field of the
677.Cm Header
678whose bytes start at
679.Cm buf[8] .
680.Pp
681258 is
682.Cm 102H ,
683and its low byte, 2, comes first: x86-64 puts a number's low byte
684first in memory.
685Another machine may put it last; a format with an order of its own is
686read a byte at a time, with
687.Cm Str.le
688or
689.Cm Str.be ,
690if the program is to run everywhere.
691.Pp
692A view isn't a conversion.
693A conversion works on the value, a view on the bytes:
694.Cm I64(x)
695is 1, the number, while
696.Cm x.(U64)
697is
698.Cm 3FF0000000000000H ,
699the bits that hold 1.0.
700When the program means a number it wants a conversion; when it means
701the bytes as they lie, a view.
702.Pp
703The view must lie inside the variable it is made of.
704For an element, as
705.Cm buf[i].(I64) ,
706that is from
707.Cm buf[i]
708to the end of
709.Cm buf ,
710and the program checks it as it checks an index:
711.Bd -literal -offset indent
712module Overrun;
713import Out;
714
715var buf: [16]U8;
716
717proc main*;
718var i: INT;
719begin
720 i := 0;
721 while i < 16 do
722 buf[i].(I32) := 1;
723 i := i + 3;
724 end;
725 Out.str("done\en");
726end;
727
728end Overrun.
729.Ed
730.Bd -literal -offset indent
731Overrun.raz:11:13: a view at index 15 runs past a length of 16
732 in Overrun.main at Overrun.raz:11:13: i = 15
733.Ed
734.Pp
735The
736.Cm I32
737at
738.Cm buf[15]
739would be
740.Cm buf[15]
741to
742.Cm buf[18] ,
743three bytes past the end.
744An index the compiler knows, it checks itself:
745.Cm buf[14].(I32)
746doesn't compile.
747A view of a whole variable must fit in it:
748.Cm x.(U64)
749needs
750.Cm x
751to have 8 bytes at least.
752.Pp
753A view is an integer, a real or a pointer, or a record or array made
754of them: types that any bytes are a value of.
755A
756.Cm BOOL
757or an enumeration isn't, since some bytes are none of its values:
758view an integer, and compare or convert it.
759A view may start at any byte, so it has no address:
760.Cm SYSTEM.ADR
761of it is an error.
762Copy it to a variable first.
763Before views, a program made a pointer for each access, as
764.Cm "p := ^I64(SYSTEM.ADR(buf[0]))"
765and then
766.Cm "p^ := 258" ,
767which checks nothing.
768.Sh 8. MEMORY AND ALLOCATORS
769.Bd -literal -offset indent
770module Stack;
771import Out, Mem, Heap, Arena, SYSTEM;
772
773type Node = record next: ^Node; val: INT; end;
774
775(* a node holding v on top of top, from the allocator a;
776 nil if a has no room *)
777proc push(top: ^Node; v: INT; a: ^Mem.Allocator): ^Node;
778var n: ^Node;
779begin
780 NEW(n, a);
781 if n # nil then
782 n^.next := top;
783 n^.val := v;
784 end;
785 return n;
786end;
787
788proc main*;
789var top, n: ^Node; i: INT; ar: Arena.Arena;
790begin
791 for i := 1 to 3 do top := push(top, i, Heap.heap); end;
792 while top # nil do
793 Out.int(top^.val); Out.char(' ');
794 n := top;
795 top := top^.next;
796 Mem.free(Heap.heap, ^U8(n));
797 end;
798 Out.ln;
799 if not Arena.init(ar, 100000) then return; end;
800 for i := 1 to 1000 do top := push(top, i, SYSTEM.ADR(ar.base)); end;
801 Out.int(top^.val); Out.ln;
802 Arena.done(ar); (* every node at once *)
803end;
804
805end Stack.
806.Ed
807.Bd -literal -offset indent
8083 2 1
8091000
810.Ed
811.Pp
812raz has no garbage collector, and no allocator of its own: memory
813comes from an allocator, a
814.Cm Mem.Allocator ,
815which the program chooses and passes.
816.Cm "NEW(n, a)"
817sets
818.Cm n
819to a fresh, zeroed
820.Cm Node
821from
822.Cm a ,
823or to
824.Cm nil
825if
826.Cm a
827has no room.
828.Cm Heap.heap
829is the general one, which
830.Cm Mem.free
831gives memory back to.
832An
833.Cm Arena
834hands out memory from one block, and frees it all at once.
835.Cm Buf , List
836and
837.Cm Map
838take the allocator they use from
839.Cm init .
840.Sh 9. ERRORS
841.Bd -literal -offset indent
842module Errors;
843import Out, Str;
844
845const
846 Empty*: ERROR = "nothing to read";
847 TooBig*: ERROR = "not a number up to 1000";
848
849(* the number s holds, up to 1000 *)
850proc number(s: []const U8): (INT, ERROR);
851var n: I64; ok: BOOL;
852begin
853 if LEN(s) = 0 then return 0, Empty; end;
854 n, ok := Str.toInt(s);
855 if not ok or (n > 1000) then return 0, TooBig; end;
856 return INT(n), nil;
857end;
858
859(* the sum of the numbers in words: the first error ends it *)
860proc total(words: [][]const U8): (INT, ERROR);
861var i, sum: INT;
862begin
863 for i := 0 to LEN(words) - 1 do
864 sum := sum + try number(words[i]);
865 end;
866 return sum, nil;
867end;
868
869proc main*;
870var words: [3][]const U8; i, n: INT; err: ERROR;
871begin
872 words := ["42", "", "12345"];
873 for i := 0 to 2 do
874 n, err := number(words[i]);
875 if err = nil then Out.int(n);
876 elsif err = Empty then Out.str("empty");
877 else Out.str(MSG(err));
878 end;
879 Out.ln;
880 end;
881 n, err := total(["1", "2", "3"]);
882 Out.int(n); Out.ln;
883 n, err := total(words);
884 if err # nil then Out.str(MSG(err)); Out.ln; end;
885end;
886
887end Errors.
888.Ed
889.Bd -literal -offset indent
89042
891empty
892not a number up to 1000
8936
894nothing to read
895.Ed
896.Pp
897A procedure that can fail returns an
898.Cm ERROR
899beside its result, and
900.Cm nil
901when it didn't.
902Each
903.Cm ERROR
904constant is an error of its own, compared with
905.Cm =
906by which declaration made it, never by its message;
907.Cm MSG(err)
908is the message.
909An exported one, as
910.Cm Empty
911is here, lets the callers tell it from the others.
912.Pp
913A caller that can't deal with an error passes it on to its own caller
914with
915.Cm try ,
916as
917.Cm total
918does: if the call returned an error that isn't
919.Cm nil ,
920the procedure
921.Cm try
922stands in returns that error, with zero for its other results, and
923otherwise
924.Cm try
925is the call's other results, here a number.
926.Cm try
927is a
928.Cm return ,
929written where the call is: it has no handler, keeps no state and
930unwinds nothing, so every place a procedure can leave is in its text.
931The procedure it stands in must itself end in an
932.Cm ERROR ,
933so
934.Cm main ,
935which returns none, tests each error and deals with it.
936raz has no exceptions.
937.Sh 10. DEFER
938.Bd -literal -offset indent
939module Defers;
940import Out, Sys;
941
942proc step(n: INT);
943begin
944 Out.str("in "); Out.int(n); Out.ln;
945 defer Out.str("out\en");
946 if n = 2 then return; end;
947 defer Out.str("done\en");
948 Out.str("working\en");
949end;
950
951(* the lines of the file at path, or -1 if it can't be read *)
952proc lines(path: []const U8): INT;
953var fd, n, i, count: INT; buf: [4096]U8;
954begin
955 fd := Sys.openRead(path);
956 if fd < 0 then return -1; end;
957 defer Sys.close(fd);
958 count := 0;
959 n := Sys.read(fd, buf);
960 while n > 0 do
961 for i := 0 to n - 1 do
962 if buf[i] = '\en' then INC(count); end;
963 end;
964 n := Sys.read(fd, buf);
965 end;
966 return count;
967end;
968
969proc main*;
970begin
971 step(1);
972 step(2);
973 Out.int(lines("/dev/null")); Out.ln;
974 Out.int(lines("/no/such/file")); Out.ln;
975end;
976
977end Defers.
978.Ed
979.Bd -literal -offset indent
980in 1
981working
982done
983out
984in 2
985out
9860
987-1
988.Ed
989.Pp
990.Cm "defer s;"
991runs
992.Cm s
993when the program leaves the statements the
994.Cm defer
995stands in: at their end, or by a
996.Cm return ,
997a
998.Cm break
999or a
1000.Cm continue .
1001Deferred statements run the last first, and only those whose
1002.Cm defer
1003was reached.
1004So a file is closed beside the line that opens it, however the
1005procedure ends.
1006.Sh 11. CHECKS, AND WHAT A FAILURE SAYS
1007.Bd -literal -offset indent
1008module Fail;
1009import Out;
1010
1011proc show(a: []INT; i: INT);
1012begin
1013 Out.int(a[i]);
1014 Out.ln;
1015end;
1016
1017proc main*;
1018var a: [3]INT; i: INT;
1019begin
1020 for i := 0 to 3 do
1021 show(a, i);
1022 end;
1023end;
1024
1025end Fail.
1026.Ed
1027.Bd -literal -offset indent
10280
10290
10300
1031Fail.raz:6:15: index 3 is out of range for a length of 3
1032 in Fail.show at Fail.raz:6:15: i = 3
1033 in Fail.main at Fail.raz:14:9: i = 3
1034.Ed
1035.Pp
1036Every index and slice is checked.
1037A failed check says where it failed and with what values, then the
1038calls under way with their variables, and ends the program with
1039status 2.
1040So do a
1041.Cm nil
1042pointer, a division by zero and a stack overflow.
1043.Pp
1044A module that is sure of its indexes may say
1045.Cm "check off;"
1046after its imports (it must import SYSTEM), for speed; an index out of range there reads or
1047writes whatever it reaches.
1048The program carries line numbers for
1049.Xr gdb 1 ,
1050and
1051.Ev RAZ_PROFILE Ns =1
1052in its environment has it say where its time went;
1053.Xr raz 1
1054says more.
1055.Sh 12. ENUMERATIONS, SETS, VARIANTS AND MATCH
1056.Bd -literal -offset indent
1057module Shapes;
1058import Out, Fmt, Math;
1059
1060type
1061 Colour = (red, green, blue);
1062 Colours = set of Colour;
1063 Shape = variant
1064 circle(r: F64);
1065 rect(w, h: F64);
1066 dot;
1067 end;
1068
1069const Some: []Shape = [circle(1.0), rect(2.0, 3.5), dot];
1070
1071proc area(const s: Shape): F64;
1072begin
1073 match s of
1074 | circle(r): return Math.pi * r * r;
1075 | rect(w, h): return w * h;
1076 | dot: return 0.0;
1077 end;
1078end;
1079
1080proc kind(c: I32): []const U8;
1081begin
1082 match c of
1083 | ' ', '\et', '\en': return "space";
1084 | '0' .. '9': return "digit";
1085 | 'a' .. 'z', 'A' .. 'Z': return "letter";
1086 | else: return "other";
1087 end;
1088end;
1089
1090proc colour(name: []const U8): Colour;
1091begin
1092 match name of
1093 | "red", "rose": return red;
1094 | "green": return green;
1095 | else: return blue;
1096 end;
1097end;
1098
1099proc main*;
1100var i: INT; warm: Colours; c: Colour;
1101begin
1102 for i := 0 to LEN(Some) - 1 do
1103 Fmt.print("{}\en", [Fmt.real(area(Some[i]), 2)]);
1104 end;
1105 Fmt.print("{} {} {}\en", [Fmt.str(kind('7')), Fmt.str(kind('x')),
1106 Fmt.str(kind('+'))]);
1107 warm := {red, blue} - {blue} + {green};
1108 for c := red to blue do
1109 if c in warm then Out.int(I64(c)); Out.ln; end;
1110 end;
1111 Out.int(I64(colour("rose"))); Out.int(I64(colour("green"))); Out.ln;
1112end;
1113
1114end Shapes.
1115.Ed
1116.Bd -literal -offset indent
11173.14
11187.00
11190.00
1120digit letter other
11210
11221
112301
1124.Ed
1125.Pp
1126An enumeration is a list of names, in order, each of which may be
1127written with its type,
1128.Cm Color.red ;
1129two enumerations may share a name, which is then always written so.
1130A
1131.Cm "set of"
1132it holds any choice of them, in the bits of a word, with
1133.Cm in ,
1134.Cm +
1135for union,
1136.Cm *
1137for intersection and
1138.Cm -
1139for difference.
1140.Pp
1141A variant holds one of its cases, each with fields of its own, and
1142.Cm match
1143is the only way to read them: it runs the arm of the case the variant
1144holds, naming its fields.
1145A constant may hold variants, each a case built from constants, as
1146.Cm Some
1147does; a
1148.Cm match
1149on one names fields that are only read.
1150Every case has an arm, unless an
1151.Cm "| else:"
1152comes last.
1153On an integer,
1154.Cm match
1155takes constants and ranges, and on a string, string constants; both
1156must have an
1157.Cm "| else:" .
1158.Sh 13. GENERIC MODULES
1159A module may take types, and the procedures it needs on them, as
1160parameters.
1161.Pa Biggest.raz :
1162.Bd -literal -offset indent
1163module Biggest(T; less: proc(a, b: T): BOOL);
1164
1165(* the biggest of s, which mustn't be empty *)
1166proc max*(s: []T): T;
1167var i: INT; m: T;
1168begin
1169 m := s[0];
1170 for i := 1 to LEN(s) - 1 do
1171 if less(m, s[i]) then m := s[i]; end;
1172 end;
1173 return m;
1174end;
1175
1176end Biggest.
1177.Ed
1178.Bd -literal -offset indent
1179module Generics;
1180import Out, Ints := Biggest(INT, before),
1181 Words := Biggest([]const U8, shorter), Order := Sort(INT, before);
1182
1183proc before(a, b: INT): BOOL;
1184begin
1185 return a < b;
1186end;
1187
1188proc shorter(a, b: []const U8): BOOL;
1189begin
1190 return LEN(a) < LEN(b);
1191end;
1192
1193proc main*;
1194var a: [5]INT; i: INT;
1195begin
1196 a := [3, 1, 4, 1, 5];
1197 Out.int(Ints.max(a)); Out.ln;
1198 Out.str(Words.max(["a", "tree", "is"])); Out.ln;
1199 Order.sort(a);
1200 for i := 0 to 4 do Out.int(a[i]); Out.char(' '); end;
1201 Out.ln;
1202end;
1203
1204end Generics.
1205.Ed
1206.Bd -literal -offset indent
12075
1208tree
12091 1 3 4 5
1210.Ed
1211.Pp
1212Each import with its own arguments makes an instance: the module
1213compiled again, with
1214.Cm T
1215standing for the type given, and
1216.Cm less
1217calling the procedure given.
1218The arguments may name what the importing module declares later, as
1219.Cm before
1220is here.
1221The library's
1222.Cm List , Map , Vec ,
1223a growable array, and
1224.Cm Sort
1225are generic modules:
1226.Bd -literal -offset indent
1227import Count := Map([]const U8, INT, Str.hash, Str.eq);
1228.Ed
1229.Sh 14. TALKING TO C
1230.Bd -literal -offset indent
1231module Qsort;
1232import Out, Fmt, SYSTEM;
1233
1234link "libm.so.6";
1235
1236extern proc qsort(base: ^U8; n, size: UINT;
1237 less: proc(a, b: ^U8): I32);
1238extern proc cbrt(x: F64): F64;
1239
1240(* the order of two INTs, as C's qsort wants it *)
1241proc order(a, b: ^U8): I32;
1242var x, y: ^INT;
1243begin
1244 x := ^INT(a);
1245 y := ^INT(b);
1246 if x^ < y^ then return -1; elsif x^ > y^ then return 1; end;
1247 return 0;
1248end;
1249
1250proc main*;
1251var a: [5]INT; i: INT;
1252begin
1253 a := [30, 10, 50, 20, 40];
1254 qsort(^U8(SYSTEM.ADR(a)), LEN(a), SIZE(INT), order);
1255 for i := 0 to 4 do Out.int(a[i]); Out.char(' '); end;
1256 Out.ln;
1257 Fmt.print("{}\en", [Fmt.real(cbrt(27.0), 3)]);
1258end;
1259
1260end Qsort.
1261.Ed
1262.Bd -literal -offset indent
126310 20 30 40 50
12643.000
1265.Ed
1266.Pp
1267A module that says
1268.Cm "import SYSTEM"
1269may declare
1270.Cm extern
1271procedures and name libraries with
1272.Cm link .
1273An
1274.Cm extern
1275procedure is found by its name in the C library, or in a library a
1276.Cm link
1277line names.
1278Its parameters are integers, reals, pointers and procedures, as C
1279declares them; a raz procedure of such types can be given to C to call
1280back, as
1281.Cm order
1282is.
1283.Cm ^INT(a)
1284sees the address
1285.Cm a
1286as a pointer to an
1287.Cm INT .
1288A slice goes to C as two arguments,
1289.Cm SYSTEM.PTR(s)
1290and
1291.Cm LEN(s) ,
1292which an empty slice gives too (section 6).
1293.Pp
1294A program that uses C is linked against it dynamically, and starts
1295through it; one that doesn't is a static executable with nothing in it
1296but its own code.
1297.Cm Out
1298and C's
1299.Xr printf 3
1300keep two buffers, so a program that writes with both flushes one
1301before it writes with the other.
1302.Sh 15. THREADS
1303.Bd -literal -offset indent
1304module Hits;
1305import Out, Thread, SYSTEM;
1306
1307const Workers = 4;
1308
1309var
1310 hits: INT; (* added to by every thread at once, by XADD *)
1311 m: Thread.Mutex;
1312 total: INT; (* added to under m *)
1313
1314proc work(arg: ^U8);
1315var i, n, sum: INT;
1316begin
1317 n := INT(arg);
1318 sum := 0;
1319 for i := 1 to n do
1320 sum := sum + i;
1321 _ := XADD(hits, 1);
1322 end;
1323 Thread.lock(m);
1324 total := total + sum;
1325 Thread.unlock(m);
1326end;
1327
1328proc main*;
1329var t: [Workers]^Thread.Thread; i: INT; err: ERROR;
1330begin
1331 for i := 0 to Workers - 1 do
1332 t[i], err := Thread.spawn(work, ^U8(1000 * (i + 1)));
1333 if err # nil then Out.str(MSG(err)); Out.ln; return; end;
1334 end;
1335 for i := 0 to Workers - 1 do Thread.join(t[i]); end;
1336 Out.int(hits); Out.char(' '); Out.int(total); Out.ln;
1337end;
1338
1339end Hits.
1340.Ed
1341.Bd -literal -offset indent
134210000 15005000
1343.Ed
1344.Pp
1345.Cm Thread.spawn
1346runs a procedure in a thread of its own, with a stack of its own, and
1347.Cm Thread.join
1348waits for it to end.
1349.Cm XADD ,
1350.Cm CAS
1351and
1352.Cm XCHG
1353change a word atomically; a
1354.Cm Thread.Mutex
1355keeps a longer section to one thread at a time.
1356.Cm Out
1357and
1358.Cm Heap
1359lock themselves.
1360.Pp
1361.Cm Thread
1362makes its own threads, without C, in a program that doesn't use C; in
1363one that does, it makes them with C's
1364.Xr pthread_create 3
1365instead, and the program is the same.
1366.Cm Thread.signal
1367sends a signal to one thread alone, so that, with
1368.Cm Sys.handle ,
1369another thread can break into a read it waits in.
1370.Sh 16. FROM PASCAL AND C TO RAZ
1371.Bl -column "for (i=0; i<n; i++)" "for i := 0 to n-1 do" "Mem.free(Heap.heap, ^U8(p))"
1372.It Sy C Ta Sy Pascal Ta Sy raz
1373.It "#include" Ta "uses" Ta "import Out, Str;"
1374.It "static" Ta "implementation" Ta "a name without *"
1375.It "int, long" Ta "integer" Ta "I32, INT, I64"
1376.It "char *s" Ta "string" Ta "s: []U8"
1377.It "\(dqit's\(dq" Ta "'it''s'" Ta "\(dqit's\(dq"
1378.It "0xFF" Ta "$FF" Ta "0FFH"
1379.It "/* ... */" Ta "{ ... }" Ta "(* ... *), nesting"
1380.It "x == y" Ta "x = y" Ta "x = y"
1381.It "x != y" Ta "x <> y" Ta "x # y"
1382.It "a && b" Ta "a and b" Ta "a and b"
1383.It "x & m" Ta "x and m" Ta "x & m"
1384.It "i++" Ta "inc(i)" Ta "INC(i)"
1385.It "(long)x" Ta "longint(x)" Ta "I64(x)"
1386.It "if (c) {...}" Ta "if c then begin" Ta "if c then ... end;"
1387.It "for (i=0; i<n; i++)" Ta "for i := 0 to n-1 do" Ta "for i := 0 to n - 1 do"
1388.It "switch (c)" Ta "case c of" Ta "match c of | 1: ..."
1389.It "continue" Ta "continue" Ta "continue;"
1390.It "goto" Ta "goto" Ta "none"
1391.It "union" Ta "variant record" Ta "variant"
1392.It "struct p {...}" Ta "record ... end" Ta "record ... end"
1393.It "&x" Ta "@x" Ta "SYSTEM.ADR(x)"
1394.It "p->f" Ta "p^.f" Ta "p^.f"
1395.It "NULL" Ta "nil" Ta "nil"
1396.It "malloc(sizeof *p)" Ta "new(p)" Ta "NEW(p, Heap.heap)"
1397.It "free(p)" Ta "dispose(p)" Ta "Mem.free(Heap.heap, ^U8(p))"
1398.It "int f(int *out)" Ta "function f(var x)" Ta "proc f: (INT, INT);"
1399.It "void f(T *p)" Ta "procedure f(var p: T)" Ta "proc f(var p: T);"
1400.It "f(const T *p)" Ta "procedure f(const p: T)" Ta "proc f(const p: T);"
1401.It "return -1; errno" Ta "exceptions" Ta "return 0, NotFound;"
1402.It "(void)f(x);" Ta "f(x);" Ta "_ := f(x);"
1403.It "goto cleanup;" Ta "try ... finally" Ta "defer close(fd);"
1404.It "printf(...)" Ta "writeln(...)" Ta "Out.str(s), Fmt.print(...)"
1405.El
1406.Pp
1407And what neither has: every index is checked, every variable starts
1408at zero, and no two integer types mix in an expression.
1409.Sh SEE ALSO
1410.Xr raz 1 ,
1411.Xr raz-lib 3 ,
1412.Xr raz 7 ;
1413the report,
1414.Pa doc/raz.md ,
1415in raz's sources.