Document (std os), numeric/si and Ctrl-C and SIGTERM

A module page and a standard library entry for (std os), numeric/si and
a section on signals in writing programs, and the span conversions in
the language basics.
This commit is contained in:
Linus Björnstam 2026-11-15 07:50:51 +01:00
parent 1a2a43bf5a
commit f07cd79e3e
4 changed files with 96 additions and 5 deletions

View file

@ -1342,7 +1342,7 @@ To work on part of an array without copying it, make a span: @code{(Span %a)} is
(span->array s) ;; #[99 3], a fresh copy (span->array s) ;; #[99 3], a fresh copy
}| }|
A span is valid only while the call that made it runs, so it can be a local variable, a function argument or a return value, and the compiler refuses it anywhere it could outlive the call (such as inside another collection or across a yield point). The section on .NET interop in Part 2 covers the full rules and how spans work with .NET methods. A span is valid only while the call that made it runs, so it can be a local variable, a function argument or a return value, and the compiler refuses it anywhere it could outlive the call (such as inside another collection or across a yield point). The section on .NET interop in Part 2 covers the full rules and how spans work with .NET methods. It also covers @code{span->} and @code{ro-span->}, which show a span of numbers as numbers of another type (longs as bytes, for example) without copying.
@subsubsection{Maps} @subsubsection{Maps}

View file

