From ddd82658b079fe26fbb2bf5de875d475cffad42e Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:11:36 +0000 Subject: [PATCH] site: a fuller tour, and Beyond Go Raz, Set, Go: each of the 14 lessons has sections and several programs. Beyond Go: 18 lessons on the library, programs with no run time, code procedures and system calls, volatile, atomics and lock-free code. build.py runs every program with -Werror, and shell sessions too, so the output shown is real. --- diff --git a/site/build.py b/site/build.py index e696023..82bffac 100644 --- a/site/build.py +++ b/site/build.py @@ -8,7 +8,8 @@ tour's pages is run here, by ./raz, and the output shown is what it printed, so a lesson that stops working fails the build. -Lessons are site/content/NN-name.txt: +Lessons are site/content//NN-name.txt, one folder to a tour (see +TOURS below): title: Hello, world (the first lines are "key: value") part: Raz (the lessons are grouped in parts) @@ -25,6 +26,10 @@ printed; "fail" runs it and shows the failure it ends in. A block with nothing in it is taken from doc/raz-tutorial.7, whose programs make check already runs, by the module's name. + +Two other blocks: "```text" is shown as written, and "```sh" is a shell +session: each line that starts with "$ " is run in the lesson's folder, +with raz on the path, and shown with what it printed. """ import html, os, re, shutil, subprocess, sys, tempfile @@ -33,6 +38,12 @@ OUT = os.path.join(HERE, "public") RAZ = os.path.join(ROOT, "raz") REPO = "https://github.com/ldiaz94/raz" + +# folder in content/, folder in public/, name, the sentence under the name +TOURS = [ + ("tour", "tour", "Raz, Set, Go", "tour-intro.html"), + ("advanced", "advanced", "Beyond Go", "advanced-intro.html"), +] KEYWORDS = set("""and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc @@ -94,10 +105,32 @@ def run(directory, name): """(stdout, stderr, status) of the module name, compiled and run.""" - p = subprocess.run([RAZ, "run", name + ".raz"], cwd=directory, + p = subprocess.run([RAZ, "run", "-Werror", name + ".raz"], cwd=directory, capture_output=True, text=True, timeout=60) return p.stdout, p.stderr, p.returncode +def shell_html(directory, script): + """A session: each "$ command" line run in directory, with its output.""" + bin = os.path.join(directory, ".bin") + os.makedirs(bin, exist_ok=True) + if not os.path.exists(os.path.join(bin, "raz")): + os.symlink(RAZ, os.path.join(bin, "raz")) # raz finds lib/ by its real path + env = dict(os.environ, PATH=bin + ":" + os.environ["PATH"], + RAZLIB=os.path.join(ROOT, "lib")) + out = [] + for line in script.rstrip("\n").split("\n"): + if not line.startswith("$ "): + out.append(html.escape(line)) + continue + out.append('%s' % html.escape(line)) + p = subprocess.run(line[2:], shell=True, cwd=directory, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, timeout=60) + text = p.stdout.rstrip("\n") + if text: + out.append(html.escape(text)) + return '
%s
' % "\n".join(out) + def output_html(stdout, stderr): out = html.escape(stdout) if stderr: @@ -117,7 +150,9 @@ out = [] for para in re.split(r"\n\s*\n", text.strip()): lines = para.split("\n") - if all(l.startswith("- ") for l in lines): + if para.startswith("## "): + out.append("

%s

