From 54a45fc7b12bf7e4587234bf5c448d67954b2c2f Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:49:43 +0100 Subject: [PATCH] Report 10.22.6: two volumes, the language (doc/raz.md) and the library (doc/raz-lib.md) --- diff --git a/Makefile b/Makefile index 535c18f..ac50bec 100644 --- a/Makefile +++ b/Makefile @@ -104,7 +104,7 @@ @rloc -c src/*.raz # raz-lib(3), the library's manual page, made by tools/Doc.raz from -# its sources, in the order of the report's section 11 +# its sources, in the order of doc/raz-lib.md LIBDOC = Rt Mem Heap Arena Lock Thread.linux-x86_64 Out Sys.linux-x86_64 \ Str Bytes.x86_64 Buf Fmt List Map Sort Math Files Opt C @@ -118,8 +118,8 @@ # CI has neither pdf: build/raz.pdf -build/raz.pdf: doc/raz.md doc/report.css | build - pandoc doc/raz.md -s --toc --toc-depth=1 --shift-heading-level-by=-1 \ +build/raz.pdf: doc/raz.md doc/raz-lib.md doc/report.css | build + pandoc doc/raz.md doc/raz-lib.md -s --toc --toc-depth=1 --shift-heading-level-by=-1 \ --syntax-highlighting=none -c ../doc/report.css \ -o build/raz.html chromium --headless --no-pdf-header-footer --print-to-pdf=$@ build/raz.html 2>/dev/null diff --git a/PLAN.md b/PLAN.md index ee48ceb..8258c91 100644 --- a/PLAN.md +++ b/PLAN.md @@ -3,7 +3,7 @@ Work goes by milestones, each a release. A milestone says what it is for, what is in it and when it is done; its steps are commits, each stopping for the owner's review. A finished milestone is cut from this -file: git keeps the history, and the report's section 12 the language's. +file: git keeps the history, and the report's history, `doc/report-history.md`, the language's. v0.9.1, the latest release, is tagged by the owner's word. All before v0.7.1 is approved by the owner; v0.7.1, v0.8.0, v0.9.0 and v0.9.1 wait diff --git a/README.md b/README.md index 603c6fb..0dcd759 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ | Path | What | |---|---| -| `doc/raz.md` | The language report: the definition of raz | +| `doc/raz.md`, `doc/raz-lib.md` | The report: the language (volume 1) and the library (volume 2) | | `doc/compiler.md` | A guide to reading the compiler, file by file | | `doc/raz.1`, `doc/raz.7`, `doc/raz-tutorial.7` | The manual pages: the command, the language at a glance, a tour; `make man` makes the library's, raz-lib(3), from `lib/` | | `src/` | The compiler, in raz | @@ -157,7 +157,7 @@ - `extern` procedures and variables from C; code procedures written in the target's assembly language; `SYSCALL`. -The report, `doc/raz.md`, says all of it in about 2,000 lines. +The report, `doc/raz.md` and `doc/raz-lib.md`, says all of it in about 2,100 lines. ## The library diff --git a/doc/raz-lib.md b/doc/raz-lib.md new file mode 100644 index 0000000..6451c99 --- /dev/null +++ b/doc/raz-lib.md @@ -0,0 +1,618 @@ +## The library, volume 2 + +The second volume of the report on raz. The first, `doc/raz.md`, defines +the language; this one defines the modules that come with it, and +refers to the first's sections by number, as "section 6.8". Only the +core binds every implementation (appendix A of the first volume); the +rest is the standard library. + +Modules written in raz, in the compiler's `lib` directory: + +| Module | What | +|---|---| +| `Rt` | ending the program, `exit` and `atExit`; `stop`, which ends it with a message; `trace`, the calls under way; what the compiler's checks call when they fail | +| `Sys` | system calls: `open`, `openRead`, `create`, `read`, `write`, `seek`, `close`, `mmap`, `munmap`, `isTerminal`, `yield`, `exit`; files and directories, `rename`, `remove`, `removeDir`, `makeDir`, `chmod`, `symlink`, `readLink`, `info`, `openDir`, `nextEntry`, `closeDir`; the terminal, `rawMode`, `restoreMode`, `termSize`, `ready`; the environment, `env`, `workDir`, `setWorkDir`; programs, pipes and signals; time, `clock`, `now`, `sleep`; `random`; and sockets. One file per target, and `Sys.raz` over the C library for the others | +| `Out` | writing text and numbers to standard output, buffered; safe to call from several threads | +| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C | +| `Lock` | a lock for short sections, for C's threads and `Thread`'s alike | +| `Thread` | threads for a program without C: `spawn`, `join`, and `Mutex`; it says `link static` | +| `Mem` | `Allocator`, the interface of every allocator, and pages from the system | +| `Heap` | a general allocator, `Heap.heap`, safe to call from several threads; freeing a block twice, or one it never gave out, stops the program | +| `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator | +| `Str` | operations on `[]U8` strings: comparing, hashing, finding, UTF-8, reading a number | +| `Bytes` | searches of bytes, many at a time: `index`, `last`, `count` and `find` in a `[]U8`; one file per target where the target has instructions for it | +| `Buf` | a growable byte buffer | +| `Fmt` | formatted output: `Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.real(x, 2)])`, or into a `Buf` with `Fmt.write` | +| `List` | a generic singly linked list, `List(T)` | +| `Map` | a generic hash map, `Map(K, V; hash, eq)` | +| `Sort` | sorting a slice in place, `Sort(T; less)` | +| `Math` | roots, powers, logarithms, rounding and trigonometry, and `pi`, for `F64` | +| `Files` | an argument as a string, and a whole file read or written | +| `Opt` | a command line read through one table, by `getopt`'s rules with long options; its help and its mistakes | + +Lengths, counts, file descriptors, process ids and statuses are +`INT`s, and a character is an `I32`. What may pass an `INT` on a small +target is an `I64`: a file's size and position, a time in nanoseconds, +and a number read from text. + +What follows is each module's interface, as `tools/Doc.raz` prints it +from the module's file; `...` stands for fields that are the module's +own. A module's `main`, where it has one, is its test, and is left +out here. + +``` +module Rt; +const Full*: ERROR = "too many procedures to run at exit"; +proc atExit*(p: proc): ERROR; (* p run when the program ends by exit *) +proc exit*(status: INT); (* the atExit procedures, the last first, then the end *) +proc stop*(msg: []U8); (* msg on standard error, then exit with status 2 *) +proc trace*; (* the calls under way, and their variables, on standard error *) +``` + +`Rt` also holds what the compiler's checks call when they fail, and +the handlers of the signals that stop a program (section 10). `exit` +takes each procedure off the list before it runs it, so it runs once +even if it fails or calls `exit` itself; in a program that uses C, it +ends through C's `exit`, so that C flushes its buffers too. + +``` +module Mem; +type + Allocator* = record + alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *) + free*: proc(a: ^Allocator; p: ^U8); + end; +const Page* = 4096; +proc pages*(size: INT): ^U8; (* size bytes, in whole pages, zeroed; or nil *) +proc unmap*(p: ^U8; size: INT); (* pages given back *) +proc alloc*(a: ^Allocator; size, align: INT): ^U8; (* a^.alloc(a, size, align) *) +proc free*(a: ^Allocator; p: ^U8); (* a^.free(a, p) *) + +module Heap; +var heap*: ^Mem.Allocator; + +module Arena; +type Arena* = record + base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *) + ... +end; +proc init*(ar: ^Arena; size: INT): BOOL; (* an arena of size bytes; false if the system has none *) +proc reset*(ar: ^Arena); (* every allocation forgotten; the memory used again *) +proc done*(ar: ^Arena); (* its memory given back *) +``` + +`NEW(p, a)` calls `a^.alloc`. `Heap` is the general +allocator. An arena hands out memory from +one block: its `free` does nothing, and `reset` forgets everything. + +``` +module Lock; +type Lock* = record ... end; +proc take*(l: ^Lock); +proc give*(l: ^Lock); + +module Thread; +const Failed*: ERROR = "can't start a thread"; +type + Thread* = record ... end; + Mutex* = record ... end; (* zero is free *) +proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); (* p(arg) in a new thread *) +proc join*(t: ^Thread); (* waits for t to end, then frees its stack *) +proc lock*(m: ^Mutex); +proc unlock*(m: ^Mutex); +``` + +A `Lock` is for short sections: a thread that finds it taken tries +again, giving up the processor now and then. A `Mutex` sleeps. Each of +`Thread`'s threads runs on a stack of its own, with a page below it +that can't be touched, so that running off the stack stops the program. +A program that uses C makes its threads with C's `pthread_create`, and +so can't use `Thread`. + +``` +module Out; +proc str*(s: []U8); +proc char*(c: U8); +proc ln*; (* a line feed *) +proc int*(n: I64); (* n in decimal *) +proc hex*(n: U64; digits: INT); (* n in hexadecimal, digits digits at least *) +proc flush*; +``` + +**Out and C's stdio.** `Out` keeps a buffer of `Sys.outSize` bytes, +4 KB on Linux. 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`. A lock keeps +what each call writes together when threads write at once. C's `stdio` +keeps a buffer of its own for the same standard output. A program that +writes with both flushes one before writing with the other, or the +text comes out of order: + +``` +module Both; +import Out, C; (* C: printf, fflush and C's FILE *stdout *) + +proc main*; +begin + Out.str("from raz\n"); + Out.flush; + C.printf("from C\n"); + C.fflush(C.stdout); + Out.str("from raz again\n"); +end; + +end Both. +``` + +**Sys** gives every target the same procedures, so that a program +that needs only these runs wherever raz does: through system calls on +Linux, through the C library elsewhere. A result that can fail is a +number, minus an errno, as on Linux; 0 is success. + +``` +module Sys; +const + stdin* = 0; stdout* = 1; stderr* = 2; + outSize* = 4096; (* the bytes Out keeps; each target has its own *) + (* signals, by their numbers on Linux; each target has its own *) + sigHup* = 1; sigInt* = 2; sigQuit* = 3; sigKill* = 9; sigPipe* = 13; + sigTerm* = 15; sigChld* = 17; sigCont* = 18; sigStop* = 19; + sigTstp* = 20; sigTtin* = 21; sigTtou* = 22; sigWinch* = 28; + +type + Access* = (reading, writing, creating, exclusive, truncating, appending); + Accesses* = set of Access; + Info* = record + size*: I64; (* in bytes *) + mtime*: I64; (* when its contents last changed, in nanoseconds since 1970 *) + mode*: INT; (* its permission bits, as chmod takes them: 1EDH is rwxr-xr-x *) + dir*: BOOL; (* a directory *) + file*: BOOL; (* a regular file: not a directory, device, pipe or socket *) + symlink*: BOOL; (* the path itself is a symbolic link *) + end; + Dir* = record ... end; (* an open directory; its fields are the target's *) + Program* = record + path*: []U8; + args*: [][]U8; (* the first is its name *) + env*: [][]U8; (* NAME=value, each added to this program's environment *) + onlyEnv*: BOOL; (* env is its whole environment *) + dir*: []U8; (* its working directory; "" for this program's *) + fds*: [3]INT; (* its standard input, output and error; 0 for this program's own *) + group*: INT; (* the process group it joins: 0 for this program's, -1 a new one it leads *) + foreground*: BOOL; (* its group takes the terminal on standard input *) + tty*: INT; (* a pseudo-terminal's fd, to start a session on; 0 for none *) + end; + Status* = (running, exited, killed, stopped); + +proc write*(fd: INT; s: []U8): INT; (* the bytes written *) +proc read*(fd: INT; buf: []U8): INT; (* the bytes read; 0 at the end *) +proc open*(path: []U8; how: Accesses): INT; (* its fd *) +proc openRead*(path: []U8): INT; (* open(path, {reading}) *) +proc create*(path: []U8): INT; (* open(path, {writing, creating, truncating}) *) +proc seek*(fd: INT; pos: I64; fromEnd: BOOL): I64; (* the new position *) +proc close*(fd: INT); +proc isTerminal*(fd: INT): BOOL; +proc mmap*(size: INT): ^U8; (* size bytes of zeroed memory, in whole pages; or nil *) +proc munmap*(p: ^U8; size: INT); +proc yield*; (* the processor given to another thread *) +proc exit*(status: INT); (* the program ended at once, without Rt's atExit *) + +proc rename*(old, new: []U8): INT; (* replaces what new names *) +proc remove*(path: []U8): INT; (* a file, not a directory *) +proc removeDir*(path: []U8): INT; (* an empty directory *) +proc makeDir*(path: []U8): INT; (* readable by all, writable by its owner *) +proc chmod*(path: []U8; mode: INT): INT; +proc symlink*(target, path: []U8): INT; (* path made a link to target *) +proc readLink*(path: []U8): ([]U8, INT); (* what the link names, good until the next call *) +proc info*(path: []U8): (Info, INT); (* following a symbolic link *) +proc space*(path: []U8): (I64, I64, INT); (* the bytes free and in all on path's file system *) + +proc openDir*(d: ^Dir; path: []U8): INT; +proc nextEntry*(d: ^Dir): ([]U8, BOOL); (* a name, good until the next call; false at the end *) +proc closeDir*(d: ^Dir); + +proc rawMode*(fd: INT): BOOL; (* the terminal on fd: no echo, no lines, no signals *) +proc restoreMode*(fd: INT); (* as rawMode found it *) +proc termSize*(fd: INT): (INT, INT); (* columns and rows; 80 and 24 if unknown *) +proc ready*(fd, ms: INT): BOOL; (* something to read within ms, or ever if ms < 0 *) +proc readyOf*(fds: []INT; ms: INT): INT; (* the first of fds with something to read within ms, or -1 *) +proc readyFor*(reads, writes: []INT; ms: INT): INT; (* readyOf, and the first of writes with room to write *) +proc setBlocking*(fd: INT; yes: BOOL): INT; (* if not yes, a read or write that would wait is -11 at once *) + +proc env*(name: []U8): []U8; (* the environment variable's value; "" if unset *) +proc workDir*: ([]U8, INT); (* the working directory, good until the next call *) +proc setWorkDir*(path: []U8): INT; + +proc pipe*: (INT, INT); (* the fd to read and the fd to write; or minus an errno and -1 *) +proc openPty*: INT; (* a pseudo-terminal: the fd of its controlling side *) +proc setTermSize*(fd, cols, rows: INT): INT; (* the size its programs are told of *) +proc spawn*(p: Program): INT; (* a program started: its process id *) +proc wait*(pid: INT; block: BOOL): (INT, Status, INT); (* which program, how, and its code *) +proc kill*(pid, signal: INT): INT; +proc pid*: INT; (* this program's process id *) +proc setGroup*(pid, group: INT): INT; (* pid 0 is this program; group 0 a new one pid leads *) +proc foreground*(fd, group: INT): INT; (* the terminal on fd gives its keys to group *) +proc foregroundOf*(fd: INT): INT; (* the group the terminal on fd gives its keys to *) + +proc catch*(sigs: []INT): INT; (* sigs caught: an fd to wait on *) +proc caught*(fd: INT): INT; (* the next signal caught, or 0 if none is waiting *) +proc ignore*(sig: INT; yes: BOOL): INT; (* sig ignored; or, if not yes, back to what it does at first *) + +proc clock*: I64; (* nanoseconds, on a clock that only goes forward *) +proc now*: I64; (* nanoseconds since 1970-01-01, UTC *) +proc sleep*(ms: INT); +proc random*(b: []U8); (* b filled with random bytes *) + +proc connect*(path: []U8): INT; (* a stream socket, connected to the Unix socket at path: its fd *) +proc connectTcp*(addr: []U8; port: INT): INT; (* addr an IPv4 or IPv6 address, as numbers *) +proc connectUdp*(addr: []U8; port: INT): INT; +proc listen*(path: []U8): INT; (* a Unix socket made at path, taking connections *) +proc listenTcp*(addr: []U8; port: INT): INT; +proc accept*(fd: INT): INT; (* the next connection, waiting for one *) +proc send*(fd: INT; s: []U8): INT; (* write, to a socket: -32 (EPIPE), not a signal, if it is closed *) +``` + +`info` follows a symbolic link: `size`, `dir` and `file` are those of +what it names, and `symlink` says the path was a link, so that a program walking +a tree can choose not to follow one back up it. A link to nothing is +`-ENOENT`, as a missing file is. `file` lets a walk open only what +holds data: opening a pipe would wait for a program to write to it. + +`nextEntry` gives every name in the directory except `.` and `..`, in +no particular order. `rawMode` turns off what the terminal does with +keys before the program reads them (echo, line editing, signals, flow +control), and NL to CR NL on output. A program that turns it on +restores it before it ends: `Rt.atExit` is the place. + +**Files.** `open` gives a file for what `how` asks: `reading`, +`writing` or both; `creating` it if it is missing, readable by all and +writable by its owner; with `exclusive`, failing with -17 (EEXIST) if +it is there, as a program does that makes a lock or a file of its +own; `truncating` it to nothing; `appending`, each write going to its +end, however other programs write it too. `seek` moves to `pos` from +the start of the file, or from its end if `fromEnd`, where a negative +`pos` reads back from the end. `Info.mtime` is what a program checks +to see whether a file changed under it; `Info.mode` holds the nine +bits of `rwxrwxrwx`, and `chmod` sets them, 1EDH (755) for a program, +1A4H (644) for data. + +**Programs.** `openPty` makes a pseudo-terminal, a terminal that a +program, a terminal emulator, plays the screen and the keyboard of: +what it writes to the fd is typed, and what the programs on the +terminal write it reads. + +`spawn` starts the program at `p.path`, with `p.args` as its +arguments, the first being its name. Its environment is this +program's with each `NAME=value` of `p.env` added or put in place of +the old value, or, if `p.onlyEnv`, `p.env` alone. It starts in +`p.dir`. Its standard input, output and error are `p.fds`; a 0 gives +it this program's own, so `{path: "/bin/ls", args: ["ls"]}` runs +`ls` as a shell runs it, with every other field zero. It gets no +other open file, every signal does what it does at first, and none +is blocked. If `p.tty` is a pseudo-terminal's fd, the program starts a +session on that terminal: it is its controlling terminal, and its +standard input, output and error, and `p.fds` and `p.group` are not +used. + +`p.group` puts the program in a process group, the programs that a +shell's job is made of: -1 makes it the first of a new group, whose +number is its process id, and the other programs of the job join that +number. The terminal gives its keys, and the signals of Ctrl-C and +Ctrl-Z, to one group, the one in its foreground: `p.foreground` puts +the program's group there before it starts, and `foreground` puts any +group there, as a shell does to take the terminal back. `setGroup` +moves a program to a group, as the shell does for each program it +starts, for whichever of the two runs first; a shell runs in a group +of its own, `setGroup(0, 0)`. + +`wait` waits for the program `pid` to change, or for any of this +program's if `pid` is -1, and says which one, and how: `exited`, with +its exit status; `killed`, with the number of the signal that ended +it; or `stopped`, by Ctrl-Z or a signal, with the signal's number. +Without `block` it doesn't wait, and is 0 and `running` if no program +changed. A program that has nothing to wait for is -10 (ECHILD). +`kill` sends a program a signal, `sigTerm` to end it; to a group, if +`pid` is minus its number. + +**Signals.** `catch` takes the signals `sigs` away from what they +would do, ending the program most of them, and gives an fd that is +ready to read when one comes, so that a program waits for signals with +`ready` and `readyOf` as it waits for keys or a server. `caught` gives +each signal that came, in turn. A later `catch` adds to the signals +caught and gives the same fd. Catching `sigKill` or `sigStop`, or the +signals `Rt` reports, SIGSEGV and SIGFPE, is -22 (EINVAL). `ignore` +makes a signal do nothing, as a shell ignores `sigTtou` so that it can +take its terminal back, and `ignore(sig, false)` gives it back what it +does at first. A program that `spawn` starts begins with neither. + +**Time.** `clock` is for measuring how long something takes: it never +goes back, and says nothing of the date. `now` is the date and time, +which a person or the network may set back. `sleep` waits `ms` +milliseconds. + +**Sockets.** `connect` is for talking to a server on the same machine, +an X server at `/tmp/.X11-unix/X0` say; `connectTcp` for one across +the network, given its address as numbers, `"127.0.0.1"` or `"::1"`: +turning a name into an address is a library's work over these. +`connectUdp` gives a socket of datagrams, each `send` one message to +that address and each `read` one message from it, as a program asks a +name server. What a socket receives comes by `read`, what it sends goes +by `send`, and `close` ends it. `send` is `write` for a socket, except +when the other end has closed it: `write` would stop the program with +the signal SIGPIPE, where `send` returns -32 (EPIPE), so that a +program learns its server has gone and can end as it wants. +`listen` and `listenTcp` are the other side: a server's socket, on +`path`, which must not be there yet, or on `port` at `addr`, +`"0.0.0.0"` or `"::"` for every address the machine has; `accept` +gives each connection that comes, as a socket of its own. + +`readyOf` waits on several file descriptors at once, as a program does +that listens to a server and a terminal both; a descriptor at its end, +or failed, counts as ready, since a read of it won't wait. It looks at +the first 64 of `fds`, and `connect` and `listen` take a path of at +most 107 bytes, as `struct sockaddr_un` holds; a longer one is -36 +(ENAMETOOLONG). + +A program that both reads from a descriptor and writes much to it, as +a terminal writes what is pasted to its program while it reads what +the program writes back, must not wait on either: the program may be +waiting for its own writes to be read. `setBlocking(fd, false)` has a +read or a write on `fd` that would wait return -11 (EAGAIN) at once, +a write having written what there was room for; `readyFor` waits, as +`readyOf` does, for something to read on any of `reads` or for room to +write on any of `writes`. A descriptor in both is given once, when it +is ready for either; the 64 it looks at are `reads`, then `writes`. + +**Strings, buffers and collections.** + +``` +module Str; +proc cmp*(a, b: []U8): INT; (* -1, 0 or 1 as a sorts before, with or after b, byte by byte *) +proc eq*(a, b: []U8): BOOL; +proc copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL); (* s's bytes in memory from a; false if a has none *) +proc hash*(s: []U8): U64; (* FNV-1a, 64 bits *) +proc find*(s, sub: []U8): INT; (* where sub first starts in s, or -1 *) +proc hasPrefix*(s, p: []U8): BOOL; +proc encode*(c: I32): ([4]U8, INT); (* c in UTF-8: its bytes, and how many *) +proc decode*(s: []U8): (I32, INT); (* the character s starts with, and its length in bytes *) +proc toInt*(s: []U8): (I64, BOOL); (* s, in decimal; false if it isn't a number an I64 holds *) +proc le*(s: []U8): U64; (* s, at most 8 bytes, the first the lowest *) +proc be*(s: []U8): U64; (* s, at most 8 bytes, the first the highest *) +proc putLE*(s: []U8; v: U64); (* v into s, the lowest byte first *) +proc putBE*(s: []U8; v: U64); (* v into s, the highest byte first *) + +module Buf; +type Buf* = record len*: INT; ... end; +proc init*(b: ^Buf; a: ^Mem.Allocator); +proc room*(b: ^Buf; n: INT): BOOL; (* room for n more bytes; false if the allocator has none *) +proc add*(b: ^Buf; c: U8); +proc str*(b: ^Buf; s: []U8); +proc bytes*(b: ^Buf): []U8; (* what it holds, until it next grows *) +proc reset*(b: ^Buf); (* emptied, its memory kept *) +proc done*(b: ^Buf); (* its memory given back *) + +module Fmt; +type Arg* = variant + int(i: I64); + uint(u: U64); + hex(h: U64); + str(s: []U8); + char(c: U8); + bool(b: BOOL); + real(r: F64; places: INT); +end; +proc print*(f: []U8; args: []Arg); (* to standard output *) +proc write*(b: ^Buf.Buf; f: []U8; args: []Arg); (* added to b *) + +module List(T); +type + Node* = record next*: ^Node; val*: T; end; + List* = record head*: ^Node; len*: INT; ... end; +proc init*(l: ^List; a: ^Mem.Allocator); +proc push*(l: ^List; v: T): BOOL; (* v at the front; false if the allocator has no room *) +proc pop*(l: ^List): (T, BOOL); (* the front value, taken off; false if the list is empty *) +proc reverse*(l: ^List); +proc clear*(l: ^List); + +module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL); +type Map* = record len*: INT; ... end; +proc init*(m: ^Map; a: ^Mem.Allocator); +proc put*(m: ^Map; k: K; v: V): BOOL; (* k now maps to v; false if there was no room *) +proc remove*(m: ^Map; k: K): BOOL; (* false if k wasn't there *) +proc get*(m: ^Map; k: K): (V, BOOL); (* what k maps to, and whether it maps to anything *) +proc next*(m: ^Map; i: INT): (INT, K, V); (* the entry after i *) + +module Sort(T; less: proc(a, b: T): BOOL); +proc sort*(s: []T); + +module Math; +const pi* = 3.141592653589793; +proc sqrt*(x: F64): F64; +proc pow*(x, y: F64): F64; (* x to the power y *) +proc floor*(x: F64): F64; +proc ceil*(x: F64): F64; +proc round*(x: F64): F64; (* to the nearest whole number; a half away from 0 *) +proc exp*(x: F64): F64; +proc ln*(x: F64): F64; +proc log2*(x: F64): F64; +proc log10*(x: F64): F64; +proc sin*(x: F64): F64; +proc cos*(x: F64): F64; +proc tan*(x: F64): F64; +proc asin*(x: F64): F64; (* from -pi/2 to pi/2 *) +proc acos*(x: F64): F64; (* from 0 to pi *) +proc atan*(x: F64): F64; (* from -pi/2 to pi/2 *) +proc atan2*(y, x: F64): F64; (* the angle of (x, y) from the x axis, from -pi to pi *) +``` + +A `Buf`, a `List` and a `Map` take their memory from the allocator +`init` gives them. `Fmt`'s format takes the next argument at each +`{}`; `{{` and `}}` stand for `{` and `}`. A `Map` hashes and +compares its keys with the procedures it is given: +`import Count := Map([]U8, INT, Str.hash, Str.eq);`. + +`Str` reads and writes UTF-8. `encode` writes a character, of at most +10FFFFH, in one to four bytes; a number that isn't one becomes FFFDH, +the character that stands for a wrong one. `decode` reads the first +character of `s`, and gives FFFDH and 1 for a byte that doesn't start +one rightly, and 0 and 0 for an empty `s`. `toInt` reads a decimal +number, with a `-` or `+` before it if any, and nothing else. + +`le` and `be` read an unsigned number of up to 8 bytes in a fixed +order, little-endian or big-endian, whatever the machine's own, and +`putLE` and `putBE` write one; more than 8 bytes stops the program. +They are how a file format or a network protocol is read and written: + +``` +len := U32(Str.le(header[4..8])); +Str.putBE(packet[0..2], U64(port)); +``` + +`Map.next` walks a map: from 0, it gives the next entry and the number +to pass for the one after it, and -1 when there are no more. A walk +sees each entry once if the map doesn't change during it: + +``` +i, k, v := Names.next(ADR(names), 0); +while i >= 0 do + Fmt.print("{} is {}\n", [Fmt.str(k), Fmt.int(v)]); + i, k, v := Names.next(ADR(names), i); +end; +``` + +`Sort.sort` puts `s` in the order `less` gives, in place, without +memory of its own, in time `n log n` at most; two elements equal by +`less` may change places. `Math`'s procedures are as C's `math.h` +has them, to within the last bit or so. `Fmt.real(x, places)` writes +`x` with `places` digits after the point, at most 9, rounded to the +nearest; from 1e15 on, with an exponent, as `1.50e17`; and `nan`, +`inf` and `-inf` as themselves. + +**Files and Opt** are what most programs need of their command line. + +``` +module Files; +proc arg*(i: INT): []U8; (* argument i; 0 is the program's name *) +proc read*(path: []U8; b: ^Buf.Buf): BOOL; (* the whole file added to b *) +proc write*(path, data: []U8): BOOL; (* the file made to hold data *) + +module Opt; +type + Row* = variant + usage(scope, line: []U8); (* a synopsis line, without "usage: " *) + sub(scope, name, help: []U8); (* a subcommand *) + option(scope: []U8; letter: U8; long, value, help: []U8); + end; + Parser* = record + letter*: U8; (* the option just read *) + value*: []U8; (* its value; "" for a flag *) + long*: BOOL; (* it was written by its long name *) + ... + end; +proc init*(p: ^Parser; name: []U8; table: []Row); (* the arguments from 1 on, by table *) +proc next*(p: ^Parser): BOOL; (* the next option; false when they end *) +proc operand*(p: ^Parser): ([]U8, BOOL); (* the next operand; false when there are no more *) +proc scope*(p: ^Parser; name: []U8); (* subcommand name's options, from the word after it *) +proc number*(p: ^Parser; lo, hi: I64): I64; (* the value just read, a number from lo to hi *) +proc fail*(p: ^Parser; text: []U8); (* the program's own mistake *) +``` + +`Opt` reads a command line by the rules of the C library's `getopt`, +with GNU's long options, so that a program's options behave as every +other Unix program's. The program describes itself once, in a table of +`Row`s: its synopsis lines, its subcommands and its options. The help +and the messages for mistakes are made from the table, so they can't +drift from it; the program's test of `p.letter` is the only other +place an option appears. The parser is a record the program owns, and +the table a slice it keeps as long as the parser: a literal written in +the call to `init` lives as long as the procedure that makes it. + +A row's `scope` is `""` for the program itself, or a subcommand's +name: `"start"`, or `"remote.add"` for a subcommand of `remote`. An +option has a `letter`, a `long` name, or both. One with a long name +only has a key of its own below `'!'` for a letter, so that the +program can tell it from the others. With a `value`, the name the +help and the messages give it, the option takes a value; with `""` it +is a flag. + +``` +const wait = 1; (* the key of --wait, which has no letter *) +... +Opt.init(ADR(p), "keep", [ + Opt.usage("", "keep [-v] [--wait secs] start ..."), + Opt.sub("", "start", "start a job"), + Opt.option("", 'v', "verbose", "", "say more"), + Opt.option("", wait, "wait", "secs", "give the job secs to start"), + Opt.usage("start", "keep start [-b label] name command [argument ...]"), + Opt.option("start", 'b', "bar", "label", "show the job in the bar as label")]); +while Opt.next(ADR(p)) do + if p.letter = 'v' then verbose := true; + elsif p.letter = wait then secs := Opt.number(ADR(p), 1, 600); + end; +end; +w, ok := Opt.operand(ADR(p)); +if not ok or (w # "start") then Opt.fail(ADR(p), "no command; see keep -h"); end; +Opt.scope(ADR(p), "start"); +while Opt.next(ADR(p)) do + if p.letter = 'b' then bar := p.value; end; +end; +job, ok := Opt.operand(ADR(p)); +``` + +The rules are `getopt`'s: + +- Flags may share a dash: `-lw` is `-l -w`. A letter's value is the + rest of its word, `-bdev`, or the whole next word, `-b dev`, even one + that starts with a dash or is empty; in a group, the first letter + that takes a value takes the rest, `-qn12`. +- A long option is written in full, with its value after a `=` or in + the next word: `--bar=dev`, `--bar dev`. An abbreviation is unknown, + not guessed, so that adding an option never breaks a script. A value + given to a flag, `--follow=x`, is a mistake. +- `--` ends the options, and isn't an operand; `-` alone is one. The + options end at the first operand, so in `keep start site python -m + http.server` the `-m` is python's. +- Each scope has its own options. An option given twice is read twice. + +`number` reads the value as `Str.toInt` does. `operand` reads what +options are left first, and the program doesn't see them. + +`-h` or `--help` among a scope's options prints its help on standard +output and ends the program with status 0. `init` and `scope` answer +it, looking through the scope's options before `next` gives one, so +that the program has done nothing yet: `keep -v -h -x` prints the +help, and the program never sees `-v`, nor the mistake. The help is +the scope's synopsis lines, a blank line, and its subcommands, its +options and the help itself, each with its line of help: + +``` +usage: keep start [-b label] name command [argument ...] + + -b, --bar label show the job in the bar as label + -h, --help print this and exit +``` + +A scope with several synopsis lines has the others indented under the +first; one with none, `usage:` and its words, as `usage: keep start`. + +A mistake on the command line is a sentence on standard error, the +program's name first, then the scope's synopsis lines, as the help +begins, and status 2: + +``` +keep: unknown option -x +usage: keep start [-b label] name command [argument ...] +``` + +The sentences are `unknown option -x` (or `--name`, up to its `=`), +`-b needs a label`, `--follow takes no value` and `--wait wants a +number from 1 to 600, not '0'`. `fail` writes the program's own +mistakes the same way, but alone, so that the sentence can say where +the help is: `keep: no command; see keep -h`. + +A mistake in the table is the program's, not its user's. `init` checks +the table before it reads a word, and ends the program with status 1: +`keep: option table, row 3: the option is in the scope already`. The +others are an option with neither a letter nor a long name, a long +name with `=` in it, a letter `-`, and `-h` or `--help` in the table, +since they are `Opt`'s. diff --git a/doc/raz.md b/doc/raz.md index 83429a2..94339f9 100644 --- a/doc/raz.md +++ b/doc/raz.md @@ -6,10 +6,14 @@ make system calls and call C libraries. It has no garbage collector and no hidden run time: what the program does is what its text says. +This is the first volume of the report: the language, what an +implementation chooses, and the grammar. The second, `doc/raz-lib.md`, +is the library, which sections 3 and 10 and appendix A name. + This report defines the language. It is short on purpose. Whatever it doesn't allow, raz doesn't have. -This is version 2026-10.21 of the report; section 12 says where each +This is version 2026-10.21 of the report; section 11 says where each version's changes are told. 2026-10.11 and 2026-10.12 are a thaw the owner chose, for a language anyone can build again. They break programs written for 2026-10.10 and before: for 2026-10.9, say, the report of compiler @@ -233,7 +237,7 @@ **Names are flat.** The names of a program's modules are one space, with no packages or paths. So the names of the library's modules -(section 11) are kept for it: a program or another library doesn't +(the library, `doc/raz-lib.md`) are kept for it: a program or another library doesn't name a module of its own `Arena`, `Buf`, `C`, `Files`, `Fmt`, `Heap`, `List`, `Lock`, `Map`, `Math`, `Mem`, `Opt`, `Out`, `Rt`, `Sort`, `Str`, `Sys` or `Thread`, nor any name the library takes later. The @@ -447,7 +451,7 @@ The bytes of a value of more than one byte are in the target's order (appendix A). A file or a message in an order of its own is read and written a byte at a time, as `Str.le`, `Str.be`, `Str.putLE` and -`Str.putBE` do (section 11). +`Str.putBE` do (the library, `doc/raz-lib.md`). ### 5.6 Variants @@ -795,7 +799,7 @@ `NEW(p, a)` calls `a^.alloc(a, SIZE(T), A)`, where `A` is the alignment of `T`, and zeroes the bytes it gets if they aren't `nil`. -`Mem.Allocator` (section 11) is the one type of the library the +`Mem.Allocator` (the library, `doc/raz-lib.md`) is the one type of the library the language names. `COPY` is a statement, as `INC` is. It copies the bytes of `LEN(s)` @@ -1326,622 +1330,9 @@ valid, and an implementation may warn of it. The text of its messages, how many it reports and which warnings it gives are its own (appendix A). - -## 11. The library - -Modules written in raz, in the compiler's `lib` directory: - -| Module | What | -|---|---| -| `Rt` | ending the program, `exit` and `atExit`; `stop`, which ends it with a message; `trace`, the calls under way; what the compiler's checks call when they fail | -| `Sys` | system calls: `open`, `openRead`, `create`, `read`, `write`, `seek`, `close`, `mmap`, `munmap`, `isTerminal`, `yield`, `exit`; files and directories, `rename`, `remove`, `removeDir`, `makeDir`, `chmod`, `symlink`, `readLink`, `info`, `openDir`, `nextEntry`, `closeDir`; the terminal, `rawMode`, `restoreMode`, `termSize`, `ready`; the environment, `env`, `workDir`, `setWorkDir`; programs, pipes and signals; time, `clock`, `now`, `sleep`; `random`; and sockets. One file per target, and `Sys.raz` over the C library for the others | -| `Out` | writing text and numbers to standard output, buffered; safe to call from several threads | -| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C | -| `Lock` | a lock for short sections, for C's threads and `Thread`'s alike | -| `Thread` | threads for a program without C: `spawn`, `join`, and `Mutex`; it says `link static` | -| `Mem` | `Allocator`, the interface of every allocator, and pages from the system | -| `Heap` | a general allocator, `Heap.heap`, safe to call from several threads; freeing a block twice, or one it never gave out, stops the program | -| `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator | -| `Str` | operations on `[]U8` strings: comparing, hashing, finding, UTF-8, reading a number | -| `Bytes` | searches of bytes, many at a time: `index`, `last`, `count` and `find` in a `[]U8`; one file per target where the target has instructions for it | -| `Buf` | a growable byte buffer | -| `Fmt` | formatted output: `Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.real(x, 2)])`, or into a `Buf` with `Fmt.write` | -| `List` | a generic singly linked list, `List(T)` | -| `Map` | a generic hash map, `Map(K, V; hash, eq)` | -| `Sort` | sorting a slice in place, `Sort(T; less)` | -| `Math` | roots, powers, logarithms, rounding and trigonometry, and `pi`, for `F64` | -| `Files` | an argument as a string, and a whole file read or written | -| `Opt` | a command line read through one table, by `getopt`'s rules with long options; its help and its mistakes | - -Lengths, counts, file descriptors, process ids and statuses are -`INT`s, and a character is an `I32`. What may pass an `INT` on a small -target is an `I64`: a file's size and position, a time in nanoseconds, -and a number read from text. - -What follows is each module's interface, as `tools/Doc.raz` prints it -from the module's file; `...` stands for fields that are the module's -own. A module's `main`, where it has one, is its test, and is left -out here. - -``` -module Rt; -const Full*: ERROR = "too many procedures to run at exit"; -proc atExit*(p: proc): ERROR; (* p run when the program ends by exit *) -proc exit*(status: INT); (* the atExit procedures, the last first, then the end *) -proc stop*(msg: []U8); (* msg on standard error, then exit with status 2 *) -proc trace*; (* the calls under way, and their variables, on standard error *) -``` - -`Rt` also holds what the compiler's checks call when they fail, and -the handlers of the signals that stop a program (section 10). `exit` -takes each procedure off the list before it runs it, so it runs once -even if it fails or calls `exit` itself; in a program that uses C, it -ends through C's `exit`, so that C flushes its buffers too. - -``` -module Mem; -type - Allocator* = record - alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *) - free*: proc(a: ^Allocator; p: ^U8); - end; -const Page* = 4096; -proc pages*(size: INT): ^U8; (* size bytes, in whole pages, zeroed; or nil *) -proc unmap*(p: ^U8; size: INT); (* pages given back *) -proc alloc*(a: ^Allocator; size, align: INT): ^U8; (* a^.alloc(a, size, align) *) -proc free*(a: ^Allocator; p: ^U8); (* a^.free(a, p) *) - -module Heap; -var heap*: ^Mem.Allocator; -module Arena; -type Arena* = record - base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *) - ... -end; -proc init*(ar: ^Arena; size: INT): BOOL; (* an arena of size bytes; false if the system has none *) -proc reset*(ar: ^Arena); (* every allocation forgotten; the memory used again *) -proc done*(ar: ^Arena); (* its memory given back *) -``` - -`NEW(p, a)` calls `a^.alloc`. `Heap` is the general -allocator. An arena hands out memory from -one block: its `free` does nothing, and `reset` forgets everything. - -``` -module Lock; -type Lock* = record ... end; -proc take*(l: ^Lock); -proc give*(l: ^Lock); - -module Thread; -const Failed*: ERROR = "can't start a thread"; -type - Thread* = record ... end; - Mutex* = record ... end; (* zero is free *) -proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); (* p(arg) in a new thread *) -proc join*(t: ^Thread); (* waits for t to end, then frees its stack *) -proc lock*(m: ^Mutex); -proc unlock*(m: ^Mutex); -``` - -A `Lock` is for short sections: a thread that finds it taken tries -again, giving up the processor now and then. A `Mutex` sleeps. Each of -`Thread`'s threads runs on a stack of its own, with a page below it -that can't be touched, so that running off the stack stops the program. -A program that uses C makes its threads with C's `pthread_create`, and -so can't use `Thread`. - -``` -module Out; -proc str*(s: []U8); -proc char*(c: U8); -proc ln*; (* a line feed *) -proc int*(n: I64); (* n in decimal *) -proc hex*(n: U64; digits: INT); (* n in hexadecimal, digits digits at least *) -proc flush*; -``` - -**Out and C's stdio.** `Out` keeps a buffer of `Sys.outSize` bytes, -4 KB on Linux. 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`. A lock keeps -what each call writes together when threads write at once. C's `stdio` -keeps a buffer of its own for the same standard output. A program that -writes with both flushes one before writing with the other, or the -text comes out of order: - -``` -module Both; -import Out, C; (* C: printf, fflush and C's FILE *stdout *) - -proc main*; -begin - Out.str("from raz\n"); - Out.flush; - C.printf("from C\n"); - C.fflush(C.stdout); - Out.str("from raz again\n"); -end; - -end Both. -``` - -**Sys** gives every target the same procedures, so that a program -that needs only these runs wherever raz does: through system calls on -Linux, through the C library elsewhere. A result that can fail is a -number, minus an errno, as on Linux; 0 is success. - -``` -module Sys; -const - stdin* = 0; stdout* = 1; stderr* = 2; - outSize* = 4096; (* the bytes Out keeps; each target has its own *) - (* signals, by their numbers on Linux; each target has its own *) - sigHup* = 1; sigInt* = 2; sigQuit* = 3; sigKill* = 9; sigPipe* = 13; - sigTerm* = 15; sigChld* = 17; sigCont* = 18; sigStop* = 19; - sigTstp* = 20; sigTtin* = 21; sigTtou* = 22; sigWinch* = 28; - -type - Access* = (reading, writing, creating, exclusive, truncating, appending); - Accesses* = set of Access; - Info* = record - size*: I64; (* in bytes *) - mtime*: I64; (* when its contents last changed, in nanoseconds since 1970 *) - mode*: INT; (* its permission bits, as chmod takes them: 1EDH is rwxr-xr-x *) - dir*: BOOL; (* a directory *) - file*: BOOL; (* a regular file: not a directory, device, pipe or socket *) - symlink*: BOOL; (* the path itself is a symbolic link *) - end; - Dir* = record ... end; (* an open directory; its fields are the target's *) - Program* = record - path*: []U8; - args*: [][]U8; (* the first is its name *) - env*: [][]U8; (* NAME=value, each added to this program's environment *) - onlyEnv*: BOOL; (* env is its whole environment *) - dir*: []U8; (* its working directory; "" for this program's *) - fds*: [3]INT; (* its standard input, output and error; 0 for this program's own *) - group*: INT; (* the process group it joins: 0 for this program's, -1 a new one it leads *) - foreground*: BOOL; (* its group takes the terminal on standard input *) - tty*: INT; (* a pseudo-terminal's fd, to start a session on; 0 for none *) - end; - Status* = (running, exited, killed, stopped); - -proc write*(fd: INT; s: []U8): INT; (* the bytes written *) -proc read*(fd: INT; buf: []U8): INT; (* the bytes read; 0 at the end *) -proc open*(path: []U8; how: Accesses): INT; (* its fd *) -proc openRead*(path: []U8): INT; (* open(path, {reading}) *) -proc create*(path: []U8): INT; (* open(path, {writing, creating, truncating}) *) -proc seek*(fd: INT; pos: I64; fromEnd: BOOL): I64; (* the new position *) -proc close*(fd: INT); -proc isTerminal*(fd: INT): BOOL; -proc mmap*(size: INT): ^U8; (* size bytes of zeroed memory, in whole pages; or nil *) -proc munmap*(p: ^U8; size: INT); -proc yield*; (* the processor given to another thread *) -proc exit*(status: INT); (* the program ended at once, without Rt's atExit *) - -proc rename*(old, new: []U8): INT; (* replaces what new names *) -proc remove*(path: []U8): INT; (* a file, not a directory *) -proc removeDir*(path: []U8): INT; (* an empty directory *) -proc makeDir*(path: []U8): INT; (* readable by all, writable by its owner *) -proc chmod*(path: []U8; mode: INT): INT; -proc symlink*(target, path: []U8): INT; (* path made a link to target *) -proc readLink*(path: []U8): ([]U8, INT); (* what the link names, good until the next call *) -proc info*(path: []U8): (Info, INT); (* following a symbolic link *) -proc space*(path: []U8): (I64, I64, INT); (* the bytes free and in all on path's file system *) - -proc openDir*(d: ^Dir; path: []U8): INT; -proc nextEntry*(d: ^Dir): ([]U8, BOOL); (* a name, good until the next call; false at the end *) -proc closeDir*(d: ^Dir); - -proc rawMode*(fd: INT): BOOL; (* the terminal on fd: no echo, no lines, no signals *) -proc restoreMode*(fd: INT); (* as rawMode found it *) -proc termSize*(fd: INT): (INT, INT); (* columns and rows; 80 and 24 if unknown *) -proc ready*(fd, ms: INT): BOOL; (* something to read within ms, or ever if ms < 0 *) -proc readyOf*(fds: []INT; ms: INT): INT; (* the first of fds with something to read within ms, or -1 *) -proc readyFor*(reads, writes: []INT; ms: INT): INT; (* readyOf, and the first of writes with room to write *) -proc setBlocking*(fd: INT; yes: BOOL): INT; (* if not yes, a read or write that would wait is -11 at once *) - -proc env*(name: []U8): []U8; (* the environment variable's value; "" if unset *) -proc workDir*: ([]U8, INT); (* the working directory, good until the next call *) -proc setWorkDir*(path: []U8): INT; - -proc pipe*: (INT, INT); (* the fd to read and the fd to write; or minus an errno and -1 *) -proc openPty*: INT; (* a pseudo-terminal: the fd of its controlling side *) -proc setTermSize*(fd, cols, rows: INT): INT; (* the size its programs are told of *) -proc spawn*(p: Program): INT; (* a program started: its process id *) -proc wait*(pid: INT; block: BOOL): (INT, Status, INT); (* which program, how, and its code *) -proc kill*(pid, signal: INT): INT; -proc pid*: INT; (* this program's process id *) -proc setGroup*(pid, group: INT): INT; (* pid 0 is this program; group 0 a new one pid leads *) -proc foreground*(fd, group: INT): INT; (* the terminal on fd gives its keys to group *) -proc foregroundOf*(fd: INT): INT; (* the group the terminal on fd gives its keys to *) - -proc catch*(sigs: []INT): INT; (* sigs caught: an fd to wait on *) -proc caught*(fd: INT): INT; (* the next signal caught, or 0 if none is waiting *) -proc ignore*(sig: INT; yes: BOOL): INT; (* sig ignored; or, if not yes, back to what it does at first *) - -proc clock*: I64; (* nanoseconds, on a clock that only goes forward *) -proc now*: I64; (* nanoseconds since 1970-01-01, UTC *) -proc sleep*(ms: INT); -proc random*(b: []U8); (* b filled with random bytes *) - -proc connect*(path: []U8): INT; (* a stream socket, connected to the Unix socket at path: its fd *) -proc connectTcp*(addr: []U8; port: INT): INT; (* addr an IPv4 or IPv6 address, as numbers *) -proc connectUdp*(addr: []U8; port: INT): INT; -proc listen*(path: []U8): INT; (* a Unix socket made at path, taking connections *) -proc listenTcp*(addr: []U8; port: INT): INT; -proc accept*(fd: INT): INT; (* the next connection, waiting for one *) -proc send*(fd: INT; s: []U8): INT; (* write, to a socket: -32 (EPIPE), not a signal, if it is closed *) -``` - -`info` follows a symbolic link: `size`, `dir` and `file` are those of -what it names, and `symlink` says the path was a link, so that a program walking -a tree can choose not to follow one back up it. A link to nothing is -`-ENOENT`, as a missing file is. `file` lets a walk open only what -holds data: opening a pipe would wait for a program to write to it. - -`nextEntry` gives every name in the directory except `.` and `..`, in -no particular order. `rawMode` turns off what the terminal does with -keys before the program reads them (echo, line editing, signals, flow -control), and NL to CR NL on output. A program that turns it on -restores it before it ends: `Rt.atExit` is the place. +## 11. Versions -**Files.** `open` gives a file for what `how` asks: `reading`, -`writing` or both; `creating` it if it is missing, readable by all and -writable by its owner; with `exclusive`, failing with -17 (EEXIST) if -it is there, as a program does that makes a lock or a file of its -own; `truncating` it to nothing; `appending`, each write going to its -end, however other programs write it too. `seek` moves to `pos` from -the start of the file, or from its end if `fromEnd`, where a negative -`pos` reads back from the end. `Info.mtime` is what a program checks -to see whether a file changed under it; `Info.mode` holds the nine -bits of `rwxrwxrwx`, and `chmod` sets them, 1EDH (755) for a program, -1A4H (644) for data. - -**Programs.** `openPty` makes a pseudo-terminal, a terminal that a -program, a terminal emulator, plays the screen and the keyboard of: -what it writes to the fd is typed, and what the programs on the -terminal write it reads. - -`spawn` starts the program at `p.path`, with `p.args` as its -arguments, the first being its name. Its environment is this -program's with each `NAME=value` of `p.env` added or put in place of -the old value, or, if `p.onlyEnv`, `p.env` alone. It starts in -`p.dir`. Its standard input, output and error are `p.fds`; a 0 gives -it this program's own, so `{path: "/bin/ls", args: ["ls"]}` runs -`ls` as a shell runs it, with every other field zero. It gets no -other open file, every signal does what it does at first, and none -is blocked. If `p.tty` is a pseudo-terminal's fd, the program starts a -session on that terminal: it is its controlling terminal, and its -standard input, output and error, and `p.fds` and `p.group` are not -used. - -`p.group` puts the program in a process group, the programs that a -shell's job is made of: -1 makes it the first of a new group, whose -number is its process id, and the other programs of the job join that -number. The terminal gives its keys, and the signals of Ctrl-C and -Ctrl-Z, to one group, the one in its foreground: `p.foreground` puts -the program's group there before it starts, and `foreground` puts any -group there, as a shell does to take the terminal back. `setGroup` -moves a program to a group, as the shell does for each program it -starts, for whichever of the two runs first; a shell runs in a group -of its own, `setGroup(0, 0)`. - -`wait` waits for the program `pid` to change, or for any of this -program's if `pid` is -1, and says which one, and how: `exited`, with -its exit status; `killed`, with the number of the signal that ended -it; or `stopped`, by Ctrl-Z or a signal, with the signal's number. -Without `block` it doesn't wait, and is 0 and `running` if no program -changed. A program that has nothing to wait for is -10 (ECHILD). -`kill` sends a program a signal, `sigTerm` to end it; to a group, if -`pid` is minus its number. - -**Signals.** `catch` takes the signals `sigs` away from what they -would do, ending the program most of them, and gives an fd that is -ready to read when one comes, so that a program waits for signals with -`ready` and `readyOf` as it waits for keys or a server. `caught` gives -each signal that came, in turn. A later `catch` adds to the signals -caught and gives the same fd. Catching `sigKill` or `sigStop`, or the -signals `Rt` reports, SIGSEGV and SIGFPE, is -22 (EINVAL). `ignore` -makes a signal do nothing, as a shell ignores `sigTtou` so that it can -take its terminal back, and `ignore(sig, false)` gives it back what it -does at first. A program that `spawn` starts begins with neither. - -**Time.** `clock` is for measuring how long something takes: it never -goes back, and says nothing of the date. `now` is the date and time, -which a person or the network may set back. `sleep` waits `ms` -milliseconds. - -**Sockets.** `connect` is for talking to a server on the same machine, -an X server at `/tmp/.X11-unix/X0` say; `connectTcp` for one across -the network, given its address as numbers, `"127.0.0.1"` or `"::1"`: -turning a name into an address is a library's work over these. -`connectUdp` gives a socket of datagrams, each `send` one message to -that address and each `read` one message from it, as a program asks a -name server. What a socket receives comes by `read`, what it sends goes -by `send`, and `close` ends it. `send` is `write` for a socket, except -when the other end has closed it: `write` would stop the program with -the signal SIGPIPE, where `send` returns -32 (EPIPE), so that a -program learns its server has gone and can end as it wants. -`listen` and `listenTcp` are the other side: a server's socket, on -`path`, which must not be there yet, or on `port` at `addr`, -`"0.0.0.0"` or `"::"` for every address the machine has; `accept` -gives each connection that comes, as a socket of its own. - -`readyOf` waits on several file descriptors at once, as a program does -that listens to a server and a terminal both; a descriptor at its end, -or failed, counts as ready, since a read of it won't wait. It looks at -the first 64 of `fds`, and `connect` and `listen` take a path of at -most 107 bytes, as `struct sockaddr_un` holds; a longer one is -36 -(ENAMETOOLONG). - -A program that both reads from a descriptor and writes much to it, as -a terminal writes what is pasted to its program while it reads what -the program writes back, must not wait on either: the program may be -waiting for its own writes to be read. `setBlocking(fd, false)` has a -read or a write on `fd` that would wait return -11 (EAGAIN) at once, -a write having written what there was room for; `readyFor` waits, as -`readyOf` does, for something to read on any of `reads` or for room to -write on any of `writes`. A descriptor in both is given once, when it -is ready for either; the 64 it looks at are `reads`, then `writes`. - -**Strings, buffers and collections.** - -``` -module Str; -proc cmp*(a, b: []U8): INT; (* -1, 0 or 1 as a sorts before, with or after b, byte by byte *) -proc eq*(a, b: []U8): BOOL; -proc copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL); (* s's bytes in memory from a; false if a has none *) -proc hash*(s: []U8): U64; (* FNV-1a, 64 bits *) -proc find*(s, sub: []U8): INT; (* where sub first starts in s, or -1 *) -proc hasPrefix*(s, p: []U8): BOOL; -proc encode*(c: I32): ([4]U8, INT); (* c in UTF-8: its bytes, and how many *) -proc decode*(s: []U8): (I32, INT); (* the character s starts with, and its length in bytes *) -proc toInt*(s: []U8): (I64, BOOL); (* s, in decimal; false if it isn't a number an I64 holds *) -proc le*(s: []U8): U64; (* s, at most 8 bytes, the first the lowest *) -proc be*(s: []U8): U64; (* s, at most 8 bytes, the first the highest *) -proc putLE*(s: []U8; v: U64); (* v into s, the lowest byte first *) -proc putBE*(s: []U8; v: U64); (* v into s, the highest byte first *) - -module Buf; -type Buf* = record len*: INT; ... end; -proc init*(b: ^Buf; a: ^Mem.Allocator); -proc room*(b: ^Buf; n: INT): BOOL; (* room for n more bytes; false if the allocator has none *) -proc add*(b: ^Buf; c: U8); -proc str*(b: ^Buf; s: []U8); -proc bytes*(b: ^Buf): []U8; (* what it holds, until it next grows *) -proc reset*(b: ^Buf); (* emptied, its memory kept *) -proc done*(b: ^Buf); (* its memory given back *) - -module Fmt; -type Arg* = variant - int(i: I64); - uint(u: U64); - hex(h: U64); - str(s: []U8); - char(c: U8); - bool(b: BOOL); - real(r: F64; places: INT); -end; -proc print*(f: []U8; args: []Arg); (* to standard output *) -proc write*(b: ^Buf.Buf; f: []U8; args: []Arg); (* added to b *) - -module List(T); -type - Node* = record next*: ^Node; val*: T; end; - List* = record head*: ^Node; len*: INT; ... end; -proc init*(l: ^List; a: ^Mem.Allocator); -proc push*(l: ^List; v: T): BOOL; (* v at the front; false if the allocator has no room *) -proc pop*(l: ^List): (T, BOOL); (* the front value, taken off; false if the list is empty *) -proc reverse*(l: ^List); -proc clear*(l: ^List); - -module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL); -type Map* = record len*: INT; ... end; -proc init*(m: ^Map; a: ^Mem.Allocator); -proc put*(m: ^Map; k: K; v: V): BOOL; (* k now maps to v; false if there was no room *) -proc remove*(m: ^Map; k: K): BOOL; (* false if k wasn't there *) -proc get*(m: ^Map; k: K): (V, BOOL); (* what k maps to, and whether it maps to anything *) -proc next*(m: ^Map; i: INT): (INT, K, V); (* the entry after i *) - -module Sort(T; less: proc(a, b: T): BOOL); -proc sort*(s: []T); - -module Math; -const pi* = 3.141592653589793; -proc sqrt*(x: F64): F64; -proc pow*(x, y: F64): F64; (* x to the power y *) -proc floor*(x: F64): F64; -proc ceil*(x: F64): F64; -proc round*(x: F64): F64; (* to the nearest whole number; a half away from 0 *) -proc exp*(x: F64): F64; -proc ln*(x: F64): F64; -proc log2*(x: F64): F64; -proc log10*(x: F64): F64; -proc sin*(x: F64): F64; -proc cos*(x: F64): F64; -proc tan*(x: F64): F64; -proc asin*(x: F64): F64; (* from -pi/2 to pi/2 *) -proc acos*(x: F64): F64; (* from 0 to pi *) -proc atan*(x: F64): F64; (* from -pi/2 to pi/2 *) -proc atan2*(y, x: F64): F64; (* the angle of (x, y) from the x axis, from -pi to pi *) -``` - -A `Buf`, a `List` and a `Map` take their memory from the allocator -`init` gives them. `Fmt`'s format takes the next argument at each -`{}`; `{{` and `}}` stand for `{` and `}`. A `Map` hashes and -compares its keys with the procedures it is given: -`import Count := Map([]U8, INT, Str.hash, Str.eq);`. - -`Str` reads and writes UTF-8. `encode` writes a character, of at most -10FFFFH, in one to four bytes; a number that isn't one becomes FFFDH, -the character that stands for a wrong one. `decode` reads the first -character of `s`, and gives FFFDH and 1 for a byte that doesn't start -one rightly, and 0 and 0 for an empty `s`. `toInt` reads a decimal -number, with a `-` or `+` before it if any, and nothing else. - -`le` and `be` read an unsigned number of up to 8 bytes in a fixed -order, little-endian or big-endian, whatever the machine's own, and -`putLE` and `putBE` write one; more than 8 bytes stops the program. -They are how a file format or a network protocol is read and written: - -``` -len := U32(Str.le(header[4..8])); -Str.putBE(packet[0..2], U64(port)); -``` - -`Map.next` walks a map: from 0, it gives the next entry and the number -to pass for the one after it, and -1 when there are no more. A walk -sees each entry once if the map doesn't change during it: - -``` -i, k, v := Names.next(ADR(names), 0); -while i >= 0 do - Fmt.print("{} is {}\n", [Fmt.str(k), Fmt.int(v)]); - i, k, v := Names.next(ADR(names), i); -end; -``` - -`Sort.sort` puts `s` in the order `less` gives, in place, without -memory of its own, in time `n log n` at most; two elements equal by -`less` may change places. `Math`'s procedures are as C's `math.h` -has them, to within the last bit or so. `Fmt.real(x, places)` writes -`x` with `places` digits after the point, at most 9, rounded to the -nearest; from 1e15 on, with an exponent, as `1.50e17`; and `nan`, -`inf` and `-inf` as themselves. - -**Files and Opt** are what most programs need of their command line. - -``` -module Files; -proc arg*(i: INT): []U8; (* argument i; 0 is the program's name *) -proc read*(path: []U8; b: ^Buf.Buf): BOOL; (* the whole file added to b *) -proc write*(path, data: []U8): BOOL; (* the file made to hold data *) - -module Opt; -type - Row* = variant - usage(scope, line: []U8); (* a synopsis line, without "usage: " *) - sub(scope, name, help: []U8); (* a subcommand *) - option(scope: []U8; letter: U8; long, value, help: []U8); - end; - Parser* = record - letter*: U8; (* the option just read *) - value*: []U8; (* its value; "" for a flag *) - long*: BOOL; (* it was written by its long name *) - ... - end; -proc init*(p: ^Parser; name: []U8; table: []Row); (* the arguments from 1 on, by table *) -proc next*(p: ^Parser): BOOL; (* the next option; false when they end *) -proc operand*(p: ^Parser): ([]U8, BOOL); (* the next operand; false when there are no more *) -proc scope*(p: ^Parser; name: []U8); (* subcommand name's options, from the word after it *) -proc number*(p: ^Parser; lo, hi: I64): I64; (* the value just read, a number from lo to hi *) -proc fail*(p: ^Parser; text: []U8); (* the program's own mistake *) -``` - -`Opt` reads a command line by the rules of the C library's `getopt`, -with GNU's long options, so that a program's options behave as every -other Unix program's. The program describes itself once, in a table of -`Row`s: its synopsis lines, its subcommands and its options. The help -and the messages for mistakes are made from the table, so they can't -drift from it; the program's test of `p.letter` is the only other -place an option appears. The parser is a record the program owns, and -the table a slice it keeps as long as the parser: a literal written in -the call to `init` lives as long as the procedure that makes it. - -A row's `scope` is `""` for the program itself, or a subcommand's -name: `"start"`, or `"remote.add"` for a subcommand of `remote`. An -option has a `letter`, a `long` name, or both. One with a long name -only has a key of its own below `'!'` for a letter, so that the -program can tell it from the others. With a `value`, the name the -help and the messages give it, the option takes a value; with `""` it -is a flag. - -``` -const wait = 1; (* the key of --wait, which has no letter *) -... -Opt.init(ADR(p), "keep", [ - Opt.usage("", "keep [-v] [--wait secs] start ..."), - Opt.sub("", "start", "start a job"), - Opt.option("", 'v', "verbose", "", "say more"), - Opt.option("", wait, "wait", "secs", "give the job secs to start"), - Opt.usage("start", "keep start [-b label] name command [argument ...]"), - Opt.option("start", 'b', "bar", "label", "show the job in the bar as label")]); -while Opt.next(ADR(p)) do - if p.letter = 'v' then verbose := true; - elsif p.letter = wait then secs := Opt.number(ADR(p), 1, 600); - end; -end; -w, ok := Opt.operand(ADR(p)); -if not ok or (w # "start") then Opt.fail(ADR(p), "no command; see keep -h"); end; -Opt.scope(ADR(p), "start"); -while Opt.next(ADR(p)) do - if p.letter = 'b' then bar := p.value; end; -end; -job, ok := Opt.operand(ADR(p)); -``` - -The rules are `getopt`'s: - -- Flags may share a dash: `-lw` is `-l -w`. A letter's value is the - rest of its word, `-bdev`, or the whole next word, `-b dev`, even one - that starts with a dash or is empty; in a group, the first letter - that takes a value takes the rest, `-qn12`. -- A long option is written in full, with its value after a `=` or in - the next word: `--bar=dev`, `--bar dev`. An abbreviation is unknown, - not guessed, so that adding an option never breaks a script. A value - given to a flag, `--follow=x`, is a mistake. -- `--` ends the options, and isn't an operand; `-` alone is one. The - options end at the first operand, so in `keep start site python -m - http.server` the `-m` is python's. -- Each scope has its own options. An option given twice is read twice. - -`number` reads the value as `Str.toInt` does. `operand` reads what -options are left first, and the program doesn't see them. - -`-h` or `--help` among a scope's options prints its help on standard -output and ends the program with status 0. `init` and `scope` answer -it, looking through the scope's options before `next` gives one, so -that the program has done nothing yet: `keep -v -h -x` prints the -help, and the program never sees `-v`, nor the mistake. The help is -the scope's synopsis lines, a blank line, and its subcommands, its -options and the help itself, each with its line of help: - -``` -usage: keep start [-b label] name command [argument ...] - - -b, --bar label show the job in the bar as label - -h, --help print this and exit -``` - -A scope with several synopsis lines has the others indented under the -first; one with none, `usage:` and its words, as `usage: keep start`. - -A mistake on the command line is a sentence on standard error, the -program's name first, then the scope's synopsis lines, as the help -begins, and status 2: - -``` -keep: unknown option -x -usage: keep start [-b label] name command [argument ...] -``` - -The sentences are `unknown option -x` (or `--name`, up to its `=`), -`-b needs a label`, `--follow takes no value` and `--wait wants a -number from 1 to 600, not '0'`. `fail` writes the program's own -mistakes the same way, but alone, so that the sentence can say where -the help is: `keep: no command; see keep -h`. - -A mistake in the table is the program's, not its user's. `init` checks -the table before it reads a word, and ends the program with status 1: -`keep: option table, row 3: the option is in the scope already`. The -others are an option with neither a letter nor a long name, a long -name with `=` in it, a letter `-`, and `-h` or `--help` in the table, -since they are `Opt`'s. - -## 12. Versions - A version of this report is named by the month it was made in and a count: `2026-10.0`, then `2026-10.1` for the next change that month. `raz --version` says which version the compiler follows. @@ -1985,7 +1376,7 @@ it, destination first. Which instructions it knows is the implementation's; `db` gives any others. - **Sizes in the library.** How many bytes `Out` keeps before it - writes them, `Sys.outSize` (section 11): 4 KB on Linux, fewer on a + writes them, `Sys.outSize` (the library volume): 4 KB on Linux, fewer on a small machine. - **The executable.** Its format, and the names and line numbers it carries for a debugger (section 10). @@ -2011,7 +1402,7 @@ that keeps to the core runs on every target. The rest of the library (`Heap`, `Fmt`, `List`, `Map`, `Sort`, `Math`, `Files`, `Opt` and the rest of `Sys`) is the standard library: a target may leave a module -out, and one that has it gives what section 11 says. `conform/` tests +out, and one that has it gives what `doc/raz-lib.md` says. `conform/` tests the core only. ## Appendix B. The grammar diff --git a/lib/Opt.raz b/lib/Opt.raz index 03da195..5487646 100644 --- a/lib/Opt.raz +++ b/lib/Opt.raz @@ -1,5 +1,5 @@ (* A command line read through one table, by the rules of the C - library's getopt with GNU's long options (report, section 11). The + library's getopt with GNU's long options (report, volume 2). The program describes its synopsis lines, subcommands and options once, in a slice of Row; the help and the messages for mistakes are made from it, so they can't drift from it. diff --git a/site/build.py b/site/build.py index 75c6240..2d41af6 100644 --- a/site/build.py +++ b/site/build.py @@ -305,7 +305,8 @@ if not shutil.which("pandoc"): sys.exit("pandoc makes the report's page: apt-get install pandoc") p = subprocess.run( - ["pandoc", os.path.join(ROOT, "doc", "raz.md"), "-s", "--template", + ["pandoc", os.path.join(ROOT, "doc", "raz.md"), + os.path.join(ROOT, "doc", "raz-lib.md"), "-s", "--template", os.path.join(HERE, "content", "spec.tmpl"), "--toc", "--toc-depth=1", "--shift-heading-level-by=-1", "--no-highlight", "-t", "html", # wide enough that no row of a table is "long": pandoc would diff --git a/test/check.sh b/test/check.sh index 397d472..3146e72 100755 --- a/test/check.sh +++ b/test/check.sh @@ -152,7 +152,7 @@ # the report's examples that are whole modules: each compiles, and # each with a main runs and ends with status 0 rm -rf $out/report; mkdir -p $out/report - for name in $($out/Doc examples doc/raz.md $out/report); do + for name in $($out/Doc examples doc/raz.md $out/report) $($out/Doc examples doc/raz-lib.md $out/report); do if ! $raz -o $out/report/$name $out/report/$name.raz 2>$out/report/$name.cerr; then echo "FAIL report example $name: $(cat $out/report/$name.cerr)"; fail=$((fail + 1)) elif grep -q '^proc main\*' $out/report/$name.raz && ! $out/report/$name > /dev/null 2>&1; then diff --git a/test/doc/Opt.expect b/test/doc/Opt.expect index 02dbea1..38ab922 100644 --- a/test/doc/Opt.expect +++ b/test/doc/Opt.expect @@ -1,6 +1,6 @@ module Opt; A command line read through one table, by the rules of the C - library's getopt with GNU's long options (report, section 11). The + library's getopt with GNU's long options (report, volume 2). The program describes its synopsis lines, subcommands and options once, in a slice of Row; the help and the messages for mistakes are made from it, so they can't drift from it. diff --git a/tools/Doc.raz b/tools/Doc.raz index 11f7844..3fa3505 100644 --- a/tools/Doc.raz +++ b/tools/Doc.raz @@ -425,7 +425,7 @@ control(".Ic main ,"); control("where it has one, is its test, and is left out."); control(".Pp"); - control("The report, section 11, says what the library promises, and which"); + control("The report's second volume says what the library promises, and which"); control("of its modules every target has."); control(".Sh MODULES"); for i := 2 to ARGC() - 1 do document(Files.arg(i)); end; @@ -436,6 +436,8 @@ control(".Xr raz-tutorial 7 ;"); control("the report,"); control(".Pa doc/raz.md ,"); + control("and its second volume,"); + control(".Pa doc/raz-lib.md ,"); control("in raz's sources."); end;