@ -671,7 +671,7 @@ Anything else is converted first:
|-----------------------------------+---------------------------------------------------------------| |-----------------------------------+---------------------------------------------------------------|
| A double @code{x} | @code{(numeric x)}, or @code{(numeric x #:precision 2)} | | A double @code{x} | @code{(numeric x)}, or @code{(numeric x #:precision 2)} |
| A bool @code{b} | @code{(if b "yes" "no")} | | A bool @code{b} | @code{(if b "yes" "no")} |
| A long @code{n} | @code{(long->string n)}, or @code{(bytes n)} for a size | | A long @code{n} | @code{(numeric n)}, or @code{(bytes n)} for a size |
| A @code{(Vec string)} @code{xs} | @code{(vec-map BStr xs)} | | A @code{(Vec string)} @code{xs} | @code{(vec-map BStr xs)} |
| A @code{(List %a)} @code{xs} | @code{(joined f xs ", ")}, where @code{f} makes the block of one element | | A @code{(List %a)} @code{xs} | @code{(joined f xs ", ")}, where @code{f} makes the block of one element |
} }
@ -784,7 +784,7 @@ A list is written with @code{joined}, which takes a function that makes each ele
@subsubsection{Numbers} @subsubsection{Numbers}
An int is a block. A double is not, as there is no one way to write one: @code{numeric} says how, with a precision, digits in groups, and the separators. @code{bytes} and @code{percent} are blocks for two common kinds of number. An int is a block. A double is not, as there is no one way to write one: @code{numeric} says how, with a precision, digits in groups, and the separators. It takes a number of any type, and writes a long, a @code{decimal} or a @code{bigint} with all its digits. @code{bytes} and @code{percent} are blocks for two common kinds of number.
@codeblock[#:lang "bjolang"]|{ @codeblock[#:lang "bjolang"]|{
(show [(numeric 1234567.891 #:precision 2 #:comma 3) " " (show [(numeric 1234567.891 #:precision 2 #:comma 3) " "
@ -797,9 +797,18 @@ An int is a block. A double is not, as there is no one way to write one: @code{n
The digits are always the invariant culture's, so the machine's locale never shows. The separators are settings, described below. The digits are always the invariant culture's, so the machine's locale never shows. The separators are settings, described below.
@code{numeric/si} writes a number with an SI prefix before its unit, as SRFI 166 does. With @code{#:binary #t} the prefixes are powers of 1024, and @code{#:sep} is what goes between the number and the prefix.
@codeblock[#:lang "bjolang"]|{
(show [(numeric/si 0.00000123 "m" #:sep " ") " "
(numeric/si 2400000000.0 "Hz" #:sep " ") " "
(numeric/si 3986.0 "B" #:binary #t) nl])
;; 1.2 µm 2.4 GHz 3.9KiB
}|
@subsubsection{Paragraphs} @subsubsection{Paragraphs}
@code{wrapped} fills content to @code{current-width}, and @code{justified} makes it flush against both margins. Every run of whitespace in the content is a break between words. @code{wrapped} fills content to @code{current-width}, and @code{justified} makes it flush against both margins. Every run of whitespace in the content is a break between words, but a no-break space is not, and a word wider than the line gets a line of its own. @code{current-word-separator?} says which characters separate words. @code{wrapped/char}, as in SRFI 166, breaks at characters instead: also inside a word, and the content's own newlines are kept. It is for text with no spaces to break at, such as a hash or a URL.
@codeblock[#:lang "bjolang"]|{ @codeblock[#:lang "bjolang"]|{
(show [(with-fmt current-width 20 (show [(with-fmt current-width 20
@ -935,7 +944,7 @@ For part of an output, such as one paragraph, one cell or the numbers of one col
;; 1 234 567,5 ;; 1 234 567,5
}| }|
The settings are @code{current-pad}, @code{current-width}, @code{current-ellipsis}, @code{current-string-width}, @code{current-precision}, @code{current-comma}, @code{current-comma-sep}, @code{current-decimal-sep} and @code{current-signed}. For text with wide characters or colours in it, which a terminal shows in more or fewer columns than it has characters, set @code{current-string-width} to @code{terminal-width}. The settings are @code{current-pad}, @code{current-width}, @code{current-ellipsis}, @code{current-string-width}, @code{current-precision}, @code{current-comma}, @code{current-comma-sep}, @code{current-decimal-sep}, @code{current-signed} and @code{current-word-separator?}. For text with wide characters or colours in it, which a terminal shows in more or fewer columns than it has characters, set @code{current-string-width} to @code{terminal-width}.
@subsubsection{When it does not compile} @subsubsection{When it does not compile}
@ -1199,6 +1208,50 @@ A scope also owns resources. @code{(own! thunk)} registers a release on the inne
Do not park a bjoroutine's thread by accident. A scope in an ordinary @code{(fun ...)} that a bjoroutine calls parks the thread of that bjoroutine, and the compiler warns about it. Write the scope in the bjoroutine itself. Or, if the function the lambda is given to takes a @code{-?->} parameter, write the lambda as a @code{(bjoroutine ...)}. Do not park a bjoroutine's thread by accident. A scope in an ordinary @code{(fun ...)} that a bjoroutine calls parks the thread of that bjoroutine, and the compiler warns about it. Write the scope in the bjoroutine itself. Or, if the function the lambda is given to takes a @code{-?->} parameter, write the lambda as a @code{(bjoroutine ...)}.
@subsubsection{Ctrl-C and SIGTERM}
By default, Ctrl-C and SIGTERM end a program at once. No @code{finally} runs, and no scope releases what it owns. @code{with-signal-cancel} from @code{(std os)} is a scope that the first of its signals cancels. The fibers stop at their next wait, the scope releases what it owns, and the form returns @code{(Err s)}, with the signal. When the body returns @code{v}, the form returns @code{(Ok v)}:
@codeblock[#:lang "bjolang"]|{
(import (std os))
(: tick (-bjo-> void))
(defbjo (tick)
(let go ()
(sync (timeout (seconds 1)))
(println "tick")
(go)))
(defbjo (main)
(match (with-signal-cancel [Interrupt Terminate]
(ignore (own! (fun () (println "released"))))
(spawn (tick))
(sync (timeout (minutes 10))))
((Ok _) 0)
((Err s) (println #"stopped by ${(signal-name s)}") 0)))
}|
@codeblock[#:lang "text"]|{
tick
tick
^C
released
stopped by SIGINT
}|
At the first signal, the form gives the signals back to the system. So when the cleanup hangs, a second Ctrl-C ends the program at once.
To do something else on a signal and go on, give @code{on-signal} a function. It calls the function for each signal that comes, in a fiber of its own, until the scope ends; in @code{main}, that is the whole program. The function can be an ordinary one or a bjoroutine:
@codeblock[#:lang "bjolang"]|{
(defun (main)
(on-signal [Interrupt] (fun (s) (println #"got ${(signal-name s)}, carrying on")))
(do-the-work)
0)
}|
The function runs at the same time as the rest of the program, so share state with it through @code{(std atomic)} or a channel. To receive signals as values in a @code{choose}, use @code{signal-subscribe} and the event @code{signal-recv}.
@subsubsection{When fibers hang} @subsubsection{When fibers hang}
A scope does not return until its fibers have ended, so a fiber that waits forever makes its scope wait forever too. Two things show you where the fibers wait. A scope does not return until its fibers have ended, so a fiber that waits forever makes its scope wait forever too. Two things show you where the fibers wait.
@ -1723,12 +1776,38 @@ A span that a .NET member @em{returns} is not an array. To copy a returned span
| @code{(span-slice s #:from #:to)} | @code{(ro-span-slice s #:from #:to)} | a sub-view of @code{s}; nothing is copied | | @code{(span-slice s #:from #:to)} | @code{(ro-span-slice s #:from #:to)} | a sub-view of @code{s}; nothing is copied |
| @code{(span->array s)} | @code{(ro-span->array s)} | a fresh array copy of the span's elements | | @code{(span->array s)} | @code{(ro-span->array s)} | a fresh array copy of the span's elements |
| @code{(span->ro-span s)} | | the same view, read-only | | @code{(span->ro-span s)} | | the same view, read-only |
| @code{(span-> s)} | @code{(ro-span-> s)} | the same bytes as numbers of another type |
} }
@code{#:from} defaults to @code{0} and @code{#:to} defaults to the length. Neither span type converts to the other implicitly; use @code{span->ro-span} when a @code{RoSpan} is needed. In @code{(std mutable vec)}, @code{(mutablevec-span v start n)} returns a @code{(Span %a)} over @code{n} elements of a @code{MutableVec}'s backing storage (valid until the vector's length changes), which pairs with @code{(mutablevec-grow! v n)} to fill a vector a block at a time. @code{#:from} defaults to @code{0} and @code{#:to} defaults to the length. Neither span type converts to the other implicitly; use @code{span->ro-span} when a @code{RoSpan} is needed. In @code{(std mutable vec)}, @code{(mutablevec-span v start n)} returns a @code{(Span %a)} over @code{n} elements of a @code{MutableVec}'s backing storage (valid until the vector's length changes), which pairs with @code{(mutablevec-grow! v n)} to fill a vector a block at a time.
You can also call a span's .NET members directly: @code{(.-Length s)}, @code{(.Slice s 1)}, @code{(.Fill s x)}, @code{(.get_Item s i)} for @code{s[i]}, and @code{(.set_Item s i x)} for @code{s[i] = x} (an indexer returning @code{ref T} reads a copy of the element, and @code{.set_Item} writes through the reference). You can also call a span's .NET members directly: @code{(.-Length s)}, @code{(.Slice s 1)}, @code{(.Fill s x)}, @code{(.get_Item s i)} for @code{s[i]}, and @code{(.set_Item s i x)} for @code{s[i] = x} (an indexer returning @code{ref T} reads a copy of the element, and @code{.set_Item} writes through the reference).
@strong{Numbers as other numbers.} @code{span->} and @code{ro-span->} show the memory of a span as numbers of another type, with no copy. This is what you need when a .NET API wants bytes and you have longs, or the other way around: an Arrow buffer, a file format, a hash. The type of the result comes from where you use it, so give it with a signature or @code{(: ...)}:
@codeblock[#:lang "bjolang"]|{
(def bytes (: (make-array 16) (Array byte)))
(: (Span long))
(def longs (span-> (array->span bytes)))
(span-set! longs 1 -1L)
(array-ref bytes 8) ;; 255uy: the longs are the bytes
(: (RoSpan byte))
(def raw (ro-span-> (array->ro-span #[1.5 2.5])))
(ro-span-length raw) ;; 16
(ro-span->array raw) ;; the doubles' bytes, copied once
}|
The new length is the length in bytes divided by the size of the new element. Writing through one span writes through the other, and the bytes are in the machine's order, which is little-endian on x64 and ARM64. Three rules keep this safe:
@read-list{
- @strong{Only plain numbers.} Both types must be integers, @code{float} or @code{double}. They contain no references, and every bit pattern is a valid value, so nothing you write as one type can break the other. @code{bool} and @code{char} are not numbers, so a span of them is a type error. A span of @code{decimal} or @code{bigint} type-checks, because they are numbers, but they are not plain, so it panics.
- @strong{Whole elements.} If the length in bytes is not a whole number of the new elements (7 bytes as longs, for example), the call panics. It does not silently cut off the end. Slice the span first.
- @strong{Read-only stays read-only.} @code{ro-span->} gives a @code{RoSpan} and there is no way to make it writable. A string's bytes are only available as a @code{(RoSpan byte)}, so nothing can change them. For the same reason, a program cannot name @code{System.Runtime.InteropServices.MemoryMarshal}, @code{SequenceMarshal} or @code{System.Runtime.CompilerServices.Unsafe}.
}
@strong{What a span is made from stays alive.} A span over memory that a .NET object owns (an Arrow buffer, a @code{Memory<T>}) holds no reference to that object. If nothing else used the object, the garbage collector could free the memory while you were still reading the span. The compiler keeps the object alive for you: a span in a local variable keeps it alive until the end of the variable's scope, even on a return, a loop jump or an exception. A span passed to a call keeps it alive until the call returns. An array needs none of this, because a span over an array keeps the array.
@strong{Where a span may not go.} A span—or any other .NET @code{ref struct}—is a view of memory that is valid only while the call that made it runs. It can be a local variable, a parameter, or a return value of a function called by name, and the compiler refuses it everywhere it could outlive the call: @strong{Where a span may not go.} A span—or any other .NET @code{ref struct}—is a view of memory that is valid only while the call that made it runs. It can be a local variable, a parameter, or a return value of a function called by name, and the compiler refuses it everywhere it could outlive the call:
@read-list{ @read-list{

View file

@ -142,6 +142,15 @@ For more details, see @link["modules/std/inbox.html"]{@code{(std inbox)}}.
Bridges for .NET APIs that want something a Bjolang function or value is not. A Bjolang function is a @code{Func} whose @code{void} return is the unit value; @code{as-delegate} and @code{as-delegate/type} wrap a function in another .NET delegate type such as @code{Action}, @code{EventHandler} or a library's custom delegate. @code{add-event-handler!} and @code{remove-event-handler!} subscribe a Bjolang function to a .NET object's event by name. @code{clr-default} produces .NET's @code{default(T)} (such as @code{null} for a reference type or a @code{Nullable<T>}) when a .NET call requires one. Bridges for .NET APIs that want something a Bjolang function or value is not. A Bjolang function is a @code{Func} whose @code{void} return is the unit value; @code{as-delegate} and @code{as-delegate/type} wrap a function in another .NET delegate type such as @code{Action}, @code{EventHandler} or a library's custom delegate. @code{add-event-handler!} and @code{remove-event-handler!} subscribe a Bjolang function to a .NET object's event by name. @code{clr-default} produces .NET's @code{default(T)} (such as @code{null} for a reference type or a @code{Nullable<T>}) when a .NET call requires one.
For more details, see @link["modules/std/interop.html"]{@code{(std interop)}}. For more details, see @link["modules/std/interop.html"]{@code{(std interop)}}.
@subsection{std/os}
The operating system the program runs on: @code{windows?}, @code{linux?}, @code{macos?}, @code{freebsd?} and the others, @code{os-platform?} by name, and @code{windows-version-at-least?} and the other version checks, with the minor version, the build and the revision as keywords. Each is .NET's @code{OperatingSystem} method, called where it is written. .NET's core library is built for one system, so the method returns a constant there, and the JIT removes the branch that cannot run. A program is built once and chooses when it runs, and code for one system can be in a module of its own: a module that nothing calls does nothing.
It also has the facts about the machine and the process: @code{os-description}, @code{os-version}, @code{os-architecture}, @code{processor-count}, @code{available-memory}, @code{machine-name}, @code{user-name}, @code{process-id} and others. And the user's folders: @code{home-directory}, @code{config-directory}, @code{data-directory}, @code{cache-directory}, @code{documents-directory}, @code{desktop-directory} and @code{temp-directory}, which follow the XDG variables on Linux and each system's own place elsewhere, and @code{make-temp-directory} for a new directory that only its owner can enter.
And the signals, as union cases such as @code{Interrupt}, @code{Terminate} and @code{Hangup}. @code{with-signal-cancel} is a scope that the first of its signals cancels, so that a program cleans up on Ctrl-C or SIGTERM; a second signal ends the program at once. @code{on-signal} calls a function for each signal that comes, until the scope ends. @code{signal-subscribe} gives signals as values from the event @code{signal-recv}, and signals of one kind that wait are merged into one.
For more details, see @link["modules/std/os.html"]{@code{(std os)}}.
@subsection{std/ports and std/net} @subsection{std/ports and std/net}
@code{(std ports)} reads and writes bytes on the prelude's ports. The byte reads @code{read-some-evt}, @code{read-bytes-evt} and @code{eof-evt} are CML events: a read that loses its @code{choose} takes nothing, so a read can race a timeout. @code{read-line} and @code{read-bytes} can be used on the same port. The module also drains ports into lists and vecs, streams them as a @code{Seq} or a channel, and has @code{byte-pipe}, a pair of ports with no file and no network, for tests. @code{(std net)} gives a TCP connection as a pair of these ports, so a protocol written for ports also runs over TCP. @code{accept-evt} is an event too: a branch that loses accepts nothing. @code{(std ports)} reads and writes bytes on the prelude's ports. The byte reads @code{read-some-evt}, @code{read-bytes-evt} and @code{eof-evt} are CML events: a read that loses its @code{choose} takes nothing, so a read can race a timeout. @code{read-line} and @code{read-bytes} can be used on the same port. The module also drains ports into lists and vecs, streams them as a @code{Seq} or a channel, and has @code{byte-pipe}, a pair of ports with no file and no network, for tests. @code{(std net)} gives a TCP connection as a pair of these ports, so a protocol written for ports also runs over TCP. @code{accept-evt} is an event too: a branch that loses accepts nothing.

3
modules/std/os.sz Normal file
View file

@ -0,0 +1,3 @@
(meta (title "(std os)"))
@generate-docs[#:module "std os"]