" % inline(para[3:])) + elif all(l.startswith("- ") for l in lines): out.append("" % "".join( "
  • %s
  • " % inline(l[2:]) for l in lines)) else: @@ -137,7 +172,7 @@ """The lesson's page content; runs its programs.""" parts, tmp = [], tempfile.mkdtemp() try: - chunks = re.split(r"^```raz ([^\n]*)\n(.*?)^```$", lesson["body"], + chunks = re.split(r"^```(raz [^\n]*|text|sh)\n(.*?)^```$", lesson["body"], flags=re.M | re.S) # chunks: text, info, code, text, info, code, ..., text for i in range(0, len(chunks), 3): @@ -145,7 +180,15 @@ parts.append(prose(chunks[i])) if i + 1 >= len(chunks): break - info, code = chunks[i + 1].split(), chunks[i + 2] + kind, code = chunks[i + 1], chunks[i + 2] + if kind == "text": + parts.append('
    %s
    ' + % html.escape(code.rstrip("\n"))) + continue + if kind == "sh": + parts.append(shell_html(tmp, code)) + continue + info = kind.split()[1:] name, flags = info[0], info[1:] if not code.strip(): code = tutorial_module(name) @@ -173,6 +216,7 @@ for key, href, label in [ ("home", "index.html", "raz"), ("tour", "tour/index.html", "Raz, Set, Go"), + ("advanced", "advanced/index.html", "Beyond Go"), ("spec", "spec.html", "Report"), ("get", "index.html#download", "Download")]) return """ @@ -199,16 +243,19 @@ with open(path, "w", encoding="utf-8") as f: f.write(text) -def build_tour(lessons): +def build_tour(tour, lessons, next_page): + """One tour's pages: a contents page and a page to each lesson. + next_page is (href, label) for what follows its last lesson.""" + folder, outdir, name, intro_file = tour parts = [] for l in lessons: if l["part"] not in parts: parts.append(l["part"]) + first = lambda p: 1 + next(i for i, x in enumerate(lessons) if x["part"] == p) for n, l in enumerate(lessons): toc = [] for p in parts: - toc.append("

    %s

      " % ( - p, 1 + next(i for i, x in enumerate(lessons) if x["part"] == p))) + toc.append("

      %s

        " % (p, first(p))) for i, x in enumerate(lessons): if x["part"] == p: cur = ' aria-current="page"' if i == n else "" @@ -223,29 +270,27 @@ pager += '' % ( lessons[n + 1]["slug"], html.escape(lessons[n + 1]["title"])) else: - pager += '' - body = ('
        ' + pager += '' % next_page + body = ('
        ' '

        %s · lesson %d of %d

        %s

        \n%s' '

        Save a program under its module’s name and run ' 'it with raz run Name.raz.

        ' '
        %s
        ') % ( - "\n".join(toc), l["part"], n + 1, len(lessons), + name, "\n".join(toc), l["part"], n + 1, len(lessons), html.escape(l["title"]), lesson_body(l), pager) - write("tour/%s.html" % l["slug"], page( - "%s - Raz, Set, Go" % l["title"], body, 1, "tour")) + write("%s/%s.html" % (outdir, l["slug"]), page( + "%s - %s" % (l["title"], name), body, 1, folder)) cards = [] for p in parts: - cards.append("

        %s

          " % ( - p, 1 + next(i for i, x in enumerate(lessons) if x["part"] == p))) + cards.append("

          %s

            " % (p, first(p))) for x in lessons: if x["part"] == p: cards.append('
          1. %s %s
          2. ' % ( x["slug"], html.escape(x["title"]), html.escape(x["summary"]))) cards.append("
          ") - intro = open(os.path.join(HERE, "content", "tour-intro.html"), - encoding="utf-8").read() - write("tour/index.html", page("Raz, Set, Go: a tour of raz", - '
          %s%s
          ' % (intro, "\n".join(cards)), 1, "tour")) + intro = open(os.path.join(HERE, "content", intro_file), encoding="utf-8").read() + write("%s/index.html" % outdir, page(name, + '
          %s%s
          ' % (intro, "\n".join(cards)), 1, folder)) def build_spec(): if not shutil.which("pandoc"): @@ -282,10 +327,19 @@ shutil.copy(os.path.join(HERE, "style.css"), OUT) names = sorted(f for f in os.listdir(os.path.join(HERE, "content")) if re.match(r"\d+-.*\.txt$", f)) - lessons = [read_lesson(os.path.join(HERE, "content", f)) for f in names] - build_tour(lessons) + counts = [] + for i, tour in enumerate(TOURS): + folder = os.path.join(HERE, "content", tour[0]) + lessons = [read_lesson(os.path.join(folder, f)) + for f in sorted(os.listdir(folder)) if re.match(r"\d+-.*\.txt$", f)] + if i + 1 < len(TOURS): + nxt = ("../%s/index.html" % TOURS[i + 1][1], TOURS[i + 1][2]) + else: + nxt = ("../spec.html", "The report") + build_tour(tour, lessons, nxt) + counts.append(len(lessons)) build_spec() build_home() - print("site/public: %d lessons" % len(lessons)) + print("site/public: %s lessons" % " + ".join(map(str, counts))) main() diff --git a/site/content/01-hello.txt b/site/content/01-hello.txt deleted file mode 100644 index 7c9ef68..0000000 --- a/site/content/01-hello.txt +++ /dev/null @@ -1,14 +0,0 @@ -title: Hello, world -part: Raz -summary: A module, an import and a procedure. ---- -Every raz program is a module with a `main` procedure. This is the smallest one that does something. - -```raz Hello run -``` - -A module lives in a file of its own name, `Hello.raz`, and its name comes again after its last `end`. `import Out` lets it use what the module `Out` exports, as `Out.str`. - -The `*` after `main` exports it; the program starts at the `main` of the module named on the command line. Every statement ends in `;`, even one that ends in `end`. - -Compile it and run it with `raz Hello.raz && ./Hello`, or with `raz run Hello.raz`, which writes no file. diff --git a/site/content/02-modules.txt b/site/content/02-modules.txt deleted file mode 100644 index 7f4db9b..0000000 --- a/site/content/02-modules.txt +++ /dev/null @@ -1,17 +0,0 @@ -title: Modules -part: Raz -summary: Exports, renaming, and a body that runs first. ---- -A program is a set of modules. Here is one, saved as `Greet.raz`: - -```raz Greet -``` - -and a program beside it that uses it: - -```raz Twice run -``` - -A name with `*` is exported; any other is the module's own. `G := Greet` imports `Greet` under a shorter name. Another module may read `G.count`, but only `Greet` may change it. - -The statements after a module's last `begin` are its body. It runs once, before `main`, which is why "Greet is ready" comes first. diff --git a/site/content/03-values.txt b/site/content/03-values.txt deleted file mode 100644 index a184562..0000000 --- a/site/content/03-values.txt +++ /dev/null @@ -1,14 +0,0 @@ -title: Values and conversions -part: Raz -summary: Sized integers that wrap, and nothing converts unasked. ---- -```raz Values run -``` - -The integers are `I8`, `I16`, `I32`, `I64` and `U8`, `U16`, `U32`, `U64`, and `INT` and `UINT`, as big as an address. `INT` is the everyday one: lengths, indexes and counts are `INT`s. The reals are `F32` and `F64`. - -Arithmetic wraps at the type's width and never stops the program, except dividing by zero. That is why `250 + 10` in a `U8` is 4. - -Two types never mix: with `i: I64`, `i < LEN(s)` is an error. A type's name converts, as `F64(n)` and `I64(b)` do above. The one silent conversion between numbers is an `INT` into an `I64`, which loses nothing. - -`#`, not `<>`, is "different". `and`, `or` and `not` are for `BOOL`s; `&`, `|`, `xor` and `~` are for the bits of integers. Every variable starts at zero. diff --git a/site/content/04-procedures.txt b/site/content/04-procedures.txt deleted file mode 100644 index 780a5c6..0000000 --- a/site/content/04-procedures.txt +++ /dev/null @@ -1,10 +0,0 @@ -title: Procedures and several results -part: Raz -summary: Return two values, change a variable, pass a procedure. ---- -```raz Procs run -``` - -A parameter is a copy, unless it is `var`, when it is the caller's variable itself. A procedure may return several results, which a multiple assignment takes apart; the blank, `_`, drops one. - -A procedure is a value too, of a procedure type, as `f` is in `twice`. A procedure without parameters leaves out the parentheses, as `Out.ln` does. Procedures don't nest, and a name is declared before it is used. diff --git a/site/content/05-slices.txt b/site/content/05-slices.txt deleted file mode 100644 index e4297b8..0000000 --- a/site/content/05-slices.txt +++ /dev/null @@ -1,12 +0,0 @@ -title: Arrays, slices and strings -part: Set -summary: Five in a row, a window onto them, and bytes in UTF-8. ---- -```raz Slices run -``` - -`[5]INT` is an array: five `INT`s in a row, copied when it is assigned. `[]INT` is a slice: a pointer to elements that live elsewhere, and their number, `LEN(s)`. `a[lo..hi]` is the slice of the elements from `lo` up to, but not including, `hi`, and an array goes silently where a slice is wanted. - -A string is a slice of bytes, `[]U8`, in UTF-8, and its bytes are constant; a `[8]U8` made from one is a copy. Arrays and slices of integers compare with `=` and `#`; `Str` has the rest: ordering, finding, hashing and reading a number. - -A `for` loop takes its bounds once, and never steps past the last: with an empty slice, `0 to LEN(s) - 1` doesn't run at all. diff --git a/site/content/06-records.txt b/site/content/06-records.txt deleted file mode 100644 index 5f189d6..0000000 --- a/site/content/06-records.txt +++ /dev/null @@ -1,10 +0,0 @@ -title: Records and pointers -part: Set -summary: Laid out as C lays out a struct, reached through ^. ---- -```raz Boxes run -``` - -A record is laid out as C lays out a struct. `{lo: ..., hi: ...}` builds one, naming its fields; the ones it leaves out are zero. - -`^Box` is a pointer to a `Box`, `ADR(b)` the address of `b`, and `b^` what a pointer points at. A pointer is never the record: it is `b^.lo`, never `b.lo`. diff --git a/site/content/07-variants.txt b/site/content/07-variants.txt deleted file mode 100644 index c33f20b..0000000 --- a/site/content/07-variants.txt +++ /dev/null @@ -1,10 +0,0 @@ -title: Enumerations, sets, variants and match -part: Set -summary: Choices the compiler can check you handled. ---- -```raz Shapes run -``` - -An enumeration is a list of names, in order; a `set of` it holds any choice of them, in the bits of a word, with `in`, `+` for union, `*` for intersection and `-` for difference. - -A variant holds one of its cases, each with fields of its own, and `match` is the only way to read them: it runs the arm of the case the variant holds, naming its fields. Every case has an arm, unless an `| else:` comes last. On an integer, `match` takes constants and ranges, and must have an `| else:`. diff --git a/site/content/08-memory.txt b/site/content/08-memory.txt deleted file mode 100644 index bd94ccf..0000000 --- a/site/content/08-memory.txt +++ /dev/null @@ -1,12 +0,0 @@ -title: Memory and allocators -part: Set -summary: No garbage collector; you choose where memory comes from. ---- -```raz Stack run -``` - -raz has no garbage collector, and no allocator of its own: memory comes from an allocator, a `Mem.Allocator`, which the program chooses and passes. - -`NEW(n, a)` sets `n` to a fresh, zeroed `Node` from `a`, or to `nil` if `a` has no room. `Heap.heap` is the general one, which `Mem.free` gives memory back to. An `Arena` hands out memory from one block and frees it all at once, as the last lines do. - -`Buf`, `List` and `Map` take the allocator they use from `init`. diff --git a/site/content/09-errors.txt b/site/content/09-errors.txt deleted file mode 100644 index 3a26d54..0000000 --- a/site/content/09-errors.txt +++ /dev/null @@ -1,10 +0,0 @@ -title: Errors -part: Go -summary: A second result, compared by identity. No exceptions. ---- -```raz Errors run -``` - -A procedure that can fail returns an `ERROR` beside its result, and `nil` when it didn't. Each `ERROR` constant is an error of its own, compared with `=` by which declaration made it, never by its message; `MSG(err)` is the message. - -An exported one, as `Empty` is here, lets the callers tell it from the others. raz has no exceptions. diff --git a/site/content/10-defer.txt b/site/content/10-defer.txt deleted file mode 100644 index 5963a06..0000000 --- a/site/content/10-defer.txt +++ /dev/null @@ -1,10 +0,0 @@ -title: Defer -part: Go -summary: Clean up beside the line that needs it. ---- -```raz Defers run -``` - -`defer s;` runs `s` when the program leaves the statements the `defer` stands in: at their end, or by a `return` or a `break`. Deferred statements run the last first, and only those whose `defer` was reached. - -So a file is closed beside the line that opens it, however the procedure ends. diff --git a/site/content/11-checks.txt b/site/content/11-checks.txt deleted file mode 100644 index 469a973..0000000 --- a/site/content/11-checks.txt +++ /dev/null @@ -1,12 +0,0 @@ -title: When it goes wrong -part: Go -summary: Every index is checked, and a failure tells you everything. ---- -```raz Fail fail -``` - -Every index and slice is checked. A failed check says where it failed and with what values, then the calls under way with their variables, and ends the program with status 2. So do a `nil` pointer, a division by zero and a stack overflow. - -A module that is sure of its indexes may say `check off;` after its imports, for speed; an index out of range there reads or writes whatever it reaches. - -The program carries line numbers for gdb, and `RAZ_PROFILE=1` in its environment has it say where its time went. diff --git a/site/content/12-generics.txt b/site/content/12-generics.txt deleted file mode 100644 index 1074fb6..0000000 --- a/site/content/12-generics.txt +++ /dev/null @@ -1,17 +0,0 @@ -title: Generic modules -part: Go -summary: A module that takes types and procedures as arguments. ---- -A module may take types, and the procedures it needs on them, as parameters. `Biggest.raz`: - -```raz Biggest -``` - -and a program that uses it: - -```raz Generics run -``` - -Each import with its own arguments makes an instance: the module compiled again, with `T` standing for the type given, and `less` calling the procedure given. The arguments may name what the importing module declares later, as `before` is here. - -The library's `List`, `Map` and `Sort` are generic modules: `import Count := Map([]U8, INT, Str.hash, Str.eq);` diff --git a/site/content/13-c.txt b/site/content/13-c.txt deleted file mode 100644 index 147ac9e..0000000 --- a/site/content/13-c.txt +++ /dev/null @@ -1,10 +0,0 @@ -title: Talking to C -part: Go -summary: Call a C library, and be called back. ---- -```raz Qsort run -``` - -An `extern` procedure is found by its name in the C library, or in a library a `link` line names. Its parameters are integers, reals, pointers and procedures, as C declares them; a raz procedure of such types can be given to C to call back, as `order` is. - -A program that uses C is linked against it dynamically and starts through it; one that doesn't is a static executable with nothing in it but its own code. diff --git a/site/content/14-threads.txt b/site/content/14-threads.txt deleted file mode 100644 index 32e18fa..0000000 --- a/site/content/14-threads.txt +++ /dev/null @@ -1,12 +0,0 @@ -title: Threads -part: Go -summary: Native threads, atomics and a mutex. ---- -```raz Hits run -``` - -`Thread.spawn` runs a procedure in a thread of its own, with a stack of its own, and `Thread.join` waits for it to end. `XADD`, `CAS` and `XCHG` change a word atomically; a `Thread.Mutex` keeps a longer section to one thread at a time. `Out` and `Heap` lock themselves. - -`Thread` makes its own threads, without C, so a program that uses it can't use C; one that does makes its threads with C's `pthread_create` instead. - -That is the tour. The rest is in [the report](../spec.html), and the library's interfaces are printed by `tools/Doc.raz`. diff --git a/site/content/advanced-intro.html b/site/content/advanced-intro.html new file mode 100644 index 0000000..4788ff0 --- /dev/null +++ b/site/content/advanced-intro.html @@ -0,0 +1,10 @@ +

          Beyond Go

          +

          The second tour, for the part of raz that sits close to the machine. It +assumes you have taken Raz, Set, Go or know +Pascal or C well enough not to need it.

          +

          It has four parts: The library, the modules every program +reaches for; Standing alone, programs that need no C and no +run time; The machine, procedures written in assembly and +direct system calls; and Shared memory, volatile accesses, +atomics and threads. Every program is compiled and run when this page is +made, as before.

          diff --git a/site/content/advanced/01-fmt.txt b/site/content/advanced/01-fmt.txt new file mode 100644 index 0000000..bb87309 --- /dev/null +++ b/site/content/advanced/01-fmt.txt @@ -0,0 +1,164 @@ +title: Output and formatting +part: The library +summary: Out's buffer, Fmt's arguments, formatting into a Buf, and laying out columns. +--- +The first tour used `Out` for everything it printed. Two modules do the work: `Out`, which owns standard output and its buffer, and `Fmt`, which turns values into text. + +## What `Out` does with its buffer + +`Out` keeps a buffer of 4 KB. It writes it out when it is full, at each line feed when standard output is a terminal, at `Out.flush`, and when the program ends by `Rt.exit` (which a normal end and a failed check both are). A lock keeps what each call writes together when threads write at once. + +You can see the effect with `strace`, which lists the system calls a program makes. A program that prints three lines to a file makes one `write`: + +```raz Three +module Three; +import Out; + +proc main*; +begin + Out.str("one\n"); + Out.str("two\n"); + Out.str("three\n"); +end; + +end Three. +``` + +```sh +$ raz Three.raz +$ strace -e trace=write ./Three > /dev/null +``` + +Three lines, one system call. That is why `Out` is cheap, and why a program that mixes it with C's `printf`, which keeps a buffer of its own, must flush one before the other. + +## `Fmt.print` + +`Fmt.print(format, args)` writes to standard output. Each `{}` in the format takes the next argument, and `{{` and `}}` stand for the braces. The arguments are a slice of `Fmt.Arg`, a variant, so each is built with the constructor for its kind: `int`, `uint`, `hex`, `str`, `char`, `bool` and `real`, which takes the number of digits after the point. + +```raz Kinds run +module Kinds; +import Fmt; + +proc main*; +var big: U64; small: I8; +begin + big := 0FFFFFFFFFFFFFFFFH; + small := -5; + Fmt.print("int {}, uint {}, hex {}\n", + [Fmt.int(-42), Fmt.uint(big), Fmt.hex(255)]); + Fmt.print("str {}, char {}, bool {}\n", + [Fmt.str("hi"), Fmt.char('x'), Fmt.bool(1 < 2)]); + Fmt.print("real {} and {} and {}\n", + [Fmt.real(3.14159, 2), Fmt.real(2.5, 0), Fmt.real(1.0 / 3.0, 9)]); + Fmt.print("an I8: {}; braces: {{ and }}\n", [Fmt.int(I64(small))]); +end; + +end Kinds. +``` + +An argument whose type is wrong doesn't compile: there is no `%d` that disagrees with its argument. A `{}` with no argument left prints nothing, and arguments left over are not printed, so a mismatch shows up as missing text, never as a crash or as memory read by mistake. + +## Into a buffer + +`Fmt.write(b, format, args)` does the same into a `Buf` instead of standard output. That is how a message is built to send somewhere else: a file, a socket, a window, a string kept for later. + +```raz Message run +module Message; +import Out, Buf, Fmt, Heap; + +(* "name (age n)", built in a Buf the caller owns *) +proc describe(b: ^Buf.Buf; name: []U8; age: INT); +begin + Fmt.write(b, "{} (age {})", [Fmt.str(name), Fmt.int(age)]); +end; + +proc main*; +var b: Buf.Buf; +begin + Buf.init(ADR(b), Heap.heap); + defer Buf.done(ADR(b)); + describe(ADR(b), "Ada", 36); + Buf.str(ADR(b), "; "); + describe(ADR(b), "Grace", 45); + Out.str(Buf.bytes(ADR(b))); Out.ln; + Out.int(b.len); Out.str(" bytes\n"); +end; + +end Message. +``` + +## Columns + +`Fmt` writes values as they are, with no widths. A program that wants columns pads in one small procedure and uses it everywhere, which is easier to read than a format language. + +```raz Table run +module Table; +import Out; + +(* s, then spaces up to width *) +proc left(s: []U8; width: INT); +var i: INT; +begin + Out.str(s); + for i := LEN(s) to width - 1 do Out.char(' '); end; +end; + +(* n, right aligned in width *) +proc right(n: INT; width: INT); +var digits: INT; v: INT; i: INT; +begin + digits := 1; + v := n; + if v < 0 then INC(digits); v := -v; end; + while v >= 10 do INC(digits); v := v div 10; end; + for i := digits to width - 1 do Out.char(' '); end; + Out.int(n); +end; + +proc row(name: []U8; qty, price: INT); +begin + left(name, 10); + right(qty, 5); + right(price, 8); + right(qty * price, 9); + Out.ln; +end; + +proc main*; +begin + Out.str("item qty price total\n"); + row("bolts", 120, 3); + row("washers", 1000, 1); + row("gears", 8, 250); + row("shims", 12, -4); +end; + +end Table. +``` + +## Writing numbers in other bases + +`Out.hex(n, digits)` writes `n` in hexadecimal, padded with zeros to `digits`. A binary dump is a `for` loop over a slice, one `Out.hex(U64(b), 2)` to a byte. + +```raz Dump run +module Dump; +import Out; + +proc dump(data: []U8); +var i: INT; +begin + for i := 0 to LEN(data) - 1 do + if i > 0 then Out.char(' '); end; + Out.hex(U64(data[i]), 2); + end; + Out.ln; +end; + +proc main*; +begin + dump("raz\n"); + dump("\u{3BB}"); +end; + +end Dump. +``` diff --git a/site/content/advanced/02-bytes.txt b/site/content/advanced/02-bytes.txt new file mode 100644 index 0000000..186f834 --- /dev/null +++ b/site/content/advanced/02-bytes.txt @@ -0,0 +1,166 @@ +title: Strings and bytes +part: The library +summary: Copying, hashing and ordering strings, and reading and writing binary formats. +--- +A `[]U8` is both a string and a block of bytes. `Str` has what is done with them: comparing, finding, hashing, copying into memory of your own, UTF-8, numbers, and the fixed byte orders of file formats and network protocols. + +## Ordering and hashing + +`Str.cmp` gives -1, 0 or 1, byte by byte, so it orders UTF-8 text by code point. `Str.eq` is equality. `Str.hash` is FNV-1a, 64 bits; it is what a `Map` of strings uses. + +```raz Order run +module Order; +import Out, Str, Fmt; + +proc main*; +var names: [4][]U8; i, j: INT; t: []U8; +begin + names := ["pear", "Apple", "fig", "apple"]; + (* a small insertion sort, with Str.cmp *) + for i := 1 to 3 do + t := names[i]; + j := i - 1; + while (j >= 0) and (Str.cmp(names[j], t) > 0) do + names[j + 1] := names[j]; + DEC(j); + end; + names[j + 1] := t; + end; + for i := 0 to 3 do Out.str(names[i]); Out.char(' '); end; + Out.ln; + Fmt.print("{}\n", [Fmt.hex(Str.hash("raz"))]); + if Str.hash("raz") = Str.hash("raz") then Out.str("stable\n"); end; +end; + +end Order. +``` + +Upper case sorts before lower, since 'A' is 65 and 'a' is 97: `Str.cmp` doesn't pretend to know a language's alphabet. + +## Keeping a string + +A slice of a string constant lives forever, but a slice of a buffer lives only as long as the buffer. To keep one past that, `Str.copy` takes memory from an allocator and says whether it got any. + +```raz Keep run +module Keep; +import Out, Str, Heap, Mem; + +type Entry = record name: []U8; n: INT; end; + +var entries: [3]Entry; + +(* remembers a name that the caller will overwrite *) +proc remember(slot: INT; name: []U8); +var copy: []U8; ok: BOOL; +begin + copy, ok := Str.copy(Heap.heap, name); + if ok then entries[slot].name := copy; entries[slot].n := slot; end; +end; + +proc main*; +var scratch: [16]U8; i: INT; +begin + for i := 0 to 2 do + scratch := "name-"; + scratch[5] := U8('0' + i); + remember(i, scratch[0..6]); + scratch := "overwritten!"; + end; + for i := 0 to 2 do + Out.str(entries[i].name); Out.char(' '); + Mem.free(Heap.heap, ^U8(ADR(entries[i].name[0]))); + end; + Out.ln; +end; + +end Keep. +``` + +## Binary formats + +A file format or a network protocol has a byte order of its own, not the machine's. `Str.le` and `Str.be` read an unsigned number of up to 8 bytes in a fixed order (little- or big-endian) and `Str.putLE` and `Str.putBE` write one. They work on any slice, so a header is read where it lies, with no struct to overlay and no byte swapping to forget. + +Here is a small record format: a 4-byte tag, a 2-byte big-endian length, a 4-byte little-endian checksum, then the data. + +```raz Frame run +module Frame; +import Out, Fmt, Str; + +const HeaderSize = 10; + +(* the sum of the bytes of data, all mod 2^32 *) +proc checksum(data: []U8): U32; +var i: INT; sum: U32; +begin + for i := 0 to LEN(data) - 1 do sum := sum + U32(data[i]); end; + return sum; +end; + +(* writes a frame to out, which must have room; its length *) +proc pack(out: []U8; tag, data: []U8): INT; +begin + COPY(out[0..4], tag); + Str.putBE(out[4..6], U64(LEN(data))); + Str.putLE(out[6..10], U64(checksum(data))); + COPY(out[HeaderSize..HeaderSize + LEN(data)], data); + return HeaderSize + LEN(data); +end; + +proc main*; +var buf: [64]U8; n, len: INT; sum: U32; i: INT; +begin + n := pack(buf, "DATA", "hello"); + for i := 0 to n - 1 do + Out.hex(U64(buf[i]), 2); Out.char(' '); + end; + Out.ln; + (* and back *) + len := INT(Str.be(buf[4..6])); + sum := U32(Str.le(buf[6..10])); + Fmt.print("tag {}, {} bytes, checksum {}, ", [Fmt.str(buf[0..4]), Fmt.int(len), Fmt.hex(U64(sum))]); + if sum = checksum(buf[HeaderSize..HeaderSize + len]) then + Out.str("valid: "); Out.str(buf[HeaderSize..HeaderSize + len]); + else + Out.str("corrupt"); + end; + Out.ln; +end; + +end Frame. +``` + +The output is the same on a little-endian and a big-endian machine, because the bytes are written one at a time in the order the format says. + +## Numbers and text + +`Str.toInt` reads a decimal number with an optional sign and nothing else, and says whether it was one. `Fmt` goes the other way. `Str.encode` and `Str.decode` move between characters and UTF-8, as the first tour showed. + +```raz Numbers run +module Numbers; +import Out, Str; + +(* the sum of the numbers in a comma separated list, or -1 if any isn't *) +proc total(s: []U8): I64; +var start, i: INT; sum, n: I64; ok: BOOL; +begin + start := 0; + for i := 0 to LEN(s) do + if (i = LEN(s)) or (s[i] = ',') then + n, ok := Str.toInt(s[start..i]); + if not ok then return -1; end; + sum := sum + n; + start := i + 1; + end; + end; + return sum; +end; + +proc main*; +begin + Out.int(total("10,20,-5,+7")); Out.ln; + Out.int(total("10,x,20")); Out.ln; + Out.int(total("10,,20")); Out.ln; +end; + +end Numbers. +``` diff --git a/site/content/advanced/03-collections.txt b/site/content/advanced/03-collections.txt new file mode 100644 index 0000000..0b91f7f --- /dev/null +++ b/site/content/advanced/03-collections.txt @@ -0,0 +1,129 @@ +title: Lists, maps and sorting +part: The library +summary: List(T), Map(K, V) and Sort(T), put together in a word-frequency program. +--- +The three generic modules are instantiated like any other generic module, with the types and procedures they need. All three take their memory from an allocator you give them; none of them allocates anything you didn't ask for. + +## `List(T)` + +A singly linked list with `push` at the front, `pop` from the front, and the nodes exported, so a program walks it itself. Both can fail if the allocator is out of room, and say so. + +```raz Pile run +module Pile; +import Out, Heap, Ints := List(INT); + +proc main*; +var l: Ints.List; n: ^Ints.Node; v: INT; +begin + Ints.init(ADR(l), Heap.heap); + defer Ints.clear(ADR(l)); + for v := 1 to 5 do _ := Ints.push(ADR(l), v * v); end; + Ints.reverse(ADR(l)); (* oldest first *) + n := l.head; + while n # nil do Out.int(n^.val); Out.char(' '); n := n^.next; end; + Out.ln; + v, _ := Ints.pop(ADR(l)); + Out.int(v); Out.str(" popped, "); Out.int(l.len); Out.str(" left\n"); +end; + +end Pile. +``` + +## `Map(K, V; hash, eq)` + +A hash map. Its key's hash and equality are procedure arguments, so any type can be a key. `put` replaces what a key maps to; `get` says what it maps to and whether it maps to anything; `remove` says whether the key was there. `next` walks the map: from 0, it gives the next entry and the number to pass for the one after, and -1 when there are no more. + +```raz Ages run +module Ages; +import Out, Fmt, Str, Heap, Book := Map([]U8, INT, Str.hash, Str.eq); + +proc main*; +var m: Book.Map; age: INT; found, ok: BOOL; i: INT; v: INT; +begin + Book.init(ADR(m), Heap.heap); + _ := Book.put(ADR(m), "ada", 36); + _ := Book.put(ADR(m), "grace", 45); + _ := Book.put(ADR(m), "alan", 41); + _ := Book.put(ADR(m), "ada", 37); (* replaces *) + age, found := Book.get(ADR(m), "ada"); + Fmt.print("ada: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]); + age, found := Book.get(ADR(m), "linus"); + Fmt.print("linus: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]); + ok := Book.remove(ADR(m), "alan"); + Fmt.print("{} entries, removed {}\n", [Fmt.int(m.len), Fmt.bool(ok)]); + v := 0; + i, _, age := Book.next(ADR(m), 0); + while i >= 0 do + INC(v, age); + i, _, age := Book.next(ADR(m), i); + end; + Out.int(v); Out.str(" years in all\n"); +end; + +end Ages. +``` + +A map's order is its own, so a program that wants an order collects the entries and sorts them, as the next section does. + +## `Sort(T; less)` + +An in-place sort of a slice, by a `less` procedure, in `n log n` at most and with no memory of its own. Elements equal by `less` may change places. + +## Putting them together + +Counting words, then listing them by count and then alphabetically: a `Map` for the counts, an array of records to sort, and `Sort` with a two-level `less`. + +```raz Freq run +module Freq; +import Fmt, Str, Heap, + Count := Map([]U8, INT, Str.hash, Str.eq), + Rank := Sort(Entry, before); + +type Entry = record word: []U8; n: INT; end; + +const Text = "the cat and the hat and the bat sat on the mat and the cat sat"; + +(* more first; equal counts alphabetically *) +proc before(a, b: Entry): BOOL; +begin + if a.n # b.n then return a.n > b.n; end; + return Str.cmp(a.word, b.word) < 0; +end; + +proc main*; +var + m: Count.Map; entries: [32]Entry; i, start, k, n, found: INT; + w: []U8; key: []U8; v: INT; +begin + Count.init(ADR(m), Heap.heap); + start := 0; + for i := 0 to LEN(Text) do + if (i = LEN(Text)) or (Text[i] = ' ') then + w := Text[start..i]; + k, _ := Count.get(ADR(m), w); + _ := Count.put(ADR(m), w, k + 1); + start := i + 1; + end; + end; + n := 0; + found, key, v := Count.next(ADR(m), 0); + while found >= 0 do + entries[n].word := key; + entries[n].n := v; + INC(n); + found, key, v := Count.next(ADR(m), found); + end; + Rank.sort(entries[0..n]); + for i := 0 to n - 1 do + Fmt.print("{} {}\n", [Fmt.int(entries[i].n), Fmt.str(entries[i].word)]); + end; +end; + +end Freq. +``` + +The keys here are slices of the constant text, so they outlive the map; a program whose keys come from a buffer it will reuse copies them first with `Str.copy`. + +## Choosing + +Use a `List` when you push and pop at one end and walk it in order. Use a `Map` when you look things up by key. Use an array and `Sort` when you know the size and want an order. When none of them fits, they are each under a hundred lines of raz in `lib/`, and the advanced tour's allocator lesson shows what is underneath. diff --git a/site/content/advanced/04-files.txt b/site/content/advanced/04-files.txt new file mode 100644 index 0000000..00d3dd0 --- /dev/null +++ b/site/content/advanced/04-files.txt @@ -0,0 +1,187 @@ +title: Files and the command line +part: The library +summary: Whole files with Files, descriptors and directories with Sys, and options with Opt. +--- +`Files` is for the common case: a whole file read or written in one call. `Sys` is the system underneath, for everything else. `Opt` reads a command line from a table, so that the help and the error messages can't drift from the code. + +## A whole file + +`Files.write(path, data)` makes the file hold `data`, and `Files.read(path, b)` adds the whole file to a `Buf`. Both say whether they worked. + +```raz Notes run +module Notes; +import Out, Files, Buf, Heap; + +proc main*; +var b: Buf.Buf; ok: BOOL; +begin + ok := Files.write("notes.txt", "first line\nsecond line\n"); + if not ok then Out.str("can't write\n"); return; end; + Buf.init(ADR(b), Heap.heap); + defer Buf.done(ADR(b)); + ok := Files.read("notes.txt", ADR(b)); + if ok then + Out.int(b.len); Out.str(" bytes: "); Out.str(Buf.bytes(ADR(b))); + end; + ok := Files.read("missing.txt", ADR(b)); + if not ok then Out.str("missing.txt: not there\n"); end; +end; + +end Notes. +``` + +## Descriptors + +Underneath, a file is a descriptor, an `INT`. `Sys.open` takes the path and the way to open it as a set; `read`, `write`, `seek` and `close` do what they say. A result that can fail is a number, and minus an errno if it failed, as on Linux itself. Reading in a loop is the pattern for anything too big to hold at once. + +```raz Count run +module Count; +import Out, Sys; + +(* the lines of the file at path, or minus an errno *) +proc lines(path: []U8): INT; +var fd, n, i, count: INT; buf: [4096]U8; +begin + fd := Sys.openRead(path); + if fd < 0 then return fd; end; + defer Sys.close(fd); + n := Sys.read(fd, buf); + while n > 0 do + for i := 0 to n - 1 do + if buf[i] = '\n' then INC(count); end; + end; + n := Sys.read(fd, buf); + end; + if n < 0 then return n; end; + return count; +end; + +proc main*; +var fd: INT; pos: I64; +begin + fd := Sys.create("log.txt"); + _ := Sys.write(fd, "a\nb\nc\n"); + pos := Sys.seek(fd, 2, false); (* from the start *) + Out.int(pos); Out.ln; + Sys.close(fd); + Out.int(lines("log.txt")); Out.str(" lines\n"); + Out.int(lines("/no/such/file")); Out.ln; (* -2: ENOENT *) + fd := Sys.open("log.txt", {Sys.writing, Sys.appending}); + _ := Sys.write(fd, "d\n"); + Sys.close(fd); + Out.int(lines("log.txt")); Out.str(" lines now\n"); +end; + +end Count. +``` + +## Looking at a file, and a directory + +`Sys.info` says a file's size, modification time, permissions, and whether it is a directory, a regular file or a link. `Sys.openDir` and `nextEntry` list a directory, in no particular order, so a program that prints one sorts it first. A name from `nextEntry` is good only until the next call, so the program keeps a copy. + +```raz Tree run +module Tree; +import Out, Sys, Str, Heap, Mem, Buf, Order := Sort([]U8, before); + +proc before(a, b: []U8): BOOL; +begin + return Str.cmp(a, b) < 0; +end; + +(* a file made to hold text *) +proc put(path, text: []U8); +var fd: INT; +begin + fd := Sys.create(path); + _ := Sys.write(fd, text); + Sys.close(fd); +end; + +proc main*; +var + d: Sys.Dir; name, copy: []U8; more, ok: BOOL; i, n: INT; + info: Sys.Info; err: INT; names: [16][]U8; path: Buf.Buf; +begin + _ := Sys.makeDir("proj"); + _ := Sys.makeDir("proj/src"); + put("proj/b.txt", "bb"); + put("proj/a.txt", "a"); + if Sys.openDir(ADR(d), "proj") < 0 then return; end; + n := 0; + name, more := Sys.nextEntry(ADR(d)); + while more do + copy, ok := Str.copy(Heap.heap, name); + if ok and (n < 16) then names[n] := copy; INC(n); end; + name, more := Sys.nextEntry(ADR(d)); + end; + Sys.closeDir(ADR(d)); + Order.sort(names[0..n]); + Buf.init(ADR(path), Heap.heap); + for i := 0 to n - 1 do + Buf.reset(ADR(path)); + Buf.str(ADR(path), "proj/"); + Buf.str(ADR(path), names[i]); + info, err := Sys.info(Buf.bytes(ADR(path))); + Out.str(names[i]); + if err < 0 then Out.str(" ?"); + elsif info.dir then Out.str("/"); + else Out.str(", "); Out.int(info.size); Out.str(" bytes"); + end; + Out.ln; + Mem.free(Heap.heap, ^U8(ADR(names[i][0]))); + end; + Buf.done(ADR(path)); +end; + +end Tree. +``` + +## A command line, from a table + +A program describes its options once, in a table of `Opt.Row`s: its synopsis lines, its subcommands and its options. The help and the error messages are made from the table. The parser reads by the rules of the C library's `getopt` with GNU's long options, so `-vn3`, `-n 3`, `--count=3` and `--count 3` all work, and `--` ends the options. + +```raz Tool +module Tool; +import Out, Fmt, Opt; + +const count = 1; (* the key of --count, which has no letter *) + +proc main*; +var p: Opt.Parser; verbose: BOOL; n, i: INT; w: []U8; ok: BOOL; +begin + n := 1; + Opt.init(ADR(p), "tool", [ + Opt.usage("", "tool [-v] [--count n] word ..."), + Opt.option("", 'v', "verbose", "", "say more"), + Opt.option("", count, "count", "n", "repeat each word n times")]); + while Opt.next(ADR(p)) do + if p.letter = 'v' then verbose := true; + elsif p.letter = count then n := INT(Opt.number(ADR(p), 1, 5)); + end; + end; + w, ok := Opt.operand(ADR(p)); + if not ok then Opt.fail(ADR(p), "no words; see tool -h"); end; + while ok do + for i := 1 to n do + if verbose then Out.str("word: "); end; + Fmt.print("{}\n", [Fmt.str(w)]); + end; + w, ok := Opt.operand(ADR(p)); + end; +end; + +end Tool. +``` + +```sh +$ raz Tool.raz +$ ./Tool -h +$ ./Tool -v hello world +$ ./Tool --count 9 hello; echo "status $?" +$ ./Tool -x; echo "status $?" +$ ./Tool; echo "status $?" +``` + +`-h` and `--help` are `Opt`'s: the program never sees them. A mistake on the command line is a sentence on standard error with the program's name first, then the synopsis, and status 2. Nothing in `Tool` wrote any of that. + +A mistake in the table itself, such as an option given twice, is the program's, and `init` says so and ends with status 1 before it reads a word. diff --git a/site/content/advanced/05-processes.txt b/site/content/advanced/05-processes.txt new file mode 100644 index 0000000..c91a7b8 --- /dev/null +++ b/site/content/advanced/05-processes.txt @@ -0,0 +1,156 @@ +title: Time, randomness and other programs +part: The library +summary: Clocks, sleeping, random bytes, and running a program with its output piped back. +--- +Everything here is in `Sys`, and is the same procedures on every target raz supports: through system calls on Linux, through the C library elsewhere. + +## Clocks and sleeping + +`Sys.clock` is a clock that only goes forward, in nanoseconds: the one to measure a duration with. `Sys.now` is the wall clock, in nanoseconds since 1970 UTC, which can be set backwards, so it is for dates, not durations. `Sys.sleep` waits some milliseconds. + +```raz Timing run +module Timing; +import Out, Sys; + +proc main*; +var t0, t1, elapsed: I64; wall: I64; +begin + t0 := Sys.clock(); + Sys.sleep(25); + t1 := Sys.clock(); + elapsed := (t1 - t0) div 1000000; (* milliseconds *) + if (elapsed >= 25) and (elapsed < 1000) then + Out.str("slept about 25 ms\n"); + end; + wall := Sys.now(); + if wall > 1700000000000000000 then Out.str("after 2023\n"); end; +end; + +end Timing. +``` + +Every duration is an `I64` of nanoseconds, because a 32-bit `INT` would hold only a couple of seconds of them. The library's rule is that what may overflow a small target's `INT` is an `I64`. + +## Random bytes + +`Sys.random` fills a slice with random bytes from the system. Anything else is made from that: a number in a range, a shuffle. + +```raz Dice run +module Dice; +import Out, Sys, Str; + +(* a number from 0 up to n, without bias *) +proc below(n: INT): INT; +var b: [8]U8; x, limit: U64; +begin + limit := 0FFFFFFFFFFFFFFFFH - (0FFFFFFFFFFFFFFFFH mod U64(n)) - 1; + Sys.random(b); + x := Str.le(b); + while x > limit do + Sys.random(b); + x := Str.le(b); + end; + return INT(x mod U64(n)); +end; + +proc main*; +var counts: [6]INT; i: INT; ok: BOOL; +begin + for i := 1 to 6000 do INC(counts[below(6)]); end; + ok := true; + for i := 0 to 5 do + if (counts[i] < 800) or (counts[i] > 1200) then ok := false; end; + end; + if ok then Out.str("all six faces came up about a thousand times\n"); end; +end; + +end Dice. +``` + +## Running a program + +`Sys.spawn` starts the program at a path with its arguments, environment, working directory and standard streams in a `Sys.Program` record. A zero field means this program's own. `Sys.wait` waits for it to end and says how: `exited` with its status, `killed` by a signal, or `stopped`. + +```raz Run run +module Run; +import Out, Sys; + +proc main*; +var p: Sys.Program; pid, status: INT; how: Sys.Status; +begin + p := {path: "/bin/echo", args: ["echo", "hello from a child"]}; + pid := Sys.spawn(p); + if pid < 0 then Out.str("can't start\n"); return; end; + Out.flush; (* so that our text isn't behind the child's *) + _, how, status := Sys.wait(pid, true); + if how = Sys.exited then + Out.str("it exited with "); Out.int(status); Out.ln; + end; +end; + +end Run. +``` + +## Capturing its output + +A program's standard output can be a pipe. `Sys.pipe` gives the descriptor to read and the one to write; give the write end to the child as `fds[1]`, close it here, and read until the end. This is how a program drives another: `ls`, a compiler, a script. + +```raz Capture run +module Capture; +import Out, Sys, Buf, Heap; + +proc main*; +var + p: Sys.Program; pid, rd, wr, n, status: INT; how: Sys.Status; + chunk: [256]U8; b: Buf.Buf; +begin + rd, wr := Sys.pipe(); + p := {path: "/bin/sh", args: ["sh", "-c", "echo one; echo two; exit 7"]}; + p.fds[1] := wr; + pid := Sys.spawn(p); + Sys.close(wr); (* only the child writes now *) + Buf.init(ADR(b), Heap.heap); + defer Buf.done(ADR(b)); + n := Sys.read(rd, chunk); + while n > 0 do + Buf.str(ADR(b), chunk[0..n]); + n := Sys.read(rd, chunk); + end; + Sys.close(rd); + _, how, status := Sys.wait(pid, true); + Out.str("captured: "); Out.str(Buf.bytes(ADR(b))); + Out.str("status "); Out.int(status); Out.ln; + if how = Sys.exited then Out.str("(a normal exit)\n"); end; +end; + +end Capture. +``` + +Closing the write end in the parent matters: the read ends only when every holder of the write end has closed it. + +## Environment and working directory + +`Sys.env("HOME")` is an environment variable's value, or an empty string if it is unset. `Sys.workDir` and `Sys.setWorkDir` read and change the directory. The `Sys.Program` record's `env`, `onlyEnv` and `dir` give a child its own. + +```raz Where run +module Where; +import Out, Sys; + +proc main*; +var p: Sys.Program; pid, rd, wr, n: INT; chunk: [64]U8; +begin + if Sys.env("RAZ_SURELY_UNSET") = "" then Out.str("unset reads as empty\n"); end; + rd, wr := Sys.pipe(); + p := {path: "/bin/sh", args: ["sh", "-c", "echo $GREETING from $(pwd)"], + env: ["GREETING=hello"], dir: "/tmp"}; + p.fds[1] := wr; + pid := Sys.spawn(p); + Sys.close(wr); + n := Sys.read(rd, chunk); + Out.str(chunk[0..n]); + Sys.close(rd); + _, _, _ := Sys.wait(pid, true); +end; + +end Where. +``` diff --git a/site/content/advanced/06-allocators.txt b/site/content/advanced/06-allocators.txt new file mode 100644 index 0000000..0c34653 --- /dev/null +++ b/site/content/advanced/06-allocators.txt @@ -0,0 +1,175 @@ +title: Writing an allocator +part: The library +summary: Mem.Allocator is two procedures; make one over a fixed array, and one that counts. +--- +An allocator is a record of two procedures, and that is all `Mem.Allocator` is: + +```text +type Allocator* = record + alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *) + free*: proc(a: ^Allocator; p: ^U8); +end; +``` + +`NEW(p, a)` calls `a^.alloc(a, SIZE(T), alignment)` and zeroes what it gets. `Buf`, `List` and `Map` call the same procedures. So anything that fills in these two fields is an allocator, and everything in the library works with it. + +## An allocator over a fixed array + +Here is one that needs no system calls at all: it hands out memory from an array in the program, a bump allocator. This is the kind a program with no operating system, or no room for a heap, uses. `free` has nothing to do; `reset` forgets everything. + +The trick that lets one procedure find its state is the same one `Arena` uses: the record puts `base: Mem.Allocator` first, so a `^Mem.Allocator` and a `^Bump` are the same address, and the procedure converts one to the other. + +```raz Bump +module Bump; +import Mem; + +type + Bump* = record + base*: Mem.Allocator; (* first, so that ^Bump(a) finds the rest *) + mem: ^U8; + size, used*: INT; + end; + +proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8; +var b: ^Bump; at: INT; +begin + b := ^Bump(a); + at := (b^.used + align - 1) div align * align; (* round up to align *) + if (size < 0) or (at + size > b^.size) then return nil; end; + b^.used := at + size; + return b^.mem + at; +end; + +proc free(_a: ^Mem.Allocator; _p: ^U8); +begin +end; + +(* a bump allocator over the size bytes at mem *) +proc init*(b: ^Bump; mem: ^U8; size: INT); +begin + b^.base := {alloc: alloc, free: free}; + b^.mem := mem; + b^.size := size; + b^.used := 0; +end; + +(* everything forgotten, the memory used again *) +proc reset*(b: ^Bump); +begin + b^.used := 0; +end; + +end Bump. +``` + +```raz Bumping run +module Bumping; +import Out, Bump; + +type Point = record x, y: INT; end; + +var arena: [256]U8; (* the allocator's whole world *) + +proc main*; +var b: Bump.Bump; p, q: ^Point; many: INT; r: ^Point; +begin + Bump.init(ADR(b), ADR(arena[0]), 256); + NEW(p, ADR(b.base)); + NEW(q, ADR(b.base)); + p^.x := 1; q^.y := 2; + Out.int(b.used); Out.str(" bytes used by two points\n"); + many := 2; + repeat + NEW(r, ADR(b.base)); + if r # nil then INC(many); end; + until r = nil; + Out.int(many); Out.str(" points fit in 256 bytes\n"); + Bump.reset(ADR(b)); + NEW(r, ADR(b.base)); + if r # nil then Out.str("room again after a reset\n"); end; +end; + +end Bumping. +``` + +An allocator that runs out says so with `nil`, and the caller decides what that means. Nothing else in the program is touched. + +## An allocator that counts + +An allocator can wrap another. This one forwards to whatever it is given and keeps count, which is how to find out what a piece of code allocates, or to prove that a path allocates nothing. + +```raz Counted +module Counted; +import Mem; + +type + Counted* = record + base*: Mem.Allocator; (* first *) + inner: ^Mem.Allocator; + allocs*, frees*, bytes*: INT; + end; + +proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8; +var c: ^Counted; p: ^U8; +begin + c := ^Counted(a); + p := Mem.alloc(c^.inner, size, align); + if p # nil then INC(c^.allocs); INC(c^.bytes, size); end; + return p; +end; + +proc free(a: ^Mem.Allocator; p: ^U8); +var c: ^Counted; +begin + c := ^Counted(a); + INC(c^.frees); + Mem.free(c^.inner, p); +end; + +(* a counting allocator in front of inner *) +proc init*(c: ^Counted; inner: ^Mem.Allocator); +begin + c^.base := {alloc: alloc, free: free}; + c^.inner := inner; + c^.allocs := 0; + c^.frees := 0; + c^.bytes := 0; +end; + +end Counted. +``` + +```raz Audit run +module Audit; +import Fmt, Heap, Mem, Buf, Counted, Names := List([]U8); + +proc main*; +var c: Counted.Counted; b: Buf.Buf; l: Names.List; i: INT; p: ^U8; +begin + Counted.init(ADR(c), Heap.heap); + Buf.init(ADR(b), ADR(c.base)); + for i := 1 to 200 do Buf.str(ADR(b), "0123456789"); end; + Fmt.print("a buffer of {} bytes took {} allocations\n", + [Fmt.int(b.len), Fmt.int(c.allocs)]); + Buf.done(ADR(b)); + + Names.init(ADR(l), ADR(c.base)); + for i := 1 to 10 do _ := Names.push(ADR(l), "x"); end; + Fmt.print("{} allocations in all, {} frees so far\n", [Fmt.int(c.allocs), Fmt.int(c.frees)]); + Names.clear(ADR(l)); + Fmt.print("{} frees after clear\n", [Fmt.int(c.frees)]); + + p := Mem.alloc(ADR(c.base), 64, 8); + Mem.free(ADR(c.base), p); +end; + +end Audit. +``` + +A `Buf` grows by doubling, so two thousand bytes took a handful of allocations and not two hundred. That is the sort of thing a counting allocator is for. + +## What to take from this + +- An allocator is a value, so it is passed, wrapped, swapped in a test and replaced by a bump allocator in a program with no heap. +- A library function that needs memory takes the allocator as a parameter, so its caller owns the policy. +- An allocator can use the record-first trick to carry any state it needs, because converting a pointer to a record's first field and back is the same address. diff --git a/site/content/advanced/07-static.txt b/site/content/advanced/07-static.txt new file mode 100644 index 0000000..ec66699 --- /dev/null +++ b/site/content/advanced/07-static.txt @@ -0,0 +1,127 @@ +title: A program with no run time +part: Standing alone +summary: What is in an executable, what isn't, and how to see it. +--- +Most languages arrive with a run time: a collector, a loader of libraries, start-up code you didn't write. A raz program that doesn't use C has none of that. The executable holds the code the program reaches, a few lines of start-up code, and nothing else. This part of the tour looks at what that means in practice, and what a program can do when nothing stands between it and the kernel. + +## The smallest program + +This program imports nothing. It makes the `write` system call itself, with the built-in `SYSCALL`, and returns. + +```raz Bare +module Bare; + +const Msg = "hello from raw system calls\n"; + +proc main*; +begin + _ := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg)); +end; + +end Bare. +``` + +```sh +$ raz Bare.raz +$ ./Bare +$ file Bare +$ ldd Bare +$ ls -l Bare | awk '{print $5, "bytes"}' +``` + +It is statically linked: no interpreter, no shared libraries, no `libc`. `ldd` says so. + +## What it does when it runs + +`strace` lists every system call a program makes. This is the whole of it: + +```sh +$ strace ./Bare 2>&1 >/dev/null | sed -e 's/0x[0-9a-f]\{5,\}/ADDR/g' -e 's/[0-9]* vars/N vars/' +``` + +The start-up code does four things before `main` runs: it sets up a stack of its own for signal handlers (`sigaltstack`), and installs handlers for `SIGSEGV` and `SIGFPE`. That is what turns a `nil` pointer or a division by zero into a message that names the place, instead of a bare "Segmentation fault". Then `main` runs its single `write`, and the program ends with `exit_group`. Nothing is mapped, loaded, or looked up. + +## Programs that use C + +A program that declares an `extern` procedure, or links a library, is a different animal. It is linked dynamically and starts through the C library, so that C's own set-up and clean-up run. Compare the same kind of hello, with C's `printf`: + +```raz Cprint +module Cprint; + +extern proc puts(s: ^U8): I32; + +proc main*; +begin + _ := puts("hello from C"); +end; + +end Cprint. +``` + +```sh +$ raz Cprint.raz +$ ./Cprint +$ file Cprint +$ ldd Cprint | sed 's/ (0x[0-9a-f]*)//' +``` + +Both are fine. The point is that you choose, and the language says which you chose: a program uses C exactly when a module of it has an `extern` or a `link` of a library. + +## Only what is reached + +The compiler keeps only what can be reached from `main` and the module bodies. Unused procedures, variables and strings are left out. Here are two programs that differ by one large procedure that nothing calls. + +```raz Lean +module Lean; +import Out; + +proc main*; +begin + Out.str("same program\n"); +end; + +end Lean. +``` + +```raz Heavy +module Heavy; +import Out; + +var table: [100000]INT; + +(* exported, but never called, so never in the executable *) +proc unused*(n: INT): INT; +var i, s: INT; +begin + for i := 0 to 99999 do table[i] := n * i; s := s + table[i]; end; + Out.str("a long string that nobody will ever print, to give it some weight"); + return s; +end; + +proc main*; +begin + Out.str("same program\n"); +end; + +end Heavy. +``` + +```sh +$ raz Lean.raz +$ raz Heavy.raz +$ ls -l Lean Heavy | awk '{print $9, $5}' +``` + +The sizes differ by a few bytes, not by the hundreds of kilobytes that the table and the procedure would take: they are not in the executable at all. You can link in a library module without worrying what else it offers. + +## Stripping + +`-s` leaves out what is there for finding faults: the symbols and line numbers, the places a failure is told by, and the profiler. It is for the final build of a size-conscious program; the default keeps them so that gdb and failure messages work. + +```sh +$ raz -s -o Lean-stripped Lean.raz +$ ls -l Lean Lean-stripped | awk '{print $9, $5}' +$ ./Lean-stripped +``` + +`raz -S Lean.raz` is the other direction: it prints the machine code the compiler made, one source line at a time. The next two parts of the tour use it. diff --git a/site/content/advanced/08-linkstatic.txt b/site/content/advanced/08-linkstatic.txt new file mode 100644 index 0000000..831d8aa --- /dev/null +++ b/site/content/advanced/08-linkstatic.txt @@ -0,0 +1,75 @@ +title: Threads without C, and keeping the two apart +part: Standing alone +summary: link static, what a module that makes its own system calls promises, and the error when it breaks. +--- +A program without C can do things a program with C can't. The most useful is to make threads of its own: C's thread functions rely on C's own set-up, which a program that never started C has not done. `Thread` creates threads directly with the `clone` system call and gives each a stack of its own. + +A module like that says so, with `link static;` after its imports. It means: "I make my own system calls or my own threads, which the C library wouldn't know about; a program that includes me must not use C." `static` isn't a reserved word; it is only meaningful after `link`. + +## What `Thread` does + +`Thread` is a module of raz, in the library, that says `link static;` and makes the `clone`, `mmap` and `futex` system calls itself. Here is its beginning, printed from the library: + +```sh +$ sed -n '1,22p' $RAZLIB/Thread.linux-x86_64.raz +``` + +A program that imports it is therefore a static executable, and every thread it spawns is a Linux thread with a stack of its own, mapped with a page below it that can't be touched, so that running off the stack ends the program with a message and not with corruption. + +```raz Hello +module Hello; +import Out, Thread; + +var done: INT; + +proc greet(arg: ^U8); +begin + Out.str("hello from thread "); Out.int(INT(arg)); Out.ln; + _ := XADD(ADR(done), 1); +end; + +proc main*; +var t: ^Thread.Thread; err: ERROR; +begin + t, err := Thread.spawn(greet, ^U8(7)); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + Thread.join(t); + Out.str("joined; done = "); Out.int(done); Out.ln; +end; + +end Hello. +``` + +```sh +$ raz Hello.raz +$ ./Hello +$ file Hello | sed 's/,.*statically/, statically/' +``` + +## When you mix them + +C's `pthread_create` and `Thread` can't share a process, and the compiler won't let you try. A program that imports a module that says `link static;` and another that uses C is an error, and the error names both: + +```raz Mixed +module Mixed; +import Out, Thread, C; + +proc main*; +begin + Out.str(MSG(Thread.Failed)); Out.ln; + _ := C.printf("%d\n", I32(1)); + Out.str("and Out\n"); +end; + +end Mixed. +``` + +```sh +$ raz Mixed.raz +``` + +Which one you want depends on what the program is for. A program that calls a C library (a window system, a database client) uses C's threads, `C.pthread_create`, because the library may assume them. A program that talks only to the kernel uses `Thread`, and is a static executable. + +## The same promise for your own modules + +The rule isn't special to `Thread`. A module of yours that makes `SYSCALL`s directly, or relies on being the only owner of signal handlers, or sets up its own stacks, says `link static;` too, and then the compiler keeps C away from it for you. The module is documenting a fact about itself, and the compiler checks it where the program is assembled. diff --git a/site/content/advanced/09-lifecycle.txt b/site/content/advanced/09-lifecycle.txt new file mode 100644 index 0000000..c928198 --- /dev/null +++ b/site/content/advanced/09-lifecycle.txt @@ -0,0 +1,134 @@ +title: Starting, ending, and signals +part: Standing alone +summary: What runs before main, what runs after, and how to wait for a signal. +--- +With no run time, the life of a program is short enough to say in a few lines. What happens, in order: + +1. The entry code sets up a stack for signal handlers and installs the handlers for `SIGSEGV` and `SIGFPE`. A program that uses C starts through C instead, so that C's own set-up runs. +2. The bodies of the modules run, each once, imported modules first. +3. The main module's `main` runs. +4. `Rt.exit` runs the procedures registered with `Rt.atExit`, the last registered first, and ends the program with `main`'s status. + +## Bodies, then main + +The first tour showed bodies running before `main`. They are the place to set a module up, and they can end early with `return;`. + +```raz Order run +module Order; +import Out; + +var steps*: INT; + +proc note(what: []U8); +begin + INC(steps); + Out.int(steps); Out.str(". "); Out.str(what); Out.ln; +end; + +begin + note("the body runs before main"); + if steps > 5 then return; end; + note("and carries on if it isn't ended early"); +end Order. +``` + +That file is a module with a body and no `main`: it can be imported, or its body run as a program. Add the `main` and see both: + +```raz Both run +module Both; +import Out, Order; + +proc main*; +begin + Out.str("main: "); Out.int(Order.steps); Out.str(" steps happened first\n"); +end; + +end Both. +``` + +## Things to do at the end + +`Rt.atExit(p)` registers a procedure with no parameters to run when the program ends by `Rt.exit`: at the end of `main`, by a call to `Rt.exit`, or by a failed check, after its message. It is where a program restores a terminal or removes a lock file. At most 32 are registered, and each runs at most once. Out's buffer is flushed this way, which is why a program that ends in a failure still shows what it printed. + +```raz Cleanup run +module Cleanup; +import Out, Rt; + +proc first; +begin + Out.str("registered first, runs last\n"); +end; + +proc second; +begin + Out.str("registered second, runs first\n"); +end; + +proc main*; +begin + _ := Rt.atExit(first); + _ := Rt.atExit(second); + Out.str("main is done\n"); +end; + +end Cleanup. +``` + +## Two ways to leave in a hurry + +`Rt.exit(status)` ends the program after the `atExit` procedures. `Sys.exit(status)` ends it at once, without them. A failed check and `Rt.exit` also skip the `defer` statements still pending in the calls under way. `Sys.exit` is for a child process that must not run what it inherited, and for nothing else. + +```raz Hurry +module Hurry; +import Out, Rt, Sys; + +proc bye; +begin + Out.str("atExit ran\n"); +end; + +proc main*; +begin + _ := Rt.atExit(bye); + defer Out.str("a deferred statement ran\n"); + Out.str("leaving\n"); + Out.flush; + Sys.exit(3); +end; + +end Hurry. +``` + +```sh +$ raz Hurry.raz +$ ./Hurry; echo "status $?" +``` + +Neither the deferred statement nor `bye` ran. That's the rule, and the reason to keep cleanup that matters (a terminal, a lock file) in `atExit` and use `Rt.exit` for ending. + +## Signals + +A program is stopped by a signal it doesn't catch, with a message that names the place for `SIGSEGV` and `SIGFPE`, and without one for the others. A program that wants to handle one, say `SIGTERM` for a clean shutdown, doesn't write a handler that runs at an arbitrary moment. It asks for the signals to arrive as data: `Sys.catch` takes a list of signals and gives a descriptor that is ready to read when one comes, and `Sys.caught` says which. So the program waits for signals the way it waits for input. + +```raz Terms run +module Terms; +import Out, Sys; + +proc main*; +var fd, sig: INT; +begin + fd := Sys.catch([Sys.sigTerm, Sys.sigWinch]); + Out.str("asking myself to stop\n"); + _ := Sys.kill(Sys.pid(), Sys.sigTerm); + if Sys.ready(fd, 1000) then + sig := Sys.caught(fd); + if sig = Sys.sigTerm then Out.str("caught SIGTERM, stopping cleanly\n"); end; + end; + sig := Sys.caught(fd); + Out.int(sig); Out.str(" waiting after that\n"); (* 0: none *) +end; + +end Terms. +``` + +`Sys.ready(fd, ms)` waits up to `ms` milliseconds for something to read; with `Sys.readyOf` it waits on several descriptors, so one loop serves a socket, a terminal and a stop signal together. `Sys.ignore(sig, true)` makes a signal do nothing, as a shell ignores `SIGTTOU`. diff --git a/site/content/advanced/10-targets.txt b/site/content/advanced/10-targets.txt new file mode 100644 index 0000000..4cd1453 --- /dev/null +++ b/site/content/advanced/10-targets.txt @@ -0,0 +1,85 @@ +title: One module, one file per target +part: Standing alone +summary: Portable programs, the code that isn't, and how the compiler keeps them in step. +--- +raz is first made for x86-64 Linux, but the language is written to be implemented elsewhere, and the library is arranged for it. The part of a program that depends on the system goes in a module of its own, one file per target. This is how `Sys` is made, and it is how your own code should keep its system-dependent parts apart. + +## The files + +A module `Name` lives in `Name.raz`. A module whose code depends on the system comes in one file per target, `Name.linux-x86_64.raz`, which the compiler looks for first. The library has `Sys.linux-x86_64.raz`, which makes system calls, and `Sys.raz`, which calls the C library instead, for every other system. A program that imports `Sys` doesn't know or care which it got. + +```sh +$ ls $RAZLIB | grep -i "^sys\|^thread" +$ cd $RAZLIB && grep -c SYSCALL Sys.linux-x86_64.raz Sys.raz +``` + +## A module of your own + +Here is a module with two files. `Clock.linux-x86_64.raz` is for this target; `Clock.raz` is what any other target would use. Both say what they are in `Name`, and both make `ticks`. + +```raz Clock.linux-x86_64 +module Clock; +import Sys; + +const Name* = "the linux-x86_64 file"; + +(* a number that only grows *) +proc ticks*: I64; +begin + return Sys.clock(); +end; + +end Clock. +``` + +```raz Clock +module Clock; +import Sys; + +const Name* = "the portable file"; + +(* a number that only grows *) +proc ticks*: I64; +begin + return Sys.clock(); +end; + +end Clock. +``` + +A program that imports `Clock` gets the first of them here: + +```raz Show run +module Show; +import Out, Clock; + +proc main*; +begin + Out.str("using "); Out.str(Clock.Name); Out.ln; + if Clock.ticks() > 0 then Out.str("and it ticks\n"); end; +end; + +end Show. +``` + +## Held to one interface + +Two files can't be told apart by their callers, so the compiler holds them to the same interface. Here is the pair again with `ticks` changed in the portable file to return an `INT`: + +```sh +$ mkdir drift && cp Clock*.raz Show.raz drift && cd drift +$ sed -i 's/proc ticks\*: I64/proc ticks*: INT/; s/return Sys.clock()/return INT(Sys.clock())/' Clock.raz +$ raz Show.raz +``` + +The program stops compiling on every target, including the ones that would never have used that file. A mismatch is found where it is made, not where someone first builds for a second target. + +## What the compiler checks + +When it takes one of `Name.*.raz`, it also reads the declarations of the others beside it, and of `Name.raz` if there is one, and reports an error unless they all export the same names, each the same kind of thing: a constant of the same type (its value may differ), a type of the same kind with the same exported fields, a variable of the same type, a procedure of the same signature. The code, the unexported fields, and so the size and layout, may differ. + +So a program written against the interface works on every target that has the module, and the places where it doesn't are the compiler's to find, not yours. + +## What stays the same everywhere + +The core of the library is what every target must have: `Rt`, `Out`, `Mem`, `Arena`, `Lock`, `Str` and `Buf`, and of `Sys` what they need. A program that keeps to the core runs on every target. `Thread`, `link` and `extern`, and most of `Sys`, are what a target may leave out when its system can't give them. diff --git a/site/content/advanced/11-asm.txt b/site/content/advanced/11-asm.txt new file mode 100644 index 0000000..c10c572 --- /dev/null +++ b/site/content/advanced/11-asm.txt @@ -0,0 +1,203 @@ +title: Procedures in assembly +part: The machine +summary: code procedures: the convention, registers, labels, db for what the assembler doesn't know. +--- +Sometimes a program needs an instruction the language has no word for: reading the cycle counter, asking the CPU what it is, counting bits in one instruction, a square root in the hardware. A procedure whose body is `code` is machine code, written by hand in the target's assembly language, one instruction to each `;`, up to `end`. + +The compiler doesn't look past what the instructions say. It trusts you, and you owe it a few rules. + +## A first one + +This reads the processor's time stamp counter. The result of a procedure goes in `rax`; `rdtsc` leaves the counter in `edx:eax`, so the two halves are joined first. + +```raz Cycles run +module Cycles; +import Out; + +proc rdtsc*: U64; +code + rdtsc; + shl rdx, 32; + or rax, rdx; + ret; +end rdtsc; + +proc main*; +var a, b: U64; +begin + a := rdtsc(); + b := rdtsc(); + if b > a then Out.str("the counter moves forward\n"); end; +end; + +end Cycles. +``` + +A code procedure is called like any procedure. Everything in it is yours, `ret` included. + +## The convention + +A code procedure follows the System V convention, as every raz procedure does: + +- Integer and pointer arguments arrive in `rdi`, `rsi`, `rdx`, `rcx`, `r8` and `r9`; `F32` and `F64` ones in `xmm0` to `xmm7`. +- The result goes in `rax` (and `rdx` for a second) or `xmm0`. +- It must keep `rbx`, `rbp`, `rsp` and `r12` to `r15` as it found them. `rax`, `rcx`, `rdx`, `rsi`, `rdi` and `r8` to `r11` are free to change. +- Its parameters and results are therefore of the types C can take, at most six integer and eight real parameters and two results. + +That is why the next one is so short: the argument is already in `rdi`. + +```raz Bits run +module Bits; +import Out; + +(* the bytes of x in the opposite order: bswap rax, which the assembler + doesn't know, written as its bytes *) +proc swap64(x: U64): U64; +code + mov rax, rdi; + db 48H, 0FH, 0C8H; + ret; +end swap64; + +(* the number of bits set in x: popcnt rax, rdi *) +proc ones(x: U64): INT; +code + db 0F3H, 48H, 0FH, 0B8H, 0C7H; + ret; +end ones; + +proc main*; +begin + Out.str("0x"); Out.hex(swap64(0102030405060708H), 16); Out.ln; + Out.int(ones(0FFH)); Out.char(' '); + Out.int(ones(0)); Out.char(' '); + Out.int(ones(0FFFFFFFFFFFFFFFFH)); Out.ln; +end; + +end Bits. +``` + +`db` writes any bytes, for an instruction the assembler doesn't know. Which instructions it knows is the implementation's business; `db` keeps you from waiting for it to learn one. (The two instructions above are from the processor manuals: `bswap r64` is `REX.W 0F C8+r`, `popcnt r64, r/m64` is `F3 REX.W 0F B8 /r`.) + +## Labels and loops + +A label, `name:`, names the place of the instruction after it, within the procedure. Jumps go to labels, and a constant of the module may stand wherever a number does. This sums an array of `INT`s, which a pointer and a length describe: + +```raz Sum run +module Sum; +import Out; + +(* the sum of the n INTs at p *) +proc sum(p: ^INT; n: INT): INT; +code + xor eax, eax; + test rsi, rsi; + jle done; +again: + add rax, [rdi]; + add rdi, 8; + dec rsi; + jnz again; +done: + ret; +end sum; + +(* the same in raz, to check it against *) +proc sumRaz(a: []INT): INT; +var i, t: INT; +begin + for i := 0 to LEN(a) - 1 do t := t + a[i]; end; + return t; +end; + +proc main*; +var a: [6]INT; i: INT; +begin + for i := 0 to 5 do a[i] := (i + 1) * 100; end; + Out.int(sum(ADR(a[0]), 6)); Out.char(' '); + Out.int(sumRaz(a)); Out.char(' '); + Out.int(sum(ADR(a[0]), 0)); Out.ln; +end; + +end Sum. +``` + +A procedure may have up to 64 labels. The check against the raz version is the habit worth keeping: write the procedure in raz first, then in assembly, and compare their results on awkward inputs. + +## Two results, and reals + +A second result goes in `rdx`. That is exactly where `idiv` leaves the remainder, so `divmod` is four instructions. Reals travel in the `xmm` registers. + +```raz Divmod run +module Divmod; +import Out, Fmt; + +(* quotient and remainder, as idiv gives them: rax and rdx *) +proc divmod(a, b: INT): (INT, INT); +code + mov rax, rdi; + cqo; + idiv rsi; + ret; +end divmod; + +(* a * x + b, on F64s in xmm0 to xmm2 *) +proc fma(a, x, b: F64): F64; +code + mulsd xmm0, xmm1; + addsd xmm0, xmm2; + ret; +end fma; + +proc main*; +var q, r: INT; +begin + q, r := divmod(-17, 5); + Out.int(q); Out.char(' '); Out.int(r); Out.ln; + Fmt.print("{}\n", [Fmt.real(fma(2.0, 3.5, 0.25), 2)]); +end; + +end Divmod. +``` + +`idiv` by zero stops the program with the machine's own division fault. It isn't a check the compiler added, since the compiler doesn't look inside a code procedure. + +## Keeping what isn't yours + +A procedure that uses `rbx` must put it back. `cpuid` clobbers `rbx`, so the vendor-string example saves it with `push` and restores it with `pop`, and keeps the buffer's address in `r8` while it works: + +```raz Vendor run +module Vendor; +import Out; + +(* the 12 bytes of the processor vendor, in buf (rdi) *) +proc vendor(buf: ^U8); +code + push rbx; + mov r8, rdi; + xor eax, eax; + cpuid; + mov [r8], ebx; + mov [r8 + 4], edx; + mov [r8 + 8], ecx; + pop rbx; + ret; +end vendor; + +proc main*; +var buf: [12]U8; i: INT; ok: BOOL; +begin + vendor(ADR(buf[0])); + ok := true; + for i := 0 to 11 do + if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end; + end; + if ok then Out.str("the vendor is 12 printable bytes\n"); end; +end; + +end Vendor. +``` + +## What goes wrong + +A code procedure that breaks its rules breaks the program, and what follows isn't defined. Writing through a wrong pointer, a changed `rbx`, a missing `ret`, a stack left unbalanced: the language can't help, because it doesn't see inside. Keep them short, give each a comment that says what it expects in which register, test each against a raz twin, and use them for what only the machine can do. diff --git a/site/content/advanced/12-syscalls.txt b/site/content/advanced/12-syscalls.txt new file mode 100644 index 0000000..de55aec --- /dev/null +++ b/site/content/advanced/12-syscalls.txt @@ -0,0 +1,177 @@ +title: System calls +part: The machine +summary: SYSCALL directly: the numbers, the arguments, negative errno, and a cat without a library. +--- +Under `Sys` there is one built-in: `SYSCALL(n, x1, ..., x6)`. It makes Linux system call number `n` with up to six arguments, each a pointer or an integer no wider than `INT`, and gives the raw result, an `INT`. A negative result is `-errno`. That is all the interface there is; `Sys.write`, `Sys.open` and the rest of `lib/Sys.linux-x86_64.raz` are written with it, in raz, in a few lines each. + +`SYSCALL` exists only on Linux targets. Other systems have no stable system call interface, which is why their `Sys` calls the C library instead. + +## The shape of a call + +`write(fd, buf, count)` is call number 1. The arguments are the descriptor, a pointer to the bytes, and how many. + +```raz Raw +module Raw; + +const Msg = "straight to the kernel\n"; + +proc main*; +var n: INT; +begin + n := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg)); + if n # LEN(Msg) then _ := SYSCALL(60, 1); end; (* exit(1), if it came up short *) +end; + +end Raw. +``` + +```sh +$ raz -Werror Raw.raz +$ ./Raw +``` + +That program has no `Out`, no `Sys`, and no output buffer. What it needs of the library is `Rt`'s start-up, which the compiler links in anyway. + +## Reading the result + +A result that is negative is a failure, and its negation is the `errno`. `open` is call 2 and wants a C string: the path's bytes followed by a zero. A `[N]U8` made from a string literal is zero-filled past its length, so there is always a terminator. + +```raz Open run +module Open; +import Out; + +proc main*; +var path: [32]U8; fd: INT; +begin + path := "/no/such/file"; + fd := SYSCALL(2, ADR(path[0]), 0, 0); (* open(path, O_RDONLY) *) + Out.str("open gave "); Out.int(fd); Out.ln; (* -2: ENOENT *) + path := "/dev/null"; + fd := SYSCALL(2, ADR(path[0]), 0, 0); + if fd >= 0 then + Out.str("opened /dev/null\n"); + _ := SYSCALL(3, fd); (* close *) + end; +end; + +end Open. +``` + +The library's `Sys.openRead` does exactly this, and `Sys.close` too. Reading `lib/Sys.linux-x86_64.raz` is the best reference there is for what each call wants. + +## A call that fills a structure + +`uname` (call 63) fills a structure of six 65-byte fields: the system name, node name, release, version, machine and domain. It is not a type raz knows; it is an array of bytes, with a `ADR` of it given to the kernel. + +```raz Who run +module Who; +import Out; + +(* the length of the zero-ended string at the start of s *) +proc cstr(s: []U8): INT; +var n: INT; +begin + n := 0; + while (n < LEN(s)) and (s[n] # 0) do INC(n); end; + return n; +end; + +proc main*; +var u: [390]U8; +begin + if SYSCALL(63, ADR(u[0])) = 0 then + Out.str("system: "); Out.str(u[0..cstr(u[0..65])]); Out.ln; + Out.str("machine: "); Out.str(u[260..260 + cstr(u[260..325])]); Out.ln; + end; +end; + +end Who. +``` + +## Memory straight from the kernel + +`mmap` is call 9: six arguments, the most one call can take. This asks for a page of anonymous, zeroed memory, writes in it, and gives it back with `munmap` (call 11). It is what `Mem.pages` does, and so what every allocator is ultimately made of. + +```raz Pages run +module Pages; +import Out; + +proc main*; +var p: ^U8; i: INT; total: INT; +begin + (* length 4096; PROT_READ|WRITE = 3; MAP_PRIVATE|ANONYMOUS = 22H; no fd *) + p := ^U8(SYSCALL(9, 0, 4096, 3, 22H, -1, 0)); + if INT(p) < 0 then Out.str("no memory\n"); return; end; + Out.int(INT(p[0]) + INT(p[4095])); Out.str(" (zero, as promised)\n"); + for i := 0 to 4095 do p[i] := U8(i); end; + for i := 0 to 4095 do INC(total, INT(p[i])); end; + Out.int(total); Out.ln; + _ := SYSCALL(11, p, 4096); +end; + +end Pages. +``` + +## A cat with no library + +Reading and writing in a loop is all `cat` does. With system calls, it is one procedure. Call 0 is `read` and call 1 is `write`; 0 and 1 are standard input and output. + +```raz Cat +module Cat; + +proc main*: INT; +var buf: [4096]U8; n, wrote, at: INT; +begin + n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf)); + while n > 0 do + at := 0; + while at < n do (* a write may be partial *) + wrote := SYSCALL(1, 1, ADR(buf[at]), n - at); + if wrote < 0 then return 1; end; + INC(at, wrote); + end; + n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf)); + end; + if n < 0 then return 1; end; + return 0; +end; + +end Cat. +``` + +```sh +$ raz Cat.raz +$ echo "through the pipe" | ./Cat +$ ./Cat < /dev/null; echo "status $?" +$ echo "see the calls" | strace -e trace=read,write ./Cat 2>&1 >/dev/null | grep -v '^+++' +``` + +The partial-write loop is the kind of detail `Sys.write` leaves to the caller on purpose: it returns the bytes written, and the program decides what to do about the rest. + +## In a code procedure + +A system call is also an instruction. `syscall` takes its number in `rax` and its arguments in `rdi`, `rsi`, `rdx`, `r10`, `r8` and `r9`, which is not quite the order a procedure's arguments arrive in, since `r10` takes the place of `rcx`, and `syscall` itself clobbers `rcx` and `r11`. + +```raz Ppid run +module Ppid; +import Out; + +(* getppid, call 110: no arguments *) +proc getppid: INT; +code + mov eax, 110; + syscall; + ret; +end getppid; + +proc main*; +begin + if (getppid() > 0) and (SYSCALL(110) = getppid()) then + Out.str("two ways to ask, one answer\n"); + end; +end; + +end Ppid. +``` + +`SYSCALL` is the right tool nearly always: the compiler puts the arguments where they belong, and the result is checked in the open. A code procedure is for the rare call you want to make from inside another piece of assembly. diff --git a/site/content/advanced/13-listing.txt b/site/content/advanced/13-listing.txt new file mode 100644 index 0000000..58e2fcc --- /dev/null +++ b/site/content/advanced/13-listing.txt @@ -0,0 +1,118 @@ +title: What the compiler makes +part: The machine +summary: raz -S, reading a listing, what a check costs and what check off removes. +--- +The compiler has no optimizer and no intermediate form. It reads the source once and writes x86-64 machine code as it goes, so the code is what the source says, in the order it says it. That makes the output readable, and there is a switch for reading it: `raz -S Main.raz` prints the main module's code instead of writing it, each line of source and under it the instructions made for it, at their offsets in the procedure. + +## A small procedure + +```raz Add +module Add; + +proc add*(a, b: INT): INT; +begin + return a + b; +end; + +proc main*; +begin + _ := add(1, 2); +end; + +end Add. +``` + +```sh +$ raz -S Add.raz +``` + +Every procedure starts by saving the caller's frame pointer and making its own (`push rbp; mov rbp, rsp`) and reserves room for what it needs. The arguments arrive in `rdi` and `rsi`, as the convention says, and the result leaves in `rax`. A call is `mov rdi, 1; mov rsi, 2; call Add.add`. Nothing is hidden: the frame pointer chain is what lets a failure show the calls under way with their variables. + +## A loop with its checks + +This is the dot product of two slices. A slice is a pointer and a length, and it travels in two registers: + +```raz Dot +module Dot; + +(* the dot product of two slices of equal length *) +proc dot*(a, b: []INT): INT; +var i, sum: INT; +begin + for i := 0 to LEN(a) - 1 do + sum := sum + a[i] * b[i]; + end; + return sum; +end; + +proc main*; +var x, y: [3]INT; +begin + x := [1, 2, 3]; + y := [4, 5, 6]; + _ := dot(x, y); +end; + +end Dot. +``` + +```sh +$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p' +``` + +Read it from the top. `a` arrives in `rdi` and `rsi`, pointer and length; `b` in `rdx` and `rcx`, which the procedure saves in its frame. `i` and `sum` live in `rbx` and `r12`, which the procedure saves and restores because the convention says they belong to the caller. The loop's test is at the bottom, and its limit, `LEN(a) - 1`, is taken once. + +In the body, each index has a check: `cmp rbx, rsi; jae` compares `i` with `a`'s length in a single instruction and jumps to a stub at the end of the procedure, which calls `Rt.check0` with the values it needs to say what failed. When the index is in range, which is nearly always, the cost is one compare and a branch that isn't taken. + +## Taking the checks out + +`check off;` after the imports leaves out the module's own checks of indexes and slice bounds. Here is the same procedure with it: + +```raz Dot2 +module Dot2; +check off; + +proc dot*(a, b: []INT): INT; +var i, sum: INT; +begin + for i := 0 to LEN(a) - 1 do + sum := sum + a[i] * b[i]; + end; + return sum; +end; + +proc main*; +var x, y: [3]INT; +begin + x := [1, 2, 3]; + y := [4, 5, 6]; + _ := dot(x, y); +end; + +end Dot2. +``` + +```sh +$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p' +$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p' | wc -l +$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p' | wc -l +``` + +The compares, the branches and the stubs are gone. It is faster, and it is no longer safe: an index out of range reads or writes whatever memory it reaches, and what follows isn't defined. A program turns checks off where it has measured and is sure, and says so at the top of the module, where a reader can see it. + +## Comparing with C + +`make kernels` in the compiler's sources measures `test/bench`'s kernels against the same kernels written in Pascal and compiled by Free Pascal at `-O2`. The compiler's own guide, `doc/compiler.md`, gives the numbers and says what the compiler does and doesn't do. It is not the fastest code: it is code whose every instruction you can account for. + +## Tools that read what it made + +- `gdb` finds procedures by name and lines by number, since the executable carries them: `break Dot.dot` and `list` work, and so does stepping a line at a time. +- `RAZ_PROFILE=1` samples the program every millisecond and says which procedures and lines took the time. +- `objdump -d` disassembles what is really in the file, if you want to see the bytes behind a listing. + +```sh +$ raz -o Dot Dot.raz +$ objdump -d -M intel --no-show-raw-insn Dot | sed -n '/:/,/ret/p' | head -12 +``` + +The listing is what the encoder meant; `objdump` is what the processor will read. They tell the same story. diff --git a/site/content/advanced/14-volatile.txt b/site/content/advanced/14-volatile.txt new file mode 100644 index 0000000..5595f84 --- /dev/null +++ b/site/content/advanced/14-volatile.txt @@ -0,0 +1,124 @@ +title: Volatile +part: Shared memory +summary: ^VOLATILE T: memory that something else may change, laid over with a record. +--- +Most memory is the program's own: only it reads and writes it, so the compiler may keep a variable in a register, leave out a write that nothing reads, and change the order of accesses, as long as the program does what the report says. Some memory is not: a device's registers, memory another processor or thread is changing, a page the kernel fills. There, each access matters, and its order. + +A variable reached through a `^VOLATILE T` is volatile, and so is any field or element of it. Each read or write of one of a basic, enumeration, set or pointer type is exactly one memory access, of exactly its size, and volatile accesses happen in the order the program writes them. + +## A device laid over memory + +The classic use is a device's registers: a record that says what is at which offset, laid over the address the hardware answers at. The record's layout is C's, so it is the same as the datasheet's struct. Here a page of the program's own stands in for the device. + +```raz Uart run +module Uart; +import Out; + +type + Regs = record + data: U32; (* offset 0 *) + status: U32; (* offset 4 *) + control: U8; (* offset 8 *) + end; + +var page: [64]U8; (* where the device would be *) + +proc main*; +var dev: ^VOLATILE Regs; i: INT; +begin + dev := ^VOLATILE Regs(ADR(page)); (* the conversion is written *) + dev^.control := 1; + dev^.status := 0FFH; + for i := 0 to 2 do + dev^.data := U32('a' + i); + Out.char(U8(dev^.data)); + end; + Out.ln; + FENCE; + Out.int(INT(page[8])); Out.char(' '); Out.int(INT(dev^.status)); Out.ln; +end; + +end Uart. +``` + +On real hardware the address would be a constant, `^VOLATILE Regs(0FEC00000H)`, which is a legal conversion since an integer constant converts to a pointer. The program is otherwise unchanged. + +## What each access is + +The listing shows what the guarantee means: each field access is one instruction of the field's size, and so is a write to a field that is never read afterwards, which an optimizer would be allowed to drop from an ordinary variable. + +```sh +$ raz -S Uart.raz | grep -n "dword\|byte" | head -2 +``` + +The `U8` control byte is written with a `byte` store, and the `U32` status with a `dword` one. Never a wider access that touches the neighbour, never two narrower ones. + +## Waiting for something else to change + +Where a program waits for another thread or a device to change a value, the loop must read the value each time. A volatile read does. This "device" is a thread that sets a bit in a status word after a delay; the main thread polls. + +```raz Poll run +module Poll; +import Out, Sys, Thread; + +type Dev = record status: INT; data: INT; end; + +var dev: Dev; + +proc device(_arg: ^U8); +var d: ^VOLATILE Dev; +begin + d := ^VOLATILE Dev(ADR(dev)); + Sys.sleep(20); + d^.data := 42; + FENCE; (* data before the flag that announces it *) + d^.status := 1; +end; + +proc main*; +var t: ^Thread.Thread; err: ERROR; d: ^VOLATILE Dev; spins: INT; +begin + d := ^VOLATILE Dev(ADR(dev)); + t, err := Thread.spawn(device, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + while d^.status = 0 do INC(spins); Sys.yield; end; + Out.int(d^.data); Out.ln; + if spins > 0 then Out.str("it waited for the device\n"); end; + Thread.join(t); +end; + +end Poll. +``` + +The `FENCE` between the two writes matters. It is a full memory barrier, ordering the program's ordinary accesses against those of other processors and devices. Without it, volatile accesses are ordered among themselves, but nothing says another processor sees `data` before `status`. The next lessons are about this. + +## What volatile is not + +- **Not atomic across a read-modify-write.** `INC(d^.count)` reads and then writes: two accesses, even through a volatile pointer. `XADD` is the atomic one. +- **Not a lock.** It says each access happens as written; it says nothing about what happens between them. +- **Not for whole records or arrays.** Copying a whole record through a volatile pointer isn't allowed, since it can't be one access. A field of a packed record can't be reached volatilely at all, since a misaligned access can't be promised as one. +- **Not silently dropped.** A `^VOLATILE T` doesn't convert to a `^T` without a written conversion, so the volatile can't be lost by accident. + +The compiler holds the line on each of them: + +```raz Wrong +module Wrong; + +type Pair = record a, b: U32; end; + +var cell: Pair; + +proc main*; +var v: ^VOLATILE Pair; p: ^Pair; copy: Pair; +begin + v := ^VOLATILE Pair(ADR(cell)); + p := v; + copy := v^; +end; + +end Wrong. +``` + +```sh +$ raz Wrong.raz +``` diff --git a/site/content/advanced/15-atomics.txt b/site/content/advanced/15-atomics.txt new file mode 100644 index 0000000..1f5da3d --- /dev/null +++ b/site/content/advanced/15-atomics.txt @@ -0,0 +1,168 @@ +title: Atomics +part: Shared memory +summary: XADD, XCHG and CAS; a compare-and-swap loop; a lock built from them. +--- +A volatile access is one access. An atomic is one *indivisible* step: nothing can happen between its read and its write, so two threads using it can't lose each other's work. There are three, built into the language as procedures, and they are sequentially consistent on every target: + +| Call | Does | +|---|---| +| `XADD(p, x)` | adds `x` to `p^` and returns the value before | +| `XCHG(p, x)` | sets `p^ := x` and returns the value before | +| `CAS(p, old, new)` | if `p^ = old`, sets `p^ := new` and returns `true`; otherwise `false` | + +`p` is a `^T` or `^VOLATILE T` where `T` is `INT`, `UINT` or a pointer type (`INT` or `UINT` for `XADD`). They compile to single x86-64 instructions: `lock xadd`, `xchg` (which is always locked when it touches memory) and `lock cmpxchg`: + +```raz Ops +module Ops; + +var counter: INT; + +proc main*; +begin + _ := XADD(ADR(counter), 5); + _ := XCHG(ADR(counter), 100); + _ := CAS(ADR(counter), 100, 7); +end; + +end Ops. +``` + +```sh +$ raz -S Ops.raz | grep -i "lock\|xchg" +``` + +## What each one gives you + +`XADD` is a counter, or a ticket dispenser: every caller gets a different number. `XCHG` takes the old value and leaves a new one, which is a flag, a swap, or the release of a lock. `CAS` is the general one: "if nobody changed it since I looked, change it". Most lock-free code is a loop around it. + +```raz Tickets run +module Tickets; +import Out, Thread; + +var + next: INT; (* the next ticket to give out *) + seen: [4000]U8; (* which tickets were taken, one byte each *) + +proc work(_arg: ^U8); +var i, t: INT; +begin + for i := 1 to 1000 do + t := XADD(ADR(next), 1); (* a ticket no other thread gets *) + seen[t] := 1; + end; +end; + +proc main*; +var th: [4]^Thread.Thread; i, taken: INT; err: ERROR; +begin + for i := 0 to 3 do + th[i], err := Thread.spawn(work, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to 3 do Thread.join(th[i]); end; + for i := 0 to 3999 do taken := taken + INT(seen[i]); end; + Out.int(next); Out.char(' '); Out.int(taken); Out.ln; +end; + +end Tickets. +``` + +Four thousand tickets, four thousand different numbers, no two threads with the same one. Each thread writes into its own bytes of `seen`, so no plain write is shared. + +## A compare-and-swap loop + +Anything that can be computed from the old value can be made atomic with a loop around `CAS`: read the value, compute the new one, and try to swap it in; if someone got there first, read again. Here is an atomic maximum, which no single instruction does. + +```raz Peak run +module Peak; +import Out, Thread; + +var peak: INT; + +(* raises peak to v if v is bigger, however many threads call it *) +proc raise(v: INT); +var seen: INT; +begin + seen := peak; + while seen < v do + if CAS(ADR(peak), seen, v) then return; end; + seen := peak; (* someone changed it: look again *) + end; +end; + +proc work(arg: ^U8); +var i, base: INT; +begin + base := INT(arg); + for i := 0 to 999 do raise(base + i * 7 mod 1001); end; +end; + +proc main*; +var th: [4]^Thread.Thread; i: INT; err: ERROR; +begin + for i := 0 to 3 do + th[i], err := Thread.spawn(work, ^U8(i * 1000)); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to 3 do Thread.join(th[i]); end; + Out.int(peak); Out.ln; +end; + +end Peak. +``` + +The result doesn't depend on how the threads interleave: it is the largest value any of them offered. That is the test of a correct atomic algorithm, and why this kind of code is written once, carefully, and used everywhere. + +## A lock, from first principles + +A lock is a word that is 0 when free and 1 when held. To take it, `CAS` it from 0 to 1; if that fails, someone holds it, so try again. To give it up, `XCHG` it back to 0. This is exactly the library's `Lock`, printed from `lib/Lock.raz`: + +```sh +$ sed -n '/^type Lock/,/^proc main/p' $RAZLIB/Lock.raz | head -n -2 +``` + +And here is a use of it: a structure with two fields that must stay in step, which no single atomic can protect. + +```raz Account run +module Account; +import Out, Lock, Thread; + +var + lock: Lock.Lock; + deposits, balance: INT; (* balance = 3 * deposits, always, under lock *) + +proc work(_arg: ^U8); +var i: INT; +begin + for i := 1 to 20000 do + Lock.take(ADR(lock)); + INC(deposits); + INC(balance, 3); + Lock.give(ADR(lock)); + end; +end; + +proc main*; +var th: [4]^Thread.Thread; i: INT; err: ERROR; +begin + for i := 0 to 3 do + th[i], err := Thread.spawn(work, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to 3 do Thread.join(th[i]); end; + Out.int(deposits); Out.char(' '); Out.int(balance); Out.ln; + if balance = 3 * deposits then Out.str("in step\n"); end; +end; + +end Account. +``` + +A `Lock` spins, giving up the processor now and then, so it is for sections of a few instructions. `Thread.Mutex` sleeps on a futex, so it is for longer ones. A spinning lock held for a long time, or by a thread that was descheduled, burns processors; that is the price of its speed when contention is short. + +## Choosing + +- A counter, a ticket, a flag: `XADD` or `XCHG`. +- A value computed from the old one: a `CAS` loop. +- Several variables that must change together: a `Lock` or a `Mutex`. Don't try to be clever with several atomics; the one invariant spanning them is the thing that breaks. + +All three act on a word. For anything bigger, the thing you swap is a pointer to the bigger thing: the next lessons do exactly that. diff --git a/site/content/advanced/16-ordering.txt b/site/content/advanced/16-ordering.txt new file mode 100644 index 0000000..7e8a57f --- /dev/null +++ b/site/content/advanced/16-ordering.txt @@ -0,0 +1,105 @@ +title: Ordering and publication +part: Shared memory +summary: Why a flag isn't enough, what FENCE and the atomics order, and the pattern that works. +--- +Atomics make one word safe. The harder question is about the *other* words: if one thread writes a value and then raises a flag, can another thread that sees the flag be sure it sees the value? + +The report is careful. Only volatile accesses, `CAS`, `XCHG`, `XADD` and `FENCE` are exact. Any other access is ordinary: an implementation may keep a variable in a register, leave out a write that nothing reads, and change the order of ordinary accesses, as long as each thread, on its own, does what the report says. A variable that one thread writes while another reads or writes it, unless both use volatile accesses or the atomic built-ins, or a `FENCE` orders them, holds no particular value then: a read of it gives a value it had or was given, or a mixture of their bytes. Nothing else of the program becomes undefined by it. + +In plain words: two threads that share an ordinary variable with no atomic, volatile or fence between them get no guarantee about what each sees. + +## The pattern that is guaranteed: publish through an atomic + +The simplest correct way to hand a value to another thread: write it with ordinary stores, then store a flag with an atomic. The reader loops on the flag with an atomic read, and then reads the data. `XCHG` is the store; `XADD(p, 0)` is the load, which adds nothing and returns the value. Both are sequentially consistent, so everything written before the flag is visible after it is seen. + +```raz Publish run +module Publish; +import Out, Sys, Thread; + +type Message = record id: INT; text: [32]U8; len: INT; end; + +var + msg: Message; (* ordinary memory, written once, then published *) + ready: INT; (* the flag: only touched by atomics *) + +proc producer(_arg: ^U8); +begin + Sys.sleep(10); + msg.id := 7; + msg.text := "built before the flag"; + msg.len := 21; + _ := XCHG(ADR(ready), 1); (* publish *) +end; + +proc main*; +var t: ^Thread.Thread; err: ERROR; +begin + t, err := Thread.spawn(producer, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + while XADD(ADR(ready), 0) = 0 do Sys.yield; end; (* wait for it *) + Out.int(msg.id); Out.char(' '); Out.str(msg.text[0..msg.len]); Out.ln; + Thread.join(t); +end; + +end Publish. +``` + +The reader's loop makes no ordinary read of `ready`: it can't be kept in a register and read once, which is the danger of `while ready = 0 do end`. And the write of `msg` can't be delayed past the `XCHG`. + +## The same with a fence + +`FENCE` is a full memory barrier: it orders the program's ordinary accesses against those of other processors and devices. With volatile accesses for the flag and a fence between the data and the flag, the same handoff works. This is the form device code takes, as in the last lesson. + +```raz Fenced run +module Fenced; +import Out, Sys, Thread; + +var + data: INT; (* ordinary *) + flag: INT; (* only reached through a volatile pointer *) + +proc producer(_arg: ^U8); +var f: ^VOLATILE INT; +begin + f := ^VOLATILE INT(ADR(flag)); + Sys.sleep(10); + data := 1234; + FENCE; (* data is written before the flag is *) + f^ := 1; +end; + +proc main*; +var t: ^Thread.Thread; err: ERROR; f: ^VOLATILE INT; +begin + f := ^VOLATILE INT(ADR(flag)); + t, err := Thread.spawn(producer, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + while f^ = 0 do Sys.yield; end; + FENCE; (* and read after the flag is seen *) + Out.int(data); Out.ln; + Thread.join(t); +end; + +end Fenced. +``` + +Both sides need a fence. A fence on the writer only says the data is written first; the reader must not read `data` before it has seen the flag. + +## The version that is not guaranteed + +This is what *not* to write, and it is the most common bug in this area: + +```text +var data, ready: INT; + +(* thread A *) data := 42; ready := 1; +(* thread B *) while ready = 0 do end; use(data); +``` + +Both threads use ordinary accesses to shared variables. B's loop may read `ready` once into a register and spin forever; A's two writes may reach memory in either order; B may read `data` before the flag, or an old copy. On a particular machine with a particular compiler it may well work, until it is changed. The language says it holds no particular value, and it means it. + +## The lesson of the three versions + +- Shared and written by someone: reach it through an atomic, a volatile pointer or a fence, every time, on both sides. +- To hand over a bundle, publish a single atomic word *after* writing the bundle, and read the bundle only *after* seeing the word. +- Everything under a `Lock` or a `Mutex` is ordered by the lock itself, so the data it guards can be ordinary variables. That is the simplest discipline, and the one to prefer until it is measured to be too slow. diff --git a/site/content/advanced/17-lockfree.txt b/site/content/advanced/17-lockfree.txt new file mode 100644 index 0000000..9e70d40 --- /dev/null +++ b/site/content/advanced/17-lockfree.txt @@ -0,0 +1,135 @@ +title: A lock-free stack +part: Shared memory +summary: CAS on pointers, a push loop that never blocks, and the ABA problem that makes pop harder. +--- +`CAS` works on pointers as well as integers, and a pointer is how a bigger thing is swapped in atomically: build the new structure privately, then make it visible by changing one word. The classic example is a stack as a linked list whose head is that word. + +## Push + +To push a node: point its `next` at the current head, then `CAS` the head from what you saw to the new node. If another thread pushed first, the `CAS` fails, because the head is no longer what you saw, so look again and retry. No thread ever waits for another, and none can stop the others by being slow. + +```raz Treiber run +module Treiber; +import Out, Thread; + +type Node = record next: ^Node; val: INT; end; + +const Threads = 4; Each = 5000; + +var + top: ^Node; (* the head, changed only by CAS *) + nodes: [Threads * Each]Node; (* every node a thread will push *) + +(* n onto the stack, without a lock *) +proc push(n: ^Node); +var old: ^Node; +begin + old := top; + n^.next := old; + while not CAS(ADR(top), old, n) do + old := top; (* lost the race: look again *) + n^.next := old; + end; +end; + +proc work(arg: ^U8); +var first, i: INT; +begin + first := INT(arg) * Each; + for i := 0 to Each - 1 do + nodes[first + i].val := first + i; + push(ADR(nodes[first + i])); + end; +end; + +proc main*; +var th: [Threads]^Thread.Thread; i, count, sum: INT; err: ERROR; n: ^Node; +begin + for i := 0 to Threads - 1 do + th[i], err := Thread.spawn(work, ^U8(i)); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to Threads - 1 do Thread.join(th[i]); end; + n := top; + while n # nil do + INC(count); + sum := sum + n^.val; + n := n^.next; + end; + Out.int(count); Out.char(' '); Out.int(sum); Out.ln; + Out.int(Threads * Each * (Threads * Each - 1) div 2); Out.ln; +end; + +end Treiber. +``` + +Twenty thousand nodes pushed by four threads at once; every one is on the stack exactly once, and the sum of their values is the sum of 0 to 19999. Nothing was lost, and there is no lock anywhere in the program. + +The loop in `push` is the shape of every lock-free algorithm: read, compute, `CAS`, and read again on failure. The `CAS` is sequentially consistent, so the node's `val` and `next`, written before it with ordinary stores, are visible to a thread that finds the node through `top`. + +## Pop, and the ABA problem + +Pop takes the head off: read `top`, read its `next`, `CAS` the head from `top` to `next`. It looks as easy as push, and it isn't. Between the two reads and the `CAS`, other threads may pop that node, pop others, and push the same node back, now with a different `next`. The head is the same pointer again, so the `CAS` succeeds, and installs a `next` that is stale: nodes disappear, or the stack points into freed memory. This is the **ABA problem**: the word changed from A to B and back to A, and the `CAS` can't tell. + +There are three common ways out, and each has a cost: + +- **Never reuse a node while anyone might hold it.** Nodes from an arena that is reset only when all threads are done, as the nodes above come from a fixed array, can't come back as a different node. +- **Add a counter to the head**, so that A-B-A is A1-B2-A3. That is a word and a counter swapped together, and raz's `CAS` is for one word, so a program packs a small index and a counter into one `UINT`. +- **Don't pop concurrently.** Many threads push and one thread, at the end, takes everything with a single `XCHG(ADR(top), nil)` and walks the list in peace. A stack used this way for work lists and logs needs no more. + +```raz Drain run +module Drain; +import Out, Thread; + +type Node = record next: ^Node; val: INT; end; + +const Threads = 3; Each = 1000; + +var + top: ^Node; + nodes: [Threads * Each]Node; + +proc push(n: ^Node); +var old: ^Node; +begin + old := top; + n^.next := old; + while not CAS(ADR(top), old, n) do + old := top; + n^.next := old; + end; +end; + +proc work(arg: ^U8); +var first, i: INT; +begin + first := INT(arg) * Each; + for i := 0 to Each - 1 do + nodes[first + i].val := 1; + push(ADR(nodes[first + i])); + end; +end; + +proc main*; +var th: [Threads]^Thread.Thread; i, count: INT; err: ERROR; all, n: ^Node; +begin + for i := 0 to Threads - 1 do + th[i], err := Thread.spawn(work, ^U8(i)); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to Threads - 1 do Thread.join(th[i]); end; + all := XCHG(ADR(top), nil); (* take the whole stack, atomically *) + n := all; + while n # nil do INC(count); n := n^.next; end; + Out.int(count); Out.str(" taken at once, "); + if top = nil then Out.str("none left\n"); end; +end; + +end Drain. +``` + +The atomic exchange takes everything pushed so far in one step, so the walk that follows races with nobody. + +## When to use it + +A lock-free structure is worth it when a lock would be held by a thread that can be descheduled, when the critical section is a single pointer, or when a signal handler or an interrupt must share data with the code it interrupts. Everywhere else a `Mutex` is shorter, easier to check, and fast enough. The advantage of knowing how to write the other kind is that you understand what the lock is doing for you. diff --git a/site/content/advanced/18-ring.txt b/site/content/advanced/18-ring.txt new file mode 100644 index 0000000..6f56f26 --- /dev/null +++ b/site/content/advanced/18-ring.txt @@ -0,0 +1,118 @@ +title: A ring buffer between threads +part: Shared memory +summary: A single-producer, single-consumer queue, put together from what the tour has covered. +--- +To finish, here is a small piece of real concurrent code that uses nearly everything in this part of the tour: a queue through which one thread sends numbers to another, with no lock and no allocation. + +## The design + +The queue is a fixed array of slots, used as a circle, and two counters that only ever grow: `tail`, the number of items the producer has put in, and `head`, the number the consumer has taken out. The item `n` lives in slot `n mod Size`. The queue is empty when the two are equal, and full when they differ by `Size`. + +The design rule is that **each counter has exactly one writer**. Only the producer changes `tail`; only the consumer changes `head`. Each thread reads its own counter with an ordinary read, since nobody else changes it, and the other thread's with an atomic one. No `CAS` is needed, because there is never a race to resolve: only a handoff. + +The handoff is the publish pattern of the ordering lesson. The producer writes the slot, then publishes it with an atomic store of `tail`; the consumer sees the new `tail` with an atomic load and only then reads the slot. In the other direction, the consumer frees a slot by storing `head`, and the producer only reuses it after loading `head` and seeing that. + +## The module + +```raz Ring +module Ring; +import Sys; + +const Size* = 64; + +type + Ring* = record + slots: [Size]INT; + head, tail: INT; (* items taken, items put; each has one writer *) + end; + +(* v into the ring, waiting while it is full *) +proc put*(r: ^Ring; v: INT); +var t: INT; +begin + t := r^.tail; (* mine: an ordinary read *) + while t - XADD(ADR(r^.head), 0) = Size do Sys.yield; end; (* full *) + r^.slots[t mod Size] := v; + _ := XCHG(ADR(r^.tail), t + 1); (* publish the slot *) +end; + +(* the next value, waiting while the ring is empty *) +proc take*(r: ^Ring): INT; +var h, v: INT; +begin + h := r^.head; (* mine *) + while XADD(ADR(r^.tail), 0) = h do Sys.yield; end; (* empty *) + v := r^.slots[h mod Size]; + _ := XCHG(ADR(r^.head), h + 1); (* give the slot back *) + return v; +end; + +end Ring. +``` + +## Using it + +One thread sends the numbers 1 to 100000 through a ring of 64 slots, so it is stopped by a full ring many times over and has to wait for the consumer. The consumer checks each number arrives in order, and adds them. + +```raz Pipe run +module Pipe; +import Out, Fmt, Ring, Thread; + +const Count = 100000; + +var + ring: Ring.Ring; + sum, outOfOrder: INT; + +proc producer(_arg: ^U8); +var i: INT; +begin + for i := 1 to Count do Ring.put(ADR(ring), i); end; +end; + +proc consumer(_arg: ^U8); +var i, v: INT; +begin + for i := 1 to Count do + v := Ring.take(ADR(ring)); + if v # i then INC(outOfOrder); end; + sum := sum + v; + end; +end; + +proc main*; +var p, c: ^Thread.Thread; err: ERROR; +begin + p, err := Thread.spawn(producer, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + c, err := Thread.spawn(consumer, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + Thread.join(p); + Thread.join(c); + Fmt.print("{} items, sum {}, {} out of order\n", + [Fmt.int(Count), Fmt.int(sum), Fmt.int(outOfOrder)]); +end; + +end Pipe. +``` + +The sum of 1 to 100000 is 5000050000, and nothing arrives out of order. `sum` and `outOfOrder` are written only by the consumer thread and read by `main` after `Thread.join`, which is the synchronization that makes them visible: a join is the thread's end, observed. + +## What it used + +- **Modules** (`Ring`, with its record's own fields unexported). +- **Atomics** for the handoff, and an ordering argument for why a slot is complete when its counter moves. +- **Threads** from `Thread`, with no C in the program. +- **The checks**, which stay on: `slots[t mod Size]` is an indexed array access that can't leave the array, whatever the counters do. + +It is not a finished library: it is one producer and one consumer, and a second of either breaks the one-writer rule. That is the sort of statement a comment above `put` and `take` should make, and the sort a reader should demand. + +## Where next + +That is the end of the tour. A few places to continue: + +- **[The report](../spec.html)** defines the language, and is short enough to read through. +- **`doc/compiler.md`** in the sources is a guide to reading the compiler, file by file; it is a model of the style the project is written in. +- **`lib/`** is the library, in raz. Each module's own `main` is its test. Reading `Heap`, `Map`, `Opt` and `Thread` is the best remaining education. +- **`tools/Doc.raz`** prints what a module exports with its comments: `raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz`. +- **`examples/`** holds small programs with the output each should give, and `conform/` holds what any implementation must do. diff --git a/site/content/home.html b/site/content/home.html index 1d87248..1d258be 100644 --- a/site/content/home.html +++ b/site/content/home.html @@ -4,6 +4,7 @@ Raz is Polish for one, as in counting.

          @@ -49,6 +50,13 @@
        + +

        Learn it

        +

        Raz, Set, Go is a tour of the +language in 14 lessons, each with programs you can run. Beyond Go is the second tour: +the library, programs with no run time, procedures in assembly, system calls, +volatile accesses, atomics and lock-free code, in 18 more.

        The language, in writing

        The language is defined by the report, which is diff --git a/site/content/tour-intro.html b/site/content/tour-intro.html index 0dc8ba6..15c9219 100644 --- a/site/content/tour-intro.html +++ b/site/content/tour-intro.html @@ -6,4 +6,4 @@ first steps; Set, how data is laid out; and Go, making programs that run, fail and finish well. To follow along, get raz and run any program with -raz run Name.raz.

        +raz run Name.raz. When you finish, Beyond Go goes down to the machine.

        diff --git a/site/content/tour/01-hello.txt b/site/content/tour/01-hello.txt new file mode 100644 index 0000000..876a97f --- /dev/null +++ b/site/content/tour/01-hello.txt @@ -0,0 +1,114 @@ +title: Hello, world +part: Raz +summary: A module, an import, a procedure; running, printing, exit status and arguments. +--- +Every raz program is a module with a `main` procedure. This is the smallest one that does something. + +```raz Hello run +``` + +A module lives in a file of its own name, `Hello.raz`, and its name comes again after its last `end`, so a stray `end` is caught early. `import Out` lets it use what the module `Out` exports, as `Out.str`. The `*` after `main` exports it; the program starts at the `main` of the module named on the command line. Every statement ends in `;`, even one that ends in `end`. + +## Compiling and running + +`raz Hello.raz` compiles the module and everything it imports, and writes the executable `Hello` beside it. `raz run` does the same without writing a file, and runs it at once. + +```raz Quiet +(* The same program, with a comment: (* ... *) nests, and may stand anywhere. *) +module Quiet; +import Out; + +proc main*; +begin + Out.str("hello, again\n"); +end; + +end Quiet. +``` + +```sh +$ raz Quiet.raz +$ ./Quiet +$ raz run Quiet.raz +$ ls -l Quiet | awk '{print $5, "bytes"}' +``` + +The program is a static executable with no run time besides the code it uses, so it is a few kilobytes, and runs without any library installed. + +## What `Out` can write + +`Out` is the library's buffered output. It writes strings, single characters, numbers in decimal or hexadecimal, and a line feed. A string is written as it is, with `\n` for a line feed, `\t` for a tab, `\"` and `\\`. + +```raz Numbers run +module Numbers; +import Out; + +proc main*; +begin + Out.str("seven is "); Out.int(7); Out.ln; + Out.str("minus one is "); Out.int(-1); Out.ln; + Out.str("255 is 0x"); Out.hex(255, 4); Out.ln; + Out.char('R'); Out.char('a'); Out.char('z'); Out.ln; + Out.str("a tab:\t|\n"); +end; + +end Numbers. +``` + +`Out.hex(n, 4)` writes at least four digits. `Out.int` takes an `I64` and `Out.hex` a `U64`. An `INT` goes into an `I64` as it is; any other integer is converted where it is written, as `Out.int(I64(b))`, because raz never converts a number unasked. + +## Ending, and the status + +`main` may return an `INT`, which is the program's exit status; a plain `proc main*;` ends with 0. A shell sees the status as `$?`. + +```raz Status +module Status; +import Out; + +proc main*: INT; +begin + Out.str("exiting with 3\n"); + return 3; +end; + +end Status. +``` + +```sh +$ raz run Status.raz; echo "status $?" +``` + +## Arguments + +`ARGC()` is the number of command line arguments, with the program's own name first, and `ARGV()` the arguments, as C strings. Most programs read them through `Files.arg` and `Opt`, which the advanced tour shows; here is the raw form. + +```raz Args +module Args; +import Out; + +(* The length of a C string. *) +proc len(s: ^U8): INT; +var n: INT; +begin + n := 0; + while s[n] # 0 do n := n + 1; end; + return n; +end; + +proc main*: INT; +var i: INT; s: ^U8; +begin + for i := 1 to ARGC() - 1 do + s := ARGV()[i]; + Out.str(s[0..len(s)]); + Out.ln; + end; + return ARGC() - 1; +end; + +end Args. +``` + +```sh +$ raz run Args.raz one "two words"; echo "status $?" +``` diff --git a/site/content/tour/02-modules.txt b/site/content/tour/02-modules.txt new file mode 100644 index 0000000..d118b58 --- /dev/null +++ b/site/content/tour/02-modules.txt @@ -0,0 +1,144 @@ +title: Modules +part: Raz +summary: Exports, renaming, the order bodies run in, and what the compiler refuses. +--- +A program is a set of modules, one to a file, and a module's interface is everything it marks with `*`. Everything else is private to it. Here is one, saved as `Greet.raz`: + +```raz Greet +``` + +and a program beside it that uses it: + +```raz Twice run +``` + +A name with `*` is exported; any other is the module's own. `G := Greet` imports `Greet` under a shorter name, so its exports are `G.hello` and `G.count`. Another module may read `G.count`, but only `Greet` may change it. + +## Where modules are found + +The compiler looks for `Greet.raz` in the main module's directory, then in each directory given with `-I`, then in the library. So a project is a directory of modules, and `raz Main.raz` finds all of them. The library's own names (`Out`, `Str`, `Map`, ...) are kept for it. + +## Bodies run first, in order + +The statements after a module's last `begin` are its body. It runs once, before `main`, after the bodies of the modules it imports, and once however many modules import it. This is how a module sets itself up: no `init` call to forget. + +```raz Base +module Base; +import Out; + +var ready*: BOOL; + +begin + Out.str("Base starts\n"); + ready := true; +end Base. +``` + +```raz Layer +module Layer; +import Out, Base; + +const Name* = "Layer"; + +begin + Out.str("Layer starts, Base is ready: "); + if Base.ready then Out.str("yes\n"); else Out.str("no\n"); end; +end Layer. +``` + +```raz Order run +module Order; +import Out, Layer, Base; + +proc main*; +begin + Out.str("main, after "); Out.str(Layer.Name); Out.char(' '); + if Base.ready then Out.str("and Base\n"); end; +end; + +end Order. +``` + +`Base` is imported twice, but starts once, before `Layer`, which needs it. A module with no body doesn't need a `begin` at all. + +## Exporting more than procedures + +A module exports constants, types, variables and procedures alike. A record type's exported fields are marked too; the rest are the module's own. + +```raz Shape +module Shape; + +const Sides* = 4; + +type + Square* = record + side*: INT; (* exported: a user may set it *) + id: INT; (* the module's own *) + end; + +var made: INT; (* only Shape may read or write it *) + +(* a square of that side, numbered in the order they are made *) +proc make*(side: INT): Square; +var s: Square; +begin + INC(made); + s.side := side; + s.id := made; + return s; +end; + +proc area*(s: Square): INT; +begin + return s.side * s.side; +end; + +proc count*: INT; +begin + return made; +end; + +end Shape. +``` + +```raz Squares run +module Squares; +import Out, Shape; + +proc main*; +var a, b: Shape.Square; +begin + a := Shape.make(3); + b := Shape.make(5); + Out.int(Shape.area(a) + Shape.area(b)); Out.ln; + Out.int(Shape.count()); Out.str(" made, "); Out.int(Shape.Sides); + Out.str(" sides each\n"); +end; + +end Squares. +``` + +## What the compiler refuses + +Reaching past an interface is an error, and the error says where. + +```raz Peek +module Peek; +import Shape; + +proc main*; +var s: Shape.Square; +begin + s := Shape.make(2); + s.id := 7; + Shape.made := 0; +end; + +end Peek. +``` + +```sh +$ raz Peek.raz +``` + +The compiler goes on to find the others, up to 20, and says what it can: where a name was declared, or a name spelled almost alike. A module with errors writes no executable. diff --git a/site/content/tour/03-values.txt b/site/content/tour/03-values.txt new file mode 100644 index 0000000..a142d1c --- /dev/null +++ b/site/content/tour/03-values.txt @@ -0,0 +1,110 @@ +title: Values and conversions +part: Raz +summary: Sized integers that wrap, reals, bits, and nothing converts unasked. +--- +```raz Values run +``` + +## Integers + +The integers are `I8`, `I16`, `I32`, `I64` and `U8`, `U16`, `U32`, `U64`, and `INT` and `UINT`, as big as an address. `INT` is the everyday one: lengths, indexes and counts are `INT`s. + +Arithmetic wraps at the type's width and never stops the program, except dividing by zero. That is why `250 + 10` in a `U8` is 4. `div` divides toward zero, and `mod` has the sign of its left side. + +```raz Wrap run +module Wrap; +import Out; + +proc main*; +var a: U8; b: I8; c: U32; d: INT; +begin + a := 250; a := a + 10; + Out.int(I64(a)); Out.ln; (* 4 *) + b := 127; b := b + 1; + Out.int(I64(b)); Out.ln; (* -128 *) + c := 0; c := c - 1; + Out.int(I64(c)); Out.ln; (* 4294967295 *) + d := -7; + Out.int(d div 2); Out.str(" "); (* -3 *) + Out.int(d mod 2); Out.ln; (* -1 *) +end; + +end Wrap. +``` + +## Conversions are written + +Two types never mix: with `i: I64` and a slice `s`, `i < LEN(s)` is an error. A type's name converts: `F64(n)`, `I64(b)`, `U8(x)`. Converting to a narrower integer cuts it; to a wider one extends it by its sign (signed) or with zeros (unsigned). The one silent conversion between numbers is an `INT` into an `I64`, which loses nothing. + +A number written in the program is untyped until it meets a type; `0FFH` is hexadecimal, and `1.5` is a real, which an integer never becomes without a conversion. + +```raz Mix +module Mix; +import Out; + +proc main*; +var i: I64; s: []U8; +begin + s := "four"; + i := 3; + if i < LEN(s) then Out.str("smaller\n"); end; +end; + +end Mix. +``` + +```sh +$ raz Mix.raz +``` + +The fix is the conversion, written where it happens: `if i < I64(LEN(s))`. It costs nothing at run time and says what is meant. + +## Bits and booleans + +`#`, not `<>`, is "different". `and`, `or` and `not` are for `BOOL`s, and bind below the relations, so `i < n and a[i] # 0` needs no parentheses. `&`, `|`, `xor`, `~`, `shl` and `shr` are for the bits of integers. There is no conversion between `BOOL` and an integer: say what you mean with `if`. + +```raz Bits run +module Bits; +import Out; + +proc main*; +var flags, mask: U8; +begin + flags := 0; + flags := flags | 1; (* set bit 0 *) + flags := flags | (1 shl 3); (* set bit 3 *) + mask := 0FH; + Out.str("flags 0x"); Out.hex(U64(flags), 2); Out.ln; + Out.str("and 0x"); Out.hex(U64(flags & mask), 2); Out.ln; + Out.str("xor 0x"); Out.hex(U64(flags xor 0FFH), 2); Out.ln; + Out.str("not 0x"); Out.hex(U64(~flags), 2); Out.ln; + if (flags & 8) # 0 then Out.str("bit 3 is set\n"); end; +end; + +end Bits. +``` + +## Reals + +`F32` and `F64` are the reals. A real constant is written with a point, `1.5` or `2.0E-3`. `Fmt.real(x, places)` writes one with that many digits after the point, and `Math` has the functions. + +```raz Reals run +module Reals; +import Fmt, Math; + +proc main*; +var n: INT; x: F64; y: F32; +begin + n := 22; + x := F64(n) / 7.0; + y := F32(x); + Fmt.print("22/7 = {}\n", [Fmt.real(x, 6)]); + Fmt.print("as F32 = {}\n", [Fmt.real(F64(y), 6)]); + Fmt.print("sqrt 2 = {}, pi = {}\n", [Fmt.real(Math.sqrt(2.0), 5), Fmt.real(Math.pi, 5)]); + Fmt.print("truncated: {} {}\n", [Fmt.int(I64(2.9)), Fmt.int(I64(-2.9))]); +end; + +end Reals. +``` + +A real converts to an integer by rounding toward zero. Every variable starts at zero, a real's `0.0` and a `BOOL`'s `false` included, so there is no uninitialised value to be surprised by. diff --git a/site/content/tour/04-procedures.txt b/site/content/tour/04-procedures.txt new file mode 100644 index 0000000..2ce342d --- /dev/null +++ b/site/content/tour/04-procedures.txt @@ -0,0 +1,161 @@ +title: Procedures and several results +part: Raz +summary: Value and var parameters, several results, forward, and procedures as values. +--- +```raz Procs run +``` + +A parameter is a copy, unless it is `var`, when it is the caller's variable itself. A procedure may return several results, which a multiple assignment takes apart; the blank, `_`, drops one. + +## Value and `var` parameters + +A value parameter is the procedure's own: it may change it, and the caller's variable stays as it was. A `var` parameter is the caller's variable, and its argument must be a variable of exactly that type. + +```raz Params run +module Params; +import Out; + +proc bump(n: INT); (* changes its own copy *) +begin + n := n + 1; +end; + +proc bumpIn(var n: INT); (* changes the caller's *) +begin + n := n + 1; +end; + +proc fill(var a: [4]INT; v: INT); (* an array is copied unless var *) +var i: INT; +begin + for i := 0 to 3 do a[i] := v; end; +end; + +proc main*; +var x: INT; a: [4]INT; +begin + x := 10; + bump(x); + Out.int(x); Out.ln; (* 10 *) + bumpIn(x); + Out.int(x); Out.ln; (* 11 *) + fill(a, 7); + Out.int(a[0] + a[3]); Out.ln; (* 14 *) +end; + +end Params. +``` + +## Several results + +Instead of an output parameter, a procedure says what it returns: `(INT, INT)`, or any list of types. The caller takes them apart with a multiple assignment. A call that returns several values may stand on the right of one, alone as a statement, or alone after `return`, which passes them on as they are. + +```raz Several run +module Several; +import Out; + +proc divmod(a, b: INT): (INT, INT); +begin + return a div b, a mod b; +end; + +proc minmax(a, b: INT): (INT, INT); +begin + if a < b then return a, b; end; + return b, a; +end; + +proc spread(a, b: INT): (INT, INT); +begin + return minmax(a, b); (* passes both results on *) +end; + +proc main*; +var q, r, lo, hi: INT; +begin + q, r := divmod(100, 7); + Out.int(q); Out.str(" rest "); Out.int(r); Out.ln; + lo, hi := spread(9, 4); + Out.int(lo); Out.str(" .. "); Out.int(hi); Out.ln; + _, r := divmod(-7, 2); (* drop the quotient *) + Out.int(r); Out.ln; +end; + +end Several. +``` + +## Recursion, and `forward` + +A name is declared before it is used, and procedures don't nest. When two procedures need each other, `forward` declares the first so that its body can come later. + +```raz Recur run +module Recur; +import Out; + +proc gcd(a, b: INT): INT; +begin + if b = 0 then return a; end; + return gcd(b, a mod b); +end; + +proc isOdd(n: INT): BOOL; forward; + +proc isEven(n: INT): BOOL; +begin + if n = 0 then return true; end; + return isOdd(n - 1); +end; + +proc isOdd(n: INT): BOOL; +begin + if n = 0 then return false; end; + return isEven(n - 1); +end; + +proc main*; +begin + Out.int(gcd(84, 36)); Out.ln; + if isEven(10) and isOdd(7) then Out.str("parity works\n"); end; +end; + +end Recur. +``` + +## Procedures are values + +A procedure used without parentheses is a procedure value, of a procedure type such as `proc(a, b: INT): INT`. It can be passed, stored in a variable or a record, and called. This is raz's only dynamic dispatch, and it is as plain as it looks. + +```raz Table run +module Table; +import Out; + +type Op = proc(a, b: INT): INT; + +proc add(a, b: INT): INT; begin return a + b; end; +proc sub(a, b: INT): INT; begin return a - b; end; +proc mul(a, b: INT): INT; begin return a * b; end; + +proc apply(f: Op; a, b: INT): INT; +begin + return f(a, b); +end; + +proc main*; +var ops: [3]Op; names: [3][]U8; i: INT; +begin + ops := [add, sub, mul]; + names := ["add", "sub", "mul"]; + for i := 0 to 2 do + Out.str(names[i]); Out.str(": "); + Out.int(apply(ops[i], 12, 5)); Out.ln; + end; +end; + +end Table. +``` + +A procedure without parameters leaves out the parentheses where it is called, as `Out.ln` does. That means `f` alone is the procedure and `f()` would not be a call, so be careful when passing one around. + +## Dropped results + +A call that drops a result, as `Sys.write(fd, s);` does, is warned of; `_ := Sys.write(fd, s);` says it is meant. The compiler also warns of a variable that is assigned and never read, and of a name declared and never used, unless it starts with `_`. diff --git a/site/content/tour/05-slices.txt b/site/content/tour/05-slices.txt new file mode 100644 index 0000000..672e73c --- /dev/null +++ b/site/content/tour/05-slices.txt @@ -0,0 +1,181 @@ +title: Arrays, slices and strings +part: Set +summary: Five in a row, a window onto them, bytes in UTF-8, and checks on every index. +--- +```raz Slices run +``` + +## Arrays + +`[5]INT` is an array: five `INT`s in a row, copied when it is assigned or passed. Its length is part of its type, so `[5]INT` and `[6]INT` are different types, and `LEN(a)` of an array is a constant. Array literals are written in brackets, and need a type from the place they are used. + +```raz Arrays run +module Arrays; +import Out; + +proc main*; +var a, b: [4]INT; grid: [3][3]INT; i, j: INT; +begin + a := [1, 2, 3, 4]; + b := a; (* a copy *) + b[0] := 99; + Out.int(a[0]); Out.char(' '); Out.int(b[0]); Out.ln; + if a # b then Out.str("they differ now\n"); end; + + for i := 0 to 2 do + for j := 0 to 2 do grid[i][j] := i * 3 + j; end; + end; + Out.int(grid[2][1]); Out.ln; (* 7 *) + Out.int(LEN(grid)); Out.char('x'); Out.int(LEN(grid[0])); Out.ln; +end; + +end Arrays. +``` + +## Slices + +`[]INT` is a slice: a pointer to elements that live elsewhere, and their number, `LEN(s)`. `a[lo..hi]` is the slice of the elements from `lo` up to, but not including, `hi`, and an array goes silently where a slice is wanted. A slice doesn't copy anything: changing an element of it changes the array it looks at. + +```raz Windows run +module Windows; +import Out; + +proc zero(s: []INT); +var i: INT; +begin + for i := 0 to LEN(s) - 1 do s[i] := 0; end; +end; + +proc show(s: []INT); +var i: INT; +begin + for i := 0 to LEN(s) - 1 do Out.int(s[i]); Out.char(' '); end; + Out.ln; +end; + +proc main*; +var a: [8]INT; i: INT; +begin + for i := 0 to 7 do a[i] := i + 1; end; + zero(a[2..5]); (* a window onto a *) + show(a); (* 1 2 0 0 0 6 7 8 *) + show(a[6..8]); + show(a[3..3]); (* empty: prints just a line feed *) +end; + +end Windows. +``` + +Every index and every slice bound is checked, so a slice can never reach past what it was made from; the lesson on failures shows what that looks like. + +## `COPY` + +`COPY(d, s)` copies the elements of `s` to the start of `d`, as one block, and is right when they overlap. `LEN(s)` must be at most `LEN(d)`. + +```raz Moves run +module Moves; +import Out; + +proc main*; +var a: [6]INT; i: INT; +begin + a := [1, 2, 3, 4, 5, 0]; + COPY(a[1..6], a[0..5]); (* shift everything one place up *) + for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end; + Out.ln; +end; + +end Moves. +``` + +## Strings + +A string is a slice of bytes, `[]U8`, in UTF-8, and a string constant's bytes are constant. A `[8]U8` made from one is a copy you can change. Arrays and slices of integers compare with `=` and `#`, so strings do too. `Str` has the rest: ordering, finding, hashing, prefixes, UTF-8 and reading a number. + +```raz Words run +module Words; +import Out, Str; + +proc main*; +var s: []U8; n: I64; ok: BOOL; name: [8]U8; +begin + s := "hello, world"; + Out.str(s[7..LEN(s)]); Out.ln; + if s[0..5] = "hello" then Out.str("it says hello\n"); end; + Out.int(Str.find(s, "world")); Out.ln; (* 7 *) + Out.int(Str.find(s, "xyz")); Out.ln; (* -1 *) + if Str.hasPrefix(s, "hell") then Out.str("prefix\n"); end; + Out.int(Str.cmp("apple", "banana")); Out.ln; (* -1 *) + + n, ok := Str.toInt("-1234"); + if ok then Out.int(n + 1); Out.ln; end; + n, ok := Str.toInt("12x"); + if not ok then Out.str("not a number\n"); end; + + name := "raz"; (* a copy, the program's own *) + name[0] := 'R'; + Out.str(name[0..3]); Out.ln; +end; + +end Words. +``` + +## UTF-8 + +A character is an `I32`, its code point. `Str.decode` reads the first character of a string and says how many bytes it took; `Str.encode` goes the other way. Byte length and character count are different things, and the program is the one that says which it wants. + +```raz Runes run +module Runes; +import Out, Str; + +(* the characters of s, not its bytes *) +proc chars(s: []U8): INT; +var i, n, size: INT; +begin + i := 0; + n := 0; + while i < LEN(s) do + _, size := Str.decode(s[i..LEN(s)]); + INC(i, size); + INC(n); + end; + return n; +end; + +proc main*; +var s: []U8; c: I32; size: INT; bytes: [4]U8; k: INT; +begin + s := "caf\u{E9} \u{3BB}"; + Out.int(LEN(s)); Out.str(" bytes, "); + Out.int(chars(s)); Out.str(" characters\n"); + c, size := Str.decode(s[3..LEN(s)]); + Out.int(I64(c)); Out.str(" took "); Out.int(size); Out.str(" bytes\n"); + bytes, k := Str.encode(955); + Out.str(bytes[0..k]); Out.ln; +end; + +end Runes. +``` + +## Loops over lengths + +A `for` loop takes its bounds once, and never steps past the last: with an empty slice, `0 to LEN(s) - 1` doesn't run at all, and the variable can't wrap. `for` takes a constant step with `by`, and `while` and `repeat ... until` do the rest. + +```raz Loops run +module Loops; +import Out; + +proc main*; +var i: INT; +begin + for i := 10 to 0 by -5 do Out.int(i); Out.char(' '); end; + Out.ln; + i := 1; + while i < 100 do i := i * 3; end; + Out.int(i); Out.ln; + repeat DEC(i, 30); until i < 0; + Out.int(i); Out.ln; +end; + +end Loops. +``` diff --git a/site/content/tour/06-records.txt b/site/content/tour/06-records.txt new file mode 100644 index 0000000..97ea279 --- /dev/null +++ b/site/content/tour/06-records.txt @@ -0,0 +1,138 @@ +title: Records and pointers +part: Set +summary: Laid out as C lays out a struct, packed records, pointers and nil. +--- +```raz Boxes run +``` + +A record is laid out as C lays out a struct. `{lo: ..., hi: ...}` builds one, naming its fields; the ones it leaves out are zero. `^Box` is a pointer to a `Box`, `ADR(b)` the address of `b`, and `b^` what a pointer points at. A pointer is never the record: it is `b^.lo`, never `b.lo`, so you always see where the memory is reached through an address. + +## Copies and literals + +Assigning a record copies it whole, as with an array. A record is compared field by field by writing the comparison, not by `=`. + +```raz Points run +module Points; +import Out; + +type Point = record x, y: INT; end; + +proc show(p: Point); +begin + Out.char('('); Out.int(p.x); Out.str(", "); Out.int(p.y); Out.char(')'); +end; + +proc mirror(p: Point): Point; +begin + return {x: p.y, y: p.x}; +end; + +proc main*; +var a, b: Point; +begin + a := {x: 3, y: 4}; + b := a; (* a copy *) + b.x := 30; + show(a); show(b); show(mirror(a)); Out.ln; + a := {y: 9}; (* x is zero *) + show(a); Out.ln; +end; + +end Points. +``` + +## Layout + +A record's layout is C's: each field at the next multiple of its own alignment, and the whole padded to a multiple of its largest alignment. `SIZE(T)` says how many bytes. A `packed record` has no padding, which is what a file format or a wire protocol wants. + +```raz Layout run +module Layout; +import Out; + +type + Loose = record a: U8; b: U32; c: U8; end; + Tight = packed record a: U8; b: U32; c: U8; end; + +proc main*; +begin + Out.str("loose: "); Out.int(SIZE(Loose)); Out.ln; (* 12 *) + Out.str("tight: "); Out.int(SIZE(Tight)); Out.ln; (* 6 *) + Out.str("INT: "); Out.int(SIZE(INT)); Out.ln; + Out.str("[5]I16: "); Out.int(SIZE([5]I16)); Out.ln; +end; + +end Layout. +``` + +A field of a packed record may sit at any address, and is read and written like any other; but it has no address of its own to take with `ADR`. + +## Pointers + +`ADR(x)` takes the address of a variable, `^T` is a pointer to a `T`, and `p^` is what it points at. A pointer that points nowhere is `nil`, and following it stops the program with a message that names the place, so a forgotten check is found at once instead of corrupting memory. + +```raz Pointers run +module Pointers; +import Out; + +type Counter = record hits: INT; name: []U8; end; + +proc hit(c: ^Counter); +begin + if c = nil then return; end; + INC(c^.hits); +end; + +proc swap(a, b: ^INT); +var t: INT; +begin + t := a^; + a^ := b^; + b^ := t; +end; + +proc main*; +var c: Counter; x, y: INT; p: ^INT; +begin + c.name := "front door"; + hit(ADR(c)); hit(ADR(c)); hit(nil); + Out.str(c.name); Out.str(": "); Out.int(c.hits); Out.ln; + x := 1; y := 2; + swap(ADR(x), ADR(y)); + Out.int(x); Out.char(' '); Out.int(y); Out.ln; + p := ADR(x); + p^ := p^ + 40; + Out.int(x); Out.ln; +end; + +end Pointers. +``` + +## Pointers that link + +A record may hold a pointer to its own type, which is how lists and trees are made. Memory for them comes from an allocator, which is the next lesson; here the nodes simply live in an array. + +```raz Chain run +module Chain; +import Out; + +type Node = record next: ^Node; val: INT; end; + +proc main*; +var nodes: [4]Node; head, n: ^Node; i: INT; +begin + head := nil; + for i := 0 to 3 do + nodes[i].val := (i + 1) * 10; + nodes[i].next := head; (* each new one in front *) + head := ADR(nodes[i]); + end; + n := head; + while n # nil do + Out.int(n^.val); Out.char(' '); + n := n^.next; + end; + Out.ln; +end; + +end Chain. +``` diff --git a/site/content/tour/07-variants.txt b/site/content/tour/07-variants.txt new file mode 100644 index 0000000..bf5a98c --- /dev/null +++ b/site/content/tour/07-variants.txt @@ -0,0 +1,165 @@ +title: Enumerations, sets, variants and match +part: Set +summary: Names in order, sets as bits, and cases the compiler makes you handle. +--- +```raz Shapes run +``` + +## Enumerations + +An enumeration is a list of names, in order. They convert to their position and back, and a `for` loop can run over them. An integer that has no name at its position is a failed check, never a silent wrong value. + +```raz Days run +module Days; +import Out; + +type Day = (mon, tue, wed, thu, fri, sat, sun); + +proc name(d: Day): []U8; +begin + match d of + | mon: return "Monday"; + | tue: return "Tuesday"; + | wed: return "Wednesday"; + | thu: return "Thursday"; + | fri: return "Friday"; + | sat: return "Saturday"; + | sun: return "Sunday"; + end; +end; + +proc main*; +var d: Day; +begin + for d := mon to sun do + Out.int(I64(d)); Out.str(" "); Out.str(name(d)); + if d >= sat then Out.str(" (weekend)"); end; + Out.ln; + end; + d := Day(4); + Out.str(name(d)); Out.ln; +end; + +end Days. +``` + +## Sets + +A `set of` an enumeration holds any choice of its names, in the bits of a word. `in` tests membership; `+` is union, `*` intersection and `-` difference; `{}` is the empty set. Sets are how Unix permissions, option flags and key modifiers are best written. + +```raz Perms run +module Perms; +import Out; + +type + Perm = (x, w, r); (* bits 0, 1, 2, as chmod has them *) + Perms = set of Perm; + +proc show(p: Perms); +begin + if r in p then Out.char('r'); else Out.char('-'); end; + if w in p then Out.char('w'); else Out.char('-'); end; + if x in p then Out.char('x'); else Out.char('-'); end; +end; + +proc main*; +var user, group, mine: Perms; +begin + user := {r, w, x}; + group := {r, x}; + show(user); Out.char(' '); show(group); Out.ln; + show(user * group); Out.char(' '); (* both: r-x *) + show(user - group); Out.char(' '); (* only user: -w- *) + show(user - {w}); Out.ln; (* r-x *) + mine := group; + if mine = {r, x} then Out.str("same as group\n"); end; + Out.int(I64(U8(user))); Out.ln; (* 7: a set is its bits *) +end; + +end Perms. +``` + +## Variants + +A variant holds one of its cases, each with fields of its own, and `match` is the only way to read them: it runs the arm of the case the variant holds, naming its fields. Every case has an arm, unless an `| else:` comes last, so adding a case to the type makes every `match` that forgot it a compile error. + +```raz Tokens run +module Tokens; +import Out; + +type + Token = variant + number(n: INT); + plus; + times; + word(s: []U8); + end; + +proc describe(t: Token); +begin + match t of + | number(n): Out.str("number "); Out.int(n); + | plus: Out.str("plus"); + | times: Out.str("times"); + | word(s): Out.str("word '"); Out.str(s); Out.char('\''); + end; + Out.ln; +end; + +(* evaluates tokens in reverse Polish; assumes the input is well formed *) +proc eval(ts: []Token): INT; +var stack: [16]INT; top, i, b: INT; +begin + top := 0; + for i := 0 to LEN(ts) - 1 do + match ts[i] of + | number(n): stack[top] := n; INC(top); + | plus: b := stack[top - 1]; DEC(top); stack[top - 1] := stack[top - 1] + b; + | times: b := stack[top - 1]; DEC(top); stack[top - 1] := stack[top - 1] * b; + | else: + end; + end; + return stack[0]; +end; + +proc main*; +var ts: [5]Token; i: INT; +begin + ts := [number(3), number(4), plus, number(5), times]; (* (3 + 4) * 5 *) + for i := 0 to 4 do describe(ts[i]); end; + Out.int(eval(ts)); Out.ln; + describe(word("hello")); +end; + +end Tokens. +``` + +## Matching integers + +On an integer, `match` takes constants and ranges, and must have an `| else:`. Characters are integers, so it is also how a scanner is written. + +```raz Classify run +module Classify; +import Out; + +proc kind(c: I32): []U8; +begin + match c of + | ' ', '\t', '\n': return "space"; + | '0' .. '9': return "digit"; + | 'a' .. 'z', 'A' .. 'Z', '_': return "letter"; + | else: return "other"; + end; +end; + +proc main*; +var s: []U8; i: INT; +begin + s := "x1 + _y"; + for i := 0 to LEN(s) - 1 do + Out.char(s[i]); Out.str(" is "); Out.str(kind(I32(s[i]))); Out.ln; + end; +end; + +end Classify. +``` diff --git a/site/content/tour/08-memory.txt b/site/content/tour/08-memory.txt new file mode 100644 index 0000000..a15d034 --- /dev/null +++ b/site/content/tour/08-memory.txt @@ -0,0 +1,119 @@ +title: Memory and allocators +part: Set +summary: No garbage collector; you choose where memory comes from, and what happens when it runs out. +--- +```raz Stack run +``` + +raz has no garbage collector, and no allocator of its own: memory comes from an allocator, a `Mem.Allocator`, which the program chooses and passes. `NEW(n, a)` sets `n` to a fresh, zeroed `Node` from `a`, or to `nil` if `a` has no room. `Heap.heap` is the general one, which `Mem.free` gives memory back to. An `Arena` hands out memory from one block and frees it all at once, as the last lines above do. + +## Why an allocator is a parameter + +A procedure that allocates takes the allocator it uses, so its caller decides where the memory comes from and when it goes: the heap for something that lives long, an arena for everything one request needs. Nothing in the library allocates behind your back. + +```raz Pool run +module Pool; +import Out, Mem, Arena; + +type Item = record id: INT; next: ^Item; end; + +(* n items, linked; or nil if the allocator ran dry (what came is lost with it) *) +proc make(n: INT; a: ^Mem.Allocator): ^Item; +var head, it: ^Item; i: INT; +begin + head := nil; + for i := 1 to n do + NEW(it, a); + if it = nil then return nil; end; + it^.id := i; + it^.next := head; + head := it; + end; + return head; +end; + +proc count(it: ^Item): INT; +var n: INT; +begin + n := 0; + while it # nil do INC(n); it := it^.next; end; + return n; +end; + +proc main*; +var ar: Arena.Arena; small: Arena.Arena; list: ^Item; +begin + if not Arena.init(ADR(ar), 1000000) then return; end; + list := make(1000, ADR(ar.base)); + Out.int(count(list)); Out.str(" items from a big arena\n"); + Arena.reset(ADR(ar)); (* every allocation forgotten *) + list := make(10, ADR(ar.base)); + Out.int(count(list)); Out.str(" after a reset\n"); + Arena.done(ADR(ar)); + + if not Arena.init(ADR(small), 4096) then return; end; + list := make(1000, ADR(small.base)); + if list = nil then Out.str("a small arena ran out, and said so\n"); end; + Arena.done(ADR(small)); +end; + +end Pool. +``` + +The run-out case is an ordinary `nil` to test, not an exception that unwinds past your code. + +## The heap + +`Heap.heap` serves any size and takes memory back with `Mem.free`. Freeing a block twice, or one that was never given out, stops the program with a message instead of corrupting the heap. It is safe to call from several threads. + +```raz Free run +module Free; +import Out, Mem, Heap; + +type Cell = record val: INT; end; + +proc main*; +var a, b: ^Cell; i, total: INT; +begin + for i := 1 to 5 do + NEW(a, Heap.heap); + a^.val := i * i; + total := total + a^.val; + Mem.free(Heap.heap, ^U8(a)); (* freed at once: its block is reused *) + end; + NEW(b, Heap.heap); + Out.int(total); Out.char(' '); Out.int(b^.val); Out.ln; (* a new block is zeroed *) + Mem.free(Heap.heap, ^U8(b)); +end; + +end Free. +``` + +## Buffers that grow + +`Buf` is a growable byte buffer; like everything else it takes the allocator it grows from. It is what the program uses to build a string of unknown length. + +```raz Build run +module Build; +import Out, Buf, Heap; + +proc main*; +var b: Buf.Buf; i: INT; +begin + Buf.init(ADR(b), Heap.heap); + defer Buf.done(ADR(b)); + for i := 1 to 5 do + Buf.str(ADR(b), "item "); + Buf.add(ADR(b), U8('0' + i)); + Buf.add(ADR(b), ','); + end; + Out.str(Buf.bytes(ADR(b))); Out.ln; + Out.int(b.len); Out.str(" bytes\n"); +end; + +end Build. +``` + +## Pages + +Under the allocators are pages from the system: `Mem.pages(size)` gives zeroed memory in whole pages, or `nil`, and `Mem.unmap` gives it back. Most programs never need to call it directly. diff --git a/site/content/tour/09-errors.txt b/site/content/tour/09-errors.txt new file mode 100644 index 0000000..03c288d --- /dev/null +++ b/site/content/tour/09-errors.txt @@ -0,0 +1,140 @@ +title: Errors +part: Go +summary: A second result, compared by identity; passing errors up; and no exceptions. +--- +```raz Errors run +``` + +A procedure that can fail returns an `ERROR` beside its result, and `nil` when it didn't. Each `ERROR` constant is an error of its own, compared with `=` by which declaration made it, never by its message; `MSG(err)` is the message. An exported one, as `Empty` is here, lets the callers tell it from the others. raz has no exceptions, so every failure is visible in the signature and handled where the call is written. + +## Handling them by kind + +Because an error is compared by identity, a caller can handle the cases it knows and pass on the rest. + +```raz Parse run +module Parse; +import Out, Str; + +const + Empty*: ERROR = "nothing to read"; + Bad*: ERROR = "not a number"; + Range*: ERROR = "out of range"; + +(* a percentage, 0 to 100 *) +proc percent(s: []U8): (INT, ERROR); +var n: I64; ok: BOOL; +begin + if LEN(s) = 0 then return 0, Empty; end; + n, ok := Str.toInt(s); + if not ok then return 0, Bad; end; + if (n < 0) or (n > 100) then return 0, Range; end; + return INT(n), nil; +end; + +proc main*; +var inputs: [4][]U8; i, n: INT; err: ERROR; +begin + inputs := ["42", "", "forty", "140"]; + for i := 0 to 3 do + n, err := percent(inputs[i]); + if err = nil then + Out.int(n); Out.str("%"); + elsif err = Empty then + Out.str("(skipped)"); + else + Out.str("error: "); Out.str(MSG(err)); + end; + Out.ln; + end; +end; + +end Parse. +``` + +## Passing errors up + +When a procedure can't do anything useful with an error, it returns it, so the first caller that can decide gets it. There is no hidden unwinding: the `return` is right there. + +```raz Layers run +module Layers; +import Out, Str; + +const Missing*: ERROR = "key missing"; + +(* the number after "n=" in a line like "n=17" *) +proc value(line: []U8): (INT, ERROR); +var n: I64; ok: BOOL; +begin + if not Str.hasPrefix(line, "n=") then return 0, Missing; end; + n, ok := Str.toInt(line[2..LEN(line)]); + if not ok then return 0, Missing; end; + return INT(n), nil; +end; + +(* the sum of the values of two lines *) +proc sum(a, b: []U8): (INT, ERROR); +var x, y: INT; err: ERROR; +begin + x, err := value(a); + if err # nil then return 0, err; end; (* passed up *) + y, err := value(b); + if err # nil then return 0, err; end; + return x + y, nil; +end; + +proc main*; +var n: INT; err: ERROR; +begin + n, err := sum("n=40", "n=2"); + if err = nil then Out.int(n); Out.ln; end; + n, err := sum("n=40", "x=2"); + if err # nil then Out.str("sum failed: "); Out.str(MSG(err)); Out.ln; end; +end; + +end Layers. +``` + +## When the library reports errors + +Library procedures that can fail say so in the same way: `Thread.spawn` returns an `ERROR`; `Sys` calls return a negative `errno` as an `INT`, with `0` or a positive count for success; `Files.read` returns a `BOOL`. The first is the language's way; the others are the system's, left as they are. + +```raz Probe run +module Probe; +import Out, Sys; + +proc main*; +var fd: INT; +begin + fd := Sys.openRead("/no/such/file"); + if fd < 0 then + Out.str("open failed, errno "); Out.int(-fd); Out.ln; (* 2: ENOENT *) + end; + fd := Sys.openRead("/dev/null"); + if fd >= 0 then + Out.str("open worked\n"); + Sys.close(fd); + end; +end; + +end Probe. +``` + +## When there is nothing to do but stop + +A program that has found a state it can't carry on from, such as a broken invariant, says so and ends with `Rt.stop`: the message goes to standard error and the status is 2, the same as a failed check. + +```raz Giveup +module Giveup; +import Rt; + +proc main*; +begin + Rt.stop("the table is corrupt"); +end; + +end Giveup. +``` + +```sh +$ raz run Giveup.raz; echo "status $?" +``` diff --git a/site/content/tour/10-defer.txt b/site/content/tour/10-defer.txt new file mode 100644 index 0000000..d04aeee --- /dev/null +++ b/site/content/tour/10-defer.txt @@ -0,0 +1,107 @@ +title: Defer +part: Go +summary: Clean up beside the line that needs it, in the right order, on every way out. +--- +```raz Defers run +``` + +`defer s;` runs `s` when the program leaves the statements the `defer` stands in: at their end, or by a `return` or a `break`. Deferred statements run the last first, and only those whose `defer` was reached. So a file is closed beside the line that opens it, however the procedure ends. + +## The order, and a `return` value + +A `return e;` evaluates `e` before the deferred statements run, so the value is what it was at the return. + +```raz Order run +module Order; +import Out; + +var counter: INT; + +proc next(): INT; +begin + defer INC(counter); + return counter; (* the old value is returned; then counter grows *) +end; + +proc nest; +begin + defer Out.str("1 "); + defer Out.str("2 "); + defer Out.str("3 "); + Out.str("body: "); +end; + +proc main*; +var a, b: INT; +begin + a := next(); + b := next(); + Out.int(a); Out.char(' '); Out.int(b); Out.char(' '); Out.int(counter); Out.ln; + nest; + Out.ln; +end; + +end Order. +``` + +## In a loop + +A `defer` stands in the statement list that holds it, so in a loop body it runs at the end of each pass, and on a `break`. + +```raz Passes run +module Passes; +import Out; + +proc main*; +var i: INT; +begin + for i := 1 to 4 do + Out.str("pass "); Out.int(i); + defer Out.str(" done\n"); + if i = 3 then break; end; + Out.str(" ..."); + end; +end; + +end Passes. +``` + +## Giving back what was taken + +The point is that acquiring and releasing sit next to each other, so a new early `return` added later can't leak. Here an arena and a buffer are both released on every path. + +```raz Report run +module Report; +import Out, Buf, Heap; + +(* a line, built in a buffer; false (nothing written) if n is negative *) +proc line(n: INT): BOOL; +var b: Buf.Buf; +begin + if n < 0 then return false; end; + Buf.init(ADR(b), Heap.heap); + defer Buf.done(ADR(b)); (* freed on every way out below *) + Buf.str(ADR(b), "n is "); + if n > 9 then + Buf.str(ADR(b), "large"); + Out.str(Buf.bytes(ADR(b))); Out.ln; + return true; + end; + Buf.str(ADR(b), "small"); + Out.str(Buf.bytes(ADR(b))); Out.ln; + return true; +end; + +proc main*; +begin + _ := line(3); + _ := line(30); + if not line(-1) then Out.str("rejected\n"); end; +end; + +end Report. +``` + +## What defer does not do + +A deferred statement can't contain a `return`, `break` or `defer` that would leave it. A failed check, `Rt.exit` and `Sys.exit` end the program without running the deferred statements still pending, so deferred cleanup is for the program's resources, not for what must happen at exit; that is what `Rt.atExit` is for. diff --git a/site/content/tour/11-checks.txt b/site/content/tour/11-checks.txt new file mode 100644 index 0000000..e3e0aa0 --- /dev/null +++ b/site/content/tour/11-checks.txt @@ -0,0 +1,130 @@ +title: When it goes wrong +part: Go +summary: Every index is checked, a failure says where and with what values, and how to read it. +--- +```raz Fail fail +``` + +Every index and slice is checked. A failed check says where it failed and with what values, then the calls under way with their variables, and ends the program with status 2. The three `0`s are what it printed before the fourth pass went one past the end. + +## Reading the message + +The first line is the place of the offending expression: file, line and column, then what failed and the numbers involved. Each `in` line after it is a call still under way, innermost first, with the basic-typed variables it held. That is usually enough to see the bug without a debugger. + +## Other failures + +The same shape of message tells of a `nil` pointer, a division by zero, a bad slice and a stack overflow. Each of them stops the program with status 2, or by the signal if the machine caught it, and never runs on with a wrong value. + +```raz Nilp fail +module Nilp; +import Out; + +type Node = record val: INT; next: ^Node; end; + +proc last(n: ^Node): INT; +begin + while n^.next # nil do n := n^.next; end; + return n^.val; +end; + +proc main*; +var a, b: Node; +begin + a.val := 1; b.val := 2; + a.next := ADR(b); + Out.int(last(ADR(a))); Out.ln; + Out.int(last(nil)); Out.ln; +end; + +end Nilp. +``` + +```raz Zero fail +module Zero; +import Out; + +proc ratio(a, b: INT): INT; +begin + return a div b; +end; + +proc main*; +var n: INT; +begin + Out.int(ratio(10, 3)); Out.ln; + Out.int(ratio(10, n)); Out.ln; (* n is zero: every variable starts at zero *) +end; + +end Zero. +``` + +```raz Slicing fail +module Slicing; +import Out; + +proc main*; +var a: [5]INT; s: []INT; hi: INT; +begin + hi := 7; + s := a[2..5]; + Out.int(LEN(s)); Out.ln; + s := a[2..hi]; (* past the end *) + Out.int(LEN(s)); Out.ln; +end; + +end Slicing. +``` + +In every case the output before the failure was written first. `Out`'s buffer is flushed by the failure, so what the program printed is never lost to the crash. + +## A constant can fail at compile time + +A division by a zero constant, or a constant index out of range, is not a run-time failure at all; the compiler says it at the line, so you never ship it. + +```raz Early +module Early; +import Out; + +proc main*; +var a: [3]INT; +begin + a[3] := 1; + Out.int(10 div 0); Out.ln; +end; + +end Early. +``` + +```sh +$ raz Early.raz +``` + +## Looking at where you are + +`Rt.trace` prints the calls under way, as a failure does, whenever you ask. It writes to standard error and the program goes on. It is the cheapest debugging tool there is. + +```raz Where run +module Where; +import Rt; + +proc inner(depth: INT); +begin + if depth = 0 then Rt.trace; return; end; + inner(depth - 1); +end; + +proc main*; +begin + inner(2); +end; + +end Where. +``` + +## Leaving the checks out + +A module that is sure of its indexes may say `check off;` after its imports and links, for speed. The module's own indexing and slicing is then unchecked, so an index out of range reads or writes whatever it reaches. Every other check stays (`nil` and division), and callers of the module keep theirs. Use it for a measured inner loop, never as a first step. + +## For gdb and the profiler + +The program carries names and line numbers, so `gdb` can break at `Fail.raz:6` and show raz source. `RAZ_PROFILE=1` in the environment makes a program sample itself every millisecond and say at the end where its time went, by procedure and by line. diff --git a/site/content/tour/12-generics.txt b/site/content/tour/12-generics.txt new file mode 100644 index 0000000..a2f88af --- /dev/null +++ b/site/content/tour/12-generics.txt @@ -0,0 +1,104 @@ +title: Generic modules +part: Go +summary: A module that takes types and procedures; the library's List, Map and Sort. +--- +A module may take types, and the procedures it needs on them, as parameters. `Biggest.raz`: + +```raz Biggest +``` + +and a program that uses it: + +```raz Generics run +``` + +Each import with its own arguments makes an instance: the module compiled again, with `T` standing for the type given, and `less` calling the procedure given. The arguments may name what the importing module declares later, as `before` is here. There is no run-time cost for being generic, and no boxing: `Ints.max` is exactly the code you would write by hand for `INT`. + +## Writing your own + +A generic module is an ordinary module with parameters in its header. Here is a stack of anything, which takes the allocator it grows from. + +```raz Stk +module Stk(T); +import Mem; + +type + Stack* = record + items: ^T; (* an array of cap Ts *) + cap*, len*: INT; + a: ^Mem.Allocator; + end; + +proc init*(s: ^Stack; a: ^Mem.Allocator); +begin + s^.a := a; + s^.items := nil; + s^.cap := 0; + s^.len := 0; +end; + +(* v on top; false if the allocator has no room *) +proc push*(s: ^Stack; v: T): BOOL; +var bigger: ^T; i, cap: INT; src, dst: ^T; +begin + if s^.len = s^.cap then + if s^.cap = 0 then cap := 4; else cap := s^.cap * 2; end; + bigger := ^T(Mem.alloc(s^.a, cap * SIZE(T), 8)); + if bigger = nil then return false; end; + for i := 0 to s^.len - 1 do + src := ^T(INT(s^.items) + i * SIZE(T)); + dst := ^T(INT(bigger) + i * SIZE(T)); + dst^ := src^; + end; + if s^.items # nil then Mem.free(s^.a, ^U8(s^.items)); end; + s^.items := bigger; + s^.cap := cap; + end; + dst := ^T(INT(s^.items) + s^.len * SIZE(T)); + dst^ := v; + INC(s^.len); + return true; +end; + +(* the top value, taken off; false if empty *) +proc pop*(s: ^Stack): (T, BOOL); +var z: T; p: ^T; +begin + if s^.len = 0 then return z, false; end; + DEC(s^.len); + p := ^T(INT(s^.items) + s^.len * SIZE(T)); + return p^, true; +end; + +end Stk. +``` + +```raz Uses run +module Uses; +import Out, Heap, Nums := Stk(INT), Pairs := Stk(Pair); + +type Pair = record a, b: INT; end; + +proc main*; +var n: Nums.Stack; p: Pairs.Stack; i, v: INT; ok: BOOL; pr: Pair; +begin + Nums.init(ADR(n), Heap.heap); + Pairs.init(ADR(p), Heap.heap); + for i := 1 to 10 do _ := Nums.push(ADR(n), i * i); end; + _ := Pairs.push(ADR(p), {a: 3, b: 4}); + v, ok := Nums.pop(ADR(n)); + Out.int(v); Out.str(" of "); Out.int(n.len + 1); Out.ln; + pr, ok := Pairs.pop(ADR(p)); + Out.int(pr.a * pr.b); Out.ln; + _, ok := Pairs.pop(ADR(p)); + if not ok then Out.str("empty\n"); end; +end; + +end Uses. +``` + +Two instances (`Nums` and `Pairs`) are two separate modules, compiled with their own `T`. Its pointer arithmetic is the one place where the program does what C does and leaves the checks behind; a library would keep that inside, as this does. + +## The library's generics + +The library's `List`, `Map` and `Sort` are generic modules. A `Map` takes its key hash and equality as procedure arguments: `import Count := Map([]U8, INT, Str.hash, Str.eq);`. The advanced tour uses each of them in a real program. diff --git a/site/content/tour/13-c.txt b/site/content/tour/13-c.txt new file mode 100644 index 0000000..833a565 --- /dev/null +++ b/site/content/tour/13-c.txt @@ -0,0 +1,89 @@ +title: Talking to C +part: Go +summary: Call a C library, be called back, share variables, and mind the two buffers. +--- +```raz Qsort run +``` + +An `extern` procedure is found by its name in the C library, or in a library a `link` line names. Its parameters are integers, reals, pointers and procedures, as C declares them; a raz procedure of such types can be given to C to call back, as `order` is. A record goes to C by pointer, never by value. + +## What using C costs + +A program that uses C is linked against it dynamically and starts through it, so that C's own set-up and clean-up run; one that doesn't is a static executable with nothing in it but its own code. A program uses C if any module it uses has an `extern` or a `link` of a library. + +## Varargs + +`...` after an `extern`'s parameters takes any number of further arguments, as `printf` wants. A string literal goes as a C string, an integer constant as an `INT`, a real constant as an `F64`. An `F32` is an error there, since C promotes it; write `F64(x)`. + +```raz Say run +module Say; +import Out; + +extern proc printf(format: ^U8; ...): I32; +extern proc fflush(f: ^U8): I32; +extern proc puts(s: ^U8): I32; + +proc main*; +var n: INT; x: F32; +begin + n := 42; + x := 2.5; + Out.str("raz first\n"); + Out.flush; (* Out has a buffer; so does C *) + _ := printf("C says %ld and %.2f and %s\n", n, F64(x), "hello"); + _ := puts("and puts"); + _ := fflush(nil); (* nil: every C stream *) + Out.str("raz again\n"); +end; + +end Say. +``` + +`Out` and C's `printf` keep two buffers, so a program that writes with both flushes one before it writes with the other, or the text comes out of order. + +## Libraries, and C's variables + +`link "libm.so.6";` names a shared library to load at run time. An `extern var` is C's variable itself: reading it reads C's, assigning it writes C's. + +```raz Env run +module Env; +import Out; + +extern var environ: ^^U8; +extern proc strlen(s: ^U8): UINT; +extern proc getenv(name: ^U8): ^U8; + +proc main*; +var p: ^U8; n: INT; +begin + n := 0; + while environ[n] # nil do INC(n); end; + if n > 0 then Out.str("the environment is not empty\n"); end; + p := getenv("RAZ_NO_SUCH_VARIABLE"); + if p = nil then Out.str("not set\n"); end; + Out.int(INT(strlen("six"))); Out.ln; +end; + +end Env. +``` + +## Callbacks + +Every raz procedure uses the System V calling convention, so any with parameters and a result of C's types may be given to C to call, as `qsort` is given `order` above. The procedure may not be a closure: it has only its arguments, so state travels through the pointer C hands back or a module variable. + +```raz Roots run +module Roots; +import Fmt; + +link "libm.so.6"; + +extern proc cbrt(x: F64): F64; +extern proc hypot(x, y: F64): F64; + +proc main*; +begin + Fmt.print("{} {}\n", [Fmt.real(cbrt(27.0), 3), Fmt.real(hypot(3.0, 4.0), 3)]); +end; + +end Roots. +``` diff --git a/site/content/tour/14-threads.txt b/site/content/tour/14-threads.txt new file mode 100644 index 0000000..b033e0e --- /dev/null +++ b/site/content/tour/14-threads.txt @@ -0,0 +1,120 @@ +title: Threads +part: Go +summary: Native threads without C, atomics, a mutex, and why the counter needs both. +--- +```raz Hits run +``` + +`Thread.spawn` runs a procedure in a thread of its own, with a stack of its own, and `Thread.join` waits for it to end. `XADD`, `CAS` and `XCHG` change a word atomically; a `Thread.Mutex` keeps a longer section to one thread at a time. `Out` and `Heap` lock themselves. + +## What goes wrong without them + +Two threads that each read a variable, add one and write it back can lose one of the additions. A plain `INC` on a variable shared by threads has no particular value afterwards; the report says so. `XADD` is the atomic add: it returns the old value and adds in one indivisible step. + +```raz Race run +module Race; +import Out, Thread; + +var + safe: INT; (* added to by XADD *) + plain: INT; (* added to by INC: unsafe, never printed *) + +proc work(_arg: ^U8); +var i: INT; +begin + for i := 1 to 100000 do + _ := XADD(ADR(safe), 1); + INC(plain); (* unsafe: lost additions *) + end; +end; + +proc main*; +var t: [4]^Thread.Thread; i: INT; err: ERROR; +begin + for i := 0 to 3 do + t[i], err := Thread.spawn(work, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to 3 do Thread.join(t[i]); end; + Out.str("safe "); Out.int(safe); Out.ln; +end; + +end Race. +``` + +The atomic count is always 400000. The plain one is usually lower, and different from run to run, which is why this page doesn't print it. + +## A mutex for longer sections + +An atomic is one word. When several variables must change together, take a `Thread.Mutex`; it sleeps while it waits, so it suits sections that take a while. Declare it as a module variable, since zero is free. + +```raz Bank run +module Bank; +import Out, Thread; + +var + m: Thread.Mutex; + balance, deposits: INT; (* kept in step, under m *) + +proc deposit(_arg: ^U8); +var i: INT; +begin + for i := 1 to 10000 do + Thread.lock(ADR(m)); + balance := balance + 5; + INC(deposits); + Thread.unlock(ADR(m)); + end; +end; + +proc main*; +var t: [3]^Thread.Thread; i: INT; err: ERROR; +begin + for i := 0 to 2 do + t[i], err := Thread.spawn(deposit, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to 2 do Thread.join(t[i]); end; + Out.int(deposits); Out.char(' '); Out.int(balance); Out.ln; +end; + +end Bank. +``` + +## Handing work out + +A thread's procedure takes one pointer argument. Pass a record's address to give each thread its own job and its own place to put the answer; then no one shares anything. + +```raz Jobs run +module Jobs; +import Out, Thread; + +type Job = record lo, hi: INT; sum: INT; end; + +proc work(arg: ^U8); +var j: ^Job; i: INT; +begin + j := ^Job(arg); + for i := j^.lo to j^.hi - 1 do j^.sum := j^.sum + i; end; +end; + +proc main*; +var jobs: [4]Job; t: [4]^Thread.Thread; i, total: INT; err: ERROR; +begin + for i := 0 to 3 do + jobs[i].lo := i * 250000; + jobs[i].hi := (i + 1) * 250000; + t[i], err := Thread.spawn(work, ^U8(ADR(jobs[i]))); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to 3 do + Thread.join(t[i]); + total := total + jobs[i].sum; + end; + Out.int(total); Out.ln; +end; + +end Jobs. +``` + +`Thread` makes its own threads, without C, so a program that uses it can't use C; one that does makes its threads with C's `pthread_create` instead. The advanced tour goes further into atomics, memory ordering and lock-free code. diff --git a/site/public/advanced/allocators.html b/site/public/advanced/allocators.html new file mode 100644 index 0000000..92b57cd --- /dev/null +++ b/site/public/advanced/allocators.html @@ -0,0 +1,193 @@ + + + + + +Writing an allocator - Beyond Go + + + +
        +
        +

        The library · lesson 6 of 18

        Writing an allocator

        +

        An allocator is a record of two procedures, and that is all Mem.Allocator is:

        +
        type Allocator* = record
        +    alloc*: proc(a: ^Allocator; size, align: INT): ^U8;   (* nil if out of room *)
        +    free*:  proc(a: ^Allocator; p: ^U8);
        +end;
        +

        NEW(p, a) calls a^.alloc(a, SIZE(T), alignment) and zeroes what it gets. Buf, List and Map call the same procedures. So anything that fills in these two fields is an allocator, and everything in the library works with it.

        +

        An allocator over a fixed array

        +

        Here is one that needs no system calls at all: it hands out memory from an array in the program, a bump allocator. This is the kind a program with no operating system, or no room for a heap, uses. free has nothing to do; reset forgets everything.

        +

        The trick that lets one procedure find its state is the same one Arena uses: the record puts base: Mem.Allocator first, so a ^Mem.Allocator and a ^Bump are the same address, and the procedure converts one to the other.

        +
        Bump.raz
        module Bump;
        +import Mem;
        +
        +type
        +    Bump* = record
        +        base*: Mem.Allocator;       (* first, so that ^Bump(a) finds the rest *)
        +        mem: ^U8;
        +        size, used*: INT;
        +    end;
        +
        +proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8;
        +var b: ^Bump; at: INT;
        +begin
        +    b := ^Bump(a);
        +    at := (b^.used + align - 1) div align * align;      (* round up to align *)
        +    if (size < 0) or (at + size > b^.size) then return nil; end;
        +    b^.used := at + size;
        +    return b^.mem + at;
        +end;
        +
        +proc free(_a: ^Mem.Allocator; _p: ^U8);
        +begin
        +end;
        +
        +(* a bump allocator over the size bytes at mem *)
        +proc init*(b: ^Bump; mem: ^U8; size: INT);
        +begin
        +    b^.base := {alloc: alloc, free: free};
        +    b^.mem := mem;
        +    b^.size := size;
        +    b^.used := 0;
        +end;
        +
        +(* everything forgotten, the memory used again *)
        +proc reset*(b: ^Bump);
        +begin
        +    b^.used := 0;
        +end;
        +
        +end Bump.
        +
        Bumping.raz
        module Bumping;
        +import Out, Bump;
        +
        +type Point = record x, y: INT; end;
        +
        +var arena: [256]U8;           (* the allocator's whole world *)
        +
        +proc main*;
        +var b: Bump.Bump; p, q: ^Point; many: INT; r: ^Point;
        +begin
        +    Bump.init(ADR(b), ADR(arena[0]), 256);
        +    NEW(p, ADR(b.base));
        +    NEW(q, ADR(b.base));
        +    p^.x := 1; q^.y := 2;
        +    Out.int(b.used); Out.str(" bytes used by two points\n");
        +    many := 2;
        +    repeat
        +        NEW(r, ADR(b.base));
        +        if r # nil then INC(many); end;
        +    until r = nil;
        +    Out.int(many); Out.str(" points fit in 256 bytes\n");
        +    Bump.reset(ADR(b));
        +    NEW(r, ADR(b.base));
        +    if r # nil then Out.str("room again after a reset\n"); end;
        +end;
        +
        +end Bumping.
        +
        32 bytes used by two points
        +16 points fit in 256 bytes
        +room again after a reset
        +
        +

        An allocator that runs out says so with nil, and the caller decides what that means. Nothing else in the program is touched.

        +

        An allocator that counts

        +

        An allocator can wrap another. This one forwards to whatever it is given and keeps count, which is how to find out what a piece of code allocates, or to prove that a path allocates nothing.

        +
        Counted.raz
        module Counted;
        +import Mem;
        +
        +type
        +    Counted* = record
        +        base*: Mem.Allocator;       (* first *)
        +        inner: ^Mem.Allocator;
        +        allocs*, frees*, bytes*: INT;
        +    end;
        +
        +proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8;
        +var c: ^Counted; p: ^U8;
        +begin
        +    c := ^Counted(a);
        +    p := Mem.alloc(c^.inner, size, align);
        +    if p # nil then INC(c^.allocs); INC(c^.bytes, size); end;
        +    return p;
        +end;
        +
        +proc free(a: ^Mem.Allocator; p: ^U8);
        +var c: ^Counted;
        +begin
        +    c := ^Counted(a);
        +    INC(c^.frees);
        +    Mem.free(c^.inner, p);
        +end;
        +
        +(* a counting allocator in front of inner *)
        +proc init*(c: ^Counted; inner: ^Mem.Allocator);
        +begin
        +    c^.base := {alloc: alloc, free: free};
        +    c^.inner := inner;
        +    c^.allocs := 0;
        +    c^.frees := 0;
        +    c^.bytes := 0;
        +end;
        +
        +end Counted.
        +
        Audit.raz
        module Audit;
        +import Fmt, Heap, Mem, Buf, Counted, Names := List([]U8);
        +
        +proc main*;
        +var c: Counted.Counted; b: Buf.Buf; l: Names.List; i: INT; p: ^U8;
        +begin
        +    Counted.init(ADR(c), Heap.heap);
        +    Buf.init(ADR(b), ADR(c.base));
        +    for i := 1 to 200 do Buf.str(ADR(b), "0123456789"); end;
        +    Fmt.print("a buffer of {} bytes took {} allocations\n",
        +        [Fmt.int(b.len), Fmt.int(c.allocs)]);
        +    Buf.done(ADR(b));
        +
        +    Names.init(ADR(l), ADR(c.base));
        +    for i := 1 to 10 do _ := Names.push(ADR(l), "x"); end;
        +    Fmt.print("{} allocations in all, {} frees so far\n", [Fmt.int(c.allocs), Fmt.int(c.frees)]);
        +    Names.clear(ADR(l));
        +    Fmt.print("{} frees after clear\n", [Fmt.int(c.frees)]);
        +
        +    p := Mem.alloc(ADR(c.base), 64, 8);
        +    Mem.free(ADR(c.base), p);
        +end;
        +
        +end Audit.
        +
        a buffer of 2000 bytes took 6 allocations
        +16 allocations in all, 6 frees so far
        +16 frees after clear
        +
        +

        A Buf grows by doubling, so two thousand bytes took a handful of allocations and not two hundred. That is the sort of thing a counting allocator is for.

        +

        What to take from this

        +
        • An allocator is a value, so it is passed, wrapped, swapped in a test and replaced by a bump allocator in a program with no heap.
        • A library function that needs memory takes the allocator as a parameter, so its caller owns the policy.
        • An allocator can use the record-first trick to carry any state it needs, because converting a pointer to a record's first field and back is the same address.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/asm.html b/site/public/advanced/asm.html new file mode 100644 index 0000000..53e6a25 --- /dev/null +++ b/site/public/advanced/asm.html @@ -0,0 +1,215 @@ + + + + + +Procedures in assembly - Beyond Go + + + +
        +
        +

        The machine · lesson 11 of 18

        Procedures in assembly

        +

        Sometimes a program needs an instruction the language has no word for: reading the cycle counter, asking the CPU what it is, counting bits in one instruction, a square root in the hardware. A procedure whose body is code is machine code, written by hand in the target's assembly language, one instruction to each ;, up to end.

        +

        The compiler doesn't look past what the instructions say. It trusts you, and you owe it a few rules.

        +

        A first one

        +

        This reads the processor's time stamp counter. The result of a procedure goes in rax; rdtsc leaves the counter in edx:eax, so the two halves are joined first.

        +
        Cycles.raz
        module Cycles;
        +import Out;
        +
        +proc rdtsc*: U64;
        +code
        +    rdtsc;
        +    shl rdx, 32;
        +    or rax, rdx;
        +    ret;
        +end rdtsc;
        +
        +proc main*;
        +var a, b: U64;
        +begin
        +    a := rdtsc();
        +    b := rdtsc();
        +    if b > a then Out.str("the counter moves forward\n"); end;
        +end;
        +
        +end Cycles.
        +
        the counter moves forward
        +
        +

        A code procedure is called like any procedure. Everything in it is yours, ret included.

        +

        The convention

        +

        A code procedure follows the System V convention, as every raz procedure does:

        +
        • Integer and pointer arguments arrive in rdi, rsi, rdx, rcx, r8 and r9; F32 and F64 ones in xmm0 to xmm7.
        • The result goes in rax (and rdx for a second) or xmm0.
        • It must keep rbx, rbp, rsp and r12 to r15 as it found them. rax, rcx, rdx, rsi, rdi and r8 to r11 are free to change.
        • Its parameters and results are therefore of the types C can take, at most six integer and eight real parameters and two results.
        +

        That is why the next one is so short: the argument is already in rdi.

        +
        Bits.raz
        module Bits;
        +import Out;
        +
        +(* the bytes of x in the opposite order: bswap rax, which the assembler
        +   doesn't know, written as its bytes *)
        +proc swap64(x: U64): U64;
        +code
        +    mov rax, rdi;
        +    db 48H, 0FH, 0C8H;
        +    ret;
        +end swap64;
        +
        +(* the number of bits set in x: popcnt rax, rdi *)
        +proc ones(x: U64): INT;
        +code
        +    db 0F3H, 48H, 0FH, 0B8H, 0C7H;
        +    ret;
        +end ones;
        +
        +proc main*;
        +begin
        +    Out.str("0x"); Out.hex(swap64(0102030405060708H), 16); Out.ln;
        +    Out.int(ones(0FFH)); Out.char(' ');
        +    Out.int(ones(0)); Out.char(' ');
        +    Out.int(ones(0FFFFFFFFFFFFFFFFH)); Out.ln;
        +end;
        +
        +end Bits.
        +
        0x0807060504030201
        +8 0 64
        +
        +

        db writes any bytes, for an instruction the assembler doesn't know. Which instructions it knows is the implementation's business; db keeps you from waiting for it to learn one. (The two instructions above are from the processor manuals: bswap r64 is REX.W 0F C8+r, popcnt r64, r/m64 is F3 REX.W 0F B8 /r.)

        +

        Labels and loops

        +

        A label, name:, names the place of the instruction after it, within the procedure. Jumps go to labels, and a constant of the module may stand wherever a number does. This sums an array of INTs, which a pointer and a length describe:

        +
        Sum.raz
        module Sum;
        +import Out;
        +
        +(* the sum of the n INTs at p *)
        +proc sum(p: ^INT; n: INT): INT;
        +code
        +    xor eax, eax;
        +    test rsi, rsi;
        +    jle done;
        +again:
        +    add rax, [rdi];
        +    add rdi, 8;
        +    dec rsi;
        +    jnz again;
        +done:
        +    ret;
        +end sum;
        +
        +(* the same in raz, to check it against *)
        +proc sumRaz(a: []INT): INT;
        +var i, t: INT;
        +begin
        +    for i := 0 to LEN(a) - 1 do t := t + a[i]; end;
        +    return t;
        +end;
        +
        +proc main*;
        +var a: [6]INT; i: INT;
        +begin
        +    for i := 0 to 5 do a[i] := (i + 1) * 100; end;
        +    Out.int(sum(ADR(a[0]), 6)); Out.char(' ');
        +    Out.int(sumRaz(a)); Out.char(' ');
        +    Out.int(sum(ADR(a[0]), 0)); Out.ln;
        +end;
        +
        +end Sum.
        +
        2100 2100 0
        +
        +

        A procedure may have up to 64 labels. The check against the raz version is the habit worth keeping: write the procedure in raz first, then in assembly, and compare their results on awkward inputs.

        +

        Two results, and reals

        +

        A second result goes in rdx. That is exactly where idiv leaves the remainder, so divmod is four instructions. Reals travel in the xmm registers.

        +
        Divmod.raz
        module Divmod;
        +import Out, Fmt;
        +
        +(* quotient and remainder, as idiv gives them: rax and rdx *)
        +proc divmod(a, b: INT): (INT, INT);
        +code
        +    mov rax, rdi;
        +    cqo;
        +    idiv rsi;
        +    ret;
        +end divmod;
        +
        +(* a * x + b, on F64s in xmm0 to xmm2 *)
        +proc fma(a, x, b: F64): F64;
        +code
        +    mulsd xmm0, xmm1;
        +    addsd xmm0, xmm2;
        +    ret;
        +end fma;
        +
        +proc main*;
        +var q, r: INT;
        +begin
        +    q, r := divmod(-17, 5);
        +    Out.int(q); Out.char(' '); Out.int(r); Out.ln;
        +    Fmt.print("{}\n", [Fmt.real(fma(2.0, 3.5, 0.25), 2)]);
        +end;
        +
        +end Divmod.
        +
        -3 -2
        +7.25
        +
        +

        idiv by zero stops the program with the machine's own division fault. It isn't a check the compiler added, since the compiler doesn't look inside a code procedure.

        +

        Keeping what isn't yours

        +

        A procedure that uses rbx must put it back. cpuid clobbers rbx, so the vendor-string example saves it with push and restores it with pop, and keeps the buffer's address in r8 while it works:

        +
        Vendor.raz
        module Vendor;
        +import Out;
        +
        +(* the 12 bytes of the processor vendor, in buf (rdi) *)
        +proc vendor(buf: ^U8);
        +code
        +    push rbx;
        +    mov r8, rdi;
        +    xor eax, eax;
        +    cpuid;
        +    mov [r8], ebx;
        +    mov [r8 + 4], edx;
        +    mov [r8 + 8], ecx;
        +    pop rbx;
        +    ret;
        +end vendor;
        +
        +proc main*;
        +var buf: [12]U8; i: INT; ok: BOOL;
        +begin
        +    vendor(ADR(buf[0]));
        +    ok := true;
        +    for i := 0 to 11 do
        +        if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end;
        +    end;
        +    if ok then Out.str("the vendor is 12 printable bytes\n"); end;
        +end;
        +
        +end Vendor.
        +
        the vendor is 12 printable bytes
        +
        +

        What goes wrong

        +

        A code procedure that breaks its rules breaks the program, and what follows isn't defined. Writing through a wrong pointer, a changed rbx, a missing ret, a stack left unbalanced: the language can't help, because it doesn't see inside. Keep them short, give each a comment that says what it expects in which register, test each against a raz twin, and use them for what only the machine can do.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/atomics.html b/site/public/advanced/atomics.html new file mode 100644 index 0000000..21836b2 --- /dev/null +++ b/site/public/advanced/atomics.html @@ -0,0 +1,195 @@ + + + + + +Atomics - Beyond Go + + + +
        +
        +

        Shared memory · lesson 15 of 18

        Atomics

        +

        A volatile access is one access. An atomic is one *indivisible* step: nothing can happen between its read and its write, so two threads using it can't lose each other's work. There are three, built into the language as procedures, and they are sequentially consistent on every target:

        +

        | Call | Does | |---|---| | XADD(p, x) | adds x to p^ and returns the value before | | XCHG(p, x) | sets p^ := x and returns the value before | | CAS(p, old, new) | if p^ = old, sets p^ := new and returns true; otherwise false |

        +

        p is a ^T or ^VOLATILE T where T is INT, UINT or a pointer type (INT or UINT for XADD). They compile to single x86-64 instructions: lock xadd, xchg (which is always locked when it touches memory) and lock cmpxchg:

        +
        Ops.raz
        module Ops;
        +
        +var counter: INT;
        +
        +proc main*;
        +begin
        +    _ := XADD(ADR(counter), 5);
        +    _ := XCHG(ADR(counter), 100);
        +    _ := CAS(ADR(counter), 100, 7);
        +end;
        +
        +end Ops.
        +
        $ raz -S Ops.raz | grep -i "lock\|xchg"
        +            23  lock xadd [r8], rax
        +     8      _ := XCHG(ADR(counter), 100);
        +            43  xchg [r8], rax
        +            67  lock cmpxchg [r8], r10
        +

        What each one gives you

        +

        XADD is a counter, or a ticket dispenser: every caller gets a different number. XCHG takes the old value and leaves a new one, which is a flag, a swap, or the release of a lock. CAS is the general one: "if nobody changed it since I looked, change it". Most lock-free code is a loop around it.

        +
        Tickets.raz
        module Tickets;
        +import Out, Thread;
        +
        +var
        +    next: INT;                  (* the next ticket to give out *)
        +    seen: [4000]U8;             (* which tickets were taken, one byte each *)
        +
        +proc work(_arg: ^U8);
        +var i, t: INT;
        +begin
        +    for i := 1 to 1000 do
        +        t := XADD(ADR(next), 1);      (* a ticket no other thread gets *)
        +        seen[t] := 1;
        +    end;
        +end;
        +
        +proc main*;
        +var th: [4]^Thread.Thread; i, taken: INT; err: ERROR;
        +begin
        +    for i := 0 to 3 do
        +        th[i], err := Thread.spawn(work, nil);
        +        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    end;
        +    for i := 0 to 3 do Thread.join(th[i]); end;
        +    for i := 0 to 3999 do taken := taken + INT(seen[i]); end;
        +    Out.int(next); Out.char(' '); Out.int(taken); Out.ln;
        +end;
        +
        +end Tickets.
        +
        4000 4000
        +
        +

        Four thousand tickets, four thousand different numbers, no two threads with the same one. Each thread writes into its own bytes of seen, so no plain write is shared.

        +

        A compare-and-swap loop

        +

        Anything that can be computed from the old value can be made atomic with a loop around CAS: read the value, compute the new one, and try to swap it in; if someone got there first, read again. Here is an atomic maximum, which no single instruction does.

        +
        Peak.raz
        module Peak;
        +import Out, Thread;
        +
        +var peak: INT;
        +
        +(* raises peak to v if v is bigger, however many threads call it *)
        +proc raise(v: INT);
        +var seen: INT;
        +begin
        +    seen := peak;
        +    while seen < v do
        +        if CAS(ADR(peak), seen, v) then return; end;
        +        seen := peak;                  (* someone changed it: look again *)
        +    end;
        +end;
        +
        +proc work(arg: ^U8);
        +var i, base: INT;
        +begin
        +    base := INT(arg);
        +    for i := 0 to 999 do raise(base + i * 7 mod 1001); end;
        +end;
        +
        +proc main*;
        +var th: [4]^Thread.Thread; i: INT; err: ERROR;
        +begin
        +    for i := 0 to 3 do
        +        th[i], err := Thread.spawn(work, ^U8(i * 1000));
        +        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    end;
        +    for i := 0 to 3 do Thread.join(th[i]); end;
        +    Out.int(peak); Out.ln;
        +end;
        +
        +end Peak.
        +
        3994
        +
        +

        The result doesn't depend on how the threads interleave: it is the largest value any of them offered. That is the test of a correct atomic algorithm, and why this kind of code is written once, carefully, and used everywhere.

        +

        A lock, from first principles

        +

        A lock is a word that is 0 when free and 1 when held. To take it, CAS it from 0 to 1; if that fails, someone holds it, so try again. To give it up, XCHG it back to 0. This is exactly the library's Lock, printed from lib/Lock.raz:

        +
        $ sed -n '/^type Lock/,/^proc main/p' $RAZLIB/Lock.raz | head -n -2
        +type Lock* = record held: INT; end;
        +
        +(* Takes l, waiting while another thread holds it. *)
        +proc take*(l: ^Lock);
        +var tries: INT;
        +begin
        +    tries := 0;
        +    while not CAS(ADR(l^.held), 0, 1) do
        +        INC(tries);
        +        if tries = 64 then Sys.yield; tries := 0; end;
        +    end;
        +end;
        +
        +(* Gives up l, which the caller holds. *)
        +proc give*(l: ^Lock);
        +begin
        +    _ := XCHG(ADR(l^.held), 0);
        +end;
        +

        And here is a use of it: a structure with two fields that must stay in step, which no single atomic can protect.

        +
        Account.raz
        module Account;
        +import Out, Lock, Thread;
        +
        +var
        +    lock: Lock.Lock;
        +    deposits, balance: INT;      (* balance = 3 * deposits, always, under lock *)
        +
        +proc work(_arg: ^U8);
        +var i: INT;
        +begin
        +    for i := 1 to 20000 do
        +        Lock.take(ADR(lock));
        +        INC(deposits);
        +        INC(balance, 3);
        +        Lock.give(ADR(lock));
        +    end;
        +end;
        +
        +proc main*;
        +var th: [4]^Thread.Thread; i: INT; err: ERROR;
        +begin
        +    for i := 0 to 3 do
        +        th[i], err := Thread.spawn(work, nil);
        +        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    end;
        +    for i := 0 to 3 do Thread.join(th[i]); end;
        +    Out.int(deposits); Out.char(' '); Out.int(balance); Out.ln;
        +    if balance = 3 * deposits then Out.str("in step\n"); end;
        +end;
        +
        +end Account.
        +
        80000 240000
        +in step
        +
        +

        A Lock spins, giving up the processor now and then, so it is for sections of a few instructions. Thread.Mutex sleeps on a futex, so it is for longer ones. A spinning lock held for a long time, or by a thread that was descheduled, burns processors; that is the price of its speed when contention is short.

        +

        Choosing

        +
        • A counter, a ticket, a flag: XADD or XCHG.
        • A value computed from the old one: a CAS loop.
        • Several variables that must change together: a Lock or a Mutex. Don't try to be clever with several atomics; the one invariant spanning them is the thing that breaks.
        +

        All three act on a word. For anything bigger, the thing you swap is a pointer to the bigger thing: the next lessons do exactly that.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/bytes.html b/site/public/advanced/bytes.html new file mode 100644 index 0000000..cbd6b54 --- /dev/null +++ b/site/public/advanced/bytes.html @@ -0,0 +1,193 @@ + + + + + +Strings and bytes - Beyond Go + + + +
        +
        +

        The library · lesson 2 of 18

        Strings and bytes

        +

        A []U8 is both a string and a block of bytes. Str has what is done with them: comparing, finding, hashing, copying into memory of your own, UTF-8, numbers, and the fixed byte orders of file formats and network protocols.

        +

        Ordering and hashing

        +

        Str.cmp gives -1, 0 or 1, byte by byte, so it orders UTF-8 text by code point. Str.eq is equality. Str.hash is FNV-1a, 64 bits; it is what a Map of strings uses.

        +
        Order.raz
        module Order;
        +import Out, Str, Fmt;
        +
        +proc main*;
        +var names: [4][]U8; i, j: INT; t: []U8;
        +begin
        +    names := ["pear", "Apple", "fig", "apple"];
        +    (* a small insertion sort, with Str.cmp *)
        +    for i := 1 to 3 do
        +        t := names[i];
        +        j := i - 1;
        +        while (j >= 0) and (Str.cmp(names[j], t) > 0) do
        +            names[j + 1] := names[j];
        +            DEC(j);
        +        end;
        +        names[j + 1] := t;
        +    end;
        +    for i := 0 to 3 do Out.str(names[i]); Out.char(' '); end;
        +    Out.ln;
        +    Fmt.print("{}\n", [Fmt.hex(Str.hash("raz"))]);
        +    if Str.hash("raz") = Str.hash("raz") then Out.str("stable\n"); end;
        +end;
        +
        +end Order.
        +
        Apple apple fig pear 
        +89F6BC1960FF4912
        +stable
        +
        +

        Upper case sorts before lower, since 'A' is 65 and 'a' is 97: Str.cmp doesn't pretend to know a language's alphabet.

        +

        Keeping a string

        +

        A slice of a string constant lives forever, but a slice of a buffer lives only as long as the buffer. To keep one past that, Str.copy takes memory from an allocator and says whether it got any.

        +
        Keep.raz
        module Keep;
        +import Out, Str, Heap, Mem;
        +
        +type Entry = record name: []U8; n: INT; end;
        +
        +var entries: [3]Entry;
        +
        +(* remembers a name that the caller will overwrite *)
        +proc remember(slot: INT; name: []U8);
        +var copy: []U8; ok: BOOL;
        +begin
        +    copy, ok := Str.copy(Heap.heap, name);
        +    if ok then entries[slot].name := copy; entries[slot].n := slot; end;
        +end;
        +
        +proc main*;
        +var scratch: [16]U8; i: INT;
        +begin
        +    for i := 0 to 2 do
        +        scratch := "name-";
        +        scratch[5] := U8('0' + i);
        +        remember(i, scratch[0..6]);
        +        scratch := "overwritten!";
        +    end;
        +    for i := 0 to 2 do
        +        Out.str(entries[i].name); Out.char(' ');
        +        Mem.free(Heap.heap, ^U8(ADR(entries[i].name[0])));
        +    end;
        +    Out.ln;
        +end;
        +
        +end Keep.
        +
        name-0 name-1 name-2 
        +
        +

        Binary formats

        +

        A file format or a network protocol has a byte order of its own, not the machine's. Str.le and Str.be read an unsigned number of up to 8 bytes in a fixed order (little- or big-endian) and Str.putLE and Str.putBE write one. They work on any slice, so a header is read where it lies, with no struct to overlay and no byte swapping to forget.

        +

        Here is a small record format: a 4-byte tag, a 2-byte big-endian length, a 4-byte little-endian checksum, then the data.

        +
        Frame.raz
        module Frame;
        +import Out, Fmt, Str;
        +
        +const HeaderSize = 10;
        +
        +(* the sum of the bytes of data, all mod 2^32 *)
        +proc checksum(data: []U8): U32;
        +var i: INT; sum: U32;
        +begin
        +    for i := 0 to LEN(data) - 1 do sum := sum + U32(data[i]); end;
        +    return sum;
        +end;
        +
        +(* writes a frame to out, which must have room; its length *)
        +proc pack(out: []U8; tag, data: []U8): INT;
        +begin
        +    COPY(out[0..4], tag);
        +    Str.putBE(out[4..6], U64(LEN(data)));
        +    Str.putLE(out[6..10], U64(checksum(data)));
        +    COPY(out[HeaderSize..HeaderSize + LEN(data)], data);
        +    return HeaderSize + LEN(data);
        +end;
        +
        +proc main*;
        +var buf: [64]U8; n, len: INT; sum: U32; i: INT;
        +begin
        +    n := pack(buf, "DATA", "hello");
        +    for i := 0 to n - 1 do
        +        Out.hex(U64(buf[i]), 2); Out.char(' ');
        +    end;
        +    Out.ln;
        +    (* and back *)
        +    len := INT(Str.be(buf[4..6]));
        +    sum := U32(Str.le(buf[6..10]));
        +    Fmt.print("tag {}, {} bytes, checksum {}, ", [Fmt.str(buf[0..4]), Fmt.int(len), Fmt.hex(U64(sum))]);
        +    if sum = checksum(buf[HeaderSize..HeaderSize + len]) then
        +        Out.str("valid: "); Out.str(buf[HeaderSize..HeaderSize + len]);
        +    else
        +        Out.str("corrupt");
        +    end;
        +    Out.ln;
        +end;
        +
        +end Frame.
        +
        44 41 54 41 00 05 14 02 00 00 68 65 6C 6C 6F 
        +tag DATA, 5 bytes, checksum 214, valid: hello
        +
        +

        The output is the same on a little-endian and a big-endian machine, because the bytes are written one at a time in the order the format says.

        +

        Numbers and text

        +

        Str.toInt reads a decimal number with an optional sign and nothing else, and says whether it was one. Fmt goes the other way. Str.encode and Str.decode move between characters and UTF-8, as the first tour showed.

        +
        Numbers.raz
        module Numbers;
        +import Out, Str;
        +
        +(* the sum of the numbers in a comma separated list, or -1 if any isn't *)
        +proc total(s: []U8): I64;
        +var start, i: INT; sum, n: I64; ok: BOOL;
        +begin
        +    start := 0;
        +    for i := 0 to LEN(s) do
        +        if (i = LEN(s)) or (s[i] = ',') then
        +            n, ok := Str.toInt(s[start..i]);
        +            if not ok then return -1; end;
        +            sum := sum + n;
        +            start := i + 1;
        +        end;
        +    end;
        +    return sum;
        +end;
        +
        +proc main*;
        +begin
        +    Out.int(total("10,20,-5,+7")); Out.ln;
        +    Out.int(total("10,x,20")); Out.ln;
        +    Out.int(total("10,,20")); Out.ln;
        +end;
        +
        +end Numbers.
        +
        32
        +-1
        +-1
        +

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/collections.html b/site/public/advanced/collections.html new file mode 100644 index 0000000..3a040a9 --- /dev/null +++ b/site/public/advanced/collections.html @@ -0,0 +1,162 @@ + + + + + +Lists, maps and sorting - Beyond Go + + + +
        +
        +

        The library · lesson 3 of 18

        Lists, maps and sorting

        +

        The three generic modules are instantiated like any other generic module, with the types and procedures they need. All three take their memory from an allocator you give them; none of them allocates anything you didn't ask for.

        +

        List(T)

        +

        A singly linked list with push at the front, pop from the front, and the nodes exported, so a program walks it itself. Both can fail if the allocator is out of room, and say so.

        +
        Pile.raz
        module Pile;
        +import Out, Heap, Ints := List(INT);
        +
        +proc main*;
        +var l: Ints.List; n: ^Ints.Node; v: INT;
        +begin
        +    Ints.init(ADR(l), Heap.heap);
        +    defer Ints.clear(ADR(l));
        +    for v := 1 to 5 do _ := Ints.push(ADR(l), v * v); end;
        +    Ints.reverse(ADR(l));                    (* oldest first *)
        +    n := l.head;
        +    while n # nil do Out.int(n^.val); Out.char(' '); n := n^.next; end;
        +    Out.ln;
        +    v, _ := Ints.pop(ADR(l));
        +    Out.int(v); Out.str(" popped, "); Out.int(l.len); Out.str(" left\n");
        +end;
        +
        +end Pile.
        +
        1 4 9 16 25 
        +1 popped, 4 left
        +
        +

        Map(K, V; hash, eq)

        +

        A hash map. Its key's hash and equality are procedure arguments, so any type can be a key. put replaces what a key maps to; get says what it maps to and whether it maps to anything; remove says whether the key was there. next walks the map: from 0, it gives the next entry and the number to pass for the one after, and -1 when there are no more.

        +
        Ages.raz
        module Ages;
        +import Out, Fmt, Str, Heap, Book := Map([]U8, INT, Str.hash, Str.eq);
        +
        +proc main*;
        +var m: Book.Map; age: INT; found, ok: BOOL; i: INT; v: INT;
        +begin
        +    Book.init(ADR(m), Heap.heap);
        +    _ := Book.put(ADR(m), "ada", 36);
        +    _ := Book.put(ADR(m), "grace", 45);
        +    _ := Book.put(ADR(m), "alan", 41);
        +    _ := Book.put(ADR(m), "ada", 37);                (* replaces *)
        +    age, found := Book.get(ADR(m), "ada");
        +    Fmt.print("ada: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]);
        +    age, found := Book.get(ADR(m), "linus");
        +    Fmt.print("linus: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]);
        +    ok := Book.remove(ADR(m), "alan");
        +    Fmt.print("{} entries, removed {}\n", [Fmt.int(m.len), Fmt.bool(ok)]);
        +    v := 0;
        +    i, _, age := Book.next(ADR(m), 0);
        +    while i >= 0 do
        +        INC(v, age);
        +        i, _, age := Book.next(ADR(m), i);
        +    end;
        +    Out.int(v); Out.str(" years in all\n");
        +end;
        +
        +end Ages.
        +
        ada: 37 (true)
        +linus: 0 (false)
        +2 entries, removed true
        +82 years in all
        +
        +

        A map's order is its own, so a program that wants an order collects the entries and sorts them, as the next section does.

        +

        Sort(T; less)

        +

        An in-place sort of a slice, by a less procedure, in n log n at most and with no memory of its own. Elements equal by less may change places.

        +

        Putting them together

        +

        Counting words, then listing them by count and then alphabetically: a Map for the counts, an array of records to sort, and Sort with a two-level less.

        +
        Freq.raz
        module Freq;
        +import Fmt, Str, Heap,
        +    Count := Map([]U8, INT, Str.hash, Str.eq),
        +    Rank := Sort(Entry, before);
        +
        +type Entry = record word: []U8; n: INT; end;
        +
        +const Text = "the cat and the hat and the bat sat on the mat and the cat sat";
        +
        +(* more first; equal counts alphabetically *)
        +proc before(a, b: Entry): BOOL;
        +begin
        +    if a.n # b.n then return a.n > b.n; end;
        +    return Str.cmp(a.word, b.word) < 0;
        +end;
        +
        +proc main*;
        +var
        +    m: Count.Map; entries: [32]Entry; i, start, k, n, found: INT;
        +    w: []U8; key: []U8; v: INT;
        +begin
        +    Count.init(ADR(m), Heap.heap);
        +    start := 0;
        +    for i := 0 to LEN(Text) do
        +        if (i = LEN(Text)) or (Text[i] = ' ') then
        +            w := Text[start..i];
        +            k, _ := Count.get(ADR(m), w);
        +            _ := Count.put(ADR(m), w, k + 1);
        +            start := i + 1;
        +        end;
        +    end;
        +    n := 0;
        +    found, key, v := Count.next(ADR(m), 0);
        +    while found >= 0 do
        +        entries[n].word := key;
        +        entries[n].n := v;
        +        INC(n);
        +        found, key, v := Count.next(ADR(m), found);
        +    end;
        +    Rank.sort(entries[0..n]);
        +    for i := 0 to n - 1 do
        +        Fmt.print("{} {}\n", [Fmt.int(entries[i].n), Fmt.str(entries[i].word)]);
        +    end;
        +end;
        +
        +end Freq.
        +
        5 the
        +3 and
        +2 cat
        +2 sat
        +1 bat
        +1 hat
        +1 mat
        +1 on
        +
        +

        The keys here are slices of the constant text, so they outlive the map; a program whose keys come from a buffer it will reuse copies them first with Str.copy.

        +

        Choosing

        +

        Use a List when you push and pop at one end and walk it in order. Use a Map when you look things up by key. Use an array and Sort when you know the size and want an order. When none of them fits, they are each under a hundred lines of raz in lib/, and the advanced tour's allocator lesson shows what is underneath.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/files.html b/site/public/advanced/files.html new file mode 100644 index 0000000..14f9c6f --- /dev/null +++ b/site/public/advanced/files.html @@ -0,0 +1,227 @@ + + + + + +Files and the command line - Beyond Go + + + +
        +
        +

        The library · lesson 4 of 18

        Files and the command line

        +

        Files is for the common case: a whole file read or written in one call. Sys is the system underneath, for everything else. Opt reads a command line from a table, so that the help and the error messages can't drift from the code.

        +

        A whole file

        +

        Files.write(path, data) makes the file hold data, and Files.read(path, b) adds the whole file to a Buf. Both say whether they worked.

        +
        Notes.raz
        module Notes;
        +import Out, Files, Buf, Heap;
        +
        +proc main*;
        +var b: Buf.Buf; ok: BOOL;
        +begin
        +    ok := Files.write("notes.txt", "first line\nsecond line\n");
        +    if not ok then Out.str("can't write\n"); return; end;
        +    Buf.init(ADR(b), Heap.heap);
        +    defer Buf.done(ADR(b));
        +    ok := Files.read("notes.txt", ADR(b));
        +    if ok then
        +        Out.int(b.len); Out.str(" bytes: "); Out.str(Buf.bytes(ADR(b)));
        +    end;
        +    ok := Files.read("missing.txt", ADR(b));
        +    if not ok then Out.str("missing.txt: not there\n"); end;
        +end;
        +
        +end Notes.
        +
        23 bytes: first line
        +second line
        +missing.txt: not there
        +
        +

        Descriptors

        +

        Underneath, a file is a descriptor, an INT. Sys.open takes the path and the way to open it as a set; read, write, seek and close do what they say. A result that can fail is a number, and minus an errno if it failed, as on Linux itself. Reading in a loop is the pattern for anything too big to hold at once.

        +
        Count.raz
        module Count;
        +import Out, Sys;
        +
        +(* the lines of the file at path, or minus an errno *)
        +proc lines(path: []U8): INT;
        +var fd, n, i, count: INT; buf: [4096]U8;
        +begin
        +    fd := Sys.openRead(path);
        +    if fd < 0 then return fd; end;
        +    defer Sys.close(fd);
        +    n := Sys.read(fd, buf);
        +    while n > 0 do
        +        for i := 0 to n - 1 do
        +            if buf[i] = '\n' then INC(count); end;
        +        end;
        +        n := Sys.read(fd, buf);
        +    end;
        +    if n < 0 then return n; end;
        +    return count;
        +end;
        +
        +proc main*;
        +var fd: INT; pos: I64;
        +begin
        +    fd := Sys.create("log.txt");
        +    _ := Sys.write(fd, "a\nb\nc\n");
        +    pos := Sys.seek(fd, 2, false);              (* from the start *)
        +    Out.int(pos); Out.ln;
        +    Sys.close(fd);
        +    Out.int(lines("log.txt")); Out.str(" lines\n");
        +    Out.int(lines("/no/such/file")); Out.ln;     (* -2: ENOENT *)
        +    fd := Sys.open("log.txt", {Sys.writing, Sys.appending});
        +    _ := Sys.write(fd, "d\n");
        +    Sys.close(fd);
        +    Out.int(lines("log.txt")); Out.str(" lines now\n");
        +end;
        +
        +end Count.
        +
        2
        +3 lines
        +-2
        +4 lines now
        +
        +

        Looking at a file, and a directory

        +

        Sys.info says a file's size, modification time, permissions, and whether it is a directory, a regular file or a link. Sys.openDir and nextEntry list a directory, in no particular order, so a program that prints one sorts it first. A name from nextEntry is good only until the next call, so the program keeps a copy.

        +
        Tree.raz
        module Tree;
        +import Out, Sys, Str, Heap, Mem, Buf, Order := Sort([]U8, before);
        +
        +proc before(a, b: []U8): BOOL;
        +begin
        +    return Str.cmp(a, b) < 0;
        +end;
        +
        +(* a file made to hold text *)
        +proc put(path, text: []U8);
        +var fd: INT;
        +begin
        +    fd := Sys.create(path);
        +    _ := Sys.write(fd, text);
        +    Sys.close(fd);
        +end;
        +
        +proc main*;
        +var
        +    d: Sys.Dir; name, copy: []U8; more, ok: BOOL; i, n: INT;
        +    info: Sys.Info; err: INT; names: [16][]U8; path: Buf.Buf;
        +begin
        +    _ := Sys.makeDir("proj");
        +    _ := Sys.makeDir("proj/src");
        +    put("proj/b.txt", "bb");
        +    put("proj/a.txt", "a");
        +    if Sys.openDir(ADR(d), "proj") < 0 then return; end;
        +    n := 0;
        +    name, more := Sys.nextEntry(ADR(d));
        +    while more do
        +        copy, ok := Str.copy(Heap.heap, name);
        +        if ok and (n < 16) then names[n] := copy; INC(n); end;
        +        name, more := Sys.nextEntry(ADR(d));
        +    end;
        +    Sys.closeDir(ADR(d));
        +    Order.sort(names[0..n]);
        +    Buf.init(ADR(path), Heap.heap);
        +    for i := 0 to n - 1 do
        +        Buf.reset(ADR(path));
        +        Buf.str(ADR(path), "proj/");
        +        Buf.str(ADR(path), names[i]);
        +        info, err := Sys.info(Buf.bytes(ADR(path)));
        +        Out.str(names[i]);
        +        if err < 0 then Out.str(" ?");
        +        elsif info.dir then Out.str("/");
        +        else Out.str(", "); Out.int(info.size); Out.str(" bytes");
        +        end;
        +        Out.ln;
        +        Mem.free(Heap.heap, ^U8(ADR(names[i][0])));
        +    end;
        +    Buf.done(ADR(path));
        +end;
        +
        +end Tree.
        +
        a.txt, 1 bytes
        +b.txt, 2 bytes
        +src/
        +
        +

        A command line, from a table

        +

        A program describes its options once, in a table of Opt.Rows: its synopsis lines, its subcommands and its options. The help and the error messages are made from the table. The parser reads by the rules of the C library's getopt with GNU's long options, so -vn3, -n 3, --count=3 and --count 3 all work, and -- ends the options.

        +
        Tool.raz
        module Tool;
        +import Out, Fmt, Opt;
        +
        +const count = 1;                   (* the key of --count, which has no letter *)
        +
        +proc main*;
        +var p: Opt.Parser; verbose: BOOL; n, i: INT; w: []U8; ok: BOOL;
        +begin
        +    n := 1;
        +    Opt.init(ADR(p), "tool", [
        +        Opt.usage("", "tool [-v] [--count n] word ..."),
        +        Opt.option("", 'v', "verbose", "", "say more"),
        +        Opt.option("", count, "count", "n", "repeat each word n times")]);
        +    while Opt.next(ADR(p)) do
        +        if p.letter = 'v' then verbose := true;
        +        elsif p.letter = count then n := INT(Opt.number(ADR(p), 1, 5));
        +        end;
        +    end;
        +    w, ok := Opt.operand(ADR(p));
        +    if not ok then Opt.fail(ADR(p), "no words; see tool -h"); end;
        +    while ok do
        +        for i := 1 to n do
        +            if verbose then Out.str("word: "); end;
        +            Fmt.print("{}\n", [Fmt.str(w)]);
        +        end;
        +        w, ok := Opt.operand(ADR(p));
        +    end;
        +end;
        +
        +end Tool.
        +
        $ raz Tool.raz
        +$ ./Tool -h
        +usage: tool [-v] [--count n] word ...
        +
        +  -v, --verbose   say more
        +      --count n   repeat each word n times
        +  -h, --help      print this and exit
        +$ ./Tool -v hello world
        +word: hello
        +word: world
        +$ ./Tool --count 9 hello; echo "status $?"
        +tool: --count wants a number from 1 to 5, not '9'
        +usage: tool [-v] [--count n] word ...
        +status 2
        +$ ./Tool -x; echo "status $?"
        +tool: unknown option -x
        +usage: tool [-v] [--count n] word ...
        +status 2
        +$ ./Tool; echo "status $?"
        +tool: no words; see tool -h
        +status 2
        +

        -h and --help are Opt's: the program never sees them. A mistake on the command line is a sentence on standard error with the program's name first, then the synopsis, and status 2. Nothing in Tool wrote any of that.

        +

        A mistake in the table itself, such as an option given twice, is the program's, and init says so and ends with status 1 before it reads a word.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/fmt.html b/site/public/advanced/fmt.html new file mode 100644 index 0000000..879d5aa --- /dev/null +++ b/site/public/advanced/fmt.html @@ -0,0 +1,189 @@ + + + + + +Output and formatting - Beyond Go + + + +
        +
        +

        The library · lesson 1 of 18

        Output and formatting

        +

        The first tour used Out for everything it printed. Two modules do the work: Out, which owns standard output and its buffer, and Fmt, which turns values into text.

        +

        What Out does with its buffer

        +

        Out keeps a buffer of 4 KB. It writes it out when it is full, at each line feed when standard output is a terminal, at Out.flush, and when the program ends by Rt.exit (which a normal end and a failed check both are). A lock keeps what each call writes together when threads write at once.

        +

        You can see the effect with strace, which lists the system calls a program makes. A program that prints three lines to a file makes one write:

        +
        Three.raz
        module Three;
        +import Out;
        +
        +proc main*;
        +begin
        +    Out.str("one\n");
        +    Out.str("two\n");
        +    Out.str("three\n");
        +end;
        +
        +end Three.
        +
        $ raz Three.raz
        +$ strace -e trace=write ./Three > /dev/null
        +write(1, "one\ntwo\nthree\n", 14)       = 14
        ++++ exited with 0 +++
        +

        Three lines, one system call. That is why Out is cheap, and why a program that mixes it with C's printf, which keeps a buffer of its own, must flush one before the other.

        +

        Fmt.print

        +

        Fmt.print(format, args) writes to standard output. Each {} in the format takes the next argument, and {{ and }} stand for the braces. The arguments are a slice of Fmt.Arg, a variant, so each is built with the constructor for its kind: int, uint, hex, str, char, bool and real, which takes the number of digits after the point.

        +
        Kinds.raz
        module Kinds;
        +import Fmt;
        +
        +proc main*;
        +var big: U64; small: I8;
        +begin
        +    big := 0FFFFFFFFFFFFFFFFH;
        +    small := -5;
        +    Fmt.print("int {}, uint {}, hex {}\n",
        +        [Fmt.int(-42), Fmt.uint(big), Fmt.hex(255)]);
        +    Fmt.print("str {}, char {}, bool {}\n",
        +        [Fmt.str("hi"), Fmt.char('x'), Fmt.bool(1 < 2)]);
        +    Fmt.print("real {} and {} and {}\n",
        +        [Fmt.real(3.14159, 2), Fmt.real(2.5, 0), Fmt.real(1.0 / 3.0, 9)]);
        +    Fmt.print("an I8: {}; braces: {{ and }}\n", [Fmt.int(I64(small))]);
        +end;
        +
        +end Kinds.
        +
        int -42, uint 18446744073709551615, hex FF
        +str hi, char x, bool true
        +real 3.14 and 3 and 0.333333333
        +an I8: -5; braces: { and }
        +
        +

        An argument whose type is wrong doesn't compile: there is no %d that disagrees with its argument. A {} with no argument left prints nothing, and arguments left over are not printed, so a mismatch shows up as missing text, never as a crash or as memory read by mistake.

        +

        Into a buffer

        +

        Fmt.write(b, format, args) does the same into a Buf instead of standard output. That is how a message is built to send somewhere else: a file, a socket, a window, a string kept for later.

        +
        Message.raz
        module Message;
        +import Out, Buf, Fmt, Heap;
        +
        +(* "name (age n)", built in a Buf the caller owns *)
        +proc describe(b: ^Buf.Buf; name: []U8; age: INT);
        +begin
        +    Fmt.write(b, "{} (age {})", [Fmt.str(name), Fmt.int(age)]);
        +end;
        +
        +proc main*;
        +var b: Buf.Buf;
        +begin
        +    Buf.init(ADR(b), Heap.heap);
        +    defer Buf.done(ADR(b));
        +    describe(ADR(b), "Ada", 36);
        +    Buf.str(ADR(b), "; ");
        +    describe(ADR(b), "Grace", 45);
        +    Out.str(Buf.bytes(ADR(b))); Out.ln;
        +    Out.int(b.len); Out.str(" bytes\n");
        +end;
        +
        +end Message.
        +
        Ada (age 36); Grace (age 45)
        +28 bytes
        +
        +

        Columns

        +

        Fmt writes values as they are, with no widths. A program that wants columns pads in one small procedure and uses it everywhere, which is easier to read than a format language.

        +
        Table.raz
        module Table;
        +import Out;
        +
        +(* s, then spaces up to width *)
        +proc left(s: []U8; width: INT);
        +var i: INT;
        +begin
        +    Out.str(s);
        +    for i := LEN(s) to width - 1 do Out.char(' '); end;
        +end;
        +
        +(* n, right aligned in width *)
        +proc right(n: INT; width: INT);
        +var digits: INT; v: INT; i: INT;
        +begin
        +    digits := 1;
        +    v := n;
        +    if v < 0 then INC(digits); v := -v; end;
        +    while v >= 10 do INC(digits); v := v div 10; end;
        +    for i := digits to width - 1 do Out.char(' '); end;
        +    Out.int(n);
        +end;
        +
        +proc row(name: []U8; qty, price: INT);
        +begin
        +    left(name, 10);
        +    right(qty, 5);
        +    right(price, 8);
        +    right(qty * price, 9);
        +    Out.ln;
        +end;
        +
        +proc main*;
        +begin
        +    Out.str("item        qty   price    total\n");
        +    row("bolts", 120, 3);
        +    row("washers", 1000, 1);
        +    row("gears", 8, 250);
        +    row("shims", 12, -4);
        +end;
        +
        +end Table.
        +
        item        qty   price    total
        +bolts       120       3      360
        +washers    1000       1     1000
        +gears         8     250     2000
        +shims        12      -4      -48
        +
        +

        Writing numbers in other bases

        +

        Out.hex(n, digits) writes n in hexadecimal, padded with zeros to digits. A binary dump is a for loop over a slice, one Out.hex(U64(b), 2) to a byte.

        +
        Dump.raz
        module Dump;
        +import Out;
        +
        +proc dump(data: []U8);
        +var i: INT;
        +begin
        +    for i := 0 to LEN(data) - 1 do
        +        if i > 0 then Out.char(' '); end;
        +        Out.hex(U64(data[i]), 2);
        +    end;
        +    Out.ln;
        +end;
        +
        +proc main*;
        +begin
        +    dump("raz\n");
        +    dump("\u{3BB}");
        +end;
        +
        +end Dump.
        +
        72 61 7A 0A
        +CE BB
        +

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/index.html b/site/public/advanced/index.html new file mode 100644 index 0000000..5b1adbb --- /dev/null +++ b/site/public/advanced/index.html @@ -0,0 +1,51 @@ + + + + + +Beyond Go + + + +
        +
        +

        Beyond Go

        +

        The second tour, for the part of raz that sits close to the machine. It +assumes you have taken Raz, Set, Go or know +Pascal or C well enough not to need it.

        +

        It has four parts: The library, the modules every program +reaches for; Standing alone, programs that need no C and no +run time; The machine, procedures written in assembly and +direct system calls; and Shared memory, volatile accesses, +atomics and threads. Every program is compiled and run when this page is +made, as before.

        +

        The library

          +
        1. Output and formatting Out's buffer, Fmt's arguments, formatting into a Buf, and laying out columns.
        2. +
        3. Strings and bytes Copying, hashing and ordering strings, and reading and writing binary formats.
        4. +
        5. Lists, maps and sorting List(T), Map(K, V) and Sort(T), put together in a word-frequency program.
        6. +
        7. Files and the command line Whole files with Files, descriptors and directories with Sys, and options with Opt.
        8. +
        9. Time, randomness and other programs Clocks, sleeping, random bytes, and running a program with its output piped back.
        10. +
        11. Writing an allocator Mem.Allocator is two procedures; make one over a fixed array, and one that counts.
        12. +
        +

        Standing alone

          +
        1. A program with no run time What is in an executable, what isn't, and how to see it.
        2. +
        3. Threads without C, and keeping the two apart link static, what a module that makes its own system calls promises, and the error when it breaks.
        4. +
        5. Starting, ending, and signals What runs before main, what runs after, and how to wait for a signal.
        6. +
        7. One module, one file per target Portable programs, the code that isn't, and how the compiler keeps them in step.
        8. +
        +

        The machine

          +
        1. Procedures in assembly code procedures: the convention, registers, labels, db for what the assembler doesn't know.
        2. +
        3. System calls SYSCALL directly: the numbers, the arguments, negative errno, and a cat without a library.
        4. +
        5. What the compiler makes raz -S, reading a listing, what a check costs and what check off removes.
        6. +
        +

        Shared memory

          +
        1. Volatile ^VOLATILE T: memory that something else may change, laid over with a record.
        2. +
        3. Atomics XADD, XCHG and CAS; a compare-and-swap loop; a lock built from them.
        4. +
        5. Ordering and publication Why a flag isn't enough, what FENCE and the atomics order, and the pattern that works.
        6. +
        7. A lock-free stack CAS on pointers, a push loop that never blocks, and the ABA problem that makes pop harder.
        8. +
        9. A ring buffer between threads A single-producer, single-consumer queue, put together from what the tour has covered.
        10. +
        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/lifecycle.html b/site/public/advanced/lifecycle.html new file mode 100644 index 0000000..f4b0ae9 --- /dev/null +++ b/site/public/advanced/lifecycle.html @@ -0,0 +1,155 @@ + + + + + +Starting, ending, and signals - Beyond Go + + + +
        +
        +

        Standing alone · lesson 9 of 18

        Starting, ending, and signals

        +

        With no run time, the life of a program is short enough to say in a few lines. What happens, in order:

        +

        1. The entry code sets up a stack for signal handlers and installs the handlers for SIGSEGV and SIGFPE. A program that uses C starts through C instead, so that C's own set-up runs. 2. The bodies of the modules run, each once, imported modules first. 3. The main module's main runs. 4. Rt.exit runs the procedures registered with Rt.atExit, the last registered first, and ends the program with main's status.

        +

        Bodies, then main

        +

        The first tour showed bodies running before main. They are the place to set a module up, and they can end early with return;.

        +
        Order.raz
        module Order;
        +import Out;
        +
        +var steps*: INT;
        +
        +proc note(what: []U8);
        +begin
        +    INC(steps);
        +    Out.int(steps); Out.str(". "); Out.str(what); Out.ln;
        +end;
        +
        +begin
        +    note("the body runs before main");
        +    if steps > 5 then return; end;
        +    note("and carries on if it isn't ended early");
        +end Order.
        +
        1. the body runs before main
        +2. and carries on if it isn't ended early
        +
        +

        That file is a module with a body and no main: it can be imported, or its body run as a program. Add the main and see both:

        +
        Both.raz
        module Both;
        +import Out, Order;
        +
        +proc main*;
        +begin
        +    Out.str("main: "); Out.int(Order.steps); Out.str(" steps happened first\n");
        +end;
        +
        +end Both.
        +
        1. the body runs before main
        +2. and carries on if it isn't ended early
        +main: 2 steps happened first
        +
        +

        Things to do at the end

        +

        Rt.atExit(p) registers a procedure with no parameters to run when the program ends by Rt.exit: at the end of main, by a call to Rt.exit, or by a failed check, after its message. It is where a program restores a terminal or removes a lock file. At most 32 are registered, and each runs at most once. Out's buffer is flushed this way, which is why a program that ends in a failure still shows what it printed.

        +
        Cleanup.raz
        module Cleanup;
        +import Out, Rt;
        +
        +proc first;
        +begin
        +    Out.str("registered first, runs last\n");
        +end;
        +
        +proc second;
        +begin
        +    Out.str("registered second, runs first\n");
        +end;
        +
        +proc main*;
        +begin
        +    _ := Rt.atExit(first);
        +    _ := Rt.atExit(second);
        +    Out.str("main is done\n");
        +end;
        +
        +end Cleanup.
        +
        main is done
        +registered second, runs first
        +registered first, runs last
        +
        +

        Two ways to leave in a hurry

        +

        Rt.exit(status) ends the program after the atExit procedures. Sys.exit(status) ends it at once, without them. A failed check and Rt.exit also skip the defer statements still pending in the calls under way. Sys.exit is for a child process that must not run what it inherited, and for nothing else.

        +
        Hurry.raz
        module Hurry;
        +import Out, Rt, Sys;
        +
        +proc bye;
        +begin
        +    Out.str("atExit ran\n");
        +end;
        +
        +proc main*;
        +begin
        +    _ := Rt.atExit(bye);
        +    defer Out.str("a deferred statement ran\n");
        +    Out.str("leaving\n");
        +    Out.flush;
        +    Sys.exit(3);
        +end;
        +
        +end Hurry.
        +
        $ raz Hurry.raz
        +$ ./Hurry; echo "status $?"
        +leaving
        +status 3
        +

        Neither the deferred statement nor bye ran. That's the rule, and the reason to keep cleanup that matters (a terminal, a lock file) in atExit and use Rt.exit for ending.

        +

        Signals

        +

        A program is stopped by a signal it doesn't catch, with a message that names the place for SIGSEGV and SIGFPE, and without one for the others. A program that wants to handle one, say SIGTERM for a clean shutdown, doesn't write a handler that runs at an arbitrary moment. It asks for the signals to arrive as data: Sys.catch takes a list of signals and gives a descriptor that is ready to read when one comes, and Sys.caught says which. So the program waits for signals the way it waits for input.

        +
        Terms.raz
        module Terms;
        +import Out, Sys;
        +
        +proc main*;
        +var fd, sig: INT;
        +begin
        +    fd := Sys.catch([Sys.sigTerm, Sys.sigWinch]);
        +    Out.str("asking myself to stop\n");
        +    _ := Sys.kill(Sys.pid(), Sys.sigTerm);
        +    if Sys.ready(fd, 1000) then
        +        sig := Sys.caught(fd);
        +        if sig = Sys.sigTerm then Out.str("caught SIGTERM, stopping cleanly\n"); end;
        +    end;
        +    sig := Sys.caught(fd);
        +    Out.int(sig); Out.str(" waiting after that\n");     (* 0: none *)
        +end;
        +
        +end Terms.
        +
        asking myself to stop
        +caught SIGTERM, stopping cleanly
        +0 waiting after that
        +
        +

        Sys.ready(fd, ms) waits up to ms milliseconds for something to read; with Sys.readyOf it waits on several descriptors, so one loop serves a socket, a terminal and a stop signal together. Sys.ignore(sig, true) makes a signal do nothing, as a shell ignores SIGTTOU.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/linkstatic.html b/site/public/advanced/linkstatic.html new file mode 100644 index 0000000..ad11f40 --- /dev/null +++ b/site/public/advanced/linkstatic.html @@ -0,0 +1,114 @@ + + + + + +Threads without C, and keeping the two apart - Beyond Go + + + +
        +
        +

        Standing alone · lesson 8 of 18

        Threads without C, and keeping the two apart

        +

        A program without C can do things a program with C can't. The most useful is to make threads of its own: C's thread functions rely on C's own set-up, which a program that never started C has not done. Thread creates threads directly with the clone system call and gives each a stack of its own.

        +

        A module like that says so, with link static; after its imports. It means: "I make my own system calls or my own threads, which the C library wouldn't know about; a program that includes me must not use C." static isn't a reserved word; it is only meaningful after link.

        +

        What Thread does

        +

        Thread is a module of raz, in the library, that says link static; and makes the clone, mmap and futex system calls itself. Here is its beginning, printed from the library:

        +
        $ sed -n '1,22p' $RAZLIB/Thread.linux-x86_64.raz
        +(* Threads for programs without C, made with the clone system call.
        +   Each runs on a stack of its own, mmaped, with a page below it that
        +   can't be touched, so that running off the stack stops the program
        +   rather than spoiling what lies below; above it, a little stack for
        +   Rt's signal handlers, so that they can say so. join waits on the
        +   thread's id, which the kernel clears, and wakes it for, when the
        +   thread ends; a Mutex sleeps on a futex. A program with C threads
        +   uses C's, through pthread_create, and so can't use these. *)
        +module Thread;
        +import Sys, Rt;
        +link static;
        +
        +const
        +    Failed*: ERROR = "can't start a thread";
        +    Stack = 1 shl 20;
        +    Alt = 16384;     (* the signal handlers' stack *)
        +    Page = 4096;
        +    (* clone: share memory, files, signal handlers, the thread group;
        +       write the id to tid, and clear it at the end *)
        +    Flags = 350F00H;
        +    FutexWait = 0;
        +    FutexWake = 1;
        +

        A program that imports it is therefore a static executable, and every thread it spawns is a Linux thread with a stack of its own, mapped with a page below it that can't be touched, so that running off the stack ends the program with a message and not with corruption.

        +
        Hello.raz
        module Hello;
        +import Out, Thread;
        +
        +var done: INT;
        +
        +proc greet(arg: ^U8);
        +begin
        +    Out.str("hello from thread "); Out.int(INT(arg)); Out.ln;
        +    _ := XADD(ADR(done), 1);
        +end;
        +
        +proc main*;
        +var t: ^Thread.Thread; err: ERROR;
        +begin
        +    t, err := Thread.spawn(greet, ^U8(7));
        +    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    Thread.join(t);
        +    Out.str("joined; done = "); Out.int(done); Out.ln;
        +end;
        +
        +end Hello.
        +
        $ raz Hello.raz
        +$ ./Hello
        +hello from thread 7
        +joined; done = 1
        +$ file Hello | sed 's/,.*statically/, statically/'
        +Hello: ELF 64-bit LSB executable, statically linked, with debug_info, not stripped
        +

        When you mix them

        +

        C's pthread_create and Thread can't share a process, and the compiler won't let you try. A program that imports a module that says link static; and another that uses C is an error, and the error names both:

        +
        Mixed.raz
        module Mixed;
        +import Out, Thread, C;
        +
        +proc main*;
        +begin
        +    Out.str(MSG(Thread.Failed)); Out.ln;
        +    _ := C.printf("%d\n", I32(1));
        +    Out.str("and Out\n");
        +end;
        +
        +end Mixed.
        +
        $ raz Mixed.raz
        +raz: Thread says link static, but C uses C
        +

        Which one you want depends on what the program is for. A program that calls a C library (a window system, a database client) uses C's threads, C.pthread_create, because the library may assume them. A program that talks only to the kernel uses Thread, and is a static executable.

        +

        The same promise for your own modules

        +

        The rule isn't special to Thread. A module of yours that makes SYSCALLs directly, or relies on being the only owner of signal handlers, or sets up its own stacks, says link static; too, and then the compiler keeps C away from it for you. The module is documenting a fact about itself, and the compiler checks it where the program is assembled.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/listing.html b/site/public/advanced/listing.html new file mode 100644 index 0000000..3026018 --- /dev/null +++ b/site/public/advanced/listing.html @@ -0,0 +1,256 @@ + + + + + +What the compiler makes - Beyond Go + + + +
        +
        +

        The machine · lesson 13 of 18

        What the compiler makes

        +

        The compiler has no optimizer and no intermediate form. It reads the source once and writes x86-64 machine code as it goes, so the code is what the source says, in the order it says it. That makes the output readable, and there is a switch for reading it: raz -S Main.raz prints the main module's code instead of writing it, each line of source and under it the instructions made for it, at their offsets in the procedure.

        +

        A small procedure

        +
        Add.raz
        module Add;
        +
        +proc add*(a, b: INT): INT;
        +begin
        +    return a + b;
        +end;
        +
        +proc main*;
        +begin
        +    _ := add(1, 2);
        +end;
        +
        +end Add.
        +
        $ raz -S Add.raz
        +
        +Add.add:
        +     3  proc add*(a, b: INT): INT;
        +             0  push rbp
        +             1  mov rbp, rsp
        +             4  sub rsp, 16
        +     5      return a + b;
        +            11  mov r8, rdi
        +            14  add r8, rsi
        +            17  mov rax, r8
        +     6  end;
        +            20  leave
        +            21  ret
        +
        +Add.main:
        +     8  proc main*;
        +             0  push rbp
        +             1  mov rbp, rsp
        +             4  sub rsp, 16
        +    10      _ := add(1, 2);
        +            11  mov rdi, 1
        +            16  mov rsi, 2
        +            21  call Add.add
        +            26  mov r8, rax
        +    11  end;
        +            29  leave
        +            30  ret
        +

        Every procedure starts by saving the caller's frame pointer and making its own (push rbp; mov rbp, rsp) and reserves room for what it needs. The arguments arrive in rdi and rsi, as the convention says, and the result leaves in rax. A call is mov rdi, 1; mov rsi, 2; call Add.add. Nothing is hidden: the frame pointer chain is what lets a failure show the calls under way with their variables.

        +

        A loop with its checks

        +

        This is the dot product of two slices. A slice is a pointer and a length, and it travels in two registers:

        +
        Dot.raz
        module Dot;
        +
        +(* the dot product of two slices of equal length *)
        +proc dot*(a, b: []INT): INT;
        +var i, sum: INT;
        +begin
        +    for i := 0 to LEN(a) - 1 do
        +        sum := sum + a[i] * b[i];
        +    end;
        +    return sum;
        +end;
        +
        +proc main*;
        +var x, y: [3]INT;
        +begin
        +    x := [1, 2, 3];
        +    y := [4, 5, 6];
        +    _ := dot(x, y);
        +end;
        +
        +end Dot.
        +
        $ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p'
        +Dot.dot:
        +     4  proc dot*(a, b: []INT): INT;
        +             0  push rbp
        +             1  mov rbp, rsp
        +             4  sub rsp, 64
        +            11  mov [rbp - 48], rbx
        +            15  xor ebx, ebx
        +            17  mov [rbp - 40], r12
        +            21  xor r12d, r12d
        +            24  mov [rbp - 32], rdx
        +            28  mov [rbp - 24], rcx
        +     7      for i := 0 to LEN(a) - 1 do
        +            32  xor ebx, ebx
        +            34  mov r8, rsi
        +            37  sub r8, 1
        +            41  mov [rbp - 56], r8
        +            45  cmp rbx, [rbp - 56]
        +            49  jg 146
        +            55  jmp 68
        +            60  nop
        +            64  add rbx, 1
        +     8          sum := sum + a[i] * b[i];
        +            68  cmp rbx, rsi
        +            71  jae 159
        +            77  mov r10, rbx
        +            80  cmp r10, [rbp - 24]
        +            84  jae 170
        +            90  shl r10, 3
        +            94  add r10, [rbp - 32]
        +            98  mov r10, [r10]
        +           101  mov r9, [rdi + rbx * 8]
        +           105  imul r9, r10
        +           109  add r12, r9
        +           112  cmp rbx, [rbp - 56]
        +           116  jl 64
        +           122  cmp rbx, [rbp - 56]
        +           126  je 146
        +           132  add rbx, 1
        +           136  cmp rbx, [rbp - 56]
        +           140  jle 68
        +    10      return sum;
        +           146  mov rax, r12
        +    11  end;
        +           149  mov rbx, [rbp - 48]
        +           153  mov r12, [rbp - 40]
        +           157  leave
        +           158  ret
        +     8          sum := sum + a[i] * b[i];
        +           159  mov rax, rbx
        +           162  mov rcx, rsi
        +           165  call Rt.check0
        +           170  mov rax, r10
        +           173  mov rcx, [rbp - 24]
        +           177  call Rt.check0
        +

        Read it from the top. a arrives in rdi and rsi, pointer and length; b in rdx and rcx, which the procedure saves in its frame. i and sum live in rbx and r12, which the procedure saves and restores because the convention says they belong to the caller. The loop's test is at the bottom, and its limit, LEN(a) - 1, is taken once.

        +

        In the body, each index has a check: cmp rbx, rsi; jae compares i with a's length in a single instruction and jumps to a stub at the end of the procedure, which calls Rt.check0 with the values it needs to say what failed. When the index is in range, which is nearly always, the cost is one compare and a branch that isn't taken.

        +

        Taking the checks out

        +

        check off; after the imports leaves out the module's own checks of indexes and slice bounds. Here is the same procedure with it:

        +
        Dot2.raz
        module Dot2;
        +check off;
        +
        +proc dot*(a, b: []INT): INT;
        +var i, sum: INT;
        +begin
        +    for i := 0 to LEN(a) - 1 do
        +        sum := sum + a[i] * b[i];
        +    end;
        +    return sum;
        +end;
        +
        +proc main*;
        +var x, y: [3]INT;
        +begin
        +    x := [1, 2, 3];
        +    y := [4, 5, 6];
        +    _ := dot(x, y);
        +end;
        +
        +end Dot2.
        +
        $ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p'
        +Dot2.dot:
        +     4  proc dot*(a, b: []INT): INT;
        +             0  push rbp
        +             1  mov rbp, rsp
        +             4  sub rsp, 64
        +            11  mov [rbp - 48], rbx
        +            15  xor ebx, ebx
        +            17  mov [rbp - 40], r12
        +            21  xor r12d, r12d
        +            24  mov [rbp - 32], rdx
        +            28  mov [rbp - 24], rcx
        +     7      for i := 0 to LEN(a) - 1 do
        +            32  xor ebx, ebx
        +            34  mov r8, rsi
        +            37  sub r8, 1
        +            41  mov [rbp - 56], r8
        +            45  cmp rbx, [rbp - 56]
        +            49  jg 127
        +            55  jmp 68
        +            60  nop
        +            64  add rbx, 1
        +     8          sum := sum + a[i] * b[i];
        +            68  mov r10, rbx
        +            71  shl r10, 3
        +            75  add r10, [rbp - 32]
        +            79  mov r10, [r10]
        +            82  mov r9, [rdi + rbx * 8]
        +            86  imul r9, r10
        +            90  add r12, r9
        +            93  cmp rbx, [rbp - 56]
        +            97  jl 64
        +           103  cmp rbx, [rbp - 56]
        +           107  je 127
        +           113  add rbx, 1
        +           117  cmp rbx, [rbp - 56]
        +           121  jle 68
        +    10      return sum;
        +           127  mov rax, r12
        +    11  end;
        +           130  mov rbx, [rbp - 48]
        +           134  mov r12, [rbp - 40]
        +           138  leave
        +           139  ret
        +$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p' | wc -l
        +55
        +$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p' | wc -l
        +44
        +

        The compares, the branches and the stubs are gone. It is faster, and it is no longer safe: an index out of range reads or writes whatever memory it reaches, and what follows isn't defined. A program turns checks off where it has measured and is sure, and says so at the top of the module, where a reader can see it.

        +

        Comparing with C

        +

        make kernels in the compiler's sources measures test/bench's kernels against the same kernels written in Pascal and compiled by Free Pascal at -O2. The compiler's own guide, doc/compiler.md, gives the numbers and says what the compiler does and doesn't do. It is not the fastest code: it is code whose every instruction you can account for.

        +

        Tools that read what it made

        +
        • gdb finds procedures by name and lines by number, since the executable carries them: break Dot.dot and list work, and so does stepping a line at a time.
        • RAZ_PROFILE=1 samples the program every millisecond and says which procedures and lines took the time.
        • objdump -d disassembles what is really in the file, if you want to see the bytes behind a listing.
        +
        $ raz -o Dot Dot.raz
        +$ objdump -d -M intel --no-show-raw-insn Dot | sed -n '/<Dot.dot>:/,/ret/p' | head -12
        +0000000000403b80 <Dot.dot>:
        +  403b80:	push   rbp
        +  403b81:	mov    rbp,rsp
        +  403b84:	sub    rsp,0x40
        +  403b8b:	mov    QWORD PTR [rbp-0x30],rbx
        +  403b8f:	xor    ebx,ebx
        +  403b91:	mov    QWORD PTR [rbp-0x28],r12
        +  403b95:	xor    r12d,r12d
        +  403b98:	mov    QWORD PTR [rbp-0x20],rdx
        +  403b9c:	mov    QWORD PTR [rbp-0x18],rcx
        +  403ba0:	xor    ebx,ebx
        +  403ba2:	mov    r8,rsi
        +

        The listing is what the encoder meant; objdump is what the processor will read. They tell the same story.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/lockfree.html b/site/public/advanced/lockfree.html new file mode 100644 index 0000000..fc042a8 --- /dev/null +++ b/site/public/advanced/lockfree.html @@ -0,0 +1,158 @@ + + + + + +A lock-free stack - Beyond Go + + + +
        +
        +

        Shared memory · lesson 17 of 18

        A lock-free stack

        +

        CAS works on pointers as well as integers, and a pointer is how a bigger thing is swapped in atomically: build the new structure privately, then make it visible by changing one word. The classic example is a stack as a linked list whose head is that word.

        +

        Push

        +

        To push a node: point its next at the current head, then CAS the head from what you saw to the new node. If another thread pushed first, the CAS fails, because the head is no longer what you saw, so look again and retry. No thread ever waits for another, and none can stop the others by being slow.

        +
        Treiber.raz
        module Treiber;
        +import Out, Thread;
        +
        +type Node = record next: ^Node; val: INT; end;
        +
        +const Threads = 4; Each = 5000;
        +
        +var
        +    top: ^Node;                          (* the head, changed only by CAS *)
        +    nodes: [Threads * Each]Node;         (* every node a thread will push *)
        +
        +(* n onto the stack, without a lock *)
        +proc push(n: ^Node);
        +var old: ^Node;
        +begin
        +    old := top;
        +    n^.next := old;
        +    while not CAS(ADR(top), old, n) do
        +        old := top;                      (* lost the race: look again *)
        +        n^.next := old;
        +    end;
        +end;
        +
        +proc work(arg: ^U8);
        +var first, i: INT;
        +begin
        +    first := INT(arg) * Each;
        +    for i := 0 to Each - 1 do
        +        nodes[first + i].val := first + i;
        +        push(ADR(nodes[first + i]));
        +    end;
        +end;
        +
        +proc main*;
        +var th: [Threads]^Thread.Thread; i, count, sum: INT; err: ERROR; n: ^Node;
        +begin
        +    for i := 0 to Threads - 1 do
        +        th[i], err := Thread.spawn(work, ^U8(i));
        +        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    end;
        +    for i := 0 to Threads - 1 do Thread.join(th[i]); end;
        +    n := top;
        +    while n # nil do
        +        INC(count);
        +        sum := sum + n^.val;
        +        n := n^.next;
        +    end;
        +    Out.int(count); Out.char(' '); Out.int(sum); Out.ln;
        +    Out.int(Threads * Each * (Threads * Each - 1) div 2); Out.ln;
        +end;
        +
        +end Treiber.
        +
        20000 199990000
        +199990000
        +
        +

        Twenty thousand nodes pushed by four threads at once; every one is on the stack exactly once, and the sum of their values is the sum of 0 to 19999. Nothing was lost, and there is no lock anywhere in the program.

        +

        The loop in push is the shape of every lock-free algorithm: read, compute, CAS, and read again on failure. The CAS is sequentially consistent, so the node's val and next, written before it with ordinary stores, are visible to a thread that finds the node through top.

        +

        Pop, and the ABA problem

        +

        Pop takes the head off: read top, read its next, CAS the head from top to next. It looks as easy as push, and it isn't. Between the two reads and the CAS, other threads may pop that node, pop others, and push the same node back, now with a different next. The head is the same pointer again, so the CAS succeeds, and installs a next that is stale: nodes disappear, or the stack points into freed memory. This is the ABA problem: the word changed from A to B and back to A, and the CAS can't tell.

        +

        There are three common ways out, and each has a cost:

        +
        • Never reuse a node while anyone might hold it. Nodes from an arena that is reset only when all threads are done, as the nodes above come from a fixed array, can't come back as a different node.
        • Add a counter to the head, so that A-B-A is A1-B2-A3. That is a word and a counter swapped together, and raz's CAS is for one word, so a program packs a small index and a counter into one UINT.
        • Don't pop concurrently. Many threads push and one thread, at the end, takes everything with a single XCHG(ADR(top), nil) and walks the list in peace. A stack used this way for work lists and logs needs no more.
        +
        Drain.raz
        module Drain;
        +import Out, Thread;
        +
        +type Node = record next: ^Node; val: INT; end;
        +
        +const Threads = 3; Each = 1000;
        +
        +var
        +    top: ^Node;
        +    nodes: [Threads * Each]Node;
        +
        +proc push(n: ^Node);
        +var old: ^Node;
        +begin
        +    old := top;
        +    n^.next := old;
        +    while not CAS(ADR(top), old, n) do
        +        old := top;
        +        n^.next := old;
        +    end;
        +end;
        +
        +proc work(arg: ^U8);
        +var first, i: INT;
        +begin
        +    first := INT(arg) * Each;
        +    for i := 0 to Each - 1 do
        +        nodes[first + i].val := 1;
        +        push(ADR(nodes[first + i]));
        +    end;
        +end;
        +
        +proc main*;
        +var th: [Threads]^Thread.Thread; i, count: INT; err: ERROR; all, n: ^Node;
        +begin
        +    for i := 0 to Threads - 1 do
        +        th[i], err := Thread.spawn(work, ^U8(i));
        +        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    end;
        +    for i := 0 to Threads - 1 do Thread.join(th[i]); end;
        +    all := XCHG(ADR(top), nil);          (* take the whole stack, atomically *)
        +    n := all;
        +    while n # nil do INC(count); n := n^.next; end;
        +    Out.int(count); Out.str(" taken at once, "); 
        +    if top = nil then Out.str("none left\n"); end;
        +end;
        +
        +end Drain.
        +
        3000 taken at once, none left
        +
        +

        The atomic exchange takes everything pushed so far in one step, so the walk that follows races with nobody.

        +

        When to use it

        +

        A lock-free structure is worth it when a lock would be held by a thread that can be descheduled, when the critical section is a single pointer, or when a signal handler or an interrupt must share data with the code it interrupts. Everywhere else a Mutex is shorter, easier to check, and fast enough. The advantage of knowing how to write the other kind is that you understand what the lock is doing for you.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/ordering.html b/site/public/advanced/ordering.html new file mode 100644 index 0000000..84d8bd2 --- /dev/null +++ b/site/public/advanced/ordering.html @@ -0,0 +1,122 @@ + + + + + +Ordering and publication - Beyond Go + + + +
        +
        +

        Shared memory · lesson 16 of 18

        Ordering and publication

        +

        Atomics make one word safe. The harder question is about the *other* words: if one thread writes a value and then raises a flag, can another thread that sees the flag be sure it sees the value?

        +

        The report is careful. Only volatile accesses, CAS, XCHG, XADD and FENCE are exact. Any other access is ordinary: an implementation may keep a variable in a register, leave out a write that nothing reads, and change the order of ordinary accesses, as long as each thread, on its own, does what the report says. A variable that one thread writes while another reads or writes it, unless both use volatile accesses or the atomic built-ins, or a FENCE orders them, holds no particular value then: a read of it gives a value it had or was given, or a mixture of their bytes. Nothing else of the program becomes undefined by it.

        +

        In plain words: two threads that share an ordinary variable with no atomic, volatile or fence between them get no guarantee about what each sees.

        +

        The pattern that is guaranteed: publish through an atomic

        +

        The simplest correct way to hand a value to another thread: write it with ordinary stores, then store a flag with an atomic. The reader loops on the flag with an atomic read, and then reads the data. XCHG is the store; XADD(p, 0) is the load, which adds nothing and returns the value. Both are sequentially consistent, so everything written before the flag is visible after it is seen.

        +
        Publish.raz
        module Publish;
        +import Out, Sys, Thread;
        +
        +type Message = record id: INT; text: [32]U8; len: INT; end;
        +
        +var
        +    msg: Message;          (* ordinary memory, written once, then published *)
        +    ready: INT;            (* the flag: only touched by atomics *)
        +
        +proc producer(_arg: ^U8);
        +begin
        +    Sys.sleep(10);
        +    msg.id := 7;
        +    msg.text := "built before the flag";
        +    msg.len := 21;
        +    _ := XCHG(ADR(ready), 1);               (* publish *)
        +end;
        +
        +proc main*;
        +var t: ^Thread.Thread; err: ERROR;
        +begin
        +    t, err := Thread.spawn(producer, nil);
        +    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    while XADD(ADR(ready), 0) = 0 do Sys.yield; end;     (* wait for it *)
        +    Out.int(msg.id); Out.char(' '); Out.str(msg.text[0..msg.len]); Out.ln;
        +    Thread.join(t);
        +end;
        +
        +end Publish.
        +
        7 built before the flag
        +
        +

        The reader's loop makes no ordinary read of ready: it can't be kept in a register and read once, which is the danger of while ready = 0 do end. And the write of msg can't be delayed past the XCHG.

        +

        The same with a fence

        +

        FENCE is a full memory barrier: it orders the program's ordinary accesses against those of other processors and devices. With volatile accesses for the flag and a fence between the data and the flag, the same handoff works. This is the form device code takes, as in the last lesson.

        +
        Fenced.raz
        module Fenced;
        +import Out, Sys, Thread;
        +
        +var
        +    data: INT;                   (* ordinary *)
        +    flag: INT;                   (* only reached through a volatile pointer *)
        +
        +proc producer(_arg: ^U8);
        +var f: ^VOLATILE INT;
        +begin
        +    f := ^VOLATILE INT(ADR(flag));
        +    Sys.sleep(10);
        +    data := 1234;
        +    FENCE;                       (* data is written before the flag is *)
        +    f^ := 1;
        +end;
        +
        +proc main*;
        +var t: ^Thread.Thread; err: ERROR; f: ^VOLATILE INT;
        +begin
        +    f := ^VOLATILE INT(ADR(flag));
        +    t, err := Thread.spawn(producer, nil);
        +    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    while f^ = 0 do Sys.yield; end;
        +    FENCE;                       (* and read after the flag is seen *)
        +    Out.int(data); Out.ln;
        +    Thread.join(t);
        +end;
        +
        +end Fenced.
        +
        1234
        +
        +

        Both sides need a fence. A fence on the writer only says the data is written first; the reader must not read data before it has seen the flag.

        +

        The version that is not guaranteed

        +

        This is what *not* to write, and it is the most common bug in this area:

        +
        var data, ready: INT;
        +
        +(* thread A *)  data := 42;  ready := 1;
        +(* thread B *)  while ready = 0 do end;  use(data);
        +

        Both threads use ordinary accesses to shared variables. B's loop may read ready once into a register and spin forever; A's two writes may reach memory in either order; B may read data before the flag, or an old copy. On a particular machine with a particular compiler it may well work, until it is changed. The language says it holds no particular value, and it means it.

        +

        The lesson of the three versions

        +
        • Shared and written by someone: reach it through an atomic, a volatile pointer or a fence, every time, on both sides.
        • To hand over a bundle, publish a single atomic word *after* writing the bundle, and read the bundle only *after* seeing the word.
        • Everything under a Lock or a Mutex is ordered by the lock itself, so the data it guards can be ordinary variables. That is the simplest discipline, and the one to prefer until it is measured to be too slow.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/processes.html b/site/public/advanced/processes.html new file mode 100644 index 0000000..ab30ebb --- /dev/null +++ b/site/public/advanced/processes.html @@ -0,0 +1,182 @@ + + + + + +Time, randomness and other programs - Beyond Go + + + +
        +
        +

        The library · lesson 5 of 18

        Time, randomness and other programs

        +

        Everything here is in Sys, and is the same procedures on every target raz supports: through system calls on Linux, through the C library elsewhere.

        +

        Clocks and sleeping

        +

        Sys.clock is a clock that only goes forward, in nanoseconds: the one to measure a duration with. Sys.now is the wall clock, in nanoseconds since 1970 UTC, which can be set backwards, so it is for dates, not durations. Sys.sleep waits some milliseconds.

        +
        Timing.raz
        module Timing;
        +import Out, Sys;
        +
        +proc main*;
        +var t0, t1, elapsed: I64; wall: I64;
        +begin
        +    t0 := Sys.clock();
        +    Sys.sleep(25);
        +    t1 := Sys.clock();
        +    elapsed := (t1 - t0) div 1000000;        (* milliseconds *)
        +    if (elapsed >= 25) and (elapsed < 1000) then
        +        Out.str("slept about 25 ms\n");
        +    end;
        +    wall := Sys.now();
        +    if wall > 1700000000000000000 then Out.str("after 2023\n"); end;
        +end;
        +
        +end Timing.
        +
        slept about 25 ms
        +after 2023
        +
        +

        Every duration is an I64 of nanoseconds, because a 32-bit INT would hold only a couple of seconds of them. The library's rule is that what may overflow a small target's INT is an I64.

        +

        Random bytes

        +

        Sys.random fills a slice with random bytes from the system. Anything else is made from that: a number in a range, a shuffle.

        +
        Dice.raz
        module Dice;
        +import Out, Sys, Str;
        +
        +(* a number from 0 up to n, without bias *)
        +proc below(n: INT): INT;
        +var b: [8]U8; x, limit: U64;
        +begin
        +    limit := 0FFFFFFFFFFFFFFFFH - (0FFFFFFFFFFFFFFFFH mod U64(n)) - 1;
        +    Sys.random(b);
        +    x := Str.le(b);
        +    while x > limit do
        +        Sys.random(b);
        +        x := Str.le(b);
        +    end;
        +    return INT(x mod U64(n));
        +end;
        +
        +proc main*;
        +var counts: [6]INT; i: INT; ok: BOOL;
        +begin
        +    for i := 1 to 6000 do INC(counts[below(6)]); end;
        +    ok := true;
        +    for i := 0 to 5 do
        +        if (counts[i] < 800) or (counts[i] > 1200) then ok := false; end;
        +    end;
        +    if ok then Out.str("all six faces came up about a thousand times\n"); end;
        +end;
        +
        +end Dice.
        +
        all six faces came up about a thousand times
        +
        +

        Running a program

        +

        Sys.spawn starts the program at a path with its arguments, environment, working directory and standard streams in a Sys.Program record. A zero field means this program's own. Sys.wait waits for it to end and says how: exited with its status, killed by a signal, or stopped.

        +
        Run.raz
        module Run;
        +import Out, Sys;
        +
        +proc main*;
        +var p: Sys.Program; pid, status: INT; how: Sys.Status;
        +begin
        +    p := {path: "/bin/echo", args: ["echo", "hello from a child"]};
        +    pid := Sys.spawn(p);
        +    if pid < 0 then Out.str("can't start\n"); return; end;
        +    Out.flush;                      (* so that our text isn't behind the child's *)
        +    _, how, status := Sys.wait(pid, true);
        +    if how = Sys.exited then
        +        Out.str("it exited with "); Out.int(status); Out.ln;
        +    end;
        +end;
        +
        +end Run.
        +
        hello from a child
        +it exited with 0
        +
        +

        Capturing its output

        +

        A program's standard output can be a pipe. Sys.pipe gives the descriptor to read and the one to write; give the write end to the child as fds[1], close it here, and read until the end. This is how a program drives another: ls, a compiler, a script.

        +
        Capture.raz
        module Capture;
        +import Out, Sys, Buf, Heap;
        +
        +proc main*;
        +var
        +    p: Sys.Program; pid, rd, wr, n, status: INT; how: Sys.Status;
        +    chunk: [256]U8; b: Buf.Buf;
        +begin
        +    rd, wr := Sys.pipe();
        +    p := {path: "/bin/sh", args: ["sh", "-c", "echo one; echo two; exit 7"]};
        +    p.fds[1] := wr;
        +    pid := Sys.spawn(p);
        +    Sys.close(wr);                      (* only the child writes now *)
        +    Buf.init(ADR(b), Heap.heap);
        +    defer Buf.done(ADR(b));
        +    n := Sys.read(rd, chunk);
        +    while n > 0 do
        +        Buf.str(ADR(b), chunk[0..n]);
        +        n := Sys.read(rd, chunk);
        +    end;
        +    Sys.close(rd);
        +    _, how, status := Sys.wait(pid, true);
        +    Out.str("captured: "); Out.str(Buf.bytes(ADR(b)));
        +    Out.str("status "); Out.int(status); Out.ln;
        +    if how = Sys.exited then Out.str("(a normal exit)\n"); end;
        +end;
        +
        +end Capture.
        +
        captured: one
        +two
        +status 7
        +(a normal exit)
        +
        +

        Closing the write end in the parent matters: the read ends only when every holder of the write end has closed it.

        +

        Environment and working directory

        +

        Sys.env("HOME") is an environment variable's value, or an empty string if it is unset. Sys.workDir and Sys.setWorkDir read and change the directory. The Sys.Program record's env, onlyEnv and dir give a child its own.

        +
        Where.raz
        module Where;
        +import Out, Sys;
        +
        +proc main*;
        +var p: Sys.Program; pid, rd, wr, n: INT; chunk: [64]U8;
        +begin
        +    if Sys.env("RAZ_SURELY_UNSET") = "" then Out.str("unset reads as empty\n"); end;
        +    rd, wr := Sys.pipe();
        +    p := {path: "/bin/sh", args: ["sh", "-c", "echo $GREETING from $(pwd)"],
        +          env: ["GREETING=hello"], dir: "/tmp"};
        +    p.fds[1] := wr;
        +    pid := Sys.spawn(p);
        +    Sys.close(wr);
        +    n := Sys.read(rd, chunk);
        +    Out.str(chunk[0..n]);
        +    Sys.close(rd);
        +    _, _, _ := Sys.wait(pid, true);
        +end;
        +
        +end Where.
        +
        unset reads as empty
        +hello from /tmp
        +

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/ring.html b/site/public/advanced/ring.html new file mode 100644 index 0000000..84cb730 --- /dev/null +++ b/site/public/advanced/ring.html @@ -0,0 +1,130 @@ + + + + + +A ring buffer between threads - Beyond Go + + + +
        +
        +

        Shared memory · lesson 18 of 18

        A ring buffer between threads

        +

        To finish, here is a small piece of real concurrent code that uses nearly everything in this part of the tour: a queue through which one thread sends numbers to another, with no lock and no allocation.

        +

        The design

        +

        The queue is a fixed array of slots, used as a circle, and two counters that only ever grow: tail, the number of items the producer has put in, and head, the number the consumer has taken out. The item n lives in slot n mod Size. The queue is empty when the two are equal, and full when they differ by Size.

        +

        The design rule is that each counter has exactly one writer. Only the producer changes tail; only the consumer changes head. Each thread reads its own counter with an ordinary read, since nobody else changes it, and the other thread's with an atomic one. No CAS is needed, because there is never a race to resolve: only a handoff.

        +

        The handoff is the publish pattern of the ordering lesson. The producer writes the slot, then publishes it with an atomic store of tail; the consumer sees the new tail with an atomic load and only then reads the slot. In the other direction, the consumer frees a slot by storing head, and the producer only reuses it after loading head and seeing that.

        +

        The module

        +
        Ring.raz
        module Ring;
        +import Sys;
        +
        +const Size* = 64;
        +
        +type
        +    Ring* = record
        +        slots: [Size]INT;
        +        head, tail: INT;      (* items taken, items put; each has one writer *)
        +    end;
        +
        +(* v into the ring, waiting while it is full *)
        +proc put*(r: ^Ring; v: INT);
        +var t: INT;
        +begin
        +    t := r^.tail;                                    (* mine: an ordinary read *)
        +    while t - XADD(ADR(r^.head), 0) = Size do Sys.yield; end;   (* full *)
        +    r^.slots[t mod Size] := v;
        +    _ := XCHG(ADR(r^.tail), t + 1);                  (* publish the slot *)
        +end;
        +
        +(* the next value, waiting while the ring is empty *)
        +proc take*(r: ^Ring): INT;
        +var h, v: INT;
        +begin
        +    h := r^.head;                                    (* mine *)
        +    while XADD(ADR(r^.tail), 0) = h do Sys.yield; end;          (* empty *)
        +    v := r^.slots[h mod Size];
        +    _ := XCHG(ADR(r^.head), h + 1);                  (* give the slot back *)
        +    return v;
        +end;
        +
        +end Ring.
        +

        Using it

        +

        One thread sends the numbers 1 to 100000 through a ring of 64 slots, so it is stopped by a full ring many times over and has to wait for the consumer. The consumer checks each number arrives in order, and adds them.

        +
        Pipe.raz
        module Pipe;
        +import Out, Fmt, Ring, Thread;
        +
        +const Count = 100000;
        +
        +var
        +    ring: Ring.Ring;
        +    sum, outOfOrder: INT;
        +
        +proc producer(_arg: ^U8);
        +var i: INT;
        +begin
        +    for i := 1 to Count do Ring.put(ADR(ring), i); end;
        +end;
        +
        +proc consumer(_arg: ^U8);
        +var i, v: INT;
        +begin
        +    for i := 1 to Count do
        +        v := Ring.take(ADR(ring));
        +        if v # i then INC(outOfOrder); end;
        +        sum := sum + v;
        +    end;
        +end;
        +
        +proc main*;
        +var p, c: ^Thread.Thread; err: ERROR;
        +begin
        +    p, err := Thread.spawn(producer, nil);
        +    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    c, err := Thread.spawn(consumer, nil);
        +    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    Thread.join(p);
        +    Thread.join(c);
        +    Fmt.print("{} items, sum {}, {} out of order\n",
        +        [Fmt.int(Count), Fmt.int(sum), Fmt.int(outOfOrder)]);
        +end;
        +
        +end Pipe.
        +
        100000 items, sum 5000050000, 0 out of order
        +
        +

        The sum of 1 to 100000 is 5000050000, and nothing arrives out of order. sum and outOfOrder are written only by the consumer thread and read by main after Thread.join, which is the synchronization that makes them visible: a join is the thread's end, observed.

        +

        What it used

        +
        • Modules (Ring, with its record's own fields unexported).
        • Atomics for the handoff, and an ordering argument for why a slot is complete when its counter moves.
        • Threads from Thread, with no C in the program.
        • The checks, which stay on: slots[t mod Size] is an indexed array access that can't leave the array, whatever the counters do.
        +

        It is not a finished library: it is one producer and one consumer, and a second of either breaks the one-writer rule. That is the sort of statement a comment above put and take should make, and the sort a reader should demand.

        +

        Where next

        +

        That is the end of the tour. A few places to continue:

        +
        • The report defines the language, and is short enough to read through.
        • doc/compiler.md in the sources is a guide to reading the compiler, file by file; it is a model of the style the project is written in.
        • lib/ is the library, in raz. Each module's own main is its test. Reading Heap, Map, Opt and Thread is the best remaining education.
        • tools/Doc.raz prints what a module exports with its comments: raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz.
        • examples/ holds small programs with the output each should give, and conform/ holds what any implementation must do.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/static.html b/site/public/advanced/static.html new file mode 100644 index 0000000..8278de8 --- /dev/null +++ b/site/public/advanced/static.html @@ -0,0 +1,143 @@ + + + + + +A program with no run time - Beyond Go + + + +
        +
        +

        Standing alone · lesson 7 of 18

        A program with no run time

        +

        Most languages arrive with a run time: a collector, a loader of libraries, start-up code you didn't write. A raz program that doesn't use C has none of that. The executable holds the code the program reaches, a few lines of start-up code, and nothing else. This part of the tour looks at what that means in practice, and what a program can do when nothing stands between it and the kernel.

        +

        The smallest program

        +

        This program imports nothing. It makes the write system call itself, with the built-in SYSCALL, and returns.

        +
        Bare.raz
        module Bare;
        +
        +const Msg = "hello from raw system calls\n";
        +
        +proc main*;
        +begin
        +    _ := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg));
        +end;
        +
        +end Bare.
        +
        $ raz Bare.raz
        +$ ./Bare
        +hello from raw system calls
        +$ file Bare
        +Bare: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, with debug_info, not stripped
        +$ ldd Bare
        +	not a dynamic executable
        +$ ls -l Bare | awk '{print $5, "bytes"}'
        +26272 bytes
        +

        It is statically linked: no interpreter, no shared libraries, no libc. ldd says so.

        +

        What it does when it runs

        +

        strace lists every system call a program makes. This is the whole of it:

        +
        $ strace ./Bare 2>&1 >/dev/null | sed -e 's/0x[0-9a-f]\{5,\}/ADDR/g' -e 's/[0-9]* vars/N vars/'
        +execve("./Bare", ["./Bare"], ADDR /* N vars */) = 0
        +sigaltstack({ss_sp=ADDR, ss_flags=0, ss_size=16384}, NULL) = 0
        +rt_sigaction(SIGSEGV, {sa_handler=ADDR, sa_mask=[], sa_flags=SA_RESTORER|SA_ONSTACK|SA_RESETHAND|SA_SIGINFO, sa_restorer=ADDR}, NULL, 8) = 0
        +rt_sigaction(SIGFPE, {sa_handler=ADDR, sa_mask=[], sa_flags=SA_RESTORER|SA_ONSTACK|SA_RESETHAND|SA_SIGINFO, sa_restorer=ADDR}, NULL, 8) = 0
        +write(1, "hello from raw system calls\n", 28) = 28
        +exit_group(0)                           = ?
        ++++ exited with 0 +++
        +

        The start-up code does four things before main runs: it sets up a stack of its own for signal handlers (sigaltstack), and installs handlers for SIGSEGV and SIGFPE. That is what turns a nil pointer or a division by zero into a message that names the place, instead of a bare "Segmentation fault". Then main runs its single write, and the program ends with exit_group. Nothing is mapped, loaded, or looked up.

        +

        Programs that use C

        +

        A program that declares an extern procedure, or links a library, is a different animal. It is linked dynamically and starts through the C library, so that C's own set-up and clean-up run. Compare the same kind of hello, with C's printf:

        +
        Cprint.raz
        module Cprint;
        +
        +extern proc puts(s: ^U8): I32;
        +
        +proc main*;
        +begin
        +    _ := puts("hello from C");
        +end;
        +
        +end Cprint.
        +
        $ raz Cprint.raz
        +$ ./Cprint
        +hello from C
        +$ file Cprint
        +Cprint: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, with debug_info, not stripped
        +$ ldd Cprint | sed 's/ (0x[0-9a-f]*)//'
        +	linux-vdso.so.1
        +	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
        +	/lib64/ld-linux-x86-64.so.2
        +

        Both are fine. The point is that you choose, and the language says which you chose: a program uses C exactly when a module of it has an extern or a link of a library.

        +

        Only what is reached

        +

        The compiler keeps only what can be reached from main and the module bodies. Unused procedures, variables and strings are left out. Here are two programs that differ by one large procedure that nothing calls.

        +
        Lean.raz
        module Lean;
        +import Out;
        +
        +proc main*;
        +begin
        +    Out.str("same program\n");
        +end;
        +
        +end Lean.
        +
        Heavy.raz
        module Heavy;
        +import Out;
        +
        +var table: [100000]INT;
        +
        +(* exported, but never called, so never in the executable *)
        +proc unused*(n: INT): INT;
        +var i, s: INT;
        +begin
        +    for i := 0 to 99999 do table[i] := n * i; s := s + table[i]; end;
        +    Out.str("a long string that nobody will ever print, to give it some weight");
        +    return s;
        +end;
        +
        +proc main*;
        +begin
        +    Out.str("same program\n");
        +end;
        +
        +end Heavy.
        +
        $ raz Lean.raz
        +$ raz Heavy.raz
        +$ ls -l Lean Heavy | awk '{print $9, $5}'
        +Heavy 28480
        +Lean 28472
        +

        The sizes differ by a few bytes, not by the hundreds of kilobytes that the table and the procedure would take: they are not in the executable at all. You can link in a library module without worrying what else it offers.

        +

        Stripping

        +

        -s leaves out what is there for finding faults: the symbols and line numbers, the places a failure is told by, and the profiler. It is for the final build of a size-conscious program; the default keeps them so that gdb and failure messages work.

        +
        $ raz -s -o Lean-stripped Lean.raz
        +$ ls -l Lean Lean-stripped | awk '{print $9, $5}'
        +Lean 28472
        +Lean-stripped 6752
        +$ ./Lean-stripped
        +same program
        +

        raz -S Lean.raz is the other direction: it prints the machine code the compiler made, one source line at a time. The next two parts of the tour use it.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/syscalls.html b/site/public/advanced/syscalls.html new file mode 100644 index 0000000..44eab44 --- /dev/null +++ b/site/public/advanced/syscalls.html @@ -0,0 +1,190 @@ + + + + + +System calls - Beyond Go + + + +
        +
        +

        The machine · lesson 12 of 18

        System calls

        +

        Under Sys there is one built-in: SYSCALL(n, x1, ..., x6). It makes Linux system call number n with up to six arguments, each a pointer or an integer no wider than INT, and gives the raw result, an INT. A negative result is -errno. That is all the interface there is; Sys.write, Sys.open and the rest of lib/Sys.linux-x86_64.raz are written with it, in raz, in a few lines each.

        +

        SYSCALL exists only on Linux targets. Other systems have no stable system call interface, which is why their Sys calls the C library instead.

        +

        The shape of a call

        +

        write(fd, buf, count) is call number 1. The arguments are the descriptor, a pointer to the bytes, and how many.

        +
        Raw.raz
        module Raw;
        +
        +const Msg = "straight to the kernel\n";
        +
        +proc main*;
        +var n: INT;
        +begin
        +    n := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg));
        +    if n # LEN(Msg) then _ := SYSCALL(60, 1); end;      (* exit(1), if it came up short *)
        +end;
        +
        +end Raw.
        +
        $ raz -Werror Raw.raz
        +$ ./Raw
        +straight to the kernel
        +

        That program has no Out, no Sys, and no output buffer. What it needs of the library is Rt's start-up, which the compiler links in anyway.

        +

        Reading the result

        +

        A result that is negative is a failure, and its negation is the errno. open is call 2 and wants a C string: the path's bytes followed by a zero. A [N]U8 made from a string literal is zero-filled past its length, so there is always a terminator.

        +
        Open.raz
        module Open;
        +import Out;
        +
        +proc main*;
        +var path: [32]U8; fd: INT;
        +begin
        +    path := "/no/such/file";
        +    fd := SYSCALL(2, ADR(path[0]), 0, 0);        (* open(path, O_RDONLY) *)
        +    Out.str("open gave "); Out.int(fd); Out.ln;   (* -2: ENOENT *)
        +    path := "/dev/null";
        +    fd := SYSCALL(2, ADR(path[0]), 0, 0);
        +    if fd >= 0 then
        +        Out.str("opened /dev/null\n");
        +        _ := SYSCALL(3, fd);                      (* close *)
        +    end;
        +end;
        +
        +end Open.
        +
        open gave -2
        +opened /dev/null
        +
        +

        The library's Sys.openRead does exactly this, and Sys.close too. Reading lib/Sys.linux-x86_64.raz is the best reference there is for what each call wants.

        +

        A call that fills a structure

        +

        uname (call 63) fills a structure of six 65-byte fields: the system name, node name, release, version, machine and domain. It is not a type raz knows; it is an array of bytes, with a ADR of it given to the kernel.

        +
        Who.raz
        module Who;
        +import Out;
        +
        +(* the length of the zero-ended string at the start of s *)
        +proc cstr(s: []U8): INT;
        +var n: INT;
        +begin
        +    n := 0;
        +    while (n < LEN(s)) and (s[n] # 0) do INC(n); end;
        +    return n;
        +end;
        +
        +proc main*;
        +var u: [390]U8;
        +begin
        +    if SYSCALL(63, ADR(u[0])) = 0 then
        +        Out.str("system: "); Out.str(u[0..cstr(u[0..65])]); Out.ln;
        +        Out.str("machine: "); Out.str(u[260..260 + cstr(u[260..325])]); Out.ln;
        +    end;
        +end;
        +
        +end Who.
        +
        system: Linux
        +machine: x86_64
        +
        +

        Memory straight from the kernel

        +

        mmap is call 9: six arguments, the most one call can take. This asks for a page of anonymous, zeroed memory, writes in it, and gives it back with munmap (call 11). It is what Mem.pages does, and so what every allocator is ultimately made of.

        +
        Pages.raz
        module Pages;
        +import Out;
        +
        +proc main*;
        +var p: ^U8; i: INT; total: INT;
        +begin
        +    (* length 4096; PROT_READ|WRITE = 3; MAP_PRIVATE|ANONYMOUS = 22H; no fd *)
        +    p := ^U8(SYSCALL(9, 0, 4096, 3, 22H, -1, 0));
        +    if INT(p) < 0 then Out.str("no memory\n"); return; end;
        +    Out.int(INT(p[0]) + INT(p[4095])); Out.str(" (zero, as promised)\n");
        +    for i := 0 to 4095 do p[i] := U8(i); end;
        +    for i := 0 to 4095 do INC(total, INT(p[i])); end;
        +    Out.int(total); Out.ln;
        +    _ := SYSCALL(11, p, 4096);
        +end;
        +
        +end Pages.
        +
        0 (zero, as promised)
        +522240
        +
        +

        A cat with no library

        +

        Reading and writing in a loop is all cat does. With system calls, it is one procedure. Call 0 is read and call 1 is write; 0 and 1 are standard input and output.

        +
        Cat.raz
        module Cat;
        +
        +proc main*: INT;
        +var buf: [4096]U8; n, wrote, at: INT;
        +begin
        +    n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf));
        +    while n > 0 do
        +        at := 0;
        +        while at < n do                   (* a write may be partial *)
        +            wrote := SYSCALL(1, 1, ADR(buf[at]), n - at);
        +            if wrote < 0 then return 1; end;
        +            INC(at, wrote);
        +        end;
        +        n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf));
        +    end;
        +    if n < 0 then return 1; end;
        +    return 0;
        +end;
        +
        +end Cat.
        +
        $ raz Cat.raz
        +$ echo "through the pipe" | ./Cat
        +through the pipe
        +$ ./Cat < /dev/null; echo "status $?"
        +status 0
        +$ echo "see the calls" | strace -e trace=read,write ./Cat 2>&1 >/dev/null | grep -v '^+++'
        +read(0, "see the calls\n", 4096)        = 14
        +write(1, "see the calls\n", 14)         = 14
        +read(0, "", 4096)                       = 0
        +

        The partial-write loop is the kind of detail Sys.write leaves to the caller on purpose: it returns the bytes written, and the program decides what to do about the rest.

        +

        In a code procedure

        +

        A system call is also an instruction. syscall takes its number in rax and its arguments in rdi, rsi, rdx, r10, r8 and r9, which is not quite the order a procedure's arguments arrive in, since r10 takes the place of rcx, and syscall itself clobbers rcx and r11.

        +
        Ppid.raz
        module Ppid;
        +import Out;
        +
        +(* getppid, call 110: no arguments *)
        +proc getppid: INT;
        +code
        +    mov eax, 110;
        +    syscall;
        +    ret;
        +end getppid;
        +
        +proc main*;
        +begin
        +    if (getppid() > 0) and (SYSCALL(110) = getppid()) then
        +        Out.str("two ways to ask, one answer\n");
        +    end;
        +end;
        +
        +end Ppid.
        +
        two ways to ask, one answer
        +
        +

        SYSCALL is the right tool nearly always: the compiler puts the arguments where they belong, and the result is checked in the open. A code procedure is for the rare call you want to make from inside another piece of assembly.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/targets.html b/site/public/advanced/targets.html new file mode 100644 index 0000000..43a8098 --- /dev/null +++ b/site/public/advanced/targets.html @@ -0,0 +1,103 @@ + + + + + +One module, one file per target - Beyond Go + + + +
        +
        +

        Standing alone · lesson 10 of 18

        One module, one file per target

        +

        raz is first made for x86-64 Linux, but the language is written to be implemented elsewhere, and the library is arranged for it. The part of a program that depends on the system goes in a module of its own, one file per target. This is how Sys is made, and it is how your own code should keep its system-dependent parts apart.

        +

        The files

        +

        A module Name lives in Name.raz. A module whose code depends on the system comes in one file per target, Name.linux-x86_64.raz, which the compiler looks for first. The library has Sys.linux-x86_64.raz, which makes system calls, and Sys.raz, which calls the C library instead, for every other system. A program that imports Sys doesn't know or care which it got.

        +
        $ ls $RAZLIB | grep -i "^sys\|^thread"
        +Sys.linux-x86_64.raz
        +Sys.raz
        +Thread.linux-x86_64.raz
        +$ cd $RAZLIB && grep -c SYSCALL Sys.linux-x86_64.raz Sys.raz
        +Sys.linux-x86_64.raz:78
        +Sys.raz:0
        +

        A module of your own

        +

        Here is a module with two files. Clock.linux-x86_64.raz is for this target; Clock.raz is what any other target would use. Both say what they are in Name, and both make ticks.

        +
        Clock.linux-x86_64.raz
        module Clock;
        +import Sys;
        +
        +const Name* = "the linux-x86_64 file";
        +
        +(* a number that only grows *)
        +proc ticks*: I64;
        +begin
        +    return Sys.clock();
        +end;
        +
        +end Clock.
        +
        Clock.raz
        module Clock;
        +import Sys;
        +
        +const Name* = "the portable file";
        +
        +(* a number that only grows *)
        +proc ticks*: I64;
        +begin
        +    return Sys.clock();
        +end;
        +
        +end Clock.
        +

        A program that imports Clock gets the first of them here:

        +
        Show.raz
        module Show;
        +import Out, Clock;
        +
        +proc main*;
        +begin
        +    Out.str("using "); Out.str(Clock.Name); Out.ln;
        +    if Clock.ticks() > 0 then Out.str("and it ticks\n"); end;
        +end;
        +
        +end Show.
        +
        using the linux-x86_64 file
        +and it ticks
        +
        +

        Held to one interface

        +

        Two files can't be told apart by their callers, so the compiler holds them to the same interface. Here is the pair again with ticks changed in the portable file to return an INT:

        +
        $ mkdir drift && cp Clock*.raz Show.raz drift && cd drift
        +$ sed -i 's/proc ticks\*: I64/proc ticks*: INT/; s/return Sys.clock()/return INT(Sys.clock())/' Clock.raz
        +$ raz Show.raz
        +raz: ./Clock.raz: ticks isn't exported as in ./Clock.linux-x86_64.raz
        +

        The program stops compiling on every target, including the ones that would never have used that file. A mismatch is found where it is made, not where someone first builds for a second target.

        +

        What the compiler checks

        +

        When it takes one of Name.*.raz, it also reads the declarations of the others beside it, and of Name.raz if there is one, and reports an error unless they all export the same names, each the same kind of thing: a constant of the same type (its value may differ), a type of the same kind with the same exported fields, a variable of the same type, a procedure of the same signature. The code, the unexported fields, and so the size and layout, may differ.

        +

        So a program written against the interface works on every target that has the module, and the places where it doesn't are the compiler's to find, not yours.

        +

        What stays the same everywhere

        +

        The core of the library is what every target must have: Rt, Out, Mem, Arena, Lock, Str and Buf, and of Sys what they need. A program that keeps to the core runs on every target. Thread, link and extern, and most of Sys, are what a target may leave out when its system can't give them.

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/advanced/volatile.html b/site/public/advanced/volatile.html new file mode 100644 index 0000000..cfeed2f --- /dev/null +++ b/site/public/advanced/volatile.html @@ -0,0 +1,145 @@ + + + + + +Volatile - Beyond Go + + + +
        +
        +

        Shared memory · lesson 14 of 18

        Volatile

        +

        Most memory is the program's own: only it reads and writes it, so the compiler may keep a variable in a register, leave out a write that nothing reads, and change the order of accesses, as long as the program does what the report says. Some memory is not: a device's registers, memory another processor or thread is changing, a page the kernel fills. There, each access matters, and its order.

        +

        A variable reached through a ^VOLATILE T is volatile, and so is any field or element of it. Each read or write of one of a basic, enumeration, set or pointer type is exactly one memory access, of exactly its size, and volatile accesses happen in the order the program writes them.

        +

        A device laid over memory

        +

        The classic use is a device's registers: a record that says what is at which offset, laid over the address the hardware answers at. The record's layout is C's, so it is the same as the datasheet's struct. Here a page of the program's own stands in for the device.

        +
        Uart.raz
        module Uart;
        +import Out;
        +
        +type
        +    Regs = record
        +        data: U32;       (* offset 0 *)
        +        status: U32;     (* offset 4 *)
        +        control: U8;     (* offset 8 *)
        +    end;
        +
        +var page: [64]U8;        (* where the device would be *)
        +
        +proc main*;
        +var dev: ^VOLATILE Regs; i: INT;
        +begin
        +    dev := ^VOLATILE Regs(ADR(page));      (* the conversion is written *)
        +    dev^.control := 1;
        +    dev^.status := 0FFH;
        +    for i := 0 to 2 do
        +        dev^.data := U32('a' + i);
        +        Out.char(U8(dev^.data));
        +    end;
        +    Out.ln;
        +    FENCE;
        +    Out.int(INT(page[8])); Out.char(' '); Out.int(INT(dev^.status)); Out.ln;
        +end;
        +
        +end Uart.
        +
        abc
        +1 255
        +
        +

        On real hardware the address would be a constant, ^VOLATILE Regs(0FEC00000H), which is a legal conversion since an integer constant converts to a pointer. The program is otherwise unchanged.

        +

        What each access is

        +

        The listing shows what the guarantee means: each field access is one instruction of the field's size, and so is a write to a field that is never read afterwards, which an optimizer would be allowed to drop from an ordinary variable.

        +
        $ raz -S Uart.raz | grep -n "dword\|byte" | head -2
        +15:            34  mov byte [rbx + 8], 1
        +17:            38  mov dword [rbx + 4], 255
        +

        The U8 control byte is written with a byte store, and the U32 status with a dword one. Never a wider access that touches the neighbour, never two narrower ones.

        +

        Waiting for something else to change

        +

        Where a program waits for another thread or a device to change a value, the loop must read the value each time. A volatile read does. This "device" is a thread that sets a bit in a status word after a delay; the main thread polls.

        +
        Poll.raz
        module Poll;
        +import Out, Sys, Thread;
        +
        +type Dev = record status: INT; data: INT; end;
        +
        +var dev: Dev;
        +
        +proc device(_arg: ^U8);
        +var d: ^VOLATILE Dev;
        +begin
        +    d := ^VOLATILE Dev(ADR(dev));
        +    Sys.sleep(20);
        +    d^.data := 42;
        +    FENCE;                          (* data before the flag that announces it *)
        +    d^.status := 1;
        +end;
        +
        +proc main*;
        +var t: ^Thread.Thread; err: ERROR; d: ^VOLATILE Dev; spins: INT;
        +begin
        +    d := ^VOLATILE Dev(ADR(dev));
        +    t, err := Thread.spawn(device, nil);
        +    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
        +    while d^.status = 0 do INC(spins); Sys.yield; end;
        +    Out.int(d^.data); Out.ln;
        +    if spins > 0 then Out.str("it waited for the device\n"); end;
        +    Thread.join(t);
        +end;
        +
        +end Poll.
        +
        42
        +it waited for the device
        +
        +

        The FENCE between the two writes matters. It is a full memory barrier, ordering the program's ordinary accesses against those of other processors and devices. Without it, volatile accesses are ordered among themselves, but nothing says another processor sees data before status. The next lessons are about this.

        +

        What volatile is not

        +
        • Not atomic across a read-modify-write. INC(d^.count) reads and then writes: two accesses, even through a volatile pointer. XADD is the atomic one.
        • Not a lock. It says each access happens as written; it says nothing about what happens between them.
        • Not for whole records or arrays. Copying a whole record through a volatile pointer isn't allowed, since it can't be one access. A field of a packed record can't be reached volatilely at all, since a misaligned access can't be promised as one.
        • Not silently dropped. A ^VOLATILE T doesn't convert to a ^T without a written conversion, so the volatile can't be lost by accident.
        +

        The compiler holds the line on each of them:

        +
        Wrong.raz
        module Wrong;
        +
        +type Pair = record a, b: U32; end;
        +
        +var cell: Pair;
        +
        +proc main*;
        +var v: ^VOLATILE Pair; p: ^Pair; copy: Pair;
        +begin
        +    v := ^VOLATILE Pair(ADR(cell));
        +    p := v;
        +    copy := v^;
        +end;
        +
        +end Wrong.
        +
        $ raz Wrong.raz
        +Wrong.raz:11:10: error: can't use ^VOLATILE Pair as ^Pair
        +   11 |     p := v;
        +      |          ^
        +Wrong.raz:12:13: error: can't copy through a volatile pointer
        +   12 |     copy := v^;
        +      |             ^^
        +raz: 2 errors

        Save a program under its module’s name and run it with raz run Name.raz.

        +
        +
        raz is under the ISC license. Source.
        + + diff --git a/site/public/index.html b/site/public/index.html index b4378b1..c9883fb 100644 --- a/site/public/index.html +++ b/site/public/index.html @@ -7,7 +7,7 @@ -
        +

        raz

        @@ -15,6 +15,7 @@ Raz is Polish for one, as in counting.

        @@ -86,6 +87,13 @@ + +

        Learn it

        +

        Raz, Set, Go is a tour of the +language in 14 lessons, each with programs you can run. Beyond Go is the second tour: +the library, programs with no run time, procedures in assembly, system calls, +volatile accesses, atomics and lock-free code, in 18 more.

        The language, in writing

        The language is defined by the report, which is diff --git a/site/public/spec.html b/site/public/spec.html index b46084a..7778615 100644 --- a/site/public/spec.html +++ b/site/public/spec.html @@ -7,7 +7,7 @@ -

        +
        • 1. A first diff --git a/site/public/style.css b/site/public/style.css index 8cc1282..5f3cdee 100644 --- a/site/public/style.css +++ b/site/public/style.css @@ -69,7 +69,7 @@ .tour aside { font-family: system-ui, sans-serif; font-size: 14px; } .tour aside h3 { margin: 1em 0 .2em; font-size: 12px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); } -.tour aside ol { margin: 0; padding-left: 1.5em; } .tour aside a { color: var(--fg); text-decoration: none; } +.tour aside ol { margin: 0; padding-left: 1.9em; } .tour aside a { color: var(--fg); text-decoration: none; } .tour aside a[aria-current] { color: var(--accent); font-weight: 700; } @media (max-width: 55.99rem) { .tour aside { order: 2; border-top: 1px solid var(--line); } } .tour article { min-width: 0; } @@ -86,3 +86,7 @@ .spec table { border-collapse: collapse; display: block; overflow-x: auto; font-size: 15px; } .spec td, .spec th { border-bottom: 1px solid var(--line); padding: 3px 10px; text-align: left; } .spec nav#TOC ul { list-style: none; padding-left: 1em; } + +/* a shell session */ +pre.term::before { content: "terminal"; } +pre .cmd { color: #8fd18f; } diff --git a/site/public/tour/c.html b/site/public/tour/c.html index b1ac93e..81d4842 100644 --- a/site/public/tour/c.html +++ b/site/public/tour/c.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/checks.html b/site/public/tour/checks.html index 7801147..e68fb8e 100644 --- a/site/public/tour/checks.html +++ b/site/public/tour/checks.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/defer.html b/site/public/tour/defer.html index f298d57..0c76f30 100644 --- a/site/public/tour/defer.html +++ b/site/public/tour/defer.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/errors.html b/site/public/tour/errors.html index be7bbe6..3d39d8d 100644 --- a/site/public/tour/errors.html +++ b/site/public/tour/errors.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/generics.html b/site/public/tour/generics.html index a2c0740..87b74b6 100644 --- a/site/public/tour/generics.html +++ b/site/public/tour/generics.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/hello.html b/site/public/tour/hello.html index b0e376f..8cd2e9a 100644 --- a/site/public/tour/hello.html +++ b/site/public/tour/hello.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/index.html b/site/public/tour/index.html index 4f1192c..19a2cbe 100644 --- a/site/public/tour/index.html +++ b/site/public/tour/index.html @@ -3,11 +3,11 @@ -Raz, Set, Go: a tour of raz +Raz, Set, Go -
          +

          Raz, Set, Go

          A tour of raz, in the spirit of A Tour of Go. Each lesson is one @@ -17,26 +17,26 @@ first steps; Set, how data is laid out; and Go, making programs that run, fail and finish well. To follow along, get raz and run any program with -raz run Name.raz.

          +raz run Name.raz. When you finish, Beyond Go goes down to the machine.

          Raz

            -
          1. Hello, world A module, an import and a procedure.
          2. -
          3. Modules Exports, renaming, and a body that runs first.
          4. -
          5. Values and conversions Sized integers that wrap, and nothing converts unasked.
          6. -
          7. Procedures and several results Return two values, change a variable, pass a procedure.
          8. +
          9. Hello, world A module, an import, a procedure; running, printing, exit status and arguments.
          10. +
          11. Modules Exports, renaming, the order bodies run in, and what the compiler refuses.
          12. +
          13. Values and conversions Sized integers that wrap, reals, bits, and nothing converts unasked.
          14. +
          15. Procedures and several results Value and var parameters, several results, forward, and procedures as values.

          Set

            -
          1. Arrays, slices and strings Five in a row, a window onto them, and bytes in UTF-8.
          2. -
          3. Records and pointers Laid out as C lays out a struct, reached through ^.
          4. -
          5. Enumerations, sets, variants and match Choices the compiler can check you handled.
          6. -
          7. Memory and allocators No garbage collector; you choose where memory comes from.
          8. +
          9. Arrays, slices and strings Five in a row, a window onto them, bytes in UTF-8, and checks on every index.
          10. +
          11. Records and pointers Laid out as C lays out a struct, packed records, pointers and nil.
          12. +
          13. Enumerations, sets, variants and match Names in order, sets as bits, and cases the compiler makes you handle.
          14. +
          15. Memory and allocators No garbage collector; you choose where memory comes from, and what happens when it runs out.

          Go

            -
          1. Errors A second result, compared by identity. No exceptions.
          2. -
          3. Defer Clean up beside the line that needs it.
          4. -
          5. When it goes wrong Every index is checked, and a failure tells you everything.
          6. -
          7. Generic modules A module that takes types and procedures as arguments.
          8. -
          9. Talking to C Call a C library, and be called back.
          10. -
          11. Threads Native threads, atomics and a mutex.
          12. +
          13. Errors A second result, compared by identity; passing errors up; and no exceptions.
          14. +
          15. Defer Clean up beside the line that needs it, in the right order, on every way out.
          16. +
          17. When it goes wrong Every index is checked, a failure says where and with what values, and how to read it.
          18. +
          19. Generic modules A module that takes types and procedures; the library's List, Map and Sort.
          20. +
          21. Talking to C Call a C library, be called back, share variables, and mind the two buffers.
          22. +
          23. Threads Native threads without C, atomics, a mutex, and why the counter needs both.
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/memory.html b/site/public/tour/memory.html index af400b6..510d01f 100644 --- a/site/public/tour/memory.html +++ b/site/public/tour/memory.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/modules.html b/site/public/tour/modules.html index c68e12b..c54a40a 100644 --- a/site/public/tour/modules.html +++ b/site/public/tour/modules.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/procedures.html b/site/public/tour/procedures.html index afbdff3..56207c0 100644 --- a/site/public/tour/procedures.html +++ b/site/public/tour/procedures.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/records.html b/site/public/tour/records.html index 94c543a..b21997b 100644 --- a/site/public/tour/records.html +++ b/site/public/tour/records.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/slices.html b/site/public/tour/slices.html index db63446..d309dbc 100644 --- a/site/public/tour/slices.html +++ b/site/public/tour/slices.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/threads.html b/site/public/tour/threads.html index 2fbeece..3cb9f67 100644 --- a/site/public/tour/threads.html +++ b/site/public/tour/threads.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/values.html b/site/public/tour/values.html index 336e45d..624e3fd 100644 --- a/site/public/tour/values.html +++ b/site/public/tour/values.html @@ -7,9 +7,9 @@ -
          +
          -
          raz is under the ISC license. Source.
          diff --git a/site/public/tour/variants.html b/site/public/tour/variants.html index bb11ef8..469afa9 100644 --- a/site/public/tour/variants.html +++ b/site/public/tour/variants.html @@ -7,9 +7,9 @@ -
          +
          -
          diff --git a/site/style.css b/site/style.css index 8cc1282..5f3cdee 100644 --- a/site/style.css +++ b/site/style.css @@ -69,7 +69,7 @@ .tour aside { font-family: system-ui, sans-serif; font-size: 14px; } .tour aside h3 { margin: 1em 0 .2em; font-size: 12px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); } -.tour aside ol { margin: 0; padding-left: 1.5em; } .tour aside a { color: var(--fg); text-decoration: none; } +.tour aside ol { margin: 0; padding-left: 1.9em; } .tour aside a { color: var(--fg); text-decoration: none; } .tour aside a[aria-current] { color: var(--accent); font-weight: 700; } @media (max-width: 55.99rem) { .tour aside { order: 2; border-top: 1px solid var(--line); } } .tour article { min-width: 0; } @@ -86,3 +86,7 @@ .spec table { border-collapse: collapse; display: block; overflow-x: auto; font-size: 15px; } .spec td, .spec th { border-bottom: 1px solid var(--line); padding: 3px 10px; text-align: left; } .spec nav#TOC ul { list-style: none; padding-left: 1em; } + +/* a shell session */ +pre.term::before { content: "terminal"; } +pre .cmd { color: #8fd18f; }