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.
| @@ -8,7 +8,8 @@ | ||
| 8 | 8 | tour's pages is run here, by ./raz, and the output shown is what it |
| 9 | 9 | printed, so a lesson that stops working fails the build. |
| 10 | 10 | |
| 11 | -Lessons are site/content/NN-name.txt: | |
| 11 | +Lessons are site/content/<tour>/NN-name.txt, one folder to a tour (see | |
| 12 | +TOURS below): | |
| 12 | 13 | |
| 13 | 14 | title: Hello, world (the first lines are "key: value") |
| 14 | 15 | part: Raz (the lessons are grouped in parts) |
| @@ -25,6 +26,10 @@ | ||
| 25 | 26 | printed; "fail" runs it and shows the failure it ends in. A block with |
| 26 | 27 | nothing in it is taken from doc/raz-tutorial.7, whose programs make |
| 27 | 28 | check already runs, by the module's name. |
| 29 | + | |
| 30 | +Two other blocks: "```text" is shown as written, and "```sh" is a shell | |
| 31 | +session: each line that starts with "$ " is run in the lesson's folder, | |
| 32 | +with raz on the path, and shown with what it printed. | |
| 28 | 33 | """ |
| 29 | 34 | import html, os, re, shutil, subprocess, sys, tempfile |
| 30 | 35 | |
| @@ -33,6 +38,12 @@ | ||
| 33 | 38 | OUT = os.path.join(HERE, "public") |
| 34 | 39 | RAZ = os.path.join(ROOT, "raz") |
| 35 | 40 | REPO = "https://github.com/ldiaz94/raz" |
| 41 | + | |
| 42 | +# folder in content/, folder in public/, name, the sentence under the name | |
| 43 | +TOURS = [ | |
| 44 | + ("tour", "tour", "Raz, Set, Go", "tour-intro.html"), | |
| 45 | + ("advanced", "advanced", "Beyond Go", "advanced-intro.html"), | |
| 46 | +] | |
| 36 | 47 | |
| 37 | 48 | KEYWORDS = set("""and begin break by code const defer div do else elsif end |
| 38 | 49 | extern for forward if import in link match mod module not of or packed proc |
| @@ -94,10 +105,32 @@ | ||
| 94 | 105 | |
| 95 | 106 | def run(directory, name): |
| 96 | 107 | """(stdout, stderr, status) of the module name, compiled and run.""" |
| 97 | - p = subprocess.run([RAZ, "run", name + ".raz"], cwd=directory, | |
| 108 | + p = subprocess.run([RAZ, "run", "-Werror", name + ".raz"], cwd=directory, | |
| 98 | 109 | capture_output=True, text=True, timeout=60) |
| 99 | 110 | return p.stdout, p.stderr, p.returncode |
| 100 | 111 | |
| 112 | +def shell_html(directory, script): | |
| 113 | + """A session: each "$ command" line run in directory, with its output.""" | |
| 114 | + bin = os.path.join(directory, ".bin") | |
| 115 | + os.makedirs(bin, exist_ok=True) | |
| 116 | + if not os.path.exists(os.path.join(bin, "raz")): | |
| 117 | + os.symlink(RAZ, os.path.join(bin, "raz")) # raz finds lib/ by its real path | |
| 118 | + env = dict(os.environ, PATH=bin + ":" + os.environ["PATH"], | |
| 119 | + RAZLIB=os.path.join(ROOT, "lib")) | |
| 120 | + out = [] | |
| 121 | + for line in script.rstrip("\n").split("\n"): | |
| 122 | + if not line.startswith("$ "): | |
| 123 | + out.append(html.escape(line)) | |
| 124 | + continue | |
| 125 | + out.append('<span class="cmd">%s</span>' % html.escape(line)) | |
| 126 | + p = subprocess.run(line[2:], shell=True, cwd=directory, env=env, | |
| 127 | + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, | |
| 128 | + text=True, timeout=60) | |
| 129 | + text = p.stdout.rstrip("\n") | |
| 130 | + if text: | |
| 131 | + out.append(html.escape(text)) | |
| 132 | + return '<pre class="output term"><code>%s</code></pre>' % "\n".join(out) | |
| 133 | + | |
| 101 | 134 | def output_html(stdout, stderr): |
| 102 | 135 | out = html.escape(stdout) |
| 103 | 136 | if stderr: |
| @@ -117,7 +150,9 @@ | ||
| 117 | 150 | out = [] |
| 118 | 151 | for para in re.split(r"\n\s*\n", text.strip()): |
| 119 | 152 | lines = para.split("\n") |
| 120 | - if all(l.startswith("- ") for l in lines): | |
| 153 | + if para.startswith("## "): | |
| 154 | + out.append("<h2>%s</h2>" % inline(para[3:])) | |
| 155 | + elif all(l.startswith("- ") for l in lines): | |
| 121 | 156 | out.append("<ul>%s</ul>" % "".join( |
| 122 | 157 | "<li>%s</li>" % inline(l[2:]) for l in lines)) |
| 123 | 158 | else: |
| @@ -137,7 +172,7 @@ | ||
| 137 | 172 | """The lesson's page content; runs its programs.""" |
| 138 | 173 | parts, tmp = [], tempfile.mkdtemp() |
| 139 | 174 | try: |
| 140 | - chunks = re.split(r"^```raz ([^\n]*)\n(.*?)^```$", lesson["body"], | |
| 175 | + chunks = re.split(r"^```(raz [^\n]*|text|sh)\n(.*?)^```$", lesson["body"], | |
| 141 | 176 | flags=re.M | re.S) |
| 142 | 177 | # chunks: text, info, code, text, info, code, ..., text |
| 143 | 178 | for i in range(0, len(chunks), 3): |
| @@ -145,7 +180,15 @@ | ||
| 145 | 180 | parts.append(prose(chunks[i])) |
| 146 | 181 | if i + 1 >= len(chunks): |
| 147 | 182 | break |
| 148 | - info, code = chunks[i + 1].split(), chunks[i + 2] | |
| 183 | + kind, code = chunks[i + 1], chunks[i + 2] | |
| 184 | + if kind == "text": | |
| 185 | + parts.append('<pre class="code"><code>%s</code></pre>' | |
| 186 | + % html.escape(code.rstrip("\n"))) | |
| 187 | + continue | |
| 188 | + if kind == "sh": | |
| 189 | + parts.append(shell_html(tmp, code)) | |
| 190 | + continue | |
| 191 | + info = kind.split()[1:] | |
| 149 | 192 | name, flags = info[0], info[1:] |
| 150 | 193 | if not code.strip(): |
| 151 | 194 | code = tutorial_module(name) |
| @@ -173,6 +216,7 @@ | ||
| 173 | 216 | for key, href, label in [ |
| 174 | 217 | ("home", "index.html", "raz"), |
| 175 | 218 | ("tour", "tour/index.html", "Raz, Set, Go"), |
| 219 | + ("advanced", "advanced/index.html", "Beyond Go"), | |
| 176 | 220 | ("spec", "spec.html", "Report"), |
| 177 | 221 | ("get", "index.html#download", "Download")]) |
| 178 | 222 | return """<!doctype html> |
| @@ -199,16 +243,19 @@ | ||
| 199 | 243 | with open(path, "w", encoding="utf-8") as f: |
| 200 | 244 | f.write(text) |
| 201 | 245 | |
| 202 | -def build_tour(lessons): | |
| 246 | +def build_tour(tour, lessons, next_page): | |
| 247 | + """One tour's pages: a contents page and a page to each lesson. | |
| 248 | + next_page is (href, label) for what follows its last lesson.""" | |
| 249 | + folder, outdir, name, intro_file = tour | |
| 203 | 250 | parts = [] |
| 204 | 251 | for l in lessons: |
| 205 | 252 | if l["part"] not in parts: |
| 206 | 253 | parts.append(l["part"]) |
| 254 | + first = lambda p: 1 + next(i for i, x in enumerate(lessons) if x["part"] == p) | |
| 207 | 255 | for n, l in enumerate(lessons): |
| 208 | 256 | toc = [] |
| 209 | 257 | for p in parts: |
| 210 | - toc.append("<h3>%s</h3><ol start='%d'>" % ( | |
| 211 | - p, 1 + next(i for i, x in enumerate(lessons) if x["part"] == p))) | |
| 258 | + toc.append("<h3>%s</h3><ol start='%d'>" % (p, first(p))) | |
| 212 | 259 | for i, x in enumerate(lessons): |
| 213 | 260 | if x["part"] == p: |
| 214 | 261 | cur = ' aria-current="page"' if i == n else "" |
| @@ -223,29 +270,27 @@ | ||
| 223 | 270 | pager += '<a class="next" href="%s.html">%s →</a>' % ( |
| 224 | 271 | lessons[n + 1]["slug"], html.escape(lessons[n + 1]["title"])) |
| 225 | 272 | else: |
| 226 | - pager += '<a class="next" href="../spec.html">The report →</a>' | |
| 227 | - body = ('<div class="tour"><aside>%s</aside><article>' | |
| 273 | + pager += '<a class="next" href="%s">%s →</a>' % next_page | |
| 274 | + body = ('<div class="tour"><aside><h2>%s</h2>%s</aside><article>' | |
| 228 | 275 | '<p class="kicker">%s · lesson %d of %d</p><h1>%s</h1>\n%s' |
| 229 | 276 | '<p class="tryit">Save a program under its module’s name and run ' |
| 230 | 277 | 'it with <code>raz run Name.raz</code>.</p>' |
| 231 | 278 | '<div class="pager">%s</div></article></div>') % ( |
| 232 | - "\n".join(toc), l["part"], n + 1, len(lessons), | |
| 279 | + name, "\n".join(toc), l["part"], n + 1, len(lessons), | |
| 233 | 280 | html.escape(l["title"]), lesson_body(l), pager) |
| 234 | - write("tour/%s.html" % l["slug"], page( | |
| 235 | - "%s - Raz, Set, Go" % l["title"], body, 1, "tour")) | |
| 281 | + write("%s/%s.html" % (outdir, l["slug"]), page( | |
| 282 | + "%s - %s" % (l["title"], name), body, 1, folder)) | |
| 236 | 283 | cards = [] |
| 237 | 284 | for p in parts: |
| 238 | - cards.append("<h2>%s</h2><ol start='%d'>" % ( | |
| 239 | - p, 1 + next(i for i, x in enumerate(lessons) if x["part"] == p))) | |
| 285 | + cards.append("<h2>%s</h2><ol start='%d'>" % (p, first(p))) | |
| 240 | 286 | for x in lessons: |
| 241 | 287 | if x["part"] == p: |
| 242 | 288 | cards.append('<li><a href="%s.html">%s</a> <span>%s</span></li>' % ( |
| 243 | 289 | x["slug"], html.escape(x["title"]), html.escape(x["summary"]))) |
| 244 | 290 | cards.append("</ol>") |
| 245 | - intro = open(os.path.join(HERE, "content", "tour-intro.html"), | |
| 246 | - encoding="utf-8").read() | |
| 247 | - write("tour/index.html", page("Raz, Set, Go: a tour of raz", | |
| 248 | - '<div class="contents">%s%s</div>' % (intro, "\n".join(cards)), 1, "tour")) | |
| 291 | + intro = open(os.path.join(HERE, "content", intro_file), encoding="utf-8").read() | |
| 292 | + write("%s/index.html" % outdir, page(name, | |
| 293 | + '<div class="contents">%s%s</div>' % (intro, "\n".join(cards)), 1, folder)) | |
| 249 | 294 | |
| 250 | 295 | def build_spec(): |
| 251 | 296 | if not shutil.which("pandoc"): |
| @@ -282,10 +327,19 @@ | ||
| 282 | 327 | shutil.copy(os.path.join(HERE, "style.css"), OUT) |
| 283 | 328 | names = sorted(f for f in os.listdir(os.path.join(HERE, "content")) |
| 284 | 329 | if re.match(r"\d+-.*\.txt$", f)) |
| 285 | - lessons = [read_lesson(os.path.join(HERE, "content", f)) for f in names] | |
| 286 | - build_tour(lessons) | |
| 330 | + counts = [] | |
| 331 | + for i, tour in enumerate(TOURS): | |
| 332 | + folder = os.path.join(HERE, "content", tour[0]) | |
| 333 | + lessons = [read_lesson(os.path.join(folder, f)) | |
| 334 | + for f in sorted(os.listdir(folder)) if re.match(r"\d+-.*\.txt$", f)] | |
| 335 | + if i + 1 < len(TOURS): | |
| 336 | + nxt = ("../%s/index.html" % TOURS[i + 1][1], TOURS[i + 1][2]) | |
| 337 | + else: | |
| 338 | + nxt = ("../spec.html", "The report") | |
| 339 | + build_tour(tour, lessons, nxt) | |
| 340 | + counts.append(len(lessons)) | |
| 287 | 341 | build_spec() |
| 288 | 342 | build_home() |
| 289 | - print("site/public: %d lessons" % len(lessons)) | |
| 343 | + print("site/public: %s lessons" % " + ".join(map(str, counts))) | |
| 290 | 344 | |
| 291 | 345 | main() |
| @@ -1,14 +0,0 @@ | ||
| 1 | -title: Hello, world | |
| 2 | -part: Raz | |
| 3 | -summary: A module, an import and a procedure. | |
| 4 | ---- | |
| 5 | -Every raz program is a module with a `main` procedure. This is the smallest one that does something. | |
| 6 | - | |
| 7 | -```raz Hello run | |
| 8 | -``` | |
| 9 | - | |
| 10 | -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`. | |
| 11 | - | |
| 12 | -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`. | |
| 13 | - | |
| 14 | -Compile it and run it with `raz Hello.raz && ./Hello`, or with `raz run Hello.raz`, which writes no file. |
| @@ -1,17 +0,0 @@ | ||
| 1 | -title: Modules | |
| 2 | -part: Raz | |
| 3 | -summary: Exports, renaming, and a body that runs first. | |
| 4 | ---- | |
| 5 | -A program is a set of modules. Here is one, saved as `Greet.raz`: | |
| 6 | - | |
| 7 | -```raz Greet | |
| 8 | -``` | |
| 9 | - | |
| 10 | -and a program beside it that uses it: | |
| 11 | - | |
| 12 | -```raz Twice run | |
| 13 | -``` | |
| 14 | - | |
| 15 | -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. | |
| 16 | - | |
| 17 | -The statements after a module's last `begin` are its body. It runs once, before `main`, which is why "Greet is ready" comes first. |
| @@ -1,14 +0,0 @@ | ||
| 1 | -title: Values and conversions | |
| 2 | -part: Raz | |
| 3 | -summary: Sized integers that wrap, and nothing converts unasked. | |
| 4 | ---- | |
| 5 | -```raz Values run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -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`. | |
| 9 | - | |
| 10 | -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. | |
| 11 | - | |
| 12 | -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. | |
| 13 | - | |
| 14 | -`#`, not `<>`, is "different". `and`, `or` and `not` are for `BOOL`s; `&`, `|`, `xor` and `~` are for the bits of integers. Every variable starts at zero. |
| @@ -1,10 +0,0 @@ | ||
| 1 | -title: Procedures and several results | |
| 2 | -part: Raz | |
| 3 | -summary: Return two values, change a variable, pass a procedure. | |
| 4 | ---- | |
| 5 | -```raz Procs run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -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. | |
| 9 | - | |
| 10 | -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. |
| @@ -1,12 +0,0 @@ | ||
| 1 | -title: Arrays, slices and strings | |
| 2 | -part: Set | |
| 3 | -summary: Five in a row, a window onto them, and bytes in UTF-8. | |
| 4 | ---- | |
| 5 | -```raz Slices run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -`[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. | |
| 9 | - | |
| 10 | -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. | |
| 11 | - | |
| 12 | -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. |
| @@ -1,10 +0,0 @@ | ||
| 1 | -title: Records and pointers | |
| 2 | -part: Set | |
| 3 | -summary: Laid out as C lays out a struct, reached through ^. | |
| 4 | ---- | |
| 5 | -```raz Boxes run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -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. | |
| 9 | - | |
| 10 | -`^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`. |
| @@ -1,10 +0,0 @@ | ||
| 1 | -title: Enumerations, sets, variants and match | |
| 2 | -part: Set | |
| 3 | -summary: Choices the compiler can check you handled. | |
| 4 | ---- | |
| 5 | -```raz Shapes run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -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. | |
| 9 | - | |
| 10 | -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:`. |
| @@ -1,12 +0,0 @@ | ||
| 1 | -title: Memory and allocators | |
| 2 | -part: Set | |
| 3 | -summary: No garbage collector; you choose where memory comes from. | |
| 4 | ---- | |
| 5 | -```raz Stack run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -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. | |
| 9 | - | |
| 10 | -`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. | |
| 11 | - | |
| 12 | -`Buf`, `List` and `Map` take the allocator they use from `init`. |
| @@ -1,10 +0,0 @@ | ||
| 1 | -title: Errors | |
| 2 | -part: Go | |
| 3 | -summary: A second result, compared by identity. No exceptions. | |
| 4 | ---- | |
| 5 | -```raz Errors run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -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. | |
| 9 | - | |
| 10 | -An exported one, as `Empty` is here, lets the callers tell it from the others. raz has no exceptions. |
| @@ -1,10 +0,0 @@ | ||
| 1 | -title: Defer | |
| 2 | -part: Go | |
| 3 | -summary: Clean up beside the line that needs it. | |
| 4 | ---- | |
| 5 | -```raz Defers run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -`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. | |
| 9 | - | |
| 10 | -So a file is closed beside the line that opens it, however the procedure ends. |
| @@ -1,12 +0,0 @@ | ||
| 1 | -title: When it goes wrong | |
| 2 | -part: Go | |
| 3 | -summary: Every index is checked, and a failure tells you everything. | |
| 4 | ---- | |
| 5 | -```raz Fail fail | |
| 6 | -``` | |
| 7 | - | |
| 8 | -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. | |
| 9 | - | |
| 10 | -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. | |
| 11 | - | |
| 12 | -The program carries line numbers for gdb, and `RAZ_PROFILE=1` in its environment has it say where its time went. |
| @@ -1,17 +0,0 @@ | ||
| 1 | -title: Generic modules | |
| 2 | -part: Go | |
| 3 | -summary: A module that takes types and procedures as arguments. | |
| 4 | ---- | |
| 5 | -A module may take types, and the procedures it needs on them, as parameters. `Biggest.raz`: | |
| 6 | - | |
| 7 | -```raz Biggest | |
| 8 | -``` | |
| 9 | - | |
| 10 | -and a program that uses it: | |
| 11 | - | |
| 12 | -```raz Generics run | |
| 13 | -``` | |
| 14 | - | |
| 15 | -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. | |
| 16 | - | |
| 17 | -The library's `List`, `Map` and `Sort` are generic modules: `import Count := Map([]U8, INT, Str.hash, Str.eq);` |
| @@ -1,10 +0,0 @@ | ||
| 1 | -title: Talking to C | |
| 2 | -part: Go | |
| 3 | -summary: Call a C library, and be called back. | |
| 4 | ---- | |
| 5 | -```raz Qsort run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -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. | |
| 9 | - | |
| 10 | -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. |
| @@ -1,12 +0,0 @@ | ||
| 1 | -title: Threads | |
| 2 | -part: Go | |
| 3 | -summary: Native threads, atomics and a mutex. | |
| 4 | ---- | |
| 5 | -```raz Hits run | |
| 6 | -``` | |
| 7 | - | |
| 8 | -`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. | |
| 9 | - | |
| 10 | -`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. | |
| 11 | - | |
| 12 | -That is the tour. The rest is in [the report](../spec.html), and the library's interfaces are printed by `tools/Doc.raz`. |
| @@ -0,0 +1,10 @@ | ||
| 1 | +<h1>Beyond Go</h1> | |
| 2 | +<p>The second tour, for the part of raz that sits close to the machine. It | |
| 3 | +assumes you have taken <a href="../tour/index.html">Raz, Set, Go</a> or know | |
| 4 | +Pascal or C well enough not to need it.</p> | |
| 5 | +<p>It has four parts: <strong>The library</strong>, the modules every program | |
| 6 | +reaches for; <strong>Standing alone</strong>, programs that need no C and no | |
| 7 | +run time; <strong>The machine</strong>, procedures written in assembly and | |
| 8 | +direct system calls; and <strong>Shared memory</strong>, volatile accesses, | |
| 9 | +atomics and threads. Every program is compiled and run when this page is | |
| 10 | +made, as before.</p> |
| @@ -0,0 +1,164 @@ | ||
| 1 | +title: Output and formatting | |
| 2 | +part: The library | |
| 3 | +summary: Out's buffer, Fmt's arguments, formatting into a Buf, and laying out columns. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +## What `Out` does with its buffer | |
| 8 | + | |
| 9 | +`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. | |
| 10 | + | |
| 11 | +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`: | |
| 12 | + | |
| 13 | +```raz Three | |
| 14 | +module Three; | |
| 15 | +import Out; | |
| 16 | + | |
| 17 | +proc main*; | |
| 18 | +begin | |
| 19 | + Out.str("one\n"); | |
| 20 | + Out.str("two\n"); | |
| 21 | + Out.str("three\n"); | |
| 22 | +end; | |
| 23 | + | |
| 24 | +end Three. | |
| 25 | +``` | |
| 26 | + | |
| 27 | +```sh | |
| 28 | +$ raz Three.raz | |
| 29 | +$ strace -e trace=write ./Three > /dev/null | |
| 30 | +``` | |
| 31 | + | |
| 32 | +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. | |
| 33 | + | |
| 34 | +## `Fmt.print` | |
| 35 | + | |
| 36 | +`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. | |
| 37 | + | |
| 38 | +```raz Kinds run | |
| 39 | +module Kinds; | |
| 40 | +import Fmt; | |
| 41 | + | |
| 42 | +proc main*; | |
| 43 | +var big: U64; small: I8; | |
| 44 | +begin | |
| 45 | + big := 0FFFFFFFFFFFFFFFFH; | |
| 46 | + small := -5; | |
| 47 | + Fmt.print("int {}, uint {}, hex {}\n", | |
| 48 | + [Fmt.int(-42), Fmt.uint(big), Fmt.hex(255)]); | |
| 49 | + Fmt.print("str {}, char {}, bool {}\n", | |
| 50 | + [Fmt.str("hi"), Fmt.char('x'), Fmt.bool(1 < 2)]); | |
| 51 | + Fmt.print("real {} and {} and {}\n", | |
| 52 | + [Fmt.real(3.14159, 2), Fmt.real(2.5, 0), Fmt.real(1.0 / 3.0, 9)]); | |
| 53 | + Fmt.print("an I8: {}; braces: {{ and }}\n", [Fmt.int(I64(small))]); | |
| 54 | +end; | |
| 55 | + | |
| 56 | +end Kinds. | |
| 57 | +``` | |
| 58 | + | |
| 59 | +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. | |
| 60 | + | |
| 61 | +## Into a buffer | |
| 62 | + | |
| 63 | +`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. | |
| 64 | + | |
| 65 | +```raz Message run | |
| 66 | +module Message; | |
| 67 | +import Out, Buf, Fmt, Heap; | |
| 68 | + | |
| 69 | +(* "name (age n)", built in a Buf the caller owns *) | |
| 70 | +proc describe(b: ^Buf.Buf; name: []U8; age: INT); | |
| 71 | +begin | |
| 72 | + Fmt.write(b, "{} (age {})", [Fmt.str(name), Fmt.int(age)]); | |
| 73 | +end; | |
| 74 | + | |
| 75 | +proc main*; | |
| 76 | +var b: Buf.Buf; | |
| 77 | +begin | |
| 78 | + Buf.init(ADR(b), Heap.heap); | |
| 79 | + defer Buf.done(ADR(b)); | |
| 80 | + describe(ADR(b), "Ada", 36); | |
| 81 | + Buf.str(ADR(b), "; "); | |
| 82 | + describe(ADR(b), "Grace", 45); | |
| 83 | + Out.str(Buf.bytes(ADR(b))); Out.ln; | |
| 84 | + Out.int(b.len); Out.str(" bytes\n"); | |
| 85 | +end; | |
| 86 | + | |
| 87 | +end Message. | |
| 88 | +``` | |
| 89 | + | |
| 90 | +## Columns | |
| 91 | + | |
| 92 | +`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. | |
| 93 | + | |
| 94 | +```raz Table run | |
| 95 | +module Table; | |
| 96 | +import Out; | |
| 97 | + | |
| 98 | +(* s, then spaces up to width *) | |
| 99 | +proc left(s: []U8; width: INT); | |
| 100 | +var i: INT; | |
| 101 | +begin | |
| 102 | + Out.str(s); | |
| 103 | + for i := LEN(s) to width - 1 do Out.char(' '); end; | |
| 104 | +end; | |
| 105 | + | |
| 106 | +(* n, right aligned in width *) | |
| 107 | +proc right(n: INT; width: INT); | |
| 108 | +var digits: INT; v: INT; i: INT; | |
| 109 | +begin | |
| 110 | + digits := 1; | |
| 111 | + v := n; | |
| 112 | + if v < 0 then INC(digits); v := -v; end; | |
| 113 | + while v >= 10 do INC(digits); v := v div 10; end; | |
| 114 | + for i := digits to width - 1 do Out.char(' '); end; | |
| 115 | + Out.int(n); | |
| 116 | +end; | |
| 117 | + | |
| 118 | +proc row(name: []U8; qty, price: INT); | |
| 119 | +begin | |
| 120 | + left(name, 10); | |
| 121 | + right(qty, 5); | |
| 122 | + right(price, 8); | |
| 123 | + right(qty * price, 9); | |
| 124 | + Out.ln; | |
| 125 | +end; | |
| 126 | + | |
| 127 | +proc main*; | |
| 128 | +begin | |
| 129 | + Out.str("item qty price total\n"); | |
| 130 | + row("bolts", 120, 3); | |
| 131 | + row("washers", 1000, 1); | |
| 132 | + row("gears", 8, 250); | |
| 133 | + row("shims", 12, -4); | |
| 134 | +end; | |
| 135 | + | |
| 136 | +end Table. | |
| 137 | +``` | |
| 138 | + | |
| 139 | +## Writing numbers in other bases | |
| 140 | + | |
| 141 | +`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. | |
| 142 | + | |
| 143 | +```raz Dump run | |
| 144 | +module Dump; | |
| 145 | +import Out; | |
| 146 | + | |
| 147 | +proc dump(data: []U8); | |
| 148 | +var i: INT; | |
| 149 | +begin | |
| 150 | + for i := 0 to LEN(data) - 1 do | |
| 151 | + if i > 0 then Out.char(' '); end; | |
| 152 | + Out.hex(U64(data[i]), 2); | |
| 153 | + end; | |
| 154 | + Out.ln; | |
| 155 | +end; | |
| 156 | + | |
| 157 | +proc main*; | |
| 158 | +begin | |
| 159 | + dump("raz\n"); | |
| 160 | + dump("\u{3BB}"); | |
| 161 | +end; | |
| 162 | + | |
| 163 | +end Dump. | |
| 164 | +``` |
| @@ -0,0 +1,166 @@ | ||
| 1 | +title: Strings and bytes | |
| 2 | +part: The library | |
| 3 | +summary: Copying, hashing and ordering strings, and reading and writing binary formats. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +## Ordering and hashing | |
| 8 | + | |
| 9 | +`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. | |
| 10 | + | |
| 11 | +```raz Order run | |
| 12 | +module Order; | |
| 13 | +import Out, Str, Fmt; | |
| 14 | + | |
| 15 | +proc main*; | |
| 16 | +var names: [4][]U8; i, j: INT; t: []U8; | |
| 17 | +begin | |
| 18 | + names := ["pear", "Apple", "fig", "apple"]; | |
| 19 | + (* a small insertion sort, with Str.cmp *) | |
| 20 | + for i := 1 to 3 do | |
| 21 | + t := names[i]; | |
| 22 | + j := i - 1; | |
| 23 | + while (j >= 0) and (Str.cmp(names[j], t) > 0) do | |
| 24 | + names[j + 1] := names[j]; | |
| 25 | + DEC(j); | |
| 26 | + end; | |
| 27 | + names[j + 1] := t; | |
| 28 | + end; | |
| 29 | + for i := 0 to 3 do Out.str(names[i]); Out.char(' '); end; | |
| 30 | + Out.ln; | |
| 31 | + Fmt.print("{}\n", [Fmt.hex(Str.hash("raz"))]); | |
| 32 | + if Str.hash("raz") = Str.hash("raz") then Out.str("stable\n"); end; | |
| 33 | +end; | |
| 34 | + | |
| 35 | +end Order. | |
| 36 | +``` | |
| 37 | + | |
| 38 | +Upper case sorts before lower, since 'A' is 65 and 'a' is 97: `Str.cmp` doesn't pretend to know a language's alphabet. | |
| 39 | + | |
| 40 | +## Keeping a string | |
| 41 | + | |
| 42 | +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. | |
| 43 | + | |
| 44 | +```raz Keep run | |
| 45 | +module Keep; | |
| 46 | +import Out, Str, Heap, Mem; | |
| 47 | + | |
| 48 | +type Entry = record name: []U8; n: INT; end; | |
| 49 | + | |
| 50 | +var entries: [3]Entry; | |
| 51 | + | |
| 52 | +(* remembers a name that the caller will overwrite *) | |
| 53 | +proc remember(slot: INT; name: []U8); | |
| 54 | +var copy: []U8; ok: BOOL; | |
| 55 | +begin | |
| 56 | + copy, ok := Str.copy(Heap.heap, name); | |
| 57 | + if ok then entries[slot].name := copy; entries[slot].n := slot; end; | |
| 58 | +end; | |
| 59 | + | |
| 60 | +proc main*; | |
| 61 | +var scratch: [16]U8; i: INT; | |
| 62 | +begin | |
| 63 | + for i := 0 to 2 do | |
| 64 | + scratch := "name-"; | |
| 65 | + scratch[5] := U8('0' + i); | |
| 66 | + remember(i, scratch[0..6]); | |
| 67 | + scratch := "overwritten!"; | |
| 68 | + end; | |
| 69 | + for i := 0 to 2 do | |
| 70 | + Out.str(entries[i].name); Out.char(' '); | |
| 71 | + Mem.free(Heap.heap, ^U8(ADR(entries[i].name[0]))); | |
| 72 | + end; | |
| 73 | + Out.ln; | |
| 74 | +end; | |
| 75 | + | |
| 76 | +end Keep. | |
| 77 | +``` | |
| 78 | + | |
| 79 | +## Binary formats | |
| 80 | + | |
| 81 | +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. | |
| 82 | + | |
| 83 | +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. | |
| 84 | + | |
| 85 | +```raz Frame run | |
| 86 | +module Frame; | |
| 87 | +import Out, Fmt, Str; | |
| 88 | + | |
| 89 | +const HeaderSize = 10; | |
| 90 | + | |
| 91 | +(* the sum of the bytes of data, all mod 2^32 *) | |
| 92 | +proc checksum(data: []U8): U32; | |
| 93 | +var i: INT; sum: U32; | |
| 94 | +begin | |
| 95 | + for i := 0 to LEN(data) - 1 do sum := sum + U32(data[i]); end; | |
| 96 | + return sum; | |
| 97 | +end; | |
| 98 | + | |
| 99 | +(* writes a frame to out, which must have room; its length *) | |
| 100 | +proc pack(out: []U8; tag, data: []U8): INT; | |
| 101 | +begin | |
| 102 | + COPY(out[0..4], tag); | |
| 103 | + Str.putBE(out[4..6], U64(LEN(data))); | |
| 104 | + Str.putLE(out[6..10], U64(checksum(data))); | |
| 105 | + COPY(out[HeaderSize..HeaderSize + LEN(data)], data); | |
| 106 | + return HeaderSize + LEN(data); | |
| 107 | +end; | |
| 108 | + | |
| 109 | +proc main*; | |
| 110 | +var buf: [64]U8; n, len: INT; sum: U32; i: INT; | |
| 111 | +begin | |
| 112 | + n := pack(buf, "DATA", "hello"); | |
| 113 | + for i := 0 to n - 1 do | |
| 114 | + Out.hex(U64(buf[i]), 2); Out.char(' '); | |
| 115 | + end; | |
| 116 | + Out.ln; | |
| 117 | + (* and back *) | |
| 118 | + len := INT(Str.be(buf[4..6])); | |
| 119 | + sum := U32(Str.le(buf[6..10])); | |
| 120 | + Fmt.print("tag {}, {} bytes, checksum {}, ", [Fmt.str(buf[0..4]), Fmt.int(len), Fmt.hex(U64(sum))]); | |
| 121 | + if sum = checksum(buf[HeaderSize..HeaderSize + len]) then | |
| 122 | + Out.str("valid: "); Out.str(buf[HeaderSize..HeaderSize + len]); | |
| 123 | + else | |
| 124 | + Out.str("corrupt"); | |
| 125 | + end; | |
| 126 | + Out.ln; | |
| 127 | +end; | |
| 128 | + | |
| 129 | +end Frame. | |
| 130 | +``` | |
| 131 | + | |
| 132 | +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. | |
| 133 | + | |
| 134 | +## Numbers and text | |
| 135 | + | |
| 136 | +`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. | |
| 137 | + | |
| 138 | +```raz Numbers run | |
| 139 | +module Numbers; | |
| 140 | +import Out, Str; | |
| 141 | + | |
| 142 | +(* the sum of the numbers in a comma separated list, or -1 if any isn't *) | |
| 143 | +proc total(s: []U8): I64; | |
| 144 | +var start, i: INT; sum, n: I64; ok: BOOL; | |
| 145 | +begin | |
| 146 | + start := 0; | |
| 147 | + for i := 0 to LEN(s) do | |
| 148 | + if (i = LEN(s)) or (s[i] = ',') then | |
| 149 | + n, ok := Str.toInt(s[start..i]); | |
| 150 | + if not ok then return -1; end; | |
| 151 | + sum := sum + n; | |
| 152 | + start := i + 1; | |
| 153 | + end; | |
| 154 | + end; | |
| 155 | + return sum; | |
| 156 | +end; | |
| 157 | + | |
| 158 | +proc main*; | |
| 159 | +begin | |
| 160 | + Out.int(total("10,20,-5,+7")); Out.ln; | |
| 161 | + Out.int(total("10,x,20")); Out.ln; | |
| 162 | + Out.int(total("10,,20")); Out.ln; | |
| 163 | +end; | |
| 164 | + | |
| 165 | +end Numbers. | |
| 166 | +``` |
| @@ -0,0 +1,129 @@ | ||
| 1 | +title: Lists, maps and sorting | |
| 2 | +part: The library | |
| 3 | +summary: List(T), Map(K, V) and Sort(T), put together in a word-frequency program. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +## `List(T)` | |
| 8 | + | |
| 9 | +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. | |
| 10 | + | |
| 11 | +```raz Pile run | |
| 12 | +module Pile; | |
| 13 | +import Out, Heap, Ints := List(INT); | |
| 14 | + | |
| 15 | +proc main*; | |
| 16 | +var l: Ints.List; n: ^Ints.Node; v: INT; | |
| 17 | +begin | |
| 18 | + Ints.init(ADR(l), Heap.heap); | |
| 19 | + defer Ints.clear(ADR(l)); | |
| 20 | + for v := 1 to 5 do _ := Ints.push(ADR(l), v * v); end; | |
| 21 | + Ints.reverse(ADR(l)); (* oldest first *) | |
| 22 | + n := l.head; | |
| 23 | + while n # nil do Out.int(n^.val); Out.char(' '); n := n^.next; end; | |
| 24 | + Out.ln; | |
| 25 | + v, _ := Ints.pop(ADR(l)); | |
| 26 | + Out.int(v); Out.str(" popped, "); Out.int(l.len); Out.str(" left\n"); | |
| 27 | +end; | |
| 28 | + | |
| 29 | +end Pile. | |
| 30 | +``` | |
| 31 | + | |
| 32 | +## `Map(K, V; hash, eq)` | |
| 33 | + | |
| 34 | +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. | |
| 35 | + | |
| 36 | +```raz Ages run | |
| 37 | +module Ages; | |
| 38 | +import Out, Fmt, Str, Heap, Book := Map([]U8, INT, Str.hash, Str.eq); | |
| 39 | + | |
| 40 | +proc main*; | |
| 41 | +var m: Book.Map; age: INT; found, ok: BOOL; i: INT; v: INT; | |
| 42 | +begin | |
| 43 | + Book.init(ADR(m), Heap.heap); | |
| 44 | + _ := Book.put(ADR(m), "ada", 36); | |
| 45 | + _ := Book.put(ADR(m), "grace", 45); | |
| 46 | + _ := Book.put(ADR(m), "alan", 41); | |
| 47 | + _ := Book.put(ADR(m), "ada", 37); (* replaces *) | |
| 48 | + age, found := Book.get(ADR(m), "ada"); | |
| 49 | + Fmt.print("ada: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]); | |
| 50 | + age, found := Book.get(ADR(m), "linus"); | |
| 51 | + Fmt.print("linus: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]); | |
| 52 | + ok := Book.remove(ADR(m), "alan"); | |
| 53 | + Fmt.print("{} entries, removed {}\n", [Fmt.int(m.len), Fmt.bool(ok)]); | |
| 54 | + v := 0; | |
| 55 | + i, _, age := Book.next(ADR(m), 0); | |
| 56 | + while i >= 0 do | |
| 57 | + INC(v, age); | |
| 58 | + i, _, age := Book.next(ADR(m), i); | |
| 59 | + end; | |
| 60 | + Out.int(v); Out.str(" years in all\n"); | |
| 61 | +end; | |
| 62 | + | |
| 63 | +end Ages. | |
| 64 | +``` | |
| 65 | + | |
| 66 | +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. | |
| 67 | + | |
| 68 | +## `Sort(T; less)` | |
| 69 | + | |
| 70 | +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. | |
| 71 | + | |
| 72 | +## Putting them together | |
| 73 | + | |
| 74 | +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`. | |
| 75 | + | |
| 76 | +```raz Freq run | |
| 77 | +module Freq; | |
| 78 | +import Fmt, Str, Heap, | |
| 79 | + Count := Map([]U8, INT, Str.hash, Str.eq), | |
| 80 | + Rank := Sort(Entry, before); | |
| 81 | + | |
| 82 | +type Entry = record word: []U8; n: INT; end; | |
| 83 | + | |
| 84 | +const Text = "the cat and the hat and the bat sat on the mat and the cat sat"; | |
| 85 | + | |
| 86 | +(* more first; equal counts alphabetically *) | |
| 87 | +proc before(a, b: Entry): BOOL; | |
| 88 | +begin | |
| 89 | + if a.n # b.n then return a.n > b.n; end; | |
| 90 | + return Str.cmp(a.word, b.word) < 0; | |
| 91 | +end; | |
| 92 | + | |
| 93 | +proc main*; | |
| 94 | +var | |
| 95 | + m: Count.Map; entries: [32]Entry; i, start, k, n, found: INT; | |
| 96 | + w: []U8; key: []U8; v: INT; | |
| 97 | +begin | |
| 98 | + Count.init(ADR(m), Heap.heap); | |
| 99 | + start := 0; | |
| 100 | + for i := 0 to LEN(Text) do | |
| 101 | + if (i = LEN(Text)) or (Text[i] = ' ') then | |
| 102 | + w := Text[start..i]; | |
| 103 | + k, _ := Count.get(ADR(m), w); | |
| 104 | + _ := Count.put(ADR(m), w, k + 1); | |
| 105 | + start := i + 1; | |
| 106 | + end; | |
| 107 | + end; | |
| 108 | + n := 0; | |
| 109 | + found, key, v := Count.next(ADR(m), 0); | |
| 110 | + while found >= 0 do | |
| 111 | + entries[n].word := key; | |
| 112 | + entries[n].n := v; | |
| 113 | + INC(n); | |
| 114 | + found, key, v := Count.next(ADR(m), found); | |
| 115 | + end; | |
| 116 | + Rank.sort(entries[0..n]); | |
| 117 | + for i := 0 to n - 1 do | |
| 118 | + Fmt.print("{} {}\n", [Fmt.int(entries[i].n), Fmt.str(entries[i].word)]); | |
| 119 | + end; | |
| 120 | +end; | |
| 121 | + | |
| 122 | +end Freq. | |
| 123 | +``` | |
| 124 | + | |
| 125 | +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`. | |
| 126 | + | |
| 127 | +## Choosing | |
| 128 | + | |
| 129 | +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. |
| @@ -0,0 +1,187 @@ | ||
| 1 | +title: Files and the command line | |
| 2 | +part: The library | |
| 3 | +summary: Whole files with Files, descriptors and directories with Sys, and options with Opt. | |
| 4 | +--- | |
| 5 | +`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. | |
| 6 | + | |
| 7 | +## A whole file | |
| 8 | + | |
| 9 | +`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. | |
| 10 | + | |
| 11 | +```raz Notes run | |
| 12 | +module Notes; | |
| 13 | +import Out, Files, Buf, Heap; | |
| 14 | + | |
| 15 | +proc main*; | |
| 16 | +var b: Buf.Buf; ok: BOOL; | |
| 17 | +begin | |
| 18 | + ok := Files.write("notes.txt", "first line\nsecond line\n"); | |
| 19 | + if not ok then Out.str("can't write\n"); return; end; | |
| 20 | + Buf.init(ADR(b), Heap.heap); | |
| 21 | + defer Buf.done(ADR(b)); | |
| 22 | + ok := Files.read("notes.txt", ADR(b)); | |
| 23 | + if ok then | |
| 24 | + Out.int(b.len); Out.str(" bytes: "); Out.str(Buf.bytes(ADR(b))); | |
| 25 | + end; | |
| 26 | + ok := Files.read("missing.txt", ADR(b)); | |
| 27 | + if not ok then Out.str("missing.txt: not there\n"); end; | |
| 28 | +end; | |
| 29 | + | |
| 30 | +end Notes. | |
| 31 | +``` | |
| 32 | + | |
| 33 | +## Descriptors | |
| 34 | + | |
| 35 | +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. | |
| 36 | + | |
| 37 | +```raz Count run | |
| 38 | +module Count; | |
| 39 | +import Out, Sys; | |
| 40 | + | |
| 41 | +(* the lines of the file at path, or minus an errno *) | |
| 42 | +proc lines(path: []U8): INT; | |
| 43 | +var fd, n, i, count: INT; buf: [4096]U8; | |
| 44 | +begin | |
| 45 | + fd := Sys.openRead(path); | |
| 46 | + if fd < 0 then return fd; end; | |
| 47 | + defer Sys.close(fd); | |
| 48 | + n := Sys.read(fd, buf); | |
| 49 | + while n > 0 do | |
| 50 | + for i := 0 to n - 1 do | |
| 51 | + if buf[i] = '\n' then INC(count); end; | |
| 52 | + end; | |
| 53 | + n := Sys.read(fd, buf); | |
| 54 | + end; | |
| 55 | + if n < 0 then return n; end; | |
| 56 | + return count; | |
| 57 | +end; | |
| 58 | + | |
| 59 | +proc main*; | |
| 60 | +var fd: INT; pos: I64; | |
| 61 | +begin | |
| 62 | + fd := Sys.create("log.txt"); | |
| 63 | + _ := Sys.write(fd, "a\nb\nc\n"); | |
| 64 | + pos := Sys.seek(fd, 2, false); (* from the start *) | |
| 65 | + Out.int(pos); Out.ln; | |
| 66 | + Sys.close(fd); | |
| 67 | + Out.int(lines("log.txt")); Out.str(" lines\n"); | |
| 68 | + Out.int(lines("/no/such/file")); Out.ln; (* -2: ENOENT *) | |
| 69 | + fd := Sys.open("log.txt", {Sys.writing, Sys.appending}); | |
| 70 | + _ := Sys.write(fd, "d\n"); | |
| 71 | + Sys.close(fd); | |
| 72 | + Out.int(lines("log.txt")); Out.str(" lines now\n"); | |
| 73 | +end; | |
| 74 | + | |
| 75 | +end Count. | |
| 76 | +``` | |
| 77 | + | |
| 78 | +## Looking at a file, and a directory | |
| 79 | + | |
| 80 | +`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. | |
| 81 | + | |
| 82 | +```raz Tree run | |
| 83 | +module Tree; | |
| 84 | +import Out, Sys, Str, Heap, Mem, Buf, Order := Sort([]U8, before); | |
| 85 | + | |
| 86 | +proc before(a, b: []U8): BOOL; | |
| 87 | +begin | |
| 88 | + return Str.cmp(a, b) < 0; | |
| 89 | +end; | |
| 90 | + | |
| 91 | +(* a file made to hold text *) | |
| 92 | +proc put(path, text: []U8); | |
| 93 | +var fd: INT; | |
| 94 | +begin | |
| 95 | + fd := Sys.create(path); | |
| 96 | + _ := Sys.write(fd, text); | |
| 97 | + Sys.close(fd); | |
| 98 | +end; | |
| 99 | + | |
| 100 | +proc main*; | |
| 101 | +var | |
| 102 | + d: Sys.Dir; name, copy: []U8; more, ok: BOOL; i, n: INT; | |
| 103 | + info: Sys.Info; err: INT; names: [16][]U8; path: Buf.Buf; | |
| 104 | +begin | |
| 105 | + _ := Sys.makeDir("proj"); | |
| 106 | + _ := Sys.makeDir("proj/src"); | |
| 107 | + put("proj/b.txt", "bb"); | |
| 108 | + put("proj/a.txt", "a"); | |
| 109 | + if Sys.openDir(ADR(d), "proj") < 0 then return; end; | |
| 110 | + n := 0; | |
| 111 | + name, more := Sys.nextEntry(ADR(d)); | |
| 112 | + while more do | |
| 113 | + copy, ok := Str.copy(Heap.heap, name); | |
| 114 | + if ok and (n < 16) then names[n] := copy; INC(n); end; | |
| 115 | + name, more := Sys.nextEntry(ADR(d)); | |
| 116 | + end; | |
| 117 | + Sys.closeDir(ADR(d)); | |
| 118 | + Order.sort(names[0..n]); | |
| 119 | + Buf.init(ADR(path), Heap.heap); | |
| 120 | + for i := 0 to n - 1 do | |
| 121 | + Buf.reset(ADR(path)); | |
| 122 | + Buf.str(ADR(path), "proj/"); | |
| 123 | + Buf.str(ADR(path), names[i]); | |
| 124 | + info, err := Sys.info(Buf.bytes(ADR(path))); | |
| 125 | + Out.str(names[i]); | |
| 126 | + if err < 0 then Out.str(" ?"); | |
| 127 | + elsif info.dir then Out.str("/"); | |
| 128 | + else Out.str(", "); Out.int(info.size); Out.str(" bytes"); | |
| 129 | + end; | |
| 130 | + Out.ln; | |
| 131 | + Mem.free(Heap.heap, ^U8(ADR(names[i][0]))); | |
| 132 | + end; | |
| 133 | + Buf.done(ADR(path)); | |
| 134 | +end; | |
| 135 | + | |
| 136 | +end Tree. | |
| 137 | +``` | |
| 138 | + | |
| 139 | +## A command line, from a table | |
| 140 | + | |
| 141 | +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. | |
| 142 | + | |
| 143 | +```raz Tool | |
| 144 | +module Tool; | |
| 145 | +import Out, Fmt, Opt; | |
| 146 | + | |
| 147 | +const count = 1; (* the key of --count, which has no letter *) | |
| 148 | + | |
| 149 | +proc main*; | |
| 150 | +var p: Opt.Parser; verbose: BOOL; n, i: INT; w: []U8; ok: BOOL; | |
| 151 | +begin | |
| 152 | + n := 1; | |
| 153 | + Opt.init(ADR(p), "tool", [ | |
| 154 | + Opt.usage("", "tool [-v] [--count n] word ..."), | |
| 155 | + Opt.option("", 'v', "verbose", "", "say more"), | |
| 156 | + Opt.option("", count, "count", "n", "repeat each word n times")]); | |
| 157 | + while Opt.next(ADR(p)) do | |
| 158 | + if p.letter = 'v' then verbose := true; | |
| 159 | + elsif p.letter = count then n := INT(Opt.number(ADR(p), 1, 5)); | |
| 160 | + end; | |
| 161 | + end; | |
| 162 | + w, ok := Opt.operand(ADR(p)); | |
| 163 | + if not ok then Opt.fail(ADR(p), "no words; see tool -h"); end; | |
| 164 | + while ok do | |
| 165 | + for i := 1 to n do | |
| 166 | + if verbose then Out.str("word: "); end; | |
| 167 | + Fmt.print("{}\n", [Fmt.str(w)]); | |
| 168 | + end; | |
| 169 | + w, ok := Opt.operand(ADR(p)); | |
| 170 | + end; | |
| 171 | +end; | |
| 172 | + | |
| 173 | +end Tool. | |
| 174 | +``` | |
| 175 | + | |
| 176 | +```sh | |
| 177 | +$ raz Tool.raz | |
| 178 | +$ ./Tool -h | |
| 179 | +$ ./Tool -v hello world | |
| 180 | +$ ./Tool --count 9 hello; echo "status $?" | |
| 181 | +$ ./Tool -x; echo "status $?" | |
| 182 | +$ ./Tool; echo "status $?" | |
| 183 | +``` | |
| 184 | + | |
| 185 | +`-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. | |
| 186 | + | |
| 187 | +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. |
| @@ -0,0 +1,156 @@ | ||
| 1 | +title: Time, randomness and other programs | |
| 2 | +part: The library | |
| 3 | +summary: Clocks, sleeping, random bytes, and running a program with its output piped back. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +## Clocks and sleeping | |
| 8 | + | |
| 9 | +`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. | |
| 10 | + | |
| 11 | +```raz Timing run | |
| 12 | +module Timing; | |
| 13 | +import Out, Sys; | |
| 14 | + | |
| 15 | +proc main*; | |
| 16 | +var t0, t1, elapsed: I64; wall: I64; | |
| 17 | +begin | |
| 18 | + t0 := Sys.clock(); | |
| 19 | + Sys.sleep(25); | |
| 20 | + t1 := Sys.clock(); | |
| 21 | + elapsed := (t1 - t0) div 1000000; (* milliseconds *) | |
| 22 | + if (elapsed >= 25) and (elapsed < 1000) then | |
| 23 | + Out.str("slept about 25 ms\n"); | |
| 24 | + end; | |
| 25 | + wall := Sys.now(); | |
| 26 | + if wall > 1700000000000000000 then Out.str("after 2023\n"); end; | |
| 27 | +end; | |
| 28 | + | |
| 29 | +end Timing. | |
| 30 | +``` | |
| 31 | + | |
| 32 | +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`. | |
| 33 | + | |
| 34 | +## Random bytes | |
| 35 | + | |
| 36 | +`Sys.random` fills a slice with random bytes from the system. Anything else is made from that: a number in a range, a shuffle. | |
| 37 | + | |
| 38 | +```raz Dice run | |
| 39 | +module Dice; | |
| 40 | +import Out, Sys, Str; | |
| 41 | + | |
| 42 | +(* a number from 0 up to n, without bias *) | |
| 43 | +proc below(n: INT): INT; | |
| 44 | +var b: [8]U8; x, limit: U64; | |
| 45 | +begin | |
| 46 | + limit := 0FFFFFFFFFFFFFFFFH - (0FFFFFFFFFFFFFFFFH mod U64(n)) - 1; | |
| 47 | + Sys.random(b); | |
| 48 | + x := Str.le(b); | |
| 49 | + while x > limit do | |
| 50 | + Sys.random(b); | |
| 51 | + x := Str.le(b); | |
| 52 | + end; | |
| 53 | + return INT(x mod U64(n)); | |
| 54 | +end; | |
| 55 | + | |
| 56 | +proc main*; | |
| 57 | +var counts: [6]INT; i: INT; ok: BOOL; | |
| 58 | +begin | |
| 59 | + for i := 1 to 6000 do INC(counts[below(6)]); end; | |
| 60 | + ok := true; | |
| 61 | + for i := 0 to 5 do | |
| 62 | + if (counts[i] < 800) or (counts[i] > 1200) then ok := false; end; | |
| 63 | + end; | |
| 64 | + if ok then Out.str("all six faces came up about a thousand times\n"); end; | |
| 65 | +end; | |
| 66 | + | |
| 67 | +end Dice. | |
| 68 | +``` | |
| 69 | + | |
| 70 | +## Running a program | |
| 71 | + | |
| 72 | +`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`. | |
| 73 | + | |
| 74 | +```raz Run run | |
| 75 | +module Run; | |
| 76 | +import Out, Sys; | |
| 77 | + | |
| 78 | +proc main*; | |
| 79 | +var p: Sys.Program; pid, status: INT; how: Sys.Status; | |
| 80 | +begin | |
| 81 | + p := {path: "/bin/echo", args: ["echo", "hello from a child"]}; | |
| 82 | + pid := Sys.spawn(p); | |
| 83 | + if pid < 0 then Out.str("can't start\n"); return; end; | |
| 84 | + Out.flush; (* so that our text isn't behind the child's *) | |
| 85 | + _, how, status := Sys.wait(pid, true); | |
| 86 | + if how = Sys.exited then | |
| 87 | + Out.str("it exited with "); Out.int(status); Out.ln; | |
| 88 | + end; | |
| 89 | +end; | |
| 90 | + | |
| 91 | +end Run. | |
| 92 | +``` | |
| 93 | + | |
| 94 | +## Capturing its output | |
| 95 | + | |
| 96 | +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. | |
| 97 | + | |
| 98 | +```raz Capture run | |
| 99 | +module Capture; | |
| 100 | +import Out, Sys, Buf, Heap; | |
| 101 | + | |
| 102 | +proc main*; | |
| 103 | +var | |
| 104 | + p: Sys.Program; pid, rd, wr, n, status: INT; how: Sys.Status; | |
| 105 | + chunk: [256]U8; b: Buf.Buf; | |
| 106 | +begin | |
| 107 | + rd, wr := Sys.pipe(); | |
| 108 | + p := {path: "/bin/sh", args: ["sh", "-c", "echo one; echo two; exit 7"]}; | |
| 109 | + p.fds[1] := wr; | |
| 110 | + pid := Sys.spawn(p); | |
| 111 | + Sys.close(wr); (* only the child writes now *) | |
| 112 | + Buf.init(ADR(b), Heap.heap); | |
| 113 | + defer Buf.done(ADR(b)); | |
| 114 | + n := Sys.read(rd, chunk); | |
| 115 | + while n > 0 do | |
| 116 | + Buf.str(ADR(b), chunk[0..n]); | |
| 117 | + n := Sys.read(rd, chunk); | |
| 118 | + end; | |
| 119 | + Sys.close(rd); | |
| 120 | + _, how, status := Sys.wait(pid, true); | |
| 121 | + Out.str("captured: "); Out.str(Buf.bytes(ADR(b))); | |
| 122 | + Out.str("status "); Out.int(status); Out.ln; | |
| 123 | + if how = Sys.exited then Out.str("(a normal exit)\n"); end; | |
| 124 | +end; | |
| 125 | + | |
| 126 | +end Capture. | |
| 127 | +``` | |
| 128 | + | |
| 129 | +Closing the write end in the parent matters: the read ends only when every holder of the write end has closed it. | |
| 130 | + | |
| 131 | +## Environment and working directory | |
| 132 | + | |
| 133 | +`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. | |
| 134 | + | |
| 135 | +```raz Where run | |
| 136 | +module Where; | |
| 137 | +import Out, Sys; | |
| 138 | + | |
| 139 | +proc main*; | |
| 140 | +var p: Sys.Program; pid, rd, wr, n: INT; chunk: [64]U8; | |
| 141 | +begin | |
| 142 | + if Sys.env("RAZ_SURELY_UNSET") = "" then Out.str("unset reads as empty\n"); end; | |
| 143 | + rd, wr := Sys.pipe(); | |
| 144 | + p := {path: "/bin/sh", args: ["sh", "-c", "echo $GREETING from $(pwd)"], | |
| 145 | + env: ["GREETING=hello"], dir: "/tmp"}; | |
| 146 | + p.fds[1] := wr; | |
| 147 | + pid := Sys.spawn(p); | |
| 148 | + Sys.close(wr); | |
| 149 | + n := Sys.read(rd, chunk); | |
| 150 | + Out.str(chunk[0..n]); | |
| 151 | + Sys.close(rd); | |
| 152 | + _, _, _ := Sys.wait(pid, true); | |
| 153 | +end; | |
| 154 | + | |
| 155 | +end Where. | |
| 156 | +``` |
| @@ -0,0 +1,175 @@ | ||
| 1 | +title: Writing an allocator | |
| 2 | +part: The library | |
| 3 | +summary: Mem.Allocator is two procedures; make one over a fixed array, and one that counts. | |
| 4 | +--- | |
| 5 | +An allocator is a record of two procedures, and that is all `Mem.Allocator` is: | |
| 6 | + | |
| 7 | +```text | |
| 8 | +type Allocator* = record | |
| 9 | + alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *) | |
| 10 | + free*: proc(a: ^Allocator; p: ^U8); | |
| 11 | +end; | |
| 12 | +``` | |
| 13 | + | |
| 14 | +`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. | |
| 15 | + | |
| 16 | +## An allocator over a fixed array | |
| 17 | + | |
| 18 | +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. | |
| 19 | + | |
| 20 | +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. | |
| 21 | + | |
| 22 | +```raz Bump | |
| 23 | +module Bump; | |
| 24 | +import Mem; | |
| 25 | + | |
| 26 | +type | |
| 27 | + Bump* = record | |
| 28 | + base*: Mem.Allocator; (* first, so that ^Bump(a) finds the rest *) | |
| 29 | + mem: ^U8; | |
| 30 | + size, used*: INT; | |
| 31 | + end; | |
| 32 | + | |
| 33 | +proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8; | |
| 34 | +var b: ^Bump; at: INT; | |
| 35 | +begin | |
| 36 | + b := ^Bump(a); | |
| 37 | + at := (b^.used + align - 1) div align * align; (* round up to align *) | |
| 38 | + if (size < 0) or (at + size > b^.size) then return nil; end; | |
| 39 | + b^.used := at + size; | |
| 40 | + return b^.mem + at; | |
| 41 | +end; | |
| 42 | + | |
| 43 | +proc free(_a: ^Mem.Allocator; _p: ^U8); | |
| 44 | +begin | |
| 45 | +end; | |
| 46 | + | |
| 47 | +(* a bump allocator over the size bytes at mem *) | |
| 48 | +proc init*(b: ^Bump; mem: ^U8; size: INT); | |
| 49 | +begin | |
| 50 | + b^.base := {alloc: alloc, free: free}; | |
| 51 | + b^.mem := mem; | |
| 52 | + b^.size := size; | |
| 53 | + b^.used := 0; | |
| 54 | +end; | |
| 55 | + | |
| 56 | +(* everything forgotten, the memory used again *) | |
| 57 | +proc reset*(b: ^Bump); | |
| 58 | +begin | |
| 59 | + b^.used := 0; | |
| 60 | +end; | |
| 61 | + | |
| 62 | +end Bump. | |
| 63 | +``` | |
| 64 | + | |
| 65 | +```raz Bumping run | |
| 66 | +module Bumping; | |
| 67 | +import Out, Bump; | |
| 68 | + | |
| 69 | +type Point = record x, y: INT; end; | |
| 70 | + | |
| 71 | +var arena: [256]U8; (* the allocator's whole world *) | |
| 72 | + | |
| 73 | +proc main*; | |
| 74 | +var b: Bump.Bump; p, q: ^Point; many: INT; r: ^Point; | |
| 75 | +begin | |
| 76 | + Bump.init(ADR(b), ADR(arena[0]), 256); | |
| 77 | + NEW(p, ADR(b.base)); | |
| 78 | + NEW(q, ADR(b.base)); | |
| 79 | + p^.x := 1; q^.y := 2; | |
| 80 | + Out.int(b.used); Out.str(" bytes used by two points\n"); | |
| 81 | + many := 2; | |
| 82 | + repeat | |
| 83 | + NEW(r, ADR(b.base)); | |
| 84 | + if r # nil then INC(many); end; | |
| 85 | + until r = nil; | |
| 86 | + Out.int(many); Out.str(" points fit in 256 bytes\n"); | |
| 87 | + Bump.reset(ADR(b)); | |
| 88 | + NEW(r, ADR(b.base)); | |
| 89 | + if r # nil then Out.str("room again after a reset\n"); end; | |
| 90 | +end; | |
| 91 | + | |
| 92 | +end Bumping. | |
| 93 | +``` | |
| 94 | + | |
| 95 | +An allocator that runs out says so with `nil`, and the caller decides what that means. Nothing else in the program is touched. | |
| 96 | + | |
| 97 | +## An allocator that counts | |
| 98 | + | |
| 99 | +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. | |
| 100 | + | |
| 101 | +```raz Counted | |
| 102 | +module Counted; | |
| 103 | +import Mem; | |
| 104 | + | |
| 105 | +type | |
| 106 | + Counted* = record | |
| 107 | + base*: Mem.Allocator; (* first *) | |
| 108 | + inner: ^Mem.Allocator; | |
| 109 | + allocs*, frees*, bytes*: INT; | |
| 110 | + end; | |
| 111 | + | |
| 112 | +proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8; | |
| 113 | +var c: ^Counted; p: ^U8; | |
| 114 | +begin | |
| 115 | + c := ^Counted(a); | |
| 116 | + p := Mem.alloc(c^.inner, size, align); | |
| 117 | + if p # nil then INC(c^.allocs); INC(c^.bytes, size); end; | |
| 118 | + return p; | |
| 119 | +end; | |
| 120 | + | |
| 121 | +proc free(a: ^Mem.Allocator; p: ^U8); | |
| 122 | +var c: ^Counted; | |
| 123 | +begin | |
| 124 | + c := ^Counted(a); | |
| 125 | + INC(c^.frees); | |
| 126 | + Mem.free(c^.inner, p); | |
| 127 | +end; | |
| 128 | + | |
| 129 | +(* a counting allocator in front of inner *) | |
| 130 | +proc init*(c: ^Counted; inner: ^Mem.Allocator); | |
| 131 | +begin | |
| 132 | + c^.base := {alloc: alloc, free: free}; | |
| 133 | + c^.inner := inner; | |
| 134 | + c^.allocs := 0; | |
| 135 | + c^.frees := 0; | |
| 136 | + c^.bytes := 0; | |
| 137 | +end; | |
| 138 | + | |
| 139 | +end Counted. | |
| 140 | +``` | |
| 141 | + | |
| 142 | +```raz Audit run | |
| 143 | +module Audit; | |
| 144 | +import Fmt, Heap, Mem, Buf, Counted, Names := List([]U8); | |
| 145 | + | |
| 146 | +proc main*; | |
| 147 | +var c: Counted.Counted; b: Buf.Buf; l: Names.List; i: INT; p: ^U8; | |
| 148 | +begin | |
| 149 | + Counted.init(ADR(c), Heap.heap); | |
| 150 | + Buf.init(ADR(b), ADR(c.base)); | |
| 151 | + for i := 1 to 200 do Buf.str(ADR(b), "0123456789"); end; | |
| 152 | + Fmt.print("a buffer of {} bytes took {} allocations\n", | |
| 153 | + [Fmt.int(b.len), Fmt.int(c.allocs)]); | |
| 154 | + Buf.done(ADR(b)); | |
| 155 | + | |
| 156 | + Names.init(ADR(l), ADR(c.base)); | |
| 157 | + for i := 1 to 10 do _ := Names.push(ADR(l), "x"); end; | |
| 158 | + Fmt.print("{} allocations in all, {} frees so far\n", [Fmt.int(c.allocs), Fmt.int(c.frees)]); | |
| 159 | + Names.clear(ADR(l)); | |
| 160 | + Fmt.print("{} frees after clear\n", [Fmt.int(c.frees)]); | |
| 161 | + | |
| 162 | + p := Mem.alloc(ADR(c.base), 64, 8); | |
| 163 | + Mem.free(ADR(c.base), p); | |
| 164 | +end; | |
| 165 | + | |
| 166 | +end Audit. | |
| 167 | +``` | |
| 168 | + | |
| 169 | +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. | |
| 170 | + | |
| 171 | +## What to take from this | |
| 172 | + | |
| 173 | +- 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. | |
| 174 | +- A library function that needs memory takes the allocator as a parameter, so its caller owns the policy. | |
| 175 | +- 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. |
| @@ -0,0 +1,127 @@ | ||
| 1 | +title: A program with no run time | |
| 2 | +part: Standing alone | |
| 3 | +summary: What is in an executable, what isn't, and how to see it. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +## The smallest program | |
| 8 | + | |
| 9 | +This program imports nothing. It makes the `write` system call itself, with the built-in `SYSCALL`, and returns. | |
| 10 | + | |
| 11 | +```raz Bare | |
| 12 | +module Bare; | |
| 13 | + | |
| 14 | +const Msg = "hello from raw system calls\n"; | |
| 15 | + | |
| 16 | +proc main*; | |
| 17 | +begin | |
| 18 | + _ := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg)); | |
| 19 | +end; | |
| 20 | + | |
| 21 | +end Bare. | |
| 22 | +``` | |
| 23 | + | |
| 24 | +```sh | |
| 25 | +$ raz Bare.raz | |
| 26 | +$ ./Bare | |
| 27 | +$ file Bare | |
| 28 | +$ ldd Bare | |
| 29 | +$ ls -l Bare | awk '{print $5, "bytes"}' | |
| 30 | +``` | |
| 31 | + | |
| 32 | +It is statically linked: no interpreter, no shared libraries, no `libc`. `ldd` says so. | |
| 33 | + | |
| 34 | +## What it does when it runs | |
| 35 | + | |
| 36 | +`strace` lists every system call a program makes. This is the whole of it: | |
| 37 | + | |
| 38 | +```sh | |
| 39 | +$ strace ./Bare 2>&1 >/dev/null | sed -e 's/0x[0-9a-f]\{5,\}/ADDR/g' -e 's/[0-9]* vars/N vars/' | |
| 40 | +``` | |
| 41 | + | |
| 42 | +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. | |
| 43 | + | |
| 44 | +## Programs that use C | |
| 45 | + | |
| 46 | +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`: | |
| 47 | + | |
| 48 | +```raz Cprint | |
| 49 | +module Cprint; | |
| 50 | + | |
| 51 | +extern proc puts(s: ^U8): I32; | |
| 52 | + | |
| 53 | +proc main*; | |
| 54 | +begin | |
| 55 | + _ := puts("hello from C"); | |
| 56 | +end; | |
| 57 | + | |
| 58 | +end Cprint. | |
| 59 | +``` | |
| 60 | + | |
| 61 | +```sh | |
| 62 | +$ raz Cprint.raz | |
| 63 | +$ ./Cprint | |
| 64 | +$ file Cprint | |
| 65 | +$ ldd Cprint | sed 's/ (0x[0-9a-f]*)//' | |
| 66 | +``` | |
| 67 | + | |
| 68 | +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. | |
| 69 | + | |
| 70 | +## Only what is reached | |
| 71 | + | |
| 72 | +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. | |
| 73 | + | |
| 74 | +```raz Lean | |
| 75 | +module Lean; | |
| 76 | +import Out; | |
| 77 | + | |
| 78 | +proc main*; | |
| 79 | +begin | |
| 80 | + Out.str("same program\n"); | |
| 81 | +end; | |
| 82 | + | |
| 83 | +end Lean. | |
| 84 | +``` | |
| 85 | + | |
| 86 | +```raz Heavy | |
| 87 | +module Heavy; | |
| 88 | +import Out; | |
| 89 | + | |
| 90 | +var table: [100000]INT; | |
| 91 | + | |
| 92 | +(* exported, but never called, so never in the executable *) | |
| 93 | +proc unused*(n: INT): INT; | |
| 94 | +var i, s: INT; | |
| 95 | +begin | |
| 96 | + for i := 0 to 99999 do table[i] := n * i; s := s + table[i]; end; | |
| 97 | + Out.str("a long string that nobody will ever print, to give it some weight"); | |
| 98 | + return s; | |
| 99 | +end; | |
| 100 | + | |
| 101 | +proc main*; | |
| 102 | +begin | |
| 103 | + Out.str("same program\n"); | |
| 104 | +end; | |
| 105 | + | |
| 106 | +end Heavy. | |
| 107 | +``` | |
| 108 | + | |
| 109 | +```sh | |
| 110 | +$ raz Lean.raz | |
| 111 | +$ raz Heavy.raz | |
| 112 | +$ ls -l Lean Heavy | awk '{print $9, $5}' | |
| 113 | +``` | |
| 114 | + | |
| 115 | +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. | |
| 116 | + | |
| 117 | +## Stripping | |
| 118 | + | |
| 119 | +`-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. | |
| 120 | + | |
| 121 | +```sh | |
| 122 | +$ raz -s -o Lean-stripped Lean.raz | |
| 123 | +$ ls -l Lean Lean-stripped | awk '{print $9, $5}' | |
| 124 | +$ ./Lean-stripped | |
| 125 | +``` | |
| 126 | + | |
| 127 | +`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. |
| @@ -0,0 +1,75 @@ | ||
| 1 | +title: Threads without C, and keeping the two apart | |
| 2 | +part: Standing alone | |
| 3 | +summary: link static, what a module that makes its own system calls promises, and the error when it breaks. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +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`. | |
| 8 | + | |
| 9 | +## What `Thread` does | |
| 10 | + | |
| 11 | +`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: | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +$ sed -n '1,22p' $RAZLIB/Thread.linux-x86_64.raz | |
| 15 | +``` | |
| 16 | + | |
| 17 | +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. | |
| 18 | + | |
| 19 | +```raz Hello | |
| 20 | +module Hello; | |
| 21 | +import Out, Thread; | |
| 22 | + | |
| 23 | +var done: INT; | |
| 24 | + | |
| 25 | +proc greet(arg: ^U8); | |
| 26 | +begin | |
| 27 | + Out.str("hello from thread "); Out.int(INT(arg)); Out.ln; | |
| 28 | + _ := XADD(ADR(done), 1); | |
| 29 | +end; | |
| 30 | + | |
| 31 | +proc main*; | |
| 32 | +var t: ^Thread.Thread; err: ERROR; | |
| 33 | +begin | |
| 34 | + t, err := Thread.spawn(greet, ^U8(7)); | |
| 35 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 36 | + Thread.join(t); | |
| 37 | + Out.str("joined; done = "); Out.int(done); Out.ln; | |
| 38 | +end; | |
| 39 | + | |
| 40 | +end Hello. | |
| 41 | +``` | |
| 42 | + | |
| 43 | +```sh | |
| 44 | +$ raz Hello.raz | |
| 45 | +$ ./Hello | |
| 46 | +$ file Hello | sed 's/,.*statically/, statically/' | |
| 47 | +``` | |
| 48 | + | |
| 49 | +## When you mix them | |
| 50 | + | |
| 51 | +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: | |
| 52 | + | |
| 53 | +```raz Mixed | |
| 54 | +module Mixed; | |
| 55 | +import Out, Thread, C; | |
| 56 | + | |
| 57 | +proc main*; | |
| 58 | +begin | |
| 59 | + Out.str(MSG(Thread.Failed)); Out.ln; | |
| 60 | + _ := C.printf("%d\n", I32(1)); | |
| 61 | + Out.str("and Out\n"); | |
| 62 | +end; | |
| 63 | + | |
| 64 | +end Mixed. | |
| 65 | +``` | |
| 66 | + | |
| 67 | +```sh | |
| 68 | +$ raz Mixed.raz | |
| 69 | +``` | |
| 70 | + | |
| 71 | +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. | |
| 72 | + | |
| 73 | +## The same promise for your own modules | |
| 74 | + | |
| 75 | +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. |
| @@ -0,0 +1,134 @@ | ||
| 1 | +title: Starting, ending, and signals | |
| 2 | +part: Standing alone | |
| 3 | +summary: What runs before main, what runs after, and how to wait for a signal. | |
| 4 | +--- | |
| 5 | +With no run time, the life of a program is short enough to say in a few lines. What happens, in order: | |
| 6 | + | |
| 7 | +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. | |
| 8 | +2. The bodies of the modules run, each once, imported modules first. | |
| 9 | +3. The main module's `main` runs. | |
| 10 | +4. `Rt.exit` runs the procedures registered with `Rt.atExit`, the last registered first, and ends the program with `main`'s status. | |
| 11 | + | |
| 12 | +## Bodies, then main | |
| 13 | + | |
| 14 | +The first tour showed bodies running before `main`. They are the place to set a module up, and they can end early with `return;`. | |
| 15 | + | |
| 16 | +```raz Order run | |
| 17 | +module Order; | |
| 18 | +import Out; | |
| 19 | + | |
| 20 | +var steps*: INT; | |
| 21 | + | |
| 22 | +proc note(what: []U8); | |
| 23 | +begin | |
| 24 | + INC(steps); | |
| 25 | + Out.int(steps); Out.str(". "); Out.str(what); Out.ln; | |
| 26 | +end; | |
| 27 | + | |
| 28 | +begin | |
| 29 | + note("the body runs before main"); | |
| 30 | + if steps > 5 then return; end; | |
| 31 | + note("and carries on if it isn't ended early"); | |
| 32 | +end Order. | |
| 33 | +``` | |
| 34 | + | |
| 35 | +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: | |
| 36 | + | |
| 37 | +```raz Both run | |
| 38 | +module Both; | |
| 39 | +import Out, Order; | |
| 40 | + | |
| 41 | +proc main*; | |
| 42 | +begin | |
| 43 | + Out.str("main: "); Out.int(Order.steps); Out.str(" steps happened first\n"); | |
| 44 | +end; | |
| 45 | + | |
| 46 | +end Both. | |
| 47 | +``` | |
| 48 | + | |
| 49 | +## Things to do at the end | |
| 50 | + | |
| 51 | +`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. | |
| 52 | + | |
| 53 | +```raz Cleanup run | |
| 54 | +module Cleanup; | |
| 55 | +import Out, Rt; | |
| 56 | + | |
| 57 | +proc first; | |
| 58 | +begin | |
| 59 | + Out.str("registered first, runs last\n"); | |
| 60 | +end; | |
| 61 | + | |
| 62 | +proc second; | |
| 63 | +begin | |
| 64 | + Out.str("registered second, runs first\n"); | |
| 65 | +end; | |
| 66 | + | |
| 67 | +proc main*; | |
| 68 | +begin | |
| 69 | + _ := Rt.atExit(first); | |
| 70 | + _ := Rt.atExit(second); | |
| 71 | + Out.str("main is done\n"); | |
| 72 | +end; | |
| 73 | + | |
| 74 | +end Cleanup. | |
| 75 | +``` | |
| 76 | + | |
| 77 | +## Two ways to leave in a hurry | |
| 78 | + | |
| 79 | +`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. | |
| 80 | + | |
| 81 | +```raz Hurry | |
| 82 | +module Hurry; | |
| 83 | +import Out, Rt, Sys; | |
| 84 | + | |
| 85 | +proc bye; | |
| 86 | +begin | |
| 87 | + Out.str("atExit ran\n"); | |
| 88 | +end; | |
| 89 | + | |
| 90 | +proc main*; | |
| 91 | +begin | |
| 92 | + _ := Rt.atExit(bye); | |
| 93 | + defer Out.str("a deferred statement ran\n"); | |
| 94 | + Out.str("leaving\n"); | |
| 95 | + Out.flush; | |
| 96 | + Sys.exit(3); | |
| 97 | +end; | |
| 98 | + | |
| 99 | +end Hurry. | |
| 100 | +``` | |
| 101 | + | |
| 102 | +```sh | |
| 103 | +$ raz Hurry.raz | |
| 104 | +$ ./Hurry; echo "status $?" | |
| 105 | +``` | |
| 106 | + | |
| 107 | +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. | |
| 108 | + | |
| 109 | +## Signals | |
| 110 | + | |
| 111 | +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. | |
| 112 | + | |
| 113 | +```raz Terms run | |
| 114 | +module Terms; | |
| 115 | +import Out, Sys; | |
| 116 | + | |
| 117 | +proc main*; | |
| 118 | +var fd, sig: INT; | |
| 119 | +begin | |
| 120 | + fd := Sys.catch([Sys.sigTerm, Sys.sigWinch]); | |
| 121 | + Out.str("asking myself to stop\n"); | |
| 122 | + _ := Sys.kill(Sys.pid(), Sys.sigTerm); | |
| 123 | + if Sys.ready(fd, 1000) then | |
| 124 | + sig := Sys.caught(fd); | |
| 125 | + if sig = Sys.sigTerm then Out.str("caught SIGTERM, stopping cleanly\n"); end; | |
| 126 | + end; | |
| 127 | + sig := Sys.caught(fd); | |
| 128 | + Out.int(sig); Out.str(" waiting after that\n"); (* 0: none *) | |
| 129 | +end; | |
| 130 | + | |
| 131 | +end Terms. | |
| 132 | +``` | |
| 133 | + | |
| 134 | +`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`. |
| @@ -0,0 +1,85 @@ | ||
| 1 | +title: One module, one file per target | |
| 2 | +part: Standing alone | |
| 3 | +summary: Portable programs, the code that isn't, and how the compiler keeps them in step. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +## The files | |
| 8 | + | |
| 9 | +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. | |
| 10 | + | |
| 11 | +```sh | |
| 12 | +$ ls $RAZLIB | grep -i "^sys\|^thread" | |
| 13 | +$ cd $RAZLIB && grep -c SYSCALL Sys.linux-x86_64.raz Sys.raz | |
| 14 | +``` | |
| 15 | + | |
| 16 | +## A module of your own | |
| 17 | + | |
| 18 | +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`. | |
| 19 | + | |
| 20 | +```raz Clock.linux-x86_64 | |
| 21 | +module Clock; | |
| 22 | +import Sys; | |
| 23 | + | |
| 24 | +const Name* = "the linux-x86_64 file"; | |
| 25 | + | |
| 26 | +(* a number that only grows *) | |
| 27 | +proc ticks*: I64; | |
| 28 | +begin | |
| 29 | + return Sys.clock(); | |
| 30 | +end; | |
| 31 | + | |
| 32 | +end Clock. | |
| 33 | +``` | |
| 34 | + | |
| 35 | +```raz Clock | |
| 36 | +module Clock; | |
| 37 | +import Sys; | |
| 38 | + | |
| 39 | +const Name* = "the portable file"; | |
| 40 | + | |
| 41 | +(* a number that only grows *) | |
| 42 | +proc ticks*: I64; | |
| 43 | +begin | |
| 44 | + return Sys.clock(); | |
| 45 | +end; | |
| 46 | + | |
| 47 | +end Clock. | |
| 48 | +``` | |
| 49 | + | |
| 50 | +A program that imports `Clock` gets the first of them here: | |
| 51 | + | |
| 52 | +```raz Show run | |
| 53 | +module Show; | |
| 54 | +import Out, Clock; | |
| 55 | + | |
| 56 | +proc main*; | |
| 57 | +begin | |
| 58 | + Out.str("using "); Out.str(Clock.Name); Out.ln; | |
| 59 | + if Clock.ticks() > 0 then Out.str("and it ticks\n"); end; | |
| 60 | +end; | |
| 61 | + | |
| 62 | +end Show. | |
| 63 | +``` | |
| 64 | + | |
| 65 | +## Held to one interface | |
| 66 | + | |
| 67 | +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`: | |
| 68 | + | |
| 69 | +```sh | |
| 70 | +$ mkdir drift && cp Clock*.raz Show.raz drift && cd drift | |
| 71 | +$ sed -i 's/proc ticks\*: I64/proc ticks*: INT/; s/return Sys.clock()/return INT(Sys.clock())/' Clock.raz | |
| 72 | +$ raz Show.raz | |
| 73 | +``` | |
| 74 | + | |
| 75 | +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. | |
| 76 | + | |
| 77 | +## What the compiler checks | |
| 78 | + | |
| 79 | +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. | |
| 80 | + | |
| 81 | +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. | |
| 82 | + | |
| 83 | +## What stays the same everywhere | |
| 84 | + | |
| 85 | +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. |
| @@ -0,0 +1,203 @@ | ||
| 1 | +title: Procedures in assembly | |
| 2 | +part: The machine | |
| 3 | +summary: code procedures: the convention, registers, labels, db for what the assembler doesn't know. | |
| 4 | +--- | |
| 5 | +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`. | |
| 6 | + | |
| 7 | +The compiler doesn't look past what the instructions say. It trusts you, and you owe it a few rules. | |
| 8 | + | |
| 9 | +## A first one | |
| 10 | + | |
| 11 | +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. | |
| 12 | + | |
| 13 | +```raz Cycles run | |
| 14 | +module Cycles; | |
| 15 | +import Out; | |
| 16 | + | |
| 17 | +proc rdtsc*: U64; | |
| 18 | +code | |
| 19 | + rdtsc; | |
| 20 | + shl rdx, 32; | |
| 21 | + or rax, rdx; | |
| 22 | + ret; | |
| 23 | +end rdtsc; | |
| 24 | + | |
| 25 | +proc main*; | |
| 26 | +var a, b: U64; | |
| 27 | +begin | |
| 28 | + a := rdtsc(); | |
| 29 | + b := rdtsc(); | |
| 30 | + if b > a then Out.str("the counter moves forward\n"); end; | |
| 31 | +end; | |
| 32 | + | |
| 33 | +end Cycles. | |
| 34 | +``` | |
| 35 | + | |
| 36 | +A code procedure is called like any procedure. Everything in it is yours, `ret` included. | |
| 37 | + | |
| 38 | +## The convention | |
| 39 | + | |
| 40 | +A code procedure follows the System V convention, as every raz procedure does: | |
| 41 | + | |
| 42 | +- Integer and pointer arguments arrive in `rdi`, `rsi`, `rdx`, `rcx`, `r8` and `r9`; `F32` and `F64` ones in `xmm0` to `xmm7`. | |
| 43 | +- The result goes in `rax` (and `rdx` for a second) or `xmm0`. | |
| 44 | +- 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. | |
| 45 | +- Its parameters and results are therefore of the types C can take, at most six integer and eight real parameters and two results. | |
| 46 | + | |
| 47 | +That is why the next one is so short: the argument is already in `rdi`. | |
| 48 | + | |
| 49 | +```raz Bits run | |
| 50 | +module Bits; | |
| 51 | +import Out; | |
| 52 | + | |
| 53 | +(* the bytes of x in the opposite order: bswap rax, which the assembler | |
| 54 | + doesn't know, written as its bytes *) | |
| 55 | +proc swap64(x: U64): U64; | |
| 56 | +code | |
| 57 | + mov rax, rdi; | |
| 58 | + db 48H, 0FH, 0C8H; | |
| 59 | + ret; | |
| 60 | +end swap64; | |
| 61 | + | |
| 62 | +(* the number of bits set in x: popcnt rax, rdi *) | |
| 63 | +proc ones(x: U64): INT; | |
| 64 | +code | |
| 65 | + db 0F3H, 48H, 0FH, 0B8H, 0C7H; | |
| 66 | + ret; | |
| 67 | +end ones; | |
| 68 | + | |
| 69 | +proc main*; | |
| 70 | +begin | |
| 71 | + Out.str("0x"); Out.hex(swap64(0102030405060708H), 16); Out.ln; | |
| 72 | + Out.int(ones(0FFH)); Out.char(' '); | |
| 73 | + Out.int(ones(0)); Out.char(' '); | |
| 74 | + Out.int(ones(0FFFFFFFFFFFFFFFFH)); Out.ln; | |
| 75 | +end; | |
| 76 | + | |
| 77 | +end Bits. | |
| 78 | +``` | |
| 79 | + | |
| 80 | +`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`.) | |
| 81 | + | |
| 82 | +## Labels and loops | |
| 83 | + | |
| 84 | +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: | |
| 85 | + | |
| 86 | +```raz Sum run | |
| 87 | +module Sum; | |
| 88 | +import Out; | |
| 89 | + | |
| 90 | +(* the sum of the n INTs at p *) | |
| 91 | +proc sum(p: ^INT; n: INT): INT; | |
| 92 | +code | |
| 93 | + xor eax, eax; | |
| 94 | + test rsi, rsi; | |
| 95 | + jle done; | |
| 96 | +again: | |
| 97 | + add rax, [rdi]; | |
| 98 | + add rdi, 8; | |
| 99 | + dec rsi; | |
| 100 | + jnz again; | |
| 101 | +done: | |
| 102 | + ret; | |
| 103 | +end sum; | |
| 104 | + | |
| 105 | +(* the same in raz, to check it against *) | |
| 106 | +proc sumRaz(a: []INT): INT; | |
| 107 | +var i, t: INT; | |
| 108 | +begin | |
| 109 | + for i := 0 to LEN(a) - 1 do t := t + a[i]; end; | |
| 110 | + return t; | |
| 111 | +end; | |
| 112 | + | |
| 113 | +proc main*; | |
| 114 | +var a: [6]INT; i: INT; | |
| 115 | +begin | |
| 116 | + for i := 0 to 5 do a[i] := (i + 1) * 100; end; | |
| 117 | + Out.int(sum(ADR(a[0]), 6)); Out.char(' '); | |
| 118 | + Out.int(sumRaz(a)); Out.char(' '); | |
| 119 | + Out.int(sum(ADR(a[0]), 0)); Out.ln; | |
| 120 | +end; | |
| 121 | + | |
| 122 | +end Sum. | |
| 123 | +``` | |
| 124 | + | |
| 125 | +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. | |
| 126 | + | |
| 127 | +## Two results, and reals | |
| 128 | + | |
| 129 | +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. | |
| 130 | + | |
| 131 | +```raz Divmod run | |
| 132 | +module Divmod; | |
| 133 | +import Out, Fmt; | |
| 134 | + | |
| 135 | +(* quotient and remainder, as idiv gives them: rax and rdx *) | |
| 136 | +proc divmod(a, b: INT): (INT, INT); | |
| 137 | +code | |
| 138 | + mov rax, rdi; | |
| 139 | + cqo; | |
| 140 | + idiv rsi; | |
| 141 | + ret; | |
| 142 | +end divmod; | |
| 143 | + | |
| 144 | +(* a * x + b, on F64s in xmm0 to xmm2 *) | |
| 145 | +proc fma(a, x, b: F64): F64; | |
| 146 | +code | |
| 147 | + mulsd xmm0, xmm1; | |
| 148 | + addsd xmm0, xmm2; | |
| 149 | + ret; | |
| 150 | +end fma; | |
| 151 | + | |
| 152 | +proc main*; | |
| 153 | +var q, r: INT; | |
| 154 | +begin | |
| 155 | + q, r := divmod(-17, 5); | |
| 156 | + Out.int(q); Out.char(' '); Out.int(r); Out.ln; | |
| 157 | + Fmt.print("{}\n", [Fmt.real(fma(2.0, 3.5, 0.25), 2)]); | |
| 158 | +end; | |
| 159 | + | |
| 160 | +end Divmod. | |
| 161 | +``` | |
| 162 | + | |
| 163 | +`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. | |
| 164 | + | |
| 165 | +## Keeping what isn't yours | |
| 166 | + | |
| 167 | +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: | |
| 168 | + | |
| 169 | +```raz Vendor run | |
| 170 | +module Vendor; | |
| 171 | +import Out; | |
| 172 | + | |
| 173 | +(* the 12 bytes of the processor vendor, in buf (rdi) *) | |
| 174 | +proc vendor(buf: ^U8); | |
| 175 | +code | |
| 176 | + push rbx; | |
| 177 | + mov r8, rdi; | |
| 178 | + xor eax, eax; | |
| 179 | + cpuid; | |
| 180 | + mov [r8], ebx; | |
| 181 | + mov [r8 + 4], edx; | |
| 182 | + mov [r8 + 8], ecx; | |
| 183 | + pop rbx; | |
| 184 | + ret; | |
| 185 | +end vendor; | |
| 186 | + | |
| 187 | +proc main*; | |
| 188 | +var buf: [12]U8; i: INT; ok: BOOL; | |
| 189 | +begin | |
| 190 | + vendor(ADR(buf[0])); | |
| 191 | + ok := true; | |
| 192 | + for i := 0 to 11 do | |
| 193 | + if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end; | |
| 194 | + end; | |
| 195 | + if ok then Out.str("the vendor is 12 printable bytes\n"); end; | |
| 196 | +end; | |
| 197 | + | |
| 198 | +end Vendor. | |
| 199 | +``` | |
| 200 | + | |
| 201 | +## What goes wrong | |
| 202 | + | |
| 203 | +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. |
| @@ -0,0 +1,177 @@ | ||
| 1 | +title: System calls | |
| 2 | +part: The machine | |
| 3 | +summary: SYSCALL directly: the numbers, the arguments, negative errno, and a cat without a library. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +`SYSCALL` exists only on Linux targets. Other systems have no stable system call interface, which is why their `Sys` calls the C library instead. | |
| 8 | + | |
| 9 | +## The shape of a call | |
| 10 | + | |
| 11 | +`write(fd, buf, count)` is call number 1. The arguments are the descriptor, a pointer to the bytes, and how many. | |
| 12 | + | |
| 13 | +```raz Raw | |
| 14 | +module Raw; | |
| 15 | + | |
| 16 | +const Msg = "straight to the kernel\n"; | |
| 17 | + | |
| 18 | +proc main*; | |
| 19 | +var n: INT; | |
| 20 | +begin | |
| 21 | + n := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg)); | |
| 22 | + if n # LEN(Msg) then _ := SYSCALL(60, 1); end; (* exit(1), if it came up short *) | |
| 23 | +end; | |
| 24 | + | |
| 25 | +end Raw. | |
| 26 | +``` | |
| 27 | + | |
| 28 | +```sh | |
| 29 | +$ raz -Werror Raw.raz | |
| 30 | +$ ./Raw | |
| 31 | +``` | |
| 32 | + | |
| 33 | +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. | |
| 34 | + | |
| 35 | +## Reading the result | |
| 36 | + | |
| 37 | +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. | |
| 38 | + | |
| 39 | +```raz Open run | |
| 40 | +module Open; | |
| 41 | +import Out; | |
| 42 | + | |
| 43 | +proc main*; | |
| 44 | +var path: [32]U8; fd: INT; | |
| 45 | +begin | |
| 46 | + path := "/no/such/file"; | |
| 47 | + fd := SYSCALL(2, ADR(path[0]), 0, 0); (* open(path, O_RDONLY) *) | |
| 48 | + Out.str("open gave "); Out.int(fd); Out.ln; (* -2: ENOENT *) | |
| 49 | + path := "/dev/null"; | |
| 50 | + fd := SYSCALL(2, ADR(path[0]), 0, 0); | |
| 51 | + if fd >= 0 then | |
| 52 | + Out.str("opened /dev/null\n"); | |
| 53 | + _ := SYSCALL(3, fd); (* close *) | |
| 54 | + end; | |
| 55 | +end; | |
| 56 | + | |
| 57 | +end Open. | |
| 58 | +``` | |
| 59 | + | |
| 60 | +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. | |
| 61 | + | |
| 62 | +## A call that fills a structure | |
| 63 | + | |
| 64 | +`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. | |
| 65 | + | |
| 66 | +```raz Who run | |
| 67 | +module Who; | |
| 68 | +import Out; | |
| 69 | + | |
| 70 | +(* the length of the zero-ended string at the start of s *) | |
| 71 | +proc cstr(s: []U8): INT; | |
| 72 | +var n: INT; | |
| 73 | +begin | |
| 74 | + n := 0; | |
| 75 | + while (n < LEN(s)) and (s[n] # 0) do INC(n); end; | |
| 76 | + return n; | |
| 77 | +end; | |
| 78 | + | |
| 79 | +proc main*; | |
| 80 | +var u: [390]U8; | |
| 81 | +begin | |
| 82 | + if SYSCALL(63, ADR(u[0])) = 0 then | |
| 83 | + Out.str("system: "); Out.str(u[0..cstr(u[0..65])]); Out.ln; | |
| 84 | + Out.str("machine: "); Out.str(u[260..260 + cstr(u[260..325])]); Out.ln; | |
| 85 | + end; | |
| 86 | +end; | |
| 87 | + | |
| 88 | +end Who. | |
| 89 | +``` | |
| 90 | + | |
| 91 | +## Memory straight from the kernel | |
| 92 | + | |
| 93 | +`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. | |
| 94 | + | |
| 95 | +```raz Pages run | |
| 96 | +module Pages; | |
| 97 | +import Out; | |
| 98 | + | |
| 99 | +proc main*; | |
| 100 | +var p: ^U8; i: INT; total: INT; | |
| 101 | +begin | |
| 102 | + (* length 4096; PROT_READ|WRITE = 3; MAP_PRIVATE|ANONYMOUS = 22H; no fd *) | |
| 103 | + p := ^U8(SYSCALL(9, 0, 4096, 3, 22H, -1, 0)); | |
| 104 | + if INT(p) < 0 then Out.str("no memory\n"); return; end; | |
| 105 | + Out.int(INT(p[0]) + INT(p[4095])); Out.str(" (zero, as promised)\n"); | |
| 106 | + for i := 0 to 4095 do p[i] := U8(i); end; | |
| 107 | + for i := 0 to 4095 do INC(total, INT(p[i])); end; | |
| 108 | + Out.int(total); Out.ln; | |
| 109 | + _ := SYSCALL(11, p, 4096); | |
| 110 | +end; | |
| 111 | + | |
| 112 | +end Pages. | |
| 113 | +``` | |
| 114 | + | |
| 115 | +## A cat with no library | |
| 116 | + | |
| 117 | +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. | |
| 118 | + | |
| 119 | +```raz Cat | |
| 120 | +module Cat; | |
| 121 | + | |
| 122 | +proc main*: INT; | |
| 123 | +var buf: [4096]U8; n, wrote, at: INT; | |
| 124 | +begin | |
| 125 | + n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf)); | |
| 126 | + while n > 0 do | |
| 127 | + at := 0; | |
| 128 | + while at < n do (* a write may be partial *) | |
| 129 | + wrote := SYSCALL(1, 1, ADR(buf[at]), n - at); | |
| 130 | + if wrote < 0 then return 1; end; | |
| 131 | + INC(at, wrote); | |
| 132 | + end; | |
| 133 | + n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf)); | |
| 134 | + end; | |
| 135 | + if n < 0 then return 1; end; | |
| 136 | + return 0; | |
| 137 | +end; | |
| 138 | + | |
| 139 | +end Cat. | |
| 140 | +``` | |
| 141 | + | |
| 142 | +```sh | |
| 143 | +$ raz Cat.raz | |
| 144 | +$ echo "through the pipe" | ./Cat | |
| 145 | +$ ./Cat < /dev/null; echo "status $?" | |
| 146 | +$ echo "see the calls" | strace -e trace=read,write ./Cat 2>&1 >/dev/null | grep -v '^+++' | |
| 147 | +``` | |
| 148 | + | |
| 149 | +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. | |
| 150 | + | |
| 151 | +## In a code procedure | |
| 152 | + | |
| 153 | +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`. | |
| 154 | + | |
| 155 | +```raz Ppid run | |
| 156 | +module Ppid; | |
| 157 | +import Out; | |
| 158 | + | |
| 159 | +(* getppid, call 110: no arguments *) | |
| 160 | +proc getppid: INT; | |
| 161 | +code | |
| 162 | + mov eax, 110; | |
| 163 | + syscall; | |
| 164 | + ret; | |
| 165 | +end getppid; | |
| 166 | + | |
| 167 | +proc main*; | |
| 168 | +begin | |
| 169 | + if (getppid() > 0) and (SYSCALL(110) = getppid()) then | |
| 170 | + Out.str("two ways to ask, one answer\n"); | |
| 171 | + end; | |
| 172 | +end; | |
| 173 | + | |
| 174 | +end Ppid. | |
| 175 | +``` | |
| 176 | + | |
| 177 | +`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. |
| @@ -0,0 +1,118 @@ | ||
| 1 | +title: What the compiler makes | |
| 2 | +part: The machine | |
| 3 | +summary: raz -S, reading a listing, what a check costs and what check off removes. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +## A small procedure | |
| 8 | + | |
| 9 | +```raz Add | |
| 10 | +module Add; | |
| 11 | + | |
| 12 | +proc add*(a, b: INT): INT; | |
| 13 | +begin | |
| 14 | + return a + b; | |
| 15 | +end; | |
| 16 | + | |
| 17 | +proc main*; | |
| 18 | +begin | |
| 19 | + _ := add(1, 2); | |
| 20 | +end; | |
| 21 | + | |
| 22 | +end Add. | |
| 23 | +``` | |
| 24 | + | |
| 25 | +```sh | |
| 26 | +$ raz -S Add.raz | |
| 27 | +``` | |
| 28 | + | |
| 29 | +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. | |
| 30 | + | |
| 31 | +## A loop with its checks | |
| 32 | + | |
| 33 | +This is the dot product of two slices. A slice is a pointer and a length, and it travels in two registers: | |
| 34 | + | |
| 35 | +```raz Dot | |
| 36 | +module Dot; | |
| 37 | + | |
| 38 | +(* the dot product of two slices of equal length *) | |
| 39 | +proc dot*(a, b: []INT): INT; | |
| 40 | +var i, sum: INT; | |
| 41 | +begin | |
| 42 | + for i := 0 to LEN(a) - 1 do | |
| 43 | + sum := sum + a[i] * b[i]; | |
| 44 | + end; | |
| 45 | + return sum; | |
| 46 | +end; | |
| 47 | + | |
| 48 | +proc main*; | |
| 49 | +var x, y: [3]INT; | |
| 50 | +begin | |
| 51 | + x := [1, 2, 3]; | |
| 52 | + y := [4, 5, 6]; | |
| 53 | + _ := dot(x, y); | |
| 54 | +end; | |
| 55 | + | |
| 56 | +end Dot. | |
| 57 | +``` | |
| 58 | + | |
| 59 | +```sh | |
| 60 | +$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p' | |
| 61 | +``` | |
| 62 | + | |
| 63 | +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. | |
| 64 | + | |
| 65 | +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. | |
| 66 | + | |
| 67 | +## Taking the checks out | |
| 68 | + | |
| 69 | +`check off;` after the imports leaves out the module's own checks of indexes and slice bounds. Here is the same procedure with it: | |
| 70 | + | |
| 71 | +```raz Dot2 | |
| 72 | +module Dot2; | |
| 73 | +check off; | |
| 74 | + | |
| 75 | +proc dot*(a, b: []INT): INT; | |
| 76 | +var i, sum: INT; | |
| 77 | +begin | |
| 78 | + for i := 0 to LEN(a) - 1 do | |
| 79 | + sum := sum + a[i] * b[i]; | |
| 80 | + end; | |
| 81 | + return sum; | |
| 82 | +end; | |
| 83 | + | |
| 84 | +proc main*; | |
| 85 | +var x, y: [3]INT; | |
| 86 | +begin | |
| 87 | + x := [1, 2, 3]; | |
| 88 | + y := [4, 5, 6]; | |
| 89 | + _ := dot(x, y); | |
| 90 | +end; | |
| 91 | + | |
| 92 | +end Dot2. | |
| 93 | +``` | |
| 94 | + | |
| 95 | +```sh | |
| 96 | +$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p' | |
| 97 | +$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p' | wc -l | |
| 98 | +$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p' | wc -l | |
| 99 | +``` | |
| 100 | + | |
| 101 | +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. | |
| 102 | + | |
| 103 | +## Comparing with C | |
| 104 | + | |
| 105 | +`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. | |
| 106 | + | |
| 107 | +## Tools that read what it made | |
| 108 | + | |
| 109 | +- `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. | |
| 110 | +- `RAZ_PROFILE=1` samples the program every millisecond and says which procedures and lines took the time. | |
| 111 | +- `objdump -d` disassembles what is really in the file, if you want to see the bytes behind a listing. | |
| 112 | + | |
| 113 | +```sh | |
| 114 | +$ raz -o Dot Dot.raz | |
| 115 | +$ objdump -d -M intel --no-show-raw-insn Dot | sed -n '/<Dot.dot>:/,/ret/p' | head -12 | |
| 116 | +``` | |
| 117 | + | |
| 118 | +The listing is what the encoder meant; `objdump` is what the processor will read. They tell the same story. |
| @@ -0,0 +1,124 @@ | ||
| 1 | +title: Volatile | |
| 2 | +part: Shared memory | |
| 3 | +summary: ^VOLATILE T: memory that something else may change, laid over with a record. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +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. | |
| 8 | + | |
| 9 | +## A device laid over memory | |
| 10 | + | |
| 11 | +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. | |
| 12 | + | |
| 13 | +```raz Uart run | |
| 14 | +module Uart; | |
| 15 | +import Out; | |
| 16 | + | |
| 17 | +type | |
| 18 | + Regs = record | |
| 19 | + data: U32; (* offset 0 *) | |
| 20 | + status: U32; (* offset 4 *) | |
| 21 | + control: U8; (* offset 8 *) | |
| 22 | + end; | |
| 23 | + | |
| 24 | +var page: [64]U8; (* where the device would be *) | |
| 25 | + | |
| 26 | +proc main*; | |
| 27 | +var dev: ^VOLATILE Regs; i: INT; | |
| 28 | +begin | |
| 29 | + dev := ^VOLATILE Regs(ADR(page)); (* the conversion is written *) | |
| 30 | + dev^.control := 1; | |
| 31 | + dev^.status := 0FFH; | |
| 32 | + for i := 0 to 2 do | |
| 33 | + dev^.data := U32('a' + i); | |
| 34 | + Out.char(U8(dev^.data)); | |
| 35 | + end; | |
| 36 | + Out.ln; | |
| 37 | + FENCE; | |
| 38 | + Out.int(INT(page[8])); Out.char(' '); Out.int(INT(dev^.status)); Out.ln; | |
| 39 | +end; | |
| 40 | + | |
| 41 | +end Uart. | |
| 42 | +``` | |
| 43 | + | |
| 44 | +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. | |
| 45 | + | |
| 46 | +## What each access is | |
| 47 | + | |
| 48 | +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. | |
| 49 | + | |
| 50 | +```sh | |
| 51 | +$ raz -S Uart.raz | grep -n "dword\|byte" | head -2 | |
| 52 | +``` | |
| 53 | + | |
| 54 | +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. | |
| 55 | + | |
| 56 | +## Waiting for something else to change | |
| 57 | + | |
| 58 | +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. | |
| 59 | + | |
| 60 | +```raz Poll run | |
| 61 | +module Poll; | |
| 62 | +import Out, Sys, Thread; | |
| 63 | + | |
| 64 | +type Dev = record status: INT; data: INT; end; | |
| 65 | + | |
| 66 | +var dev: Dev; | |
| 67 | + | |
| 68 | +proc device(_arg: ^U8); | |
| 69 | +var d: ^VOLATILE Dev; | |
| 70 | +begin | |
| 71 | + d := ^VOLATILE Dev(ADR(dev)); | |
| 72 | + Sys.sleep(20); | |
| 73 | + d^.data := 42; | |
| 74 | + FENCE; (* data before the flag that announces it *) | |
| 75 | + d^.status := 1; | |
| 76 | +end; | |
| 77 | + | |
| 78 | +proc main*; | |
| 79 | +var t: ^Thread.Thread; err: ERROR; d: ^VOLATILE Dev; spins: INT; | |
| 80 | +begin | |
| 81 | + d := ^VOLATILE Dev(ADR(dev)); | |
| 82 | + t, err := Thread.spawn(device, nil); | |
| 83 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 84 | + while d^.status = 0 do INC(spins); Sys.yield; end; | |
| 85 | + Out.int(d^.data); Out.ln; | |
| 86 | + if spins > 0 then Out.str("it waited for the device\n"); end; | |
| 87 | + Thread.join(t); | |
| 88 | +end; | |
| 89 | + | |
| 90 | +end Poll. | |
| 91 | +``` | |
| 92 | + | |
| 93 | +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. | |
| 94 | + | |
| 95 | +## What volatile is not | |
| 96 | + | |
| 97 | +- **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. | |
| 98 | +- **Not a lock.** It says each access happens as written; it says nothing about what happens between them. | |
| 99 | +- **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. | |
| 100 | +- **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. | |
| 101 | + | |
| 102 | +The compiler holds the line on each of them: | |
| 103 | + | |
| 104 | +```raz Wrong | |
| 105 | +module Wrong; | |
| 106 | + | |
| 107 | +type Pair = record a, b: U32; end; | |
| 108 | + | |
| 109 | +var cell: Pair; | |
| 110 | + | |
| 111 | +proc main*; | |
| 112 | +var v: ^VOLATILE Pair; p: ^Pair; copy: Pair; | |
| 113 | +begin | |
| 114 | + v := ^VOLATILE Pair(ADR(cell)); | |
| 115 | + p := v; | |
| 116 | + copy := v^; | |
| 117 | +end; | |
| 118 | + | |
| 119 | +end Wrong. | |
| 120 | +``` | |
| 121 | + | |
| 122 | +```sh | |
| 123 | +$ raz Wrong.raz | |
| 124 | +``` |
| @@ -0,0 +1,168 @@ | ||
| 1 | +title: Atomics | |
| 2 | +part: Shared memory | |
| 3 | +summary: XADD, XCHG and CAS; a compare-and-swap loop; a lock built from them. | |
| 4 | +--- | |
| 5 | +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: | |
| 6 | + | |
| 7 | +| Call | Does | | |
| 8 | +|---|---| | |
| 9 | +| `XADD(p, x)` | adds `x` to `p^` and returns the value before | | |
| 10 | +| `XCHG(p, x)` | sets `p^ := x` and returns the value before | | |
| 11 | +| `CAS(p, old, new)` | if `p^ = old`, sets `p^ := new` and returns `true`; otherwise `false` | | |
| 12 | + | |
| 13 | +`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`: | |
| 14 | + | |
| 15 | +```raz Ops | |
| 16 | +module Ops; | |
| 17 | + | |
| 18 | +var counter: INT; | |
| 19 | + | |
| 20 | +proc main*; | |
| 21 | +begin | |
| 22 | + _ := XADD(ADR(counter), 5); | |
| 23 | + _ := XCHG(ADR(counter), 100); | |
| 24 | + _ := CAS(ADR(counter), 100, 7); | |
| 25 | +end; | |
| 26 | + | |
| 27 | +end Ops. | |
| 28 | +``` | |
| 29 | + | |
| 30 | +```sh | |
| 31 | +$ raz -S Ops.raz | grep -i "lock\|xchg" | |
| 32 | +``` | |
| 33 | + | |
| 34 | +## What each one gives you | |
| 35 | + | |
| 36 | +`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. | |
| 37 | + | |
| 38 | +```raz Tickets run | |
| 39 | +module Tickets; | |
| 40 | +import Out, Thread; | |
| 41 | + | |
| 42 | +var | |
| 43 | + next: INT; (* the next ticket to give out *) | |
| 44 | + seen: [4000]U8; (* which tickets were taken, one byte each *) | |
| 45 | + | |
| 46 | +proc work(_arg: ^U8); | |
| 47 | +var i, t: INT; | |
| 48 | +begin | |
| 49 | + for i := 1 to 1000 do | |
| 50 | + t := XADD(ADR(next), 1); (* a ticket no other thread gets *) | |
| 51 | + seen[t] := 1; | |
| 52 | + end; | |
| 53 | +end; | |
| 54 | + | |
| 55 | +proc main*; | |
| 56 | +var th: [4]^Thread.Thread; i, taken: INT; err: ERROR; | |
| 57 | +begin | |
| 58 | + for i := 0 to 3 do | |
| 59 | + th[i], err := Thread.spawn(work, nil); | |
| 60 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 61 | + end; | |
| 62 | + for i := 0 to 3 do Thread.join(th[i]); end; | |
| 63 | + for i := 0 to 3999 do taken := taken + INT(seen[i]); end; | |
| 64 | + Out.int(next); Out.char(' '); Out.int(taken); Out.ln; | |
| 65 | +end; | |
| 66 | + | |
| 67 | +end Tickets. | |
| 68 | +``` | |
| 69 | + | |
| 70 | +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. | |
| 71 | + | |
| 72 | +## A compare-and-swap loop | |
| 73 | + | |
| 74 | +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. | |
| 75 | + | |
| 76 | +```raz Peak run | |
| 77 | +module Peak; | |
| 78 | +import Out, Thread; | |
| 79 | + | |
| 80 | +var peak: INT; | |
| 81 | + | |
| 82 | +(* raises peak to v if v is bigger, however many threads call it *) | |
| 83 | +proc raise(v: INT); | |
| 84 | +var seen: INT; | |
| 85 | +begin | |
| 86 | + seen := peak; | |
| 87 | + while seen < v do | |
| 88 | + if CAS(ADR(peak), seen, v) then return; end; | |
| 89 | + seen := peak; (* someone changed it: look again *) | |
| 90 | + end; | |
| 91 | +end; | |
| 92 | + | |
| 93 | +proc work(arg: ^U8); | |
| 94 | +var i, base: INT; | |
| 95 | +begin | |
| 96 | + base := INT(arg); | |
| 97 | + for i := 0 to 999 do raise(base + i * 7 mod 1001); end; | |
| 98 | +end; | |
| 99 | + | |
| 100 | +proc main*; | |
| 101 | +var th: [4]^Thread.Thread; i: INT; err: ERROR; | |
| 102 | +begin | |
| 103 | + for i := 0 to 3 do | |
| 104 | + th[i], err := Thread.spawn(work, ^U8(i * 1000)); | |
| 105 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 106 | + end; | |
| 107 | + for i := 0 to 3 do Thread.join(th[i]); end; | |
| 108 | + Out.int(peak); Out.ln; | |
| 109 | +end; | |
| 110 | + | |
| 111 | +end Peak. | |
| 112 | +``` | |
| 113 | + | |
| 114 | +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. | |
| 115 | + | |
| 116 | +## A lock, from first principles | |
| 117 | + | |
| 118 | +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`: | |
| 119 | + | |
| 120 | +```sh | |
| 121 | +$ sed -n '/^type Lock/,/^proc main/p' $RAZLIB/Lock.raz | head -n -2 | |
| 122 | +``` | |
| 123 | + | |
| 124 | +And here is a use of it: a structure with two fields that must stay in step, which no single atomic can protect. | |
| 125 | + | |
| 126 | +```raz Account run | |
| 127 | +module Account; | |
| 128 | +import Out, Lock, Thread; | |
| 129 | + | |
| 130 | +var | |
| 131 | + lock: Lock.Lock; | |
| 132 | + deposits, balance: INT; (* balance = 3 * deposits, always, under lock *) | |
| 133 | + | |
| 134 | +proc work(_arg: ^U8); | |
| 135 | +var i: INT; | |
| 136 | +begin | |
| 137 | + for i := 1 to 20000 do | |
| 138 | + Lock.take(ADR(lock)); | |
| 139 | + INC(deposits); | |
| 140 | + INC(balance, 3); | |
| 141 | + Lock.give(ADR(lock)); | |
| 142 | + end; | |
| 143 | +end; | |
| 144 | + | |
| 145 | +proc main*; | |
| 146 | +var th: [4]^Thread.Thread; i: INT; err: ERROR; | |
| 147 | +begin | |
| 148 | + for i := 0 to 3 do | |
| 149 | + th[i], err := Thread.spawn(work, nil); | |
| 150 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 151 | + end; | |
| 152 | + for i := 0 to 3 do Thread.join(th[i]); end; | |
| 153 | + Out.int(deposits); Out.char(' '); Out.int(balance); Out.ln; | |
| 154 | + if balance = 3 * deposits then Out.str("in step\n"); end; | |
| 155 | +end; | |
| 156 | + | |
| 157 | +end Account. | |
| 158 | +``` | |
| 159 | + | |
| 160 | +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. | |
| 161 | + | |
| 162 | +## Choosing | |
| 163 | + | |
| 164 | +- A counter, a ticket, a flag: `XADD` or `XCHG`. | |
| 165 | +- A value computed from the old one: a `CAS` loop. | |
| 166 | +- 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. | |
| 167 | + | |
| 168 | +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. |
| @@ -0,0 +1,105 @@ | ||
| 1 | +title: Ordering and publication | |
| 2 | +part: Shared memory | |
| 3 | +summary: Why a flag isn't enough, what FENCE and the atomics order, and the pattern that works. | |
| 4 | +--- | |
| 5 | +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? | |
| 6 | + | |
| 7 | +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. | |
| 8 | + | |
| 9 | +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. | |
| 10 | + | |
| 11 | +## The pattern that is guaranteed: publish through an atomic | |
| 12 | + | |
| 13 | +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. | |
| 14 | + | |
| 15 | +```raz Publish run | |
| 16 | +module Publish; | |
| 17 | +import Out, Sys, Thread; | |
| 18 | + | |
| 19 | +type Message = record id: INT; text: [32]U8; len: INT; end; | |
| 20 | + | |
| 21 | +var | |
| 22 | + msg: Message; (* ordinary memory, written once, then published *) | |
| 23 | + ready: INT; (* the flag: only touched by atomics *) | |
| 24 | + | |
| 25 | +proc producer(_arg: ^U8); | |
| 26 | +begin | |
| 27 | + Sys.sleep(10); | |
| 28 | + msg.id := 7; | |
| 29 | + msg.text := "built before the flag"; | |
| 30 | + msg.len := 21; | |
| 31 | + _ := XCHG(ADR(ready), 1); (* publish *) | |
| 32 | +end; | |
| 33 | + | |
| 34 | +proc main*; | |
| 35 | +var t: ^Thread.Thread; err: ERROR; | |
| 36 | +begin | |
| 37 | + t, err := Thread.spawn(producer, nil); | |
| 38 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 39 | + while XADD(ADR(ready), 0) = 0 do Sys.yield; end; (* wait for it *) | |
| 40 | + Out.int(msg.id); Out.char(' '); Out.str(msg.text[0..msg.len]); Out.ln; | |
| 41 | + Thread.join(t); | |
| 42 | +end; | |
| 43 | + | |
| 44 | +end Publish. | |
| 45 | +``` | |
| 46 | + | |
| 47 | +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`. | |
| 48 | + | |
| 49 | +## The same with a fence | |
| 50 | + | |
| 51 | +`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. | |
| 52 | + | |
| 53 | +```raz Fenced run | |
| 54 | +module Fenced; | |
| 55 | +import Out, Sys, Thread; | |
| 56 | + | |
| 57 | +var | |
| 58 | + data: INT; (* ordinary *) | |
| 59 | + flag: INT; (* only reached through a volatile pointer *) | |
| 60 | + | |
| 61 | +proc producer(_arg: ^U8); | |
| 62 | +var f: ^VOLATILE INT; | |
| 63 | +begin | |
| 64 | + f := ^VOLATILE INT(ADR(flag)); | |
| 65 | + Sys.sleep(10); | |
| 66 | + data := 1234; | |
| 67 | + FENCE; (* data is written before the flag is *) | |
| 68 | + f^ := 1; | |
| 69 | +end; | |
| 70 | + | |
| 71 | +proc main*; | |
| 72 | +var t: ^Thread.Thread; err: ERROR; f: ^VOLATILE INT; | |
| 73 | +begin | |
| 74 | + f := ^VOLATILE INT(ADR(flag)); | |
| 75 | + t, err := Thread.spawn(producer, nil); | |
| 76 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 77 | + while f^ = 0 do Sys.yield; end; | |
| 78 | + FENCE; (* and read after the flag is seen *) | |
| 79 | + Out.int(data); Out.ln; | |
| 80 | + Thread.join(t); | |
| 81 | +end; | |
| 82 | + | |
| 83 | +end Fenced. | |
| 84 | +``` | |
| 85 | + | |
| 86 | +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. | |
| 87 | + | |
| 88 | +## The version that is not guaranteed | |
| 89 | + | |
| 90 | +This is what *not* to write, and it is the most common bug in this area: | |
| 91 | + | |
| 92 | +```text | |
| 93 | +var data, ready: INT; | |
| 94 | + | |
| 95 | +(* thread A *) data := 42; ready := 1; | |
| 96 | +(* thread B *) while ready = 0 do end; use(data); | |
| 97 | +``` | |
| 98 | + | |
| 99 | +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. | |
| 100 | + | |
| 101 | +## The lesson of the three versions | |
| 102 | + | |
| 103 | +- Shared and written by someone: reach it through an atomic, a volatile pointer or a fence, every time, on both sides. | |
| 104 | +- To hand over a bundle, publish a single atomic word *after* writing the bundle, and read the bundle only *after* seeing the word. | |
| 105 | +- 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. |
| @@ -0,0 +1,135 @@ | ||
| 1 | +title: A lock-free stack | |
| 2 | +part: Shared memory | |
| 3 | +summary: CAS on pointers, a push loop that never blocks, and the ABA problem that makes pop harder. | |
| 4 | +--- | |
| 5 | +`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. | |
| 6 | + | |
| 7 | +## Push | |
| 8 | + | |
| 9 | +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. | |
| 10 | + | |
| 11 | +```raz Treiber run | |
| 12 | +module Treiber; | |
| 13 | +import Out, Thread; | |
| 14 | + | |
| 15 | +type Node = record next: ^Node; val: INT; end; | |
| 16 | + | |
| 17 | +const Threads = 4; Each = 5000; | |
| 18 | + | |
| 19 | +var | |
| 20 | + top: ^Node; (* the head, changed only by CAS *) | |
| 21 | + nodes: [Threads * Each]Node; (* every node a thread will push *) | |
| 22 | + | |
| 23 | +(* n onto the stack, without a lock *) | |
| 24 | +proc push(n: ^Node); | |
| 25 | +var old: ^Node; | |
| 26 | +begin | |
| 27 | + old := top; | |
| 28 | + n^.next := old; | |
| 29 | + while not CAS(ADR(top), old, n) do | |
| 30 | + old := top; (* lost the race: look again *) | |
| 31 | + n^.next := old; | |
| 32 | + end; | |
| 33 | +end; | |
| 34 | + | |
| 35 | +proc work(arg: ^U8); | |
| 36 | +var first, i: INT; | |
| 37 | +begin | |
| 38 | + first := INT(arg) * Each; | |
| 39 | + for i := 0 to Each - 1 do | |
| 40 | + nodes[first + i].val := first + i; | |
| 41 | + push(ADR(nodes[first + i])); | |
| 42 | + end; | |
| 43 | +end; | |
| 44 | + | |
| 45 | +proc main*; | |
| 46 | +var th: [Threads]^Thread.Thread; i, count, sum: INT; err: ERROR; n: ^Node; | |
| 47 | +begin | |
| 48 | + for i := 0 to Threads - 1 do | |
| 49 | + th[i], err := Thread.spawn(work, ^U8(i)); | |
| 50 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 51 | + end; | |
| 52 | + for i := 0 to Threads - 1 do Thread.join(th[i]); end; | |
| 53 | + n := top; | |
| 54 | + while n # nil do | |
| 55 | + INC(count); | |
| 56 | + sum := sum + n^.val; | |
| 57 | + n := n^.next; | |
| 58 | + end; | |
| 59 | + Out.int(count); Out.char(' '); Out.int(sum); Out.ln; | |
| 60 | + Out.int(Threads * Each * (Threads * Each - 1) div 2); Out.ln; | |
| 61 | +end; | |
| 62 | + | |
| 63 | +end Treiber. | |
| 64 | +``` | |
| 65 | + | |
| 66 | +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. | |
| 67 | + | |
| 68 | +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`. | |
| 69 | + | |
| 70 | +## Pop, and the ABA problem | |
| 71 | + | |
| 72 | +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. | |
| 73 | + | |
| 74 | +There are three common ways out, and each has a cost: | |
| 75 | + | |
| 76 | +- **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. | |
| 77 | +- **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`. | |
| 78 | +- **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. | |
| 79 | + | |
| 80 | +```raz Drain run | |
| 81 | +module Drain; | |
| 82 | +import Out, Thread; | |
| 83 | + | |
| 84 | +type Node = record next: ^Node; val: INT; end; | |
| 85 | + | |
| 86 | +const Threads = 3; Each = 1000; | |
| 87 | + | |
| 88 | +var | |
| 89 | + top: ^Node; | |
| 90 | + nodes: [Threads * Each]Node; | |
| 91 | + | |
| 92 | +proc push(n: ^Node); | |
| 93 | +var old: ^Node; | |
| 94 | +begin | |
| 95 | + old := top; | |
| 96 | + n^.next := old; | |
| 97 | + while not CAS(ADR(top), old, n) do | |
| 98 | + old := top; | |
| 99 | + n^.next := old; | |
| 100 | + end; | |
| 101 | +end; | |
| 102 | + | |
| 103 | +proc work(arg: ^U8); | |
| 104 | +var first, i: INT; | |
| 105 | +begin | |
| 106 | + first := INT(arg) * Each; | |
| 107 | + for i := 0 to Each - 1 do | |
| 108 | + nodes[first + i].val := 1; | |
| 109 | + push(ADR(nodes[first + i])); | |
| 110 | + end; | |
| 111 | +end; | |
| 112 | + | |
| 113 | +proc main*; | |
| 114 | +var th: [Threads]^Thread.Thread; i, count: INT; err: ERROR; all, n: ^Node; | |
| 115 | +begin | |
| 116 | + for i := 0 to Threads - 1 do | |
| 117 | + th[i], err := Thread.spawn(work, ^U8(i)); | |
| 118 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 119 | + end; | |
| 120 | + for i := 0 to Threads - 1 do Thread.join(th[i]); end; | |
| 121 | + all := XCHG(ADR(top), nil); (* take the whole stack, atomically *) | |
| 122 | + n := all; | |
| 123 | + while n # nil do INC(count); n := n^.next; end; | |
| 124 | + Out.int(count); Out.str(" taken at once, "); | |
| 125 | + if top = nil then Out.str("none left\n"); end; | |
| 126 | +end; | |
| 127 | + | |
| 128 | +end Drain. | |
| 129 | +``` | |
| 130 | + | |
| 131 | +The atomic exchange takes everything pushed so far in one step, so the walk that follows races with nobody. | |
| 132 | + | |
| 133 | +## When to use it | |
| 134 | + | |
| 135 | +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. |
| @@ -0,0 +1,118 @@ | ||
| 1 | +title: A ring buffer between threads | |
| 2 | +part: Shared memory | |
| 3 | +summary: A single-producer, single-consumer queue, put together from what the tour has covered. | |
| 4 | +--- | |
| 5 | +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. | |
| 6 | + | |
| 7 | +## The design | |
| 8 | + | |
| 9 | +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`. | |
| 10 | + | |
| 11 | +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. | |
| 12 | + | |
| 13 | +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. | |
| 14 | + | |
| 15 | +## The module | |
| 16 | + | |
| 17 | +```raz Ring | |
| 18 | +module Ring; | |
| 19 | +import Sys; | |
| 20 | + | |
| 21 | +const Size* = 64; | |
| 22 | + | |
| 23 | +type | |
| 24 | + Ring* = record | |
| 25 | + slots: [Size]INT; | |
| 26 | + head, tail: INT; (* items taken, items put; each has one writer *) | |
| 27 | + end; | |
| 28 | + | |
| 29 | +(* v into the ring, waiting while it is full *) | |
| 30 | +proc put*(r: ^Ring; v: INT); | |
| 31 | +var t: INT; | |
| 32 | +begin | |
| 33 | + t := r^.tail; (* mine: an ordinary read *) | |
| 34 | + while t - XADD(ADR(r^.head), 0) = Size do Sys.yield; end; (* full *) | |
| 35 | + r^.slots[t mod Size] := v; | |
| 36 | + _ := XCHG(ADR(r^.tail), t + 1); (* publish the slot *) | |
| 37 | +end; | |
| 38 | + | |
| 39 | +(* the next value, waiting while the ring is empty *) | |
| 40 | +proc take*(r: ^Ring): INT; | |
| 41 | +var h, v: INT; | |
| 42 | +begin | |
| 43 | + h := r^.head; (* mine *) | |
| 44 | + while XADD(ADR(r^.tail), 0) = h do Sys.yield; end; (* empty *) | |
| 45 | + v := r^.slots[h mod Size]; | |
| 46 | + _ := XCHG(ADR(r^.head), h + 1); (* give the slot back *) | |
| 47 | + return v; | |
| 48 | +end; | |
| 49 | + | |
| 50 | +end Ring. | |
| 51 | +``` | |
| 52 | + | |
| 53 | +## Using it | |
| 54 | + | |
| 55 | +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. | |
| 56 | + | |
| 57 | +```raz Pipe run | |
| 58 | +module Pipe; | |
| 59 | +import Out, Fmt, Ring, Thread; | |
| 60 | + | |
| 61 | +const Count = 100000; | |
| 62 | + | |
| 63 | +var | |
| 64 | + ring: Ring.Ring; | |
| 65 | + sum, outOfOrder: INT; | |
| 66 | + | |
| 67 | +proc producer(_arg: ^U8); | |
| 68 | +var i: INT; | |
| 69 | +begin | |
| 70 | + for i := 1 to Count do Ring.put(ADR(ring), i); end; | |
| 71 | +end; | |
| 72 | + | |
| 73 | +proc consumer(_arg: ^U8); | |
| 74 | +var i, v: INT; | |
| 75 | +begin | |
| 76 | + for i := 1 to Count do | |
| 77 | + v := Ring.take(ADR(ring)); | |
| 78 | + if v # i then INC(outOfOrder); end; | |
| 79 | + sum := sum + v; | |
| 80 | + end; | |
| 81 | +end; | |
| 82 | + | |
| 83 | +proc main*; | |
| 84 | +var p, c: ^Thread.Thread; err: ERROR; | |
| 85 | +begin | |
| 86 | + p, err := Thread.spawn(producer, nil); | |
| 87 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 88 | + c, err := Thread.spawn(consumer, nil); | |
| 89 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 90 | + Thread.join(p); | |
| 91 | + Thread.join(c); | |
| 92 | + Fmt.print("{} items, sum {}, {} out of order\n", | |
| 93 | + [Fmt.int(Count), Fmt.int(sum), Fmt.int(outOfOrder)]); | |
| 94 | +end; | |
| 95 | + | |
| 96 | +end Pipe. | |
| 97 | +``` | |
| 98 | + | |
| 99 | +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. | |
| 100 | + | |
| 101 | +## What it used | |
| 102 | + | |
| 103 | +- **Modules** (`Ring`, with its record's own fields unexported). | |
| 104 | +- **Atomics** for the handoff, and an ordering argument for why a slot is complete when its counter moves. | |
| 105 | +- **Threads** from `Thread`, with no C in the program. | |
| 106 | +- **The checks**, which stay on: `slots[t mod Size]` is an indexed array access that can't leave the array, whatever the counters do. | |
| 107 | + | |
| 108 | +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. | |
| 109 | + | |
| 110 | +## Where next | |
| 111 | + | |
| 112 | +That is the end of the tour. A few places to continue: | |
| 113 | + | |
| 114 | +- **[The report](../spec.html)** defines the language, and is short enough to read through. | |
| 115 | +- **`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. | |
| 116 | +- **`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. | |
| 117 | +- **`tools/Doc.raz`** prints what a module exports with its comments: `raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz`. | |
| 118 | +- **`examples/`** holds small programs with the output each should give, and `conform/` holds what any implementation must do. |
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | <em>Raz</em> is Polish for <em>one</em>, as in counting.</p> |
| 5 | 5 | <div class="cta"> |
| 6 | 6 | <a class="btn primary" href="tour/index.html">Take the tour: Raz, Set, Go</a> |
| 7 | + <a class="btn" href="advanced/index.html">Beyond Go</a> | |
| 7 | 8 | <a class="btn" href="#download">Download</a> |
| 8 | 9 | <a class="btn" href="spec.html">Read the report</a> |
| 9 | 10 | </div> |
| @@ -49,6 +50,13 @@ | ||
| 49 | 50 | </ul> |
| 50 | 51 | </div> |
| 51 | 52 | </div> |
| 53 | + | |
| 54 | +<h2>Learn it</h2> | |
| 55 | +<p><a href="tour/index.html"><strong>Raz, Set, Go</strong></a> is a tour of the | |
| 56 | +language in 14 lessons, each with programs you can run. <a | |
| 57 | +href="advanced/index.html"><strong>Beyond Go</strong></a> is the second tour: | |
| 58 | +the library, programs with no run time, procedures in assembly, system calls, | |
| 59 | +volatile accesses, atomics and lock-free code, in 18 more.</p> | |
| 52 | 60 | |
| 53 | 61 | <h2>The language, in writing</h2> |
| 54 | 62 | <p>The language is defined by <a href="spec.html">the report</a>, which is |
| @@ -6,4 +6,4 @@ | ||
| 6 | 6 | first steps; <strong>Set</strong>, how data is laid out; and |
| 7 | 7 | <strong>Go</strong>, making programs that run, fail and finish well. To follow |
| 8 | 8 | along, <a href="../index.html#download">get raz</a> and run any program with |
| 9 | -<code>raz run Name.raz</code>.</p> | |
| 9 | +<code>raz run Name.raz</code>. When you finish, <a href="../advanced/index.html">Beyond Go</a> goes down to the machine.</p> |
| @@ -0,0 +1,114 @@ | ||
| 1 | +title: Hello, world | |
| 2 | +part: Raz | |
| 3 | +summary: A module, an import, a procedure; running, printing, exit status and arguments. | |
| 4 | +--- | |
| 5 | +Every raz program is a module with a `main` procedure. This is the smallest one that does something. | |
| 6 | + | |
| 7 | +```raz Hello run | |
| 8 | +``` | |
| 9 | + | |
| 10 | +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`. | |
| 11 | + | |
| 12 | +## Compiling and running | |
| 13 | + | |
| 14 | +`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. | |
| 15 | + | |
| 16 | +```raz Quiet | |
| 17 | +(* The same program, with a comment: (* ... *) nests, and may stand anywhere. *) | |
| 18 | +module Quiet; | |
| 19 | +import Out; | |
| 20 | + | |
| 21 | +proc main*; | |
| 22 | +begin | |
| 23 | + Out.str("hello, again\n"); | |
| 24 | +end; | |
| 25 | + | |
| 26 | +end Quiet. | |
| 27 | +``` | |
| 28 | + | |
| 29 | +```sh | |
| 30 | +$ raz Quiet.raz | |
| 31 | +$ ./Quiet | |
| 32 | +$ raz run Quiet.raz | |
| 33 | +$ ls -l Quiet | awk '{print $5, "bytes"}' | |
| 34 | +``` | |
| 35 | + | |
| 36 | +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. | |
| 37 | + | |
| 38 | +## What `Out` can write | |
| 39 | + | |
| 40 | +`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 `\\`. | |
| 41 | + | |
| 42 | +```raz Numbers run | |
| 43 | +module Numbers; | |
| 44 | +import Out; | |
| 45 | + | |
| 46 | +proc main*; | |
| 47 | +begin | |
| 48 | + Out.str("seven is "); Out.int(7); Out.ln; | |
| 49 | + Out.str("minus one is "); Out.int(-1); Out.ln; | |
| 50 | + Out.str("255 is 0x"); Out.hex(255, 4); Out.ln; | |
| 51 | + Out.char('R'); Out.char('a'); Out.char('z'); Out.ln; | |
| 52 | + Out.str("a tab:\t|\n"); | |
| 53 | +end; | |
| 54 | + | |
| 55 | +end Numbers. | |
| 56 | +``` | |
| 57 | + | |
| 58 | +`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. | |
| 59 | + | |
| 60 | +## Ending, and the status | |
| 61 | + | |
| 62 | +`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 `$?`. | |
| 63 | + | |
| 64 | +```raz Status | |
| 65 | +module Status; | |
| 66 | +import Out; | |
| 67 | + | |
| 68 | +proc main*: INT; | |
| 69 | +begin | |
| 70 | + Out.str("exiting with 3\n"); | |
| 71 | + return 3; | |
| 72 | +end; | |
| 73 | + | |
| 74 | +end Status. | |
| 75 | +``` | |
| 76 | + | |
| 77 | +```sh | |
| 78 | +$ raz run Status.raz; echo "status $?" | |
| 79 | +``` | |
| 80 | + | |
| 81 | +## Arguments | |
| 82 | + | |
| 83 | +`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. | |
| 84 | + | |
| 85 | +```raz Args | |
| 86 | +module Args; | |
| 87 | +import Out; | |
| 88 | + | |
| 89 | +(* The length of a C string. *) | |
| 90 | +proc len(s: ^U8): INT; | |
| 91 | +var n: INT; | |
| 92 | +begin | |
| 93 | + n := 0; | |
| 94 | + while s[n] # 0 do n := n + 1; end; | |
| 95 | + return n; | |
| 96 | +end; | |
| 97 | + | |
| 98 | +proc main*: INT; | |
| 99 | +var i: INT; s: ^U8; | |
| 100 | +begin | |
| 101 | + for i := 1 to ARGC() - 1 do | |
| 102 | + s := ARGV()[i]; | |
| 103 | + Out.str(s[0..len(s)]); | |
| 104 | + Out.ln; | |
| 105 | + end; | |
| 106 | + return ARGC() - 1; | |
| 107 | +end; | |
| 108 | + | |
| 109 | +end Args. | |
| 110 | +``` | |
| 111 | + | |
| 112 | +```sh | |
| 113 | +$ raz run Args.raz one "two words"; echo "status $?" | |
| 114 | +``` |
| @@ -0,0 +1,144 @@ | ||
| 1 | +title: Modules | |
| 2 | +part: Raz | |
| 3 | +summary: Exports, renaming, the order bodies run in, and what the compiler refuses. | |
| 4 | +--- | |
| 5 | +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`: | |
| 6 | + | |
| 7 | +```raz Greet | |
| 8 | +``` | |
| 9 | + | |
| 10 | +and a program beside it that uses it: | |
| 11 | + | |
| 12 | +```raz Twice run | |
| 13 | +``` | |
| 14 | + | |
| 15 | +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. | |
| 16 | + | |
| 17 | +## Where modules are found | |
| 18 | + | |
| 19 | +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. | |
| 20 | + | |
| 21 | +## Bodies run first, in order | |
| 22 | + | |
| 23 | +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. | |
| 24 | + | |
| 25 | +```raz Base | |
| 26 | +module Base; | |
| 27 | +import Out; | |
| 28 | + | |
| 29 | +var ready*: BOOL; | |
| 30 | + | |
| 31 | +begin | |
| 32 | + Out.str("Base starts\n"); | |
| 33 | + ready := true; | |
| 34 | +end Base. | |
| 35 | +``` | |
| 36 | + | |
| 37 | +```raz Layer | |
| 38 | +module Layer; | |
| 39 | +import Out, Base; | |
| 40 | + | |
| 41 | +const Name* = "Layer"; | |
| 42 | + | |
| 43 | +begin | |
| 44 | + Out.str("Layer starts, Base is ready: "); | |
| 45 | + if Base.ready then Out.str("yes\n"); else Out.str("no\n"); end; | |
| 46 | +end Layer. | |
| 47 | +``` | |
| 48 | + | |
| 49 | +```raz Order run | |
| 50 | +module Order; | |
| 51 | +import Out, Layer, Base; | |
| 52 | + | |
| 53 | +proc main*; | |
| 54 | +begin | |
| 55 | + Out.str("main, after "); Out.str(Layer.Name); Out.char(' '); | |
| 56 | + if Base.ready then Out.str("and Base\n"); end; | |
| 57 | +end; | |
| 58 | + | |
| 59 | +end Order. | |
| 60 | +``` | |
| 61 | + | |
| 62 | +`Base` is imported twice, but starts once, before `Layer`, which needs it. A module with no body doesn't need a `begin` at all. | |
| 63 | + | |
| 64 | +## Exporting more than procedures | |
| 65 | + | |
| 66 | +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. | |
| 67 | + | |
| 68 | +```raz Shape | |
| 69 | +module Shape; | |
| 70 | + | |
| 71 | +const Sides* = 4; | |
| 72 | + | |
| 73 | +type | |
| 74 | + Square* = record | |
| 75 | + side*: INT; (* exported: a user may set it *) | |
| 76 | + id: INT; (* the module's own *) | |
| 77 | + end; | |
| 78 | + | |
| 79 | +var made: INT; (* only Shape may read or write it *) | |
| 80 | + | |
| 81 | +(* a square of that side, numbered in the order they are made *) | |
| 82 | +proc make*(side: INT): Square; | |
| 83 | +var s: Square; | |
| 84 | +begin | |
| 85 | + INC(made); | |
| 86 | + s.side := side; | |
| 87 | + s.id := made; | |
| 88 | + return s; | |
| 89 | +end; | |
| 90 | + | |
| 91 | +proc area*(s: Square): INT; | |
| 92 | +begin | |
| 93 | + return s.side * s.side; | |
| 94 | +end; | |
| 95 | + | |
| 96 | +proc count*: INT; | |
| 97 | +begin | |
| 98 | + return made; | |
| 99 | +end; | |
| 100 | + | |
| 101 | +end Shape. | |
| 102 | +``` | |
| 103 | + | |
| 104 | +```raz Squares run | |
| 105 | +module Squares; | |
| 106 | +import Out, Shape; | |
| 107 | + | |
| 108 | +proc main*; | |
| 109 | +var a, b: Shape.Square; | |
| 110 | +begin | |
| 111 | + a := Shape.make(3); | |
| 112 | + b := Shape.make(5); | |
| 113 | + Out.int(Shape.area(a) + Shape.area(b)); Out.ln; | |
| 114 | + Out.int(Shape.count()); Out.str(" made, "); Out.int(Shape.Sides); | |
| 115 | + Out.str(" sides each\n"); | |
| 116 | +end; | |
| 117 | + | |
| 118 | +end Squares. | |
| 119 | +``` | |
| 120 | + | |
| 121 | +## What the compiler refuses | |
| 122 | + | |
| 123 | +Reaching past an interface is an error, and the error says where. | |
| 124 | + | |
| 125 | +```raz Peek | |
| 126 | +module Peek; | |
| 127 | +import Shape; | |
| 128 | + | |
| 129 | +proc main*; | |
| 130 | +var s: Shape.Square; | |
| 131 | +begin | |
| 132 | + s := Shape.make(2); | |
| 133 | + s.id := 7; | |
| 134 | + Shape.made := 0; | |
| 135 | +end; | |
| 136 | + | |
| 137 | +end Peek. | |
| 138 | +``` | |
| 139 | + | |
| 140 | +```sh | |
| 141 | +$ raz Peek.raz | |
| 142 | +``` | |
| 143 | + | |
| 144 | +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. |
| @@ -0,0 +1,110 @@ | ||
| 1 | +title: Values and conversions | |
| 2 | +part: Raz | |
| 3 | +summary: Sized integers that wrap, reals, bits, and nothing converts unasked. | |
| 4 | +--- | |
| 5 | +```raz Values run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +## Integers | |
| 9 | + | |
| 10 | +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. | |
| 11 | + | |
| 12 | +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. | |
| 13 | + | |
| 14 | +```raz Wrap run | |
| 15 | +module Wrap; | |
| 16 | +import Out; | |
| 17 | + | |
| 18 | +proc main*; | |
| 19 | +var a: U8; b: I8; c: U32; d: INT; | |
| 20 | +begin | |
| 21 | + a := 250; a := a + 10; | |
| 22 | + Out.int(I64(a)); Out.ln; (* 4 *) | |
| 23 | + b := 127; b := b + 1; | |
| 24 | + Out.int(I64(b)); Out.ln; (* -128 *) | |
| 25 | + c := 0; c := c - 1; | |
| 26 | + Out.int(I64(c)); Out.ln; (* 4294967295 *) | |
| 27 | + d := -7; | |
| 28 | + Out.int(d div 2); Out.str(" "); (* -3 *) | |
| 29 | + Out.int(d mod 2); Out.ln; (* -1 *) | |
| 30 | +end; | |
| 31 | + | |
| 32 | +end Wrap. | |
| 33 | +``` | |
| 34 | + | |
| 35 | +## Conversions are written | |
| 36 | + | |
| 37 | +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. | |
| 38 | + | |
| 39 | +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. | |
| 40 | + | |
| 41 | +```raz Mix | |
| 42 | +module Mix; | |
| 43 | +import Out; | |
| 44 | + | |
| 45 | +proc main*; | |
| 46 | +var i: I64; s: []U8; | |
| 47 | +begin | |
| 48 | + s := "four"; | |
| 49 | + i := 3; | |
| 50 | + if i < LEN(s) then Out.str("smaller\n"); end; | |
| 51 | +end; | |
| 52 | + | |
| 53 | +end Mix. | |
| 54 | +``` | |
| 55 | + | |
| 56 | +```sh | |
| 57 | +$ raz Mix.raz | |
| 58 | +``` | |
| 59 | + | |
| 60 | +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. | |
| 61 | + | |
| 62 | +## Bits and booleans | |
| 63 | + | |
| 64 | +`#`, 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`. | |
| 65 | + | |
| 66 | +```raz Bits run | |
| 67 | +module Bits; | |
| 68 | +import Out; | |
| 69 | + | |
| 70 | +proc main*; | |
| 71 | +var flags, mask: U8; | |
| 72 | +begin | |
| 73 | + flags := 0; | |
| 74 | + flags := flags | 1; (* set bit 0 *) | |
| 75 | + flags := flags | (1 shl 3); (* set bit 3 *) | |
| 76 | + mask := 0FH; | |
| 77 | + Out.str("flags 0x"); Out.hex(U64(flags), 2); Out.ln; | |
| 78 | + Out.str("and 0x"); Out.hex(U64(flags & mask), 2); Out.ln; | |
| 79 | + Out.str("xor 0x"); Out.hex(U64(flags xor 0FFH), 2); Out.ln; | |
| 80 | + Out.str("not 0x"); Out.hex(U64(~flags), 2); Out.ln; | |
| 81 | + if (flags & 8) # 0 then Out.str("bit 3 is set\n"); end; | |
| 82 | +end; | |
| 83 | + | |
| 84 | +end Bits. | |
| 85 | +``` | |
| 86 | + | |
| 87 | +## Reals | |
| 88 | + | |
| 89 | +`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. | |
| 90 | + | |
| 91 | +```raz Reals run | |
| 92 | +module Reals; | |
| 93 | +import Fmt, Math; | |
| 94 | + | |
| 95 | +proc main*; | |
| 96 | +var n: INT; x: F64; y: F32; | |
| 97 | +begin | |
| 98 | + n := 22; | |
| 99 | + x := F64(n) / 7.0; | |
| 100 | + y := F32(x); | |
| 101 | + Fmt.print("22/7 = {}\n", [Fmt.real(x, 6)]); | |
| 102 | + Fmt.print("as F32 = {}\n", [Fmt.real(F64(y), 6)]); | |
| 103 | + Fmt.print("sqrt 2 = {}, pi = {}\n", [Fmt.real(Math.sqrt(2.0), 5), Fmt.real(Math.pi, 5)]); | |
| 104 | + Fmt.print("truncated: {} {}\n", [Fmt.int(I64(2.9)), Fmt.int(I64(-2.9))]); | |
| 105 | +end; | |
| 106 | + | |
| 107 | +end Reals. | |
| 108 | +``` | |
| 109 | + | |
| 110 | +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. |
| @@ -0,0 +1,161 @@ | ||
| 1 | +title: Procedures and several results | |
| 2 | +part: Raz | |
| 3 | +summary: Value and var parameters, several results, forward, and procedures as values. | |
| 4 | +--- | |
| 5 | +```raz Procs run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +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. | |
| 9 | + | |
| 10 | +## Value and `var` parameters | |
| 11 | + | |
| 12 | +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. | |
| 13 | + | |
| 14 | +```raz Params run | |
| 15 | +module Params; | |
| 16 | +import Out; | |
| 17 | + | |
| 18 | +proc bump(n: INT); (* changes its own copy *) | |
| 19 | +begin | |
| 20 | + n := n + 1; | |
| 21 | +end; | |
| 22 | + | |
| 23 | +proc bumpIn(var n: INT); (* changes the caller's *) | |
| 24 | +begin | |
| 25 | + n := n + 1; | |
| 26 | +end; | |
| 27 | + | |
| 28 | +proc fill(var a: [4]INT; v: INT); (* an array is copied unless var *) | |
| 29 | +var i: INT; | |
| 30 | +begin | |
| 31 | + for i := 0 to 3 do a[i] := v; end; | |
| 32 | +end; | |
| 33 | + | |
| 34 | +proc main*; | |
| 35 | +var x: INT; a: [4]INT; | |
| 36 | +begin | |
| 37 | + x := 10; | |
| 38 | + bump(x); | |
| 39 | + Out.int(x); Out.ln; (* 10 *) | |
| 40 | + bumpIn(x); | |
| 41 | + Out.int(x); Out.ln; (* 11 *) | |
| 42 | + fill(a, 7); | |
| 43 | + Out.int(a[0] + a[3]); Out.ln; (* 14 *) | |
| 44 | +end; | |
| 45 | + | |
| 46 | +end Params. | |
| 47 | +``` | |
| 48 | + | |
| 49 | +## Several results | |
| 50 | + | |
| 51 | +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. | |
| 52 | + | |
| 53 | +```raz Several run | |
| 54 | +module Several; | |
| 55 | +import Out; | |
| 56 | + | |
| 57 | +proc divmod(a, b: INT): (INT, INT); | |
| 58 | +begin | |
| 59 | + return a div b, a mod b; | |
| 60 | +end; | |
| 61 | + | |
| 62 | +proc minmax(a, b: INT): (INT, INT); | |
| 63 | +begin | |
| 64 | + if a < b then return a, b; end; | |
| 65 | + return b, a; | |
| 66 | +end; | |
| 67 | + | |
| 68 | +proc spread(a, b: INT): (INT, INT); | |
| 69 | +begin | |
| 70 | + return minmax(a, b); (* passes both results on *) | |
| 71 | +end; | |
| 72 | + | |
| 73 | +proc main*; | |
| 74 | +var q, r, lo, hi: INT; | |
| 75 | +begin | |
| 76 | + q, r := divmod(100, 7); | |
| 77 | + Out.int(q); Out.str(" rest "); Out.int(r); Out.ln; | |
| 78 | + lo, hi := spread(9, 4); | |
| 79 | + Out.int(lo); Out.str(" .. "); Out.int(hi); Out.ln; | |
| 80 | + _, r := divmod(-7, 2); (* drop the quotient *) | |
| 81 | + Out.int(r); Out.ln; | |
| 82 | +end; | |
| 83 | + | |
| 84 | +end Several. | |
| 85 | +``` | |
| 86 | + | |
| 87 | +## Recursion, and `forward` | |
| 88 | + | |
| 89 | +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. | |
| 90 | + | |
| 91 | +```raz Recur run | |
| 92 | +module Recur; | |
| 93 | +import Out; | |
| 94 | + | |
| 95 | +proc gcd(a, b: INT): INT; | |
| 96 | +begin | |
| 97 | + if b = 0 then return a; end; | |
| 98 | + return gcd(b, a mod b); | |
| 99 | +end; | |
| 100 | + | |
| 101 | +proc isOdd(n: INT): BOOL; forward; | |
| 102 | + | |
| 103 | +proc isEven(n: INT): BOOL; | |
| 104 | +begin | |
| 105 | + if n = 0 then return true; end; | |
| 106 | + return isOdd(n - 1); | |
| 107 | +end; | |
| 108 | + | |
| 109 | +proc isOdd(n: INT): BOOL; | |
| 110 | +begin | |
| 111 | + if n = 0 then return false; end; | |
| 112 | + return isEven(n - 1); | |
| 113 | +end; | |
| 114 | + | |
| 115 | +proc main*; | |
| 116 | +begin | |
| 117 | + Out.int(gcd(84, 36)); Out.ln; | |
| 118 | + if isEven(10) and isOdd(7) then Out.str("parity works\n"); end; | |
| 119 | +end; | |
| 120 | + | |
| 121 | +end Recur. | |
| 122 | +``` | |
| 123 | + | |
| 124 | +## Procedures are values | |
| 125 | + | |
| 126 | +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. | |
| 127 | + | |
| 128 | +```raz Table run | |
| 129 | +module Table; | |
| 130 | +import Out; | |
| 131 | + | |
| 132 | +type Op = proc(a, b: INT): INT; | |
| 133 | + | |
| 134 | +proc add(a, b: INT): INT; begin return a + b; end; | |
| 135 | +proc sub(a, b: INT): INT; begin return a - b; end; | |
| 136 | +proc mul(a, b: INT): INT; begin return a * b; end; | |
| 137 | + | |
| 138 | +proc apply(f: Op; a, b: INT): INT; | |
| 139 | +begin | |
| 140 | + return f(a, b); | |
| 141 | +end; | |
| 142 | + | |
| 143 | +proc main*; | |
| 144 | +var ops: [3]Op; names: [3][]U8; i: INT; | |
| 145 | +begin | |
| 146 | + ops := [add, sub, mul]; | |
| 147 | + names := ["add", "sub", "mul"]; | |
| 148 | + for i := 0 to 2 do | |
| 149 | + Out.str(names[i]); Out.str(": "); | |
| 150 | + Out.int(apply(ops[i], 12, 5)); Out.ln; | |
| 151 | + end; | |
| 152 | +end; | |
| 153 | + | |
| 154 | +end Table. | |
| 155 | +``` | |
| 156 | + | |
| 157 | +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. | |
| 158 | + | |
| 159 | +## Dropped results | |
| 160 | + | |
| 161 | +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 `_`. |
| @@ -0,0 +1,181 @@ | ||
| 1 | +title: Arrays, slices and strings | |
| 2 | +part: Set | |
| 3 | +summary: Five in a row, a window onto them, bytes in UTF-8, and checks on every index. | |
| 4 | +--- | |
| 5 | +```raz Slices run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +## Arrays | |
| 9 | + | |
| 10 | +`[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. | |
| 11 | + | |
| 12 | +```raz Arrays run | |
| 13 | +module Arrays; | |
| 14 | +import Out; | |
| 15 | + | |
| 16 | +proc main*; | |
| 17 | +var a, b: [4]INT; grid: [3][3]INT; i, j: INT; | |
| 18 | +begin | |
| 19 | + a := [1, 2, 3, 4]; | |
| 20 | + b := a; (* a copy *) | |
| 21 | + b[0] := 99; | |
| 22 | + Out.int(a[0]); Out.char(' '); Out.int(b[0]); Out.ln; | |
| 23 | + if a # b then Out.str("they differ now\n"); end; | |
| 24 | + | |
| 25 | + for i := 0 to 2 do | |
| 26 | + for j := 0 to 2 do grid[i][j] := i * 3 + j; end; | |
| 27 | + end; | |
| 28 | + Out.int(grid[2][1]); Out.ln; (* 7 *) | |
| 29 | + Out.int(LEN(grid)); Out.char('x'); Out.int(LEN(grid[0])); Out.ln; | |
| 30 | +end; | |
| 31 | + | |
| 32 | +end Arrays. | |
| 33 | +``` | |
| 34 | + | |
| 35 | +## Slices | |
| 36 | + | |
| 37 | +`[]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. | |
| 38 | + | |
| 39 | +```raz Windows run | |
| 40 | +module Windows; | |
| 41 | +import Out; | |
| 42 | + | |
| 43 | +proc zero(s: []INT); | |
| 44 | +var i: INT; | |
| 45 | +begin | |
| 46 | + for i := 0 to LEN(s) - 1 do s[i] := 0; end; | |
| 47 | +end; | |
| 48 | + | |
| 49 | +proc show(s: []INT); | |
| 50 | +var i: INT; | |
| 51 | +begin | |
| 52 | + for i := 0 to LEN(s) - 1 do Out.int(s[i]); Out.char(' '); end; | |
| 53 | + Out.ln; | |
| 54 | +end; | |
| 55 | + | |
| 56 | +proc main*; | |
| 57 | +var a: [8]INT; i: INT; | |
| 58 | +begin | |
| 59 | + for i := 0 to 7 do a[i] := i + 1; end; | |
| 60 | + zero(a[2..5]); (* a window onto a *) | |
| 61 | + show(a); (* 1 2 0 0 0 6 7 8 *) | |
| 62 | + show(a[6..8]); | |
| 63 | + show(a[3..3]); (* empty: prints just a line feed *) | |
| 64 | +end; | |
| 65 | + | |
| 66 | +end Windows. | |
| 67 | +``` | |
| 68 | + | |
| 69 | +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. | |
| 70 | + | |
| 71 | +## `COPY` | |
| 72 | + | |
| 73 | +`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)`. | |
| 74 | + | |
| 75 | +```raz Moves run | |
| 76 | +module Moves; | |
| 77 | +import Out; | |
| 78 | + | |
| 79 | +proc main*; | |
| 80 | +var a: [6]INT; i: INT; | |
| 81 | +begin | |
| 82 | + a := [1, 2, 3, 4, 5, 0]; | |
| 83 | + COPY(a[1..6], a[0..5]); (* shift everything one place up *) | |
| 84 | + for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end; | |
| 85 | + Out.ln; | |
| 86 | +end; | |
| 87 | + | |
| 88 | +end Moves. | |
| 89 | +``` | |
| 90 | + | |
| 91 | +## Strings | |
| 92 | + | |
| 93 | +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. | |
| 94 | + | |
| 95 | +```raz Words run | |
| 96 | +module Words; | |
| 97 | +import Out, Str; | |
| 98 | + | |
| 99 | +proc main*; | |
| 100 | +var s: []U8; n: I64; ok: BOOL; name: [8]U8; | |
| 101 | +begin | |
| 102 | + s := "hello, world"; | |
| 103 | + Out.str(s[7..LEN(s)]); Out.ln; | |
| 104 | + if s[0..5] = "hello" then Out.str("it says hello\n"); end; | |
| 105 | + Out.int(Str.find(s, "world")); Out.ln; (* 7 *) | |
| 106 | + Out.int(Str.find(s, "xyz")); Out.ln; (* -1 *) | |
| 107 | + if Str.hasPrefix(s, "hell") then Out.str("prefix\n"); end; | |
| 108 | + Out.int(Str.cmp("apple", "banana")); Out.ln; (* -1 *) | |
| 109 | + | |
| 110 | + n, ok := Str.toInt("-1234"); | |
| 111 | + if ok then Out.int(n + 1); Out.ln; end; | |
| 112 | + n, ok := Str.toInt("12x"); | |
| 113 | + if not ok then Out.str("not a number\n"); end; | |
| 114 | + | |
| 115 | + name := "raz"; (* a copy, the program's own *) | |
| 116 | + name[0] := 'R'; | |
| 117 | + Out.str(name[0..3]); Out.ln; | |
| 118 | +end; | |
| 119 | + | |
| 120 | +end Words. | |
| 121 | +``` | |
| 122 | + | |
| 123 | +## UTF-8 | |
| 124 | + | |
| 125 | +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. | |
| 126 | + | |
| 127 | +```raz Runes run | |
| 128 | +module Runes; | |
| 129 | +import Out, Str; | |
| 130 | + | |
| 131 | +(* the characters of s, not its bytes *) | |
| 132 | +proc chars(s: []U8): INT; | |
| 133 | +var i, n, size: INT; | |
| 134 | +begin | |
| 135 | + i := 0; | |
| 136 | + n := 0; | |
| 137 | + while i < LEN(s) do | |
| 138 | + _, size := Str.decode(s[i..LEN(s)]); | |
| 139 | + INC(i, size); | |
| 140 | + INC(n); | |
| 141 | + end; | |
| 142 | + return n; | |
| 143 | +end; | |
| 144 | + | |
| 145 | +proc main*; | |
| 146 | +var s: []U8; c: I32; size: INT; bytes: [4]U8; k: INT; | |
| 147 | +begin | |
| 148 | + s := "caf\u{E9} \u{3BB}"; | |
| 149 | + Out.int(LEN(s)); Out.str(" bytes, "); | |
| 150 | + Out.int(chars(s)); Out.str(" characters\n"); | |
| 151 | + c, size := Str.decode(s[3..LEN(s)]); | |
| 152 | + Out.int(I64(c)); Out.str(" took "); Out.int(size); Out.str(" bytes\n"); | |
| 153 | + bytes, k := Str.encode(955); | |
| 154 | + Out.str(bytes[0..k]); Out.ln; | |
| 155 | +end; | |
| 156 | + | |
| 157 | +end Runes. | |
| 158 | +``` | |
| 159 | + | |
| 160 | +## Loops over lengths | |
| 161 | + | |
| 162 | +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. | |
| 163 | + | |
| 164 | +```raz Loops run | |
| 165 | +module Loops; | |
| 166 | +import Out; | |
| 167 | + | |
| 168 | +proc main*; | |
| 169 | +var i: INT; | |
| 170 | +begin | |
| 171 | + for i := 10 to 0 by -5 do Out.int(i); Out.char(' '); end; | |
| 172 | + Out.ln; | |
| 173 | + i := 1; | |
| 174 | + while i < 100 do i := i * 3; end; | |
| 175 | + Out.int(i); Out.ln; | |
| 176 | + repeat DEC(i, 30); until i < 0; | |
| 177 | + Out.int(i); Out.ln; | |
| 178 | +end; | |
| 179 | + | |
| 180 | +end Loops. | |
| 181 | +``` |
| @@ -0,0 +1,138 @@ | ||
| 1 | +title: Records and pointers | |
| 2 | +part: Set | |
| 3 | +summary: Laid out as C lays out a struct, packed records, pointers and nil. | |
| 4 | +--- | |
| 5 | +```raz Boxes run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +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. | |
| 9 | + | |
| 10 | +## Copies and literals | |
| 11 | + | |
| 12 | +Assigning a record copies it whole, as with an array. A record is compared field by field by writing the comparison, not by `=`. | |
| 13 | + | |
| 14 | +```raz Points run | |
| 15 | +module Points; | |
| 16 | +import Out; | |
| 17 | + | |
| 18 | +type Point = record x, y: INT; end; | |
| 19 | + | |
| 20 | +proc show(p: Point); | |
| 21 | +begin | |
| 22 | + Out.char('('); Out.int(p.x); Out.str(", "); Out.int(p.y); Out.char(')'); | |
| 23 | +end; | |
| 24 | + | |
| 25 | +proc mirror(p: Point): Point; | |
| 26 | +begin | |
| 27 | + return {x: p.y, y: p.x}; | |
| 28 | +end; | |
| 29 | + | |
| 30 | +proc main*; | |
| 31 | +var a, b: Point; | |
| 32 | +begin | |
| 33 | + a := {x: 3, y: 4}; | |
| 34 | + b := a; (* a copy *) | |
| 35 | + b.x := 30; | |
| 36 | + show(a); show(b); show(mirror(a)); Out.ln; | |
| 37 | + a := {y: 9}; (* x is zero *) | |
| 38 | + show(a); Out.ln; | |
| 39 | +end; | |
| 40 | + | |
| 41 | +end Points. | |
| 42 | +``` | |
| 43 | + | |
| 44 | +## Layout | |
| 45 | + | |
| 46 | +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. | |
| 47 | + | |
| 48 | +```raz Layout run | |
| 49 | +module Layout; | |
| 50 | +import Out; | |
| 51 | + | |
| 52 | +type | |
| 53 | + Loose = record a: U8; b: U32; c: U8; end; | |
| 54 | + Tight = packed record a: U8; b: U32; c: U8; end; | |
| 55 | + | |
| 56 | +proc main*; | |
| 57 | +begin | |
| 58 | + Out.str("loose: "); Out.int(SIZE(Loose)); Out.ln; (* 12 *) | |
| 59 | + Out.str("tight: "); Out.int(SIZE(Tight)); Out.ln; (* 6 *) | |
| 60 | + Out.str("INT: "); Out.int(SIZE(INT)); Out.ln; | |
| 61 | + Out.str("[5]I16: "); Out.int(SIZE([5]I16)); Out.ln; | |
| 62 | +end; | |
| 63 | + | |
| 64 | +end Layout. | |
| 65 | +``` | |
| 66 | + | |
| 67 | +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`. | |
| 68 | + | |
| 69 | +## Pointers | |
| 70 | + | |
| 71 | +`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. | |
| 72 | + | |
| 73 | +```raz Pointers run | |
| 74 | +module Pointers; | |
| 75 | +import Out; | |
| 76 | + | |
| 77 | +type Counter = record hits: INT; name: []U8; end; | |
| 78 | + | |
| 79 | +proc hit(c: ^Counter); | |
| 80 | +begin | |
| 81 | + if c = nil then return; end; | |
| 82 | + INC(c^.hits); | |
| 83 | +end; | |
| 84 | + | |
| 85 | +proc swap(a, b: ^INT); | |
| 86 | +var t: INT; | |
| 87 | +begin | |
| 88 | + t := a^; | |
| 89 | + a^ := b^; | |
| 90 | + b^ := t; | |
| 91 | +end; | |
| 92 | + | |
| 93 | +proc main*; | |
| 94 | +var c: Counter; x, y: INT; p: ^INT; | |
| 95 | +begin | |
| 96 | + c.name := "front door"; | |
| 97 | + hit(ADR(c)); hit(ADR(c)); hit(nil); | |
| 98 | + Out.str(c.name); Out.str(": "); Out.int(c.hits); Out.ln; | |
| 99 | + x := 1; y := 2; | |
| 100 | + swap(ADR(x), ADR(y)); | |
| 101 | + Out.int(x); Out.char(' '); Out.int(y); Out.ln; | |
| 102 | + p := ADR(x); | |
| 103 | + p^ := p^ + 40; | |
| 104 | + Out.int(x); Out.ln; | |
| 105 | +end; | |
| 106 | + | |
| 107 | +end Pointers. | |
| 108 | +``` | |
| 109 | + | |
| 110 | +## Pointers that link | |
| 111 | + | |
| 112 | +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. | |
| 113 | + | |
| 114 | +```raz Chain run | |
| 115 | +module Chain; | |
| 116 | +import Out; | |
| 117 | + | |
| 118 | +type Node = record next: ^Node; val: INT; end; | |
| 119 | + | |
| 120 | +proc main*; | |
| 121 | +var nodes: [4]Node; head, n: ^Node; i: INT; | |
| 122 | +begin | |
| 123 | + head := nil; | |
| 124 | + for i := 0 to 3 do | |
| 125 | + nodes[i].val := (i + 1) * 10; | |
| 126 | + nodes[i].next := head; (* each new one in front *) | |
| 127 | + head := ADR(nodes[i]); | |
| 128 | + end; | |
| 129 | + n := head; | |
| 130 | + while n # nil do | |
| 131 | + Out.int(n^.val); Out.char(' '); | |
| 132 | + n := n^.next; | |
| 133 | + end; | |
| 134 | + Out.ln; | |
| 135 | +end; | |
| 136 | + | |
| 137 | +end Chain. | |
| 138 | +``` |
| @@ -0,0 +1,165 @@ | ||
| 1 | +title: Enumerations, sets, variants and match | |
| 2 | +part: Set | |
| 3 | +summary: Names in order, sets as bits, and cases the compiler makes you handle. | |
| 4 | +--- | |
| 5 | +```raz Shapes run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +## Enumerations | |
| 9 | + | |
| 10 | +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. | |
| 11 | + | |
| 12 | +```raz Days run | |
| 13 | +module Days; | |
| 14 | +import Out; | |
| 15 | + | |
| 16 | +type Day = (mon, tue, wed, thu, fri, sat, sun); | |
| 17 | + | |
| 18 | +proc name(d: Day): []U8; | |
| 19 | +begin | |
| 20 | + match d of | |
| 21 | + | mon: return "Monday"; | |
| 22 | + | tue: return "Tuesday"; | |
| 23 | + | wed: return "Wednesday"; | |
| 24 | + | thu: return "Thursday"; | |
| 25 | + | fri: return "Friday"; | |
| 26 | + | sat: return "Saturday"; | |
| 27 | + | sun: return "Sunday"; | |
| 28 | + end; | |
| 29 | +end; | |
| 30 | + | |
| 31 | +proc main*; | |
| 32 | +var d: Day; | |
| 33 | +begin | |
| 34 | + for d := mon to sun do | |
| 35 | + Out.int(I64(d)); Out.str(" "); Out.str(name(d)); | |
| 36 | + if d >= sat then Out.str(" (weekend)"); end; | |
| 37 | + Out.ln; | |
| 38 | + end; | |
| 39 | + d := Day(4); | |
| 40 | + Out.str(name(d)); Out.ln; | |
| 41 | +end; | |
| 42 | + | |
| 43 | +end Days. | |
| 44 | +``` | |
| 45 | + | |
| 46 | +## Sets | |
| 47 | + | |
| 48 | +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. | |
| 49 | + | |
| 50 | +```raz Perms run | |
| 51 | +module Perms; | |
| 52 | +import Out; | |
| 53 | + | |
| 54 | +type | |
| 55 | + Perm = (x, w, r); (* bits 0, 1, 2, as chmod has them *) | |
| 56 | + Perms = set of Perm; | |
| 57 | + | |
| 58 | +proc show(p: Perms); | |
| 59 | +begin | |
| 60 | + if r in p then Out.char('r'); else Out.char('-'); end; | |
| 61 | + if w in p then Out.char('w'); else Out.char('-'); end; | |
| 62 | + if x in p then Out.char('x'); else Out.char('-'); end; | |
| 63 | +end; | |
| 64 | + | |
| 65 | +proc main*; | |
| 66 | +var user, group, mine: Perms; | |
| 67 | +begin | |
| 68 | + user := {r, w, x}; | |
| 69 | + group := {r, x}; | |
| 70 | + show(user); Out.char(' '); show(group); Out.ln; | |
| 71 | + show(user * group); Out.char(' '); (* both: r-x *) | |
| 72 | + show(user - group); Out.char(' '); (* only user: -w- *) | |
| 73 | + show(user - {w}); Out.ln; (* r-x *) | |
| 74 | + mine := group; | |
| 75 | + if mine = {r, x} then Out.str("same as group\n"); end; | |
| 76 | + Out.int(I64(U8(user))); Out.ln; (* 7: a set is its bits *) | |
| 77 | +end; | |
| 78 | + | |
| 79 | +end Perms. | |
| 80 | +``` | |
| 81 | + | |
| 82 | +## Variants | |
| 83 | + | |
| 84 | +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. | |
| 85 | + | |
| 86 | +```raz Tokens run | |
| 87 | +module Tokens; | |
| 88 | +import Out; | |
| 89 | + | |
| 90 | +type | |
| 91 | + Token = variant | |
| 92 | + number(n: INT); | |
| 93 | + plus; | |
| 94 | + times; | |
| 95 | + word(s: []U8); | |
| 96 | + end; | |
| 97 | + | |
| 98 | +proc describe(t: Token); | |
| 99 | +begin | |
| 100 | + match t of | |
| 101 | + | number(n): Out.str("number "); Out.int(n); | |
| 102 | + | plus: Out.str("plus"); | |
| 103 | + | times: Out.str("times"); | |
| 104 | + | word(s): Out.str("word '"); Out.str(s); Out.char('\''); | |
| 105 | + end; | |
| 106 | + Out.ln; | |
| 107 | +end; | |
| 108 | + | |
| 109 | +(* evaluates tokens in reverse Polish; assumes the input is well formed *) | |
| 110 | +proc eval(ts: []Token): INT; | |
| 111 | +var stack: [16]INT; top, i, b: INT; | |
| 112 | +begin | |
| 113 | + top := 0; | |
| 114 | + for i := 0 to LEN(ts) - 1 do | |
| 115 | + match ts[i] of | |
| 116 | + | number(n): stack[top] := n; INC(top); | |
| 117 | + | plus: b := stack[top - 1]; DEC(top); stack[top - 1] := stack[top - 1] + b; | |
| 118 | + | times: b := stack[top - 1]; DEC(top); stack[top - 1] := stack[top - 1] * b; | |
| 119 | + | else: | |
| 120 | + end; | |
| 121 | + end; | |
| 122 | + return stack[0]; | |
| 123 | +end; | |
| 124 | + | |
| 125 | +proc main*; | |
| 126 | +var ts: [5]Token; i: INT; | |
| 127 | +begin | |
| 128 | + ts := [number(3), number(4), plus, number(5), times]; (* (3 + 4) * 5 *) | |
| 129 | + for i := 0 to 4 do describe(ts[i]); end; | |
| 130 | + Out.int(eval(ts)); Out.ln; | |
| 131 | + describe(word("hello")); | |
| 132 | +end; | |
| 133 | + | |
| 134 | +end Tokens. | |
| 135 | +``` | |
| 136 | + | |
| 137 | +## Matching integers | |
| 138 | + | |
| 139 | +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. | |
| 140 | + | |
| 141 | +```raz Classify run | |
| 142 | +module Classify; | |
| 143 | +import Out; | |
| 144 | + | |
| 145 | +proc kind(c: I32): []U8; | |
| 146 | +begin | |
| 147 | + match c of | |
| 148 | + | ' ', '\t', '\n': return "space"; | |
| 149 | + | '0' .. '9': return "digit"; | |
| 150 | + | 'a' .. 'z', 'A' .. 'Z', '_': return "letter"; | |
| 151 | + | else: return "other"; | |
| 152 | + end; | |
| 153 | +end; | |
| 154 | + | |
| 155 | +proc main*; | |
| 156 | +var s: []U8; i: INT; | |
| 157 | +begin | |
| 158 | + s := "x1 + _y"; | |
| 159 | + for i := 0 to LEN(s) - 1 do | |
| 160 | + Out.char(s[i]); Out.str(" is "); Out.str(kind(I32(s[i]))); Out.ln; | |
| 161 | + end; | |
| 162 | +end; | |
| 163 | + | |
| 164 | +end Classify. | |
| 165 | +``` |
| @@ -0,0 +1,119 @@ | ||
| 1 | +title: Memory and allocators | |
| 2 | +part: Set | |
| 3 | +summary: No garbage collector; you choose where memory comes from, and what happens when it runs out. | |
| 4 | +--- | |
| 5 | +```raz Stack run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +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. | |
| 9 | + | |
| 10 | +## Why an allocator is a parameter | |
| 11 | + | |
| 12 | +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. | |
| 13 | + | |
| 14 | +```raz Pool run | |
| 15 | +module Pool; | |
| 16 | +import Out, Mem, Arena; | |
| 17 | + | |
| 18 | +type Item = record id: INT; next: ^Item; end; | |
| 19 | + | |
| 20 | +(* n items, linked; or nil if the allocator ran dry (what came is lost with it) *) | |
| 21 | +proc make(n: INT; a: ^Mem.Allocator): ^Item; | |
| 22 | +var head, it: ^Item; i: INT; | |
| 23 | +begin | |
| 24 | + head := nil; | |
| 25 | + for i := 1 to n do | |
| 26 | + NEW(it, a); | |
| 27 | + if it = nil then return nil; end; | |
| 28 | + it^.id := i; | |
| 29 | + it^.next := head; | |
| 30 | + head := it; | |
| 31 | + end; | |
| 32 | + return head; | |
| 33 | +end; | |
| 34 | + | |
| 35 | +proc count(it: ^Item): INT; | |
| 36 | +var n: INT; | |
| 37 | +begin | |
| 38 | + n := 0; | |
| 39 | + while it # nil do INC(n); it := it^.next; end; | |
| 40 | + return n; | |
| 41 | +end; | |
| 42 | + | |
| 43 | +proc main*; | |
| 44 | +var ar: Arena.Arena; small: Arena.Arena; list: ^Item; | |
| 45 | +begin | |
| 46 | + if not Arena.init(ADR(ar), 1000000) then return; end; | |
| 47 | + list := make(1000, ADR(ar.base)); | |
| 48 | + Out.int(count(list)); Out.str(" items from a big arena\n"); | |
| 49 | + Arena.reset(ADR(ar)); (* every allocation forgotten *) | |
| 50 | + list := make(10, ADR(ar.base)); | |
| 51 | + Out.int(count(list)); Out.str(" after a reset\n"); | |
| 52 | + Arena.done(ADR(ar)); | |
| 53 | + | |
| 54 | + if not Arena.init(ADR(small), 4096) then return; end; | |
| 55 | + list := make(1000, ADR(small.base)); | |
| 56 | + if list = nil then Out.str("a small arena ran out, and said so\n"); end; | |
| 57 | + Arena.done(ADR(small)); | |
| 58 | +end; | |
| 59 | + | |
| 60 | +end Pool. | |
| 61 | +``` | |
| 62 | + | |
| 63 | +The run-out case is an ordinary `nil` to test, not an exception that unwinds past your code. | |
| 64 | + | |
| 65 | +## The heap | |
| 66 | + | |
| 67 | +`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. | |
| 68 | + | |
| 69 | +```raz Free run | |
| 70 | +module Free; | |
| 71 | +import Out, Mem, Heap; | |
| 72 | + | |
| 73 | +type Cell = record val: INT; end; | |
| 74 | + | |
| 75 | +proc main*; | |
| 76 | +var a, b: ^Cell; i, total: INT; | |
| 77 | +begin | |
| 78 | + for i := 1 to 5 do | |
| 79 | + NEW(a, Heap.heap); | |
| 80 | + a^.val := i * i; | |
| 81 | + total := total + a^.val; | |
| 82 | + Mem.free(Heap.heap, ^U8(a)); (* freed at once: its block is reused *) | |
| 83 | + end; | |
| 84 | + NEW(b, Heap.heap); | |
| 85 | + Out.int(total); Out.char(' '); Out.int(b^.val); Out.ln; (* a new block is zeroed *) | |
| 86 | + Mem.free(Heap.heap, ^U8(b)); | |
| 87 | +end; | |
| 88 | + | |
| 89 | +end Free. | |
| 90 | +``` | |
| 91 | + | |
| 92 | +## Buffers that grow | |
| 93 | + | |
| 94 | +`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. | |
| 95 | + | |
| 96 | +```raz Build run | |
| 97 | +module Build; | |
| 98 | +import Out, Buf, Heap; | |
| 99 | + | |
| 100 | +proc main*; | |
| 101 | +var b: Buf.Buf; i: INT; | |
| 102 | +begin | |
| 103 | + Buf.init(ADR(b), Heap.heap); | |
| 104 | + defer Buf.done(ADR(b)); | |
| 105 | + for i := 1 to 5 do | |
| 106 | + Buf.str(ADR(b), "item "); | |
| 107 | + Buf.add(ADR(b), U8('0' + i)); | |
| 108 | + Buf.add(ADR(b), ','); | |
| 109 | + end; | |
| 110 | + Out.str(Buf.bytes(ADR(b))); Out.ln; | |
| 111 | + Out.int(b.len); Out.str(" bytes\n"); | |
| 112 | +end; | |
| 113 | + | |
| 114 | +end Build. | |
| 115 | +``` | |
| 116 | + | |
| 117 | +## Pages | |
| 118 | + | |
| 119 | +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. |
| @@ -0,0 +1,140 @@ | ||
| 1 | +title: Errors | |
| 2 | +part: Go | |
| 3 | +summary: A second result, compared by identity; passing errors up; and no exceptions. | |
| 4 | +--- | |
| 5 | +```raz Errors run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +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. | |
| 9 | + | |
| 10 | +## Handling them by kind | |
| 11 | + | |
| 12 | +Because an error is compared by identity, a caller can handle the cases it knows and pass on the rest. | |
| 13 | + | |
| 14 | +```raz Parse run | |
| 15 | +module Parse; | |
| 16 | +import Out, Str; | |
| 17 | + | |
| 18 | +const | |
| 19 | + Empty*: ERROR = "nothing to read"; | |
| 20 | + Bad*: ERROR = "not a number"; | |
| 21 | + Range*: ERROR = "out of range"; | |
| 22 | + | |
| 23 | +(* a percentage, 0 to 100 *) | |
| 24 | +proc percent(s: []U8): (INT, ERROR); | |
| 25 | +var n: I64; ok: BOOL; | |
| 26 | +begin | |
| 27 | + if LEN(s) = 0 then return 0, Empty; end; | |
| 28 | + n, ok := Str.toInt(s); | |
| 29 | + if not ok then return 0, Bad; end; | |
| 30 | + if (n < 0) or (n > 100) then return 0, Range; end; | |
| 31 | + return INT(n), nil; | |
| 32 | +end; | |
| 33 | + | |
| 34 | +proc main*; | |
| 35 | +var inputs: [4][]U8; i, n: INT; err: ERROR; | |
| 36 | +begin | |
| 37 | + inputs := ["42", "", "forty", "140"]; | |
| 38 | + for i := 0 to 3 do | |
| 39 | + n, err := percent(inputs[i]); | |
| 40 | + if err = nil then | |
| 41 | + Out.int(n); Out.str("%"); | |
| 42 | + elsif err = Empty then | |
| 43 | + Out.str("(skipped)"); | |
| 44 | + else | |
| 45 | + Out.str("error: "); Out.str(MSG(err)); | |
| 46 | + end; | |
| 47 | + Out.ln; | |
| 48 | + end; | |
| 49 | +end; | |
| 50 | + | |
| 51 | +end Parse. | |
| 52 | +``` | |
| 53 | + | |
| 54 | +## Passing errors up | |
| 55 | + | |
| 56 | +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. | |
| 57 | + | |
| 58 | +```raz Layers run | |
| 59 | +module Layers; | |
| 60 | +import Out, Str; | |
| 61 | + | |
| 62 | +const Missing*: ERROR = "key missing"; | |
| 63 | + | |
| 64 | +(* the number after "n=" in a line like "n=17" *) | |
| 65 | +proc value(line: []U8): (INT, ERROR); | |
| 66 | +var n: I64; ok: BOOL; | |
| 67 | +begin | |
| 68 | + if not Str.hasPrefix(line, "n=") then return 0, Missing; end; | |
| 69 | + n, ok := Str.toInt(line[2..LEN(line)]); | |
| 70 | + if not ok then return 0, Missing; end; | |
| 71 | + return INT(n), nil; | |
| 72 | +end; | |
| 73 | + | |
| 74 | +(* the sum of the values of two lines *) | |
| 75 | +proc sum(a, b: []U8): (INT, ERROR); | |
| 76 | +var x, y: INT; err: ERROR; | |
| 77 | +begin | |
| 78 | + x, err := value(a); | |
| 79 | + if err # nil then return 0, err; end; (* passed up *) | |
| 80 | + y, err := value(b); | |
| 81 | + if err # nil then return 0, err; end; | |
| 82 | + return x + y, nil; | |
| 83 | +end; | |
| 84 | + | |
| 85 | +proc main*; | |
| 86 | +var n: INT; err: ERROR; | |
| 87 | +begin | |
| 88 | + n, err := sum("n=40", "n=2"); | |
| 89 | + if err = nil then Out.int(n); Out.ln; end; | |
| 90 | + n, err := sum("n=40", "x=2"); | |
| 91 | + if err # nil then Out.str("sum failed: "); Out.str(MSG(err)); Out.ln; end; | |
| 92 | +end; | |
| 93 | + | |
| 94 | +end Layers. | |
| 95 | +``` | |
| 96 | + | |
| 97 | +## When the library reports errors | |
| 98 | + | |
| 99 | +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. | |
| 100 | + | |
| 101 | +```raz Probe run | |
| 102 | +module Probe; | |
| 103 | +import Out, Sys; | |
| 104 | + | |
| 105 | +proc main*; | |
| 106 | +var fd: INT; | |
| 107 | +begin | |
| 108 | + fd := Sys.openRead("/no/such/file"); | |
| 109 | + if fd < 0 then | |
| 110 | + Out.str("open failed, errno "); Out.int(-fd); Out.ln; (* 2: ENOENT *) | |
| 111 | + end; | |
| 112 | + fd := Sys.openRead("/dev/null"); | |
| 113 | + if fd >= 0 then | |
| 114 | + Out.str("open worked\n"); | |
| 115 | + Sys.close(fd); | |
| 116 | + end; | |
| 117 | +end; | |
| 118 | + | |
| 119 | +end Probe. | |
| 120 | +``` | |
| 121 | + | |
| 122 | +## When there is nothing to do but stop | |
| 123 | + | |
| 124 | +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. | |
| 125 | + | |
| 126 | +```raz Giveup | |
| 127 | +module Giveup; | |
| 128 | +import Rt; | |
| 129 | + | |
| 130 | +proc main*; | |
| 131 | +begin | |
| 132 | + Rt.stop("the table is corrupt"); | |
| 133 | +end; | |
| 134 | + | |
| 135 | +end Giveup. | |
| 136 | +``` | |
| 137 | + | |
| 138 | +```sh | |
| 139 | +$ raz run Giveup.raz; echo "status $?" | |
| 140 | +``` |
| @@ -0,0 +1,107 @@ | ||
| 1 | +title: Defer | |
| 2 | +part: Go | |
| 3 | +summary: Clean up beside the line that needs it, in the right order, on every way out. | |
| 4 | +--- | |
| 5 | +```raz Defers run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +`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. | |
| 9 | + | |
| 10 | +## The order, and a `return` value | |
| 11 | + | |
| 12 | +A `return e;` evaluates `e` before the deferred statements run, so the value is what it was at the return. | |
| 13 | + | |
| 14 | +```raz Order run | |
| 15 | +module Order; | |
| 16 | +import Out; | |
| 17 | + | |
| 18 | +var counter: INT; | |
| 19 | + | |
| 20 | +proc next(): INT; | |
| 21 | +begin | |
| 22 | + defer INC(counter); | |
| 23 | + return counter; (* the old value is returned; then counter grows *) | |
| 24 | +end; | |
| 25 | + | |
| 26 | +proc nest; | |
| 27 | +begin | |
| 28 | + defer Out.str("1 "); | |
| 29 | + defer Out.str("2 "); | |
| 30 | + defer Out.str("3 "); | |
| 31 | + Out.str("body: "); | |
| 32 | +end; | |
| 33 | + | |
| 34 | +proc main*; | |
| 35 | +var a, b: INT; | |
| 36 | +begin | |
| 37 | + a := next(); | |
| 38 | + b := next(); | |
| 39 | + Out.int(a); Out.char(' '); Out.int(b); Out.char(' '); Out.int(counter); Out.ln; | |
| 40 | + nest; | |
| 41 | + Out.ln; | |
| 42 | +end; | |
| 43 | + | |
| 44 | +end Order. | |
| 45 | +``` | |
| 46 | + | |
| 47 | +## In a loop | |
| 48 | + | |
| 49 | +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`. | |
| 50 | + | |
| 51 | +```raz Passes run | |
| 52 | +module Passes; | |
| 53 | +import Out; | |
| 54 | + | |
| 55 | +proc main*; | |
| 56 | +var i: INT; | |
| 57 | +begin | |
| 58 | + for i := 1 to 4 do | |
| 59 | + Out.str("pass "); Out.int(i); | |
| 60 | + defer Out.str(" done\n"); | |
| 61 | + if i = 3 then break; end; | |
| 62 | + Out.str(" ..."); | |
| 63 | + end; | |
| 64 | +end; | |
| 65 | + | |
| 66 | +end Passes. | |
| 67 | +``` | |
| 68 | + | |
| 69 | +## Giving back what was taken | |
| 70 | + | |
| 71 | +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. | |
| 72 | + | |
| 73 | +```raz Report run | |
| 74 | +module Report; | |
| 75 | +import Out, Buf, Heap; | |
| 76 | + | |
| 77 | +(* a line, built in a buffer; false (nothing written) if n is negative *) | |
| 78 | +proc line(n: INT): BOOL; | |
| 79 | +var b: Buf.Buf; | |
| 80 | +begin | |
| 81 | + if n < 0 then return false; end; | |
| 82 | + Buf.init(ADR(b), Heap.heap); | |
| 83 | + defer Buf.done(ADR(b)); (* freed on every way out below *) | |
| 84 | + Buf.str(ADR(b), "n is "); | |
| 85 | + if n > 9 then | |
| 86 | + Buf.str(ADR(b), "large"); | |
| 87 | + Out.str(Buf.bytes(ADR(b))); Out.ln; | |
| 88 | + return true; | |
| 89 | + end; | |
| 90 | + Buf.str(ADR(b), "small"); | |
| 91 | + Out.str(Buf.bytes(ADR(b))); Out.ln; | |
| 92 | + return true; | |
| 93 | +end; | |
| 94 | + | |
| 95 | +proc main*; | |
| 96 | +begin | |
| 97 | + _ := line(3); | |
| 98 | + _ := line(30); | |
| 99 | + if not line(-1) then Out.str("rejected\n"); end; | |
| 100 | +end; | |
| 101 | + | |
| 102 | +end Report. | |
| 103 | +``` | |
| 104 | + | |
| 105 | +## What defer does not do | |
| 106 | + | |
| 107 | +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. |
| @@ -0,0 +1,130 @@ | ||
| 1 | +title: When it goes wrong | |
| 2 | +part: Go | |
| 3 | +summary: Every index is checked, a failure says where and with what values, and how to read it. | |
| 4 | +--- | |
| 5 | +```raz Fail fail | |
| 6 | +``` | |
| 7 | + | |
| 8 | +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. | |
| 9 | + | |
| 10 | +## Reading the message | |
| 11 | + | |
| 12 | +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. | |
| 13 | + | |
| 14 | +## Other failures | |
| 15 | + | |
| 16 | +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. | |
| 17 | + | |
| 18 | +```raz Nilp fail | |
| 19 | +module Nilp; | |
| 20 | +import Out; | |
| 21 | + | |
| 22 | +type Node = record val: INT; next: ^Node; end; | |
| 23 | + | |
| 24 | +proc last(n: ^Node): INT; | |
| 25 | +begin | |
| 26 | + while n^.next # nil do n := n^.next; end; | |
| 27 | + return n^.val; | |
| 28 | +end; | |
| 29 | + | |
| 30 | +proc main*; | |
| 31 | +var a, b: Node; | |
| 32 | +begin | |
| 33 | + a.val := 1; b.val := 2; | |
| 34 | + a.next := ADR(b); | |
| 35 | + Out.int(last(ADR(a))); Out.ln; | |
| 36 | + Out.int(last(nil)); Out.ln; | |
| 37 | +end; | |
| 38 | + | |
| 39 | +end Nilp. | |
| 40 | +``` | |
| 41 | + | |
| 42 | +```raz Zero fail | |
| 43 | +module Zero; | |
| 44 | +import Out; | |
| 45 | + | |
| 46 | +proc ratio(a, b: INT): INT; | |
| 47 | +begin | |
| 48 | + return a div b; | |
| 49 | +end; | |
| 50 | + | |
| 51 | +proc main*; | |
| 52 | +var n: INT; | |
| 53 | +begin | |
| 54 | + Out.int(ratio(10, 3)); Out.ln; | |
| 55 | + Out.int(ratio(10, n)); Out.ln; (* n is zero: every variable starts at zero *) | |
| 56 | +end; | |
| 57 | + | |
| 58 | +end Zero. | |
| 59 | +``` | |
| 60 | + | |
| 61 | +```raz Slicing fail | |
| 62 | +module Slicing; | |
| 63 | +import Out; | |
| 64 | + | |
| 65 | +proc main*; | |
| 66 | +var a: [5]INT; s: []INT; hi: INT; | |
| 67 | +begin | |
| 68 | + hi := 7; | |
| 69 | + s := a[2..5]; | |
| 70 | + Out.int(LEN(s)); Out.ln; | |
| 71 | + s := a[2..hi]; (* past the end *) | |
| 72 | + Out.int(LEN(s)); Out.ln; | |
| 73 | +end; | |
| 74 | + | |
| 75 | +end Slicing. | |
| 76 | +``` | |
| 77 | + | |
| 78 | +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. | |
| 79 | + | |
| 80 | +## A constant can fail at compile time | |
| 81 | + | |
| 82 | +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. | |
| 83 | + | |
| 84 | +```raz Early | |
| 85 | +module Early; | |
| 86 | +import Out; | |
| 87 | + | |
| 88 | +proc main*; | |
| 89 | +var a: [3]INT; | |
| 90 | +begin | |
| 91 | + a[3] := 1; | |
| 92 | + Out.int(10 div 0); Out.ln; | |
| 93 | +end; | |
| 94 | + | |
| 95 | +end Early. | |
| 96 | +``` | |
| 97 | + | |
| 98 | +```sh | |
| 99 | +$ raz Early.raz | |
| 100 | +``` | |
| 101 | + | |
| 102 | +## Looking at where you are | |
| 103 | + | |
| 104 | +`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. | |
| 105 | + | |
| 106 | +```raz Where run | |
| 107 | +module Where; | |
| 108 | +import Rt; | |
| 109 | + | |
| 110 | +proc inner(depth: INT); | |
| 111 | +begin | |
| 112 | + if depth = 0 then Rt.trace; return; end; | |
| 113 | + inner(depth - 1); | |
| 114 | +end; | |
| 115 | + | |
| 116 | +proc main*; | |
| 117 | +begin | |
| 118 | + inner(2); | |
| 119 | +end; | |
| 120 | + | |
| 121 | +end Where. | |
| 122 | +``` | |
| 123 | + | |
| 124 | +## Leaving the checks out | |
| 125 | + | |
| 126 | +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. | |
| 127 | + | |
| 128 | +## For gdb and the profiler | |
| 129 | + | |
| 130 | +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. |
| @@ -0,0 +1,104 @@ | ||
| 1 | +title: Generic modules | |
| 2 | +part: Go | |
| 3 | +summary: A module that takes types and procedures; the library's List, Map and Sort. | |
| 4 | +--- | |
| 5 | +A module may take types, and the procedures it needs on them, as parameters. `Biggest.raz`: | |
| 6 | + | |
| 7 | +```raz Biggest | |
| 8 | +``` | |
| 9 | + | |
| 10 | +and a program that uses it: | |
| 11 | + | |
| 12 | +```raz Generics run | |
| 13 | +``` | |
| 14 | + | |
| 15 | +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`. | |
| 16 | + | |
| 17 | +## Writing your own | |
| 18 | + | |
| 19 | +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. | |
| 20 | + | |
| 21 | +```raz Stk | |
| 22 | +module Stk(T); | |
| 23 | +import Mem; | |
| 24 | + | |
| 25 | +type | |
| 26 | + Stack* = record | |
| 27 | + items: ^T; (* an array of cap Ts *) | |
| 28 | + cap*, len*: INT; | |
| 29 | + a: ^Mem.Allocator; | |
| 30 | + end; | |
| 31 | + | |
| 32 | +proc init*(s: ^Stack; a: ^Mem.Allocator); | |
| 33 | +begin | |
| 34 | + s^.a := a; | |
| 35 | + s^.items := nil; | |
| 36 | + s^.cap := 0; | |
| 37 | + s^.len := 0; | |
| 38 | +end; | |
| 39 | + | |
| 40 | +(* v on top; false if the allocator has no room *) | |
| 41 | +proc push*(s: ^Stack; v: T): BOOL; | |
| 42 | +var bigger: ^T; i, cap: INT; src, dst: ^T; | |
| 43 | +begin | |
| 44 | + if s^.len = s^.cap then | |
| 45 | + if s^.cap = 0 then cap := 4; else cap := s^.cap * 2; end; | |
| 46 | + bigger := ^T(Mem.alloc(s^.a, cap * SIZE(T), 8)); | |
| 47 | + if bigger = nil then return false; end; | |
| 48 | + for i := 0 to s^.len - 1 do | |
| 49 | + src := ^T(INT(s^.items) + i * SIZE(T)); | |
| 50 | + dst := ^T(INT(bigger) + i * SIZE(T)); | |
| 51 | + dst^ := src^; | |
| 52 | + end; | |
| 53 | + if s^.items # nil then Mem.free(s^.a, ^U8(s^.items)); end; | |
| 54 | + s^.items := bigger; | |
| 55 | + s^.cap := cap; | |
| 56 | + end; | |
| 57 | + dst := ^T(INT(s^.items) + s^.len * SIZE(T)); | |
| 58 | + dst^ := v; | |
| 59 | + INC(s^.len); | |
| 60 | + return true; | |
| 61 | +end; | |
| 62 | + | |
| 63 | +(* the top value, taken off; false if empty *) | |
| 64 | +proc pop*(s: ^Stack): (T, BOOL); | |
| 65 | +var z: T; p: ^T; | |
| 66 | +begin | |
| 67 | + if s^.len = 0 then return z, false; end; | |
| 68 | + DEC(s^.len); | |
| 69 | + p := ^T(INT(s^.items) + s^.len * SIZE(T)); | |
| 70 | + return p^, true; | |
| 71 | +end; | |
| 72 | + | |
| 73 | +end Stk. | |
| 74 | +``` | |
| 75 | + | |
| 76 | +```raz Uses run | |
| 77 | +module Uses; | |
| 78 | +import Out, Heap, Nums := Stk(INT), Pairs := Stk(Pair); | |
| 79 | + | |
| 80 | +type Pair = record a, b: INT; end; | |
| 81 | + | |
| 82 | +proc main*; | |
| 83 | +var n: Nums.Stack; p: Pairs.Stack; i, v: INT; ok: BOOL; pr: Pair; | |
| 84 | +begin | |
| 85 | + Nums.init(ADR(n), Heap.heap); | |
| 86 | + Pairs.init(ADR(p), Heap.heap); | |
| 87 | + for i := 1 to 10 do _ := Nums.push(ADR(n), i * i); end; | |
| 88 | + _ := Pairs.push(ADR(p), {a: 3, b: 4}); | |
| 89 | + v, ok := Nums.pop(ADR(n)); | |
| 90 | + Out.int(v); Out.str(" of "); Out.int(n.len + 1); Out.ln; | |
| 91 | + pr, ok := Pairs.pop(ADR(p)); | |
| 92 | + Out.int(pr.a * pr.b); Out.ln; | |
| 93 | + _, ok := Pairs.pop(ADR(p)); | |
| 94 | + if not ok then Out.str("empty\n"); end; | |
| 95 | +end; | |
| 96 | + | |
| 97 | +end Uses. | |
| 98 | +``` | |
| 99 | + | |
| 100 | +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. | |
| 101 | + | |
| 102 | +## The library's generics | |
| 103 | + | |
| 104 | +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. |
| @@ -0,0 +1,89 @@ | ||
| 1 | +title: Talking to C | |
| 2 | +part: Go | |
| 3 | +summary: Call a C library, be called back, share variables, and mind the two buffers. | |
| 4 | +--- | |
| 5 | +```raz Qsort run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +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. | |
| 9 | + | |
| 10 | +## What using C costs | |
| 11 | + | |
| 12 | +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. | |
| 13 | + | |
| 14 | +## Varargs | |
| 15 | + | |
| 16 | +`...` 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)`. | |
| 17 | + | |
| 18 | +```raz Say run | |
| 19 | +module Say; | |
| 20 | +import Out; | |
| 21 | + | |
| 22 | +extern proc printf(format: ^U8; ...): I32; | |
| 23 | +extern proc fflush(f: ^U8): I32; | |
| 24 | +extern proc puts(s: ^U8): I32; | |
| 25 | + | |
| 26 | +proc main*; | |
| 27 | +var n: INT; x: F32; | |
| 28 | +begin | |
| 29 | + n := 42; | |
| 30 | + x := 2.5; | |
| 31 | + Out.str("raz first\n"); | |
| 32 | + Out.flush; (* Out has a buffer; so does C *) | |
| 33 | + _ := printf("C says %ld and %.2f and %s\n", n, F64(x), "hello"); | |
| 34 | + _ := puts("and puts"); | |
| 35 | + _ := fflush(nil); (* nil: every C stream *) | |
| 36 | + Out.str("raz again\n"); | |
| 37 | +end; | |
| 38 | + | |
| 39 | +end Say. | |
| 40 | +``` | |
| 41 | + | |
| 42 | +`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. | |
| 43 | + | |
| 44 | +## Libraries, and C's variables | |
| 45 | + | |
| 46 | +`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. | |
| 47 | + | |
| 48 | +```raz Env run | |
| 49 | +module Env; | |
| 50 | +import Out; | |
| 51 | + | |
| 52 | +extern var environ: ^^U8; | |
| 53 | +extern proc strlen(s: ^U8): UINT; | |
| 54 | +extern proc getenv(name: ^U8): ^U8; | |
| 55 | + | |
| 56 | +proc main*; | |
| 57 | +var p: ^U8; n: INT; | |
| 58 | +begin | |
| 59 | + n := 0; | |
| 60 | + while environ[n] # nil do INC(n); end; | |
| 61 | + if n > 0 then Out.str("the environment is not empty\n"); end; | |
| 62 | + p := getenv("RAZ_NO_SUCH_VARIABLE"); | |
| 63 | + if p = nil then Out.str("not set\n"); end; | |
| 64 | + Out.int(INT(strlen("six"))); Out.ln; | |
| 65 | +end; | |
| 66 | + | |
| 67 | +end Env. | |
| 68 | +``` | |
| 69 | + | |
| 70 | +## Callbacks | |
| 71 | + | |
| 72 | +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. | |
| 73 | + | |
| 74 | +```raz Roots run | |
| 75 | +module Roots; | |
| 76 | +import Fmt; | |
| 77 | + | |
| 78 | +link "libm.so.6"; | |
| 79 | + | |
| 80 | +extern proc cbrt(x: F64): F64; | |
| 81 | +extern proc hypot(x, y: F64): F64; | |
| 82 | + | |
| 83 | +proc main*; | |
| 84 | +begin | |
| 85 | + Fmt.print("{} {}\n", [Fmt.real(cbrt(27.0), 3), Fmt.real(hypot(3.0, 4.0), 3)]); | |
| 86 | +end; | |
| 87 | + | |
| 88 | +end Roots. | |
| 89 | +``` |
| @@ -0,0 +1,120 @@ | ||
| 1 | +title: Threads | |
| 2 | +part: Go | |
| 3 | +summary: Native threads without C, atomics, a mutex, and why the counter needs both. | |
| 4 | +--- | |
| 5 | +```raz Hits run | |
| 6 | +``` | |
| 7 | + | |
| 8 | +`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. | |
| 9 | + | |
| 10 | +## What goes wrong without them | |
| 11 | + | |
| 12 | +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. | |
| 13 | + | |
| 14 | +```raz Race run | |
| 15 | +module Race; | |
| 16 | +import Out, Thread; | |
| 17 | + | |
| 18 | +var | |
| 19 | + safe: INT; (* added to by XADD *) | |
| 20 | + plain: INT; (* added to by INC: unsafe, never printed *) | |
| 21 | + | |
| 22 | +proc work(_arg: ^U8); | |
| 23 | +var i: INT; | |
| 24 | +begin | |
| 25 | + for i := 1 to 100000 do | |
| 26 | + _ := XADD(ADR(safe), 1); | |
| 27 | + INC(plain); (* unsafe: lost additions *) | |
| 28 | + end; | |
| 29 | +end; | |
| 30 | + | |
| 31 | +proc main*; | |
| 32 | +var t: [4]^Thread.Thread; i: INT; err: ERROR; | |
| 33 | +begin | |
| 34 | + for i := 0 to 3 do | |
| 35 | + t[i], err := Thread.spawn(work, nil); | |
| 36 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 37 | + end; | |
| 38 | + for i := 0 to 3 do Thread.join(t[i]); end; | |
| 39 | + Out.str("safe "); Out.int(safe); Out.ln; | |
| 40 | +end; | |
| 41 | + | |
| 42 | +end Race. | |
| 43 | +``` | |
| 44 | + | |
| 45 | +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. | |
| 46 | + | |
| 47 | +## A mutex for longer sections | |
| 48 | + | |
| 49 | +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. | |
| 50 | + | |
| 51 | +```raz Bank run | |
| 52 | +module Bank; | |
| 53 | +import Out, Thread; | |
| 54 | + | |
| 55 | +var | |
| 56 | + m: Thread.Mutex; | |
| 57 | + balance, deposits: INT; (* kept in step, under m *) | |
| 58 | + | |
| 59 | +proc deposit(_arg: ^U8); | |
| 60 | +var i: INT; | |
| 61 | +begin | |
| 62 | + for i := 1 to 10000 do | |
| 63 | + Thread.lock(ADR(m)); | |
| 64 | + balance := balance + 5; | |
| 65 | + INC(deposits); | |
| 66 | + Thread.unlock(ADR(m)); | |
| 67 | + end; | |
| 68 | +end; | |
| 69 | + | |
| 70 | +proc main*; | |
| 71 | +var t: [3]^Thread.Thread; i: INT; err: ERROR; | |
| 72 | +begin | |
| 73 | + for i := 0 to 2 do | |
| 74 | + t[i], err := Thread.spawn(deposit, nil); | |
| 75 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 76 | + end; | |
| 77 | + for i := 0 to 2 do Thread.join(t[i]); end; | |
| 78 | + Out.int(deposits); Out.char(' '); Out.int(balance); Out.ln; | |
| 79 | +end; | |
| 80 | + | |
| 81 | +end Bank. | |
| 82 | +``` | |
| 83 | + | |
| 84 | +## Handing work out | |
| 85 | + | |
| 86 | +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. | |
| 87 | + | |
| 88 | +```raz Jobs run | |
| 89 | +module Jobs; | |
| 90 | +import Out, Thread; | |
| 91 | + | |
| 92 | +type Job = record lo, hi: INT; sum: INT; end; | |
| 93 | + | |
| 94 | +proc work(arg: ^U8); | |
| 95 | +var j: ^Job; i: INT; | |
| 96 | +begin | |
| 97 | + j := ^Job(arg); | |
| 98 | + for i := j^.lo to j^.hi - 1 do j^.sum := j^.sum + i; end; | |
| 99 | +end; | |
| 100 | + | |
| 101 | +proc main*; | |
| 102 | +var jobs: [4]Job; t: [4]^Thread.Thread; i, total: INT; err: ERROR; | |
| 103 | +begin | |
| 104 | + for i := 0 to 3 do | |
| 105 | + jobs[i].lo := i * 250000; | |
| 106 | + jobs[i].hi := (i + 1) * 250000; | |
| 107 | + t[i], err := Thread.spawn(work, ^U8(ADR(jobs[i]))); | |
| 108 | + if err # nil then Out.str(MSG(err)); Out.ln; return; end; | |
| 109 | + end; | |
| 110 | + for i := 0 to 3 do | |
| 111 | + Thread.join(t[i]); | |
| 112 | + total := total + jobs[i].sum; | |
| 113 | + end; | |
| 114 | + Out.int(total); Out.ln; | |
| 115 | +end; | |
| 116 | + | |
| 117 | +end Jobs. | |
| 118 | +``` | |
| 119 | + | |
| 120 | +`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. |
| @@ -0,0 +1,193 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Writing an allocator - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html" aria-current="page">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">The library · lesson 6 of 18</p><h1>Writing an allocator</h1> | |
| 38 | +<p>An allocator is a record of two procedures, and that is all <code>Mem.Allocator</code> is:</p> | |
| 39 | +<pre class="code"><code>type Allocator* = record | |
| 40 | + alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *) | |
| 41 | + free*: proc(a: ^Allocator; p: ^U8); | |
| 42 | +end;</code></pre> | |
| 43 | +<p><code>NEW(p, a)</code> calls <code>a^.alloc(a, SIZE(T), alignment)</code> and zeroes what it gets. <code>Buf</code>, <code>List</code> and <code>Map</code> call the same procedures. So anything that fills in these two fields is an allocator, and everything in the library works with it.</p> | |
| 44 | +<h2>An allocator over a fixed array</h2> | |
| 45 | +<p>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. <code>free</code> has nothing to do; <code>reset</code> forgets everything.</p> | |
| 46 | +<p>The trick that lets one procedure find its state is the same one <code>Arena</code> uses: the record puts <code>base: Mem.Allocator</code> first, so a <code>^Mem.Allocator</code> and a <code>^Bump</code> are the same address, and the procedure converts one to the other.</p> | |
| 47 | +<div class="file"><span>Bump.raz</span></div><pre class="code"><code><span class="kw">module</span> Bump; | |
| 48 | +<span class="kw">import</span> Mem; | |
| 49 | + | |
| 50 | +<span class="kw">type</span> | |
| 51 | + Bump* = <span class="kw">record</span> | |
| 52 | + base*: Mem.Allocator; <span class="comment">(* first, so that ^Bump(a) finds the rest *)</span> | |
| 53 | + mem: ^<span class="ty">U8</span>; | |
| 54 | + size, used*: <span class="ty">INT</span>; | |
| 55 | + <span class="kw">end</span>; | |
| 56 | + | |
| 57 | +<span class="kw">proc</span> alloc(a: ^Mem.Allocator; size, align: <span class="ty">INT</span>): ^<span class="ty">U8</span>; | |
| 58 | +<span class="kw">var</span> b: ^Bump; at: <span class="ty">INT</span>; | |
| 59 | +<span class="kw">begin</span> | |
| 60 | + b := ^Bump(a); | |
| 61 | + at := (b^.used + align - <span class="number">1</span>) <span class="kw">div</span> align * align; <span class="comment">(* round up to align *)</span> | |
| 62 | + <span class="kw">if</span> (size < <span class="number">0</span>) <span class="kw">or</span> (at + size > b^.size) <span class="kw">then</span> <span class="kw">return</span> <span class="ty">nil</span>; <span class="kw">end</span>; | |
| 63 | + b^.used := at + size; | |
| 64 | + <span class="kw">return</span> b^.mem + at; | |
| 65 | +<span class="kw">end</span>; | |
| 66 | + | |
| 67 | +<span class="kw">proc</span> free(_a: ^Mem.Allocator; _p: ^<span class="ty">U8</span>); | |
| 68 | +<span class="kw">begin</span> | |
| 69 | +<span class="kw">end</span>; | |
| 70 | + | |
| 71 | +<span class="comment">(* a bump allocator over the size bytes at mem *)</span> | |
| 72 | +<span class="kw">proc</span> init*(b: ^Bump; mem: ^<span class="ty">U8</span>; size: <span class="ty">INT</span>); | |
| 73 | +<span class="kw">begin</span> | |
| 74 | + b^.base := {alloc: alloc, free: free}; | |
| 75 | + b^.mem := mem; | |
| 76 | + b^.size := size; | |
| 77 | + b^.used := <span class="number">0</span>; | |
| 78 | +<span class="kw">end</span>; | |
| 79 | + | |
| 80 | +<span class="comment">(* everything forgotten, the memory used again *)</span> | |
| 81 | +<span class="kw">proc</span> reset*(b: ^Bump); | |
| 82 | +<span class="kw">begin</span> | |
| 83 | + b^.used := <span class="number">0</span>; | |
| 84 | +<span class="kw">end</span>; | |
| 85 | + | |
| 86 | +<span class="kw">end</span> Bump.</code></pre> | |
| 87 | +<div class="file"><span>Bumping.raz</span></div><pre class="code"><code><span class="kw">module</span> Bumping; | |
| 88 | +<span class="kw">import</span> Out, Bump; | |
| 89 | + | |
| 90 | +<span class="kw">type</span> Point = <span class="kw">record</span> x, y: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 91 | + | |
| 92 | +<span class="kw">var</span> arena: [<span class="number">256</span>]<span class="ty">U8</span>; <span class="comment">(* the allocator's whole world *)</span> | |
| 93 | + | |
| 94 | +<span class="kw">proc</span> main*; | |
| 95 | +<span class="kw">var</span> b: Bump.Bump; p, q: ^Point; many: <span class="ty">INT</span>; r: ^Point; | |
| 96 | +<span class="kw">begin</span> | |
| 97 | + Bump.init(<span class="ty">ADR</span>(b), <span class="ty">ADR</span>(arena[<span class="number">0</span>]), <span class="number">256</span>); | |
| 98 | + <span class="ty">NEW</span>(p, <span class="ty">ADR</span>(b.base)); | |
| 99 | + <span class="ty">NEW</span>(q, <span class="ty">ADR</span>(b.base)); | |
| 100 | + p^.x := <span class="number">1</span>; q^.y := <span class="number">2</span>; | |
| 101 | + Out.int(b.used); Out.str(<span class="string">" bytes used by two points\n"</span>); | |
| 102 | + many := <span class="number">2</span>; | |
| 103 | + <span class="kw">repeat</span> | |
| 104 | + <span class="ty">NEW</span>(r, <span class="ty">ADR</span>(b.base)); | |
| 105 | + <span class="kw">if</span> r # <span class="ty">nil</span> <span class="kw">then</span> <span class="ty">INC</span>(many); <span class="kw">end</span>; | |
| 106 | + <span class="kw">until</span> r = <span class="ty">nil</span>; | |
| 107 | + Out.int(many); Out.str(<span class="string">" points fit in 256 bytes\n"</span>); | |
| 108 | + Bump.reset(<span class="ty">ADR</span>(b)); | |
| 109 | + <span class="ty">NEW</span>(r, <span class="ty">ADR</span>(b.base)); | |
| 110 | + <span class="kw">if</span> r # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"room again after a reset\n"</span>); <span class="kw">end</span>; | |
| 111 | +<span class="kw">end</span>; | |
| 112 | + | |
| 113 | +<span class="kw">end</span> Bumping.</code></pre> | |
| 114 | +<pre class="output"><code>32 bytes used by two points | |
| 115 | +16 points fit in 256 bytes | |
| 116 | +room again after a reset | |
| 117 | +</code></pre> | |
| 118 | +<p>An allocator that runs out says so with <code>nil</code>, and the caller decides what that means. Nothing else in the program is touched.</p> | |
| 119 | +<h2>An allocator that counts</h2> | |
| 120 | +<p>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.</p> | |
| 121 | +<div class="file"><span>Counted.raz</span></div><pre class="code"><code><span class="kw">module</span> Counted; | |
| 122 | +<span class="kw">import</span> Mem; | |
| 123 | + | |
| 124 | +<span class="kw">type</span> | |
| 125 | + Counted* = <span class="kw">record</span> | |
| 126 | + base*: Mem.Allocator; <span class="comment">(* first *)</span> | |
| 127 | + inner: ^Mem.Allocator; | |
| 128 | + allocs*, frees*, bytes*: <span class="ty">INT</span>; | |
| 129 | + <span class="kw">end</span>; | |
| 130 | + | |
| 131 | +<span class="kw">proc</span> alloc(a: ^Mem.Allocator; size, align: <span class="ty">INT</span>): ^<span class="ty">U8</span>; | |
| 132 | +<span class="kw">var</span> c: ^Counted; p: ^<span class="ty">U8</span>; | |
| 133 | +<span class="kw">begin</span> | |
| 134 | + c := ^Counted(a); | |
| 135 | + p := Mem.alloc(c^.inner, size, align); | |
| 136 | + <span class="kw">if</span> p # <span class="ty">nil</span> <span class="kw">then</span> <span class="ty">INC</span>(c^.allocs); <span class="ty">INC</span>(c^.bytes, size); <span class="kw">end</span>; | |
| 137 | + <span class="kw">return</span> p; | |
| 138 | +<span class="kw">end</span>; | |
| 139 | + | |
| 140 | +<span class="kw">proc</span> free(a: ^Mem.Allocator; p: ^<span class="ty">U8</span>); | |
| 141 | +<span class="kw">var</span> c: ^Counted; | |
| 142 | +<span class="kw">begin</span> | |
| 143 | + c := ^Counted(a); | |
| 144 | + <span class="ty">INC</span>(c^.frees); | |
| 145 | + Mem.free(c^.inner, p); | |
| 146 | +<span class="kw">end</span>; | |
| 147 | + | |
| 148 | +<span class="comment">(* a counting allocator in front of inner *)</span> | |
| 149 | +<span class="kw">proc</span> init*(c: ^Counted; inner: ^Mem.Allocator); | |
| 150 | +<span class="kw">begin</span> | |
| 151 | + c^.base := {alloc: alloc, free: free}; | |
| 152 | + c^.inner := inner; | |
| 153 | + c^.allocs := <span class="number">0</span>; | |
| 154 | + c^.frees := <span class="number">0</span>; | |
| 155 | + c^.bytes := <span class="number">0</span>; | |
| 156 | +<span class="kw">end</span>; | |
| 157 | + | |
| 158 | +<span class="kw">end</span> Counted.</code></pre> | |
| 159 | +<div class="file"><span>Audit.raz</span></div><pre class="code"><code><span class="kw">module</span> Audit; | |
| 160 | +<span class="kw">import</span> Fmt, Heap, Mem, Buf, Counted, Names := List([]<span class="ty">U8</span>); | |
| 161 | + | |
| 162 | +<span class="kw">proc</span> main*; | |
| 163 | +<span class="kw">var</span> c: Counted.Counted; b: Buf.Buf; l: Names.List; i: <span class="ty">INT</span>; p: ^<span class="ty">U8</span>; | |
| 164 | +<span class="kw">begin</span> | |
| 165 | + Counted.init(<span class="ty">ADR</span>(c), Heap.heap); | |
| 166 | + Buf.init(<span class="ty">ADR</span>(b), <span class="ty">ADR</span>(c.base)); | |
| 167 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">200</span> <span class="kw">do</span> Buf.str(<span class="ty">ADR</span>(b), <span class="string">"0123456789"</span>); <span class="kw">end</span>; | |
| 168 | + Fmt.print(<span class="string">"a buffer of {} bytes took {} allocations\n"</span>, | |
| 169 | + [Fmt.int(b.len), Fmt.int(c.allocs)]); | |
| 170 | + Buf.done(<span class="ty">ADR</span>(b)); | |
| 171 | + | |
| 172 | + Names.init(<span class="ty">ADR</span>(l), <span class="ty">ADR</span>(c.base)); | |
| 173 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">10</span> <span class="kw">do</span> _ := Names.push(<span class="ty">ADR</span>(l), <span class="string">"x"</span>); <span class="kw">end</span>; | |
| 174 | + Fmt.print(<span class="string">"{} allocations in all, {} frees so far\n"</span>, [Fmt.int(c.allocs), Fmt.int(c.frees)]); | |
| 175 | + Names.clear(<span class="ty">ADR</span>(l)); | |
| 176 | + Fmt.print(<span class="string">"{} frees after clear\n"</span>, [Fmt.int(c.frees)]); | |
| 177 | + | |
| 178 | + p := Mem.alloc(<span class="ty">ADR</span>(c.base), <span class="number">64</span>, <span class="number">8</span>); | |
| 179 | + Mem.free(<span class="ty">ADR</span>(c.base), p); | |
| 180 | +<span class="kw">end</span>; | |
| 181 | + | |
| 182 | +<span class="kw">end</span> Audit.</code></pre> | |
| 183 | +<pre class="output"><code>a buffer of 2000 bytes took 6 allocations | |
| 184 | +16 allocations in all, 6 frees so far | |
| 185 | +16 frees after clear | |
| 186 | +</code></pre> | |
| 187 | +<p>A <code>Buf</code> 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.</p> | |
| 188 | +<h2>What to take from this</h2> | |
| 189 | +<ul><li>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.</li><li>A library function that needs memory takes the allocator as a parameter, so its caller owns the policy.</li><li>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.</li></ul><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="processes.html">← Time, randomness and other programs</a><a href="index.html">Contents</a><a class="next" href="static.html">A program with no run time →</a></div></article></div> | |
| 190 | +</main> | |
| 191 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 192 | +</body> | |
| 193 | +</html> |
| @@ -0,0 +1,215 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Procedures in assembly - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html" aria-current="page">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">The machine · lesson 11 of 18</p><h1>Procedures in assembly</h1> | |
| 38 | +<p>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>code</code> is machine code, written by hand in the target's assembly language, one instruction to each <code>;</code>, up to <code>end</code>.</p> | |
| 39 | +<p>The compiler doesn't look past what the instructions say. It trusts you, and you owe it a few rules.</p> | |
| 40 | +<h2>A first one</h2> | |
| 41 | +<p>This reads the processor's time stamp counter. The result of a procedure goes in <code>rax</code>; <code>rdtsc</code> leaves the counter in <code>edx:eax</code>, so the two halves are joined first.</p> | |
| 42 | +<div class="file"><span>Cycles.raz</span></div><pre class="code"><code><span class="kw">module</span> Cycles; | |
| 43 | +<span class="kw">import</span> Out; | |
| 44 | + | |
| 45 | +<span class="kw">proc</span> rdtsc*: <span class="ty">U64</span>; | |
| 46 | +<span class="kw">code</span> | |
| 47 | + rdtsc; | |
| 48 | + <span class="kw">shl</span> rdx, <span class="number">32</span>; | |
| 49 | + <span class="kw">or</span> rax, rdx; | |
| 50 | + ret; | |
| 51 | +<span class="kw">end</span> rdtsc; | |
| 52 | + | |
| 53 | +<span class="kw">proc</span> main*; | |
| 54 | +<span class="kw">var</span> a, b: <span class="ty">U64</span>; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + a := rdtsc(); | |
| 57 | + b := rdtsc(); | |
| 58 | + <span class="kw">if</span> b > a <span class="kw">then</span> Out.str(<span class="string">"the counter moves forward\n"</span>); <span class="kw">end</span>; | |
| 59 | +<span class="kw">end</span>; | |
| 60 | + | |
| 61 | +<span class="kw">end</span> Cycles.</code></pre> | |
| 62 | +<pre class="output"><code>the counter moves forward | |
| 63 | +</code></pre> | |
| 64 | +<p>A code procedure is called like any procedure. Everything in it is yours, <code>ret</code> included.</p> | |
| 65 | +<h2>The convention</h2> | |
| 66 | +<p>A code procedure follows the System V convention, as every raz procedure does:</p> | |
| 67 | +<ul><li>Integer and pointer arguments arrive in <code>rdi</code>, <code>rsi</code>, <code>rdx</code>, <code>rcx</code>, <code>r8</code> and <code>r9</code>; <code>F32</code> and <code>F64</code> ones in <code>xmm0</code> to <code>xmm7</code>.</li><li>The result goes in <code>rax</code> (and <code>rdx</code> for a second) or <code>xmm0</code>.</li><li>It must keep <code>rbx</code>, <code>rbp</code>, <code>rsp</code> and <code>r12</code> to <code>r15</code> as it found them. <code>rax</code>, <code>rcx</code>, <code>rdx</code>, <code>rsi</code>, <code>rdi</code> and <code>r8</code> to <code>r11</code> are free to change.</li><li>Its parameters and results are therefore of the types C can take, at most six integer and eight real parameters and two results.</li></ul> | |
| 68 | +<p>That is why the next one is so short: the argument is already in <code>rdi</code>.</p> | |
| 69 | +<div class="file"><span>Bits.raz</span></div><pre class="code"><code><span class="kw">module</span> Bits; | |
| 70 | +<span class="kw">import</span> Out; | |
| 71 | + | |
| 72 | +<span class="comment">(* the bytes of x in the opposite order: bswap rax, which the assembler | |
| 73 | + doesn't know, written as its bytes *)</span> | |
| 74 | +<span class="kw">proc</span> swap64(x: <span class="ty">U64</span>): <span class="ty">U64</span>; | |
| 75 | +<span class="kw">code</span> | |
| 76 | + mov rax, rdi; | |
| 77 | + db <span class="number">48H</span>, <span class="number">0FH</span>, <span class="number">0C8H</span>; | |
| 78 | + ret; | |
| 79 | +<span class="kw">end</span> swap64; | |
| 80 | + | |
| 81 | +<span class="comment">(* the number of bits set in x: popcnt rax, rdi *)</span> | |
| 82 | +<span class="kw">proc</span> ones(x: <span class="ty">U64</span>): <span class="ty">INT</span>; | |
| 83 | +<span class="kw">code</span> | |
| 84 | + db <span class="number">0F3H</span>, <span class="number">48H</span>, <span class="number">0FH</span>, <span class="number">0B8H</span>, <span class="number">0C7H</span>; | |
| 85 | + ret; | |
| 86 | +<span class="kw">end</span> ones; | |
| 87 | + | |
| 88 | +<span class="kw">proc</span> main*; | |
| 89 | +<span class="kw">begin</span> | |
| 90 | + Out.str(<span class="string">"0x"</span>); Out.hex(swap64(<span class="number">0102030405060708H</span>), <span class="number">16</span>); Out.ln; | |
| 91 | + Out.int(ones(<span class="number">0FFH</span>)); Out.char(<span class="string">' '</span>); | |
| 92 | + Out.int(ones(<span class="number">0</span>)); Out.char(<span class="string">' '</span>); | |
| 93 | + Out.int(ones(<span class="number">0FFFFFFFFFFFFFFFFH</span>)); Out.ln; | |
| 94 | +<span class="kw">end</span>; | |
| 95 | + | |
| 96 | +<span class="kw">end</span> Bits.</code></pre> | |
| 97 | +<pre class="output"><code>0x0807060504030201 | |
| 98 | +8 0 64 | |
| 99 | +</code></pre> | |
| 100 | +<p><code>db</code> writes any bytes, for an instruction the assembler doesn't know. Which instructions it knows is the implementation's business; <code>db</code> keeps you from waiting for it to learn one. (The two instructions above are from the processor manuals: <code>bswap r64</code> is <code>REX.W 0F C8+r</code>, <code>popcnt r64, r/m64</code> is <code>F3 REX.W 0F B8 /r</code>.)</p> | |
| 101 | +<h2>Labels and loops</h2> | |
| 102 | +<p>A label, <code>name:</code>, 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 <code>INT</code>s, which a pointer and a length describe:</p> | |
| 103 | +<div class="file"><span>Sum.raz</span></div><pre class="code"><code><span class="kw">module</span> Sum; | |
| 104 | +<span class="kw">import</span> Out; | |
| 105 | + | |
| 106 | +<span class="comment">(* the sum of the n INTs at p *)</span> | |
| 107 | +<span class="kw">proc</span> sum(p: ^<span class="ty">INT</span>; n: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 108 | +<span class="kw">code</span> | |
| 109 | + <span class="kw">xor</span> eax, eax; | |
| 110 | + test rsi, rsi; | |
| 111 | + jle done; | |
| 112 | +again: | |
| 113 | + add rax, [rdi]; | |
| 114 | + add rdi, <span class="number">8</span>; | |
| 115 | + dec rsi; | |
| 116 | + jnz again; | |
| 117 | +done: | |
| 118 | + ret; | |
| 119 | +<span class="kw">end</span> sum; | |
| 120 | + | |
| 121 | +<span class="comment">(* the same in raz, to check it against *)</span> | |
| 122 | +<span class="kw">proc</span> sumRaz(a: []<span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 123 | +<span class="kw">var</span> i, t: <span class="ty">INT</span>; | |
| 124 | +<span class="kw">begin</span> | |
| 125 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(a) - <span class="number">1</span> <span class="kw">do</span> t := t + a[i]; <span class="kw">end</span>; | |
| 126 | + <span class="kw">return</span> t; | |
| 127 | +<span class="kw">end</span>; | |
| 128 | + | |
| 129 | +<span class="kw">proc</span> main*; | |
| 130 | +<span class="kw">var</span> a: [<span class="number">6</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 131 | +<span class="kw">begin</span> | |
| 132 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> a[i] := (i + <span class="number">1</span>) * <span class="number">100</span>; <span class="kw">end</span>; | |
| 133 | + Out.int(sum(<span class="ty">ADR</span>(a[<span class="number">0</span>]), <span class="number">6</span>)); Out.char(<span class="string">' '</span>); | |
| 134 | + Out.int(sumRaz(a)); Out.char(<span class="string">' '</span>); | |
| 135 | + Out.int(sum(<span class="ty">ADR</span>(a[<span class="number">0</span>]), <span class="number">0</span>)); Out.ln; | |
| 136 | +<span class="kw">end</span>; | |
| 137 | + | |
| 138 | +<span class="kw">end</span> Sum.</code></pre> | |
| 139 | +<pre class="output"><code>2100 2100 0 | |
| 140 | +</code></pre> | |
| 141 | +<p>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.</p> | |
| 142 | +<h2>Two results, and reals</h2> | |
| 143 | +<p>A second result goes in <code>rdx</code>. That is exactly where <code>idiv</code> leaves the remainder, so <code>divmod</code> is four instructions. Reals travel in the <code>xmm</code> registers.</p> | |
| 144 | +<div class="file"><span>Divmod.raz</span></div><pre class="code"><code><span class="kw">module</span> Divmod; | |
| 145 | +<span class="kw">import</span> Out, Fmt; | |
| 146 | + | |
| 147 | +<span class="comment">(* quotient and remainder, as idiv gives them: rax and rdx *)</span> | |
| 148 | +<span class="kw">proc</span> divmod(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 149 | +<span class="kw">code</span> | |
| 150 | + mov rax, rdi; | |
| 151 | + cqo; | |
| 152 | + idiv rsi; | |
| 153 | + ret; | |
| 154 | +<span class="kw">end</span> divmod; | |
| 155 | + | |
| 156 | +<span class="comment">(* a * x + b, on F64s in xmm0 to xmm2 *)</span> | |
| 157 | +<span class="kw">proc</span> fma(a, x, b: <span class="ty">F64</span>): <span class="ty">F64</span>; | |
| 158 | +<span class="kw">code</span> | |
| 159 | + mulsd xmm0, xmm1; | |
| 160 | + addsd xmm0, xmm2; | |
| 161 | + ret; | |
| 162 | +<span class="kw">end</span> fma; | |
| 163 | + | |
| 164 | +<span class="kw">proc</span> main*; | |
| 165 | +<span class="kw">var</span> q, r: <span class="ty">INT</span>; | |
| 166 | +<span class="kw">begin</span> | |
| 167 | + q, r := divmod(-<span class="number">17</span>, <span class="number">5</span>); | |
| 168 | + Out.int(q); Out.char(<span class="string">' '</span>); Out.int(r); Out.ln; | |
| 169 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.real(fma(<span class="number">2.0</span>, <span class="number">3.5</span>, <span class="number">0.25</span>), <span class="number">2</span>)]); | |
| 170 | +<span class="kw">end</span>; | |
| 171 | + | |
| 172 | +<span class="kw">end</span> Divmod.</code></pre> | |
| 173 | +<pre class="output"><code>-3 -2 | |
| 174 | +7.25 | |
| 175 | +</code></pre> | |
| 176 | +<p><code>idiv</code> 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.</p> | |
| 177 | +<h2>Keeping what isn't yours</h2> | |
| 178 | +<p>A procedure that uses <code>rbx</code> must put it back. <code>cpuid</code> clobbers <code>rbx</code>, so the vendor-string example saves it with <code>push</code> and restores it with <code>pop</code>, and keeps the buffer's address in <code>r8</code> while it works:</p> | |
| 179 | +<div class="file"><span>Vendor.raz</span></div><pre class="code"><code><span class="kw">module</span> Vendor; | |
| 180 | +<span class="kw">import</span> Out; | |
| 181 | + | |
| 182 | +<span class="comment">(* the 12 bytes of the processor vendor, in buf (rdi) *)</span> | |
| 183 | +<span class="kw">proc</span> vendor(buf: ^<span class="ty">U8</span>); | |
| 184 | +<span class="kw">code</span> | |
| 185 | + push rbx; | |
| 186 | + mov r8, rdi; | |
| 187 | + <span class="kw">xor</span> eax, eax; | |
| 188 | + cpuid; | |
| 189 | + mov [r8], ebx; | |
| 190 | + mov [r8 + <span class="number">4</span>], edx; | |
| 191 | + mov [r8 + <span class="number">8</span>], ecx; | |
| 192 | + pop rbx; | |
| 193 | + ret; | |
| 194 | +<span class="kw">end</span> vendor; | |
| 195 | + | |
| 196 | +<span class="kw">proc</span> main*; | |
| 197 | +<span class="kw">var</span> buf: [<span class="number">12</span>]<span class="ty">U8</span>; i: <span class="ty">INT</span>; ok: <span class="ty">BOOL</span>; | |
| 198 | +<span class="kw">begin</span> | |
| 199 | + vendor(<span class="ty">ADR</span>(buf[<span class="number">0</span>])); | |
| 200 | + ok := <span class="ty">true</span>; | |
| 201 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">11</span> <span class="kw">do</span> | |
| 202 | + <span class="kw">if</span> (buf[i] < <span class="string">' '</span>) <span class="kw">or</span> (buf[i] > <span class="string">'~'</span>) <span class="kw">then</span> ok := <span class="ty">false</span>; <span class="kw">end</span>; | |
| 203 | + <span class="kw">end</span>; | |
| 204 | + <span class="kw">if</span> ok <span class="kw">then</span> Out.str(<span class="string">"the vendor is 12 printable bytes\n"</span>); <span class="kw">end</span>; | |
| 205 | +<span class="kw">end</span>; | |
| 206 | + | |
| 207 | +<span class="kw">end</span> Vendor.</code></pre> | |
| 208 | +<pre class="output"><code>the vendor is 12 printable bytes | |
| 209 | +</code></pre> | |
| 210 | +<h2>What goes wrong</h2> | |
| 211 | +<p>A code procedure that breaks its rules breaks the program, and what follows isn't defined. Writing through a wrong pointer, a changed <code>rbx</code>, a missing <code>ret</code>, 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.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="targets.html">← One module, one file per target</a><a href="index.html">Contents</a><a class="next" href="syscalls.html">System calls →</a></div></article></div> | |
| 212 | +</main> | |
| 213 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 214 | +</body> | |
| 215 | +</html> |
| @@ -0,0 +1,195 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Atomics - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html" aria-current="page">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">Shared memory · lesson 15 of 18</p><h1>Atomics</h1> | |
| 38 | +<p>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:</p> | |
| 39 | +<p>| Call | Does | |---|---| | <code>XADD(p, x)</code> | adds <code>x</code> to <code>p^</code> and returns the value before | | <code>XCHG(p, x)</code> | sets <code>p^ := x</code> and returns the value before | | <code>CAS(p, old, new)</code> | if <code>p^ = old</code>, sets <code>p^ := new</code> and returns <code>true</code>; otherwise <code>false</code> |</p> | |
| 40 | +<p><code>p</code> is a <code>^T</code> or <code>^VOLATILE T</code> where <code>T</code> is <code>INT</code>, <code>UINT</code> or a pointer type (<code>INT</code> or <code>UINT</code> for <code>XADD</code>). They compile to single x86-64 instructions: <code>lock xadd</code>, <code>xchg</code> (which is always locked when it touches memory) and <code>lock cmpxchg</code>:</p> | |
| 41 | +<div class="file"><span>Ops.raz</span></div><pre class="code"><code><span class="kw">module</span> Ops; | |
| 42 | + | |
| 43 | +<span class="kw">var</span> counter: <span class="ty">INT</span>; | |
| 44 | + | |
| 45 | +<span class="kw">proc</span> main*; | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + _ := <span class="ty">XADD</span>(<span class="ty">ADR</span>(counter), <span class="number">5</span>); | |
| 48 | + _ := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(counter), <span class="number">100</span>); | |
| 49 | + _ := <span class="ty">CAS</span>(<span class="ty">ADR</span>(counter), <span class="number">100</span>, <span class="number">7</span>); | |
| 50 | +<span class="kw">end</span>; | |
| 51 | + | |
| 52 | +<span class="kw">end</span> Ops.</code></pre> | |
| 53 | +<pre class="output term"><code><span class="cmd">$ raz -S Ops.raz | grep -i "lock\|xchg"</span> | |
| 54 | + 23 lock xadd [r8], rax | |
| 55 | + 8 _ := XCHG(ADR(counter), 100); | |
| 56 | + 43 xchg [r8], rax | |
| 57 | + 67 lock cmpxchg [r8], r10</code></pre> | |
| 58 | +<h2>What each one gives you</h2> | |
| 59 | +<p><code>XADD</code> is a counter, or a ticket dispenser: every caller gets a different number. <code>XCHG</code> takes the old value and leaves a new one, which is a flag, a swap, or the release of a lock. <code>CAS</code> is the general one: "if nobody changed it since I looked, change it". Most lock-free code is a loop around it.</p> | |
| 60 | +<div class="file"><span>Tickets.raz</span></div><pre class="code"><code><span class="kw">module</span> Tickets; | |
| 61 | +<span class="kw">import</span> Out, Thread; | |
| 62 | + | |
| 63 | +<span class="kw">var</span> | |
| 64 | + next: <span class="ty">INT</span>; <span class="comment">(* the next ticket to give out *)</span> | |
| 65 | + seen: [<span class="number">4000</span>]<span class="ty">U8</span>; <span class="comment">(* which tickets were taken, one byte each *)</span> | |
| 66 | + | |
| 67 | +<span class="kw">proc</span> work(_arg: ^<span class="ty">U8</span>); | |
| 68 | +<span class="kw">var</span> i, t: <span class="ty">INT</span>; | |
| 69 | +<span class="kw">begin</span> | |
| 70 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">1000</span> <span class="kw">do</span> | |
| 71 | + t := <span class="ty">XADD</span>(<span class="ty">ADR</span>(next), <span class="number">1</span>); <span class="comment">(* a ticket no other thread gets *)</span> | |
| 72 | + seen[t] := <span class="number">1</span>; | |
| 73 | + <span class="kw">end</span>; | |
| 74 | +<span class="kw">end</span>; | |
| 75 | + | |
| 76 | +<span class="kw">proc</span> main*; | |
| 77 | +<span class="kw">var</span> th: [<span class="number">4</span>]^Thread.Thread; i, taken: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 78 | +<span class="kw">begin</span> | |
| 79 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 80 | + th[i], err := Thread.spawn(work, <span class="ty">nil</span>); | |
| 81 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 82 | + <span class="kw">end</span>; | |
| 83 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 84 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3999</span> <span class="kw">do</span> taken := taken + <span class="ty">INT</span>(seen[i]); <span class="kw">end</span>; | |
| 85 | + Out.int(next); Out.char(<span class="string">' '</span>); Out.int(taken); Out.ln; | |
| 86 | +<span class="kw">end</span>; | |
| 87 | + | |
| 88 | +<span class="kw">end</span> Tickets.</code></pre> | |
| 89 | +<pre class="output"><code>4000 4000 | |
| 90 | +</code></pre> | |
| 91 | +<p>Four thousand tickets, four thousand different numbers, no two threads with the same one. Each thread writes into its own bytes of <code>seen</code>, so no plain write is shared.</p> | |
| 92 | +<h2>A compare-and-swap loop</h2> | |
| 93 | +<p>Anything that can be computed from the old value can be made atomic with a loop around <code>CAS</code>: 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.</p> | |
| 94 | +<div class="file"><span>Peak.raz</span></div><pre class="code"><code><span class="kw">module</span> Peak; | |
| 95 | +<span class="kw">import</span> Out, Thread; | |
| 96 | + | |
| 97 | +<span class="kw">var</span> peak: <span class="ty">INT</span>; | |
| 98 | + | |
| 99 | +<span class="comment">(* raises peak to v if v is bigger, however many threads call it *)</span> | |
| 100 | +<span class="kw">proc</span> raise(v: <span class="ty">INT</span>); | |
| 101 | +<span class="kw">var</span> seen: <span class="ty">INT</span>; | |
| 102 | +<span class="kw">begin</span> | |
| 103 | + seen := peak; | |
| 104 | + <span class="kw">while</span> seen < v <span class="kw">do</span> | |
| 105 | + <span class="kw">if</span> <span class="ty">CAS</span>(<span class="ty">ADR</span>(peak), seen, v) <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 106 | + seen := peak; <span class="comment">(* someone changed it: look again *)</span> | |
| 107 | + <span class="kw">end</span>; | |
| 108 | +<span class="kw">end</span>; | |
| 109 | + | |
| 110 | +<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); | |
| 111 | +<span class="kw">var</span> i, base: <span class="ty">INT</span>; | |
| 112 | +<span class="kw">begin</span> | |
| 113 | + base := <span class="ty">INT</span>(arg); | |
| 114 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">999</span> <span class="kw">do</span> raise(base + i * <span class="number">7</span> <span class="kw">mod</span> <span class="number">1001</span>); <span class="kw">end</span>; | |
| 115 | +<span class="kw">end</span>; | |
| 116 | + | |
| 117 | +<span class="kw">proc</span> main*; | |
| 118 | +<span class="kw">var</span> th: [<span class="number">4</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 119 | +<span class="kw">begin</span> | |
| 120 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 121 | + th[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(i * <span class="number">1000</span>)); | |
| 122 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 123 | + <span class="kw">end</span>; | |
| 124 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 125 | + Out.int(peak); Out.ln; | |
| 126 | +<span class="kw">end</span>; | |
| 127 | + | |
| 128 | +<span class="kw">end</span> Peak.</code></pre> | |
| 129 | +<pre class="output"><code>3994 | |
| 130 | +</code></pre> | |
| 131 | +<p>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.</p> | |
| 132 | +<h2>A lock, from first principles</h2> | |
| 133 | +<p>A lock is a word that is 0 when free and 1 when held. To take it, <code>CAS</code> it from 0 to 1; if that fails, someone holds it, so try again. To give it up, <code>XCHG</code> it back to 0. This is exactly the library's <code>Lock</code>, printed from <code>lib/Lock.raz</code>:</p> | |
| 134 | +<pre class="output term"><code><span class="cmd">$ sed -n '/^type Lock/,/^proc main/p' $RAZLIB/Lock.raz | head -n -2</span> | |
| 135 | +type Lock* = record held: INT; end; | |
| 136 | + | |
| 137 | +(* Takes l, waiting while another thread holds it. *) | |
| 138 | +proc take*(l: ^Lock); | |
| 139 | +var tries: INT; | |
| 140 | +begin | |
| 141 | + tries := 0; | |
| 142 | + while not CAS(ADR(l^.held), 0, 1) do | |
| 143 | + INC(tries); | |
| 144 | + if tries = 64 then Sys.yield; tries := 0; end; | |
| 145 | + end; | |
| 146 | +end; | |
| 147 | + | |
| 148 | +(* Gives up l, which the caller holds. *) | |
| 149 | +proc give*(l: ^Lock); | |
| 150 | +begin | |
| 151 | + _ := XCHG(ADR(l^.held), 0); | |
| 152 | +end;</code></pre> | |
| 153 | +<p>And here is a use of it: a structure with two fields that must stay in step, which no single atomic can protect.</p> | |
| 154 | +<div class="file"><span>Account.raz</span></div><pre class="code"><code><span class="kw">module</span> Account; | |
| 155 | +<span class="kw">import</span> Out, Lock, Thread; | |
| 156 | + | |
| 157 | +<span class="kw">var</span> | |
| 158 | + lock: Lock.Lock; | |
| 159 | + deposits, balance: <span class="ty">INT</span>; <span class="comment">(* balance = 3 * deposits, always, under lock *)</span> | |
| 160 | + | |
| 161 | +<span class="kw">proc</span> work(_arg: ^<span class="ty">U8</span>); | |
| 162 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 163 | +<span class="kw">begin</span> | |
| 164 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">20000</span> <span class="kw">do</span> | |
| 165 | + Lock.take(<span class="ty">ADR</span>(lock)); | |
| 166 | + <span class="ty">INC</span>(deposits); | |
| 167 | + <span class="ty">INC</span>(balance, <span class="number">3</span>); | |
| 168 | + Lock.give(<span class="ty">ADR</span>(lock)); | |
| 169 | + <span class="kw">end</span>; | |
| 170 | +<span class="kw">end</span>; | |
| 171 | + | |
| 172 | +<span class="kw">proc</span> main*; | |
| 173 | +<span class="kw">var</span> th: [<span class="number">4</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 174 | +<span class="kw">begin</span> | |
| 175 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 176 | + th[i], err := Thread.spawn(work, <span class="ty">nil</span>); | |
| 177 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 178 | + <span class="kw">end</span>; | |
| 179 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 180 | + Out.int(deposits); Out.char(<span class="string">' '</span>); Out.int(balance); Out.ln; | |
| 181 | + <span class="kw">if</span> balance = <span class="number">3</span> * deposits <span class="kw">then</span> Out.str(<span class="string">"in step\n"</span>); <span class="kw">end</span>; | |
| 182 | +<span class="kw">end</span>; | |
| 183 | + | |
| 184 | +<span class="kw">end</span> Account.</code></pre> | |
| 185 | +<pre class="output"><code>80000 240000 | |
| 186 | +in step | |
| 187 | +</code></pre> | |
| 188 | +<p>A <code>Lock</code> spins, giving up the processor now and then, so it is for sections of a few instructions. <code>Thread.Mutex</code> 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.</p> | |
| 189 | +<h2>Choosing</h2> | |
| 190 | +<ul><li>A counter, a ticket, a flag: <code>XADD</code> or <code>XCHG</code>.</li><li>A value computed from the old one: a <code>CAS</code> loop.</li><li>Several variables that must change together: a <code>Lock</code> or a <code>Mutex</code>. Don't try to be clever with several atomics; the one invariant spanning them is the thing that breaks.</li></ul> | |
| 191 | +<p>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.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="volatile.html">← Volatile</a><a href="index.html">Contents</a><a class="next" href="ordering.html">Ordering and publication →</a></div></article></div> | |
| 192 | +</main> | |
| 193 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 194 | +</body> | |
| 195 | +</html> |
| @@ -0,0 +1,193 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Strings and bytes - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html" aria-current="page">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">The library · lesson 2 of 18</p><h1>Strings and bytes</h1> | |
| 38 | +<p>A <code>[]U8</code> is both a string and a block of bytes. <code>Str</code> 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.</p> | |
| 39 | +<h2>Ordering and hashing</h2> | |
| 40 | +<p><code>Str.cmp</code> gives -1, 0 or 1, byte by byte, so it orders UTF-8 text by code point. <code>Str.eq</code> is equality. <code>Str.hash</code> is FNV-1a, 64 bits; it is what a <code>Map</code> of strings uses.</p> | |
| 41 | +<div class="file"><span>Order.raz</span></div><pre class="code"><code><span class="kw">module</span> Order; | |
| 42 | +<span class="kw">import</span> Out, Str, Fmt; | |
| 43 | + | |
| 44 | +<span class="kw">proc</span> main*; | |
| 45 | +<span class="kw">var</span> names: [<span class="number">4</span>][]<span class="ty">U8</span>; i, j: <span class="ty">INT</span>; t: []<span class="ty">U8</span>; | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + names := [<span class="string">"pear"</span>, <span class="string">"Apple"</span>, <span class="string">"fig"</span>, <span class="string">"apple"</span>]; | |
| 48 | + <span class="comment">(* a small insertion sort, with Str.cmp *)</span> | |
| 49 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 50 | + t := names[i]; | |
| 51 | + j := i - <span class="number">1</span>; | |
| 52 | + <span class="kw">while</span> (j >= <span class="number">0</span>) <span class="kw">and</span> (Str.cmp(names[j], t) > <span class="number">0</span>) <span class="kw">do</span> | |
| 53 | + names[j + <span class="number">1</span>] := names[j]; | |
| 54 | + <span class="ty">DEC</span>(j); | |
| 55 | + <span class="kw">end</span>; | |
| 56 | + names[j + <span class="number">1</span>] := t; | |
| 57 | + <span class="kw">end</span>; | |
| 58 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Out.str(names[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 59 | + Out.ln; | |
| 60 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.hex(Str.hash(<span class="string">"raz"</span>))]); | |
| 61 | + <span class="kw">if</span> Str.hash(<span class="string">"raz"</span>) = Str.hash(<span class="string">"raz"</span>) <span class="kw">then</span> Out.str(<span class="string">"stable\n"</span>); <span class="kw">end</span>; | |
| 62 | +<span class="kw">end</span>; | |
| 63 | + | |
| 64 | +<span class="kw">end</span> Order.</code></pre> | |
| 65 | +<pre class="output"><code>Apple apple fig pear | |
| 66 | +89F6BC1960FF4912 | |
| 67 | +stable | |
| 68 | +</code></pre> | |
| 69 | +<p>Upper case sorts before lower, since 'A' is 65 and 'a' is 97: <code>Str.cmp</code> doesn't pretend to know a language's alphabet.</p> | |
| 70 | +<h2>Keeping a string</h2> | |
| 71 | +<p>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, <code>Str.copy</code> takes memory from an allocator and says whether it got any.</p> | |
| 72 | +<div class="file"><span>Keep.raz</span></div><pre class="code"><code><span class="kw">module</span> Keep; | |
| 73 | +<span class="kw">import</span> Out, Str, Heap, Mem; | |
| 74 | + | |
| 75 | +<span class="kw">type</span> Entry = <span class="kw">record</span> name: []<span class="ty">U8</span>; n: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 76 | + | |
| 77 | +<span class="kw">var</span> entries: [<span class="number">3</span>]Entry; | |
| 78 | + | |
| 79 | +<span class="comment">(* remembers a name that the caller will overwrite *)</span> | |
| 80 | +<span class="kw">proc</span> remember(slot: <span class="ty">INT</span>; name: []<span class="ty">U8</span>); | |
| 81 | +<span class="kw">var</span> copy: []<span class="ty">U8</span>; ok: <span class="ty">BOOL</span>; | |
| 82 | +<span class="kw">begin</span> | |
| 83 | + copy, ok := Str.copy(Heap.heap, name); | |
| 84 | + <span class="kw">if</span> ok <span class="kw">then</span> entries[slot].name := copy; entries[slot].n := slot; <span class="kw">end</span>; | |
| 85 | +<span class="kw">end</span>; | |
| 86 | + | |
| 87 | +<span class="kw">proc</span> main*; | |
| 88 | +<span class="kw">var</span> scratch: [<span class="number">16</span>]<span class="ty">U8</span>; i: <span class="ty">INT</span>; | |
| 89 | +<span class="kw">begin</span> | |
| 90 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 91 | + scratch := <span class="string">"name-"</span>; | |
| 92 | + scratch[<span class="number">5</span>] := <span class="ty">U8</span>(<span class="string">'0'</span> + i); | |
| 93 | + remember(i, scratch[<span class="number">0</span>..<span class="number">6</span>]); | |
| 94 | + scratch := <span class="string">"overwritten!"</span>; | |
| 95 | + <span class="kw">end</span>; | |
| 96 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 97 | + Out.str(entries[i].name); Out.char(<span class="string">' '</span>); | |
| 98 | + Mem.free(Heap.heap, ^<span class="ty">U8</span>(<span class="ty">ADR</span>(entries[i].name[<span class="number">0</span>]))); | |
| 99 | + <span class="kw">end</span>; | |
| 100 | + Out.ln; | |
| 101 | +<span class="kw">end</span>; | |
| 102 | + | |
| 103 | +<span class="kw">end</span> Keep.</code></pre> | |
| 104 | +<pre class="output"><code>name-0 name-1 name-2 | |
| 105 | +</code></pre> | |
| 106 | +<h2>Binary formats</h2> | |
| 107 | +<p>A file format or a network protocol has a byte order of its own, not the machine's. <code>Str.le</code> and <code>Str.be</code> read an unsigned number of up to 8 bytes in a fixed order (little- or big-endian) and <code>Str.putLE</code> and <code>Str.putBE</code> 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.</p> | |
| 108 | +<p>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.</p> | |
| 109 | +<div class="file"><span>Frame.raz</span></div><pre class="code"><code><span class="kw">module</span> Frame; | |
| 110 | +<span class="kw">import</span> Out, Fmt, Str; | |
| 111 | + | |
| 112 | +<span class="kw">const</span> HeaderSize = <span class="number">10</span>; | |
| 113 | + | |
| 114 | +<span class="comment">(* the sum of the bytes of data, all mod 2^32 *)</span> | |
| 115 | +<span class="kw">proc</span> checksum(data: []<span class="ty">U8</span>): <span class="ty">U32</span>; | |
| 116 | +<span class="kw">var</span> i: <span class="ty">INT</span>; sum: <span class="ty">U32</span>; | |
| 117 | +<span class="kw">begin</span> | |
| 118 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(data) - <span class="number">1</span> <span class="kw">do</span> sum := sum + <span class="ty">U32</span>(data[i]); <span class="kw">end</span>; | |
| 119 | + <span class="kw">return</span> sum; | |
| 120 | +<span class="kw">end</span>; | |
| 121 | + | |
| 122 | +<span class="comment">(* writes a frame to out, which must have room; its length *)</span> | |
| 123 | +<span class="kw">proc</span> pack(out: []<span class="ty">U8</span>; tag, data: []<span class="ty">U8</span>): <span class="ty">INT</span>; | |
| 124 | +<span class="kw">begin</span> | |
| 125 | + COPY(out[<span class="number">0</span>..<span class="number">4</span>], tag); | |
| 126 | + Str.putBE(out[<span class="number">4</span>..<span class="number">6</span>], <span class="ty">U64</span>(<span class="ty">LEN</span>(data))); | |
| 127 | + Str.putLE(out[<span class="number">6</span>..<span class="number">10</span>], <span class="ty">U64</span>(checksum(data))); | |
| 128 | + COPY(out[HeaderSize..HeaderSize + <span class="ty">LEN</span>(data)], data); | |
| 129 | + <span class="kw">return</span> HeaderSize + <span class="ty">LEN</span>(data); | |
| 130 | +<span class="kw">end</span>; | |
| 131 | + | |
| 132 | +<span class="kw">proc</span> main*; | |
| 133 | +<span class="kw">var</span> buf: [<span class="number">64</span>]<span class="ty">U8</span>; n, len: <span class="ty">INT</span>; sum: <span class="ty">U32</span>; i: <span class="ty">INT</span>; | |
| 134 | +<span class="kw">begin</span> | |
| 135 | + n := pack(buf, <span class="string">"DATA"</span>, <span class="string">"hello"</span>); | |
| 136 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> n - <span class="number">1</span> <span class="kw">do</span> | |
| 137 | + Out.hex(<span class="ty">U64</span>(buf[i]), <span class="number">2</span>); Out.char(<span class="string">' '</span>); | |
| 138 | + <span class="kw">end</span>; | |
| 139 | + Out.ln; | |
| 140 | + <span class="comment">(* and back *)</span> | |
| 141 | + len := <span class="ty">INT</span>(Str.be(buf[<span class="number">4</span>..<span class="number">6</span>])); | |
| 142 | + sum := <span class="ty">U32</span>(Str.le(buf[<span class="number">6</span>..<span class="number">10</span>])); | |
| 143 | + Fmt.print(<span class="string">"tag {}, {} bytes, checksum {}, "</span>, [Fmt.str(buf[<span class="number">0</span>..<span class="number">4</span>]), Fmt.int(len), Fmt.hex(<span class="ty">U64</span>(sum))]); | |
| 144 | + <span class="kw">if</span> sum = checksum(buf[HeaderSize..HeaderSize + len]) <span class="kw">then</span> | |
| 145 | + Out.str(<span class="string">"valid: "</span>); Out.str(buf[HeaderSize..HeaderSize + len]); | |
| 146 | + <span class="kw">else</span> | |
| 147 | + Out.str(<span class="string">"corrupt"</span>); | |
| 148 | + <span class="kw">end</span>; | |
| 149 | + Out.ln; | |
| 150 | +<span class="kw">end</span>; | |
| 151 | + | |
| 152 | +<span class="kw">end</span> Frame.</code></pre> | |
| 153 | +<pre class="output"><code>44 41 54 41 00 05 14 02 00 00 68 65 6C 6C 6F | |
| 154 | +tag DATA, 5 bytes, checksum 214, valid: hello | |
| 155 | +</code></pre> | |
| 156 | +<p>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.</p> | |
| 157 | +<h2>Numbers and text</h2> | |
| 158 | +<p><code>Str.toInt</code> reads a decimal number with an optional sign and nothing else, and says whether it was one. <code>Fmt</code> goes the other way. <code>Str.encode</code> and <code>Str.decode</code> move between characters and UTF-8, as the first tour showed.</p> | |
| 159 | +<div class="file"><span>Numbers.raz</span></div><pre class="code"><code><span class="kw">module</span> Numbers; | |
| 160 | +<span class="kw">import</span> Out, Str; | |
| 161 | + | |
| 162 | +<span class="comment">(* the sum of the numbers in a comma separated list, or -1 if any isn't *)</span> | |
| 163 | +<span class="kw">proc</span> total(s: []<span class="ty">U8</span>): <span class="ty">I64</span>; | |
| 164 | +<span class="kw">var</span> start, i: <span class="ty">INT</span>; sum, n: <span class="ty">I64</span>; ok: <span class="ty">BOOL</span>; | |
| 165 | +<span class="kw">begin</span> | |
| 166 | + start := <span class="number">0</span>; | |
| 167 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) <span class="kw">do</span> | |
| 168 | + <span class="kw">if</span> (i = <span class="ty">LEN</span>(s)) <span class="kw">or</span> (s[i] = <span class="string">','</span>) <span class="kw">then</span> | |
| 169 | + n, ok := Str.toInt(s[start..i]); | |
| 170 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> <span class="kw">return</span> -<span class="number">1</span>; <span class="kw">end</span>; | |
| 171 | + sum := sum + n; | |
| 172 | + start := i + <span class="number">1</span>; | |
| 173 | + <span class="kw">end</span>; | |
| 174 | + <span class="kw">end</span>; | |
| 175 | + <span class="kw">return</span> sum; | |
| 176 | +<span class="kw">end</span>; | |
| 177 | + | |
| 178 | +<span class="kw">proc</span> main*; | |
| 179 | +<span class="kw">begin</span> | |
| 180 | + Out.int(total(<span class="string">"10,20,-5,+7"</span>)); Out.ln; | |
| 181 | + Out.int(total(<span class="string">"10,x,20"</span>)); Out.ln; | |
| 182 | + Out.int(total(<span class="string">"10,,20"</span>)); Out.ln; | |
| 183 | +<span class="kw">end</span>; | |
| 184 | + | |
| 185 | +<span class="kw">end</span> Numbers.</code></pre> | |
| 186 | +<pre class="output"><code>32 | |
| 187 | +-1 | |
| 188 | +-1 | |
| 189 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="fmt.html">← Output and formatting</a><a href="index.html">Contents</a><a class="next" href="collections.html">Lists, maps and sorting →</a></div></article></div> | |
| 190 | +</main> | |
| 191 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 192 | +</body> | |
| 193 | +</html> |
| @@ -0,0 +1,162 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Lists, maps and sorting - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html" aria-current="page">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">The library · lesson 3 of 18</p><h1>Lists, maps and sorting</h1> | |
| 38 | +<p>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.</p> | |
| 39 | +<h2><code>List(T)</code></h2> | |
| 40 | +<p>A singly linked list with <code>push</code> at the front, <code>pop</code> 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.</p> | |
| 41 | +<div class="file"><span>Pile.raz</span></div><pre class="code"><code><span class="kw">module</span> Pile; | |
| 42 | +<span class="kw">import</span> Out, Heap, Ints := List(<span class="ty">INT</span>); | |
| 43 | + | |
| 44 | +<span class="kw">proc</span> main*; | |
| 45 | +<span class="kw">var</span> l: Ints.List; n: ^Ints.Node; v: <span class="ty">INT</span>; | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + Ints.init(<span class="ty">ADR</span>(l), Heap.heap); | |
| 48 | + <span class="kw">defer</span> Ints.clear(<span class="ty">ADR</span>(l)); | |
| 49 | + <span class="kw">for</span> v := <span class="number">1</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> _ := Ints.push(<span class="ty">ADR</span>(l), v * v); <span class="kw">end</span>; | |
| 50 | + Ints.reverse(<span class="ty">ADR</span>(l)); <span class="comment">(* oldest first *)</span> | |
| 51 | + n := l.head; | |
| 52 | + <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> Out.int(n^.val); Out.char(<span class="string">' '</span>); n := n^.next; <span class="kw">end</span>; | |
| 53 | + Out.ln; | |
| 54 | + v, _ := Ints.pop(<span class="ty">ADR</span>(l)); | |
| 55 | + Out.int(v); Out.str(<span class="string">" popped, "</span>); Out.int(l.len); Out.str(<span class="string">" left\n"</span>); | |
| 56 | +<span class="kw">end</span>; | |
| 57 | + | |
| 58 | +<span class="kw">end</span> Pile.</code></pre> | |
| 59 | +<pre class="output"><code>1 4 9 16 25 | |
| 60 | +1 popped, 4 left | |
| 61 | +</code></pre> | |
| 62 | +<h2><code>Map(K, V; hash, eq)</code></h2> | |
| 63 | +<p>A hash map. Its key's hash and equality are procedure arguments, so any type can be a key. <code>put</code> replaces what a key maps to; <code>get</code> says what it maps to and whether it maps to anything; <code>remove</code> says whether the key was there. <code>next</code> 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.</p> | |
| 64 | +<div class="file"><span>Ages.raz</span></div><pre class="code"><code><span class="kw">module</span> Ages; | |
| 65 | +<span class="kw">import</span> Out, Fmt, Str, Heap, Book := Map([]<span class="ty">U8</span>, <span class="ty">INT</span>, Str.hash, Str.eq); | |
| 66 | + | |
| 67 | +<span class="kw">proc</span> main*; | |
| 68 | +<span class="kw">var</span> m: Book.Map; age: <span class="ty">INT</span>; found, ok: <span class="ty">BOOL</span>; i: <span class="ty">INT</span>; v: <span class="ty">INT</span>; | |
| 69 | +<span class="kw">begin</span> | |
| 70 | + Book.init(<span class="ty">ADR</span>(m), Heap.heap); | |
| 71 | + _ := Book.put(<span class="ty">ADR</span>(m), <span class="string">"ada"</span>, <span class="number">36</span>); | |
| 72 | + _ := Book.put(<span class="ty">ADR</span>(m), <span class="string">"grace"</span>, <span class="number">45</span>); | |
| 73 | + _ := Book.put(<span class="ty">ADR</span>(m), <span class="string">"alan"</span>, <span class="number">41</span>); | |
| 74 | + _ := Book.put(<span class="ty">ADR</span>(m), <span class="string">"ada"</span>, <span class="number">37</span>); <span class="comment">(* replaces *)</span> | |
| 75 | + age, found := Book.get(<span class="ty">ADR</span>(m), <span class="string">"ada"</span>); | |
| 76 | + Fmt.print(<span class="string">"ada: {} ({})\n"</span>, [Fmt.int(age), Fmt.bool(found)]); | |
| 77 | + age, found := Book.get(<span class="ty">ADR</span>(m), <span class="string">"linus"</span>); | |
| 78 | + Fmt.print(<span class="string">"linus: {} ({})\n"</span>, [Fmt.int(age), Fmt.bool(found)]); | |
| 79 | + ok := Book.remove(<span class="ty">ADR</span>(m), <span class="string">"alan"</span>); | |
| 80 | + Fmt.print(<span class="string">"{} entries, removed {}\n"</span>, [Fmt.int(m.len), Fmt.bool(ok)]); | |
| 81 | + v := <span class="number">0</span>; | |
| 82 | + i, _, age := Book.next(<span class="ty">ADR</span>(m), <span class="number">0</span>); | |
| 83 | + <span class="kw">while</span> i >= <span class="number">0</span> <span class="kw">do</span> | |
| 84 | + <span class="ty">INC</span>(v, age); | |
| 85 | + i, _, age := Book.next(<span class="ty">ADR</span>(m), i); | |
| 86 | + <span class="kw">end</span>; | |
| 87 | + Out.int(v); Out.str(<span class="string">" years in all\n"</span>); | |
| 88 | +<span class="kw">end</span>; | |
| 89 | + | |
| 90 | +<span class="kw">end</span> Ages.</code></pre> | |
| 91 | +<pre class="output"><code>ada: 37 (true) | |
| 92 | +linus: 0 (false) | |
| 93 | +2 entries, removed true | |
| 94 | +82 years in all | |
| 95 | +</code></pre> | |
| 96 | +<p>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.</p> | |
| 97 | +<h2><code>Sort(T; less)</code></h2> | |
| 98 | +<p>An in-place sort of a slice, by a <code>less</code> procedure, in <code>n log n</code> at most and with no memory of its own. Elements equal by <code>less</code> may change places.</p> | |
| 99 | +<h2>Putting them together</h2> | |
| 100 | +<p>Counting words, then listing them by count and then alphabetically: a <code>Map</code> for the counts, an array of records to sort, and <code>Sort</code> with a two-level <code>less</code>.</p> | |
| 101 | +<div class="file"><span>Freq.raz</span></div><pre class="code"><code><span class="kw">module</span> Freq; | |
| 102 | +<span class="kw">import</span> Fmt, Str, Heap, | |
| 103 | + Count := Map([]<span class="ty">U8</span>, <span class="ty">INT</span>, Str.hash, Str.eq), | |
| 104 | + Rank := Sort(Entry, before); | |
| 105 | + | |
| 106 | +<span class="kw">type</span> Entry = <span class="kw">record</span> word: []<span class="ty">U8</span>; n: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 107 | + | |
| 108 | +<span class="kw">const</span> Text = <span class="string">"the cat and the hat and the bat sat on the mat and the cat sat"</span>; | |
| 109 | + | |
| 110 | +<span class="comment">(* more first; equal counts alphabetically *)</span> | |
| 111 | +<span class="kw">proc</span> before(a, b: Entry): <span class="ty">BOOL</span>; | |
| 112 | +<span class="kw">begin</span> | |
| 113 | + <span class="kw">if</span> a.n # b.n <span class="kw">then</span> <span class="kw">return</span> a.n > b.n; <span class="kw">end</span>; | |
| 114 | + <span class="kw">return</span> Str.cmp(a.word, b.word) < <span class="number">0</span>; | |
| 115 | +<span class="kw">end</span>; | |
| 116 | + | |
| 117 | +<span class="kw">proc</span> main*; | |
| 118 | +<span class="kw">var</span> | |
| 119 | + m: Count.Map; entries: [<span class="number">32</span>]Entry; i, start, k, n, found: <span class="ty">INT</span>; | |
| 120 | + w: []<span class="ty">U8</span>; key: []<span class="ty">U8</span>; v: <span class="ty">INT</span>; | |
| 121 | +<span class="kw">begin</span> | |
| 122 | + Count.init(<span class="ty">ADR</span>(m), Heap.heap); | |
| 123 | + start := <span class="number">0</span>; | |
| 124 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(Text) <span class="kw">do</span> | |
| 125 | + <span class="kw">if</span> (i = <span class="ty">LEN</span>(Text)) <span class="kw">or</span> (Text[i] = <span class="string">' '</span>) <span class="kw">then</span> | |
| 126 | + w := Text[start..i]; | |
| 127 | + k, _ := Count.get(<span class="ty">ADR</span>(m), w); | |
| 128 | + _ := Count.put(<span class="ty">ADR</span>(m), w, k + <span class="number">1</span>); | |
| 129 | + start := i + <span class="number">1</span>; | |
| 130 | + <span class="kw">end</span>; | |
| 131 | + <span class="kw">end</span>; | |
| 132 | + n := <span class="number">0</span>; | |
| 133 | + found, key, v := Count.next(<span class="ty">ADR</span>(m), <span class="number">0</span>); | |
| 134 | + <span class="kw">while</span> found >= <span class="number">0</span> <span class="kw">do</span> | |
| 135 | + entries[n].word := key; | |
| 136 | + entries[n].n := v; | |
| 137 | + <span class="ty">INC</span>(n); | |
| 138 | + found, key, v := Count.next(<span class="ty">ADR</span>(m), found); | |
| 139 | + <span class="kw">end</span>; | |
| 140 | + Rank.sort(entries[<span class="number">0</span>..n]); | |
| 141 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> n - <span class="number">1</span> <span class="kw">do</span> | |
| 142 | + Fmt.print(<span class="string">"{} {}\n"</span>, [Fmt.int(entries[i].n), Fmt.str(entries[i].word)]); | |
| 143 | + <span class="kw">end</span>; | |
| 144 | +<span class="kw">end</span>; | |
| 145 | + | |
| 146 | +<span class="kw">end</span> Freq.</code></pre> | |
| 147 | +<pre class="output"><code>5 the | |
| 148 | +3 and | |
| 149 | +2 cat | |
| 150 | +2 sat | |
| 151 | +1 bat | |
| 152 | +1 hat | |
| 153 | +1 mat | |
| 154 | +1 on | |
| 155 | +</code></pre> | |
| 156 | +<p>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 <code>Str.copy</code>.</p> | |
| 157 | +<h2>Choosing</h2> | |
| 158 | +<p>Use a <code>List</code> when you push and pop at one end and walk it in order. Use a <code>Map</code> when you look things up by key. Use an array and <code>Sort</code> when you know the size and want an order. When none of them fits, they are each under a hundred lines of raz in <code>lib/</code>, and the advanced tour's allocator lesson shows what is underneath.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="bytes.html">← Strings and bytes</a><a href="index.html">Contents</a><a class="next" href="files.html">Files and the command line →</a></div></article></div> | |
| 159 | +</main> | |
| 160 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 161 | +</body> | |
| 162 | +</html> |
| @@ -0,0 +1,227 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Files and the command line - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html" aria-current="page">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">The library · lesson 4 of 18</p><h1>Files and the command line</h1> | |
| 38 | +<p><code>Files</code> is for the common case: a whole file read or written in one call. <code>Sys</code> is the system underneath, for everything else. <code>Opt</code> reads a command line from a table, so that the help and the error messages can't drift from the code.</p> | |
| 39 | +<h2>A whole file</h2> | |
| 40 | +<p><code>Files.write(path, data)</code> makes the file hold <code>data</code>, and <code>Files.read(path, b)</code> adds the whole file to a <code>Buf</code>. Both say whether they worked.</p> | |
| 41 | +<div class="file"><span>Notes.raz</span></div><pre class="code"><code><span class="kw">module</span> Notes; | |
| 42 | +<span class="kw">import</span> Out, Files, Buf, Heap; | |
| 43 | + | |
| 44 | +<span class="kw">proc</span> main*; | |
| 45 | +<span class="kw">var</span> b: Buf.Buf; ok: <span class="ty">BOOL</span>; | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + ok := Files.write(<span class="string">"notes.txt"</span>, <span class="string">"first line\nsecond line\n"</span>); | |
| 48 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Out.str(<span class="string">"can't write\n"</span>); <span class="kw">return</span>; <span class="kw">end</span>; | |
| 49 | + Buf.init(<span class="ty">ADR</span>(b), Heap.heap); | |
| 50 | + <span class="kw">defer</span> Buf.done(<span class="ty">ADR</span>(b)); | |
| 51 | + ok := Files.read(<span class="string">"notes.txt"</span>, <span class="ty">ADR</span>(b)); | |
| 52 | + <span class="kw">if</span> ok <span class="kw">then</span> | |
| 53 | + Out.int(b.len); Out.str(<span class="string">" bytes: "</span>); Out.str(Buf.bytes(<span class="ty">ADR</span>(b))); | |
| 54 | + <span class="kw">end</span>; | |
| 55 | + ok := Files.read(<span class="string">"missing.txt"</span>, <span class="ty">ADR</span>(b)); | |
| 56 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Out.str(<span class="string">"missing.txt: not there\n"</span>); <span class="kw">end</span>; | |
| 57 | +<span class="kw">end</span>; | |
| 58 | + | |
| 59 | +<span class="kw">end</span> Notes.</code></pre> | |
| 60 | +<pre class="output"><code>23 bytes: first line | |
| 61 | +second line | |
| 62 | +missing.txt: not there | |
| 63 | +</code></pre> | |
| 64 | +<h2>Descriptors</h2> | |
| 65 | +<p>Underneath, a file is a descriptor, an <code>INT</code>. <code>Sys.open</code> takes the path and the way to open it as a set; <code>read</code>, <code>write</code>, <code>seek</code> and <code>close</code> 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.</p> | |
| 66 | +<div class="file"><span>Count.raz</span></div><pre class="code"><code><span class="kw">module</span> Count; | |
| 67 | +<span class="kw">import</span> Out, Sys; | |
| 68 | + | |
| 69 | +<span class="comment">(* the lines of the file at path, or minus an errno *)</span> | |
| 70 | +<span class="kw">proc</span> lines(path: []<span class="ty">U8</span>): <span class="ty">INT</span>; | |
| 71 | +<span class="kw">var</span> fd, n, i, count: <span class="ty">INT</span>; buf: [<span class="number">4096</span>]<span class="ty">U8</span>; | |
| 72 | +<span class="kw">begin</span> | |
| 73 | + fd := Sys.openRead(path); | |
| 74 | + <span class="kw">if</span> fd < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> fd; <span class="kw">end</span>; | |
| 75 | + <span class="kw">defer</span> Sys.close(fd); | |
| 76 | + n := Sys.read(fd, buf); | |
| 77 | + <span class="kw">while</span> n > <span class="number">0</span> <span class="kw">do</span> | |
| 78 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> n - <span class="number">1</span> <span class="kw">do</span> | |
| 79 | + <span class="kw">if</span> buf[i] = <span class="string">'\n'</span> <span class="kw">then</span> <span class="ty">INC</span>(count); <span class="kw">end</span>; | |
| 80 | + <span class="kw">end</span>; | |
| 81 | + n := Sys.read(fd, buf); | |
| 82 | + <span class="kw">end</span>; | |
| 83 | + <span class="kw">if</span> n < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> n; <span class="kw">end</span>; | |
| 84 | + <span class="kw">return</span> count; | |
| 85 | +<span class="kw">end</span>; | |
| 86 | + | |
| 87 | +<span class="kw">proc</span> main*; | |
| 88 | +<span class="kw">var</span> fd: <span class="ty">INT</span>; pos: <span class="ty">I64</span>; | |
| 89 | +<span class="kw">begin</span> | |
| 90 | + fd := Sys.create(<span class="string">"log.txt"</span>); | |
| 91 | + _ := Sys.write(fd, <span class="string">"a\nb\nc\n"</span>); | |
| 92 | + pos := Sys.seek(fd, <span class="number">2</span>, <span class="ty">false</span>); <span class="comment">(* from the start *)</span> | |
| 93 | + Out.int(pos); Out.ln; | |
| 94 | + Sys.close(fd); | |
| 95 | + Out.int(lines(<span class="string">"log.txt"</span>)); Out.str(<span class="string">" lines\n"</span>); | |
| 96 | + Out.int(lines(<span class="string">"/no/such/file"</span>)); Out.ln; <span class="comment">(* -2: ENOENT *)</span> | |
| 97 | + fd := Sys.open(<span class="string">"log.txt"</span>, {Sys.writing, Sys.appending}); | |
| 98 | + _ := Sys.write(fd, <span class="string">"d\n"</span>); | |
| 99 | + Sys.close(fd); | |
| 100 | + Out.int(lines(<span class="string">"log.txt"</span>)); Out.str(<span class="string">" lines now\n"</span>); | |
| 101 | +<span class="kw">end</span>; | |
| 102 | + | |
| 103 | +<span class="kw">end</span> Count.</code></pre> | |
| 104 | +<pre class="output"><code>2 | |
| 105 | +3 lines | |
| 106 | +-2 | |
| 107 | +4 lines now | |
| 108 | +</code></pre> | |
| 109 | +<h2>Looking at a file, and a directory</h2> | |
| 110 | +<p><code>Sys.info</code> says a file's size, modification time, permissions, and whether it is a directory, a regular file or a link. <code>Sys.openDir</code> and <code>nextEntry</code> list a directory, in no particular order, so a program that prints one sorts it first. A name from <code>nextEntry</code> is good only until the next call, so the program keeps a copy.</p> | |
| 111 | +<div class="file"><span>Tree.raz</span></div><pre class="code"><code><span class="kw">module</span> Tree; | |
| 112 | +<span class="kw">import</span> Out, Sys, Str, Heap, Mem, Buf, Order := Sort([]<span class="ty">U8</span>, before); | |
| 113 | + | |
| 114 | +<span class="kw">proc</span> before(a, b: []<span class="ty">U8</span>): <span class="ty">BOOL</span>; | |
| 115 | +<span class="kw">begin</span> | |
| 116 | + <span class="kw">return</span> Str.cmp(a, b) < <span class="number">0</span>; | |
| 117 | +<span class="kw">end</span>; | |
| 118 | + | |
| 119 | +<span class="comment">(* a file made to hold text *)</span> | |
| 120 | +<span class="kw">proc</span> put(path, text: []<span class="ty">U8</span>); | |
| 121 | +<span class="kw">var</span> fd: <span class="ty">INT</span>; | |
| 122 | +<span class="kw">begin</span> | |
| 123 | + fd := Sys.create(path); | |
| 124 | + _ := Sys.write(fd, text); | |
| 125 | + Sys.close(fd); | |
| 126 | +<span class="kw">end</span>; | |
| 127 | + | |
| 128 | +<span class="kw">proc</span> main*; | |
| 129 | +<span class="kw">var</span> | |
| 130 | + d: Sys.Dir; name, copy: []<span class="ty">U8</span>; more, ok: <span class="ty">BOOL</span>; i, n: <span class="ty">INT</span>; | |
| 131 | + info: Sys.Info; err: <span class="ty">INT</span>; names: [<span class="number">16</span>][]<span class="ty">U8</span>; path: Buf.Buf; | |
| 132 | +<span class="kw">begin</span> | |
| 133 | + _ := Sys.makeDir(<span class="string">"proj"</span>); | |
| 134 | + _ := Sys.makeDir(<span class="string">"proj/src"</span>); | |
| 135 | + put(<span class="string">"proj/b.txt"</span>, <span class="string">"bb"</span>); | |
| 136 | + put(<span class="string">"proj/a.txt"</span>, <span class="string">"a"</span>); | |
| 137 | + <span class="kw">if</span> Sys.openDir(<span class="ty">ADR</span>(d), <span class="string">"proj"</span>) < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 138 | + n := <span class="number">0</span>; | |
| 139 | + name, more := Sys.nextEntry(<span class="ty">ADR</span>(d)); | |
| 140 | + <span class="kw">while</span> more <span class="kw">do</span> | |
| 141 | + copy, ok := Str.copy(Heap.heap, name); | |
| 142 | + <span class="kw">if</span> ok <span class="kw">and</span> (n < <span class="number">16</span>) <span class="kw">then</span> names[n] := copy; <span class="ty">INC</span>(n); <span class="kw">end</span>; | |
| 143 | + name, more := Sys.nextEntry(<span class="ty">ADR</span>(d)); | |
| 144 | + <span class="kw">end</span>; | |
| 145 | + Sys.closeDir(<span class="ty">ADR</span>(d)); | |
| 146 | + Order.sort(names[<span class="number">0</span>..n]); | |
| 147 | + Buf.init(<span class="ty">ADR</span>(path), Heap.heap); | |
| 148 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> n - <span class="number">1</span> <span class="kw">do</span> | |
| 149 | + Buf.reset(<span class="ty">ADR</span>(path)); | |
| 150 | + Buf.str(<span class="ty">ADR</span>(path), <span class="string">"proj/"</span>); | |
| 151 | + Buf.str(<span class="ty">ADR</span>(path), names[i]); | |
| 152 | + info, err := Sys.info(Buf.bytes(<span class="ty">ADR</span>(path))); | |
| 153 | + Out.str(names[i]); | |
| 154 | + <span class="kw">if</span> err < <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">" ?"</span>); | |
| 155 | + <span class="kw">elsif</span> info.dir <span class="kw">then</span> Out.str(<span class="string">"/"</span>); | |
| 156 | + <span class="kw">else</span> Out.str(<span class="string">", "</span>); Out.int(info.size); Out.str(<span class="string">" bytes"</span>); | |
| 157 | + <span class="kw">end</span>; | |
| 158 | + Out.ln; | |
| 159 | + Mem.free(Heap.heap, ^<span class="ty">U8</span>(<span class="ty">ADR</span>(names[i][<span class="number">0</span>]))); | |
| 160 | + <span class="kw">end</span>; | |
| 161 | + Buf.done(<span class="ty">ADR</span>(path)); | |
| 162 | +<span class="kw">end</span>; | |
| 163 | + | |
| 164 | +<span class="kw">end</span> Tree.</code></pre> | |
| 165 | +<pre class="output"><code>a.txt, 1 bytes | |
| 166 | +b.txt, 2 bytes | |
| 167 | +src/ | |
| 168 | +</code></pre> | |
| 169 | +<h2>A command line, from a table</h2> | |
| 170 | +<p>A program describes its options once, in a table of <code>Opt.Row</code>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 <code>getopt</code> with GNU's long options, so <code>-vn3</code>, <code>-n 3</code>, <code>--count=3</code> and <code>--count 3</code> all work, and <code>--</code> ends the options.</p> | |
| 171 | +<div class="file"><span>Tool.raz</span></div><pre class="code"><code><span class="kw">module</span> Tool; | |
| 172 | +<span class="kw">import</span> Out, Fmt, Opt; | |
| 173 | + | |
| 174 | +<span class="kw">const</span> count = <span class="number">1</span>; <span class="comment">(* the key of --count, which has no letter *)</span> | |
| 175 | + | |
| 176 | +<span class="kw">proc</span> main*; | |
| 177 | +<span class="kw">var</span> p: Opt.Parser; verbose: <span class="ty">BOOL</span>; n, i: <span class="ty">INT</span>; w: []<span class="ty">U8</span>; ok: <span class="ty">BOOL</span>; | |
| 178 | +<span class="kw">begin</span> | |
| 179 | + n := <span class="number">1</span>; | |
| 180 | + Opt.init(<span class="ty">ADR</span>(p), <span class="string">"tool"</span>, [ | |
| 181 | + Opt.usage(<span class="string">""</span>, <span class="string">"tool [-v] [--count n] word ..."</span>), | |
| 182 | + Opt.option(<span class="string">""</span>, <span class="string">'v'</span>, <span class="string">"verbose"</span>, <span class="string">""</span>, <span class="string">"say more"</span>), | |
| 183 | + Opt.option(<span class="string">""</span>, count, <span class="string">"count"</span>, <span class="string">"n"</span>, <span class="string">"repeat each word n times"</span>)]); | |
| 184 | + <span class="kw">while</span> Opt.next(<span class="ty">ADR</span>(p)) <span class="kw">do</span> | |
| 185 | + <span class="kw">if</span> p.letter = <span class="string">'v'</span> <span class="kw">then</span> verbose := <span class="ty">true</span>; | |
| 186 | + <span class="kw">elsif</span> p.letter = count <span class="kw">then</span> n := <span class="ty">INT</span>(Opt.number(<span class="ty">ADR</span>(p), <span class="number">1</span>, <span class="number">5</span>)); | |
| 187 | + <span class="kw">end</span>; | |
| 188 | + <span class="kw">end</span>; | |
| 189 | + w, ok := Opt.operand(<span class="ty">ADR</span>(p)); | |
| 190 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Opt.fail(<span class="ty">ADR</span>(p), <span class="string">"no words; see tool -h"</span>); <span class="kw">end</span>; | |
| 191 | + <span class="kw">while</span> ok <span class="kw">do</span> | |
| 192 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> n <span class="kw">do</span> | |
| 193 | + <span class="kw">if</span> verbose <span class="kw">then</span> Out.str(<span class="string">"word: "</span>); <span class="kw">end</span>; | |
| 194 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.str(w)]); | |
| 195 | + <span class="kw">end</span>; | |
| 196 | + w, ok := Opt.operand(<span class="ty">ADR</span>(p)); | |
| 197 | + <span class="kw">end</span>; | |
| 198 | +<span class="kw">end</span>; | |
| 199 | + | |
| 200 | +<span class="kw">end</span> Tool.</code></pre> | |
| 201 | +<pre class="output term"><code><span class="cmd">$ raz Tool.raz</span> | |
| 202 | +<span class="cmd">$ ./Tool -h</span> | |
| 203 | +usage: tool [-v] [--count n] word ... | |
| 204 | + | |
| 205 | + -v, --verbose say more | |
| 206 | + --count n repeat each word n times | |
| 207 | + -h, --help print this and exit | |
| 208 | +<span class="cmd">$ ./Tool -v hello world</span> | |
| 209 | +word: hello | |
| 210 | +word: world | |
| 211 | +<span class="cmd">$ ./Tool --count 9 hello; echo "status $?"</span> | |
| 212 | +tool: --count wants a number from 1 to 5, not '9' | |
| 213 | +usage: tool [-v] [--count n] word ... | |
| 214 | +status 2 | |
| 215 | +<span class="cmd">$ ./Tool -x; echo "status $?"</span> | |
| 216 | +tool: unknown option -x | |
| 217 | +usage: tool [-v] [--count n] word ... | |
| 218 | +status 2 | |
| 219 | +<span class="cmd">$ ./Tool; echo "status $?"</span> | |
| 220 | +tool: no words; see tool -h | |
| 221 | +status 2</code></pre> | |
| 222 | +<p><code>-h</code> and <code>--help</code> are <code>Opt</code>'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 <code>Tool</code> wrote any of that.</p> | |
| 223 | +<p>A mistake in the table itself, such as an option given twice, is the program's, and <code>init</code> says so and ends with status 1 before it reads a word.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="collections.html">← Lists, maps and sorting</a><a href="index.html">Contents</a><a class="next" href="processes.html">Time, randomness and other programs →</a></div></article></div> | |
| 224 | +</main> | |
| 225 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 226 | +</body> | |
| 227 | +</html> |
| @@ -0,0 +1,189 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Output and formatting - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html" aria-current="page">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">The library · lesson 1 of 18</p><h1>Output and formatting</h1> | |
| 38 | +<p>The first tour used <code>Out</code> for everything it printed. Two modules do the work: <code>Out</code>, which owns standard output and its buffer, and <code>Fmt</code>, which turns values into text.</p> | |
| 39 | +<h2>What <code>Out</code> does with its buffer</h2> | |
| 40 | +<p><code>Out</code> 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 <code>Out.flush</code>, and when the program ends by <code>Rt.exit</code> (which a normal end and a failed check both are). A lock keeps what each call writes together when threads write at once.</p> | |
| 41 | +<p>You can see the effect with <code>strace</code>, which lists the system calls a program makes. A program that prints three lines to a file makes one <code>write</code>:</p> | |
| 42 | +<div class="file"><span>Three.raz</span></div><pre class="code"><code><span class="kw">module</span> Three; | |
| 43 | +<span class="kw">import</span> Out; | |
| 44 | + | |
| 45 | +<span class="kw">proc</span> main*; | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + Out.str(<span class="string">"one\n"</span>); | |
| 48 | + Out.str(<span class="string">"two\n"</span>); | |
| 49 | + Out.str(<span class="string">"three\n"</span>); | |
| 50 | +<span class="kw">end</span>; | |
| 51 | + | |
| 52 | +<span class="kw">end</span> Three.</code></pre> | |
| 53 | +<pre class="output term"><code><span class="cmd">$ raz Three.raz</span> | |
| 54 | +<span class="cmd">$ strace -e trace=write ./Three > /dev/null</span> | |
| 55 | +write(1, "one\ntwo\nthree\n", 14) = 14 | |
| 56 | ++++ exited with 0 +++</code></pre> | |
| 57 | +<p>Three lines, one system call. That is why <code>Out</code> is cheap, and why a program that mixes it with C's <code>printf</code>, which keeps a buffer of its own, must flush one before the other.</p> | |
| 58 | +<h2><code>Fmt.print</code></h2> | |
| 59 | +<p><code>Fmt.print(format, args)</code> writes to standard output. Each <code>{}</code> in the format takes the next argument, and <code>{{</code> and <code>}}</code> stand for the braces. The arguments are a slice of <code>Fmt.Arg</code>, a variant, so each is built with the constructor for its kind: <code>int</code>, <code>uint</code>, <code>hex</code>, <code>str</code>, <code>char</code>, <code>bool</code> and <code>real</code>, which takes the number of digits after the point.</p> | |
| 60 | +<div class="file"><span>Kinds.raz</span></div><pre class="code"><code><span class="kw">module</span> Kinds; | |
| 61 | +<span class="kw">import</span> Fmt; | |
| 62 | + | |
| 63 | +<span class="kw">proc</span> main*; | |
| 64 | +<span class="kw">var</span> big: <span class="ty">U64</span>; small: <span class="ty">I8</span>; | |
| 65 | +<span class="kw">begin</span> | |
| 66 | + big := <span class="number">0FFFFFFFFFFFFFFFFH</span>; | |
| 67 | + small := -<span class="number">5</span>; | |
| 68 | + Fmt.print(<span class="string">"int {}, uint {}, hex {}\n"</span>, | |
| 69 | + [Fmt.int(-<span class="number">42</span>), Fmt.uint(big), Fmt.hex(<span class="number">255</span>)]); | |
| 70 | + Fmt.print(<span class="string">"str {}, char {}, bool {}\n"</span>, | |
| 71 | + [Fmt.str(<span class="string">"hi"</span>), Fmt.char(<span class="string">'x'</span>), Fmt.bool(<span class="number">1</span> < <span class="number">2</span>)]); | |
| 72 | + Fmt.print(<span class="string">"real {} and {} and {}\n"</span>, | |
| 73 | + [Fmt.real(<span class="number">3.14159</span>, <span class="number">2</span>), Fmt.real(<span class="number">2.5</span>, <span class="number">0</span>), Fmt.real(<span class="number">1.0</span> / <span class="number">3.0</span>, <span class="number">9</span>)]); | |
| 74 | + Fmt.print(<span class="string">"an I8: {}; braces: {{ and }}\n"</span>, [Fmt.int(<span class="ty">I64</span>(small))]); | |
| 75 | +<span class="kw">end</span>; | |
| 76 | + | |
| 77 | +<span class="kw">end</span> Kinds.</code></pre> | |
| 78 | +<pre class="output"><code>int -42, uint 18446744073709551615, hex FF | |
| 79 | +str hi, char x, bool true | |
| 80 | +real 3.14 and 3 and 0.333333333 | |
| 81 | +an I8: -5; braces: { and } | |
| 82 | +</code></pre> | |
| 83 | +<p>An argument whose type is wrong doesn't compile: there is no <code>%d</code> that disagrees with its argument. A <code>{}</code> 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.</p> | |
| 84 | +<h2>Into a buffer</h2> | |
| 85 | +<p><code>Fmt.write(b, format, args)</code> does the same into a <code>Buf</code> 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.</p> | |
| 86 | +<div class="file"><span>Message.raz</span></div><pre class="code"><code><span class="kw">module</span> Message; | |
| 87 | +<span class="kw">import</span> Out, Buf, Fmt, Heap; | |
| 88 | + | |
| 89 | +<span class="comment">(* "name (age n)", built in a Buf the caller owns *)</span> | |
| 90 | +<span class="kw">proc</span> describe(b: ^Buf.Buf; name: []<span class="ty">U8</span>; age: <span class="ty">INT</span>); | |
| 91 | +<span class="kw">begin</span> | |
| 92 | + Fmt.write(b, <span class="string">"{} (age {})"</span>, [Fmt.str(name), Fmt.int(age)]); | |
| 93 | +<span class="kw">end</span>; | |
| 94 | + | |
| 95 | +<span class="kw">proc</span> main*; | |
| 96 | +<span class="kw">var</span> b: Buf.Buf; | |
| 97 | +<span class="kw">begin</span> | |
| 98 | + Buf.init(<span class="ty">ADR</span>(b), Heap.heap); | |
| 99 | + <span class="kw">defer</span> Buf.done(<span class="ty">ADR</span>(b)); | |
| 100 | + describe(<span class="ty">ADR</span>(b), <span class="string">"Ada"</span>, <span class="number">36</span>); | |
| 101 | + Buf.str(<span class="ty">ADR</span>(b), <span class="string">"; "</span>); | |
| 102 | + describe(<span class="ty">ADR</span>(b), <span class="string">"Grace"</span>, <span class="number">45</span>); | |
| 103 | + Out.str(Buf.bytes(<span class="ty">ADR</span>(b))); Out.ln; | |
| 104 | + Out.int(b.len); Out.str(<span class="string">" bytes\n"</span>); | |
| 105 | +<span class="kw">end</span>; | |
| 106 | + | |
| 107 | +<span class="kw">end</span> Message.</code></pre> | |
| 108 | +<pre class="output"><code>Ada (age 36); Grace (age 45) | |
| 109 | +28 bytes | |
| 110 | +</code></pre> | |
| 111 | +<h2>Columns</h2> | |
| 112 | +<p><code>Fmt</code> 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.</p> | |
| 113 | +<div class="file"><span>Table.raz</span></div><pre class="code"><code><span class="kw">module</span> Table; | |
| 114 | +<span class="kw">import</span> Out; | |
| 115 | + | |
| 116 | +<span class="comment">(* s, then spaces up to width *)</span> | |
| 117 | +<span class="kw">proc</span> left(s: []<span class="ty">U8</span>; width: <span class="ty">INT</span>); | |
| 118 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 119 | +<span class="kw">begin</span> | |
| 120 | + Out.str(s); | |
| 121 | + <span class="kw">for</span> i := <span class="ty">LEN</span>(s) <span class="kw">to</span> width - <span class="number">1</span> <span class="kw">do</span> Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 122 | +<span class="kw">end</span>; | |
| 123 | + | |
| 124 | +<span class="comment">(* n, right aligned in width *)</span> | |
| 125 | +<span class="kw">proc</span> right(n: <span class="ty">INT</span>; width: <span class="ty">INT</span>); | |
| 126 | +<span class="kw">var</span> digits: <span class="ty">INT</span>; v: <span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 127 | +<span class="kw">begin</span> | |
| 128 | + digits := <span class="number">1</span>; | |
| 129 | + v := n; | |
| 130 | + <span class="kw">if</span> v < <span class="number">0</span> <span class="kw">then</span> <span class="ty">INC</span>(digits); v := -v; <span class="kw">end</span>; | |
| 131 | + <span class="kw">while</span> v >= <span class="number">10</span> <span class="kw">do</span> <span class="ty">INC</span>(digits); v := v <span class="kw">div</span> <span class="number">10</span>; <span class="kw">end</span>; | |
| 132 | + <span class="kw">for</span> i := digits <span class="kw">to</span> width - <span class="number">1</span> <span class="kw">do</span> Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 133 | + Out.int(n); | |
| 134 | +<span class="kw">end</span>; | |
| 135 | + | |
| 136 | +<span class="kw">proc</span> row(name: []<span class="ty">U8</span>; qty, price: <span class="ty">INT</span>); | |
| 137 | +<span class="kw">begin</span> | |
| 138 | + left(name, <span class="number">10</span>); | |
| 139 | + right(qty, <span class="number">5</span>); | |
| 140 | + right(price, <span class="number">8</span>); | |
| 141 | + right(qty * price, <span class="number">9</span>); | |
| 142 | + Out.ln; | |
| 143 | +<span class="kw">end</span>; | |
| 144 | + | |
| 145 | +<span class="kw">proc</span> main*; | |
| 146 | +<span class="kw">begin</span> | |
| 147 | + Out.str(<span class="string">"item qty price total\n"</span>); | |
| 148 | + row(<span class="string">"bolts"</span>, <span class="number">120</span>, <span class="number">3</span>); | |
| 149 | + row(<span class="string">"washers"</span>, <span class="number">1000</span>, <span class="number">1</span>); | |
| 150 | + row(<span class="string">"gears"</span>, <span class="number">8</span>, <span class="number">250</span>); | |
| 151 | + row(<span class="string">"shims"</span>, <span class="number">12</span>, -<span class="number">4</span>); | |
| 152 | +<span class="kw">end</span>; | |
| 153 | + | |
| 154 | +<span class="kw">end</span> Table.</code></pre> | |
| 155 | +<pre class="output"><code>item qty price total | |
| 156 | +bolts 120 3 360 | |
| 157 | +washers 1000 1 1000 | |
| 158 | +gears 8 250 2000 | |
| 159 | +shims 12 -4 -48 | |
| 160 | +</code></pre> | |
| 161 | +<h2>Writing numbers in other bases</h2> | |
| 162 | +<p><code>Out.hex(n, digits)</code> writes <code>n</code> in hexadecimal, padded with zeros to <code>digits</code>. A binary dump is a <code>for</code> loop over a slice, one <code>Out.hex(U64(b), 2)</code> to a byte.</p> | |
| 163 | +<div class="file"><span>Dump.raz</span></div><pre class="code"><code><span class="kw">module</span> Dump; | |
| 164 | +<span class="kw">import</span> Out; | |
| 165 | + | |
| 166 | +<span class="kw">proc</span> dump(data: []<span class="ty">U8</span>); | |
| 167 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 168 | +<span class="kw">begin</span> | |
| 169 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(data) - <span class="number">1</span> <span class="kw">do</span> | |
| 170 | + <span class="kw">if</span> i > <span class="number">0</span> <span class="kw">then</span> Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 171 | + Out.hex(<span class="ty">U64</span>(data[i]), <span class="number">2</span>); | |
| 172 | + <span class="kw">end</span>; | |
| 173 | + Out.ln; | |
| 174 | +<span class="kw">end</span>; | |
| 175 | + | |
| 176 | +<span class="kw">proc</span> main*; | |
| 177 | +<span class="kw">begin</span> | |
| 178 | + dump(<span class="string">"raz\n"</span>); | |
| 179 | + dump(<span class="string">"\u{3BB}"</span>); | |
| 180 | +<span class="kw">end</span>; | |
| 181 | + | |
| 182 | +<span class="kw">end</span> Dump.</code></pre> | |
| 183 | +<pre class="output"><code>72 61 7A 0A | |
| 184 | +CE BB | |
| 185 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="index.html">Contents</a><a class="next" href="bytes.html">Strings and bytes →</a></div></article></div> | |
| 186 | +</main> | |
| 187 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 188 | +</body> | |
| 189 | +</html> |
| @@ -0,0 +1,51 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="contents"><h1>Beyond Go</h1> | |
| 13 | +<p>The second tour, for the part of raz that sits close to the machine. It | |
| 14 | +assumes you have taken <a href="../tour/index.html">Raz, Set, Go</a> or know | |
| 15 | +Pascal or C well enough not to need it.</p> | |
| 16 | +<p>It has four parts: <strong>The library</strong>, the modules every program | |
| 17 | +reaches for; <strong>Standing alone</strong>, programs that need no C and no | |
| 18 | +run time; <strong>The machine</strong>, procedures written in assembly and | |
| 19 | +direct system calls; and <strong>Shared memory</strong>, volatile accesses, | |
| 20 | +atomics and threads. Every program is compiled and run when this page is | |
| 21 | +made, as before.</p> | |
| 22 | +<h2>The library</h2><ol start='1'> | |
| 23 | +<li><a href="fmt.html">Output and formatting</a> <span>Out's buffer, Fmt's arguments, formatting into a Buf, and laying out columns.</span></li> | |
| 24 | +<li><a href="bytes.html">Strings and bytes</a> <span>Copying, hashing and ordering strings, and reading and writing binary formats.</span></li> | |
| 25 | +<li><a href="collections.html">Lists, maps and sorting</a> <span>List(T), Map(K, V) and Sort(T), put together in a word-frequency program.</span></li> | |
| 26 | +<li><a href="files.html">Files and the command line</a> <span>Whole files with Files, descriptors and directories with Sys, and options with Opt.</span></li> | |
| 27 | +<li><a href="processes.html">Time, randomness and other programs</a> <span>Clocks, sleeping, random bytes, and running a program with its output piped back.</span></li> | |
| 28 | +<li><a href="allocators.html">Writing an allocator</a> <span>Mem.Allocator is two procedures; make one over a fixed array, and one that counts.</span></li> | |
| 29 | +</ol> | |
| 30 | +<h2>Standing alone</h2><ol start='7'> | |
| 31 | +<li><a href="static.html">A program with no run time</a> <span>What is in an executable, what isn't, and how to see it.</span></li> | |
| 32 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a> <span>link static, what a module that makes its own system calls promises, and the error when it breaks.</span></li> | |
| 33 | +<li><a href="lifecycle.html">Starting, ending, and signals</a> <span>What runs before main, what runs after, and how to wait for a signal.</span></li> | |
| 34 | +<li><a href="targets.html">One module, one file per target</a> <span>Portable programs, the code that isn't, and how the compiler keeps them in step.</span></li> | |
| 35 | +</ol> | |
| 36 | +<h2>The machine</h2><ol start='11'> | |
| 37 | +<li><a href="asm.html">Procedures in assembly</a> <span>code procedures: the convention, registers, labels, db for what the assembler doesn't know.</span></li> | |
| 38 | +<li><a href="syscalls.html">System calls</a> <span>SYSCALL directly: the numbers, the arguments, negative errno, and a cat without a library.</span></li> | |
| 39 | +<li><a href="listing.html">What the compiler makes</a> <span>raz -S, reading a listing, what a check costs and what check off removes.</span></li> | |
| 40 | +</ol> | |
| 41 | +<h2>Shared memory</h2><ol start='14'> | |
| 42 | +<li><a href="volatile.html">Volatile</a> <span>^VOLATILE T: memory that something else may change, laid over with a record.</span></li> | |
| 43 | +<li><a href="atomics.html">Atomics</a> <span>XADD, XCHG and CAS; a compare-and-swap loop; a lock built from them.</span></li> | |
| 44 | +<li><a href="ordering.html">Ordering and publication</a> <span>Why a flag isn't enough, what FENCE and the atomics order, and the pattern that works.</span></li> | |
| 45 | +<li><a href="lockfree.html">A lock-free stack</a> <span>CAS on pointers, a push loop that never blocks, and the ABA problem that makes pop harder.</span></li> | |
| 46 | +<li><a href="ring.html">A ring buffer between threads</a> <span>A single-producer, single-consumer queue, put together from what the tour has covered.</span></li> | |
| 47 | +</ol></div> | |
| 48 | +</main> | |
| 49 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 50 | +</body> | |
| 51 | +</html> |
| @@ -0,0 +1,155 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Starting, ending, and signals - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html" aria-current="page">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">Standing alone · lesson 9 of 18</p><h1>Starting, ending, and signals</h1> | |
| 38 | +<p>With no run time, the life of a program is short enough to say in a few lines. What happens, in order:</p> | |
| 39 | +<p>1. The entry code sets up a stack for signal handlers and installs the handlers for <code>SIGSEGV</code> and <code>SIGFPE</code>. 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 <code>main</code> runs. 4. <code>Rt.exit</code> runs the procedures registered with <code>Rt.atExit</code>, the last registered first, and ends the program with <code>main</code>'s status.</p> | |
| 40 | +<h2>Bodies, then main</h2> | |
| 41 | +<p>The first tour showed bodies running before <code>main</code>. They are the place to set a module up, and they can end early with <code>return;</code>.</p> | |
| 42 | +<div class="file"><span>Order.raz</span></div><pre class="code"><code><span class="kw">module</span> Order; | |
| 43 | +<span class="kw">import</span> Out; | |
| 44 | + | |
| 45 | +<span class="kw">var</span> steps*: <span class="ty">INT</span>; | |
| 46 | + | |
| 47 | +<span class="kw">proc</span> note(what: []<span class="ty">U8</span>); | |
| 48 | +<span class="kw">begin</span> | |
| 49 | + <span class="ty">INC</span>(steps); | |
| 50 | + Out.int(steps); Out.str(<span class="string">". "</span>); Out.str(what); Out.ln; | |
| 51 | +<span class="kw">end</span>; | |
| 52 | + | |
| 53 | +<span class="kw">begin</span> | |
| 54 | + note(<span class="string">"the body runs before main"</span>); | |
| 55 | + <span class="kw">if</span> steps > <span class="number">5</span> <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 56 | + note(<span class="string">"and carries on if it isn't ended early"</span>); | |
| 57 | +<span class="kw">end</span> Order.</code></pre> | |
| 58 | +<pre class="output"><code>1. the body runs before main | |
| 59 | +2. and carries on if it isn't ended early | |
| 60 | +</code></pre> | |
| 61 | +<p>That file is a module with a body and no <code>main</code>: it can be imported, or its body run as a program. Add the <code>main</code> and see both:</p> | |
| 62 | +<div class="file"><span>Both.raz</span></div><pre class="code"><code><span class="kw">module</span> Both; | |
| 63 | +<span class="kw">import</span> Out, Order; | |
| 64 | + | |
| 65 | +<span class="kw">proc</span> main*; | |
| 66 | +<span class="kw">begin</span> | |
| 67 | + Out.str(<span class="string">"main: "</span>); Out.int(Order.steps); Out.str(<span class="string">" steps happened first\n"</span>); | |
| 68 | +<span class="kw">end</span>; | |
| 69 | + | |
| 70 | +<span class="kw">end</span> Both.</code></pre> | |
| 71 | +<pre class="output"><code>1. the body runs before main | |
| 72 | +2. and carries on if it isn't ended early | |
| 73 | +main: 2 steps happened first | |
| 74 | +</code></pre> | |
| 75 | +<h2>Things to do at the end</h2> | |
| 76 | +<p><code>Rt.atExit(p)</code> registers a procedure with no parameters to run when the program ends by <code>Rt.exit</code>: at the end of <code>main</code>, by a call to <code>Rt.exit</code>, 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.</p> | |
| 77 | +<div class="file"><span>Cleanup.raz</span></div><pre class="code"><code><span class="kw">module</span> Cleanup; | |
| 78 | +<span class="kw">import</span> Out, Rt; | |
| 79 | + | |
| 80 | +<span class="kw">proc</span> first; | |
| 81 | +<span class="kw">begin</span> | |
| 82 | + Out.str(<span class="string">"registered first, runs last\n"</span>); | |
| 83 | +<span class="kw">end</span>; | |
| 84 | + | |
| 85 | +<span class="kw">proc</span> second; | |
| 86 | +<span class="kw">begin</span> | |
| 87 | + Out.str(<span class="string">"registered second, runs first\n"</span>); | |
| 88 | +<span class="kw">end</span>; | |
| 89 | + | |
| 90 | +<span class="kw">proc</span> main*; | |
| 91 | +<span class="kw">begin</span> | |
| 92 | + _ := Rt.atExit(first); | |
| 93 | + _ := Rt.atExit(second); | |
| 94 | + Out.str(<span class="string">"main is done\n"</span>); | |
| 95 | +<span class="kw">end</span>; | |
| 96 | + | |
| 97 | +<span class="kw">end</span> Cleanup.</code></pre> | |
| 98 | +<pre class="output"><code>main is done | |
| 99 | +registered second, runs first | |
| 100 | +registered first, runs last | |
| 101 | +</code></pre> | |
| 102 | +<h2>Two ways to leave in a hurry</h2> | |
| 103 | +<p><code>Rt.exit(status)</code> ends the program after the <code>atExit</code> procedures. <code>Sys.exit(status)</code> ends it at once, without them. A failed check and <code>Rt.exit</code> also skip the <code>defer</code> statements still pending in the calls under way. <code>Sys.exit</code> is for a child process that must not run what it inherited, and for nothing else.</p> | |
| 104 | +<div class="file"><span>Hurry.raz</span></div><pre class="code"><code><span class="kw">module</span> Hurry; | |
| 105 | +<span class="kw">import</span> Out, Rt, Sys; | |
| 106 | + | |
| 107 | +<span class="kw">proc</span> bye; | |
| 108 | +<span class="kw">begin</span> | |
| 109 | + Out.str(<span class="string">"atExit ran\n"</span>); | |
| 110 | +<span class="kw">end</span>; | |
| 111 | + | |
| 112 | +<span class="kw">proc</span> main*; | |
| 113 | +<span class="kw">begin</span> | |
| 114 | + _ := Rt.atExit(bye); | |
| 115 | + <span class="kw">defer</span> Out.str(<span class="string">"a deferred statement ran\n"</span>); | |
| 116 | + Out.str(<span class="string">"leaving\n"</span>); | |
| 117 | + Out.flush; | |
| 118 | + Sys.exit(<span class="number">3</span>); | |
| 119 | +<span class="kw">end</span>; | |
| 120 | + | |
| 121 | +<span class="kw">end</span> Hurry.</code></pre> | |
| 122 | +<pre class="output term"><code><span class="cmd">$ raz Hurry.raz</span> | |
| 123 | +<span class="cmd">$ ./Hurry; echo "status $?"</span> | |
| 124 | +leaving | |
| 125 | +status 3</code></pre> | |
| 126 | +<p>Neither the deferred statement nor <code>bye</code> ran. That's the rule, and the reason to keep cleanup that matters (a terminal, a lock file) in <code>atExit</code> and use <code>Rt.exit</code> for ending.</p> | |
| 127 | +<h2>Signals</h2> | |
| 128 | +<p>A program is stopped by a signal it doesn't catch, with a message that names the place for <code>SIGSEGV</code> and <code>SIGFPE</code>, and without one for the others. A program that wants to handle one, say <code>SIGTERM</code> for a clean shutdown, doesn't write a handler that runs at an arbitrary moment. It asks for the signals to arrive as data: <code>Sys.catch</code> takes a list of signals and gives a descriptor that is ready to read when one comes, and <code>Sys.caught</code> says which. So the program waits for signals the way it waits for input.</p> | |
| 129 | +<div class="file"><span>Terms.raz</span></div><pre class="code"><code><span class="kw">module</span> Terms; | |
| 130 | +<span class="kw">import</span> Out, Sys; | |
| 131 | + | |
| 132 | +<span class="kw">proc</span> main*; | |
| 133 | +<span class="kw">var</span> fd, sig: <span class="ty">INT</span>; | |
| 134 | +<span class="kw">begin</span> | |
| 135 | + fd := Sys.catch([Sys.sigTerm, Sys.sigWinch]); | |
| 136 | + Out.str(<span class="string">"asking myself to stop\n"</span>); | |
| 137 | + _ := Sys.kill(Sys.pid(), Sys.sigTerm); | |
| 138 | + <span class="kw">if</span> Sys.ready(fd, <span class="number">1000</span>) <span class="kw">then</span> | |
| 139 | + sig := Sys.caught(fd); | |
| 140 | + <span class="kw">if</span> sig = Sys.sigTerm <span class="kw">then</span> Out.str(<span class="string">"caught SIGTERM, stopping cleanly\n"</span>); <span class="kw">end</span>; | |
| 141 | + <span class="kw">end</span>; | |
| 142 | + sig := Sys.caught(fd); | |
| 143 | + Out.int(sig); Out.str(<span class="string">" waiting after that\n"</span>); <span class="comment">(* 0: none *)</span> | |
| 144 | +<span class="kw">end</span>; | |
| 145 | + | |
| 146 | +<span class="kw">end</span> Terms.</code></pre> | |
| 147 | +<pre class="output"><code>asking myself to stop | |
| 148 | +caught SIGTERM, stopping cleanly | |
| 149 | +0 waiting after that | |
| 150 | +</code></pre> | |
| 151 | +<p><code>Sys.ready(fd, ms)</code> waits up to <code>ms</code> milliseconds for something to read; with <code>Sys.readyOf</code> it waits on several descriptors, so one loop serves a socket, a terminal and a stop signal together. <code>Sys.ignore(sig, true)</code> makes a signal do nothing, as a shell ignores <code>SIGTTOU</code>.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="linkstatic.html">← Threads without C, and keeping the two apart</a><a href="index.html">Contents</a><a class="next" href="targets.html">One module, one file per target →</a></div></article></div> | |
| 152 | +</main> | |
| 153 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 154 | +</body> | |
| 155 | +</html> |
| @@ -0,0 +1,114 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Threads without C, and keeping the two apart - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html" aria-current="page">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">Standing alone · lesson 8 of 18</p><h1>Threads without C, and keeping the two apart</h1> | |
| 38 | +<p>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. <code>Thread</code> creates threads directly with the <code>clone</code> system call and gives each a stack of its own.</p> | |
| 39 | +<p>A module like that says so, with <code>link static;</code> 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." <code>static</code> isn't a reserved word; it is only meaningful after <code>link</code>.</p> | |
| 40 | +<h2>What <code>Thread</code> does</h2> | |
| 41 | +<p><code>Thread</code> is a module of raz, in the library, that says <code>link static;</code> and makes the <code>clone</code>, <code>mmap</code> and <code>futex</code> system calls itself. Here is its beginning, printed from the library:</p> | |
| 42 | +<pre class="output term"><code><span class="cmd">$ sed -n '1,22p' $RAZLIB/Thread.linux-x86_64.raz</span> | |
| 43 | +(* Threads for programs without C, made with the clone system call. | |
| 44 | + Each runs on a stack of its own, mmaped, with a page below it that | |
| 45 | + can't be touched, so that running off the stack stops the program | |
| 46 | + rather than spoiling what lies below; above it, a little stack for | |
| 47 | + Rt's signal handlers, so that they can say so. join waits on the | |
| 48 | + thread's id, which the kernel clears, and wakes it for, when the | |
| 49 | + thread ends; a Mutex sleeps on a futex. A program with C threads | |
| 50 | + uses C's, through pthread_create, and so can't use these. *) | |
| 51 | +module Thread; | |
| 52 | +import Sys, Rt; | |
| 53 | +link static; | |
| 54 | + | |
| 55 | +const | |
| 56 | + Failed*: ERROR = "can't start a thread"; | |
| 57 | + Stack = 1 shl 20; | |
| 58 | + Alt = 16384; (* the signal handlers' stack *) | |
| 59 | + Page = 4096; | |
| 60 | + (* clone: share memory, files, signal handlers, the thread group; | |
| 61 | + write the id to tid, and clear it at the end *) | |
| 62 | + Flags = 350F00H; | |
| 63 | + FutexWait = 0; | |
| 64 | + FutexWake = 1;</code></pre> | |
| 65 | +<p>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.</p> | |
| 66 | +<div class="file"><span>Hello.raz</span></div><pre class="code"><code><span class="kw">module</span> Hello; | |
| 67 | +<span class="kw">import</span> Out, Thread; | |
| 68 | + | |
| 69 | +<span class="kw">var</span> done: <span class="ty">INT</span>; | |
| 70 | + | |
| 71 | +<span class="kw">proc</span> greet(arg: ^<span class="ty">U8</span>); | |
| 72 | +<span class="kw">begin</span> | |
| 73 | + Out.str(<span class="string">"hello from thread "</span>); Out.int(<span class="ty">INT</span>(arg)); Out.ln; | |
| 74 | + _ := <span class="ty">XADD</span>(<span class="ty">ADR</span>(done), <span class="number">1</span>); | |
| 75 | +<span class="kw">end</span>; | |
| 76 | + | |
| 77 | +<span class="kw">proc</span> main*; | |
| 78 | +<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>; | |
| 79 | +<span class="kw">begin</span> | |
| 80 | + t, err := Thread.spawn(greet, ^<span class="ty">U8</span>(<span class="number">7</span>)); | |
| 81 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 82 | + Thread.join(t); | |
| 83 | + Out.str(<span class="string">"joined; done = "</span>); Out.int(done); Out.ln; | |
| 84 | +<span class="kw">end</span>; | |
| 85 | + | |
| 86 | +<span class="kw">end</span> Hello.</code></pre> | |
| 87 | +<pre class="output term"><code><span class="cmd">$ raz Hello.raz</span> | |
| 88 | +<span class="cmd">$ ./Hello</span> | |
| 89 | +hello from thread 7 | |
| 90 | +joined; done = 1 | |
| 91 | +<span class="cmd">$ file Hello | sed 's/,.*statically/, statically/'</span> | |
| 92 | +Hello: ELF 64-bit LSB executable, statically linked, with debug_info, not stripped</code></pre> | |
| 93 | +<h2>When you mix them</h2> | |
| 94 | +<p>C's <code>pthread_create</code> and <code>Thread</code> can't share a process, and the compiler won't let you try. A program that imports a module that says <code>link static;</code> and another that uses C is an error, and the error names both:</p> | |
| 95 | +<div class="file"><span>Mixed.raz</span></div><pre class="code"><code><span class="kw">module</span> Mixed; | |
| 96 | +<span class="kw">import</span> Out, Thread, C; | |
| 97 | + | |
| 98 | +<span class="kw">proc</span> main*; | |
| 99 | +<span class="kw">begin</span> | |
| 100 | + Out.str(<span class="ty">MSG</span>(Thread.Failed)); Out.ln; | |
| 101 | + _ := C.printf(<span class="string">"%d\n"</span>, <span class="ty">I32</span>(<span class="number">1</span>)); | |
| 102 | + Out.str(<span class="string">"and Out\n"</span>); | |
| 103 | +<span class="kw">end</span>; | |
| 104 | + | |
| 105 | +<span class="kw">end</span> Mixed.</code></pre> | |
| 106 | +<pre class="output term"><code><span class="cmd">$ raz Mixed.raz</span> | |
| 107 | +raz: Thread says link static, but C uses C</code></pre> | |
| 108 | +<p>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, <code>C.pthread_create</code>, because the library may assume them. A program that talks only to the kernel uses <code>Thread</code>, and is a static executable.</p> | |
| 109 | +<h2>The same promise for your own modules</h2> | |
| 110 | +<p>The rule isn't special to <code>Thread</code>. A module of yours that makes <code>SYSCALL</code>s directly, or relies on being the only owner of signal handlers, or sets up its own stacks, says <code>link static;</code> 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.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="static.html">← A program with no run time</a><a href="index.html">Contents</a><a class="next" href="lifecycle.html">Starting, ending, and signals →</a></div></article></div> | |
| 111 | +</main> | |
| 112 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 113 | +</body> | |
| 114 | +</html> |
| @@ -0,0 +1,256 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>What the compiler makes - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html" aria-current="page">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">The machine · lesson 13 of 18</p><h1>What the compiler makes</h1> | |
| 38 | +<p>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: <code>raz -S Main.raz</code> 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.</p> | |
| 39 | +<h2>A small procedure</h2> | |
| 40 | +<div class="file"><span>Add.raz</span></div><pre class="code"><code><span class="kw">module</span> Add; | |
| 41 | + | |
| 42 | +<span class="kw">proc</span> add*(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 43 | +<span class="kw">begin</span> | |
| 44 | + <span class="kw">return</span> a + b; | |
| 45 | +<span class="kw">end</span>; | |
| 46 | + | |
| 47 | +<span class="kw">proc</span> main*; | |
| 48 | +<span class="kw">begin</span> | |
| 49 | + _ := add(<span class="number">1</span>, <span class="number">2</span>); | |
| 50 | +<span class="kw">end</span>; | |
| 51 | + | |
| 52 | +<span class="kw">end</span> Add.</code></pre> | |
| 53 | +<pre class="output term"><code><span class="cmd">$ raz -S Add.raz</span> | |
| 54 | + | |
| 55 | +Add.add: | |
| 56 | + 3 proc add*(a, b: INT): INT; | |
| 57 | + 0 push rbp | |
| 58 | + 1 mov rbp, rsp | |
| 59 | + 4 sub rsp, 16 | |
| 60 | + 5 return a + b; | |
| 61 | + 11 mov r8, rdi | |
| 62 | + 14 add r8, rsi | |
| 63 | + 17 mov rax, r8 | |
| 64 | + 6 end; | |
| 65 | + 20 leave | |
| 66 | + 21 ret | |
| 67 | + | |
| 68 | +Add.main: | |
| 69 | + 8 proc main*; | |
| 70 | + 0 push rbp | |
| 71 | + 1 mov rbp, rsp | |
| 72 | + 4 sub rsp, 16 | |
| 73 | + 10 _ := add(1, 2); | |
| 74 | + 11 mov rdi, 1 | |
| 75 | + 16 mov rsi, 2 | |
| 76 | + 21 call Add.add | |
| 77 | + 26 mov r8, rax | |
| 78 | + 11 end; | |
| 79 | + 29 leave | |
| 80 | + 30 ret</code></pre> | |
| 81 | +<p>Every procedure starts by saving the caller's frame pointer and making its own (<code>push rbp; mov rbp, rsp</code>) and reserves room for what it needs. The arguments arrive in <code>rdi</code> and <code>rsi</code>, as the convention says, and the result leaves in <code>rax</code>. A call is <code>mov rdi, 1; mov rsi, 2; call Add.add</code>. Nothing is hidden: the frame pointer chain is what lets a failure show the calls under way with their variables.</p> | |
| 82 | +<h2>A loop with its checks</h2> | |
| 83 | +<p>This is the dot product of two slices. A slice is a pointer and a length, and it travels in two registers:</p> | |
| 84 | +<div class="file"><span>Dot.raz</span></div><pre class="code"><code><span class="kw">module</span> Dot; | |
| 85 | + | |
| 86 | +<span class="comment">(* the dot product of two slices of equal length *)</span> | |
| 87 | +<span class="kw">proc</span> dot*(a, b: []<span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 88 | +<span class="kw">var</span> i, sum: <span class="ty">INT</span>; | |
| 89 | +<span class="kw">begin</span> | |
| 90 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(a) - <span class="number">1</span> <span class="kw">do</span> | |
| 91 | + sum := sum + a[i] * b[i]; | |
| 92 | + <span class="kw">end</span>; | |
| 93 | + <span class="kw">return</span> sum; | |
| 94 | +<span class="kw">end</span>; | |
| 95 | + | |
| 96 | +<span class="kw">proc</span> main*; | |
| 97 | +<span class="kw">var</span> x, y: [<span class="number">3</span>]<span class="ty">INT</span>; | |
| 98 | +<span class="kw">begin</span> | |
| 99 | + x := [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]; | |
| 100 | + y := [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]; | |
| 101 | + _ := dot(x, y); | |
| 102 | +<span class="kw">end</span>; | |
| 103 | + | |
| 104 | +<span class="kw">end</span> Dot.</code></pre> | |
| 105 | +<pre class="output term"><code><span class="cmd">$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p'</span> | |
| 106 | +Dot.dot: | |
| 107 | + 4 proc dot*(a, b: []INT): INT; | |
| 108 | + 0 push rbp | |
| 109 | + 1 mov rbp, rsp | |
| 110 | + 4 sub rsp, 64 | |
| 111 | + 11 mov [rbp - 48], rbx | |
| 112 | + 15 xor ebx, ebx | |
| 113 | + 17 mov [rbp - 40], r12 | |
| 114 | + 21 xor r12d, r12d | |
| 115 | + 24 mov [rbp - 32], rdx | |
| 116 | + 28 mov [rbp - 24], rcx | |
| 117 | + 7 for i := 0 to LEN(a) - 1 do | |
| 118 | + 32 xor ebx, ebx | |
| 119 | + 34 mov r8, rsi | |
| 120 | + 37 sub r8, 1 | |
| 121 | + 41 mov [rbp - 56], r8 | |
| 122 | + 45 cmp rbx, [rbp - 56] | |
| 123 | + 49 jg 146 | |
| 124 | + 55 jmp 68 | |
| 125 | + 60 nop | |
| 126 | + 64 add rbx, 1 | |
| 127 | + 8 sum := sum + a[i] * b[i]; | |
| 128 | + 68 cmp rbx, rsi | |
| 129 | + 71 jae 159 | |
| 130 | + 77 mov r10, rbx | |
| 131 | + 80 cmp r10, [rbp - 24] | |
| 132 | + 84 jae 170 | |
| 133 | + 90 shl r10, 3 | |
| 134 | + 94 add r10, [rbp - 32] | |
| 135 | + 98 mov r10, [r10] | |
| 136 | + 101 mov r9, [rdi + rbx * 8] | |
| 137 | + 105 imul r9, r10 | |
| 138 | + 109 add r12, r9 | |
| 139 | + 112 cmp rbx, [rbp - 56] | |
| 140 | + 116 jl 64 | |
| 141 | + 122 cmp rbx, [rbp - 56] | |
| 142 | + 126 je 146 | |
| 143 | + 132 add rbx, 1 | |
| 144 | + 136 cmp rbx, [rbp - 56] | |
| 145 | + 140 jle 68 | |
| 146 | + 10 return sum; | |
| 147 | + 146 mov rax, r12 | |
| 148 | + 11 end; | |
| 149 | + 149 mov rbx, [rbp - 48] | |
| 150 | + 153 mov r12, [rbp - 40] | |
| 151 | + 157 leave | |
| 152 | + 158 ret | |
| 153 | + 8 sum := sum + a[i] * b[i]; | |
| 154 | + 159 mov rax, rbx | |
| 155 | + 162 mov rcx, rsi | |
| 156 | + 165 call Rt.check0 | |
| 157 | + 170 mov rax, r10 | |
| 158 | + 173 mov rcx, [rbp - 24] | |
| 159 | + 177 call Rt.check0</code></pre> | |
| 160 | +<p>Read it from the top. <code>a</code> arrives in <code>rdi</code> and <code>rsi</code>, pointer and length; <code>b</code> in <code>rdx</code> and <code>rcx</code>, which the procedure saves in its frame. <code>i</code> and <code>sum</code> live in <code>rbx</code> and <code>r12</code>, 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, <code>LEN(a) - 1</code>, is taken once.</p> | |
| 161 | +<p>In the body, each index has a check: <code>cmp rbx, rsi; jae</code> compares <code>i</code> with <code>a</code>'s length in a single instruction and jumps to a stub at the end of the procedure, which calls <code>Rt.check0</code> 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.</p> | |
| 162 | +<h2>Taking the checks out</h2> | |
| 163 | +<p><code>check off;</code> after the imports leaves out the module's own checks of indexes and slice bounds. Here is the same procedure with it:</p> | |
| 164 | +<div class="file"><span>Dot2.raz</span></div><pre class="code"><code><span class="kw">module</span> Dot2; | |
| 165 | +check off; | |
| 166 | + | |
| 167 | +<span class="kw">proc</span> dot*(a, b: []<span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 168 | +<span class="kw">var</span> i, sum: <span class="ty">INT</span>; | |
| 169 | +<span class="kw">begin</span> | |
| 170 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(a) - <span class="number">1</span> <span class="kw">do</span> | |
| 171 | + sum := sum + a[i] * b[i]; | |
| 172 | + <span class="kw">end</span>; | |
| 173 | + <span class="kw">return</span> sum; | |
| 174 | +<span class="kw">end</span>; | |
| 175 | + | |
| 176 | +<span class="kw">proc</span> main*; | |
| 177 | +<span class="kw">var</span> x, y: [<span class="number">3</span>]<span class="ty">INT</span>; | |
| 178 | +<span class="kw">begin</span> | |
| 179 | + x := [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]; | |
| 180 | + y := [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]; | |
| 181 | + _ := dot(x, y); | |
| 182 | +<span class="kw">end</span>; | |
| 183 | + | |
| 184 | +<span class="kw">end</span> Dot2.</code></pre> | |
| 185 | +<pre class="output term"><code><span class="cmd">$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p'</span> | |
| 186 | +Dot2.dot: | |
| 187 | + 4 proc dot*(a, b: []INT): INT; | |
| 188 | + 0 push rbp | |
| 189 | + 1 mov rbp, rsp | |
| 190 | + 4 sub rsp, 64 | |
| 191 | + 11 mov [rbp - 48], rbx | |
| 192 | + 15 xor ebx, ebx | |
| 193 | + 17 mov [rbp - 40], r12 | |
| 194 | + 21 xor r12d, r12d | |
| 195 | + 24 mov [rbp - 32], rdx | |
| 196 | + 28 mov [rbp - 24], rcx | |
| 197 | + 7 for i := 0 to LEN(a) - 1 do | |
| 198 | + 32 xor ebx, ebx | |
| 199 | + 34 mov r8, rsi | |
| 200 | + 37 sub r8, 1 | |
| 201 | + 41 mov [rbp - 56], r8 | |
| 202 | + 45 cmp rbx, [rbp - 56] | |
| 203 | + 49 jg 127 | |
| 204 | + 55 jmp 68 | |
| 205 | + 60 nop | |
| 206 | + 64 add rbx, 1 | |
| 207 | + 8 sum := sum + a[i] * b[i]; | |
| 208 | + 68 mov r10, rbx | |
| 209 | + 71 shl r10, 3 | |
| 210 | + 75 add r10, [rbp - 32] | |
| 211 | + 79 mov r10, [r10] | |
| 212 | + 82 mov r9, [rdi + rbx * 8] | |
| 213 | + 86 imul r9, r10 | |
| 214 | + 90 add r12, r9 | |
| 215 | + 93 cmp rbx, [rbp - 56] | |
| 216 | + 97 jl 64 | |
| 217 | + 103 cmp rbx, [rbp - 56] | |
| 218 | + 107 je 127 | |
| 219 | + 113 add rbx, 1 | |
| 220 | + 117 cmp rbx, [rbp - 56] | |
| 221 | + 121 jle 68 | |
| 222 | + 10 return sum; | |
| 223 | + 127 mov rax, r12 | |
| 224 | + 11 end; | |
| 225 | + 130 mov rbx, [rbp - 48] | |
| 226 | + 134 mov r12, [rbp - 40] | |
| 227 | + 138 leave | |
| 228 | + 139 ret | |
| 229 | +<span class="cmd">$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p' | wc -l</span> | |
| 230 | +55 | |
| 231 | +<span class="cmd">$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p' | wc -l</span> | |
| 232 | +44</code></pre> | |
| 233 | +<p>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.</p> | |
| 234 | +<h2>Comparing with C</h2> | |
| 235 | +<p><code>make kernels</code> in the compiler's sources measures <code>test/bench</code>'s kernels against the same kernels written in Pascal and compiled by Free Pascal at <code>-O2</code>. The compiler's own guide, <code>doc/compiler.md</code>, 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.</p> | |
| 236 | +<h2>Tools that read what it made</h2> | |
| 237 | +<ul><li><code>gdb</code> finds procedures by name and lines by number, since the executable carries them: <code>break Dot.dot</code> and <code>list</code> work, and so does stepping a line at a time.</li><li><code>RAZ_PROFILE=1</code> samples the program every millisecond and says which procedures and lines took the time.</li><li><code>objdump -d</code> disassembles what is really in the file, if you want to see the bytes behind a listing.</li></ul> | |
| 238 | +<pre class="output term"><code><span class="cmd">$ raz -o Dot Dot.raz</span> | |
| 239 | +<span class="cmd">$ objdump -d -M intel --no-show-raw-insn Dot | sed -n '/<Dot.dot>:/,/ret/p' | head -12</span> | |
| 240 | +0000000000403b80 <Dot.dot>: | |
| 241 | + 403b80: push rbp | |
| 242 | + 403b81: mov rbp,rsp | |
| 243 | + 403b84: sub rsp,0x40 | |
| 244 | + 403b8b: mov QWORD PTR [rbp-0x30],rbx | |
| 245 | + 403b8f: xor ebx,ebx | |
| 246 | + 403b91: mov QWORD PTR [rbp-0x28],r12 | |
| 247 | + 403b95: xor r12d,r12d | |
| 248 | + 403b98: mov QWORD PTR [rbp-0x20],rdx | |
| 249 | + 403b9c: mov QWORD PTR [rbp-0x18],rcx | |
| 250 | + 403ba0: xor ebx,ebx | |
| 251 | + 403ba2: mov r8,rsi</code></pre> | |
| 252 | +<p>The listing is what the encoder meant; <code>objdump</code> is what the processor will read. They tell the same story.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="syscalls.html">← System calls</a><a href="index.html">Contents</a><a class="next" href="volatile.html">Volatile →</a></div></article></div> | |
| 253 | +</main> | |
| 254 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 255 | +</body> | |
| 256 | +</html> |
| @@ -0,0 +1,158 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>A lock-free stack - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html" aria-current="page">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">Shared memory · lesson 17 of 18</p><h1>A lock-free stack</h1> | |
| 38 | +<p><code>CAS</code> 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.</p> | |
| 39 | +<h2>Push</h2> | |
| 40 | +<p>To push a node: point its <code>next</code> at the current head, then <code>CAS</code> the head from what you saw to the new node. If another thread pushed first, the <code>CAS</code> 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.</p> | |
| 41 | +<div class="file"><span>Treiber.raz</span></div><pre class="code"><code><span class="kw">module</span> Treiber; | |
| 42 | +<span class="kw">import</span> Out, Thread; | |
| 43 | + | |
| 44 | +<span class="kw">type</span> Node = <span class="kw">record</span> next: ^Node; val: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 45 | + | |
| 46 | +<span class="kw">const</span> Threads = <span class="number">4</span>; Each = <span class="number">5000</span>; | |
| 47 | + | |
| 48 | +<span class="kw">var</span> | |
| 49 | + top: ^Node; <span class="comment">(* the head, changed only by CAS *)</span> | |
| 50 | + nodes: [Threads * Each]Node; <span class="comment">(* every node a thread will push *)</span> | |
| 51 | + | |
| 52 | +<span class="comment">(* n onto the stack, without a lock *)</span> | |
| 53 | +<span class="kw">proc</span> push(n: ^Node); | |
| 54 | +<span class="kw">var</span> old: ^Node; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + old := top; | |
| 57 | + n^.next := old; | |
| 58 | + <span class="kw">while</span> <span class="kw">not</span> <span class="ty">CAS</span>(<span class="ty">ADR</span>(top), old, n) <span class="kw">do</span> | |
| 59 | + old := top; <span class="comment">(* lost the race: look again *)</span> | |
| 60 | + n^.next := old; | |
| 61 | + <span class="kw">end</span>; | |
| 62 | +<span class="kw">end</span>; | |
| 63 | + | |
| 64 | +<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); | |
| 65 | +<span class="kw">var</span> first, i: <span class="ty">INT</span>; | |
| 66 | +<span class="kw">begin</span> | |
| 67 | + first := <span class="ty">INT</span>(arg) * Each; | |
| 68 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Each - <span class="number">1</span> <span class="kw">do</span> | |
| 69 | + nodes[first + i].val := first + i; | |
| 70 | + push(<span class="ty">ADR</span>(nodes[first + i])); | |
| 71 | + <span class="kw">end</span>; | |
| 72 | +<span class="kw">end</span>; | |
| 73 | + | |
| 74 | +<span class="kw">proc</span> main*; | |
| 75 | +<span class="kw">var</span> th: [Threads]^Thread.Thread; i, count, sum: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; n: ^Node; | |
| 76 | +<span class="kw">begin</span> | |
| 77 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> | |
| 78 | + th[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(i)); | |
| 79 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 80 | + <span class="kw">end</span>; | |
| 81 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 82 | + n := top; | |
| 83 | + <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> | |
| 84 | + <span class="ty">INC</span>(count); | |
| 85 | + sum := sum + n^.val; | |
| 86 | + n := n^.next; | |
| 87 | + <span class="kw">end</span>; | |
| 88 | + Out.int(count); Out.char(<span class="string">' '</span>); Out.int(sum); Out.ln; | |
| 89 | + Out.int(Threads * Each * (Threads * Each - <span class="number">1</span>) <span class="kw">div</span> <span class="number">2</span>); Out.ln; | |
| 90 | +<span class="kw">end</span>; | |
| 91 | + | |
| 92 | +<span class="kw">end</span> Treiber.</code></pre> | |
| 93 | +<pre class="output"><code>20000 199990000 | |
| 94 | +199990000 | |
| 95 | +</code></pre> | |
| 96 | +<p>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.</p> | |
| 97 | +<p>The loop in <code>push</code> is the shape of every lock-free algorithm: read, compute, <code>CAS</code>, and read again on failure. The <code>CAS</code> is sequentially consistent, so the node's <code>val</code> and <code>next</code>, written before it with ordinary stores, are visible to a thread that finds the node through <code>top</code>.</p> | |
| 98 | +<h2>Pop, and the ABA problem</h2> | |
| 99 | +<p>Pop takes the head off: read <code>top</code>, read its <code>next</code>, <code>CAS</code> the head from <code>top</code> to <code>next</code>. It looks as easy as push, and it isn't. Between the two reads and the <code>CAS</code>, other threads may pop that node, pop others, and push the same node back, now with a different <code>next</code>. The head is the same pointer again, so the <code>CAS</code> succeeds, and installs a <code>next</code> that is stale: nodes disappear, or the stack points into freed memory. This is the <strong>ABA problem</strong>: the word changed from A to B and back to A, and the <code>CAS</code> can't tell.</p> | |
| 100 | +<p>There are three common ways out, and each has a cost:</p> | |
| 101 | +<ul><li><strong>Never reuse a node while anyone might hold it.</strong> 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.</li><li><strong>Add a counter to the head</strong>, so that A-B-A is A1-B2-A3. That is a word and a counter swapped together, and raz's <code>CAS</code> is for one word, so a program packs a small index and a counter into one <code>UINT</code>.</li><li><strong>Don't pop concurrently.</strong> Many threads push and one thread, at the end, takes everything with a single <code>XCHG(ADR(top), nil)</code> and walks the list in peace. A stack used this way for work lists and logs needs no more.</li></ul> | |
| 102 | +<div class="file"><span>Drain.raz</span></div><pre class="code"><code><span class="kw">module</span> Drain; | |
| 103 | +<span class="kw">import</span> Out, Thread; | |
| 104 | + | |
| 105 | +<span class="kw">type</span> Node = <span class="kw">record</span> next: ^Node; val: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 106 | + | |
| 107 | +<span class="kw">const</span> Threads = <span class="number">3</span>; Each = <span class="number">1000</span>; | |
| 108 | + | |
| 109 | +<span class="kw">var</span> | |
| 110 | + top: ^Node; | |
| 111 | + nodes: [Threads * Each]Node; | |
| 112 | + | |
| 113 | +<span class="kw">proc</span> push(n: ^Node); | |
| 114 | +<span class="kw">var</span> old: ^Node; | |
| 115 | +<span class="kw">begin</span> | |
| 116 | + old := top; | |
| 117 | + n^.next := old; | |
| 118 | + <span class="kw">while</span> <span class="kw">not</span> <span class="ty">CAS</span>(<span class="ty">ADR</span>(top), old, n) <span class="kw">do</span> | |
| 119 | + old := top; | |
| 120 | + n^.next := old; | |
| 121 | + <span class="kw">end</span>; | |
| 122 | +<span class="kw">end</span>; | |
| 123 | + | |
| 124 | +<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); | |
| 125 | +<span class="kw">var</span> first, i: <span class="ty">INT</span>; | |
| 126 | +<span class="kw">begin</span> | |
| 127 | + first := <span class="ty">INT</span>(arg) * Each; | |
| 128 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Each - <span class="number">1</span> <span class="kw">do</span> | |
| 129 | + nodes[first + i].val := <span class="number">1</span>; | |
| 130 | + push(<span class="ty">ADR</span>(nodes[first + i])); | |
| 131 | + <span class="kw">end</span>; | |
| 132 | +<span class="kw">end</span>; | |
| 133 | + | |
| 134 | +<span class="kw">proc</span> main*; | |
| 135 | +<span class="kw">var</span> th: [Threads]^Thread.Thread; i, count: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; all, n: ^Node; | |
| 136 | +<span class="kw">begin</span> | |
| 137 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> | |
| 138 | + th[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(i)); | |
| 139 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 140 | + <span class="kw">end</span>; | |
| 141 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 142 | + all := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(top), <span class="ty">nil</span>); <span class="comment">(* take the whole stack, atomically *)</span> | |
| 143 | + n := all; | |
| 144 | + <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> <span class="ty">INC</span>(count); n := n^.next; <span class="kw">end</span>; | |
| 145 | + Out.int(count); Out.str(<span class="string">" taken at once, "</span>); | |
| 146 | + <span class="kw">if</span> top = <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"none left\n"</span>); <span class="kw">end</span>; | |
| 147 | +<span class="kw">end</span>; | |
| 148 | + | |
| 149 | +<span class="kw">end</span> Drain.</code></pre> | |
| 150 | +<pre class="output"><code>3000 taken at once, none left | |
| 151 | +</code></pre> | |
| 152 | +<p>The atomic exchange takes everything pushed so far in one step, so the walk that follows races with nobody.</p> | |
| 153 | +<h2>When to use it</h2> | |
| 154 | +<p>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 <code>Mutex</code> 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.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="ordering.html">← Ordering and publication</a><a href="index.html">Contents</a><a class="next" href="ring.html">A ring buffer between threads →</a></div></article></div> | |
| 155 | +</main> | |
| 156 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 157 | +</body> | |
| 158 | +</html> |
| @@ -0,0 +1,122 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Ordering and publication - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html" aria-current="page">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">Shared memory · lesson 16 of 18</p><h1>Ordering and publication</h1> | |
| 38 | +<p>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?</p> | |
| 39 | +<p>The report is careful. Only volatile accesses, <code>CAS</code>, <code>XCHG</code>, <code>XADD</code> and <code>FENCE</code> 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 <code>FENCE</code> 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.</p> | |
| 40 | +<p>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.</p> | |
| 41 | +<h2>The pattern that is guaranteed: publish through an atomic</h2> | |
| 42 | +<p>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. <code>XCHG</code> is the store; <code>XADD(p, 0)</code> 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.</p> | |
| 43 | +<div class="file"><span>Publish.raz</span></div><pre class="code"><code><span class="kw">module</span> Publish; | |
| 44 | +<span class="kw">import</span> Out, Sys, Thread; | |
| 45 | + | |
| 46 | +<span class="kw">type</span> Message = <span class="kw">record</span> id: <span class="ty">INT</span>; text: [<span class="number">32</span>]<span class="ty">U8</span>; len: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 47 | + | |
| 48 | +<span class="kw">var</span> | |
| 49 | + msg: Message; <span class="comment">(* ordinary memory, written once, then published *)</span> | |
| 50 | + ready: <span class="ty">INT</span>; <span class="comment">(* the flag: only touched by atomics *)</span> | |
| 51 | + | |
| 52 | +<span class="kw">proc</span> producer(_arg: ^<span class="ty">U8</span>); | |
| 53 | +<span class="kw">begin</span> | |
| 54 | + Sys.sleep(<span class="number">10</span>); | |
| 55 | + msg.id := <span class="number">7</span>; | |
| 56 | + msg.text := <span class="string">"built before the flag"</span>; | |
| 57 | + msg.len := <span class="number">21</span>; | |
| 58 | + _ := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(ready), <span class="number">1</span>); <span class="comment">(* publish *)</span> | |
| 59 | +<span class="kw">end</span>; | |
| 60 | + | |
| 61 | +<span class="kw">proc</span> main*; | |
| 62 | +<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>; | |
| 63 | +<span class="kw">begin</span> | |
| 64 | + t, err := Thread.spawn(producer, <span class="ty">nil</span>); | |
| 65 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 66 | + <span class="kw">while</span> <span class="ty">XADD</span>(<span class="ty">ADR</span>(ready), <span class="number">0</span>) = <span class="number">0</span> <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; <span class="comment">(* wait for it *)</span> | |
| 67 | + Out.int(msg.id); Out.char(<span class="string">' '</span>); Out.str(msg.text[<span class="number">0</span>..msg.len]); Out.ln; | |
| 68 | + Thread.join(t); | |
| 69 | +<span class="kw">end</span>; | |
| 70 | + | |
| 71 | +<span class="kw">end</span> Publish.</code></pre> | |
| 72 | +<pre class="output"><code>7 built before the flag | |
| 73 | +</code></pre> | |
| 74 | +<p>The reader's loop makes no ordinary read of <code>ready</code>: it can't be kept in a register and read once, which is the danger of <code>while ready = 0 do end</code>. And the write of <code>msg</code> can't be delayed past the <code>XCHG</code>.</p> | |
| 75 | +<h2>The same with a fence</h2> | |
| 76 | +<p><code>FENCE</code> 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.</p> | |
| 77 | +<div class="file"><span>Fenced.raz</span></div><pre class="code"><code><span class="kw">module</span> Fenced; | |
| 78 | +<span class="kw">import</span> Out, Sys, Thread; | |
| 79 | + | |
| 80 | +<span class="kw">var</span> | |
| 81 | + data: <span class="ty">INT</span>; <span class="comment">(* ordinary *)</span> | |
| 82 | + flag: <span class="ty">INT</span>; <span class="comment">(* only reached through a volatile pointer *)</span> | |
| 83 | + | |
| 84 | +<span class="kw">proc</span> producer(_arg: ^<span class="ty">U8</span>); | |
| 85 | +<span class="kw">var</span> f: ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>; | |
| 86 | +<span class="kw">begin</span> | |
| 87 | + f := ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>(<span class="ty">ADR</span>(flag)); | |
| 88 | + Sys.sleep(<span class="number">10</span>); | |
| 89 | + data := <span class="number">1234</span>; | |
| 90 | + FENCE; <span class="comment">(* data is written before the flag is *)</span> | |
| 91 | + f^ := <span class="number">1</span>; | |
| 92 | +<span class="kw">end</span>; | |
| 93 | + | |
| 94 | +<span class="kw">proc</span> main*; | |
| 95 | +<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>; f: ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>; | |
| 96 | +<span class="kw">begin</span> | |
| 97 | + f := ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>(<span class="ty">ADR</span>(flag)); | |
| 98 | + t, err := Thread.spawn(producer, <span class="ty">nil</span>); | |
| 99 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 100 | + <span class="kw">while</span> f^ = <span class="number">0</span> <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; | |
| 101 | + FENCE; <span class="comment">(* and read after the flag is seen *)</span> | |
| 102 | + Out.int(data); Out.ln; | |
| 103 | + Thread.join(t); | |
| 104 | +<span class="kw">end</span>; | |
| 105 | + | |
| 106 | +<span class="kw">end</span> Fenced.</code></pre> | |
| 107 | +<pre class="output"><code>1234 | |
| 108 | +</code></pre> | |
| 109 | +<p>Both sides need a fence. A fence on the writer only says the data is written first; the reader must not read <code>data</code> before it has seen the flag.</p> | |
| 110 | +<h2>The version that is not guaranteed</h2> | |
| 111 | +<p>This is what *not* to write, and it is the most common bug in this area:</p> | |
| 112 | +<pre class="code"><code>var data, ready: INT; | |
| 113 | + | |
| 114 | +(* thread A *) data := 42; ready := 1; | |
| 115 | +(* thread B *) while ready = 0 do end; use(data);</code></pre> | |
| 116 | +<p>Both threads use ordinary accesses to shared variables. B's loop may read <code>ready</code> once into a register and spin forever; A's two writes may reach memory in either order; B may read <code>data</code> 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.</p> | |
| 117 | +<h2>The lesson of the three versions</h2> | |
| 118 | +<ul><li>Shared and written by someone: reach it through an atomic, a volatile pointer or a fence, every time, on both sides.</li><li>To hand over a bundle, publish a single atomic word *after* writing the bundle, and read the bundle only *after* seeing the word.</li><li>Everything under a <code>Lock</code> or a <code>Mutex</code> 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.</li></ul><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="atomics.html">← Atomics</a><a href="index.html">Contents</a><a class="next" href="lockfree.html">A lock-free stack →</a></div></article></div> | |
| 119 | +</main> | |
| 120 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 121 | +</body> | |
| 122 | +</html> |
| @@ -0,0 +1,182 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Time, randomness and other programs - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html" aria-current="page">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">The library · lesson 5 of 18</p><h1>Time, randomness and other programs</h1> | |
| 38 | +<p>Everything here is in <code>Sys</code>, and is the same procedures on every target raz supports: through system calls on Linux, through the C library elsewhere.</p> | |
| 39 | +<h2>Clocks and sleeping</h2> | |
| 40 | +<p><code>Sys.clock</code> is a clock that only goes forward, in nanoseconds: the one to measure a duration with. <code>Sys.now</code> is the wall clock, in nanoseconds since 1970 UTC, which can be set backwards, so it is for dates, not durations. <code>Sys.sleep</code> waits some milliseconds.</p> | |
| 41 | +<div class="file"><span>Timing.raz</span></div><pre class="code"><code><span class="kw">module</span> Timing; | |
| 42 | +<span class="kw">import</span> Out, Sys; | |
| 43 | + | |
| 44 | +<span class="kw">proc</span> main*; | |
| 45 | +<span class="kw">var</span> t0, t1, elapsed: <span class="ty">I64</span>; wall: <span class="ty">I64</span>; | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + t0 := Sys.clock(); | |
| 48 | + Sys.sleep(<span class="number">25</span>); | |
| 49 | + t1 := Sys.clock(); | |
| 50 | + elapsed := (t1 - t0) <span class="kw">div</span> <span class="number">1000000</span>; <span class="comment">(* milliseconds *)</span> | |
| 51 | + <span class="kw">if</span> (elapsed >= <span class="number">25</span>) <span class="kw">and</span> (elapsed < <span class="number">1000</span>) <span class="kw">then</span> | |
| 52 | + Out.str(<span class="string">"slept about 25 ms\n"</span>); | |
| 53 | + <span class="kw">end</span>; | |
| 54 | + wall := Sys.now(); | |
| 55 | + <span class="kw">if</span> wall > <span class="number">1700000000000000000</span> <span class="kw">then</span> Out.str(<span class="string">"after 2023\n"</span>); <span class="kw">end</span>; | |
| 56 | +<span class="kw">end</span>; | |
| 57 | + | |
| 58 | +<span class="kw">end</span> Timing.</code></pre> | |
| 59 | +<pre class="output"><code>slept about 25 ms | |
| 60 | +after 2023 | |
| 61 | +</code></pre> | |
| 62 | +<p>Every duration is an <code>I64</code> of nanoseconds, because a 32-bit <code>INT</code> would hold only a couple of seconds of them. The library's rule is that what may overflow a small target's <code>INT</code> is an <code>I64</code>.</p> | |
| 63 | +<h2>Random bytes</h2> | |
| 64 | +<p><code>Sys.random</code> fills a slice with random bytes from the system. Anything else is made from that: a number in a range, a shuffle.</p> | |
| 65 | +<div class="file"><span>Dice.raz</span></div><pre class="code"><code><span class="kw">module</span> Dice; | |
| 66 | +<span class="kw">import</span> Out, Sys, Str; | |
| 67 | + | |
| 68 | +<span class="comment">(* a number from 0 up to n, without bias *)</span> | |
| 69 | +<span class="kw">proc</span> below(n: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 70 | +<span class="kw">var</span> b: [<span class="number">8</span>]<span class="ty">U8</span>; x, limit: <span class="ty">U64</span>; | |
| 71 | +<span class="kw">begin</span> | |
| 72 | + limit := <span class="number">0FFFFFFFFFFFFFFFFH</span> - (<span class="number">0FFFFFFFFFFFFFFFFH</span> <span class="kw">mod</span> <span class="ty">U64</span>(n)) - <span class="number">1</span>; | |
| 73 | + Sys.random(b); | |
| 74 | + x := Str.le(b); | |
| 75 | + <span class="kw">while</span> x > limit <span class="kw">do</span> | |
| 76 | + Sys.random(b); | |
| 77 | + x := Str.le(b); | |
| 78 | + <span class="kw">end</span>; | |
| 79 | + <span class="kw">return</span> <span class="ty">INT</span>(x <span class="kw">mod</span> <span class="ty">U64</span>(n)); | |
| 80 | +<span class="kw">end</span>; | |
| 81 | + | |
| 82 | +<span class="kw">proc</span> main*; | |
| 83 | +<span class="kw">var</span> counts: [<span class="number">6</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; ok: <span class="ty">BOOL</span>; | |
| 84 | +<span class="kw">begin</span> | |
| 85 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">6000</span> <span class="kw">do</span> <span class="ty">INC</span>(counts[below(<span class="number">6</span>)]); <span class="kw">end</span>; | |
| 86 | + ok := <span class="ty">true</span>; | |
| 87 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> | |
| 88 | + <span class="kw">if</span> (counts[i] < <span class="number">800</span>) <span class="kw">or</span> (counts[i] > <span class="number">1200</span>) <span class="kw">then</span> ok := <span class="ty">false</span>; <span class="kw">end</span>; | |
| 89 | + <span class="kw">end</span>; | |
| 90 | + <span class="kw">if</span> ok <span class="kw">then</span> Out.str(<span class="string">"all six faces came up about a thousand times\n"</span>); <span class="kw">end</span>; | |
| 91 | +<span class="kw">end</span>; | |
| 92 | + | |
| 93 | +<span class="kw">end</span> Dice.</code></pre> | |
| 94 | +<pre class="output"><code>all six faces came up about a thousand times | |
| 95 | +</code></pre> | |
| 96 | +<h2>Running a program</h2> | |
| 97 | +<p><code>Sys.spawn</code> starts the program at a path with its arguments, environment, working directory and standard streams in a <code>Sys.Program</code> record. A zero field means this program's own. <code>Sys.wait</code> waits for it to end and says how: <code>exited</code> with its status, <code>killed</code> by a signal, or <code>stopped</code>.</p> | |
| 98 | +<div class="file"><span>Run.raz</span></div><pre class="code"><code><span class="kw">module</span> Run; | |
| 99 | +<span class="kw">import</span> Out, Sys; | |
| 100 | + | |
| 101 | +<span class="kw">proc</span> main*; | |
| 102 | +<span class="kw">var</span> p: Sys.Program; pid, status: <span class="ty">INT</span>; how: Sys.Status; | |
| 103 | +<span class="kw">begin</span> | |
| 104 | + p := {path: <span class="string">"/bin/echo"</span>, args: [<span class="string">"echo"</span>, <span class="string">"hello from a child"</span>]}; | |
| 105 | + pid := Sys.spawn(p); | |
| 106 | + <span class="kw">if</span> pid < <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"can't start\n"</span>); <span class="kw">return</span>; <span class="kw">end</span>; | |
| 107 | + Out.flush; <span class="comment">(* so that our text isn't behind the child's *)</span> | |
| 108 | + _, how, status := Sys.wait(pid, <span class="ty">true</span>); | |
| 109 | + <span class="kw">if</span> how = Sys.exited <span class="kw">then</span> | |
| 110 | + Out.str(<span class="string">"it exited with "</span>); Out.int(status); Out.ln; | |
| 111 | + <span class="kw">end</span>; | |
| 112 | +<span class="kw">end</span>; | |
| 113 | + | |
| 114 | +<span class="kw">end</span> Run.</code></pre> | |
| 115 | +<pre class="output"><code>hello from a child | |
| 116 | +it exited with 0 | |
| 117 | +</code></pre> | |
| 118 | +<h2>Capturing its output</h2> | |
| 119 | +<p>A program's standard output can be a pipe. <code>Sys.pipe</code> gives the descriptor to read and the one to write; give the write end to the child as <code>fds[1]</code>, close it here, and read until the end. This is how a program drives another: <code>ls</code>, a compiler, a script.</p> | |
| 120 | +<div class="file"><span>Capture.raz</span></div><pre class="code"><code><span class="kw">module</span> Capture; | |
| 121 | +<span class="kw">import</span> Out, Sys, Buf, Heap; | |
| 122 | + | |
| 123 | +<span class="kw">proc</span> main*; | |
| 124 | +<span class="kw">var</span> | |
| 125 | + p: Sys.Program; pid, rd, wr, n, status: <span class="ty">INT</span>; how: Sys.Status; | |
| 126 | + chunk: [<span class="number">256</span>]<span class="ty">U8</span>; b: Buf.Buf; | |
| 127 | +<span class="kw">begin</span> | |
| 128 | + rd, wr := Sys.pipe(); | |
| 129 | + p := {path: <span class="string">"/bin/sh"</span>, args: [<span class="string">"sh"</span>, <span class="string">"-c"</span>, <span class="string">"echo one; echo two; exit 7"</span>]}; | |
| 130 | + p.fds[<span class="number">1</span>] := wr; | |
| 131 | + pid := Sys.spawn(p); | |
| 132 | + Sys.close(wr); <span class="comment">(* only the child writes now *)</span> | |
| 133 | + Buf.init(<span class="ty">ADR</span>(b), Heap.heap); | |
| 134 | + <span class="kw">defer</span> Buf.done(<span class="ty">ADR</span>(b)); | |
| 135 | + n := Sys.read(rd, chunk); | |
| 136 | + <span class="kw">while</span> n > <span class="number">0</span> <span class="kw">do</span> | |
| 137 | + Buf.str(<span class="ty">ADR</span>(b), chunk[<span class="number">0</span>..n]); | |
| 138 | + n := Sys.read(rd, chunk); | |
| 139 | + <span class="kw">end</span>; | |
| 140 | + Sys.close(rd); | |
| 141 | + _, how, status := Sys.wait(pid, <span class="ty">true</span>); | |
| 142 | + Out.str(<span class="string">"captured: "</span>); Out.str(Buf.bytes(<span class="ty">ADR</span>(b))); | |
| 143 | + Out.str(<span class="string">"status "</span>); Out.int(status); Out.ln; | |
| 144 | + <span class="kw">if</span> how = Sys.exited <span class="kw">then</span> Out.str(<span class="string">"(a normal exit)\n"</span>); <span class="kw">end</span>; | |
| 145 | +<span class="kw">end</span>; | |
| 146 | + | |
| 147 | +<span class="kw">end</span> Capture.</code></pre> | |
| 148 | +<pre class="output"><code>captured: one | |
| 149 | +two | |
| 150 | +status 7 | |
| 151 | +(a normal exit) | |
| 152 | +</code></pre> | |
| 153 | +<p>Closing the write end in the parent matters: the read ends only when every holder of the write end has closed it.</p> | |
| 154 | +<h2>Environment and working directory</h2> | |
| 155 | +<p><code>Sys.env("HOME")</code> is an environment variable's value, or an empty string if it is unset. <code>Sys.workDir</code> and <code>Sys.setWorkDir</code> read and change the directory. The <code>Sys.Program</code> record's <code>env</code>, <code>onlyEnv</code> and <code>dir</code> give a child its own.</p> | |
| 156 | +<div class="file"><span>Where.raz</span></div><pre class="code"><code><span class="kw">module</span> Where; | |
| 157 | +<span class="kw">import</span> Out, Sys; | |
| 158 | + | |
| 159 | +<span class="kw">proc</span> main*; | |
| 160 | +<span class="kw">var</span> p: Sys.Program; pid, rd, wr, n: <span class="ty">INT</span>; chunk: [<span class="number">64</span>]<span class="ty">U8</span>; | |
| 161 | +<span class="kw">begin</span> | |
| 162 | + <span class="kw">if</span> Sys.env(<span class="string">"RAZ_SURELY_UNSET"</span>) = <span class="string">""</span> <span class="kw">then</span> Out.str(<span class="string">"unset reads as empty\n"</span>); <span class="kw">end</span>; | |
| 163 | + rd, wr := Sys.pipe(); | |
| 164 | + p := {path: <span class="string">"/bin/sh"</span>, args: [<span class="string">"sh"</span>, <span class="string">"-c"</span>, <span class="string">"echo $GREETING from $(pwd)"</span>], | |
| 165 | + env: [<span class="string">"GREETING=hello"</span>], dir: <span class="string">"/tmp"</span>}; | |
| 166 | + p.fds[<span class="number">1</span>] := wr; | |
| 167 | + pid := Sys.spawn(p); | |
| 168 | + Sys.close(wr); | |
| 169 | + n := Sys.read(rd, chunk); | |
| 170 | + Out.str(chunk[<span class="number">0</span>..n]); | |
| 171 | + Sys.close(rd); | |
| 172 | + _, _, _ := Sys.wait(pid, <span class="ty">true</span>); | |
| 173 | +<span class="kw">end</span>; | |
| 174 | + | |
| 175 | +<span class="kw">end</span> Where.</code></pre> | |
| 176 | +<pre class="output"><code>unset reads as empty | |
| 177 | +hello from /tmp | |
| 178 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="files.html">← Files and the command line</a><a href="index.html">Contents</a><a class="next" href="allocators.html">Writing an allocator →</a></div></article></div> | |
| 179 | +</main> | |
| 180 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 181 | +</body> | |
| 182 | +</html> |
| @@ -0,0 +1,130 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>A ring buffer between threads - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html" aria-current="page">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">Shared memory · lesson 18 of 18</p><h1>A ring buffer between threads</h1> | |
| 38 | +<p>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.</p> | |
| 39 | +<h2>The design</h2> | |
| 40 | +<p>The queue is a fixed array of slots, used as a circle, and two counters that only ever grow: <code>tail</code>, the number of items the producer has put in, and <code>head</code>, the number the consumer has taken out. The item <code>n</code> lives in slot <code>n mod Size</code>. The queue is empty when the two are equal, and full when they differ by <code>Size</code>.</p> | |
| 41 | +<p>The design rule is that <strong>each counter has exactly one writer</strong>. Only the producer changes <code>tail</code>; only the consumer changes <code>head</code>. 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 <code>CAS</code> is needed, because there is never a race to resolve: only a handoff.</p> | |
| 42 | +<p>The handoff is the publish pattern of the ordering lesson. The producer writes the slot, then publishes it with an atomic store of <code>tail</code>; the consumer sees the new <code>tail</code> with an atomic load and only then reads the slot. In the other direction, the consumer frees a slot by storing <code>head</code>, and the producer only reuses it after loading <code>head</code> and seeing that.</p> | |
| 43 | +<h2>The module</h2> | |
| 44 | +<div class="file"><span>Ring.raz</span></div><pre class="code"><code><span class="kw">module</span> Ring; | |
| 45 | +<span class="kw">import</span> Sys; | |
| 46 | + | |
| 47 | +<span class="kw">const</span> Size* = <span class="number">64</span>; | |
| 48 | + | |
| 49 | +<span class="kw">type</span> | |
| 50 | + Ring* = <span class="kw">record</span> | |
| 51 | + slots: [Size]<span class="ty">INT</span>; | |
| 52 | + head, tail: <span class="ty">INT</span>; <span class="comment">(* items taken, items put; each has one writer *)</span> | |
| 53 | + <span class="kw">end</span>; | |
| 54 | + | |
| 55 | +<span class="comment">(* v into the ring, waiting while it is full *)</span> | |
| 56 | +<span class="kw">proc</span> put*(r: ^Ring; v: <span class="ty">INT</span>); | |
| 57 | +<span class="kw">var</span> t: <span class="ty">INT</span>; | |
| 58 | +<span class="kw">begin</span> | |
| 59 | + t := r^.tail; <span class="comment">(* mine: an ordinary read *)</span> | |
| 60 | + <span class="kw">while</span> t - <span class="ty">XADD</span>(<span class="ty">ADR</span>(r^.head), <span class="number">0</span>) = Size <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; <span class="comment">(* full *)</span> | |
| 61 | + r^.slots[t <span class="kw">mod</span> Size] := v; | |
| 62 | + _ := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(r^.tail), t + <span class="number">1</span>); <span class="comment">(* publish the slot *)</span> | |
| 63 | +<span class="kw">end</span>; | |
| 64 | + | |
| 65 | +<span class="comment">(* the next value, waiting while the ring is empty *)</span> | |
| 66 | +<span class="kw">proc</span> take*(r: ^Ring): <span class="ty">INT</span>; | |
| 67 | +<span class="kw">var</span> h, v: <span class="ty">INT</span>; | |
| 68 | +<span class="kw">begin</span> | |
| 69 | + h := r^.head; <span class="comment">(* mine *)</span> | |
| 70 | + <span class="kw">while</span> <span class="ty">XADD</span>(<span class="ty">ADR</span>(r^.tail), <span class="number">0</span>) = h <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; <span class="comment">(* empty *)</span> | |
| 71 | + v := r^.slots[h <span class="kw">mod</span> Size]; | |
| 72 | + _ := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(r^.head), h + <span class="number">1</span>); <span class="comment">(* give the slot back *)</span> | |
| 73 | + <span class="kw">return</span> v; | |
| 74 | +<span class="kw">end</span>; | |
| 75 | + | |
| 76 | +<span class="kw">end</span> Ring.</code></pre> | |
| 77 | +<h2>Using it</h2> | |
| 78 | +<p>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.</p> | |
| 79 | +<div class="file"><span>Pipe.raz</span></div><pre class="code"><code><span class="kw">module</span> Pipe; | |
| 80 | +<span class="kw">import</span> Out, Fmt, Ring, Thread; | |
| 81 | + | |
| 82 | +<span class="kw">const</span> Count = <span class="number">100000</span>; | |
| 83 | + | |
| 84 | +<span class="kw">var</span> | |
| 85 | + ring: Ring.Ring; | |
| 86 | + sum, outOfOrder: <span class="ty">INT</span>; | |
| 87 | + | |
| 88 | +<span class="kw">proc</span> producer(_arg: ^<span class="ty">U8</span>); | |
| 89 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 90 | +<span class="kw">begin</span> | |
| 91 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> Count <span class="kw">do</span> Ring.put(<span class="ty">ADR</span>(ring), i); <span class="kw">end</span>; | |
| 92 | +<span class="kw">end</span>; | |
| 93 | + | |
| 94 | +<span class="kw">proc</span> consumer(_arg: ^<span class="ty">U8</span>); | |
| 95 | +<span class="kw">var</span> i, v: <span class="ty">INT</span>; | |
| 96 | +<span class="kw">begin</span> | |
| 97 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> Count <span class="kw">do</span> | |
| 98 | + v := Ring.take(<span class="ty">ADR</span>(ring)); | |
| 99 | + <span class="kw">if</span> v # i <span class="kw">then</span> <span class="ty">INC</span>(outOfOrder); <span class="kw">end</span>; | |
| 100 | + sum := sum + v; | |
| 101 | + <span class="kw">end</span>; | |
| 102 | +<span class="kw">end</span>; | |
| 103 | + | |
| 104 | +<span class="kw">proc</span> main*; | |
| 105 | +<span class="kw">var</span> p, c: ^Thread.Thread; err: <span class="ty">ERROR</span>; | |
| 106 | +<span class="kw">begin</span> | |
| 107 | + p, err := Thread.spawn(producer, <span class="ty">nil</span>); | |
| 108 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 109 | + c, err := Thread.spawn(consumer, <span class="ty">nil</span>); | |
| 110 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 111 | + Thread.join(p); | |
| 112 | + Thread.join(c); | |
| 113 | + Fmt.print(<span class="string">"{} items, sum {}, {} out of order\n"</span>, | |
| 114 | + [Fmt.int(Count), Fmt.int(sum), Fmt.int(outOfOrder)]); | |
| 115 | +<span class="kw">end</span>; | |
| 116 | + | |
| 117 | +<span class="kw">end</span> Pipe.</code></pre> | |
| 118 | +<pre class="output"><code>100000 items, sum 5000050000, 0 out of order | |
| 119 | +</code></pre> | |
| 120 | +<p>The sum of 1 to 100000 is 5000050000, and nothing arrives out of order. <code>sum</code> and <code>outOfOrder</code> are written only by the consumer thread and read by <code>main</code> after <code>Thread.join</code>, which is the synchronization that makes them visible: a join is the thread's end, observed.</p> | |
| 121 | +<h2>What it used</h2> | |
| 122 | +<ul><li><strong>Modules</strong> (<code>Ring</code>, with its record's own fields unexported).</li><li><strong>Atomics</strong> for the handoff, and an ordering argument for why a slot is complete when its counter moves.</li><li><strong>Threads</strong> from <code>Thread</code>, with no C in the program.</li><li><strong>The checks</strong>, which stay on: <code>slots[t mod Size]</code> is an indexed array access that can't leave the array, whatever the counters do.</li></ul> | |
| 123 | +<p>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 <code>put</code> and <code>take</code> should make, and the sort a reader should demand.</p> | |
| 124 | +<h2>Where next</h2> | |
| 125 | +<p>That is the end of the tour. A few places to continue:</p> | |
| 126 | +<ul><li><strong><a href="../spec.html">The report</a></strong> defines the language, and is short enough to read through.</li><li><strong><code>doc/compiler.md</code></strong> 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.</li><li><strong><code>lib/</code></strong> is the library, in raz. Each module's own <code>main</code> is its test. Reading <code>Heap</code>, <code>Map</code>, <code>Opt</code> and <code>Thread</code> is the best remaining education.</li><li><strong><code>tools/Doc.raz</code></strong> prints what a module exports with its comments: <code>raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz</code>.</li><li><strong><code>examples/</code></strong> holds small programs with the output each should give, and <code>conform/</code> holds what any implementation must do.</li></ul><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="lockfree.html">← A lock-free stack</a><a href="index.html">Contents</a><a class="next" href="../spec.html">The report →</a></div></article></div> | |
| 127 | +</main> | |
| 128 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 129 | +</body> | |
| 130 | +</html> |
| @@ -0,0 +1,143 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>A program with no run time - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html" aria-current="page">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">Standing alone · lesson 7 of 18</p><h1>A program with no run time</h1> | |
| 38 | +<p>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.</p> | |
| 39 | +<h2>The smallest program</h2> | |
| 40 | +<p>This program imports nothing. It makes the <code>write</code> system call itself, with the built-in <code>SYSCALL</code>, and returns.</p> | |
| 41 | +<div class="file"><span>Bare.raz</span></div><pre class="code"><code><span class="kw">module</span> Bare; | |
| 42 | + | |
| 43 | +<span class="kw">const</span> Msg = <span class="string">"hello from raw system calls\n"</span>; | |
| 44 | + | |
| 45 | +<span class="kw">proc</span> main*; | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + _ := SYSCALL(<span class="number">1</span>, <span class="number">1</span>, <span class="ty">ADR</span>(Msg[<span class="number">0</span>]), <span class="ty">LEN</span>(Msg)); | |
| 48 | +<span class="kw">end</span>; | |
| 49 | + | |
| 50 | +<span class="kw">end</span> Bare.</code></pre> | |
| 51 | +<pre class="output term"><code><span class="cmd">$ raz Bare.raz</span> | |
| 52 | +<span class="cmd">$ ./Bare</span> | |
| 53 | +hello from raw system calls | |
| 54 | +<span class="cmd">$ file Bare</span> | |
| 55 | +Bare: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, with debug_info, not stripped | |
| 56 | +<span class="cmd">$ ldd Bare</span> | |
| 57 | + not a dynamic executable | |
| 58 | +<span class="cmd">$ ls -l Bare | awk '{print $5, "bytes"}'</span> | |
| 59 | +26272 bytes</code></pre> | |
| 60 | +<p>It is statically linked: no interpreter, no shared libraries, no <code>libc</code>. <code>ldd</code> says so.</p> | |
| 61 | +<h2>What it does when it runs</h2> | |
| 62 | +<p><code>strace</code> lists every system call a program makes. This is the whole of it:</p> | |
| 63 | +<pre class="output term"><code><span class="cmd">$ strace ./Bare 2>&1 >/dev/null | sed -e 's/0x[0-9a-f]\{5,\}/ADDR/g' -e 's/[0-9]* vars/N vars/'</span> | |
| 64 | +execve("./Bare", ["./Bare"], ADDR /* N vars */) = 0 | |
| 65 | +sigaltstack({ss_sp=ADDR, ss_flags=0, ss_size=16384}, NULL) = 0 | |
| 66 | +rt_sigaction(SIGSEGV, {sa_handler=ADDR, sa_mask=[], sa_flags=SA_RESTORER|SA_ONSTACK|SA_RESETHAND|SA_SIGINFO, sa_restorer=ADDR}, NULL, 8) = 0 | |
| 67 | +rt_sigaction(SIGFPE, {sa_handler=ADDR, sa_mask=[], sa_flags=SA_RESTORER|SA_ONSTACK|SA_RESETHAND|SA_SIGINFO, sa_restorer=ADDR}, NULL, 8) = 0 | |
| 68 | +write(1, "hello from raw system calls\n", 28) = 28 | |
| 69 | +exit_group(0) = ? | |
| 70 | ++++ exited with 0 +++</code></pre> | |
| 71 | +<p>The start-up code does four things before <code>main</code> runs: it sets up a stack of its own for signal handlers (<code>sigaltstack</code>), and installs handlers for <code>SIGSEGV</code> and <code>SIGFPE</code>. That is what turns a <code>nil</code> pointer or a division by zero into a message that names the place, instead of a bare "Segmentation fault". Then <code>main</code> runs its single <code>write</code>, and the program ends with <code>exit_group</code>. Nothing is mapped, loaded, or looked up.</p> | |
| 72 | +<h2>Programs that use C</h2> | |
| 73 | +<p>A program that declares an <code>extern</code> 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 <code>printf</code>:</p> | |
| 74 | +<div class="file"><span>Cprint.raz</span></div><pre class="code"><code><span class="kw">module</span> Cprint; | |
| 75 | + | |
| 76 | +<span class="kw">extern</span> <span class="kw">proc</span> puts(s: ^<span class="ty">U8</span>): <span class="ty">I32</span>; | |
| 77 | + | |
| 78 | +<span class="kw">proc</span> main*; | |
| 79 | +<span class="kw">begin</span> | |
| 80 | + _ := puts(<span class="string">"hello from C"</span>); | |
| 81 | +<span class="kw">end</span>; | |
| 82 | + | |
| 83 | +<span class="kw">end</span> Cprint.</code></pre> | |
| 84 | +<pre class="output term"><code><span class="cmd">$ raz Cprint.raz</span> | |
| 85 | +<span class="cmd">$ ./Cprint</span> | |
| 86 | +hello from C | |
| 87 | +<span class="cmd">$ file Cprint</span> | |
| 88 | +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 | |
| 89 | +<span class="cmd">$ ldd Cprint | sed 's/ (0x[0-9a-f]*)//'</span> | |
| 90 | + linux-vdso.so.1 | |
| 91 | + libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 | |
| 92 | + /lib64/ld-linux-x86-64.so.2</code></pre> | |
| 93 | +<p>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 <code>extern</code> or a <code>link</code> of a library.</p> | |
| 94 | +<h2>Only what is reached</h2> | |
| 95 | +<p>The compiler keeps only what can be reached from <code>main</code> 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.</p> | |
| 96 | +<div class="file"><span>Lean.raz</span></div><pre class="code"><code><span class="kw">module</span> Lean; | |
| 97 | +<span class="kw">import</span> Out; | |
| 98 | + | |
| 99 | +<span class="kw">proc</span> main*; | |
| 100 | +<span class="kw">begin</span> | |
| 101 | + Out.str(<span class="string">"same program\n"</span>); | |
| 102 | +<span class="kw">end</span>; | |
| 103 | + | |
| 104 | +<span class="kw">end</span> Lean.</code></pre> | |
| 105 | +<div class="file"><span>Heavy.raz</span></div><pre class="code"><code><span class="kw">module</span> Heavy; | |
| 106 | +<span class="kw">import</span> Out; | |
| 107 | + | |
| 108 | +<span class="kw">var</span> table: [<span class="number">100000</span>]<span class="ty">INT</span>; | |
| 109 | + | |
| 110 | +<span class="comment">(* exported, but never called, so never in the executable *)</span> | |
| 111 | +<span class="kw">proc</span> unused*(n: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 112 | +<span class="kw">var</span> i, s: <span class="ty">INT</span>; | |
| 113 | +<span class="kw">begin</span> | |
| 114 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">99999</span> <span class="kw">do</span> table[i] := n * i; s := s + table[i]; <span class="kw">end</span>; | |
| 115 | + Out.str(<span class="string">"a long string that nobody will ever print, to give it some weight"</span>); | |
| 116 | + <span class="kw">return</span> s; | |
| 117 | +<span class="kw">end</span>; | |
| 118 | + | |
| 119 | +<span class="kw">proc</span> main*; | |
| 120 | +<span class="kw">begin</span> | |
| 121 | + Out.str(<span class="string">"same program\n"</span>); | |
| 122 | +<span class="kw">end</span>; | |
| 123 | + | |
| 124 | +<span class="kw">end</span> Heavy.</code></pre> | |
| 125 | +<pre class="output term"><code><span class="cmd">$ raz Lean.raz</span> | |
| 126 | +<span class="cmd">$ raz Heavy.raz</span> | |
| 127 | +<span class="cmd">$ ls -l Lean Heavy | awk '{print $9, $5}'</span> | |
| 128 | +Heavy 28480 | |
| 129 | +Lean 28472</code></pre> | |
| 130 | +<p>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.</p> | |
| 131 | +<h2>Stripping</h2> | |
| 132 | +<p><code>-s</code> 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.</p> | |
| 133 | +<pre class="output term"><code><span class="cmd">$ raz -s -o Lean-stripped Lean.raz</span> | |
| 134 | +<span class="cmd">$ ls -l Lean Lean-stripped | awk '{print $9, $5}'</span> | |
| 135 | +Lean 28472 | |
| 136 | +Lean-stripped 6752 | |
| 137 | +<span class="cmd">$ ./Lean-stripped</span> | |
| 138 | +same program</code></pre> | |
| 139 | +<p><code>raz -S Lean.raz</code> 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.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="allocators.html">← Writing an allocator</a><a href="index.html">Contents</a><a class="next" href="linkstatic.html">Threads without C, and keeping the two apart →</a></div></article></div> | |
| 140 | +</main> | |
| 141 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 142 | +</body> | |
| 143 | +</html> |
| @@ -0,0 +1,190 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>System calls - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html" aria-current="page">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">The machine · lesson 12 of 18</p><h1>System calls</h1> | |
| 38 | +<p>Under <code>Sys</code> there is one built-in: <code>SYSCALL(n, x1, ..., x6)</code>. It makes Linux system call number <code>n</code> with up to six arguments, each a pointer or an integer no wider than <code>INT</code>, and gives the raw result, an <code>INT</code>. A negative result is <code>-errno</code>. That is all the interface there is; <code>Sys.write</code>, <code>Sys.open</code> and the rest of <code>lib/Sys.linux-x86_64.raz</code> are written with it, in raz, in a few lines each.</p> | |
| 39 | +<p><code>SYSCALL</code> exists only on Linux targets. Other systems have no stable system call interface, which is why their <code>Sys</code> calls the C library instead.</p> | |
| 40 | +<h2>The shape of a call</h2> | |
| 41 | +<p><code>write(fd, buf, count)</code> is call number 1. The arguments are the descriptor, a pointer to the bytes, and how many.</p> | |
| 42 | +<div class="file"><span>Raw.raz</span></div><pre class="code"><code><span class="kw">module</span> Raw; | |
| 43 | + | |
| 44 | +<span class="kw">const</span> Msg = <span class="string">"straight to the kernel\n"</span>; | |
| 45 | + | |
| 46 | +<span class="kw">proc</span> main*; | |
| 47 | +<span class="kw">var</span> n: <span class="ty">INT</span>; | |
| 48 | +<span class="kw">begin</span> | |
| 49 | + n := SYSCALL(<span class="number">1</span>, <span class="number">1</span>, <span class="ty">ADR</span>(Msg[<span class="number">0</span>]), <span class="ty">LEN</span>(Msg)); | |
| 50 | + <span class="kw">if</span> n # <span class="ty">LEN</span>(Msg) <span class="kw">then</span> _ := SYSCALL(<span class="number">60</span>, <span class="number">1</span>); <span class="kw">end</span>; <span class="comment">(* exit(1), if it came up short *)</span> | |
| 51 | +<span class="kw">end</span>; | |
| 52 | + | |
| 53 | +<span class="kw">end</span> Raw.</code></pre> | |
| 54 | +<pre class="output term"><code><span class="cmd">$ raz -Werror Raw.raz</span> | |
| 55 | +<span class="cmd">$ ./Raw</span> | |
| 56 | +straight to the kernel</code></pre> | |
| 57 | +<p>That program has no <code>Out</code>, no <code>Sys</code>, and no output buffer. What it needs of the library is <code>Rt</code>'s start-up, which the compiler links in anyway.</p> | |
| 58 | +<h2>Reading the result</h2> | |
| 59 | +<p>A result that is negative is a failure, and its negation is the <code>errno</code>. <code>open</code> is call 2 and wants a C string: the path's bytes followed by a zero. A <code>[N]U8</code> made from a string literal is zero-filled past its length, so there is always a terminator.</p> | |
| 60 | +<div class="file"><span>Open.raz</span></div><pre class="code"><code><span class="kw">module</span> Open; | |
| 61 | +<span class="kw">import</span> Out; | |
| 62 | + | |
| 63 | +<span class="kw">proc</span> main*; | |
| 64 | +<span class="kw">var</span> path: [<span class="number">32</span>]<span class="ty">U8</span>; fd: <span class="ty">INT</span>; | |
| 65 | +<span class="kw">begin</span> | |
| 66 | + path := <span class="string">"/no/such/file"</span>; | |
| 67 | + fd := SYSCALL(<span class="number">2</span>, <span class="ty">ADR</span>(path[<span class="number">0</span>]), <span class="number">0</span>, <span class="number">0</span>); <span class="comment">(* open(path, O_RDONLY) *)</span> | |
| 68 | + Out.str(<span class="string">"open gave "</span>); Out.int(fd); Out.ln; <span class="comment">(* -2: ENOENT *)</span> | |
| 69 | + path := <span class="string">"/dev/null"</span>; | |
| 70 | + fd := SYSCALL(<span class="number">2</span>, <span class="ty">ADR</span>(path[<span class="number">0</span>]), <span class="number">0</span>, <span class="number">0</span>); | |
| 71 | + <span class="kw">if</span> fd >= <span class="number">0</span> <span class="kw">then</span> | |
| 72 | + Out.str(<span class="string">"opened /dev/null\n"</span>); | |
| 73 | + _ := SYSCALL(<span class="number">3</span>, fd); <span class="comment">(* close *)</span> | |
| 74 | + <span class="kw">end</span>; | |
| 75 | +<span class="kw">end</span>; | |
| 76 | + | |
| 77 | +<span class="kw">end</span> Open.</code></pre> | |
| 78 | +<pre class="output"><code>open gave -2 | |
| 79 | +opened /dev/null | |
| 80 | +</code></pre> | |
| 81 | +<p>The library's <code>Sys.openRead</code> does exactly this, and <code>Sys.close</code> too. Reading <code>lib/Sys.linux-x86_64.raz</code> is the best reference there is for what each call wants.</p> | |
| 82 | +<h2>A call that fills a structure</h2> | |
| 83 | +<p><code>uname</code> (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 <code>ADR</code> of it given to the kernel.</p> | |
| 84 | +<div class="file"><span>Who.raz</span></div><pre class="code"><code><span class="kw">module</span> Who; | |
| 85 | +<span class="kw">import</span> Out; | |
| 86 | + | |
| 87 | +<span class="comment">(* the length of the zero-ended string at the start of s *)</span> | |
| 88 | +<span class="kw">proc</span> cstr(s: []<span class="ty">U8</span>): <span class="ty">INT</span>; | |
| 89 | +<span class="kw">var</span> n: <span class="ty">INT</span>; | |
| 90 | +<span class="kw">begin</span> | |
| 91 | + n := <span class="number">0</span>; | |
| 92 | + <span class="kw">while</span> (n < <span class="ty">LEN</span>(s)) <span class="kw">and</span> (s[n] # <span class="number">0</span>) <span class="kw">do</span> <span class="ty">INC</span>(n); <span class="kw">end</span>; | |
| 93 | + <span class="kw">return</span> n; | |
| 94 | +<span class="kw">end</span>; | |
| 95 | + | |
| 96 | +<span class="kw">proc</span> main*; | |
| 97 | +<span class="kw">var</span> u: [<span class="number">390</span>]<span class="ty">U8</span>; | |
| 98 | +<span class="kw">begin</span> | |
| 99 | + <span class="kw">if</span> SYSCALL(<span class="number">63</span>, <span class="ty">ADR</span>(u[<span class="number">0</span>])) = <span class="number">0</span> <span class="kw">then</span> | |
| 100 | + Out.str(<span class="string">"system: "</span>); Out.str(u[<span class="number">0</span>..cstr(u[<span class="number">0</span>..<span class="number">65</span>])]); Out.ln; | |
| 101 | + Out.str(<span class="string">"machine: "</span>); Out.str(u[<span class="number">260</span>..<span class="number">260</span> + cstr(u[<span class="number">260</span>..<span class="number">325</span>])]); Out.ln; | |
| 102 | + <span class="kw">end</span>; | |
| 103 | +<span class="kw">end</span>; | |
| 104 | + | |
| 105 | +<span class="kw">end</span> Who.</code></pre> | |
| 106 | +<pre class="output"><code>system: Linux | |
| 107 | +machine: x86_64 | |
| 108 | +</code></pre> | |
| 109 | +<h2>Memory straight from the kernel</h2> | |
| 110 | +<p><code>mmap</code> 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 <code>munmap</code> (call 11). It is what <code>Mem.pages</code> does, and so what every allocator is ultimately made of.</p> | |
| 111 | +<div class="file"><span>Pages.raz</span></div><pre class="code"><code><span class="kw">module</span> Pages; | |
| 112 | +<span class="kw">import</span> Out; | |
| 113 | + | |
| 114 | +<span class="kw">proc</span> main*; | |
| 115 | +<span class="kw">var</span> p: ^<span class="ty">U8</span>; i: <span class="ty">INT</span>; total: <span class="ty">INT</span>; | |
| 116 | +<span class="kw">begin</span> | |
| 117 | + <span class="comment">(* length 4096; PROT_READ|WRITE = 3; MAP_PRIVATE|ANONYMOUS = 22H; no fd *)</span> | |
| 118 | + p := ^<span class="ty">U8</span>(SYSCALL(<span class="number">9</span>, <span class="number">0</span>, <span class="number">4096</span>, <span class="number">3</span>, <span class="number">22H</span>, -<span class="number">1</span>, <span class="number">0</span>)); | |
| 119 | + <span class="kw">if</span> <span class="ty">INT</span>(p) < <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"no memory\n"</span>); <span class="kw">return</span>; <span class="kw">end</span>; | |
| 120 | + Out.int(<span class="ty">INT</span>(p[<span class="number">0</span>]) + <span class="ty">INT</span>(p[<span class="number">4095</span>])); Out.str(<span class="string">" (zero, as promised)\n"</span>); | |
| 121 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4095</span> <span class="kw">do</span> p[i] := <span class="ty">U8</span>(i); <span class="kw">end</span>; | |
| 122 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4095</span> <span class="kw">do</span> <span class="ty">INC</span>(total, <span class="ty">INT</span>(p[i])); <span class="kw">end</span>; | |
| 123 | + Out.int(total); Out.ln; | |
| 124 | + _ := SYSCALL(<span class="number">11</span>, p, <span class="number">4096</span>); | |
| 125 | +<span class="kw">end</span>; | |
| 126 | + | |
| 127 | +<span class="kw">end</span> Pages.</code></pre> | |
| 128 | +<pre class="output"><code>0 (zero, as promised) | |
| 129 | +522240 | |
| 130 | +</code></pre> | |
| 131 | +<h2>A cat with no library</h2> | |
| 132 | +<p>Reading and writing in a loop is all <code>cat</code> does. With system calls, it is one procedure. Call 0 is <code>read</code> and call 1 is <code>write</code>; 0 and 1 are standard input and output.</p> | |
| 133 | +<div class="file"><span>Cat.raz</span></div><pre class="code"><code><span class="kw">module</span> Cat; | |
| 134 | + | |
| 135 | +<span class="kw">proc</span> main*: <span class="ty">INT</span>; | |
| 136 | +<span class="kw">var</span> buf: [<span class="number">4096</span>]<span class="ty">U8</span>; n, wrote, at: <span class="ty">INT</span>; | |
| 137 | +<span class="kw">begin</span> | |
| 138 | + n := SYSCALL(<span class="number">0</span>, <span class="number">0</span>, <span class="ty">ADR</span>(buf[<span class="number">0</span>]), <span class="ty">LEN</span>(buf)); | |
| 139 | + <span class="kw">while</span> n > <span class="number">0</span> <span class="kw">do</span> | |
| 140 | + at := <span class="number">0</span>; | |
| 141 | + <span class="kw">while</span> at < n <span class="kw">do</span> <span class="comment">(* a write may be partial *)</span> | |
| 142 | + wrote := SYSCALL(<span class="number">1</span>, <span class="number">1</span>, <span class="ty">ADR</span>(buf[at]), n - at); | |
| 143 | + <span class="kw">if</span> wrote < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="number">1</span>; <span class="kw">end</span>; | |
| 144 | + <span class="ty">INC</span>(at, wrote); | |
| 145 | + <span class="kw">end</span>; | |
| 146 | + n := SYSCALL(<span class="number">0</span>, <span class="number">0</span>, <span class="ty">ADR</span>(buf[<span class="number">0</span>]), <span class="ty">LEN</span>(buf)); | |
| 147 | + <span class="kw">end</span>; | |
| 148 | + <span class="kw">if</span> n < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="number">1</span>; <span class="kw">end</span>; | |
| 149 | + <span class="kw">return</span> <span class="number">0</span>; | |
| 150 | +<span class="kw">end</span>; | |
| 151 | + | |
| 152 | +<span class="kw">end</span> Cat.</code></pre> | |
| 153 | +<pre class="output term"><code><span class="cmd">$ raz Cat.raz</span> | |
| 154 | +<span class="cmd">$ echo "through the pipe" | ./Cat</span> | |
| 155 | +through the pipe | |
| 156 | +<span class="cmd">$ ./Cat < /dev/null; echo "status $?"</span> | |
| 157 | +status 0 | |
| 158 | +<span class="cmd">$ echo "see the calls" | strace -e trace=read,write ./Cat 2>&1 >/dev/null | grep -v '^+++'</span> | |
| 159 | +read(0, "see the calls\n", 4096) = 14 | |
| 160 | +write(1, "see the calls\n", 14) = 14 | |
| 161 | +read(0, "", 4096) = 0</code></pre> | |
| 162 | +<p>The partial-write loop is the kind of detail <code>Sys.write</code> leaves to the caller on purpose: it returns the bytes written, and the program decides what to do about the rest.</p> | |
| 163 | +<h2>In a code procedure</h2> | |
| 164 | +<p>A system call is also an instruction. <code>syscall</code> takes its number in <code>rax</code> and its arguments in <code>rdi</code>, <code>rsi</code>, <code>rdx</code>, <code>r10</code>, <code>r8</code> and <code>r9</code>, which is not quite the order a procedure's arguments arrive in, since <code>r10</code> takes the place of <code>rcx</code>, and <code>syscall</code> itself clobbers <code>rcx</code> and <code>r11</code>.</p> | |
| 165 | +<div class="file"><span>Ppid.raz</span></div><pre class="code"><code><span class="kw">module</span> Ppid; | |
| 166 | +<span class="kw">import</span> Out; | |
| 167 | + | |
| 168 | +<span class="comment">(* getppid, call 110: no arguments *)</span> | |
| 169 | +<span class="kw">proc</span> getppid: <span class="ty">INT</span>; | |
| 170 | +<span class="kw">code</span> | |
| 171 | + mov eax, <span class="number">110</span>; | |
| 172 | + syscall; | |
| 173 | + ret; | |
| 174 | +<span class="kw">end</span> getppid; | |
| 175 | + | |
| 176 | +<span class="kw">proc</span> main*; | |
| 177 | +<span class="kw">begin</span> | |
| 178 | + <span class="kw">if</span> (getppid() > <span class="number">0</span>) <span class="kw">and</span> (SYSCALL(<span class="number">110</span>) = getppid()) <span class="kw">then</span> | |
| 179 | + Out.str(<span class="string">"two ways to ask, one answer\n"</span>); | |
| 180 | + <span class="kw">end</span>; | |
| 181 | +<span class="kw">end</span>; | |
| 182 | + | |
| 183 | +<span class="kw">end</span> Ppid.</code></pre> | |
| 184 | +<pre class="output"><code>two ways to ask, one answer | |
| 185 | +</code></pre> | |
| 186 | +<p><code>SYSCALL</code> 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.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="asm.html">← Procedures in assembly</a><a href="index.html">Contents</a><a class="next" href="listing.html">What the compiler makes →</a></div></article></div> | |
| 187 | +</main> | |
| 188 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 189 | +</body> | |
| 190 | +</html> |
| @@ -0,0 +1,103 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>One module, one file per target - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html" aria-current="page">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">Standing alone · lesson 10 of 18</p><h1>One module, one file per target</h1> | |
| 38 | +<p>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 <code>Sys</code> is made, and it is how your own code should keep its system-dependent parts apart.</p> | |
| 39 | +<h2>The files</h2> | |
| 40 | +<p>A module <code>Name</code> lives in <code>Name.raz</code>. A module whose code depends on the system comes in one file per target, <code>Name.linux-x86_64.raz</code>, which the compiler looks for first. The library has <code>Sys.linux-x86_64.raz</code>, which makes system calls, and <code>Sys.raz</code>, which calls the C library instead, for every other system. A program that imports <code>Sys</code> doesn't know or care which it got.</p> | |
| 41 | +<pre class="output term"><code><span class="cmd">$ ls $RAZLIB | grep -i "^sys\|^thread"</span> | |
| 42 | +Sys.linux-x86_64.raz | |
| 43 | +Sys.raz | |
| 44 | +Thread.linux-x86_64.raz | |
| 45 | +<span class="cmd">$ cd $RAZLIB && grep -c SYSCALL Sys.linux-x86_64.raz Sys.raz</span> | |
| 46 | +Sys.linux-x86_64.raz:78 | |
| 47 | +Sys.raz:0</code></pre> | |
| 48 | +<h2>A module of your own</h2> | |
| 49 | +<p>Here is a module with two files. <code>Clock.linux-x86_64.raz</code> is for this target; <code>Clock.raz</code> is what any other target would use. Both say what they are in <code>Name</code>, and both make <code>ticks</code>.</p> | |
| 50 | +<div class="file"><span>Clock.linux-x86_64.raz</span></div><pre class="code"><code><span class="kw">module</span> Clock; | |
| 51 | +<span class="kw">import</span> Sys; | |
| 52 | + | |
| 53 | +<span class="kw">const</span> Name* = <span class="string">"the linux-x86_64 file"</span>; | |
| 54 | + | |
| 55 | +<span class="comment">(* a number that only grows *)</span> | |
| 56 | +<span class="kw">proc</span> ticks*: <span class="ty">I64</span>; | |
| 57 | +<span class="kw">begin</span> | |
| 58 | + <span class="kw">return</span> Sys.clock(); | |
| 59 | +<span class="kw">end</span>; | |
| 60 | + | |
| 61 | +<span class="kw">end</span> Clock.</code></pre> | |
| 62 | +<div class="file"><span>Clock.raz</span></div><pre class="code"><code><span class="kw">module</span> Clock; | |
| 63 | +<span class="kw">import</span> Sys; | |
| 64 | + | |
| 65 | +<span class="kw">const</span> Name* = <span class="string">"the portable file"</span>; | |
| 66 | + | |
| 67 | +<span class="comment">(* a number that only grows *)</span> | |
| 68 | +<span class="kw">proc</span> ticks*: <span class="ty">I64</span>; | |
| 69 | +<span class="kw">begin</span> | |
| 70 | + <span class="kw">return</span> Sys.clock(); | |
| 71 | +<span class="kw">end</span>; | |
| 72 | + | |
| 73 | +<span class="kw">end</span> Clock.</code></pre> | |
| 74 | +<p>A program that imports <code>Clock</code> gets the first of them here:</p> | |
| 75 | +<div class="file"><span>Show.raz</span></div><pre class="code"><code><span class="kw">module</span> Show; | |
| 76 | +<span class="kw">import</span> Out, Clock; | |
| 77 | + | |
| 78 | +<span class="kw">proc</span> main*; | |
| 79 | +<span class="kw">begin</span> | |
| 80 | + Out.str(<span class="string">"using "</span>); Out.str(Clock.Name); Out.ln; | |
| 81 | + <span class="kw">if</span> Clock.ticks() > <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"and it ticks\n"</span>); <span class="kw">end</span>; | |
| 82 | +<span class="kw">end</span>; | |
| 83 | + | |
| 84 | +<span class="kw">end</span> Show.</code></pre> | |
| 85 | +<pre class="output"><code>using the linux-x86_64 file | |
| 86 | +and it ticks | |
| 87 | +</code></pre> | |
| 88 | +<h2>Held to one interface</h2> | |
| 89 | +<p>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 <code>ticks</code> changed in the portable file to return an <code>INT</code>:</p> | |
| 90 | +<pre class="output term"><code><span class="cmd">$ mkdir drift && cp Clock*.raz Show.raz drift && cd drift</span> | |
| 91 | +<span class="cmd">$ sed -i 's/proc ticks\*: I64/proc ticks*: INT/; s/return Sys.clock()/return INT(Sys.clock())/' Clock.raz</span> | |
| 92 | +<span class="cmd">$ raz Show.raz</span> | |
| 93 | +raz: ./Clock.raz: ticks isn't exported as in ./Clock.linux-x86_64.raz</code></pre> | |
| 94 | +<p>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.</p> | |
| 95 | +<h2>What the compiler checks</h2> | |
| 96 | +<p>When it takes one of <code>Name.*.raz</code>, it also reads the declarations of the others beside it, and of <code>Name.raz</code> 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.</p> | |
| 97 | +<p>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.</p> | |
| 98 | +<h2>What stays the same everywhere</h2> | |
| 99 | +<p>The core of the library is what every target must have: <code>Rt</code>, <code>Out</code>, <code>Mem</code>, <code>Arena</code>, <code>Lock</code>, <code>Str</code> and <code>Buf</code>, and of <code>Sys</code> what they need. A program that keeps to the core runs on every target. <code>Thread</code>, <code>link</code> and <code>extern</code>, and most of <code>Sys</code>, are what a target may leave out when its system can't give them.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="lifecycle.html">← Starting, ending, and signals</a><a href="index.html">Contents</a><a class="next" href="asm.html">Procedures in assembly →</a></div></article></div> | |
| 100 | +</main> | |
| 101 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 102 | +</body> | |
| 103 | +</html> |
| @@ -0,0 +1,145 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | +<title>Volatile - Beyond Go</title> | |
| 7 | +<link rel="stylesheet" href="../style.css"> | |
| 8 | +</head> | |
| 9 | +<body> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | +<main> | |
| 12 | +<div class="tour"><aside><h2>Beyond Go</h2><h3>The library</h3><ol start='1'> | |
| 13 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 14 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 15 | +<li><a href="collections.html">Lists, maps and sorting</a></li> | |
| 16 | +<li><a href="files.html">Files and the command line</a></li> | |
| 17 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 18 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 19 | +</ol> | |
| 20 | +<h3>Standing alone</h3><ol start='7'> | |
| 21 | +<li><a href="static.html">A program with no run time</a></li> | |
| 22 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 23 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 24 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 25 | +</ol> | |
| 26 | +<h3>The machine</h3><ol start='11'> | |
| 27 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 28 | +<li><a href="syscalls.html">System calls</a></li> | |
| 29 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 30 | +</ol> | |
| 31 | +<h3>Shared memory</h3><ol start='14'> | |
| 32 | +<li><a href="volatile.html" aria-current="page">Volatile</a></li> | |
| 33 | +<li><a href="atomics.html">Atomics</a></li> | |
| 34 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 35 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 36 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 37 | +</ol></aside><article><p class="kicker">Shared memory · lesson 14 of 18</p><h1>Volatile</h1> | |
| 38 | +<p>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.</p> | |
| 39 | +<p>A variable reached through a <code>^VOLATILE T</code> 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.</p> | |
| 40 | +<h2>A device laid over memory</h2> | |
| 41 | +<p>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.</p> | |
| 42 | +<div class="file"><span>Uart.raz</span></div><pre class="code"><code><span class="kw">module</span> Uart; | |
| 43 | +<span class="kw">import</span> Out; | |
| 44 | + | |
| 45 | +<span class="kw">type</span> | |
| 46 | + Regs = <span class="kw">record</span> | |
| 47 | + data: <span class="ty">U32</span>; <span class="comment">(* offset 0 *)</span> | |
| 48 | + status: <span class="ty">U32</span>; <span class="comment">(* offset 4 *)</span> | |
| 49 | + control: <span class="ty">U8</span>; <span class="comment">(* offset 8 *)</span> | |
| 50 | + <span class="kw">end</span>; | |
| 51 | + | |
| 52 | +<span class="kw">var</span> page: [<span class="number">64</span>]<span class="ty">U8</span>; <span class="comment">(* where the device would be *)</span> | |
| 53 | + | |
| 54 | +<span class="kw">proc</span> main*; | |
| 55 | +<span class="kw">var</span> dev: ^<span class="kw">VOLATILE</span> Regs; i: <span class="ty">INT</span>; | |
| 56 | +<span class="kw">begin</span> | |
| 57 | + dev := ^<span class="kw">VOLATILE</span> Regs(<span class="ty">ADR</span>(page)); <span class="comment">(* the conversion is written *)</span> | |
| 58 | + dev^.control := <span class="number">1</span>; | |
| 59 | + dev^.status := <span class="number">0FFH</span>; | |
| 60 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 61 | + dev^.data := <span class="ty">U32</span>(<span class="string">'a'</span> + i); | |
| 62 | + Out.char(<span class="ty">U8</span>(dev^.data)); | |
| 63 | + <span class="kw">end</span>; | |
| 64 | + Out.ln; | |
| 65 | + FENCE; | |
| 66 | + Out.int(<span class="ty">INT</span>(page[<span class="number">8</span>])); Out.char(<span class="string">' '</span>); Out.int(<span class="ty">INT</span>(dev^.status)); Out.ln; | |
| 67 | +<span class="kw">end</span>; | |
| 68 | + | |
| 69 | +<span class="kw">end</span> Uart.</code></pre> | |
| 70 | +<pre class="output"><code>abc | |
| 71 | +1 255 | |
| 72 | +</code></pre> | |
| 73 | +<p>On real hardware the address would be a constant, <code>^VOLATILE Regs(0FEC00000H)</code>, which is a legal conversion since an integer constant converts to a pointer. The program is otherwise unchanged.</p> | |
| 74 | +<h2>What each access is</h2> | |
| 75 | +<p>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.</p> | |
| 76 | +<pre class="output term"><code><span class="cmd">$ raz -S Uart.raz | grep -n "dword\|byte" | head -2</span> | |
| 77 | +15: 34 mov byte [rbx + 8], 1 | |
| 78 | +17: 38 mov dword [rbx + 4], 255</code></pre> | |
| 79 | +<p>The <code>U8</code> control byte is written with a <code>byte</code> store, and the <code>U32</code> status with a <code>dword</code> one. Never a wider access that touches the neighbour, never two narrower ones.</p> | |
| 80 | +<h2>Waiting for something else to change</h2> | |
| 81 | +<p>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.</p> | |
| 82 | +<div class="file"><span>Poll.raz</span></div><pre class="code"><code><span class="kw">module</span> Poll; | |
| 83 | +<span class="kw">import</span> Out, Sys, Thread; | |
| 84 | + | |
| 85 | +<span class="kw">type</span> Dev = <span class="kw">record</span> status: <span class="ty">INT</span>; data: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 86 | + | |
| 87 | +<span class="kw">var</span> dev: Dev; | |
| 88 | + | |
| 89 | +<span class="kw">proc</span> device(_arg: ^<span class="ty">U8</span>); | |
| 90 | +<span class="kw">var</span> d: ^<span class="kw">VOLATILE</span> Dev; | |
| 91 | +<span class="kw">begin</span> | |
| 92 | + d := ^<span class="kw">VOLATILE</span> Dev(<span class="ty">ADR</span>(dev)); | |
| 93 | + Sys.sleep(<span class="number">20</span>); | |
| 94 | + d^.data := <span class="number">42</span>; | |
| 95 | + FENCE; <span class="comment">(* data before the flag that announces it *)</span> | |
| 96 | + d^.status := <span class="number">1</span>; | |
| 97 | +<span class="kw">end</span>; | |
| 98 | + | |
| 99 | +<span class="kw">proc</span> main*; | |
| 100 | +<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>; d: ^<span class="kw">VOLATILE</span> Dev; spins: <span class="ty">INT</span>; | |
| 101 | +<span class="kw">begin</span> | |
| 102 | + d := ^<span class="kw">VOLATILE</span> Dev(<span class="ty">ADR</span>(dev)); | |
| 103 | + t, err := Thread.spawn(device, <span class="ty">nil</span>); | |
| 104 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 105 | + <span class="kw">while</span> d^.status = <span class="number">0</span> <span class="kw">do</span> <span class="ty">INC</span>(spins); Sys.yield; <span class="kw">end</span>; | |
| 106 | + Out.int(d^.data); Out.ln; | |
| 107 | + <span class="kw">if</span> spins > <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"it waited for the device\n"</span>); <span class="kw">end</span>; | |
| 108 | + Thread.join(t); | |
| 109 | +<span class="kw">end</span>; | |
| 110 | + | |
| 111 | +<span class="kw">end</span> Poll.</code></pre> | |
| 112 | +<pre class="output"><code>42 | |
| 113 | +it waited for the device | |
| 114 | +</code></pre> | |
| 115 | +<p>The <code>FENCE</code> 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 <code>data</code> before <code>status</code>. The next lessons are about this.</p> | |
| 116 | +<h2>What volatile is not</h2> | |
| 117 | +<ul><li><strong>Not atomic across a read-modify-write.</strong> <code>INC(d^.count)</code> reads and then writes: two accesses, even through a volatile pointer. <code>XADD</code> is the atomic one.</li><li><strong>Not a lock.</strong> It says each access happens as written; it says nothing about what happens between them.</li><li><strong>Not for whole records or arrays.</strong> 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.</li><li><strong>Not silently dropped.</strong> A <code>^VOLATILE T</code> doesn't convert to a <code>^T</code> without a written conversion, so the volatile can't be lost by accident.</li></ul> | |
| 118 | +<p>The compiler holds the line on each of them:</p> | |
| 119 | +<div class="file"><span>Wrong.raz</span></div><pre class="code"><code><span class="kw">module</span> Wrong; | |
| 120 | + | |
| 121 | +<span class="kw">type</span> Pair = <span class="kw">record</span> a, b: <span class="ty">U32</span>; <span class="kw">end</span>; | |
| 122 | + | |
| 123 | +<span class="kw">var</span> cell: Pair; | |
| 124 | + | |
| 125 | +<span class="kw">proc</span> main*; | |
| 126 | +<span class="kw">var</span> v: ^<span class="kw">VOLATILE</span> Pair; p: ^Pair; copy: Pair; | |
| 127 | +<span class="kw">begin</span> | |
| 128 | + v := ^<span class="kw">VOLATILE</span> Pair(<span class="ty">ADR</span>(cell)); | |
| 129 | + p := v; | |
| 130 | + copy := v^; | |
| 131 | +<span class="kw">end</span>; | |
| 132 | + | |
| 133 | +<span class="kw">end</span> Wrong.</code></pre> | |
| 134 | +<pre class="output term"><code><span class="cmd">$ raz Wrong.raz</span> | |
| 135 | +Wrong.raz:11:10: error: can't use ^VOLATILE Pair as ^Pair | |
| 136 | + 11 | p := v; | |
| 137 | + | ^ | |
| 138 | +Wrong.raz:12:13: error: can't copy through a volatile pointer | |
| 139 | + 12 | copy := v^; | |
| 140 | + | ^^ | |
| 141 | +raz: 2 errors</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="listing.html">← What the compiler makes</a><a href="index.html">Contents</a><a class="next" href="atomics.html">Atomics →</a></div></article></div> | |
| 142 | +</main> | |
| 143 | +<footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> | |
| 144 | +</body> | |
| 145 | +</html> |
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="index.html" aria-current="page">raz</a><a href="tour/index.html">Raz, Set, Go</a><a href="spec.html">Report</a><a href="index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="index.html" aria-current="page">raz</a><a href="tour/index.html">Raz, Set, Go</a><a href="advanced/index.html">Beyond Go</a><a href="spec.html">Report</a><a href="index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | 12 | <section class="hero"> |
| 13 | 13 | <h1>raz</h1> |
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | <em>Raz</em> is Polish for <em>one</em>, as in counting.</p> |
| 16 | 16 | <div class="cta"> |
| 17 | 17 | <a class="btn primary" href="tour/index.html">Take the tour: Raz, Set, Go</a> |
| 18 | + <a class="btn" href="advanced/index.html">Beyond Go</a> | |
| 18 | 19 | <a class="btn" href="#download">Download</a> |
| 19 | 20 | <a class="btn" href="spec.html">Read the report</a> |
| 20 | 21 | </div> |
| @@ -86,6 +87,13 @@ | ||
| 86 | 87 | </ul> |
| 87 | 88 | </div> |
| 88 | 89 | </div> |
| 90 | + | |
| 91 | +<h2>Learn it</h2> | |
| 92 | +<p><a href="tour/index.html"><strong>Raz, Set, Go</strong></a> is a tour of the | |
| 93 | +language in 14 lessons, each with programs you can run. <a | |
| 94 | +href="advanced/index.html"><strong>Beyond Go</strong></a> is the second tour: | |
| 95 | +the library, programs with no run time, procedures in assembly, system calls, | |
| 96 | +volatile accesses, atomics and lock-free code, in 18 more.</p> | |
| 89 | 97 | |
| 90 | 98 | <h2>The language, in writing</h2> |
| 91 | 99 | <p>The language is defined by <a href="spec.html">the report</a>, which is |
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="index.html">raz</a><a href="tour/index.html">Raz, Set, Go</a><a href="spec.html" aria-current="page">Report</a><a href="index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="index.html">raz</a><a href="tour/index.html">Raz, Set, Go</a><a href="advanced/index.html">Beyond Go</a><a href="spec.html" aria-current="page">Report</a><a href="index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | 12 | <div class="spec"><ul> |
| 13 | 13 | <li><a href="#a-first-look" id="toc-a-first-look">1. A first |
| @@ -69,7 +69,7 @@ | ||
| 69 | 69 | .tour aside { font-family: system-ui, sans-serif; font-size: 14px; } |
| 70 | 70 | .tour aside h3 { margin: 1em 0 .2em; font-size: 12px; text-transform: uppercase; |
| 71 | 71 | letter-spacing: .08em; color: var(--muted); } |
| 72 | -.tour aside ol { margin: 0; padding-left: 1.5em; } .tour aside a { color: var(--fg); text-decoration: none; } | |
| 72 | +.tour aside ol { margin: 0; padding-left: 1.9em; } .tour aside a { color: var(--fg); text-decoration: none; } | |
| 73 | 73 | .tour aside a[aria-current] { color: var(--accent); font-weight: 700; } |
| 74 | 74 | @media (max-width: 55.99rem) { .tour aside { order: 2; border-top: 1px solid var(--line); } } |
| 75 | 75 | .tour article { min-width: 0; } |
| @@ -86,3 +86,7 @@ | ||
| 86 | 86 | .spec table { border-collapse: collapse; display: block; overflow-x: auto; font-size: 15px; } |
| 87 | 87 | .spec td, .spec th { border-bottom: 1px solid var(--line); padding: 3px 10px; text-align: left; } |
| 88 | 88 | .spec nav#TOC ul { list-style: none; padding-left: 1em; } |
| 89 | + | |
| 90 | +/* a shell session */ | |
| 91 | +pre.term::before { content: "terminal"; } | |
| 92 | +pre .cmd { color: #8fd18f; } |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -62,8 +62,81 @@ | ||
| 62 | 62 | <pre class="output"><code>10 20 30 40 50 |
| 63 | 63 | 3.000 |
| 64 | 64 | </code></pre> |
| 65 | -<p>An <code>extern</code> procedure is found by its name in the C library, or in a library a <code>link</code> 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 <code>order</code> is.</p> | |
| 66 | -<p>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.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="generics.html">← Generic modules</a><a href="index.html">Contents</a><a class="next" href="threads.html">Threads →</a></div></article></div> | |
| 65 | +<p>An <code>extern</code> procedure is found by its name in the C library, or in a library a <code>link</code> 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 <code>order</code> is. A record goes to C by pointer, never by value.</p> | |
| 66 | +<h2>What using C costs</h2> | |
| 67 | +<p>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 <code>extern</code> or a <code>link</code> of a library.</p> | |
| 68 | +<h2>Varargs</h2> | |
| 69 | +<p><code>...</code> after an <code>extern</code>'s parameters takes any number of further arguments, as <code>printf</code> wants. A string literal goes as a C string, an integer constant as an <code>INT</code>, a real constant as an <code>F64</code>. An <code>F32</code> is an error there, since C promotes it; write <code>F64(x)</code>.</p> | |
| 70 | +<div class="file"><span>Say.raz</span></div><pre class="code"><code><span class="kw">module</span> Say; | |
| 71 | +<span class="kw">import</span> Out; | |
| 72 | + | |
| 73 | +<span class="kw">extern</span> <span class="kw">proc</span> printf(format: ^<span class="ty">U8</span>; ...): <span class="ty">I32</span>; | |
| 74 | +<span class="kw">extern</span> <span class="kw">proc</span> fflush(f: ^<span class="ty">U8</span>): <span class="ty">I32</span>; | |
| 75 | +<span class="kw">extern</span> <span class="kw">proc</span> puts(s: ^<span class="ty">U8</span>): <span class="ty">I32</span>; | |
| 76 | + | |
| 77 | +<span class="kw">proc</span> main*; | |
| 78 | +<span class="kw">var</span> n: <span class="ty">INT</span>; x: <span class="ty">F32</span>; | |
| 79 | +<span class="kw">begin</span> | |
| 80 | + n := <span class="number">42</span>; | |
| 81 | + x := <span class="number">2.5</span>; | |
| 82 | + Out.str(<span class="string">"raz first\n"</span>); | |
| 83 | + Out.flush; <span class="comment">(* Out has a buffer; so does C *)</span> | |
| 84 | + _ := printf(<span class="string">"C says %ld and %.2f and %s\n"</span>, n, <span class="ty">F64</span>(x), <span class="string">"hello"</span>); | |
| 85 | + _ := puts(<span class="string">"and puts"</span>); | |
| 86 | + _ := fflush(<span class="ty">nil</span>); <span class="comment">(* nil: every C stream *)</span> | |
| 87 | + Out.str(<span class="string">"raz again\n"</span>); | |
| 88 | +<span class="kw">end</span>; | |
| 89 | + | |
| 90 | +<span class="kw">end</span> Say.</code></pre> | |
| 91 | +<pre class="output"><code>raz first | |
| 92 | +C says 42 and 2.50 and hello | |
| 93 | +and puts | |
| 94 | +raz again | |
| 95 | +</code></pre> | |
| 96 | +<p><code>Out</code> and C's <code>printf</code> 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.</p> | |
| 97 | +<h2>Libraries, and C's variables</h2> | |
| 98 | +<p><code>link "libm.so.6";</code> names a shared library to load at run time. An <code>extern var</code> is C's variable itself: reading it reads C's, assigning it writes C's.</p> | |
| 99 | +<div class="file"><span>Env.raz</span></div><pre class="code"><code><span class="kw">module</span> Env; | |
| 100 | +<span class="kw">import</span> Out; | |
| 101 | + | |
| 102 | +<span class="kw">extern</span> <span class="kw">var</span> environ: ^^<span class="ty">U8</span>; | |
| 103 | +<span class="kw">extern</span> <span class="kw">proc</span> strlen(s: ^<span class="ty">U8</span>): <span class="ty">UINT</span>; | |
| 104 | +<span class="kw">extern</span> <span class="kw">proc</span> getenv(name: ^<span class="ty">U8</span>): ^<span class="ty">U8</span>; | |
| 105 | + | |
| 106 | +<span class="kw">proc</span> main*; | |
| 107 | +<span class="kw">var</span> p: ^<span class="ty">U8</span>; n: <span class="ty">INT</span>; | |
| 108 | +<span class="kw">begin</span> | |
| 109 | + n := <span class="number">0</span>; | |
| 110 | + <span class="kw">while</span> environ[n] # <span class="ty">nil</span> <span class="kw">do</span> <span class="ty">INC</span>(n); <span class="kw">end</span>; | |
| 111 | + <span class="kw">if</span> n > <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"the environment is not empty\n"</span>); <span class="kw">end</span>; | |
| 112 | + p := getenv(<span class="string">"RAZ_NO_SUCH_VARIABLE"</span>); | |
| 113 | + <span class="kw">if</span> p = <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"not set\n"</span>); <span class="kw">end</span>; | |
| 114 | + Out.int(<span class="ty">INT</span>(strlen(<span class="string">"six"</span>))); Out.ln; | |
| 115 | +<span class="kw">end</span>; | |
| 116 | + | |
| 117 | +<span class="kw">end</span> Env.</code></pre> | |
| 118 | +<pre class="output"><code>the environment is not empty | |
| 119 | +not set | |
| 120 | +3 | |
| 121 | +</code></pre> | |
| 122 | +<h2>Callbacks</h2> | |
| 123 | +<p>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 <code>qsort</code> is given <code>order</code> 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.</p> | |
| 124 | +<div class="file"><span>Roots.raz</span></div><pre class="code"><code><span class="kw">module</span> Roots; | |
| 125 | +<span class="kw">import</span> Fmt; | |
| 126 | + | |
| 127 | +<span class="kw">link</span> <span class="string">"libm.so.6"</span>; | |
| 128 | + | |
| 129 | +<span class="kw">extern</span> <span class="kw">proc</span> cbrt(x: <span class="ty">F64</span>): <span class="ty">F64</span>; | |
| 130 | +<span class="kw">extern</span> <span class="kw">proc</span> hypot(x, y: <span class="ty">F64</span>): <span class="ty">F64</span>; | |
| 131 | + | |
| 132 | +<span class="kw">proc</span> main*; | |
| 133 | +<span class="kw">begin</span> | |
| 134 | + Fmt.print(<span class="string">"{} {}\n"</span>, [Fmt.real(cbrt(<span class="number">27.0</span>), <span class="number">3</span>), Fmt.real(hypot(<span class="number">3.0</span>, <span class="number">4.0</span>), <span class="number">3</span>)]); | |
| 135 | +<span class="kw">end</span>; | |
| 136 | + | |
| 137 | +<span class="kw">end</span> Roots.</code></pre> | |
| 138 | +<pre class="output"><code>3.000 5.000 | |
| 139 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="generics.html">← Generic modules</a><a href="index.html">Contents</a><a class="next" href="threads.html">Threads →</a></div></article></div> | |
| 67 | 140 | </main> |
| 68 | 141 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 69 | 142 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -54,9 +54,122 @@ | ||
| 54 | 54 | in Fail.get at Fail.raz:6:14: i = 3 |
| 55 | 55 | in Fail.main at Fail.raz:13:9: i = 3 |
| 56 | 56 | </span></code></pre> |
| 57 | -<p>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 <code>nil</code> pointer, a division by zero and a stack overflow.</p> | |
| 58 | -<p>A module that is sure of its indexes may say <code>check off;</code> after its imports, for speed; an index out of range there reads or writes whatever it reaches.</p> | |
| 59 | -<p>The program carries line numbers for gdb, and <code>RAZ_PROFILE=1</code> in its environment has it say where its time went.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="defer.html">← Defer</a><a href="index.html">Contents</a><a class="next" href="generics.html">Generic modules →</a></div></article></div> | |
| 57 | +<p>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 <code>0</code>s are what it printed before the fourth pass went one past the end.</p> | |
| 58 | +<h2>Reading the message</h2> | |
| 59 | +<p>The first line is the place of the offending expression: file, line and column, then what failed and the numbers involved. Each <code>in</code> 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.</p> | |
| 60 | +<h2>Other failures</h2> | |
| 61 | +<p>The same shape of message tells of a <code>nil</code> 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.</p> | |
| 62 | +<div class="file"><span>Nilp.raz</span></div><pre class="code"><code><span class="kw">module</span> Nilp; | |
| 63 | +<span class="kw">import</span> Out; | |
| 64 | + | |
| 65 | +<span class="kw">type</span> Node = <span class="kw">record</span> val: <span class="ty">INT</span>; next: ^Node; <span class="kw">end</span>; | |
| 66 | + | |
| 67 | +<span class="kw">proc</span> last(n: ^Node): <span class="ty">INT</span>; | |
| 68 | +<span class="kw">begin</span> | |
| 69 | + <span class="kw">while</span> n^.next # <span class="ty">nil</span> <span class="kw">do</span> n := n^.next; <span class="kw">end</span>; | |
| 70 | + <span class="kw">return</span> n^.val; | |
| 71 | +<span class="kw">end</span>; | |
| 72 | + | |
| 73 | +<span class="kw">proc</span> main*; | |
| 74 | +<span class="kw">var</span> a, b: Node; | |
| 75 | +<span class="kw">begin</span> | |
| 76 | + a.val := <span class="number">1</span>; b.val := <span class="number">2</span>; | |
| 77 | + a.next := <span class="ty">ADR</span>(b); | |
| 78 | + Out.int(last(<span class="ty">ADR</span>(a))); Out.ln; | |
| 79 | + Out.int(last(<span class="ty">nil</span>)); Out.ln; | |
| 80 | +<span class="kw">end</span>; | |
| 81 | + | |
| 82 | +<span class="kw">end</span> Nilp.</code></pre> | |
| 83 | +<pre class="output"><code><span class="err">Nilp.raz:8:11: stopped by a nil pointer | |
| 84 | + in Nilp.last at Nilp.raz:8:11: n = nil | |
| 85 | + in Nilp.main at Nilp.raz:18:5 | |
| 86 | +</span></code></pre> | |
| 87 | +<div class="file"><span>Zero.raz</span></div><pre class="code"><code><span class="kw">module</span> Zero; | |
| 88 | +<span class="kw">import</span> Out; | |
| 89 | + | |
| 90 | +<span class="kw">proc</span> ratio(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 91 | +<span class="kw">begin</span> | |
| 92 | + <span class="kw">return</span> a <span class="kw">div</span> b; | |
| 93 | +<span class="kw">end</span>; | |
| 94 | + | |
| 95 | +<span class="kw">proc</span> main*; | |
| 96 | +<span class="kw">var</span> n: <span class="ty">INT</span>; | |
| 97 | +<span class="kw">begin</span> | |
| 98 | + Out.int(ratio(<span class="number">10</span>, <span class="number">3</span>)); Out.ln; | |
| 99 | + Out.int(ratio(<span class="number">10</span>, n)); Out.ln; <span class="comment">(* n is zero: every variable starts at zero *)</span> | |
| 100 | +<span class="kw">end</span>; | |
| 101 | + | |
| 102 | +<span class="kw">end</span> Zero.</code></pre> | |
| 103 | +<pre class="output"><code><span class="err">Zero.raz:6:5: stopped by a division fault | |
| 104 | + in Zero.ratio at Zero.raz:6:5: a = 10, b = 0 | |
| 105 | + in Zero.main at Zero.raz:13:5: n = 0 | |
| 106 | +</span></code></pre> | |
| 107 | +<div class="file"><span>Slicing.raz</span></div><pre class="code"><code><span class="kw">module</span> Slicing; | |
| 108 | +<span class="kw">import</span> Out; | |
| 109 | + | |
| 110 | +<span class="kw">proc</span> main*; | |
| 111 | +<span class="kw">var</span> a: [<span class="number">5</span>]<span class="ty">INT</span>; s: []<span class="ty">INT</span>; hi: <span class="ty">INT</span>; | |
| 112 | +<span class="kw">begin</span> | |
| 113 | + hi := <span class="number">7</span>; | |
| 114 | + s := a[<span class="number">2</span>..<span class="number">5</span>]; | |
| 115 | + Out.int(<span class="ty">LEN</span>(s)); Out.ln; | |
| 116 | + s := a[<span class="number">2</span>..hi]; <span class="comment">(* past the end *)</span> | |
| 117 | + Out.int(<span class="ty">LEN</span>(s)); Out.ln; | |
| 118 | +<span class="kw">end</span>; | |
| 119 | + | |
| 120 | +<span class="kw">end</span> Slicing.</code></pre> | |
| 121 | +<pre class="output"><code>3 | |
| 122 | +<span class="err">Slicing.raz:10:12: slice 2..7 is out of range for a length of 5 | |
| 123 | + in Slicing.main at Slicing.raz:10:12: hi = 7 | |
| 124 | +</span></code></pre> | |
| 125 | +<p>In every case the output before the failure was written first. <code>Out</code>'s buffer is flushed by the failure, so what the program printed is never lost to the crash.</p> | |
| 126 | +<h2>A constant can fail at compile time</h2> | |
| 127 | +<p>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.</p> | |
| 128 | +<div class="file"><span>Early.raz</span></div><pre class="code"><code><span class="kw">module</span> Early; | |
| 129 | +<span class="kw">import</span> Out; | |
| 130 | + | |
| 131 | +<span class="kw">proc</span> main*; | |
| 132 | +<span class="kw">var</span> a: [<span class="number">3</span>]<span class="ty">INT</span>; | |
| 133 | +<span class="kw">begin</span> | |
| 134 | + a[<span class="number">3</span>] := <span class="number">1</span>; | |
| 135 | + Out.int(<span class="number">10</span> <span class="kw">div</span> <span class="number">0</span>); Out.ln; | |
| 136 | +<span class="kw">end</span>; | |
| 137 | + | |
| 138 | +<span class="kw">end</span> Early.</code></pre> | |
| 139 | +<pre class="output term"><code><span class="cmd">$ raz Early.raz</span> | |
| 140 | +Early.raz:7:7: error: index 3 is out of range for a length of 3 | |
| 141 | + 7 | a[3] := 1; | |
| 142 | + | ^ | |
| 143 | +Early.raz:8:13: error: division by zero | |
| 144 | + 8 | Out.int(10 div 0); Out.ln; | |
| 145 | + | ^^^^^^^^ | |
| 146 | +raz: 2 errors</code></pre> | |
| 147 | +<h2>Looking at where you are</h2> | |
| 148 | +<p><code>Rt.trace</code> 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.</p> | |
| 149 | +<div class="file"><span>Where.raz</span></div><pre class="code"><code><span class="kw">module</span> Where; | |
| 150 | +<span class="kw">import</span> Rt; | |
| 151 | + | |
| 152 | +<span class="kw">proc</span> inner(depth: <span class="ty">INT</span>); | |
| 153 | +<span class="kw">begin</span> | |
| 154 | + <span class="kw">if</span> depth = <span class="number">0</span> <span class="kw">then</span> Rt.trace; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 155 | + inner(depth - <span class="number">1</span>); | |
| 156 | +<span class="kw">end</span>; | |
| 157 | + | |
| 158 | +<span class="kw">proc</span> main*; | |
| 159 | +<span class="kw">begin</span> | |
| 160 | + inner(<span class="number">2</span>); | |
| 161 | +<span class="kw">end</span>; | |
| 162 | + | |
| 163 | +<span class="kw">end</span> Where.</code></pre> | |
| 164 | +<pre class="output"><code><span class="err"> in Where.inner at Where.raz:6:23: depth = 0 | |
| 165 | + in Where.inner at Where.raz:7:5: depth = 1 | |
| 166 | + and 1 more the same | |
| 167 | + in Where.main at Where.raz:12:5 | |
| 168 | +</span></code></pre> | |
| 169 | +<h2>Leaving the checks out</h2> | |
| 170 | +<p>A module that is sure of its indexes may say <code>check off;</code> 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 (<code>nil</code> and division), and callers of the module keep theirs. Use it for a measured inner loop, never as a first step.</p> | |
| 171 | +<h2>For gdb and the profiler</h2> | |
| 172 | +<p>The program carries names and line numbers, so <code>gdb</code> can break at <code>Fail.raz:6</code> and show raz source. <code>RAZ_PROFILE=1</code> in the environment makes a program sample itself every millisecond and say at the end where its time went, by procedure and by line.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="defer.html">← Defer</a><a href="index.html">Contents</a><a class="next" href="generics.html">Generic modules →</a></div></article></div> | |
| 60 | 173 | </main> |
| 61 | 174 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 62 | 175 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -77,8 +77,100 @@ | ||
| 77 | 77 | 0 |
| 78 | 78 | -1 |
| 79 | 79 | </code></pre> |
| 80 | -<p><code>defer s;</code> runs <code>s</code> when the program leaves the statements the <code>defer</code> stands in: at their end, or by a <code>return</code> or a <code>break</code>. Deferred statements run the last first, and only those whose <code>defer</code> was reached.</p> | |
| 81 | -<p>So a file is closed beside the line that opens it, however the procedure ends.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="errors.html">← Errors</a><a href="index.html">Contents</a><a class="next" href="checks.html">When it goes wrong →</a></div></article></div> | |
| 80 | +<p><code>defer s;</code> runs <code>s</code> when the program leaves the statements the <code>defer</code> stands in: at their end, or by a <code>return</code> or a <code>break</code>. Deferred statements run the last first, and only those whose <code>defer</code> was reached. So a file is closed beside the line that opens it, however the procedure ends.</p> | |
| 81 | +<h2>The order, and a <code>return</code> value</h2> | |
| 82 | +<p>A <code>return e;</code> evaluates <code>e</code> before the deferred statements run, so the value is what it was at the return.</p> | |
| 83 | +<div class="file"><span>Order.raz</span></div><pre class="code"><code><span class="kw">module</span> Order; | |
| 84 | +<span class="kw">import</span> Out; | |
| 85 | + | |
| 86 | +<span class="kw">var</span> counter: <span class="ty">INT</span>; | |
| 87 | + | |
| 88 | +<span class="kw">proc</span> next(): <span class="ty">INT</span>; | |
| 89 | +<span class="kw">begin</span> | |
| 90 | + <span class="kw">defer</span> <span class="ty">INC</span>(counter); | |
| 91 | + <span class="kw">return</span> counter; <span class="comment">(* the old value is returned; then counter grows *)</span> | |
| 92 | +<span class="kw">end</span>; | |
| 93 | + | |
| 94 | +<span class="kw">proc</span> nest; | |
| 95 | +<span class="kw">begin</span> | |
| 96 | + <span class="kw">defer</span> Out.str(<span class="string">"1 "</span>); | |
| 97 | + <span class="kw">defer</span> Out.str(<span class="string">"2 "</span>); | |
| 98 | + <span class="kw">defer</span> Out.str(<span class="string">"3 "</span>); | |
| 99 | + Out.str(<span class="string">"body: "</span>); | |
| 100 | +<span class="kw">end</span>; | |
| 101 | + | |
| 102 | +<span class="kw">proc</span> main*; | |
| 103 | +<span class="kw">var</span> a, b: <span class="ty">INT</span>; | |
| 104 | +<span class="kw">begin</span> | |
| 105 | + a := next(); | |
| 106 | + b := next(); | |
| 107 | + Out.int(a); Out.char(<span class="string">' '</span>); Out.int(b); Out.char(<span class="string">' '</span>); Out.int(counter); Out.ln; | |
| 108 | + nest; | |
| 109 | + Out.ln; | |
| 110 | +<span class="kw">end</span>; | |
| 111 | + | |
| 112 | +<span class="kw">end</span> Order.</code></pre> | |
| 113 | +<pre class="output"><code>0 1 2 | |
| 114 | +body: 3 2 1 | |
| 115 | +</code></pre> | |
| 116 | +<h2>In a loop</h2> | |
| 117 | +<p>A <code>defer</code> stands in the statement list that holds it, so in a loop body it runs at the end of each pass, and on a <code>break</code>.</p> | |
| 118 | +<div class="file"><span>Passes.raz</span></div><pre class="code"><code><span class="kw">module</span> Passes; | |
| 119 | +<span class="kw">import</span> Out; | |
| 120 | + | |
| 121 | +<span class="kw">proc</span> main*; | |
| 122 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 123 | +<span class="kw">begin</span> | |
| 124 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">4</span> <span class="kw">do</span> | |
| 125 | + Out.str(<span class="string">"pass "</span>); Out.int(i); | |
| 126 | + <span class="kw">defer</span> Out.str(<span class="string">" done\n"</span>); | |
| 127 | + <span class="kw">if</span> i = <span class="number">3</span> <span class="kw">then</span> <span class="kw">break</span>; <span class="kw">end</span>; | |
| 128 | + Out.str(<span class="string">" ..."</span>); | |
| 129 | + <span class="kw">end</span>; | |
| 130 | +<span class="kw">end</span>; | |
| 131 | + | |
| 132 | +<span class="kw">end</span> Passes.</code></pre> | |
| 133 | +<pre class="output"><code>pass 1 ... done | |
| 134 | +pass 2 ... done | |
| 135 | +pass 3 done | |
| 136 | +</code></pre> | |
| 137 | +<h2>Giving back what was taken</h2> | |
| 138 | +<p>The point is that acquiring and releasing sit next to each other, so a new early <code>return</code> added later can't leak. Here an arena and a buffer are both released on every path.</p> | |
| 139 | +<div class="file"><span>Report.raz</span></div><pre class="code"><code><span class="kw">module</span> Report; | |
| 140 | +<span class="kw">import</span> Out, Buf, Heap; | |
| 141 | + | |
| 142 | +<span class="comment">(* a line, built in a buffer; false (nothing written) if n is negative *)</span> | |
| 143 | +<span class="kw">proc</span> line(n: <span class="ty">INT</span>): <span class="ty">BOOL</span>; | |
| 144 | +<span class="kw">var</span> b: Buf.Buf; | |
| 145 | +<span class="kw">begin</span> | |
| 146 | + <span class="kw">if</span> n < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">false</span>; <span class="kw">end</span>; | |
| 147 | + Buf.init(<span class="ty">ADR</span>(b), Heap.heap); | |
| 148 | + <span class="kw">defer</span> Buf.done(<span class="ty">ADR</span>(b)); <span class="comment">(* freed on every way out below *)</span> | |
| 149 | + Buf.str(<span class="ty">ADR</span>(b), <span class="string">"n is "</span>); | |
| 150 | + <span class="kw">if</span> n > <span class="number">9</span> <span class="kw">then</span> | |
| 151 | + Buf.str(<span class="ty">ADR</span>(b), <span class="string">"large"</span>); | |
| 152 | + Out.str(Buf.bytes(<span class="ty">ADR</span>(b))); Out.ln; | |
| 153 | + <span class="kw">return</span> <span class="ty">true</span>; | |
| 154 | + <span class="kw">end</span>; | |
| 155 | + Buf.str(<span class="ty">ADR</span>(b), <span class="string">"small"</span>); | |
| 156 | + Out.str(Buf.bytes(<span class="ty">ADR</span>(b))); Out.ln; | |
| 157 | + <span class="kw">return</span> <span class="ty">true</span>; | |
| 158 | +<span class="kw">end</span>; | |
| 159 | + | |
| 160 | +<span class="kw">proc</span> main*; | |
| 161 | +<span class="kw">begin</span> | |
| 162 | + _ := line(<span class="number">3</span>); | |
| 163 | + _ := line(<span class="number">30</span>); | |
| 164 | + <span class="kw">if</span> <span class="kw">not</span> line(-<span class="number">1</span>) <span class="kw">then</span> Out.str(<span class="string">"rejected\n"</span>); <span class="kw">end</span>; | |
| 165 | +<span class="kw">end</span>; | |
| 166 | + | |
| 167 | +<span class="kw">end</span> Report.</code></pre> | |
| 168 | +<pre class="output"><code>n is small | |
| 169 | +n is large | |
| 170 | +rejected | |
| 171 | +</code></pre> | |
| 172 | +<h2>What defer does not do</h2> | |
| 173 | +<p>A deferred statement can't contain a <code>return</code>, <code>break</code> or <code>defer</code> that would leave it. A failed check, <code>Rt.exit</code> and <code>Sys.exit</code> 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 <code>Rt.atExit</code> is for.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="errors.html">← Errors</a><a href="index.html">Contents</a><a class="next" href="checks.html">When it goes wrong →</a></div></article></div> | |
| 82 | 174 | </main> |
| 83 | 175 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 84 | 176 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -65,8 +65,129 @@ | ||
| 65 | 65 | empty |
| 66 | 66 | not a number up to 1000 |
| 67 | 67 | </code></pre> |
| 68 | -<p>A procedure that can fail returns an <code>ERROR</code> beside its result, and <code>nil</code> when it didn't. Each <code>ERROR</code> constant is an error of its own, compared with <code>=</code> by which declaration made it, never by its message; <code>MSG(err)</code> is the message.</p> | |
| 69 | -<p>An exported one, as <code>Empty</code> is here, lets the callers tell it from the others. raz has no exceptions.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="memory.html">← Memory and allocators</a><a href="index.html">Contents</a><a class="next" href="defer.html">Defer →</a></div></article></div> | |
| 68 | +<p>A procedure that can fail returns an <code>ERROR</code> beside its result, and <code>nil</code> when it didn't. Each <code>ERROR</code> constant is an error of its own, compared with <code>=</code> by which declaration made it, never by its message; <code>MSG(err)</code> is the message. An exported one, as <code>Empty</code> 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.</p> | |
| 69 | +<h2>Handling them by kind</h2> | |
| 70 | +<p>Because an error is compared by identity, a caller can handle the cases it knows and pass on the rest.</p> | |
| 71 | +<div class="file"><span>Parse.raz</span></div><pre class="code"><code><span class="kw">module</span> Parse; | |
| 72 | +<span class="kw">import</span> Out, Str; | |
| 73 | + | |
| 74 | +<span class="kw">const</span> | |
| 75 | + Empty*: <span class="ty">ERROR</span> = <span class="string">"nothing to read"</span>; | |
| 76 | + Bad*: <span class="ty">ERROR</span> = <span class="string">"not a number"</span>; | |
| 77 | + Range*: <span class="ty">ERROR</span> = <span class="string">"out of range"</span>; | |
| 78 | + | |
| 79 | +<span class="comment">(* a percentage, 0 to 100 *)</span> | |
| 80 | +<span class="kw">proc</span> percent(s: []<span class="ty">U8</span>): (<span class="ty">INT</span>, <span class="ty">ERROR</span>); | |
| 81 | +<span class="kw">var</span> n: <span class="ty">I64</span>; ok: <span class="ty">BOOL</span>; | |
| 82 | +<span class="kw">begin</span> | |
| 83 | + <span class="kw">if</span> <span class="ty">LEN</span>(s) = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Empty; <span class="kw">end</span>; | |
| 84 | + n, ok := Str.toInt(s); | |
| 85 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Bad; <span class="kw">end</span>; | |
| 86 | + <span class="kw">if</span> (n < <span class="number">0</span>) <span class="kw">or</span> (n > <span class="number">100</span>) <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Range; <span class="kw">end</span>; | |
| 87 | + <span class="kw">return</span> <span class="ty">INT</span>(n), <span class="ty">nil</span>; | |
| 88 | +<span class="kw">end</span>; | |
| 89 | + | |
| 90 | +<span class="kw">proc</span> main*; | |
| 91 | +<span class="kw">var</span> inputs: [<span class="number">4</span>][]<span class="ty">U8</span>; i, n: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 92 | +<span class="kw">begin</span> | |
| 93 | + inputs := [<span class="string">"42"</span>, <span class="string">""</span>, <span class="string">"forty"</span>, <span class="string">"140"</span>]; | |
| 94 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 95 | + n, err := percent(inputs[i]); | |
| 96 | + <span class="kw">if</span> err = <span class="ty">nil</span> <span class="kw">then</span> | |
| 97 | + Out.int(n); Out.str(<span class="string">"%"</span>); | |
| 98 | + <span class="kw">elsif</span> err = Empty <span class="kw">then</span> | |
| 99 | + Out.str(<span class="string">"(skipped)"</span>); | |
| 100 | + <span class="kw">else</span> | |
| 101 | + Out.str(<span class="string">"error: "</span>); Out.str(<span class="ty">MSG</span>(err)); | |
| 102 | + <span class="kw">end</span>; | |
| 103 | + Out.ln; | |
| 104 | + <span class="kw">end</span>; | |
| 105 | +<span class="kw">end</span>; | |
| 106 | + | |
| 107 | +<span class="kw">end</span> Parse.</code></pre> | |
| 108 | +<pre class="output"><code>42% | |
| 109 | +(skipped) | |
| 110 | +error: not a number | |
| 111 | +error: out of range | |
| 112 | +</code></pre> | |
| 113 | +<h2>Passing errors up</h2> | |
| 114 | +<p>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 <code>return</code> is right there.</p> | |
| 115 | +<div class="file"><span>Layers.raz</span></div><pre class="code"><code><span class="kw">module</span> Layers; | |
| 116 | +<span class="kw">import</span> Out, Str; | |
| 117 | + | |
| 118 | +<span class="kw">const</span> Missing*: <span class="ty">ERROR</span> = <span class="string">"key missing"</span>; | |
| 119 | + | |
| 120 | +<span class="comment">(* the number after "n=" in a line like "n=17" *)</span> | |
| 121 | +<span class="kw">proc</span> value(line: []<span class="ty">U8</span>): (<span class="ty">INT</span>, <span class="ty">ERROR</span>); | |
| 122 | +<span class="kw">var</span> n: <span class="ty">I64</span>; ok: <span class="ty">BOOL</span>; | |
| 123 | +<span class="kw">begin</span> | |
| 124 | + <span class="kw">if</span> <span class="kw">not</span> Str.hasPrefix(line, <span class="string">"n="</span>) <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Missing; <span class="kw">end</span>; | |
| 125 | + n, ok := Str.toInt(line[<span class="number">2</span>..<span class="ty">LEN</span>(line)]); | |
| 126 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Missing; <span class="kw">end</span>; | |
| 127 | + <span class="kw">return</span> <span class="ty">INT</span>(n), <span class="ty">nil</span>; | |
| 128 | +<span class="kw">end</span>; | |
| 129 | + | |
| 130 | +<span class="comment">(* the sum of the values of two lines *)</span> | |
| 131 | +<span class="kw">proc</span> sum(a, b: []<span class="ty">U8</span>): (<span class="ty">INT</span>, <span class="ty">ERROR</span>); | |
| 132 | +<span class="kw">var</span> x, y: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 133 | +<span class="kw">begin</span> | |
| 134 | + x, err := value(a); | |
| 135 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, err; <span class="kw">end</span>; <span class="comment">(* passed up *)</span> | |
| 136 | + y, err := value(b); | |
| 137 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, err; <span class="kw">end</span>; | |
| 138 | + <span class="kw">return</span> x + y, <span class="ty">nil</span>; | |
| 139 | +<span class="kw">end</span>; | |
| 140 | + | |
| 141 | +<span class="kw">proc</span> main*; | |
| 142 | +<span class="kw">var</span> n: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 143 | +<span class="kw">begin</span> | |
| 144 | + n, err := sum(<span class="string">"n=40"</span>, <span class="string">"n=2"</span>); | |
| 145 | + <span class="kw">if</span> err = <span class="ty">nil</span> <span class="kw">then</span> Out.int(n); Out.ln; <span class="kw">end</span>; | |
| 146 | + n, err := sum(<span class="string">"n=40"</span>, <span class="string">"x=2"</span>); | |
| 147 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"sum failed: "</span>); Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">end</span>; | |
| 148 | +<span class="kw">end</span>; | |
| 149 | + | |
| 150 | +<span class="kw">end</span> Layers.</code></pre> | |
| 151 | +<pre class="output"><code>42 | |
| 152 | +sum failed: key missing | |
| 153 | +</code></pre> | |
| 154 | +<h2>When the library reports errors</h2> | |
| 155 | +<p>Library procedures that can fail say so in the same way: <code>Thread.spawn</code> returns an <code>ERROR</code>; <code>Sys</code> calls return a negative <code>errno</code> as an <code>INT</code>, with <code>0</code> or a positive count for success; <code>Files.read</code> returns a <code>BOOL</code>. The first is the language's way; the others are the system's, left as they are.</p> | |
| 156 | +<div class="file"><span>Probe.raz</span></div><pre class="code"><code><span class="kw">module</span> Probe; | |
| 157 | +<span class="kw">import</span> Out, Sys; | |
| 158 | + | |
| 159 | +<span class="kw">proc</span> main*; | |
| 160 | +<span class="kw">var</span> fd: <span class="ty">INT</span>; | |
| 161 | +<span class="kw">begin</span> | |
| 162 | + fd := Sys.openRead(<span class="string">"/no/such/file"</span>); | |
| 163 | + <span class="kw">if</span> fd < <span class="number">0</span> <span class="kw">then</span> | |
| 164 | + Out.str(<span class="string">"open failed, errno "</span>); Out.int(-fd); Out.ln; <span class="comment">(* 2: ENOENT *)</span> | |
| 165 | + <span class="kw">end</span>; | |
| 166 | + fd := Sys.openRead(<span class="string">"/dev/null"</span>); | |
| 167 | + <span class="kw">if</span> fd >= <span class="number">0</span> <span class="kw">then</span> | |
| 168 | + Out.str(<span class="string">"open worked\n"</span>); | |
| 169 | + Sys.close(fd); | |
| 170 | + <span class="kw">end</span>; | |
| 171 | +<span class="kw">end</span>; | |
| 172 | + | |
| 173 | +<span class="kw">end</span> Probe.</code></pre> | |
| 174 | +<pre class="output"><code>open failed, errno 2 | |
| 175 | +open worked | |
| 176 | +</code></pre> | |
| 177 | +<h2>When there is nothing to do but stop</h2> | |
| 178 | +<p>A program that has found a state it can't carry on from, such as a broken invariant, says so and ends with <code>Rt.stop</code>: the message goes to standard error and the status is 2, the same as a failed check.</p> | |
| 179 | +<div class="file"><span>Giveup.raz</span></div><pre class="code"><code><span class="kw">module</span> Giveup; | |
| 180 | +<span class="kw">import</span> Rt; | |
| 181 | + | |
| 182 | +<span class="kw">proc</span> main*; | |
| 183 | +<span class="kw">begin</span> | |
| 184 | + Rt.stop(<span class="string">"the table is corrupt"</span>); | |
| 185 | +<span class="kw">end</span>; | |
| 186 | + | |
| 187 | +<span class="kw">end</span> Giveup.</code></pre> | |
| 188 | +<pre class="output term"><code><span class="cmd">$ raz run Giveup.raz; echo "status $?"</span> | |
| 189 | +the table is corrupt | |
| 190 | +status 2</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="memory.html">← Memory and allocators</a><a href="index.html">Contents</a><a class="next" href="defer.html">Defer →</a></div></article></div> | |
| 70 | 191 | </main> |
| 71 | 192 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 72 | 193 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -75,8 +75,89 @@ | ||
| 75 | 75 | tree |
| 76 | 76 | 1 1 3 4 5 |
| 77 | 77 | </code></pre> |
| 78 | -<p>Each import with its own arguments makes an instance: the module compiled again, with <code>T</code> standing for the type given, and <code>less</code> calling the procedure given. The arguments may name what the importing module declares later, as <code>before</code> is here.</p> | |
| 79 | -<p>The library's <code>List</code>, <code>Map</code> and <code>Sort</code> are generic modules: <code>import Count := Map([]U8, INT, Str.hash, Str.eq);</code></p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="checks.html">← When it goes wrong</a><a href="index.html">Contents</a><a class="next" href="c.html">Talking to C →</a></div></article></div> | |
| 78 | +<p>Each import with its own arguments makes an instance: the module compiled again, with <code>T</code> standing for the type given, and <code>less</code> calling the procedure given. The arguments may name what the importing module declares later, as <code>before</code> is here. There is no run-time cost for being generic, and no boxing: <code>Ints.max</code> is exactly the code you would write by hand for <code>INT</code>.</p> | |
| 79 | +<h2>Writing your own</h2> | |
| 80 | +<p>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.</p> | |
| 81 | +<div class="file"><span>Stk.raz</span></div><pre class="code"><code><span class="kw">module</span> Stk(T); | |
| 82 | +<span class="kw">import</span> Mem; | |
| 83 | + | |
| 84 | +<span class="kw">type</span> | |
| 85 | + Stack* = <span class="kw">record</span> | |
| 86 | + items: ^T; <span class="comment">(* an array of cap Ts *)</span> | |
| 87 | + cap*, len*: <span class="ty">INT</span>; | |
| 88 | + a: ^Mem.Allocator; | |
| 89 | + <span class="kw">end</span>; | |
| 90 | + | |
| 91 | +<span class="kw">proc</span> init*(s: ^Stack; a: ^Mem.Allocator); | |
| 92 | +<span class="kw">begin</span> | |
| 93 | + s^.a := a; | |
| 94 | + s^.items := <span class="ty">nil</span>; | |
| 95 | + s^.cap := <span class="number">0</span>; | |
| 96 | + s^.len := <span class="number">0</span>; | |
| 97 | +<span class="kw">end</span>; | |
| 98 | + | |
| 99 | +<span class="comment">(* v on top; false if the allocator has no room *)</span> | |
| 100 | +<span class="kw">proc</span> push*(s: ^Stack; v: T): <span class="ty">BOOL</span>; | |
| 101 | +<span class="kw">var</span> bigger: ^T; i, cap: <span class="ty">INT</span>; src, dst: ^T; | |
| 102 | +<span class="kw">begin</span> | |
| 103 | + <span class="kw">if</span> s^.len = s^.cap <span class="kw">then</span> | |
| 104 | + <span class="kw">if</span> s^.cap = <span class="number">0</span> <span class="kw">then</span> cap := <span class="number">4</span>; <span class="kw">else</span> cap := s^.cap * <span class="number">2</span>; <span class="kw">end</span>; | |
| 105 | + bigger := ^T(Mem.alloc(s^.a, cap * <span class="ty">SIZE</span>(T), <span class="number">8</span>)); | |
| 106 | + <span class="kw">if</span> bigger = <span class="ty">nil</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">false</span>; <span class="kw">end</span>; | |
| 107 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> s^.len - <span class="number">1</span> <span class="kw">do</span> | |
| 108 | + src := ^T(<span class="ty">INT</span>(s^.items) + i * <span class="ty">SIZE</span>(T)); | |
| 109 | + dst := ^T(<span class="ty">INT</span>(bigger) + i * <span class="ty">SIZE</span>(T)); | |
| 110 | + dst^ := src^; | |
| 111 | + <span class="kw">end</span>; | |
| 112 | + <span class="kw">if</span> s^.items # <span class="ty">nil</span> <span class="kw">then</span> Mem.free(s^.a, ^<span class="ty">U8</span>(s^.items)); <span class="kw">end</span>; | |
| 113 | + s^.items := bigger; | |
| 114 | + s^.cap := cap; | |
| 115 | + <span class="kw">end</span>; | |
| 116 | + dst := ^T(<span class="ty">INT</span>(s^.items) + s^.len * <span class="ty">SIZE</span>(T)); | |
| 117 | + dst^ := v; | |
| 118 | + <span class="ty">INC</span>(s^.len); | |
| 119 | + <span class="kw">return</span> <span class="ty">true</span>; | |
| 120 | +<span class="kw">end</span>; | |
| 121 | + | |
| 122 | +<span class="comment">(* the top value, taken off; false if empty *)</span> | |
| 123 | +<span class="kw">proc</span> pop*(s: ^Stack): (T, <span class="ty">BOOL</span>); | |
| 124 | +<span class="kw">var</span> z: T; p: ^T; | |
| 125 | +<span class="kw">begin</span> | |
| 126 | + <span class="kw">if</span> s^.len = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> z, <span class="ty">false</span>; <span class="kw">end</span>; | |
| 127 | + <span class="ty">DEC</span>(s^.len); | |
| 128 | + p := ^T(<span class="ty">INT</span>(s^.items) + s^.len * <span class="ty">SIZE</span>(T)); | |
| 129 | + <span class="kw">return</span> p^, <span class="ty">true</span>; | |
| 130 | +<span class="kw">end</span>; | |
| 131 | + | |
| 132 | +<span class="kw">end</span> Stk.</code></pre> | |
| 133 | +<div class="file"><span>Uses.raz</span></div><pre class="code"><code><span class="kw">module</span> Uses; | |
| 134 | +<span class="kw">import</span> Out, Heap, Nums := Stk(<span class="ty">INT</span>), Pairs := Stk(Pair); | |
| 135 | + | |
| 136 | +<span class="kw">type</span> Pair = <span class="kw">record</span> a, b: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 137 | + | |
| 138 | +<span class="kw">proc</span> main*; | |
| 139 | +<span class="kw">var</span> n: Nums.Stack; p: Pairs.Stack; i, v: <span class="ty">INT</span>; ok: <span class="ty">BOOL</span>; pr: Pair; | |
| 140 | +<span class="kw">begin</span> | |
| 141 | + Nums.init(<span class="ty">ADR</span>(n), Heap.heap); | |
| 142 | + Pairs.init(<span class="ty">ADR</span>(p), Heap.heap); | |
| 143 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">10</span> <span class="kw">do</span> _ := Nums.push(<span class="ty">ADR</span>(n), i * i); <span class="kw">end</span>; | |
| 144 | + _ := Pairs.push(<span class="ty">ADR</span>(p), {a: <span class="number">3</span>, b: <span class="number">4</span>}); | |
| 145 | + v, ok := Nums.pop(<span class="ty">ADR</span>(n)); | |
| 146 | + Out.int(v); Out.str(<span class="string">" of "</span>); Out.int(n.len + <span class="number">1</span>); Out.ln; | |
| 147 | + pr, ok := Pairs.pop(<span class="ty">ADR</span>(p)); | |
| 148 | + Out.int(pr.a * pr.b); Out.ln; | |
| 149 | + _, ok := Pairs.pop(<span class="ty">ADR</span>(p)); | |
| 150 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Out.str(<span class="string">"empty\n"</span>); <span class="kw">end</span>; | |
| 151 | +<span class="kw">end</span>; | |
| 152 | + | |
| 153 | +<span class="kw">end</span> Uses.</code></pre> | |
| 154 | +<pre class="output"><code>100 of 10 | |
| 155 | +12 | |
| 156 | +empty | |
| 157 | +</code></pre> | |
| 158 | +<p>Two instances (<code>Nums</code> and <code>Pairs</code>) are two separate modules, compiled with their own <code>T</code>. 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.</p> | |
| 159 | +<h2>The library's generics</h2> | |
| 160 | +<p>The library's <code>List</code>, <code>Map</code> and <code>Sort</code> are generic modules. A <code>Map</code> takes its key hash and equality as procedure arguments: <code>import Count := Map([]U8, INT, Str.hash, Str.eq);</code>. The advanced tour uses each of them in a real program.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="checks.html">← When it goes wrong</a><a href="index.html">Contents</a><a class="next" href="c.html">Talking to C →</a></div></article></div> | |
| 80 | 161 | </main> |
| 81 | 162 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 82 | 163 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html" aria-current="page">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -41,9 +41,94 @@ | ||
| 41 | 41 | <span class="kw">end</span> Hello.</code></pre> |
| 42 | 42 | <pre class="output"><code>hello, world |
| 43 | 43 | </code></pre> |
| 44 | -<p>A module lives in a file of its own name, <code>Hello.raz</code>, and its name comes again after its last <code>end</code>. <code>import Out</code> lets it use what the module <code>Out</code> exports, as <code>Out.str</code>.</p> | |
| 45 | -<p>The <code>*</code> after <code>main</code> exports it; the program starts at the <code>main</code> of the module named on the command line. Every statement ends in <code>;</code>, even one that ends in <code>end</code>.</p> | |
| 46 | -<p>Compile it and run it with <code>raz Hello.raz && ./Hello</code>, or with <code>raz run Hello.raz</code>, which writes no file.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="index.html">Contents</a><a class="next" href="modules.html">Modules →</a></div></article></div> | |
| 44 | +<p>A module lives in a file of its own name, <code>Hello.raz</code>, and its name comes again after its last <code>end</code>, so a stray <code>end</code> is caught early. <code>import Out</code> lets it use what the module <code>Out</code> exports, as <code>Out.str</code>. The <code>*</code> after <code>main</code> exports it; the program starts at the <code>main</code> of the module named on the command line. Every statement ends in <code>;</code>, even one that ends in <code>end</code>.</p> | |
| 45 | +<h2>Compiling and running</h2> | |
| 46 | +<p><code>raz Hello.raz</code> compiles the module and everything it imports, and writes the executable <code>Hello</code> beside it. <code>raz run</code> does the same without writing a file, and runs it at once.</p> | |
| 47 | +<div class="file"><span>Quiet.raz</span></div><pre class="code"><code><span class="comment">(* The same program, with a comment: (* ... *)</span> nests, <span class="kw">and</span> may stand anywhere. *) | |
| 48 | +<span class="kw">module</span> Quiet; | |
| 49 | +<span class="kw">import</span> Out; | |
| 50 | + | |
| 51 | +<span class="kw">proc</span> main*; | |
| 52 | +<span class="kw">begin</span> | |
| 53 | + Out.str(<span class="string">"hello, again\n"</span>); | |
| 54 | +<span class="kw">end</span>; | |
| 55 | + | |
| 56 | +<span class="kw">end</span> Quiet.</code></pre> | |
| 57 | +<pre class="output term"><code><span class="cmd">$ raz Quiet.raz</span> | |
| 58 | +<span class="cmd">$ ./Quiet</span> | |
| 59 | +hello, again | |
| 60 | +<span class="cmd">$ raz run Quiet.raz</span> | |
| 61 | +hello, again | |
| 62 | +<span class="cmd">$ ls -l Quiet | awk '{print $5, "bytes"}'</span> | |
| 63 | +28480 bytes</code></pre> | |
| 64 | +<p>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.</p> | |
| 65 | +<h2>What <code>Out</code> can write</h2> | |
| 66 | +<p><code>Out</code> 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 <code>\n</code> for a line feed, <code>\t</code> for a tab, <code>\"</code> and <code>\\</code>.</p> | |
| 67 | +<div class="file"><span>Numbers.raz</span></div><pre class="code"><code><span class="kw">module</span> Numbers; | |
| 68 | +<span class="kw">import</span> Out; | |
| 69 | + | |
| 70 | +<span class="kw">proc</span> main*; | |
| 71 | +<span class="kw">begin</span> | |
| 72 | + Out.str(<span class="string">"seven is "</span>); Out.int(<span class="number">7</span>); Out.ln; | |
| 73 | + Out.str(<span class="string">"minus one is "</span>); Out.int(-<span class="number">1</span>); Out.ln; | |
| 74 | + Out.str(<span class="string">"255 is 0x"</span>); Out.hex(<span class="number">255</span>, <span class="number">4</span>); Out.ln; | |
| 75 | + Out.char(<span class="string">'R'</span>); Out.char(<span class="string">'a'</span>); Out.char(<span class="string">'z'</span>); Out.ln; | |
| 76 | + Out.str(<span class="string">"a tab:\t|\n"</span>); | |
| 77 | +<span class="kw">end</span>; | |
| 78 | + | |
| 79 | +<span class="kw">end</span> Numbers.</code></pre> | |
| 80 | +<pre class="output"><code>seven is 7 | |
| 81 | +minus one is -1 | |
| 82 | +255 is 0x00FF | |
| 83 | +Raz | |
| 84 | +a tab: | | |
| 85 | +</code></pre> | |
| 86 | +<p><code>Out.hex(n, 4)</code> writes at least four digits. <code>Out.int</code> takes an <code>I64</code> and <code>Out.hex</code> a <code>U64</code>. An <code>INT</code> goes into an <code>I64</code> as it is; any other integer is converted where it is written, as <code>Out.int(I64(b))</code>, because raz never converts a number unasked.</p> | |
| 87 | +<h2>Ending, and the status</h2> | |
| 88 | +<p><code>main</code> may return an <code>INT</code>, which is the program's exit status; a plain <code>proc main*;</code> ends with 0. A shell sees the status as <code>$?</code>.</p> | |
| 89 | +<div class="file"><span>Status.raz</span></div><pre class="code"><code><span class="kw">module</span> Status; | |
| 90 | +<span class="kw">import</span> Out; | |
| 91 | + | |
| 92 | +<span class="kw">proc</span> main*: <span class="ty">INT</span>; | |
| 93 | +<span class="kw">begin</span> | |
| 94 | + Out.str(<span class="string">"exiting with 3\n"</span>); | |
| 95 | + <span class="kw">return</span> <span class="number">3</span>; | |
| 96 | +<span class="kw">end</span>; | |
| 97 | + | |
| 98 | +<span class="kw">end</span> Status.</code></pre> | |
| 99 | +<pre class="output term"><code><span class="cmd">$ raz run Status.raz; echo "status $?"</span> | |
| 100 | +exiting with 3 | |
| 101 | +status 3</code></pre> | |
| 102 | +<h2>Arguments</h2> | |
| 103 | +<p><code>ARGC()</code> is the number of command line arguments, with the program's own name first, and <code>ARGV()</code> the arguments, as C strings. Most programs read them through <code>Files.arg</code> and <code>Opt</code>, which the advanced tour shows; here is the raw form.</p> | |
| 104 | +<div class="file"><span>Args.raz</span></div><pre class="code"><code><span class="kw">module</span> Args; | |
| 105 | +<span class="kw">import</span> Out; | |
| 106 | + | |
| 107 | +<span class="comment">(* The length of a C string. *)</span> | |
| 108 | +<span class="kw">proc</span> len(s: ^<span class="ty">U8</span>): <span class="ty">INT</span>; | |
| 109 | +<span class="kw">var</span> n: <span class="ty">INT</span>; | |
| 110 | +<span class="kw">begin</span> | |
| 111 | + n := <span class="number">0</span>; | |
| 112 | + <span class="kw">while</span> s[n] # <span class="number">0</span> <span class="kw">do</span> n := n + <span class="number">1</span>; <span class="kw">end</span>; | |
| 113 | + <span class="kw">return</span> n; | |
| 114 | +<span class="kw">end</span>; | |
| 115 | + | |
| 116 | +<span class="kw">proc</span> main*: <span class="ty">INT</span>; | |
| 117 | +<span class="kw">var</span> i: <span class="ty">INT</span>; s: ^<span class="ty">U8</span>; | |
| 118 | +<span class="kw">begin</span> | |
| 119 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> ARGC() - <span class="number">1</span> <span class="kw">do</span> | |
| 120 | + s := ARGV()[i]; | |
| 121 | + Out.str(s[<span class="number">0</span>..len(s)]); | |
| 122 | + Out.ln; | |
| 123 | + <span class="kw">end</span>; | |
| 124 | + <span class="kw">return</span> ARGC() - <span class="number">1</span>; | |
| 125 | +<span class="kw">end</span>; | |
| 126 | + | |
| 127 | +<span class="kw">end</span> Args.</code></pre> | |
| 128 | +<pre class="output term"><code><span class="cmd">$ raz run Args.raz one "two words"; echo "status $?"</span> | |
| 129 | +one | |
| 130 | +two words | |
| 131 | +status 2</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="index.html">Contents</a><a class="next" href="modules.html">Modules →</a></div></article></div> | |
| 47 | 132 | </main> |
| 48 | 133 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 49 | 134 | </body> |
| @@ -3,11 +3,11 @@ | ||
| 3 | 3 | <head> |
| 4 | 4 | <meta charset="utf-8"> |
| 5 | 5 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 6 | -<title>Raz, Set, Go: a tour of raz</title> | |
| 6 | +<title>Raz, Set, Go</title> | |
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | 12 | <div class="contents"><h1>Raz, Set, Go</h1> |
| 13 | 13 | <p>A tour of raz, in the spirit of <em>A Tour of Go</em>. Each lesson is one |
| @@ -17,26 +17,26 @@ | ||
| 17 | 17 | first steps; <strong>Set</strong>, how data is laid out; and |
| 18 | 18 | <strong>Go</strong>, making programs that run, fail and finish well. To follow |
| 19 | 19 | along, <a href="../index.html#download">get raz</a> and run any program with |
| 20 | -<code>raz run Name.raz</code>.</p> | |
| 20 | +<code>raz run Name.raz</code>. When you finish, <a href="../advanced/index.html">Beyond Go</a> goes down to the machine.</p> | |
| 21 | 21 | <h2>Raz</h2><ol start='1'> |
| 22 | -<li><a href="hello.html">Hello, world</a> <span>A module, an import and a procedure.</span></li> | |
| 23 | -<li><a href="modules.html">Modules</a> <span>Exports, renaming, and a body that runs first.</span></li> | |
| 24 | -<li><a href="values.html">Values and conversions</a> <span>Sized integers that wrap, and nothing converts unasked.</span></li> | |
| 25 | -<li><a href="procedures.html">Procedures and several results</a> <span>Return two values, change a variable, pass a procedure.</span></li> | |
| 22 | +<li><a href="hello.html">Hello, world</a> <span>A module, an import, a procedure; running, printing, exit status and arguments.</span></li> | |
| 23 | +<li><a href="modules.html">Modules</a> <span>Exports, renaming, the order bodies run in, and what the compiler refuses.</span></li> | |
| 24 | +<li><a href="values.html">Values and conversions</a> <span>Sized integers that wrap, reals, bits, and nothing converts unasked.</span></li> | |
| 25 | +<li><a href="procedures.html">Procedures and several results</a> <span>Value and var parameters, several results, forward, and procedures as values.</span></li> | |
| 26 | 26 | </ol> |
| 27 | 27 | <h2>Set</h2><ol start='5'> |
| 28 | -<li><a href="slices.html">Arrays, slices and strings</a> <span>Five in a row, a window onto them, and bytes in UTF-8.</span></li> | |
| 29 | -<li><a href="records.html">Records and pointers</a> <span>Laid out as C lays out a struct, reached through ^.</span></li> | |
| 30 | -<li><a href="variants.html">Enumerations, sets, variants and match</a> <span>Choices the compiler can check you handled.</span></li> | |
| 31 | -<li><a href="memory.html">Memory and allocators</a> <span>No garbage collector; you choose where memory comes from.</span></li> | |
| 28 | +<li><a href="slices.html">Arrays, slices and strings</a> <span>Five in a row, a window onto them, bytes in UTF-8, and checks on every index.</span></li> | |
| 29 | +<li><a href="records.html">Records and pointers</a> <span>Laid out as C lays out a struct, packed records, pointers and nil.</span></li> | |
| 30 | +<li><a href="variants.html">Enumerations, sets, variants and match</a> <span>Names in order, sets as bits, and cases the compiler makes you handle.</span></li> | |
| 31 | +<li><a href="memory.html">Memory and allocators</a> <span>No garbage collector; you choose where memory comes from, and what happens when it runs out.</span></li> | |
| 32 | 32 | </ol> |
| 33 | 33 | <h2>Go</h2><ol start='9'> |
| 34 | -<li><a href="errors.html">Errors</a> <span>A second result, compared by identity. No exceptions.</span></li> | |
| 35 | -<li><a href="defer.html">Defer</a> <span>Clean up beside the line that needs it.</span></li> | |
| 36 | -<li><a href="checks.html">When it goes wrong</a> <span>Every index is checked, and a failure tells you everything.</span></li> | |
| 37 | -<li><a href="generics.html">Generic modules</a> <span>A module that takes types and procedures as arguments.</span></li> | |
| 38 | -<li><a href="c.html">Talking to C</a> <span>Call a C library, and be called back.</span></li> | |
| 39 | -<li><a href="threads.html">Threads</a> <span>Native threads, atomics and a mutex.</span></li> | |
| 34 | +<li><a href="errors.html">Errors</a> <span>A second result, compared by identity; passing errors up; and no exceptions.</span></li> | |
| 35 | +<li><a href="defer.html">Defer</a> <span>Clean up beside the line that needs it, in the right order, on every way out.</span></li> | |
| 36 | +<li><a href="checks.html">When it goes wrong</a> <span>Every index is checked, a failure says where and with what values, and how to read it.</span></li> | |
| 37 | +<li><a href="generics.html">Generic modules</a> <span>A module that takes types and procedures; the library's List, Map and Sort.</span></li> | |
| 38 | +<li><a href="c.html">Talking to C</a> <span>Call a C library, be called back, share variables, and mind the two buffers.</span></li> | |
| 39 | +<li><a href="threads.html">Threads</a> <span>Native threads without C, atomics, a mutex, and why the counter needs both.</span></li> | |
| 40 | 40 | </ol></div> |
| 41 | 41 | </main> |
| 42 | 42 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -68,9 +68,109 @@ | ||
| 68 | 68 | <pre class="output"><code>3 2 1 |
| 69 | 69 | 1000 |
| 70 | 70 | </code></pre> |
| 71 | -<p>raz has no garbage collector, and no allocator of its own: memory comes from an allocator, a <code>Mem.Allocator</code>, which the program chooses and passes.</p> | |
| 72 | -<p><code>NEW(n, a)</code> sets <code>n</code> to a fresh, zeroed <code>Node</code> from <code>a</code>, or to <code>nil</code> if <code>a</code> has no room. <code>Heap.heap</code> is the general one, which <code>Mem.free</code> gives memory back to. An <code>Arena</code> hands out memory from one block and frees it all at once, as the last lines do.</p> | |
| 73 | -<p><code>Buf</code>, <code>List</code> and <code>Map</code> take the allocator they use from <code>init</code>.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="variants.html">← Enumerations, sets, variants and match</a><a href="index.html">Contents</a><a class="next" href="errors.html">Errors →</a></div></article></div> | |
| 71 | +<p>raz has no garbage collector, and no allocator of its own: memory comes from an allocator, a <code>Mem.Allocator</code>, which the program chooses and passes. <code>NEW(n, a)</code> sets <code>n</code> to a fresh, zeroed <code>Node</code> from <code>a</code>, or to <code>nil</code> if <code>a</code> has no room. <code>Heap.heap</code> is the general one, which <code>Mem.free</code> gives memory back to. An <code>Arena</code> hands out memory from one block and frees it all at once, as the last lines above do.</p> | |
| 72 | +<h2>Why an allocator is a parameter</h2> | |
| 73 | +<p>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.</p> | |
| 74 | +<div class="file"><span>Pool.raz</span></div><pre class="code"><code><span class="kw">module</span> Pool; | |
| 75 | +<span class="kw">import</span> Out, Mem, Arena; | |
| 76 | + | |
| 77 | +<span class="kw">type</span> Item = <span class="kw">record</span> id: <span class="ty">INT</span>; next: ^Item; <span class="kw">end</span>; | |
| 78 | + | |
| 79 | +<span class="comment">(* n items, linked; or nil if the allocator ran dry (what came is lost with it) *)</span> | |
| 80 | +<span class="kw">proc</span> make(n: <span class="ty">INT</span>; a: ^Mem.Allocator): ^Item; | |
| 81 | +<span class="kw">var</span> head, it: ^Item; i: <span class="ty">INT</span>; | |
| 82 | +<span class="kw">begin</span> | |
| 83 | + head := <span class="ty">nil</span>; | |
| 84 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> n <span class="kw">do</span> | |
| 85 | + <span class="ty">NEW</span>(it, a); | |
| 86 | + <span class="kw">if</span> it = <span class="ty">nil</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">nil</span>; <span class="kw">end</span>; | |
| 87 | + it^.id := i; | |
| 88 | + it^.next := head; | |
| 89 | + head := it; | |
| 90 | + <span class="kw">end</span>; | |
| 91 | + <span class="kw">return</span> head; | |
| 92 | +<span class="kw">end</span>; | |
| 93 | + | |
| 94 | +<span class="kw">proc</span> count(it: ^Item): <span class="ty">INT</span>; | |
| 95 | +<span class="kw">var</span> n: <span class="ty">INT</span>; | |
| 96 | +<span class="kw">begin</span> | |
| 97 | + n := <span class="number">0</span>; | |
| 98 | + <span class="kw">while</span> it # <span class="ty">nil</span> <span class="kw">do</span> <span class="ty">INC</span>(n); it := it^.next; <span class="kw">end</span>; | |
| 99 | + <span class="kw">return</span> n; | |
| 100 | +<span class="kw">end</span>; | |
| 101 | + | |
| 102 | +<span class="kw">proc</span> main*; | |
| 103 | +<span class="kw">var</span> ar: Arena.Arena; small: Arena.Arena; list: ^Item; | |
| 104 | +<span class="kw">begin</span> | |
| 105 | + <span class="kw">if</span> <span class="kw">not</span> Arena.init(<span class="ty">ADR</span>(ar), <span class="number">1000000</span>) <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 106 | + list := make(<span class="number">1000</span>, <span class="ty">ADR</span>(ar.base)); | |
| 107 | + Out.int(count(list)); Out.str(<span class="string">" items from a big arena\n"</span>); | |
| 108 | + Arena.reset(<span class="ty">ADR</span>(ar)); <span class="comment">(* every allocation forgotten *)</span> | |
| 109 | + list := make(<span class="number">10</span>, <span class="ty">ADR</span>(ar.base)); | |
| 110 | + Out.int(count(list)); Out.str(<span class="string">" after a reset\n"</span>); | |
| 111 | + Arena.done(<span class="ty">ADR</span>(ar)); | |
| 112 | + | |
| 113 | + <span class="kw">if</span> <span class="kw">not</span> Arena.init(<span class="ty">ADR</span>(small), <span class="number">4096</span>) <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 114 | + list := make(<span class="number">1000</span>, <span class="ty">ADR</span>(small.base)); | |
| 115 | + <span class="kw">if</span> list = <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"a small arena ran out, and said so\n"</span>); <span class="kw">end</span>; | |
| 116 | + Arena.done(<span class="ty">ADR</span>(small)); | |
| 117 | +<span class="kw">end</span>; | |
| 118 | + | |
| 119 | +<span class="kw">end</span> Pool.</code></pre> | |
| 120 | +<pre class="output"><code>1000 items from a big arena | |
| 121 | +10 after a reset | |
| 122 | +a small arena ran out, and said so | |
| 123 | +</code></pre> | |
| 124 | +<p>The run-out case is an ordinary <code>nil</code> to test, not an exception that unwinds past your code.</p> | |
| 125 | +<h2>The heap</h2> | |
| 126 | +<p><code>Heap.heap</code> serves any size and takes memory back with <code>Mem.free</code>. 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.</p> | |
| 127 | +<div class="file"><span>Free.raz</span></div><pre class="code"><code><span class="kw">module</span> Free; | |
| 128 | +<span class="kw">import</span> Out, Mem, Heap; | |
| 129 | + | |
| 130 | +<span class="kw">type</span> Cell = <span class="kw">record</span> val: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 131 | + | |
| 132 | +<span class="kw">proc</span> main*; | |
| 133 | +<span class="kw">var</span> a, b: ^Cell; i, total: <span class="ty">INT</span>; | |
| 134 | +<span class="kw">begin</span> | |
| 135 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> | |
| 136 | + <span class="ty">NEW</span>(a, Heap.heap); | |
| 137 | + a^.val := i * i; | |
| 138 | + total := total + a^.val; | |
| 139 | + Mem.free(Heap.heap, ^<span class="ty">U8</span>(a)); <span class="comment">(* freed at once: its block is reused *)</span> | |
| 140 | + <span class="kw">end</span>; | |
| 141 | + <span class="ty">NEW</span>(b, Heap.heap); | |
| 142 | + Out.int(total); Out.char(<span class="string">' '</span>); Out.int(b^.val); Out.ln; <span class="comment">(* a new block is zeroed *)</span> | |
| 143 | + Mem.free(Heap.heap, ^<span class="ty">U8</span>(b)); | |
| 144 | +<span class="kw">end</span>; | |
| 145 | + | |
| 146 | +<span class="kw">end</span> Free.</code></pre> | |
| 147 | +<pre class="output"><code>55 0 | |
| 148 | +</code></pre> | |
| 149 | +<h2>Buffers that grow</h2> | |
| 150 | +<p><code>Buf</code> 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.</p> | |
| 151 | +<div class="file"><span>Build.raz</span></div><pre class="code"><code><span class="kw">module</span> Build; | |
| 152 | +<span class="kw">import</span> Out, Buf, Heap; | |
| 153 | + | |
| 154 | +<span class="kw">proc</span> main*; | |
| 155 | +<span class="kw">var</span> b: Buf.Buf; i: <span class="ty">INT</span>; | |
| 156 | +<span class="kw">begin</span> | |
| 157 | + Buf.init(<span class="ty">ADR</span>(b), Heap.heap); | |
| 158 | + <span class="kw">defer</span> Buf.done(<span class="ty">ADR</span>(b)); | |
| 159 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> | |
| 160 | + Buf.str(<span class="ty">ADR</span>(b), <span class="string">"item "</span>); | |
| 161 | + Buf.add(<span class="ty">ADR</span>(b), <span class="ty">U8</span>(<span class="string">'0'</span> + i)); | |
| 162 | + Buf.add(<span class="ty">ADR</span>(b), <span class="string">','</span>); | |
| 163 | + <span class="kw">end</span>; | |
| 164 | + Out.str(Buf.bytes(<span class="ty">ADR</span>(b))); Out.ln; | |
| 165 | + Out.int(b.len); Out.str(<span class="string">" bytes\n"</span>); | |
| 166 | +<span class="kw">end</span>; | |
| 167 | + | |
| 168 | +<span class="kw">end</span> Build.</code></pre> | |
| 169 | +<pre class="output"><code>item 1,item 2,item 3,item 4,item 5, | |
| 170 | +35 bytes | |
| 171 | +</code></pre> | |
| 172 | +<h2>Pages</h2> | |
| 173 | +<p>Under the allocators are pages from the system: <code>Mem.pages(size)</code> gives zeroed memory in whole pages, or <code>nil</code>, and <code>Mem.unmap</code> gives it back. Most programs never need to call it directly.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="variants.html">← Enumerations, sets, variants and match</a><a href="index.html">Contents</a><a class="next" href="errors.html">Errors →</a></div></article></div> | |
| 74 | 174 | </main> |
| 75 | 175 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 76 | 176 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html" aria-current="page">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -29,7 +29,7 @@ | ||
| 29 | 29 | <li><a href="c.html">Talking to C</a></li> |
| 30 | 30 | <li><a href="threads.html">Threads</a></li> |
| 31 | 31 | </ol></aside><article><p class="kicker">Raz · lesson 2 of 14</p><h1>Modules</h1> |
| 32 | -<p>A program is a set of modules. Here is one, saved as <code>Greet.raz</code>:</p> | |
| 32 | +<p>A program is a set of modules, one to a file, and a module's interface is everything it marks with <code>*</code>. Everything else is private to it. Here is one, saved as <code>Greet.raz</code>:</p> | |
| 33 | 33 | <div class="file"><span>Greet.raz</span></div><pre class="code"><code><span class="kw">module</span> Greet; |
| 34 | 34 | <span class="kw">import</span> Out; |
| 35 | 35 | |
| @@ -64,8 +64,125 @@ | ||
| 64 | 64 | hello, raz |
| 65 | 65 | 2 greetings |
| 66 | 66 | </code></pre> |
| 67 | -<p>A name with <code>*</code> is exported; any other is the module's own. <code>G := Greet</code> imports <code>Greet</code> under a shorter name. Another module may read <code>G.count</code>, but only <code>Greet</code> may change it.</p> | |
| 68 | -<p>The statements after a module's last <code>begin</code> are its body. It runs once, before <code>main</code>, which is why "Greet is ready" comes first.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="hello.html">← Hello, world</a><a href="index.html">Contents</a><a class="next" href="values.html">Values and conversions →</a></div></article></div> | |
| 67 | +<p>A name with <code>*</code> is exported; any other is the module's own. <code>G := Greet</code> imports <code>Greet</code> under a shorter name, so its exports are <code>G.hello</code> and <code>G.count</code>. Another module may read <code>G.count</code>, but only <code>Greet</code> may change it.</p> | |
| 68 | +<h2>Where modules are found</h2> | |
| 69 | +<p>The compiler looks for <code>Greet.raz</code> in the main module's directory, then in each directory given with <code>-I</code>, then in the library. So a project is a directory of modules, and <code>raz Main.raz</code> finds all of them. The library's own names (<code>Out</code>, <code>Str</code>, <code>Map</code>, ...) are kept for it.</p> | |
| 70 | +<h2>Bodies run first, in order</h2> | |
| 71 | +<p>The statements after a module's last <code>begin</code> are its body. It runs once, before <code>main</code>, after the bodies of the modules it imports, and once however many modules import it. This is how a module sets itself up: no <code>init</code> call to forget.</p> | |
| 72 | +<div class="file"><span>Base.raz</span></div><pre class="code"><code><span class="kw">module</span> Base; | |
| 73 | +<span class="kw">import</span> Out; | |
| 74 | + | |
| 75 | +<span class="kw">var</span> ready*: <span class="ty">BOOL</span>; | |
| 76 | + | |
| 77 | +<span class="kw">begin</span> | |
| 78 | + Out.str(<span class="string">"Base starts\n"</span>); | |
| 79 | + ready := <span class="ty">true</span>; | |
| 80 | +<span class="kw">end</span> Base.</code></pre> | |
| 81 | +<div class="file"><span>Layer.raz</span></div><pre class="code"><code><span class="kw">module</span> Layer; | |
| 82 | +<span class="kw">import</span> Out, Base; | |
| 83 | + | |
| 84 | +<span class="kw">const</span> Name* = <span class="string">"Layer"</span>; | |
| 85 | + | |
| 86 | +<span class="kw">begin</span> | |
| 87 | + Out.str(<span class="string">"Layer starts, Base is ready: "</span>); | |
| 88 | + <span class="kw">if</span> Base.ready <span class="kw">then</span> Out.str(<span class="string">"yes\n"</span>); <span class="kw">else</span> Out.str(<span class="string">"no\n"</span>); <span class="kw">end</span>; | |
| 89 | +<span class="kw">end</span> Layer.</code></pre> | |
| 90 | +<div class="file"><span>Order.raz</span></div><pre class="code"><code><span class="kw">module</span> Order; | |
| 91 | +<span class="kw">import</span> Out, Layer, Base; | |
| 92 | + | |
| 93 | +<span class="kw">proc</span> main*; | |
| 94 | +<span class="kw">begin</span> | |
| 95 | + Out.str(<span class="string">"main, after "</span>); Out.str(Layer.Name); Out.char(<span class="string">' '</span>); | |
| 96 | + <span class="kw">if</span> Base.ready <span class="kw">then</span> Out.str(<span class="string">"and Base\n"</span>); <span class="kw">end</span>; | |
| 97 | +<span class="kw">end</span>; | |
| 98 | + | |
| 99 | +<span class="kw">end</span> Order.</code></pre> | |
| 100 | +<pre class="output"><code>Base starts | |
| 101 | +Layer starts, Base is ready: yes | |
| 102 | +main, after Layer and Base | |
| 103 | +</code></pre> | |
| 104 | +<p><code>Base</code> is imported twice, but starts once, before <code>Layer</code>, which needs it. A module with no body doesn't need a <code>begin</code> at all.</p> | |
| 105 | +<h2>Exporting more than procedures</h2> | |
| 106 | +<p>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.</p> | |
| 107 | +<div class="file"><span>Shape.raz</span></div><pre class="code"><code><span class="kw">module</span> Shape; | |
| 108 | + | |
| 109 | +<span class="kw">const</span> Sides* = <span class="number">4</span>; | |
| 110 | + | |
| 111 | +<span class="kw">type</span> | |
| 112 | + Square* = <span class="kw">record</span> | |
| 113 | + side*: <span class="ty">INT</span>; <span class="comment">(* exported: a user may set it *)</span> | |
| 114 | + id: <span class="ty">INT</span>; <span class="comment">(* the module's own *)</span> | |
| 115 | + <span class="kw">end</span>; | |
| 116 | + | |
| 117 | +<span class="kw">var</span> made: <span class="ty">INT</span>; <span class="comment">(* only Shape may read or write it *)</span> | |
| 118 | + | |
| 119 | +<span class="comment">(* a square of that side, numbered in the order they are made *)</span> | |
| 120 | +<span class="kw">proc</span> make*(side: <span class="ty">INT</span>): Square; | |
| 121 | +<span class="kw">var</span> s: Square; | |
| 122 | +<span class="kw">begin</span> | |
| 123 | + <span class="ty">INC</span>(made); | |
| 124 | + s.side := side; | |
| 125 | + s.id := made; | |
| 126 | + <span class="kw">return</span> s; | |
| 127 | +<span class="kw">end</span>; | |
| 128 | + | |
| 129 | +<span class="kw">proc</span> area*(s: Square): <span class="ty">INT</span>; | |
| 130 | +<span class="kw">begin</span> | |
| 131 | + <span class="kw">return</span> s.side * s.side; | |
| 132 | +<span class="kw">end</span>; | |
| 133 | + | |
| 134 | +<span class="kw">proc</span> count*: <span class="ty">INT</span>; | |
| 135 | +<span class="kw">begin</span> | |
| 136 | + <span class="kw">return</span> made; | |
| 137 | +<span class="kw">end</span>; | |
| 138 | + | |
| 139 | +<span class="kw">end</span> Shape.</code></pre> | |
| 140 | +<div class="file"><span>Squares.raz</span></div><pre class="code"><code><span class="kw">module</span> Squares; | |
| 141 | +<span class="kw">import</span> Out, Shape; | |
| 142 | + | |
| 143 | +<span class="kw">proc</span> main*; | |
| 144 | +<span class="kw">var</span> a, b: Shape.Square; | |
| 145 | +<span class="kw">begin</span> | |
| 146 | + a := Shape.make(<span class="number">3</span>); | |
| 147 | + b := Shape.make(<span class="number">5</span>); | |
| 148 | + Out.int(Shape.area(a) + Shape.area(b)); Out.ln; | |
| 149 | + Out.int(Shape.count()); Out.str(<span class="string">" made, "</span>); Out.int(Shape.Sides); | |
| 150 | + Out.str(<span class="string">" sides each\n"</span>); | |
| 151 | +<span class="kw">end</span>; | |
| 152 | + | |
| 153 | +<span class="kw">end</span> Squares.</code></pre> | |
| 154 | +<pre class="output"><code>34 | |
| 155 | +2 made, 4 sides each | |
| 156 | +</code></pre> | |
| 157 | +<h2>What the compiler refuses</h2> | |
| 158 | +<p>Reaching past an interface is an error, and the error says where.</p> | |
| 159 | +<div class="file"><span>Peek.raz</span></div><pre class="code"><code><span class="kw">module</span> Peek; | |
| 160 | +<span class="kw">import</span> Shape; | |
| 161 | + | |
| 162 | +<span class="kw">proc</span> main*; | |
| 163 | +<span class="kw">var</span> s: Shape.Square; | |
| 164 | +<span class="kw">begin</span> | |
| 165 | + s := Shape.make(<span class="number">2</span>); | |
| 166 | + s.id := <span class="number">7</span>; | |
| 167 | + Shape.made := <span class="number">0</span>; | |
| 168 | +<span class="kw">end</span>; | |
| 169 | + | |
| 170 | +<span class="kw">end</span> Peek.</code></pre> | |
| 171 | +<pre class="output term"><code><span class="cmd">$ raz Peek.raz</span> | |
| 172 | +Peek.raz:8:7: error: field id of Shape.Square isn't exported | |
| 173 | + 8 | s.id := 7; | |
| 174 | + | ^^ | |
| 175 | +./Shape.raz:8:9: note: id is declared here, without a * | |
| 176 | + 8 | id: INT; (* the module's own *) | |
| 177 | + | ^^ | |
| 178 | +Peek.raz:9:11: error: made isn't exported by Shape | |
| 179 | + 9 | Shape.made := 0; | |
| 180 | + | ^^^^ | |
| 181 | +./Shape.raz:11:5: note: made is declared here, without a * | |
| 182 | + 11 | var made: INT; (* only Shape may read or write it *) | |
| 183 | + | ^^^^ | |
| 184 | +raz: 2 errors</code></pre> | |
| 185 | +<p>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.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="hello.html">← Hello, world</a><a href="index.html">Contents</a><a class="next" href="values.html">Values and conversions →</a></div></article></div> | |
| 69 | 186 | </main> |
| 70 | 187 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 71 | 188 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -76,7 +76,151 @@ | ||
| 76 | 76 | -1 |
| 77 | 77 | </code></pre> |
| 78 | 78 | <p>A parameter is a copy, unless it is <code>var</code>, when it is the caller's variable itself. A procedure may return several results, which a multiple assignment takes apart; the blank, <code>_</code>, drops one.</p> |
| 79 | -<p>A procedure is a value too, of a procedure type, as <code>f</code> is in <code>twice</code>. A procedure without parameters leaves out the parentheses, as <code>Out.ln</code> does. Procedures don't nest, and a name is declared before it is used.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="values.html">← Values and conversions</a><a href="index.html">Contents</a><a class="next" href="slices.html">Arrays, slices and strings →</a></div></article></div> | |
| 79 | +<h2>Value and <code>var</code> parameters</h2> | |
| 80 | +<p>A value parameter is the procedure's own: it may change it, and the caller's variable stays as it was. A <code>var</code> parameter is the caller's variable, and its argument must be a variable of exactly that type.</p> | |
| 81 | +<div class="file"><span>Params.raz</span></div><pre class="code"><code><span class="kw">module</span> Params; | |
| 82 | +<span class="kw">import</span> Out; | |
| 83 | + | |
| 84 | +<span class="kw">proc</span> bump(n: <span class="ty">INT</span>); <span class="comment">(* changes its own copy *)</span> | |
| 85 | +<span class="kw">begin</span> | |
| 86 | + n := n + <span class="number">1</span>; | |
| 87 | +<span class="kw">end</span>; | |
| 88 | + | |
| 89 | +<span class="kw">proc</span> bumpIn(<span class="kw">var</span> n: <span class="ty">INT</span>); <span class="comment">(* changes the caller's *)</span> | |
| 90 | +<span class="kw">begin</span> | |
| 91 | + n := n + <span class="number">1</span>; | |
| 92 | +<span class="kw">end</span>; | |
| 93 | + | |
| 94 | +<span class="kw">proc</span> fill(<span class="kw">var</span> a: [<span class="number">4</span>]<span class="ty">INT</span>; v: <span class="ty">INT</span>); <span class="comment">(* an array is copied unless var *)</span> | |
| 95 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 96 | +<span class="kw">begin</span> | |
| 97 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> a[i] := v; <span class="kw">end</span>; | |
| 98 | +<span class="kw">end</span>; | |
| 99 | + | |
| 100 | +<span class="kw">proc</span> main*; | |
| 101 | +<span class="kw">var</span> x: <span class="ty">INT</span>; a: [<span class="number">4</span>]<span class="ty">INT</span>; | |
| 102 | +<span class="kw">begin</span> | |
| 103 | + x := <span class="number">10</span>; | |
| 104 | + bump(x); | |
| 105 | + Out.int(x); Out.ln; <span class="comment">(* 10 *)</span> | |
| 106 | + bumpIn(x); | |
| 107 | + Out.int(x); Out.ln; <span class="comment">(* 11 *)</span> | |
| 108 | + fill(a, <span class="number">7</span>); | |
| 109 | + Out.int(a[<span class="number">0</span>] + a[<span class="number">3</span>]); Out.ln; <span class="comment">(* 14 *)</span> | |
| 110 | +<span class="kw">end</span>; | |
| 111 | + | |
| 112 | +<span class="kw">end</span> Params.</code></pre> | |
| 113 | +<pre class="output"><code>10 | |
| 114 | +11 | |
| 115 | +14 | |
| 116 | +</code></pre> | |
| 117 | +<h2>Several results</h2> | |
| 118 | +<p>Instead of an output parameter, a procedure says what it returns: <code>(INT, INT)</code>, 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 <code>return</code>, which passes them on as they are.</p> | |
| 119 | +<div class="file"><span>Several.raz</span></div><pre class="code"><code><span class="kw">module</span> Several; | |
| 120 | +<span class="kw">import</span> Out; | |
| 121 | + | |
| 122 | +<span class="kw">proc</span> divmod(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 123 | +<span class="kw">begin</span> | |
| 124 | + <span class="kw">return</span> a <span class="kw">div</span> b, a <span class="kw">mod</span> b; | |
| 125 | +<span class="kw">end</span>; | |
| 126 | + | |
| 127 | +<span class="kw">proc</span> minmax(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 128 | +<span class="kw">begin</span> | |
| 129 | + <span class="kw">if</span> a < b <span class="kw">then</span> <span class="kw">return</span> a, b; <span class="kw">end</span>; | |
| 130 | + <span class="kw">return</span> b, a; | |
| 131 | +<span class="kw">end</span>; | |
| 132 | + | |
| 133 | +<span class="kw">proc</span> spread(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 134 | +<span class="kw">begin</span> | |
| 135 | + <span class="kw">return</span> minmax(a, b); <span class="comment">(* passes both results on *)</span> | |
| 136 | +<span class="kw">end</span>; | |
| 137 | + | |
| 138 | +<span class="kw">proc</span> main*; | |
| 139 | +<span class="kw">var</span> q, r, lo, hi: <span class="ty">INT</span>; | |
| 140 | +<span class="kw">begin</span> | |
| 141 | + q, r := divmod(<span class="number">100</span>, <span class="number">7</span>); | |
| 142 | + Out.int(q); Out.str(<span class="string">" rest "</span>); Out.int(r); Out.ln; | |
| 143 | + lo, hi := spread(<span class="number">9</span>, <span class="number">4</span>); | |
| 144 | + Out.int(lo); Out.str(<span class="string">" .. "</span>); Out.int(hi); Out.ln; | |
| 145 | + _, r := divmod(-<span class="number">7</span>, <span class="number">2</span>); <span class="comment">(* drop the quotient *)</span> | |
| 146 | + Out.int(r); Out.ln; | |
| 147 | +<span class="kw">end</span>; | |
| 148 | + | |
| 149 | +<span class="kw">end</span> Several.</code></pre> | |
| 150 | +<pre class="output"><code>14 rest 2 | |
| 151 | +4 .. 9 | |
| 152 | +-1 | |
| 153 | +</code></pre> | |
| 154 | +<h2>Recursion, and <code>forward</code></h2> | |
| 155 | +<p>A name is declared before it is used, and procedures don't nest. When two procedures need each other, <code>forward</code> declares the first so that its body can come later.</p> | |
| 156 | +<div class="file"><span>Recur.raz</span></div><pre class="code"><code><span class="kw">module</span> Recur; | |
| 157 | +<span class="kw">import</span> Out; | |
| 158 | + | |
| 159 | +<span class="kw">proc</span> gcd(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 160 | +<span class="kw">begin</span> | |
| 161 | + <span class="kw">if</span> b = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> a; <span class="kw">end</span>; | |
| 162 | + <span class="kw">return</span> gcd(b, a <span class="kw">mod</span> b); | |
| 163 | +<span class="kw">end</span>; | |
| 164 | + | |
| 165 | +<span class="kw">proc</span> isOdd(n: <span class="ty">INT</span>): <span class="ty">BOOL</span>; <span class="kw">forward</span>; | |
| 166 | + | |
| 167 | +<span class="kw">proc</span> isEven(n: <span class="ty">INT</span>): <span class="ty">BOOL</span>; | |
| 168 | +<span class="kw">begin</span> | |
| 169 | + <span class="kw">if</span> n = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">true</span>; <span class="kw">end</span>; | |
| 170 | + <span class="kw">return</span> isOdd(n - <span class="number">1</span>); | |
| 171 | +<span class="kw">end</span>; | |
| 172 | + | |
| 173 | +<span class="kw">proc</span> isOdd(n: <span class="ty">INT</span>): <span class="ty">BOOL</span>; | |
| 174 | +<span class="kw">begin</span> | |
| 175 | + <span class="kw">if</span> n = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">false</span>; <span class="kw">end</span>; | |
| 176 | + <span class="kw">return</span> isEven(n - <span class="number">1</span>); | |
| 177 | +<span class="kw">end</span>; | |
| 178 | + | |
| 179 | +<span class="kw">proc</span> main*; | |
| 180 | +<span class="kw">begin</span> | |
| 181 | + Out.int(gcd(<span class="number">84</span>, <span class="number">36</span>)); Out.ln; | |
| 182 | + <span class="kw">if</span> isEven(<span class="number">10</span>) <span class="kw">and</span> isOdd(<span class="number">7</span>) <span class="kw">then</span> Out.str(<span class="string">"parity works\n"</span>); <span class="kw">end</span>; | |
| 183 | +<span class="kw">end</span>; | |
| 184 | + | |
| 185 | +<span class="kw">end</span> Recur.</code></pre> | |
| 186 | +<pre class="output"><code>12 | |
| 187 | +parity works | |
| 188 | +</code></pre> | |
| 189 | +<h2>Procedures are values</h2> | |
| 190 | +<p>A procedure used without parentheses is a procedure value, of a procedure type such as <code>proc(a, b: INT): INT</code>. 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.</p> | |
| 191 | +<div class="file"><span>Table.raz</span></div><pre class="code"><code><span class="kw">module</span> Table; | |
| 192 | +<span class="kw">import</span> Out; | |
| 193 | + | |
| 194 | +<span class="kw">type</span> Op = <span class="kw">proc</span>(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 195 | + | |
| 196 | +<span class="kw">proc</span> add(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; <span class="kw">begin</span> <span class="kw">return</span> a + b; <span class="kw">end</span>; | |
| 197 | +<span class="kw">proc</span> sub(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; <span class="kw">begin</span> <span class="kw">return</span> a - b; <span class="kw">end</span>; | |
| 198 | +<span class="kw">proc</span> mul(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; <span class="kw">begin</span> <span class="kw">return</span> a * b; <span class="kw">end</span>; | |
| 199 | + | |
| 200 | +<span class="kw">proc</span> apply(f: Op; a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 201 | +<span class="kw">begin</span> | |
| 202 | + <span class="kw">return</span> f(a, b); | |
| 203 | +<span class="kw">end</span>; | |
| 204 | + | |
| 205 | +<span class="kw">proc</span> main*; | |
| 206 | +<span class="kw">var</span> ops: [<span class="number">3</span>]Op; names: [<span class="number">3</span>][]<span class="ty">U8</span>; i: <span class="ty">INT</span>; | |
| 207 | +<span class="kw">begin</span> | |
| 208 | + ops := [add, sub, mul]; | |
| 209 | + names := [<span class="string">"add"</span>, <span class="string">"sub"</span>, <span class="string">"mul"</span>]; | |
| 210 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 211 | + Out.str(names[i]); Out.str(<span class="string">": "</span>); | |
| 212 | + Out.int(apply(ops[i], <span class="number">12</span>, <span class="number">5</span>)); Out.ln; | |
| 213 | + <span class="kw">end</span>; | |
| 214 | +<span class="kw">end</span>; | |
| 215 | + | |
| 216 | +<span class="kw">end</span> Table.</code></pre> | |
| 217 | +<pre class="output"><code>add: 17 | |
| 218 | +sub: 7 | |
| 219 | +mul: 60 | |
| 220 | +</code></pre> | |
| 221 | +<p>A procedure without parameters leaves out the parentheses where it is called, as <code>Out.ln</code> does. That means <code>f</code> alone is the procedure and <code>f()</code> would not be a call, so be careful when passing one around.</p> | |
| 222 | +<h2>Dropped results</h2> | |
| 223 | +<p>A call that drops a result, as <code>Sys.write(fd, s);</code> does, is warned of; <code>_ := Sys.write(fd, s);</code> 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 <code>_</code>.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="values.html">← Values and conversions</a><a href="index.html">Contents</a><a class="next" href="slices.html">Arrays, slices and strings →</a></div></article></div> | |
| 80 | 224 | </main> |
| 81 | 225 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 82 | 226 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -64,8 +64,130 @@ | ||
| 64 | 64 | <pre class="output"><code>6 |
| 65 | 65 | 40 10 |
| 66 | 66 | </code></pre> |
| 67 | -<p>A record is laid out as C lays out a struct. <code>{lo: ..., hi: ...}</code> builds one, naming its fields; the ones it leaves out are zero.</p> | |
| 68 | -<p><code>^Box</code> is a pointer to a <code>Box</code>, <code>ADR(b)</code> the address of <code>b</code>, and <code>b^</code> what a pointer points at. A pointer is never the record: it is <code>b^.lo</code>, never <code>b.lo</code>.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="slices.html">← Arrays, slices and strings</a><a href="index.html">Contents</a><a class="next" href="variants.html">Enumerations, sets, variants and match →</a></div></article></div> | |
| 67 | +<p>A record is laid out as C lays out a struct. <code>{lo: ..., hi: ...}</code> builds one, naming its fields; the ones it leaves out are zero. <code>^Box</code> is a pointer to a <code>Box</code>, <code>ADR(b)</code> the address of <code>b</code>, and <code>b^</code> what a pointer points at. A pointer is never the record: it is <code>b^.lo</code>, never <code>b.lo</code>, so you always see where the memory is reached through an address.</p> | |
| 68 | +<h2>Copies and literals</h2> | |
| 69 | +<p>Assigning a record copies it whole, as with an array. A record is compared field by field by writing the comparison, not by <code>=</code>.</p> | |
| 70 | +<div class="file"><span>Points.raz</span></div><pre class="code"><code><span class="kw">module</span> Points; | |
| 71 | +<span class="kw">import</span> Out; | |
| 72 | + | |
| 73 | +<span class="kw">type</span> Point = <span class="kw">record</span> x, y: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 74 | + | |
| 75 | +<span class="kw">proc</span> show(p: Point); | |
| 76 | +<span class="kw">begin</span> | |
| 77 | + Out.char(<span class="string">'('</span>); Out.int(p.x); Out.str(<span class="string">", "</span>); Out.int(p.y); Out.char(<span class="string">')'</span>); | |
| 78 | +<span class="kw">end</span>; | |
| 79 | + | |
| 80 | +<span class="kw">proc</span> mirror(p: Point): Point; | |
| 81 | +<span class="kw">begin</span> | |
| 82 | + <span class="kw">return</span> {x: p.y, y: p.x}; | |
| 83 | +<span class="kw">end</span>; | |
| 84 | + | |
| 85 | +<span class="kw">proc</span> main*; | |
| 86 | +<span class="kw">var</span> a, b: Point; | |
| 87 | +<span class="kw">begin</span> | |
| 88 | + a := {x: <span class="number">3</span>, y: <span class="number">4</span>}; | |
| 89 | + b := a; <span class="comment">(* a copy *)</span> | |
| 90 | + b.x := <span class="number">30</span>; | |
| 91 | + show(a); show(b); show(mirror(a)); Out.ln; | |
| 92 | + a := {y: <span class="number">9</span>}; <span class="comment">(* x is zero *)</span> | |
| 93 | + show(a); Out.ln; | |
| 94 | +<span class="kw">end</span>; | |
| 95 | + | |
| 96 | +<span class="kw">end</span> Points.</code></pre> | |
| 97 | +<pre class="output"><code>(3, 4)(30, 4)(4, 3) | |
| 98 | +(0, 9) | |
| 99 | +</code></pre> | |
| 100 | +<h2>Layout</h2> | |
| 101 | +<p>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. <code>SIZE(T)</code> says how many bytes. A <code>packed record</code> has no padding, which is what a file format or a wire protocol wants.</p> | |
| 102 | +<div class="file"><span>Layout.raz</span></div><pre class="code"><code><span class="kw">module</span> Layout; | |
| 103 | +<span class="kw">import</span> Out; | |
| 104 | + | |
| 105 | +<span class="kw">type</span> | |
| 106 | + Loose = <span class="kw">record</span> a: <span class="ty">U8</span>; b: <span class="ty">U32</span>; c: <span class="ty">U8</span>; <span class="kw">end</span>; | |
| 107 | + Tight = <span class="kw">packed</span> <span class="kw">record</span> a: <span class="ty">U8</span>; b: <span class="ty">U32</span>; c: <span class="ty">U8</span>; <span class="kw">end</span>; | |
| 108 | + | |
| 109 | +<span class="kw">proc</span> main*; | |
| 110 | +<span class="kw">begin</span> | |
| 111 | + Out.str(<span class="string">"loose: "</span>); Out.int(<span class="ty">SIZE</span>(Loose)); Out.ln; <span class="comment">(* 12 *)</span> | |
| 112 | + Out.str(<span class="string">"tight: "</span>); Out.int(<span class="ty">SIZE</span>(Tight)); Out.ln; <span class="comment">(* 6 *)</span> | |
| 113 | + Out.str(<span class="string">"INT: "</span>); Out.int(<span class="ty">SIZE</span>(<span class="ty">INT</span>)); Out.ln; | |
| 114 | + Out.str(<span class="string">"[5]I16: "</span>); Out.int(<span class="ty">SIZE</span>([<span class="number">5</span>]<span class="ty">I16</span>)); Out.ln; | |
| 115 | +<span class="kw">end</span>; | |
| 116 | + | |
| 117 | +<span class="kw">end</span> Layout.</code></pre> | |
| 118 | +<pre class="output"><code>loose: 12 | |
| 119 | +tight: 6 | |
| 120 | +INT: 8 | |
| 121 | +[5]I16: 10 | |
| 122 | +</code></pre> | |
| 123 | +<p>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 <code>ADR</code>.</p> | |
| 124 | +<h2>Pointers</h2> | |
| 125 | +<p><code>ADR(x)</code> takes the address of a variable, <code>^T</code> is a pointer to a <code>T</code>, and <code>p^</code> is what it points at. A pointer that points nowhere is <code>nil</code>, 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.</p> | |
| 126 | +<div class="file"><span>Pointers.raz</span></div><pre class="code"><code><span class="kw">module</span> Pointers; | |
| 127 | +<span class="kw">import</span> Out; | |
| 128 | + | |
| 129 | +<span class="kw">type</span> Counter = <span class="kw">record</span> hits: <span class="ty">INT</span>; name: []<span class="ty">U8</span>; <span class="kw">end</span>; | |
| 130 | + | |
| 131 | +<span class="kw">proc</span> hit(c: ^Counter); | |
| 132 | +<span class="kw">begin</span> | |
| 133 | + <span class="kw">if</span> c = <span class="ty">nil</span> <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 134 | + <span class="ty">INC</span>(c^.hits); | |
| 135 | +<span class="kw">end</span>; | |
| 136 | + | |
| 137 | +<span class="kw">proc</span> swap(a, b: ^<span class="ty">INT</span>); | |
| 138 | +<span class="kw">var</span> t: <span class="ty">INT</span>; | |
| 139 | +<span class="kw">begin</span> | |
| 140 | + t := a^; | |
| 141 | + a^ := b^; | |
| 142 | + b^ := t; | |
| 143 | +<span class="kw">end</span>; | |
| 144 | + | |
| 145 | +<span class="kw">proc</span> main*; | |
| 146 | +<span class="kw">var</span> c: Counter; x, y: <span class="ty">INT</span>; p: ^<span class="ty">INT</span>; | |
| 147 | +<span class="kw">begin</span> | |
| 148 | + c.name := <span class="string">"front door"</span>; | |
| 149 | + hit(<span class="ty">ADR</span>(c)); hit(<span class="ty">ADR</span>(c)); hit(<span class="ty">nil</span>); | |
| 150 | + Out.str(c.name); Out.str(<span class="string">": "</span>); Out.int(c.hits); Out.ln; | |
| 151 | + x := <span class="number">1</span>; y := <span class="number">2</span>; | |
| 152 | + swap(<span class="ty">ADR</span>(x), <span class="ty">ADR</span>(y)); | |
| 153 | + Out.int(x); Out.char(<span class="string">' '</span>); Out.int(y); Out.ln; | |
| 154 | + p := <span class="ty">ADR</span>(x); | |
| 155 | + p^ := p^ + <span class="number">40</span>; | |
| 156 | + Out.int(x); Out.ln; | |
| 157 | +<span class="kw">end</span>; | |
| 158 | + | |
| 159 | +<span class="kw">end</span> Pointers.</code></pre> | |
| 160 | +<pre class="output"><code>front door: 2 | |
| 161 | +2 1 | |
| 162 | +42 | |
| 163 | +</code></pre> | |
| 164 | +<h2>Pointers that link</h2> | |
| 165 | +<p>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.</p> | |
| 166 | +<div class="file"><span>Chain.raz</span></div><pre class="code"><code><span class="kw">module</span> Chain; | |
| 167 | +<span class="kw">import</span> Out; | |
| 168 | + | |
| 169 | +<span class="kw">type</span> Node = <span class="kw">record</span> next: ^Node; val: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 170 | + | |
| 171 | +<span class="kw">proc</span> main*; | |
| 172 | +<span class="kw">var</span> nodes: [<span class="number">4</span>]Node; head, n: ^Node; i: <span class="ty">INT</span>; | |
| 173 | +<span class="kw">begin</span> | |
| 174 | + head := <span class="ty">nil</span>; | |
| 175 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 176 | + nodes[i].val := (i + <span class="number">1</span>) * <span class="number">10</span>; | |
| 177 | + nodes[i].next := head; <span class="comment">(* each new one in front *)</span> | |
| 178 | + head := <span class="ty">ADR</span>(nodes[i]); | |
| 179 | + <span class="kw">end</span>; | |
| 180 | + n := head; | |
| 181 | + <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> | |
| 182 | + Out.int(n^.val); Out.char(<span class="string">' '</span>); | |
| 183 | + n := n^.next; | |
| 184 | + <span class="kw">end</span>; | |
| 185 | + Out.ln; | |
| 186 | +<span class="kw">end</span>; | |
| 187 | + | |
| 188 | +<span class="kw">end</span> Chain.</code></pre> | |
| 189 | +<pre class="output"><code>40 30 20 10 | |
| 190 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="slices.html">← Arrays, slices and strings</a><a href="index.html">Contents</a><a class="next" href="variants.html">Enumerations, sets, variants and match →</a></div></article></div> | |
| 69 | 191 | </main> |
| 70 | 192 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 71 | 193 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -63,9 +63,179 @@ | ||
| 63 | 63 | 7 |
| 64 | 64 | Raz |
| 65 | 65 | </code></pre> |
| 66 | -<p><code>[5]INT</code> is an array: five <code>INT</code>s in a row, copied when it is assigned. <code>[]INT</code> is a slice: a pointer to elements that live elsewhere, and their number, <code>LEN(s)</code>. <code>a[lo..hi]</code> is the slice of the elements from <code>lo</code> up to, but not including, <code>hi</code>, and an array goes silently where a slice is wanted.</p> | |
| 67 | -<p>A string is a slice of bytes, <code>[]U8</code>, in UTF-8, and its bytes are constant; a <code>[8]U8</code> made from one is a copy. Arrays and slices of integers compare with <code>=</code> and <code>#</code>; <code>Str</code> has the rest: ordering, finding, hashing and reading a number.</p> | |
| 68 | -<p>A <code>for</code> loop takes its bounds once, and never steps past the last: with an empty slice, <code>0 to LEN(s) - 1</code> doesn't run at all.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="procedures.html">← Procedures and several results</a><a href="index.html">Contents</a><a class="next" href="records.html">Records and pointers →</a></div></article></div> | |
| 66 | +<h2>Arrays</h2> | |
| 67 | +<p><code>[5]INT</code> is an array: five <code>INT</code>s in a row, copied when it is assigned or passed. Its length is part of its type, so <code>[5]INT</code> and <code>[6]INT</code> are different types, and <code>LEN(a)</code> of an array is a constant. Array literals are written in brackets, and need a type from the place they are used.</p> | |
| 68 | +<div class="file"><span>Arrays.raz</span></div><pre class="code"><code><span class="kw">module</span> Arrays; | |
| 69 | +<span class="kw">import</span> Out; | |
| 70 | + | |
| 71 | +<span class="kw">proc</span> main*; | |
| 72 | +<span class="kw">var</span> a, b: [<span class="number">4</span>]<span class="ty">INT</span>; grid: [<span class="number">3</span>][<span class="number">3</span>]<span class="ty">INT</span>; i, j: <span class="ty">INT</span>; | |
| 73 | +<span class="kw">begin</span> | |
| 74 | + a := [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]; | |
| 75 | + b := a; <span class="comment">(* a copy *)</span> | |
| 76 | + b[<span class="number">0</span>] := <span class="number">99</span>; | |
| 77 | + Out.int(a[<span class="number">0</span>]); Out.char(<span class="string">' '</span>); Out.int(b[<span class="number">0</span>]); Out.ln; | |
| 78 | + <span class="kw">if</span> a # b <span class="kw">then</span> Out.str(<span class="string">"they differ now\n"</span>); <span class="kw">end</span>; | |
| 79 | + | |
| 80 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 81 | + <span class="kw">for</span> j := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> grid[i][j] := i * <span class="number">3</span> + j; <span class="kw">end</span>; | |
| 82 | + <span class="kw">end</span>; | |
| 83 | + Out.int(grid[<span class="number">2</span>][<span class="number">1</span>]); Out.ln; <span class="comment">(* 7 *)</span> | |
| 84 | + Out.int(<span class="ty">LEN</span>(grid)); Out.char(<span class="string">'x'</span>); Out.int(<span class="ty">LEN</span>(grid[<span class="number">0</span>])); Out.ln; | |
| 85 | +<span class="kw">end</span>; | |
| 86 | + | |
| 87 | +<span class="kw">end</span> Arrays.</code></pre> | |
| 88 | +<pre class="output"><code>1 99 | |
| 89 | +they differ now | |
| 90 | +7 | |
| 91 | +3x3 | |
| 92 | +</code></pre> | |
| 93 | +<h2>Slices</h2> | |
| 94 | +<p><code>[]INT</code> is a slice: a pointer to elements that live elsewhere, and their number, <code>LEN(s)</code>. <code>a[lo..hi]</code> is the slice of the elements from <code>lo</code> up to, but not including, <code>hi</code>, 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.</p> | |
| 95 | +<div class="file"><span>Windows.raz</span></div><pre class="code"><code><span class="kw">module</span> Windows; | |
| 96 | +<span class="kw">import</span> Out; | |
| 97 | + | |
| 98 | +<span class="kw">proc</span> zero(s: []<span class="ty">INT</span>); | |
| 99 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 100 | +<span class="kw">begin</span> | |
| 101 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> s[i] := <span class="number">0</span>; <span class="kw">end</span>; | |
| 102 | +<span class="kw">end</span>; | |
| 103 | + | |
| 104 | +<span class="kw">proc</span> show(s: []<span class="ty">INT</span>); | |
| 105 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 106 | +<span class="kw">begin</span> | |
| 107 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> Out.int(s[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 108 | + Out.ln; | |
| 109 | +<span class="kw">end</span>; | |
| 110 | + | |
| 111 | +<span class="kw">proc</span> main*; | |
| 112 | +<span class="kw">var</span> a: [<span class="number">8</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 113 | +<span class="kw">begin</span> | |
| 114 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">7</span> <span class="kw">do</span> a[i] := i + <span class="number">1</span>; <span class="kw">end</span>; | |
| 115 | + zero(a[<span class="number">2</span>..<span class="number">5</span>]); <span class="comment">(* a window onto a *)</span> | |
| 116 | + show(a); <span class="comment">(* 1 2 0 0 0 6 7 8 *)</span> | |
| 117 | + show(a[<span class="number">6</span>..<span class="number">8</span>]); | |
| 118 | + show(a[<span class="number">3</span>..<span class="number">3</span>]); <span class="comment">(* empty: prints just a line feed *)</span> | |
| 119 | +<span class="kw">end</span>; | |
| 120 | + | |
| 121 | +<span class="kw">end</span> Windows.</code></pre> | |
| 122 | +<pre class="output"><code>1 2 0 0 0 6 7 8 | |
| 123 | +7 8 | |
| 124 | + | |
| 125 | +</code></pre> | |
| 126 | +<p>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.</p> | |
| 127 | +<h2><code>COPY</code></h2> | |
| 128 | +<p><code>COPY(d, s)</code> copies the elements of <code>s</code> to the start of <code>d</code>, as one block, and is right when they overlap. <code>LEN(s)</code> must be at most <code>LEN(d)</code>.</p> | |
| 129 | +<div class="file"><span>Moves.raz</span></div><pre class="code"><code><span class="kw">module</span> Moves; | |
| 130 | +<span class="kw">import</span> Out; | |
| 131 | + | |
| 132 | +<span class="kw">proc</span> main*; | |
| 133 | +<span class="kw">var</span> a: [<span class="number">6</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 134 | +<span class="kw">begin</span> | |
| 135 | + a := [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">0</span>]; | |
| 136 | + COPY(a[<span class="number">1</span>..<span class="number">6</span>], a[<span class="number">0</span>..<span class="number">5</span>]); <span class="comment">(* shift everything one place up *)</span> | |
| 137 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> Out.int(a[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 138 | + Out.ln; | |
| 139 | +<span class="kw">end</span>; | |
| 140 | + | |
| 141 | +<span class="kw">end</span> Moves.</code></pre> | |
| 142 | +<pre class="output"><code>1 1 2 3 4 5 | |
| 143 | +</code></pre> | |
| 144 | +<h2>Strings</h2> | |
| 145 | +<p>A string is a slice of bytes, <code>[]U8</code>, in UTF-8, and a string constant's bytes are constant. A <code>[8]U8</code> made from one is a copy you can change. Arrays and slices of integers compare with <code>=</code> and <code>#</code>, so strings do too. <code>Str</code> has the rest: ordering, finding, hashing, prefixes, UTF-8 and reading a number.</p> | |
| 146 | +<div class="file"><span>Words.raz</span></div><pre class="code"><code><span class="kw">module</span> Words; | |
| 147 | +<span class="kw">import</span> Out, Str; | |
| 148 | + | |
| 149 | +<span class="kw">proc</span> main*; | |
| 150 | +<span class="kw">var</span> s: []<span class="ty">U8</span>; n: <span class="ty">I64</span>; ok: <span class="ty">BOOL</span>; name: [<span class="number">8</span>]<span class="ty">U8</span>; | |
| 151 | +<span class="kw">begin</span> | |
| 152 | + s := <span class="string">"hello, world"</span>; | |
| 153 | + Out.str(s[<span class="number">7</span>..<span class="ty">LEN</span>(s)]); Out.ln; | |
| 154 | + <span class="kw">if</span> s[<span class="number">0</span>..<span class="number">5</span>] = <span class="string">"hello"</span> <span class="kw">then</span> Out.str(<span class="string">"it says hello\n"</span>); <span class="kw">end</span>; | |
| 155 | + Out.int(Str.find(s, <span class="string">"world"</span>)); Out.ln; <span class="comment">(* 7 *)</span> | |
| 156 | + Out.int(Str.find(s, <span class="string">"xyz"</span>)); Out.ln; <span class="comment">(* -1 *)</span> | |
| 157 | + <span class="kw">if</span> Str.hasPrefix(s, <span class="string">"hell"</span>) <span class="kw">then</span> Out.str(<span class="string">"prefix\n"</span>); <span class="kw">end</span>; | |
| 158 | + Out.int(Str.cmp(<span class="string">"apple"</span>, <span class="string">"banana"</span>)); Out.ln; <span class="comment">(* -1 *)</span> | |
| 159 | + | |
| 160 | + n, ok := Str.toInt(<span class="string">"-1234"</span>); | |
| 161 | + <span class="kw">if</span> ok <span class="kw">then</span> Out.int(n + <span class="number">1</span>); Out.ln; <span class="kw">end</span>; | |
| 162 | + n, ok := Str.toInt(<span class="string">"12x"</span>); | |
| 163 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Out.str(<span class="string">"not a number\n"</span>); <span class="kw">end</span>; | |
| 164 | + | |
| 165 | + name := <span class="string">"raz"</span>; <span class="comment">(* a copy, the program's own *)</span> | |
| 166 | + name[<span class="number">0</span>] := <span class="string">'R'</span>; | |
| 167 | + Out.str(name[<span class="number">0</span>..<span class="number">3</span>]); Out.ln; | |
| 168 | +<span class="kw">end</span>; | |
| 169 | + | |
| 170 | +<span class="kw">end</span> Words.</code></pre> | |
| 171 | +<pre class="output"><code>world | |
| 172 | +it says hello | |
| 173 | +7 | |
| 174 | +-1 | |
| 175 | +prefix | |
| 176 | +-1 | |
| 177 | +-1233 | |
| 178 | +not a number | |
| 179 | +Raz | |
| 180 | +</code></pre> | |
| 181 | +<h2>UTF-8</h2> | |
| 182 | +<p>A character is an <code>I32</code>, its code point. <code>Str.decode</code> reads the first character of a string and says how many bytes it took; <code>Str.encode</code> goes the other way. Byte length and character count are different things, and the program is the one that says which it wants.</p> | |
| 183 | +<div class="file"><span>Runes.raz</span></div><pre class="code"><code><span class="kw">module</span> Runes; | |
| 184 | +<span class="kw">import</span> Out, Str; | |
| 185 | + | |
| 186 | +<span class="comment">(* the characters of s, not its bytes *)</span> | |
| 187 | +<span class="kw">proc</span> chars(s: []<span class="ty">U8</span>): <span class="ty">INT</span>; | |
| 188 | +<span class="kw">var</span> i, n, size: <span class="ty">INT</span>; | |
| 189 | +<span class="kw">begin</span> | |
| 190 | + i := <span class="number">0</span>; | |
| 191 | + n := <span class="number">0</span>; | |
| 192 | + <span class="kw">while</span> i < <span class="ty">LEN</span>(s) <span class="kw">do</span> | |
| 193 | + _, size := Str.decode(s[i..<span class="ty">LEN</span>(s)]); | |
| 194 | + <span class="ty">INC</span>(i, size); | |
| 195 | + <span class="ty">INC</span>(n); | |
| 196 | + <span class="kw">end</span>; | |
| 197 | + <span class="kw">return</span> n; | |
| 198 | +<span class="kw">end</span>; | |
| 199 | + | |
| 200 | +<span class="kw">proc</span> main*; | |
| 201 | +<span class="kw">var</span> s: []<span class="ty">U8</span>; c: <span class="ty">I32</span>; size: <span class="ty">INT</span>; bytes: [<span class="number">4</span>]<span class="ty">U8</span>; k: <span class="ty">INT</span>; | |
| 202 | +<span class="kw">begin</span> | |
| 203 | + s := <span class="string">"caf\u{E9} \u{3BB}"</span>; | |
| 204 | + Out.int(<span class="ty">LEN</span>(s)); Out.str(<span class="string">" bytes, "</span>); | |
| 205 | + Out.int(chars(s)); Out.str(<span class="string">" characters\n"</span>); | |
| 206 | + c, size := Str.decode(s[<span class="number">3</span>..<span class="ty">LEN</span>(s)]); | |
| 207 | + Out.int(<span class="ty">I64</span>(c)); Out.str(<span class="string">" took "</span>); Out.int(size); Out.str(<span class="string">" bytes\n"</span>); | |
| 208 | + bytes, k := Str.encode(<span class="number">955</span>); | |
| 209 | + Out.str(bytes[<span class="number">0</span>..k]); Out.ln; | |
| 210 | +<span class="kw">end</span>; | |
| 211 | + | |
| 212 | +<span class="kw">end</span> Runes.</code></pre> | |
| 213 | +<pre class="output"><code>8 bytes, 6 characters | |
| 214 | +233 took 2 bytes | |
| 215 | +λ | |
| 216 | +</code></pre> | |
| 217 | +<h2>Loops over lengths</h2> | |
| 218 | +<p>A <code>for</code> loop takes its bounds once, and never steps past the last: with an empty slice, <code>0 to LEN(s) - 1</code> doesn't run at all, and the variable can't wrap. <code>for</code> takes a constant step with <code>by</code>, and <code>while</code> and <code>repeat ... until</code> do the rest.</p> | |
| 219 | +<div class="file"><span>Loops.raz</span></div><pre class="code"><code><span class="kw">module</span> Loops; | |
| 220 | +<span class="kw">import</span> Out; | |
| 221 | + | |
| 222 | +<span class="kw">proc</span> main*; | |
| 223 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 224 | +<span class="kw">begin</span> | |
| 225 | + <span class="kw">for</span> i := <span class="number">10</span> <span class="kw">to</span> <span class="number">0</span> <span class="kw">by</span> -<span class="number">5</span> <span class="kw">do</span> Out.int(i); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 226 | + Out.ln; | |
| 227 | + i := <span class="number">1</span>; | |
| 228 | + <span class="kw">while</span> i < <span class="number">100</span> <span class="kw">do</span> i := i * <span class="number">3</span>; <span class="kw">end</span>; | |
| 229 | + Out.int(i); Out.ln; | |
| 230 | + <span class="kw">repeat</span> <span class="ty">DEC</span>(i, <span class="number">30</span>); <span class="kw">until</span> i < <span class="number">0</span>; | |
| 231 | + Out.int(i); Out.ln; | |
| 232 | +<span class="kw">end</span>; | |
| 233 | + | |
| 234 | +<span class="kw">end</span> Loops.</code></pre> | |
| 235 | +<pre class="output"><code>10 5 0 | |
| 236 | +243 | |
| 237 | +-27 | |
| 238 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="procedures.html">← Procedures and several results</a><a href="index.html">Contents</a><a class="next" href="records.html">Records and pointers →</a></div></article></div> | |
| 69 | 239 | </main> |
| 70 | 240 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 71 | 241 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -68,8 +68,107 @@ | ||
| 68 | 68 | <pre class="output"><code>10000 15005000 |
| 69 | 69 | </code></pre> |
| 70 | 70 | <p><code>Thread.spawn</code> runs a procedure in a thread of its own, with a stack of its own, and <code>Thread.join</code> waits for it to end. <code>XADD</code>, <code>CAS</code> and <code>XCHG</code> change a word atomically; a <code>Thread.Mutex</code> keeps a longer section to one thread at a time. <code>Out</code> and <code>Heap</code> lock themselves.</p> |
| 71 | -<p><code>Thread</code> 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 <code>pthread_create</code> instead.</p> | |
| 72 | -<p>That is the tour. The rest is in <a href="../spec.html">the report</a>, and the library's interfaces are printed by <code>tools/Doc.raz</code>.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="c.html">← Talking to C</a><a href="index.html">Contents</a><a class="next" href="../spec.html">The report →</a></div></article></div> | |
| 71 | +<h2>What goes wrong without them</h2> | |
| 72 | +<p>Two threads that each read a variable, add one and write it back can lose one of the additions. A plain <code>INC</code> on a variable shared by threads has no particular value afterwards; the report says so. <code>XADD</code> is the atomic add: it returns the old value and adds in one indivisible step.</p> | |
| 73 | +<div class="file"><span>Race.raz</span></div><pre class="code"><code><span class="kw">module</span> Race; | |
| 74 | +<span class="kw">import</span> Out, Thread; | |
| 75 | + | |
| 76 | +<span class="kw">var</span> | |
| 77 | + safe: <span class="ty">INT</span>; <span class="comment">(* added to by XADD *)</span> | |
| 78 | + plain: <span class="ty">INT</span>; <span class="comment">(* added to by INC: unsafe, never printed *)</span> | |
| 79 | + | |
| 80 | +<span class="kw">proc</span> work(_arg: ^<span class="ty">U8</span>); | |
| 81 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 82 | +<span class="kw">begin</span> | |
| 83 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">100000</span> <span class="kw">do</span> | |
| 84 | + _ := <span class="ty">XADD</span>(<span class="ty">ADR</span>(safe), <span class="number">1</span>); | |
| 85 | + <span class="ty">INC</span>(plain); <span class="comment">(* unsafe: lost additions *)</span> | |
| 86 | + <span class="kw">end</span>; | |
| 87 | +<span class="kw">end</span>; | |
| 88 | + | |
| 89 | +<span class="kw">proc</span> main*; | |
| 90 | +<span class="kw">var</span> t: [<span class="number">4</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 91 | +<span class="kw">begin</span> | |
| 92 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 93 | + t[i], err := Thread.spawn(work, <span class="ty">nil</span>); | |
| 94 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 95 | + <span class="kw">end</span>; | |
| 96 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(t[i]); <span class="kw">end</span>; | |
| 97 | + Out.str(<span class="string">"safe "</span>); Out.int(safe); Out.ln; | |
| 98 | +<span class="kw">end</span>; | |
| 99 | + | |
| 100 | +<span class="kw">end</span> Race.</code></pre> | |
| 101 | +<pre class="output"><code>safe 400000 | |
| 102 | +</code></pre> | |
| 103 | +<p>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.</p> | |
| 104 | +<h2>A mutex for longer sections</h2> | |
| 105 | +<p>An atomic is one word. When several variables must change together, take a <code>Thread.Mutex</code>; it sleeps while it waits, so it suits sections that take a while. Declare it as a module variable, since zero is free.</p> | |
| 106 | +<div class="file"><span>Bank.raz</span></div><pre class="code"><code><span class="kw">module</span> Bank; | |
| 107 | +<span class="kw">import</span> Out, Thread; | |
| 108 | + | |
| 109 | +<span class="kw">var</span> | |
| 110 | + m: Thread.Mutex; | |
| 111 | + balance, deposits: <span class="ty">INT</span>; <span class="comment">(* kept in step, under m *)</span> | |
| 112 | + | |
| 113 | +<span class="kw">proc</span> deposit(_arg: ^<span class="ty">U8</span>); | |
| 114 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 115 | +<span class="kw">begin</span> | |
| 116 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">10000</span> <span class="kw">do</span> | |
| 117 | + Thread.lock(<span class="ty">ADR</span>(m)); | |
| 118 | + balance := balance + <span class="number">5</span>; | |
| 119 | + <span class="ty">INC</span>(deposits); | |
| 120 | + Thread.unlock(<span class="ty">ADR</span>(m)); | |
| 121 | + <span class="kw">end</span>; | |
| 122 | +<span class="kw">end</span>; | |
| 123 | + | |
| 124 | +<span class="kw">proc</span> main*; | |
| 125 | +<span class="kw">var</span> t: [<span class="number">3</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 126 | +<span class="kw">begin</span> | |
| 127 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 128 | + t[i], err := Thread.spawn(deposit, <span class="ty">nil</span>); | |
| 129 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 130 | + <span class="kw">end</span>; | |
| 131 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> Thread.join(t[i]); <span class="kw">end</span>; | |
| 132 | + Out.int(deposits); Out.char(<span class="string">' '</span>); Out.int(balance); Out.ln; | |
| 133 | +<span class="kw">end</span>; | |
| 134 | + | |
| 135 | +<span class="kw">end</span> Bank.</code></pre> | |
| 136 | +<pre class="output"><code>30000 150000 | |
| 137 | +</code></pre> | |
| 138 | +<h2>Handing work out</h2> | |
| 139 | +<p>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.</p> | |
| 140 | +<div class="file"><span>Jobs.raz</span></div><pre class="code"><code><span class="kw">module</span> Jobs; | |
| 141 | +<span class="kw">import</span> Out, Thread; | |
| 142 | + | |
| 143 | +<span class="kw">type</span> Job = <span class="kw">record</span> lo, hi: <span class="ty">INT</span>; sum: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 144 | + | |
| 145 | +<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); | |
| 146 | +<span class="kw">var</span> j: ^Job; i: <span class="ty">INT</span>; | |
| 147 | +<span class="kw">begin</span> | |
| 148 | + j := ^Job(arg); | |
| 149 | + <span class="kw">for</span> i := j^.lo <span class="kw">to</span> j^.hi - <span class="number">1</span> <span class="kw">do</span> j^.sum := j^.sum + i; <span class="kw">end</span>; | |
| 150 | +<span class="kw">end</span>; | |
| 151 | + | |
| 152 | +<span class="kw">proc</span> main*; | |
| 153 | +<span class="kw">var</span> jobs: [<span class="number">4</span>]Job; t: [<span class="number">4</span>]^Thread.Thread; i, total: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 154 | +<span class="kw">begin</span> | |
| 155 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 156 | + jobs[i].lo := i * <span class="number">250000</span>; | |
| 157 | + jobs[i].hi := (i + <span class="number">1</span>) * <span class="number">250000</span>; | |
| 158 | + t[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(<span class="ty">ADR</span>(jobs[i]))); | |
| 159 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 160 | + <span class="kw">end</span>; | |
| 161 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 162 | + Thread.join(t[i]); | |
| 163 | + total := total + jobs[i].sum; | |
| 164 | + <span class="kw">end</span>; | |
| 165 | + Out.int(total); Out.ln; | |
| 166 | +<span class="kw">end</span>; | |
| 167 | + | |
| 168 | +<span class="kw">end</span> Jobs.</code></pre> | |
| 169 | +<pre class="output"><code>499999500000 | |
| 170 | +</code></pre> | |
| 171 | +<p><code>Thread</code> 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 <code>pthread_create</code> instead. The advanced tour goes further into atomics, memory ordering and lock-free code.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="c.html">← Talking to C</a><a href="index.html">Contents</a><a class="next" href="../advanced/index.html">Beyond Go →</a></div></article></div> | |
| 73 | 172 | </main> |
| 74 | 173 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 75 | 174 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html" aria-current="page">Values and conversions</a></li> |
| @@ -52,10 +52,104 @@ | ||
| 52 | 52 | <span class="kw">end</span> Values.</code></pre> |
| 53 | 53 | <pre class="output"><code>300 4 300 42.857 233 true |
| 54 | 54 | </code></pre> |
| 55 | -<p>The integers are <code>I8</code>, <code>I16</code>, <code>I32</code>, <code>I64</code> and <code>U8</code>, <code>U16</code>, <code>U32</code>, <code>U64</code>, and <code>INT</code> and <code>UINT</code>, as big as an address. <code>INT</code> is the everyday one: lengths, indexes and counts are <code>INT</code>s. The reals are <code>F32</code> and <code>F64</code>.</p> | |
| 56 | -<p>Arithmetic wraps at the type's width and never stops the program, except dividing by zero. That is why <code>250 + 10</code> in a <code>U8</code> is 4.</p> | |
| 57 | -<p>Two types never mix: with <code>i: I64</code>, <code>i < LEN(s)</code> is an error. A type's name converts, as <code>F64(n)</code> and <code>I64(b)</code> do above. The one silent conversion between numbers is an <code>INT</code> into an <code>I64</code>, which loses nothing.</p> | |
| 58 | -<p><code>#</code>, not <code><></code>, is "different". <code>and</code>, <code>or</code> and <code>not</code> are for <code>BOOL</code>s; <code>&</code>, <code>|</code>, <code>xor</code> and <code>~</code> are for the bits of integers. Every variable starts at zero.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="modules.html">← Modules</a><a href="index.html">Contents</a><a class="next" href="procedures.html">Procedures and several results →</a></div></article></div> | |
| 55 | +<h2>Integers</h2> | |
| 56 | +<p>The integers are <code>I8</code>, <code>I16</code>, <code>I32</code>, <code>I64</code> and <code>U8</code>, <code>U16</code>, <code>U32</code>, <code>U64</code>, and <code>INT</code> and <code>UINT</code>, as big as an address. <code>INT</code> is the everyday one: lengths, indexes and counts are <code>INT</code>s.</p> | |
| 57 | +<p>Arithmetic wraps at the type's width and never stops the program, except dividing by zero. That is why <code>250 + 10</code> in a <code>U8</code> is 4. <code>div</code> divides toward zero, and <code>mod</code> has the sign of its left side.</p> | |
| 58 | +<div class="file"><span>Wrap.raz</span></div><pre class="code"><code><span class="kw">module</span> Wrap; | |
| 59 | +<span class="kw">import</span> Out; | |
| 60 | + | |
| 61 | +<span class="kw">proc</span> main*; | |
| 62 | +<span class="kw">var</span> a: <span class="ty">U8</span>; b: <span class="ty">I8</span>; c: <span class="ty">U32</span>; d: <span class="ty">INT</span>; | |
| 63 | +<span class="kw">begin</span> | |
| 64 | + a := <span class="number">250</span>; a := a + <span class="number">10</span>; | |
| 65 | + Out.int(<span class="ty">I64</span>(a)); Out.ln; <span class="comment">(* 4 *)</span> | |
| 66 | + b := <span class="number">127</span>; b := b + <span class="number">1</span>; | |
| 67 | + Out.int(<span class="ty">I64</span>(b)); Out.ln; <span class="comment">(* -128 *)</span> | |
| 68 | + c := <span class="number">0</span>; c := c - <span class="number">1</span>; | |
| 69 | + Out.int(<span class="ty">I64</span>(c)); Out.ln; <span class="comment">(* 4294967295 *)</span> | |
| 70 | + d := -<span class="number">7</span>; | |
| 71 | + Out.int(d <span class="kw">div</span> <span class="number">2</span>); Out.str(<span class="string">" "</span>); <span class="comment">(* -3 *)</span> | |
| 72 | + Out.int(d <span class="kw">mod</span> <span class="number">2</span>); Out.ln; <span class="comment">(* -1 *)</span> | |
| 73 | +<span class="kw">end</span>; | |
| 74 | + | |
| 75 | +<span class="kw">end</span> Wrap.</code></pre> | |
| 76 | +<pre class="output"><code>4 | |
| 77 | +-128 | |
| 78 | +4294967295 | |
| 79 | +-3 -1 | |
| 80 | +</code></pre> | |
| 81 | +<h2>Conversions are written</h2> | |
| 82 | +<p>Two types never mix: with <code>i: I64</code> and a slice <code>s</code>, <code>i < LEN(s)</code> is an error. A type's name converts: <code>F64(n)</code>, <code>I64(b)</code>, <code>U8(x)</code>. 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 <code>INT</code> into an <code>I64</code>, which loses nothing.</p> | |
| 83 | +<p>A number written in the program is untyped until it meets a type; <code>0FFH</code> is hexadecimal, and <code>1.5</code> is a real, which an integer never becomes without a conversion.</p> | |
| 84 | +<div class="file"><span>Mix.raz</span></div><pre class="code"><code><span class="kw">module</span> Mix; | |
| 85 | +<span class="kw">import</span> Out; | |
| 86 | + | |
| 87 | +<span class="kw">proc</span> main*; | |
| 88 | +<span class="kw">var</span> i: <span class="ty">I64</span>; s: []<span class="ty">U8</span>; | |
| 89 | +<span class="kw">begin</span> | |
| 90 | + s := <span class="string">"four"</span>; | |
| 91 | + i := <span class="number">3</span>; | |
| 92 | + <span class="kw">if</span> i < <span class="ty">LEN</span>(s) <span class="kw">then</span> Out.str(<span class="string">"smaller\n"</span>); <span class="kw">end</span>; | |
| 93 | +<span class="kw">end</span>; | |
| 94 | + | |
| 95 | +<span class="kw">end</span> Mix.</code></pre> | |
| 96 | +<pre class="output term"><code><span class="cmd">$ raz Mix.raz</span> | |
| 97 | +Mix.raz:9:8: error: I64 and INT are different types | |
| 98 | + 9 | if i < LEN(s) then Out.str("smaller\n"); end; | |
| 99 | + | ^^^^^^^^^^ | |
| 100 | +help: convert one to the other's type, as in I64(LEN(s)) | |
| 101 | +raz: 1 error</code></pre> | |
| 102 | +<p>The fix is the conversion, written where it happens: <code>if i < I64(LEN(s))</code>. It costs nothing at run time and says what is meant.</p> | |
| 103 | +<h2>Bits and booleans</h2> | |
| 104 | +<p><code>#</code>, not <code><></code>, is "different". <code>and</code>, <code>or</code> and <code>not</code> are for <code>BOOL</code>s, and bind below the relations, so <code>i < n and a[i] # 0</code> needs no parentheses. <code>&</code>, <code>|</code>, <code>xor</code>, <code>~</code>, <code>shl</code> and <code>shr</code> are for the bits of integers. There is no conversion between <code>BOOL</code> and an integer: say what you mean with <code>if</code>.</p> | |
| 105 | +<div class="file"><span>Bits.raz</span></div><pre class="code"><code><span class="kw">module</span> Bits; | |
| 106 | +<span class="kw">import</span> Out; | |
| 107 | + | |
| 108 | +<span class="kw">proc</span> main*; | |
| 109 | +<span class="kw">var</span> flags, mask: <span class="ty">U8</span>; | |
| 110 | +<span class="kw">begin</span> | |
| 111 | + flags := <span class="number">0</span>; | |
| 112 | + flags := flags | <span class="number">1</span>; <span class="comment">(* set bit 0 *)</span> | |
| 113 | + flags := flags | (<span class="number">1</span> <span class="kw">shl</span> <span class="number">3</span>); <span class="comment">(* set bit 3 *)</span> | |
| 114 | + mask := <span class="number">0FH</span>; | |
| 115 | + Out.str(<span class="string">"flags 0x"</span>); Out.hex(<span class="ty">U64</span>(flags), <span class="number">2</span>); Out.ln; | |
| 116 | + Out.str(<span class="string">"and 0x"</span>); Out.hex(<span class="ty">U64</span>(flags & mask), <span class="number">2</span>); Out.ln; | |
| 117 | + Out.str(<span class="string">"xor 0x"</span>); Out.hex(<span class="ty">U64</span>(flags <span class="kw">xor</span> <span class="number">0FFH</span>), <span class="number">2</span>); Out.ln; | |
| 118 | + Out.str(<span class="string">"not 0x"</span>); Out.hex(<span class="ty">U64</span>(~flags), <span class="number">2</span>); Out.ln; | |
| 119 | + <span class="kw">if</span> (flags & <span class="number">8</span>) # <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"bit 3 is set\n"</span>); <span class="kw">end</span>; | |
| 120 | +<span class="kw">end</span>; | |
| 121 | + | |
| 122 | +<span class="kw">end</span> Bits.</code></pre> | |
| 123 | +<pre class="output"><code>flags 0x09 | |
| 124 | +and 0x09 | |
| 125 | +xor 0xF6 | |
| 126 | +not 0xF6 | |
| 127 | +bit 3 is set | |
| 128 | +</code></pre> | |
| 129 | +<h2>Reals</h2> | |
| 130 | +<p><code>F32</code> and <code>F64</code> are the reals. A real constant is written with a point, <code>1.5</code> or <code>2.0E-3</code>. <code>Fmt.real(x, places)</code> writes one with that many digits after the point, and <code>Math</code> has the functions.</p> | |
| 131 | +<div class="file"><span>Reals.raz</span></div><pre class="code"><code><span class="kw">module</span> Reals; | |
| 132 | +<span class="kw">import</span> Fmt, Math; | |
| 133 | + | |
| 134 | +<span class="kw">proc</span> main*; | |
| 135 | +<span class="kw">var</span> n: <span class="ty">INT</span>; x: <span class="ty">F64</span>; y: <span class="ty">F32</span>; | |
| 136 | +<span class="kw">begin</span> | |
| 137 | + n := <span class="number">22</span>; | |
| 138 | + x := <span class="ty">F64</span>(n) / <span class="number">7.0</span>; | |
| 139 | + y := <span class="ty">F32</span>(x); | |
| 140 | + Fmt.print(<span class="string">"22/7 = {}\n"</span>, [Fmt.real(x, <span class="number">6</span>)]); | |
| 141 | + Fmt.print(<span class="string">"as F32 = {}\n"</span>, [Fmt.real(<span class="ty">F64</span>(y), <span class="number">6</span>)]); | |
| 142 | + Fmt.print(<span class="string">"sqrt 2 = {}, pi = {}\n"</span>, [Fmt.real(Math.sqrt(<span class="number">2.0</span>), <span class="number">5</span>), Fmt.real(Math.pi, <span class="number">5</span>)]); | |
| 143 | + Fmt.print(<span class="string">"truncated: {} {}\n"</span>, [Fmt.int(<span class="ty">I64</span>(<span class="number">2.9</span>)), Fmt.int(<span class="ty">I64</span>(-<span class="number">2.9</span>))]); | |
| 144 | +<span class="kw">end</span>; | |
| 145 | + | |
| 146 | +<span class="kw">end</span> Reals.</code></pre> | |
| 147 | +<pre class="output"><code>22/7 = 3.142857 | |
| 148 | +as F32 = 3.142857 | |
| 149 | +sqrt 2 = 1.41421, pi = 3.14159 | |
| 150 | +truncated: 2 -2 | |
| 151 | +</code></pre> | |
| 152 | +<p>A real converts to an integer by rounding toward zero. Every variable starts at zero, a real's <code>0.0</code> and a <code>BOOL</code>'s <code>false</code> included, so there is no uninitialised value to be surprised by.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="modules.html">← Modules</a><a href="index.html">Contents</a><a class="next" href="procedures.html">Procedures and several results →</a></div></article></div> | |
| 59 | 153 | </main> |
| 60 | 154 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 61 | 155 | </body> |
| @@ -7,9 +7,9 @@ | ||
| 7 | 7 | <link rel="stylesheet" href="../style.css"> |
| 8 | 8 | </head> |
| 9 | 9 | <body> |
| 10 | -<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 10 | +<header><nav><a href="../index.html">raz</a><a href="../tour/index.html" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">Beyond Go</a><a href="../spec.html">Report</a><a href="../index.html#download">Download</a><a class="repo" href="https://github.com/ldiaz94/raz">GitHub</a></nav></header> | |
| 11 | 11 | <main> |
| 12 | -<div class="tour"><aside><h3>Raz</h3><ol start='1'> | |
| 12 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 13 | 13 | <li><a href="hello.html">Hello, world</a></li> |
| 14 | 14 | <li><a href="modules.html">Modules</a></li> |
| 15 | 15 | <li><a href="values.html">Values and conversions</a></li> |
| @@ -83,8 +83,175 @@ | ||
| 83 | 83 | 0 |
| 84 | 84 | 1 |
| 85 | 85 | </code></pre> |
| 86 | -<p>An enumeration is a list of names, in order; a <code>set of</code> it holds any choice of them, in the bits of a word, with <code>in</code>, <code>+</code> for union, <code>*</code> for intersection and <code>-</code> for difference.</p> | |
| 87 | -<p>A variant holds one of its cases, each with fields of its own, and <code>match</code> 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 <code>| else:</code> comes last. On an integer, <code>match</code> takes constants and ranges, and must have an <code>| else:</code>.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="records.html">← Records and pointers</a><a href="index.html">Contents</a><a class="next" href="memory.html">Memory and allocators →</a></div></article></div> | |
| 86 | +<h2>Enumerations</h2> | |
| 87 | +<p>An enumeration is a list of names, in order. They convert to their position and back, and a <code>for</code> loop can run over them. An integer that has no name at its position is a failed check, never a silent wrong value.</p> | |
| 88 | +<div class="file"><span>Days.raz</span></div><pre class="code"><code><span class="kw">module</span> Days; | |
| 89 | +<span class="kw">import</span> Out; | |
| 90 | + | |
| 91 | +<span class="kw">type</span> Day = (mon, tue, wed, thu, fri, sat, sun); | |
| 92 | + | |
| 93 | +<span class="kw">proc</span> name(d: Day): []<span class="ty">U8</span>; | |
| 94 | +<span class="kw">begin</span> | |
| 95 | + <span class="kw">match</span> d <span class="kw">of</span> | |
| 96 | + | mon: <span class="kw">return</span> <span class="string">"Monday"</span>; | |
| 97 | + | tue: <span class="kw">return</span> <span class="string">"Tuesday"</span>; | |
| 98 | + | wed: <span class="kw">return</span> <span class="string">"Wednesday"</span>; | |
| 99 | + | thu: <span class="kw">return</span> <span class="string">"Thursday"</span>; | |
| 100 | + | fri: <span class="kw">return</span> <span class="string">"Friday"</span>; | |
| 101 | + | sat: <span class="kw">return</span> <span class="string">"Saturday"</span>; | |
| 102 | + | sun: <span class="kw">return</span> <span class="string">"Sunday"</span>; | |
| 103 | + <span class="kw">end</span>; | |
| 104 | +<span class="kw">end</span>; | |
| 105 | + | |
| 106 | +<span class="kw">proc</span> main*; | |
| 107 | +<span class="kw">var</span> d: Day; | |
| 108 | +<span class="kw">begin</span> | |
| 109 | + <span class="kw">for</span> d := mon <span class="kw">to</span> sun <span class="kw">do</span> | |
| 110 | + Out.int(<span class="ty">I64</span>(d)); Out.str(<span class="string">" "</span>); Out.str(name(d)); | |
| 111 | + <span class="kw">if</span> d >= sat <span class="kw">then</span> Out.str(<span class="string">" (weekend)"</span>); <span class="kw">end</span>; | |
| 112 | + Out.ln; | |
| 113 | + <span class="kw">end</span>; | |
| 114 | + d := Day(<span class="number">4</span>); | |
| 115 | + Out.str(name(d)); Out.ln; | |
| 116 | +<span class="kw">end</span>; | |
| 117 | + | |
| 118 | +<span class="kw">end</span> Days.</code></pre> | |
| 119 | +<pre class="output"><code>0 Monday | |
| 120 | +1 Tuesday | |
| 121 | +2 Wednesday | |
| 122 | +3 Thursday | |
| 123 | +4 Friday | |
| 124 | +5 Saturday (weekend) | |
| 125 | +6 Sunday (weekend) | |
| 126 | +Friday | |
| 127 | +</code></pre> | |
| 128 | +<h2>Sets</h2> | |
| 129 | +<p>A <code>set of</code> an enumeration holds any choice of its names, in the bits of a word. <code>in</code> tests membership; <code>+</code> is union, <code>*</code> intersection and <code>-</code> difference; <code>{}</code> is the empty set. Sets are how Unix permissions, option flags and key modifiers are best written.</p> | |
| 130 | +<div class="file"><span>Perms.raz</span></div><pre class="code"><code><span class="kw">module</span> Perms; | |
| 131 | +<span class="kw">import</span> Out; | |
| 132 | + | |
| 133 | +<span class="kw">type</span> | |
| 134 | + Perm = (x, w, r); <span class="comment">(* bits 0, 1, 2, as chmod has them *)</span> | |
| 135 | + Perms = <span class="kw">set</span> <span class="kw">of</span> Perm; | |
| 136 | + | |
| 137 | +<span class="kw">proc</span> show(p: Perms); | |
| 138 | +<span class="kw">begin</span> | |
| 139 | + <span class="kw">if</span> r <span class="kw">in</span> p <span class="kw">then</span> Out.char(<span class="string">'r'</span>); <span class="kw">else</span> Out.char(<span class="string">'-'</span>); <span class="kw">end</span>; | |
| 140 | + <span class="kw">if</span> w <span class="kw">in</span> p <span class="kw">then</span> Out.char(<span class="string">'w'</span>); <span class="kw">else</span> Out.char(<span class="string">'-'</span>); <span class="kw">end</span>; | |
| 141 | + <span class="kw">if</span> x <span class="kw">in</span> p <span class="kw">then</span> Out.char(<span class="string">'x'</span>); <span class="kw">else</span> Out.char(<span class="string">'-'</span>); <span class="kw">end</span>; | |
| 142 | +<span class="kw">end</span>; | |
| 143 | + | |
| 144 | +<span class="kw">proc</span> main*; | |
| 145 | +<span class="kw">var</span> user, group, mine: Perms; | |
| 146 | +<span class="kw">begin</span> | |
| 147 | + user := {r, w, x}; | |
| 148 | + group := {r, x}; | |
| 149 | + show(user); Out.char(<span class="string">' '</span>); show(group); Out.ln; | |
| 150 | + show(user * group); Out.char(<span class="string">' '</span>); <span class="comment">(* both: r-x *)</span> | |
| 151 | + show(user - group); Out.char(<span class="string">' '</span>); <span class="comment">(* only user: -w- *)</span> | |
| 152 | + show(user - {w}); Out.ln; <span class="comment">(* r-x *)</span> | |
| 153 | + mine := group; | |
| 154 | + <span class="kw">if</span> mine = {r, x} <span class="kw">then</span> Out.str(<span class="string">"same as group\n"</span>); <span class="kw">end</span>; | |
| 155 | + Out.int(<span class="ty">I64</span>(<span class="ty">U8</span>(user))); Out.ln; <span class="comment">(* 7: a set is its bits *)</span> | |
| 156 | +<span class="kw">end</span>; | |
| 157 | + | |
| 158 | +<span class="kw">end</span> Perms.</code></pre> | |
| 159 | +<pre class="output"><code>rwx r-x | |
| 160 | +r-x -w- r-x | |
| 161 | +same as group | |
| 162 | +7 | |
| 163 | +</code></pre> | |
| 164 | +<h2>Variants</h2> | |
| 165 | +<p>A variant holds one of its cases, each with fields of its own, and <code>match</code> 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 <code>| else:</code> comes last, so adding a case to the type makes every <code>match</code> that forgot it a compile error.</p> | |
| 166 | +<div class="file"><span>Tokens.raz</span></div><pre class="code"><code><span class="kw">module</span> Tokens; | |
| 167 | +<span class="kw">import</span> Out; | |
| 168 | + | |
| 169 | +<span class="kw">type</span> | |
| 170 | + Token = <span class="kw">variant</span> | |
| 171 | + number(n: <span class="ty">INT</span>); | |
| 172 | + plus; | |
| 173 | + times; | |
| 174 | + word(s: []<span class="ty">U8</span>); | |
| 175 | + <span class="kw">end</span>; | |
| 176 | + | |
| 177 | +<span class="kw">proc</span> describe(t: Token); | |
| 178 | +<span class="kw">begin</span> | |
| 179 | + <span class="kw">match</span> t <span class="kw">of</span> | |
| 180 | + | number(n): Out.str(<span class="string">"number "</span>); Out.int(n); | |
| 181 | + | plus: Out.str(<span class="string">"plus"</span>); | |
| 182 | + | times: Out.str(<span class="string">"times"</span>); | |
| 183 | + | word(s): Out.str(<span class="string">"word '"</span>); Out.str(s); Out.char(<span class="string">'\''</span>); | |
| 184 | + <span class="kw">end</span>; | |
| 185 | + Out.ln; | |
| 186 | +<span class="kw">end</span>; | |
| 187 | + | |
| 188 | +<span class="comment">(* evaluates tokens in reverse Polish; assumes the input is well formed *)</span> | |
| 189 | +<span class="kw">proc</span> eval(ts: []Token): <span class="ty">INT</span>; | |
| 190 | +<span class="kw">var</span> stack: [<span class="number">16</span>]<span class="ty">INT</span>; top, i, b: <span class="ty">INT</span>; | |
| 191 | +<span class="kw">begin</span> | |
| 192 | + top := <span class="number">0</span>; | |
| 193 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(ts) - <span class="number">1</span> <span class="kw">do</span> | |
| 194 | + <span class="kw">match</span> ts[i] <span class="kw">of</span> | |
| 195 | + | number(n): stack[top] := n; <span class="ty">INC</span>(top); | |
| 196 | + | plus: b := stack[top - <span class="number">1</span>]; <span class="ty">DEC</span>(top); stack[top - <span class="number">1</span>] := stack[top - <span class="number">1</span>] + b; | |
| 197 | + | times: b := stack[top - <span class="number">1</span>]; <span class="ty">DEC</span>(top); stack[top - <span class="number">1</span>] := stack[top - <span class="number">1</span>] * b; | |
| 198 | + | <span class="kw">else</span>: | |
| 199 | + <span class="kw">end</span>; | |
| 200 | + <span class="kw">end</span>; | |
| 201 | + <span class="kw">return</span> stack[<span class="number">0</span>]; | |
| 202 | +<span class="kw">end</span>; | |
| 203 | + | |
| 204 | +<span class="kw">proc</span> main*; | |
| 205 | +<span class="kw">var</span> ts: [<span class="number">5</span>]Token; i: <span class="ty">INT</span>; | |
| 206 | +<span class="kw">begin</span> | |
| 207 | + ts := [number(<span class="number">3</span>), number(<span class="number">4</span>), plus, number(<span class="number">5</span>), times]; <span class="comment">(* (3 + 4) * 5 *)</span> | |
| 208 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4</span> <span class="kw">do</span> describe(ts[i]); <span class="kw">end</span>; | |
| 209 | + Out.int(eval(ts)); Out.ln; | |
| 210 | + describe(word(<span class="string">"hello"</span>)); | |
| 211 | +<span class="kw">end</span>; | |
| 212 | + | |
| 213 | +<span class="kw">end</span> Tokens.</code></pre> | |
| 214 | +<pre class="output"><code>number 3 | |
| 215 | +number 4 | |
| 216 | +plus | |
| 217 | +number 5 | |
| 218 | +times | |
| 219 | +35 | |
| 220 | +word 'hello' | |
| 221 | +</code></pre> | |
| 222 | +<h2>Matching integers</h2> | |
| 223 | +<p>On an integer, <code>match</code> takes constants and ranges, and must have an <code>| else:</code>. Characters are integers, so it is also how a scanner is written.</p> | |
| 224 | +<div class="file"><span>Classify.raz</span></div><pre class="code"><code><span class="kw">module</span> Classify; | |
| 225 | +<span class="kw">import</span> Out; | |
| 226 | + | |
| 227 | +<span class="kw">proc</span> kind(c: <span class="ty">I32</span>): []<span class="ty">U8</span>; | |
| 228 | +<span class="kw">begin</span> | |
| 229 | + <span class="kw">match</span> c <span class="kw">of</span> | |
| 230 | + | <span class="string">' '</span>, <span class="string">'\t'</span>, <span class="string">'\n'</span>: <span class="kw">return</span> <span class="string">"space"</span>; | |
| 231 | + | <span class="string">'0'</span> .. <span class="string">'9'</span>: <span class="kw">return</span> <span class="string">"digit"</span>; | |
| 232 | + | <span class="string">'a'</span> .. <span class="string">'z'</span>, <span class="string">'A'</span> .. <span class="string">'Z'</span>, <span class="string">'_'</span>: <span class="kw">return</span> <span class="string">"letter"</span>; | |
| 233 | + | <span class="kw">else</span>: <span class="kw">return</span> <span class="string">"other"</span>; | |
| 234 | + <span class="kw">end</span>; | |
| 235 | +<span class="kw">end</span>; | |
| 236 | + | |
| 237 | +<span class="kw">proc</span> main*; | |
| 238 | +<span class="kw">var</span> s: []<span class="ty">U8</span>; i: <span class="ty">INT</span>; | |
| 239 | +<span class="kw">begin</span> | |
| 240 | + s := <span class="string">"x1 + _y"</span>; | |
| 241 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> | |
| 242 | + Out.char(s[i]); Out.str(<span class="string">" is "</span>); Out.str(kind(<span class="ty">I32</span>(s[i]))); Out.ln; | |
| 243 | + <span class="kw">end</span>; | |
| 244 | +<span class="kw">end</span>; | |
| 245 | + | |
| 246 | +<span class="kw">end</span> Classify.</code></pre> | |
| 247 | +<pre class="output"><code>x is letter | |
| 248 | +1 is digit | |
| 249 | + is space | |
| 250 | ++ is other | |
| 251 | + is space | |
| 252 | +_ is letter | |
| 253 | +y is letter | |
| 254 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="records.html">← Records and pointers</a><a href="index.html">Contents</a><a class="next" href="memory.html">Memory and allocators →</a></div></article></div> | |
| 88 | 255 | </main> |
| 89 | 256 | <footer>raz is under the ISC license. <a href="https://github.com/ldiaz94/raz">Source</a>.</footer> |
| 90 | 257 | </body> |
| @@ -69,7 +69,7 @@ | ||
| 69 | 69 | .tour aside { font-family: system-ui, sans-serif; font-size: 14px; } |
| 70 | 70 | .tour aside h3 { margin: 1em 0 .2em; font-size: 12px; text-transform: uppercase; |
| 71 | 71 | letter-spacing: .08em; color: var(--muted); } |
| 72 | -.tour aside ol { margin: 0; padding-left: 1.5em; } .tour aside a { color: var(--fg); text-decoration: none; } | |
| 72 | +.tour aside ol { margin: 0; padding-left: 1.9em; } .tour aside a { color: var(--fg); text-decoration: none; } | |
| 73 | 73 | .tour aside a[aria-current] { color: var(--accent); font-weight: 700; } |
| 74 | 74 | @media (max-width: 55.99rem) { .tour aside { order: 2; border-top: 1px solid var(--line); } } |
| 75 | 75 | .tour article { min-width: 0; } |
| @@ -86,3 +86,7 @@ | ||
| 86 | 86 | .spec table { border-collapse: collapse; display: block; overflow-x: auto; font-size: 15px; } |
| 87 | 87 | .spec td, .spec th { border-bottom: 1px solid var(--line); padding: 3px 10px; text-align: left; } |
| 88 | 88 | .spec nav#TOC ul { list-style: none; padding-left: 1em; } |
| 89 | + | |
| 90 | +/* a shell session */ | |
| 91 | +pre.term::before { content: "terminal"; } | |
| 92 | +pre .cmd { color: #8fd18f; } |