7The Urbit interpreter is built on a Nock runtime system written
8in C, `u3`. This document is a relatively complete description
10You should keep reading if (a) you're planning to work on the
11Urbit interpreter; (b) you're a language implementation geek; or
12(c) you don't really understand anything until you've seen the
15## u3: noun processing in C
17`u3` is the C library that makes Urbit work. If it wasn't called
18`u3`, it might be called `libnoun` - it's a library for making
21What's a noun? A noun is either a cell or an atom. A cell is an
22ordered pair of any two nouns. An atom is an unsigned integer of
25To the C programmer, this is not a terribly complicated data
26structure, so why do you need a library for it?
28One: nouns have a well-defined computation kernel, Nock, whose
29spec fits on a page and gzips to 340 bytes. But the only
30arithmetic operation in Nock is increment. So it's nontrivial
31to compute both efficiently and correctly.
33Two: `u3` is designed to be a "solid-state interpreter," ie, a
34single-level store which is transparently snapshotted. This
35implies a specialized memory-management model, etc, etc.
37(Does `u3` depend on the higher levels of Urbit, Arvo and Hoon?
38Yes and no. `u3` expects you to load something shaped like an
39Arvo kernel, and use it as an event-processing function. But you
40don't need to use this feature if you don't want, and your kernel
41doesn't have to be Arvo proper - just Arvo-compatible. Think of
42`u3` as the BIOS and Arvo as the boot kernel. And there are no
43dependencies at all between Hoon the language and `u3`.)
47Under `u3` is the simple `c3` layer, which is just how we write C
50When writing C in u3, please of course follow the conventions of
51the code around you as regards indentation, etc. It's especially
52important that every function have a header comment, even if it
53says nothing interesting.
55But some of our idiosyncrasies go beyond convention. Yes, we've
56done awful things to C. Here's what we did and why we did.
60First, it's generally acknowledged that underspecified integer
61types are C's worst disaster. C99 fixed this, but the `stdint`
62types are wordy and annoying. We've replaced them with:
66 typedef uint64_t c3_d; // double-word
67 typedef int64_t c3_ds; // signed double-word
68 typedef uint32_t c3_w; // word
69 typedef int32_t c3_ws; // signed word
70 typedef uint16_t c3_s; // short
71 typedef int16_t c3_ss; // signed short
72 typedef uint8_t c3_y; // byte
73 typedef int8_t c3_ys; // signed byte
74 typedef uint8_t c3_b; // bit
76 typedef uint8_t c3_t; // boolean
77 typedef uint8_t c3_o; // loobean
78 typedef uint8_t c3_g; // 5-bit atom for a 32-bit log.
79 typedef uint32_t c3_l; // little; 31-bit unsigned integer
80 typedef uint32_t c3_m; // mote; also c3_l; LSB first a-z 4-char string.
84 typedef char c3_c; // does not match int8_t or uint8_t
85 typedef int c3_i; // int - really bad
86 typedef uintptr_t c3_p; // pointer-length uint - really really bad
87 typedef intptr_t c3_ps; // pointer-length int - really really bad
89Some of these need explanation. A loobean is a Nock boolean -
90Nock, for mysterious reasons, uses 0 as true (always say "yes")
91and 1 as false (always say "no").
93Nock and/or Hoon cannot tell the difference between a short atom
94and a long one, but at the `u3` level every atom under `2^31` is
95direct. The `c3_l` type is useful to annotate this. A `c3_m` is
96a *mote* - a string of up to 4 characters in a `c3_l`, least
97significant byte first. A `c3_g` should be a 5-bit atom. Of
98course, C cannot enforce these constraints, only document them.
100Use the "bad" - ie, poorly specified - integer types only when
101interfacing with external code that expects them.
103An enormous number of motes are defined in `i/c/motes.h`. There
104is no reason to delete motes that aren't being used, or even to
105modularize the definitions. Keep them alphabetical, though.
107### c3: variables and variable naming
109The C3 style uses Hoon style TLV variable names, with a quasi
110Hungarian syntax. This is weird, but works really well, as long
111as what you're doing isn't hideously complicated. (Then it works
112badly, but we shouldn't need anything hideous in u3.)
114A TLV variable name is a random pronounceable three-letter
115string, sometimes with some vague relationship to its meaning,
116but usually not. Usually CVC (consonant-vowel-consonant) is a
119You should use TLVs much the way math people use Greek letters.
120The same concept should in general get the same name across
121different contexts. When you're working in a given area, you'll
122tend to remember the binding from TLV to concept by sheer power
123of associative memory. When you come back to it, it's not that
124hard to relearn. And of course, when in doubt, comment it.
126Variables take pseudo-Hungarian suffixes, matching in general the
127suffix of the integer type:
129 c3_w wor_w; // 32-bit word
131Unlike in standard Hungarian, there is no change for pointer
132variables. C structure variables take a `_u` suffix.
136The code (from `defs.h`) tells the story:
141 # define _(x) (c3y == (x))
142 # define __(x) ((x) ? c3y : c3n)
143 # define c3a(x, y) __(_(x) && _(y))
144 # define c3o(x, y) __(_(x) || _(y))
146In short, use `_()` to turn a loobean into a boolean, `__` to go
147the other way. Use `!` as usual, `c3y` for yes and `c3n` for no,
148`c3a` for and and `c3o` for or.
152The division between `c3` and `u3` is that you could theoretically
153imagine using `c3` as just a generic C environment. Anything to do
154with nouns is in `u3`.
156### u3: a map of the system
158There are two kinds of symbols in `u3`: regular and irregular.
159Regular symbols follow this pattern:
162 -------------------------------------------------------
163 u3a_ allocation i/n/a.h n/a.c
164 u3e_ persistence i/n/e.h n/e.c
165 u3h_ hashtables i/n/h.h n/h.c
166 u3i_ noun construction i/n/i.h n/i.c
167 u3j_ jet control i/n/j.h n/j.c
168 u3m_ system management i/n/m.h n/m.c
169 u3n_ nock computation i/n/n.h n/n.c
170 u3r_ noun access (error returns) i/n/r.h n/r.c
171 u3t_ profiling i/n/t.h n/t.c
172 u3v_ arvo i/n/v.h n/v.c
173 u3x_ noun access (error crashes) i/n/x.h n/x.c
174 u3z_ memoization i/n/z.h n/z.c
175 u3k[a-g] jets (transfer, C args) i/j/k.h j/[a-g]/*.c
176 u3q[a-g] jets (retain, C args) i/j/q.h j/[a-g]/*.c
177 u3w[a-g] jets (retain, nock core) i/j/w.h j/[a-g]/*.c
179Irregular symbols always start with `u3` and obey no other rules.
180They're defined in `i/n/u.h`. Finally, `i/all.h` includes all
181these headers (fast compilers, yay) and is all you need to
184### u3: noun internals
186A noun is a `u3_noun` - currently defined as a 32-bit `c3_w`.
188If your `u3_noun` is less than `(1 << 31)`, it's a direct atom.
189Every unsigned integer between `0` and `0x7fffffff` inclusive is
192If bit `31` is set in a `u3_noun`, bit `30` is always set - this
193bit is reserved. Bit `29` is `1` if the noun is a cell, `0` if
194it's an atom. Bits `28` through `0` are a word pointer into the
195loom - see below. The structures are:
200 c3_w buf_w[0]; // actually [len_w]
209The only thing that should be mysterious here is `mug_w`, which
210is a 31-bit lazily computed nonzero short hash (FNV currently,
211soon Murmur3). If `mug_w` is 0, the hash is not yet computed.
212We also hijack this field for various hacks, such as saving the
213new address of a noun when copying over.
215Also, the value `0xffffffff` is `u3_none`, which is never a valid
216noun. Use the type `u3_weak` to express that a noun variable may
219### u3: reference counts
221The only really essential thing you need to know about `u3` is
222how to handle reference counts. Everything else, you can skip
225u3 deals with reference-counted, immutable, acyclic nouns.
226Unfortunately, we are not Apple and can't build reference
227counting into your C compiler, so you need to count by hand.
229Every allocated noun (or any allocation object, because our
230allocator is general-purpose) contains a counter which counts the
231number of references to it - typically variables with type
232`u3_noun`. When this counter goes to 0, the noun is freed.
234To tell `u3` that you've added a reference to a noun, call the
235function `u3a_gain()` or its shorthand `u3k()`. (For your
236convenience, this function returns its argument.) To tell `u3`
237that you've destroyed a reference, call `u3a_lose()` or `u3z()`.
239(If you screw up by decrementing the counter too much, `u3` will
240dump core in horrible ways. If you screw up by incrementing it
241too much, `u3` will leak memory. To check for memory leaks,
242set the `bug_o` flag in `u3e_boot()` - eg, run `vere` with `-g`.
243Memory leaks are difficult to debug - the best way to handle
244leaks is just to revert to a version that didn't have them, and
245look over your code again.)
247(You can gain or lose a direct atom. It does nothing.)
249### u3: reference protocols
251*THIS IS THE MOST CRITICAL SECTION IN THE `u3` DOCUMENTATION.*
253The key question when calling a C function in a refcounted world
254is what the function will do to the noun refcounts - and, if the
255function returns a noun, what it does to the return.
257There are two semantic patterns, `transfer` and `retain`. In
258`transfer` semantics, the caller "gives" a use count to the
259callee, which "gives back" any return. For instance, if I have
262 u3_noun foo = u3i_string("foobar");
270Suppose `u3f_futz()` has `transfer` semantics. At `[...]`, my
271code holds one reference to `bar` and zero references to `foo` -
272which has been freed, unless it's part of `bar`. My code now
273owns `bar` and gets to work with it until it's done, at which
274point a `u3z()` is required.
276On the other hand, if `u3f_futz()` has `retain` semantics, we
280 u3_noun foo = u3i_string("foobar");
288because calling `u3f_futz()` does not release our ownership of
289`foo`, which we have to free ourselves.
291But if we free `bar`, we are making a great mistake, because our
292reference to it is not in any way registered in the memory
293manager (which cannot track references in C variables, of
294course). It is normal and healthy to have these uncounted
295C references, but they must be treated with care.
297The bottom line is that it's essential for the caller to know
298the refcount semantics of any function which takes or returns a
299noun. (In some unusual circumstances, different arguments or
300returns in one function may be handled differently.)
302Broadly speaking, as a design question, retain semantics are more
303appropriate for functions which inspect or query nouns. For
304instance, `u3h()` (which takes the head of a noun) retains, so
305that we can traverse a noun tree without constantly incrementing
308Transfer semantics are more appropriate for functions which make
309nouns, which is obviously what most functions do.
311In general, though, in most places it's not worth thinking about
312what your function does. There is a convention for it, which
313depends on where it is, not what it does. Follow the convention.
315### u3: reference conventions
317The `u3` convention is that, unless otherwise specified, *all
318functions have transfer semantics* - with the exception of the
319prefixes: `u3r`, `u3x`, `u3z`, `u3q` and `u3w`. Also, within
320jet directories `a` through `f` (but not `g`), internal functions
321retain (for historical reasons).
323If functions outside this set have retain semantics, they need to
324be commented, both in the `.h` and `.c` file, with `RETAIN` in
325all caps. Yes, it's this important.
327### u3: system architecture
329If you just want to tinker with some existing code, it might be
330enough to understand the above. If not, it's probably worth
331taking the time to look at `u3` as a whole.
333`u3` is designed to work as a persistent event processor.
334Logically, it computes a function of the form
336 f(event, old state) -> (actions, new state)
338Obviously almost any computing model - including, but not limited
339to, Urbit - can be defined in this form. To create the illusion
340of a computer that never loses state and never fails, we:
342- log every event externally before it goes into u3
343- keep a single reference to a permanent state noun.
344- can abort any event without damaging the permanent state.
345- snapshot the permanent state periodically, and/or prune logs.
347### u3: the road model
349`u3` uses a memory design which I'm sure someone has invented
350somewhere before, because it's not very clever, but I've never
351seen it anywhere in particular.
353Every allocation starts with a solid block of memory, which `u3`
354calls the `loom`. How do we allocate on the loom? You're
355probably familiar with the Unix heap-stack design, in which the
356stack grows downward and the heap (malloc arena) grows upward:
360 |------------#################################+++++++++++++|
364A road is a normal heap-stack system, except that the heap
365and stack can point in *either direction*. Therefore, inside
366a road, we can nest another road in the *opposite direction*.
368When the opposite road completes, its heap is left on top of
369the opposite heap's stack. It's no more than the normal
370behavior of a stack machine for all subcomputations to push
371their results on the stack.
373The performance tradeoff of "leaping" - reversing directions in
374the road - is that if the outer computation wants to preserve the
375results of the inner one, not just use them for temporary
376purposes, it has to *copy them*.
378This is a trivial cost in some cases, a prohibitive cost in
379others. The upside, of course, is that all garbage accrued
380in the inner computation is discarded at zero cost.
382The goal of the road system is the ability to *layer* memory
383models. If you are allocating on a road, you have no idea
384how deep within a nested road system you are - in other words,
385you have no idea exactly how durable your result may be.
386But free space is never fragmented within a road.
388Roads do not reduce the generality or performance of a memory
389system, since even the most complex GC system can be nested
390within a road at no particular loss of performance - a road
391is just a block of memory.
393Each road (`u3a_road` to be exact) uses four pointers: `rut` is
394the bottom of the arena, `hat` the top of the arena, `mat` the
395bottom of the stack, `cap` the top of the stack. (Bear in mind
396that the road "stack" is not actually used as the C function-call
397stack, though it probably should be.)
399A "north" road has the stack high and the heap low:
403 |~~~~~~~~~~~~-------##########################+++++++$~~~~~|
407A "south" road is the other way around:
411 |~~~~~~~~~~~~$++++++##########################--------~~~~~|
415Legend: `-` is durable storage (heap); `+` is temporary storage
416(stack); `~` is deep storage (immutable); `$` is the allocation
417frame `#` is free memory.
419Pointer restrictions: pointers stored in `+` can point anywhere.
420Pointers in `-` can only point to `-` or `~`; pointers in `~`
423To "leap" is to create a new inner road in the `###` free space.
424but in the reverse direction, so that when the inner road
425"falls" (terminates), its durable storage is left on the
426temporary storage of the outer road.
428`u3` keeps a global variable, `u3_Road` or its alias `u3R`, which
429points to the current road. (If we ever run threads in inner
430roads - see below - this will become a thread-local variable.)
431Relative to `u3R`, `+` memory is called `junior` memory; `-`
432memory is `normal` memory; `~` is `senior` memory.
434### u3: explaining the road model
438We're now ready to understand why the road system works so
439logically with the event and persistence model.
441The key is that *we don't update refcounts in senior memory.*
442A pointer from an inner road to an outer road is not counted.
443Also, the outmost, or `surface` road, is the only part of the
444image that gets checkpointed.
446So the surface road contains the entire durable state of `u3`.
447When we process an event, or perform any kind of complicated or
448interesting calculation, *we process it in an inner road*. If
449its results are saved, they need to be copied.
451Since processing in an inner road does not touch surface memory,
452(a) we can leave the surface road in a read-only state and not
453mark its pages dirty; (b) we can abort an inner calculation
454without screwing up the surface; and (c) because inner results
455are copied onto the surface, the surface doesn't get fragmented.
457All of (a), (b) and (c) are needed for checkpointing to be easy.
458It might be tractable otherwise, but easy is even better.
460Moreover, while the surface is most definitely single-threaded,
461we could easily run multiple threads in multiple inner roads
462(as long as the threads don't have pointers into each others'
463memory, which they obviously shouldn't).
465Moreover, in future, we'll experiment more with adding road
466control hints to the programmer's toolbox. Reference counting is
467expensive. We hypothesize that in many - if not most - cases,
468the programmer can identify procedural structures whose garbage
469should be discarded in one step by copying the results. Then,
470within the procedure, we can switch the allocator into `sand`
471mode, and stop tracking references at all.
473### u3: rules for C programming
475There are two levels at which we program in C: (1) above the
476interpreter; (2) within the interpreter or jets. These have
477separate rules which need to be respected.
479### u3: rules above the interpreter
481In its relations with Unix, Urbit follows a strict rule of "call
482me, I won't call you." We do of course call Unix system calls,
483but only for the purpose of actually computing.
485Above Urbit, you are in a normal C/Unix programming environment
486and can call anything in or out of Urbit. Note that when using
487`u3`, you're always on the surface road, which is not thread-safe
488by default. Generally speaking, `u3` is designed to support
489event-oriented, single-threaded programming.
491If you need threads which create nouns, you could use
492`u3m_hate()` and `u3m_love()` to run these threads in subroads.
493You'd need to make the global road pointer, `u3R`, a thread-local
494variable instead. This seems perfectly practical, but we haven't
495done it because we haven't needed to.
497### u3: rules within the interpreter
499Within the interpreter, your code can run either in the surface
500road or in a deep road. You can test this by testing
504ie: does the pier's home road equal the current road pointer?
506Normally in this context you assume you're obeying the rules of
507running on an inner road, ie, "deep memory." Remember, however,
508that the interpreter *can* run on surface memory - but anything
509you can do deep, you can do on the surface. The converse is by
512In deep memory, think of yourself as if in a signal handler.
513Your execution context is extremely fragile and may be terminated
514without warning or cleanup at any time (for instance, by ^C).
516For instance, you can't call `malloc` (or C++ `new`) in your C
517code, because you don't have the right to modify data structures
518at the global level, and will leave them in an inconsistent state
519if your inner road gets terminated. (Instead, use our drop-in
520replacements, `u3a_malloc()`, `u3a_free()`, `u3a_realloc()`.)
522A good example is the different meaning of `c3_assert()` inside
523and outside the interpreter. At either layer, you can use
524regular assert(), which will just kill your process. On the
525surface, `c3_assert()` will just... kill your process.
527In deep execution, `c3_assert()` will issue an exception that
528queues an error event, complete with trace stack, on the Arvo
529event queue. Let's see how this happens.
533You produce an exception with
535 /* u3m_bail(): bail out. Does not return.
539 ** %exit :: semantic failure
540 ** %evil :: bad crypto
541 ** %intr :: interrupt
542 ** %fail :: execution failure
543 ** %foul :: assert failure
544 ** %need :: network block
545 ** %meme :: out of memory
546 ** %time :: timed out
547 ** %oops :: assertion failure
550 u3m_bail(c3_m how_m);
552Broadly speaking, there are two classes of exception: internal
553and external. An external exception begins in a Unix signal
554handler. An internal exception begins with a call to longjmp()
557There are also two kinds of exception: mild and severe. An
558external exception is always severe. An internal exception is
559normally mild, but some (like `c3__oops`, generated by
560`c3_assert()`) are severe.
562Either way, exceptions come with a stack trace. The `u3` nock
563interpreter is instrumented to retain stack trace hints and
564produce them as a printable `(list tank)`.
566Mild exceptions are caught by the first virtualization layer and
567returned to the caller, following the behavior of the Nock
568virtualizer `++mock` (in `hoon.hoon`)
570Severe exceptions, or mild exceptions at the surface, terminate
571the entire execution stack at any depth and send the cumulative
572trace back to the `u3` caller.
574For instance, `vere` uses this trace to construct a `%crud`
575event, which conveys our trace back toward the Arvo context where
576it crashed. This lets any UI component anywhere, even on a
577remote node, render the stacktrace as a consequence of the user's
578action - even if its its direct cause was (for instance) a Unix
581### u3: C structures on the loom
583Normally, all data on the loom is nouns. Sometimes we break this
584rule just a little, though - eg, in the `u3h` hashtables.
586To point to non-noun C structs on the loom, we use a `u3_post`,
587which is just a loom word offset. A macro lets us declare this
588as if it was a pointer:
590 typedef c3_w u3_post;
591 #define u3p(type) u3_post
593Some may regard this as clever, others as pointless. Anyway, use
594`u3to()` and `u3of()` to convert to and from pointers.
596When using C structs on the loom - generally a bad idea - make
597sure anything which could be on the surface road is structurally
598portable, eg, won't change size when the pointer size changes.
599(Note also: we consider little-endian, rightly or wrongly, to
600have won the endian wars.)
602## u3: API overview by prefix
604Let's run through the `u3` modules one by one. All public
605functions are commented, but the comments may be cryptic.
611 /* u3m_boot(): start the u3 system.
614 u3m_boot(c3_o nuu_o, c3_o bug_o, c3_c* dir_c);
616`nuu_o` is `c3y` (yes, `0`) if you're creating a new pier,
617`c3n` (no, `1`) if you're loading an existing one. `bug_o`
618is `c3y` if you want to test the garbage-collector, `c3n`
619otherwise. `dir_c` is the directory for the pier files.
621`u3m_boot()` expects an `urbit.pill` file to load the kernel
622from. It will try first `$dir/.urb.urbit.pill`, then `U3_LIB`.
624Any significant computation with nouns, certainly anything Turing
625complete, should be run (a) virtualized and (b) in an inner road.
626These are slightly different things, but at the highest level we
627bundle them together for your convenience, in `u3m_soft()`:
629 /* u3m_soft(): system soft wrapper. unifies unix and nock errors.
631 ** Produces [%$ result] or [%error (list tank)].
634 u3m_soft(c3_w sec_w, u3_funk fun_f, u3_noun arg);
636`sec_w` is the number of seconds to time out the computation.
637`fun_f` is a C function accepting `arg`.
639The result of `u3m_soft()` is a cell whose head is an atom. If
640the head is `%$` - ie, `0` - the tail is the result of
641`fun_f(arg)`. Otherwise, the head is a `term` (an atom which is
642an LSB first string), and the tail is a `(list tank)` (a list of
643`tank` printables - see `++tank` in `hoon.hoon`). Error terms
644should be the same as the exception terms above.
646If you're confident that your computation won't fail, you can
647use `u3m_soft_sure()`, `u3m_soft_slam()`, or `u3m_soft_nock()`
648for C functions, Hoon function calls, and Nock invocations.
649Caution - this returns just the result, and asserts globally.
651All the `u3m_soft` functions above work *only on the surface*.
652Within the surface, virtualize with `u3m_soft_run()`. Note that
653this takes a `fly` (a namespace gate), thus activating the `11`
654super-operator in the nock virtualizer, `++mock`. When actually
655using the `fly`, call `u3m_soft_esc()`. Don't do either unless
656you know what you're doing!
658For descending into a subroad *without* Nock virtualization,
659use `u3m_hate()` and `u3m_love` respectively. Hating enters
660a subroad; loving leaves it, copying out a product noun.
662Other miscellaneous tools in `u3m`: `u3m_file()` loads a Unix
663file as a Nock atom; `u3m_water()` measures the boundaries of
664the loom in current use (ie, watermarks); and a variety of
665prettyprinting routines, none perfect, are available, mainly for
666debugging printfs: `u3m_pretty()`, `u3m_p()`, `u3m_tape()` and
669It's sometimes nice to run a mark-and-sweep garbage collector,
670`u3m_grab()`, which collects the world from a list of roots,
671and asserts if it finds any leaks or incorrect refcounts. This
672tool is for debugging and long-term maintenance only; refcounts
677The jet system, `u3j`, is what makes `u3` and `nock` in any sense
678a useful computing environment. Except perhaps `u3a` (there is
679really no such thing as a trivial allocator, though `u3a` is
680dumber than most) - `u3j` is the most interesting code in `u3`.
682Let's consider the minor miracle of driver-to-battery binding
683which lets `u3j` work - and decrement not be `O(n)` - without
684violating the precisely defined semantics of pure Nock, *ever*.
686It's easy to assume that jets represent an architectural coupling
687between Hoon language semantics and Nock interpreter internals.
688Indeed such a coupling would be wholly wrongtious and un-Urbit.
689But the jet system is not Hoon-specific. It is specific to nock
690runtime systems that use a design pattern we call a `core`.
692#### u3j: core structure
694A core is no more than a cell `[code data]`, in which a `code` is
695either a Nock formula or a cell of `code`s, and `data` is anything.
696In a proper core, the subject each formula expects is the core
699Except for the arbitrary decision to make a core `[code data]`,
700(or as we sometimes say, `[battery payload]`), instead of `[data
701code]`, any high-level language transforming itself to Nock would
704So jets are in fact fully general. Broadly speaking, the jet
705system works by matching a C *driver* to a battery. When the
706battery is invoked with Nock operator `9`, it must be found in
707associative memory and linked to its driver. Then we link the
708formula axis of the operation (`a` in `[9 a b]`) to a specific
709function in the driver.
711To validate this jet binding, we need to know two things. One,
712we need to know the C function actually is a perfect semantic
713match for the Nock formula. This can be developed with driver
714test flags, which work, and locked down with a secure formula
715hash in the driver, which we haven't bothered with just yet.
716(You could also try to develop a formal method for verifying
717that C functions and Nock formulas are equivalent, but this is
718a research problem for the future.)
720Two, we need to validate that the payload is appropriate for the
721battery. We should note that jets are a Nock feature and have no
722reference to Hoon. A driver which relies on the Hoon type system
723to only pair it with valid payloads is a broken driver, and
724breaks the Nock compliance of the system as a whole. So don't.
726Now, a casual observer might look at `[battery payload]` and
727expect the simplest case of it to be `[formula subject]`. That
728is: to execute a simple core whose battery is a single formula,
733Then, naturally, when we go from Hoon or a high-level language
734containing functions down to Nock, `[function arguments]` turns
735into `[formula subject]`. This seems like an obvious design, and
736we mention it only because it is *completely wrong*.
738Rather, to execute a one-armed core like the above, we run
742and the normal structure of a `gate`, which is simply Urbitese
745 [formula [sample context]]
747where `sample` is Urbitese for "arguments" - and `context`, any
748Lisper will at once recognize, is Urbitese for "environment."
750To `slam` or call the gate, we simply replace the default sample
751with the caller's data, then nock the formula on the entire gate.
753What's in the context? Unlike in most dynamic languages, it is
754not some secret system-level bag of tricks. Almost always it is
755another core. This onion continues until at the bottom, there is
756an atomic constant, conventionally is the kernel version number.
758Thus a (highly desirable) `static` core is one of the form
761 [battery static-core]
763ie, a solid stack of nested libraries without any dynamic data.
764The typical gate will thus be, for example,
766 [formula [sample [battery battery battery constant]]]
768but we would be most foolish to restrict the jet mechanism to
769cores of this particular structure. We cannot constrain a
770payload to be `[sample static-core]`, or even `[sample core]`.
771Any such constraint would not be rich enough to handle Hoon,
772let alone other languages.
776There are two fundamental rules of computer science: (1) every
777system is best understood through its state; (2) less state is
778better than more state. Sadly, a pier has three different jet
779state systems: `cold`, `warm` and `hot`. It needs all of them.
781Hot state is associated with this particular Unix process. The
782persistent pier is portable not just between process and process,
783but machine and machine or OS and OS. The set of jets loaded
784into a pier may itself change (in theory, though not in the
785present implementation) during the lifetime of the process. Hot
786state is a pure C data structure.
788Cold state is associated with the logical execution history of
789the pier. It consists entirely of nouns and ignores restarts.
791Warm state contains all dependencies between cold and hot
792state. It consists of C structures allocated on the loom.
794Warm state is purely a function of cold and hot states, and
795we can wipe and regenerate it at any time. On any restart where
796the hot state might have changed, we clear the warm state
799There is only one hot state, the global jet dashboard
800`u3j_Dash` or `u3D` for short. In the present implementation,
801u3D is a static structure not modified at runtime, except for
802numbering itself on process initialization. This structure -
803which embeds function pointers to all the jets - is defined
804in `j/tree.c`. The data structures:
806 /* u3j_harm: driver arm.
808 typedef struct _u3j_harm {
809 c3_c* fcs_c; // `.axe` or name
810 u3_noun (*fun_f)(u3_noun); // compute or 0 / semitransfer
811 c3_o ice; // perfect (don't test)
812 c3_o tot; // total (never punts)
813 c3_o liv; // live (enabled)
816 /* u3j_core: C core driver.
818 typedef struct _u3j_core {
819 c3_c* cos_c; // control string
820 struct _u3j_harm* arm_u; // blank-terminated static list
821 struct _u3j_core* dev_u; // blank-terminated static list
822 struct _u3j_core* par_u; // dynamic parent pointer
823 c3_l jax_l; // dynamic jet index
826 /* u3e_dash, u3_Dash, u3D: jet dashboard singleton
828 typedef struct _u3e_dash {
829 u3j_core* dev_u; // null-terminated static list
830 c3_l len_l; // ray_u filled length
831 c3_l all_l; // ray_u allocated length
832 u3j_core* ray_u; // dynamic driver array
835Warm and cold state is *per road*. In other words, as we nest
836roads, we also nest jet state. The jet state in the road is:
838 struct { // jet dashboard
839 u3p(u3h_root) har_p; // warm state
840 u3_noun das; // cold state
843In case you understand Hoon, `das` (cold state) is a `++dash`,
844and `har_p` (warm state) is a map from battery to `++calx`:
846 ++ bane ,@tas :: battery name
847 ++ bash ,@uvH :: label hash
848 ++ bosh ,@uvH :: local battery hash
849 ++ batt ,* :: battery
851 $: jax=,@ud :: hot core index
852 hap=(map ,@ud ,@ud) :: axis/hot arm index
853 lab=path :: label as path
854 jit=* :: arbitrary data
856 ++ calx (trel calf (pair bash cope) club) :: cached by battery
857 ++ clog (pair cope (map batt club)) :: identity record
858 ++ club (pair corp (map term nock)) :: battery pattern
859 ++ cope (trel bane axis (each bash noun)) :: core pattern
861 ++ corp (each core batt) :: parent or static
862 ++ dash (map bash clog) :: jet system
864The driver index `jax` in a `++calx` is an index into `ray_u` in the
865dashboard - ie, a pointer into hot state. This is why the warm
866state has to be reset when we reload the pier in a new process.
868Why is jet state nested? Nock of course is a functional system,
869so as we compute we don't explicitly create state. Jet state is
870an exception to this principle (which works only because it can't
871be semantically detected from Nock/Hoon) - but it can't violate
872the fundamental rules of the allocation system.
874For instance, when we're on an inner road, we can't allocate on
875an outer road, or point from an outer road to an inner. So if we
876learn something - like a mapping from battery to jet - in the
877inner road, we have to keep it in the inner road.
879Mitigating this problem, when we leave an inner road (with
880`u3m_love()`), we call `u3j_reap()` to promote jet information in
881the dying road. Reaping promotes anything we've learned about
882any battery that either (a) already existed in the outer road, or
883(b) is being saved to the outer road.
887Jet binding starts with a `%fast` hint. (In Hoon, this is
888produced by the runes `~%`, for the general case, or `~/`
889for simple functions.) To bind a jet, execute a formula of the
892 [10 [%fast clue-formula] core-formula]
894`core-formula` assembles the core to be jet-propelled.
895`clue-formula` produces the hint information, or `++clue`
896above, which we want to annotate it with.
898A clue is a triple of name, parent, and hooks:
900 ++ clue (trel chum nock (list (pair term nock)))
902The name, or `++chum`, has a bunch of historical structure which
903we don't need (cleaning these things up is tricky), but just gets
904flattened into a term.
906The parent axis is a nock formula, but always reduces to a simple
907axis, which is the address of this core's *parent*. Consider
908again an ordinary gate
910 [formula [sample context]]
912Typically the `context` is itself a library core, which itself
913has a jet binding. If so, the parent axis of this gate is `7`.
915If the parent is already bound - and the parent *must* be already
916bound, in this road or a road containing it - we can hook this core
917bottom-up into a tree hierarchy. Normally the child core is
918produced by an arm of the parent core, so this is not a problem -
919we wouldn't have the child if we hadn't already made the parent.
921The clue also contains a list of *hooks*, named nock formulas on
922the core. Usually these are arms, but they need not be. The
923point is that we often want to call a core from C, in a situation
924where we have no type or other source information. A common case
925of this is a complex system in which we're mixing functions which
926are jet-propelled with functions that aren't.
928In any case, all the information in the `%fast` hint goes to
929`u3j_mine()`, which registers the battery in cold state (`das` in
930`jed` in `u3R`), then warm state (`har_p` in `jed`).
932It's essential to understand that the `%fast` hint has to be,
933well, fast - because we apply it whenever we build a core. For
934instance, if the core is a Hoon gate - a function - we will call
935`u3j_mine` every time the function is called.
937### u3j: the cold jet dashboard
939For even more fun, the jet tree is not actually a tree of
940batteries. It's a tree of battery *labels*, where a label is
941an [axis term] path from the root of the tree. (At the root,
942if the core pattern is always followed properly, is a core whose
943payload is an atomic constant, conventionally the Hoon version.)
945Under each of these labels, it's normal to have an arbitrary
946number of different Nock batteries (not just multiple copies
947of the same noun, a situation we *do* strive to avoid). For
948instance, one might be compiled with debugging hints, one not.
950We might even have changed the semantics of the battery without
951changing the label - so long as those semantics don't invalidate
954et tree. For instance, it's normal to have
955two equivalent Nock batteries at the same time in one pier: one
956battery compiled with debugging hints, one not.
958Rather, the jet tree is a semantic hierarchy. The root of the
959hierarchy is a constant, by convention the Hoon kernel version
960because any normal jet-propelled core has, at the bottom of its
961onion of libraries, the standard kernel. Thus if the core is
963 [foo-battery [bar-battery [moo-battery 164]]]
965we can reverse the nesting to construct a hierarchical core
970extends the static core `164/moo/bar` by wrapping the `foo`
971battery (ie, in Hoon, `|%`) around it. With the core above,
972you can compute `foo` stuff, `bar` stuff, and `moo` stuff.
975Not all cores are static, of course - they may contain live data,
976like the sample in a gate (ie, argument to a function). Once
977again, it's important to remember that we track jet bindings not
978by the core, which may not be static, but by the battery, which
981(And if you're wondering how we can use a deep noun like a Nock
982formula or battery as a key in a key-value table, remember
983`mug_w`, the lazily computed short hash, in all boxed nouns.)
985In any case, `das`, the dashboard, is a map from `bash` to jet
986location record (`++clog`). A `clog` in turn contains two kinds
987of information: the `++cope`, or per-location noun; and a map of
988batteries to a per-battery `++club`.
990The `cope` is a triple of `++bane` (battery name, right now just
991a `term`); `++axis`, the axis, within *this* core, of the parent;
992and `(each bash noun)`, which is either `[0 bash]` if the parent
993is another core, or `[1 noun]`, for the constant noun (like
994`164`) if there is no parent core.
996A `bash` is just the noun hash (`++sham`) of a `cope`, which
997uniquely expresses the battery's hierarchical location without
998depending on the actual formulas.
1000The `club` contains a `++corp`, which we use to actually validate
1001the core. Obviously jet execution has to be perfectly compatible
1002with Nock. We search on the battery, but getting the battery
1003right is not enough - a typical battery is dependent on its
1004context. For example, your jet-propelled library function is
1005very likely to call `++dec` or other advanced kernel technology.
1006If you've replaced the kernel in your context with something
1007else, we need to detect this and not run the jet.
1009There are two cases for a jet-propelled core - either the entire
1010core is a static constant, or it isn't. Hence the definition
1013 ++ corp (each core batt) :: parent or static
1015Ie, a `corp` is `[0 core]` or `[1 batt]`. If it's static -
1016meaning that the jet only works with one specific core, ie, the
1017parent axis of each location in the hierarchy is `3` - we can
1018validate with a single comparison. Otherwise, we have to recurse
1019upward by checking the parent.
1021Note that there is at present no way to force a jet to depend on
1024### u3j: the warm jet dashboard
1026We don't use the cold state to match jets as we call them. We
1027use the cold state to register jets as we find them, and also to
1028rebuild the warm state after the hot state is reset.
1030What we actually use at runtime is the warm state, `jed->har_p`,
1031which is a `u3h` (built-in hashtable), allocated on the loom,
1032from battery to `++calx`.
1034A `calx` is a triple of a `++calf`, a `[bash cope]` cell, and a
1035`club`. The latter two are all straight from cold state.
1037The `calf` contains warm data dependent on hot state. It's a
1038quadruple: of `jax`, the hot driver index (in `ray_u` in
1039`u3j_dash`); `hap`, a table from arm axis (ie, the axis of each
1040formula within the battery) to driver arm index (into `arm_u` in
1041`u3j_core`); `lab`, the complete label path; and `jit`, any
1042other dynamic data that may speed up execution.
1044We construct `hap`, when we create the calx, by iterating through
1045the arms registered in the `u3j_core`. Note the way a `u3j_harm`
1046declares itself, with the string `fcs_c` which can contain either
1047an axis or a name. Most jetted cores are of course gates, which
1048have one formula at one axis within the core: `fcs_c` is `".3"`.
1050But we do often have fast cores with more complex arm structure,
1051and it would be sad to have to manage their axes by hand. To use
1052an `fcs_c` with a named arm, it's sufficient to make sure the
1053name is bound to a formula `[0 axis]` in the hook table.
1055`jit`, as its name suggests, is a stub where any sort of
1056optimization data computed on battery registration might go. To
1057use it, fill in the `_cj_jit()` function.
1059### u3j: the hot dashboard
1061Now it should be easy to see how we actually invoke jets. Every
1062time we run a nock `9` instruction (pretty often, obviously), we
1063have a core and an axis. We pass these to `u3j_kick()`, which
1064will try to execute them.
1066Because nouns with a reference count of 1 are precious,
1067`u3j_kick()` has a tricky reference control definition. It
1068reserves the right to return `u3_none` in the case where there is
1069no driver, or the driver does not apply for this case; in this
1070case, it retains argument `cor`. If it succeeds, though, it
1073`u3j_kick()` searches for the battery (always the head of the
1074core, of course) in the hot dashboard. If the battery is
1075registered, it searches for the axis in `hap` in the `calx`.
1076If it exists, the core matches a driver and the driver jets this
1077arm. If not, we return `u3_none`.
1079Otherwise, we call `fun_f` in our `u3j_harm`. This obeys the
1080same protocol as `u3j_kick()`; it can refuse to function by
1081returning `u3_none`, or consume the noun.
1083Besides the actual function pointer `fun_f`, we have some flags
1084in the `u3j_harm` which tell us how to call the arm function.
1086If `ice` is yes (`&`, `0`), the jet is known to be perfect and we
1087can just trust the product of `fun_f`. Otherwise, we need to run
1088*both* the Nock arm and `fun_f`, and compare their results.
1090(Note that while executing the C side of this test, we have to
1091set `ice` to yes; on the Nock side, we have to set `liv` to no.
1092Otherwise, many non-exponential functions become exponential.
1093When auto-testing jets in this way, the principle is that the
1094test is on the outermost layer of recursion.)
1096(Note also that anyone who multi-threads this execution
1097environment has a slight locking problem with these flags if arm
1098testing is multi-threaded.)
1100If `tot` is yes, (`&`, `0`), the arm function is *total* and has
1101to return properly (though it can still return *u3_none*).
1102Otherwise, it is *partial* and can `u3_cm_bail()` out with
1103c3__punt. This feature has a cost: the jet runs in a subroad.
1105Finally, if `liv` is no (`|`, 1), the jet is off and doesn't run.
1107It should be easy to see how the tree of cores gets declared -
1108precisely, in `j/dash.c`. We declare the hierarchy as a tree
1109of `u3j_core` structures, each of which comes with a static list
1110of arms `arm_u` and sub-cores `dev_u`.
1112In `u3j_boot()`, we traverse the hierarchy, fill in parent
1113pointers `par_u`, and enumerate all `u3j_core` structures
1114into a single flat array `u3j_dash.ray_u`. Our hot state
1115then appears ready for action.
1117### u3j: jet functions
1119At present, all drivers are compiled statically into `u3`. This is
1120not a long-term permanent solution or anything. However, it will
1121always be the case with a certain amount of core functionality.
1123For instance, there are some jet functions that we need to call
1124as part of loading the Arvo kernel - like `++cue` to unpack a
1125noun from an atom. And obviously it makes sense, when jets are
1126significant enough to compile into `u3`, to export their symbols
1127in headers and the linker.
1129There are three interface prefixes for standard jet functions:
1130`u3k`, `u3q`, and `u3w`. All jets have `u3w` interfaces; most
1131have `u3q`; some have `u3k`. Of course the actual logic is
1134`u3w` interfaces use the same protocol as `fun_f` above: the
1135caller passes the entire core, which is retained if the function
1136returns `u3_none`, transferred otherwise. Why? Again, use
1137counts of 1 are special and precious for performance hackers.
1139`u3q` interfaces break the core into C arguments, *retain* noun
1140arguments, and *transfer* noun returns. `u3k` interfaces are the
1141same, except with more use of `u3_none` and other simple C
1142variations on the Hoon original, but *transfer* both arguments
1143and returns. Generally, `u3k` are most convenient for new code.
1145Following `u3k/q/w` is `[a-f]`, corresponding to the 6 logical
1146tiers of the kernel, or `g` for user-level jets. Another letter
1147is added for functions within subcores. The filename, under
1148`j/`, follows the tier and the function name.
1150For instance, `++add` is `u3wa_add(cor)`, `u3qa_add(a, b)`, or
1151`u3ka_add(a, b)`, in `j/a/add.c`. `++get` in `++by` is
1152`u3wdb_get(cor)`, `u3kdb_get(a, b)`, etc, in `j/d/by_get.c`.
1154For historical reasons, all internal jet code in `j/[a-f]`
1155*retains* noun arguments, and *transfers* noun results. Please
1156do not do this in new `g` jets! The new standard protocol is to
1157transfer both arguments and results.
1159### u3a: allocation functions
1161`u3a` allocates on the current road (u3R). Its internal
1162structures are uninteresting and typical of a naive allocator.
1164The two most-used `u3a` functions are `u3a_gain()` to add a
1165reference count, and `u3a_lose()` to release one (and free the
1166noun, if the use count is zero). For convenience, `u3a_gain()`
1167returns its argument. The pair are generally abbreviated with
1168the macros `u3k()` and `u3z()` respectively.
1170Normally we create nouns through `u3i` functions, and don't call
1171the `u3a` allocators directly. But if you do:
1173One, there are *two* sets of allocators: the word-aligned
1174allocators and the fully-aligned (ie, malloc compatible)
1175allocators. For instance, on a typical OS X setup, malloc
1176produces 16-byte aligned results - needed for some SSE
1179These allocators are *not compatible*. For 32-bit alignment
1180as used in nouns, call
1182 /* u3a_walloc(): allocate storage measured in words.
1185 u3a_walloc(c3_w len_w);
1187 /* u3a_wfree(): free storage.
1190 u3a_wfree(void* lag_v);
1192 /* u3a_wealloc(): word realloc.
1195 u3a_wealloc(void* lag_v, c3_w len_w);
1197For full alignment, call:
1199 /* u3a_malloc(): aligned storage measured in bytes.
1202 u3a_malloc(size_t len_i);
1204 /* u3a_realloc(): aligned realloc in bytes.
1207 u3a_realloc(void* lag_v, size_t len_i);
1209 /* u3a_realloc2(): gmp-shaped realloc.
1212 u3a_realloc2(void* lag_v, size_t old_i, size_t new_i);
1214 /* u3a_free(): free for aligned malloc.
1217 u3a_free(void* tox_v);
1219 /* u3a_free2(): gmp-shaped free.
1222 u3a_free2(void* tox_v, size_t siz_i);
1224There are also a set of special-purpose allocators for building
1225atoms. When building atoms, please remember that it's incorrect
1226to have a high 0 word - the word length in the atom structure
1227must be strictly correct.
1229Of course, we don't always know how large our atom will be.
1230Therefore, the standard way of building large atoms is to
1231allocate a block of raw space with `u3a_slab()`, then chop off
1232the end with `u3a_malt()` (which does the measuring itself)
1233or `u3a_mint()` in case you've measured it yourself.
1235Once again, *do not call `malloc()`* (or C++ `new`) within any
1236code that may be run within a jet. This will cause rare sporadic
1237corruption when we interrupt execution within a `malloc()`. We'd
1238just override the symbol, but `libuv` uses `malloc()` across
1239threads within its own synchronization primitives - for this to
1240work with `u3a_malloc()`, we'd have to introduce our own locks on
1241the surface-level road (which might be a viable solution).
1243### u3n: nock execution
1245The `u3n` routines execute Nock itself. On the inside, they have
1246a surprising resemblance to the spec proper (the only interesting
1247detail is how we handle tail-call elimination) and are, as one
1248would expect, quite slow. (There is no such thing as a fast tree
1251There is only one Nock, but there are lots of ways to call it.
1252(Remember that all `u3n` functions *transfer* C arguments and
1255The simplest interpreter, `u3n_nock_on(u3_noun bus, u3_noun fol)`
1256invokes Nock on `bus` (the subject) and `fol` (the formula).
1257(Why is it`[subject formula]`, not `[formula subject]`? The same
1258reason `0` is true and `1` is false.)
1260A close relative is `u3n_slam_on(u3_noun gat, u3_noun sam)`,
1261which slams a *gate* (`gat`) on a sample (`sam`). (In a normal
1262programming language which didn't talk funny and was retarded,
1263`u3n_slam_on()` would call a function on an argument.) We could
1264write it most simply as:
1267 u3n_slam_on(u3_noun gat, u3_noun sam)
1269 u3_noun pro = u3n_nock_on
1270 (u3nc(u3k(u3h(gat)),
1271 u3nc(sam, u3k(u3t(u3t(gat))))),
1277Simpler is `u3n_kick_on(u3_noun gat)`, which slams a gate (or,
1278more generally, a *trap* - because sample structure is not even
1279needed here) without changing its sample:
1282 u3n_kick_on(u3_noun gat, u3_noun sam)
1284 return u3n_nock_on(gat, u3k(u3h(gat)));
1287The `_on` functions in `u3n` are all defined as pure Nock. But
1288actually, even though we say we don't extend Nock, we do. But we
1291Note that `u3` has a well-developed error handling system -
1292`u3m_bail()` to throw an exception, `u3m_soft_*` to catch one.
1293But Nock has no exception model at all. That's okay - all it
1294means if that if an `_on` function bails, the exception is an
1295exception in the caller.
1297However, `u3`'s exception handling happens to match a convenient
1298virtual super-Nock in `hoon.hoon`, the infamous `++mock`. Of
1299course, Nock is slow, and `mock` is Nock in Nock, so it is
1300(logically) super-slow. Then again, so is decrement.
1302With the power of `u3`, we nest arbitrary layers of `mock`
1303without any particular performance cost. Moreover, we simply
1304treat Nock proper as a special case of `mock`. (More precisely,
1305the internal VM loop is `++mink` and the error compiler is
1306`++mook`. But we call the whole sandbox system `mock`.)
1308The nice thing about `mock` functions is that (by executing
1309within `u3m_soft_run()`, which as you may recall uses a nested
1310road) they provide both exceptions and the namespace operator -
1311`.^` in Hoon, which becomes operator `11` in `mock`.
1313`11` requires a namespace function, or `fly`, which produces a
1314`++unit` - `~` (`0`) for no binding, or `[0 value]`. The sample
1315to a `fly` is a `++path`, just a list of text `span`.
1317`mock` functions produce a `++toon`. Fully elaborated:
1319 ++ noun ,* :: any noun
1320 ++ path (list ,@ta) :: namespace path
1321 ++ span ,@ta :: text-atom (ASCII)
1322 ++ toon $% [%0 p=noun] :: success
1323 [%1 p=(list path)] :: blocking paths
1324 [%2 p=(list tank)] :: stack trace
1326 ++ tank :: printable
1327 $% [%leaf p=tape] :: flat text
1328 $: %palm :: backstep list
1329 p=[p=tape q=tape r=tape s=tape] :: mid cap open close
1330 q=(list tank) :: contents
1332 $: %rose :: straight list
1333 p=[p=tape q=tape r=tape] :: mid open close
1334 q=(list tank) :: contents
1338(Note that `tank` is overdesigned and due for replacement.)
1340What does a `toon` mean? Either your computation succeded (`[0
1341noun]`, or could not finish because it blocked on one or more
1342global paths (`[1 (list path)]`), or it exited with a stack trace
1345Note that of all the `u3` exceptions, only `%exit` is produced
1346deterministically by the Nock definition. Therefore, only
1347`%exit` produces a `2` result. Any other argument to
1348`u3m_bail()` will unwind the virtualization stack all the way to
1349the top - or to be more exact, to `u3m_soft_top()`.
1351In any case, the simplest `mock` functions are `u3n_nock_un()`
1352and `u3n_slam_un()`. These provide exception control without
1353any namespace change, as you can see by the code:
1355 /* u3n_nock_un(): produce .*(bus fol), as ++toon.
1358 u3n_nock_un(u3_noun bus, u3_noun fol)
1360 u3_noun fly = u3nt(u3nt(11, 0, 6), 0, 0); // |=(a=* .^(a))
1362 return u3n_nock_in(fly, bus, fol);
1365 /* u3n_slam_un(): produce (gat sam), as ++toon.
1368 u3n_slam_un(u3_noun gat, u3_noun sam)
1370 u3_noun fly = u3nt(u3nt(11, 0, 6), 0, 0); // |=(a=* .^(a))
1372 return u3n_slam_in(fly, gat, sam);
1375The `fly` is added as the first argument to `u3n_nock_in()` and
1376`u3n_slam_in()`. Of course, logically, `fly` executes in the
1377caller's exception layer. (Maintaining this illusion is slightly
1378nontrivial.) Finally, `u3n_nock_an()` is a sandbox with a null
1383The only `u3e` function you should need to call is `u3e_save()`,
1384which saves the loom. As it can be restored on any platform,
1385please make sure you don't have any state in the loom that is
1386bound to your process or architecture - except for exceptions
1387like the warm jet state, which is actively purged on reboot.
1389### u3r: reading nouns (weak)
1391As befits accessors they don't make anything, `u3r` noun reading
1392functions always retain their arguments and their returns. They
1393never bail; rather, when they don't work, they return a `u3_weak`
1396Most of these functions are straightforward and do only what
1397their comments say. A few are interesting enough to discuss.
1399`u3r_at()` is the familiar tree fragment function, `/` from the
1400Nock spec. For taking complex nouns apart, `u3r_mean()` is a
1401relatively funky way of deconstructing nouns with a varargs list
1402of `axis`, `u3_noun *`. For cells, triples, etc, decompose with
1403`u3r_cell()`, `u3r_trel()`, etc. For the tagged equivalents, use
1404`u3r_pq()` and friends.
1406`u3r_sing(u3_noun a, u3_noun b)` (true if `a` and `b` are a
1407*single* noun) are interesting because it uses mugs to help it
1408out. Clearly, different nouns may have the same mug, but the
1409same nouns cannot have a different mug. It's important to
1410understand the performance characteristics of `u3r_sing()`:
1411the worst possible case is a comparison of duplicate nouns,
1412which have the same value but were created separately. In this
1413case, the tree is traversed
1415`u3r_sung()` is a deeply funky and frightening version of
1416`u3r_sing()` that unifies pointers to the duplicate nouns it
1417finds, freeing the second copy. Obviously, do not use
1418`u3r_sung()` when you have live, but not reference counted, noun
1419references from C - if they match a noun with a refcount of 1
1420that gets freed, bad things happen.
1422It's important to remember that `u3r_mug()`, which produces a
142331-bit, nonzero insecure hash, uses the `mug_w` slot in any boxed
1424noun as a lazy cache. There are a number of variants of
1425`u3r_mug()` that can get you out of building unneeded nouns.
1427### u3x: reading nouns (bail)
1429`u3x` functions are like `u3r` functions, but instead of
1430returning `u3_none` when (for instance) we try to take the head
1431of an atom, they bail with `%exit`. In other words, they do what
1432the same operation would do in Nock.
1434### u3h: hash tables.
1436We can of course use the Hoon `map` structure as an associative
1437array. This is a balanced treap and reasonably fast. However,
1438it's considerably inferior to a custom structure like an HAMT
1439(hash array-mapped trie). We use `u3_post` to allocate HAMT
1440structures on the loom.
1442(Our HAMT implements the classic Bagwell algorithm which depends
1443on the `gcc` standard directive `__builtin_popcount()`. On a CPU
1444which doesn't support popcount or an equivalent instruction, some
1445other design would probably be preferable.)
1447There's no particular rocket science in the API. `u3h_new()`
1448creates a hashtable; `u3h_free()` destroys one; `u3h_put()`
1449inserts, `u3h_get()` retrieves. You can transform values in a
1450hashtable with `u3h_walk()`.
1452The only funky function is `u3h_gut()`, which unifies keys with
1453`u3r_sung()`. As with all cases of `u3r_sung()`, this must be
1454used with extreme caution.
1458Connected to the `~+` rune in Hoon, via the Nock `%memo` hint,
1459the memoization facility is a general-purpose cache.
1461(It's also used for partial memoization - a feature that'll
1462probably be removed, in which conservative worklist algorithms
1463(which would otherwise be exponential) memoize everything in the
1464subject *except* the worklist. This is used heavily in the Hoon
1465compiler jets (j/f/*.c). Unfortunately, it's probably not
1466possible to make this work perfectly in that it can't be abused
1467to violate Nock, so we'll probably remove it at a later date,
1468instead making `++ut` keep its own monadic cache.)
1470Each `u3z` function comes with a `c3_m` mote which disambiguates
1471the function mapping key to value. For Nock itself, use 0. For
1472extra speed, small tuples are split out in C; thus, find with
1474 u3_weak u3z_find(c3_m, u3_noun);
1475 u3_weak u3z_find_2(c3_m, u3_noun, u3_noun);
1476 u3_weak u3z_find_3(c3_m, u3_noun, u3_noun, u3_noun);
1477 u3_weak u3z_find_4(c3_m, u3_noun, u3_noun, u3_noun, u3_noun);
1481 u3_noun u3z_save(c3_m, u3_noun, u3_noun);
1482 u3_noun u3z_save_2(c3_m, u3_noun, u3_noun, u3_noun);
1483 u3_noun u3z_save_3(c3_m, u3_noun, u3_noun, u3_noun, u3_noun);
1484 u3_noun u3z_save_4(c3_m, u3_noun, u3_noun, u3_noun, u3_noun, u3_noun);
1486where the value is the last argument. To eliminate duplicate
1492`u3z` functions retain keys and transfer values.
1494The `u3z` cache, built on `u3h` hashes, is part of the current
1495road, and goes away when it goes away. (In future, we may wish
1496to promote keys/values which outlive the road, as we do with jet
1497state.) There is no cache reclamation at present, so be careful.
1499### u3t: tracing and profiling.
1503### u3v: the Arvo kernel
1505An Arvo kernel - or at least, a core that compiles with the Arvo
1506interface - is part of the global `u3` state. What is an Arvo
1507core? Slightly pseudocoded:
1511 ++ come |= [yen=@ ova=(list ovum) nyf=pone] :: 11
1512 ^- [(list ovum) _+>]
1514 ++ keep |= [now=@da hap=path] :: 4
1517 ++ load |= [yen=@ ova=(list ovum) nyf=pane] :: 86
1518 ^- [(list ovum) _+>]
1520 ++ peek |= [now=@da path] :: 87
1523 ++ poke |= [now=@da ovo=ovum] :: 42
1524 ^- [(list ovum) _+>]
1526 ++ wish |= txt=@ta :: 20
1530 ++ card ,[p=@tas q=*] :: typeless card
1531 ++ ovum ,[p=wire q=card] :: Arvo event
1532 ++ wire path :: event cause
1534This is the Arvo ABI in a very real sense. Arvo is a core with
1535these six arms. To use these arms, we hardcode the axis of the
1536formula (`11`, `4`, `86`, etc) into the C code that calls Arvo,
1537because otherwise we'd need type metadata - which we can get, by
1540It's important to understand the Arvo event/action structure, or
1541`++ovum`. An `ovum` is a `card`, which is any `[term noun]`
1542cell, and a `++wire`, a `path` which indicates the location of
1543the event. At the Unix level, the `wire` corresponds to a system
1544module or context. For input events, this is the module that
1545caused the event; for output actions, it's the module that
1548`++poke` sends Arvo an event `ovum`, producing a cell of action
1549ova and a new Arvo core.
1551`++peek` dereferences the Arvo namespace. It takes a date and a
1552key, and produces `~` (`0`) or `[~ value]`.
1554`++keep` asks Arvo the next time it wants to be woken up, for the
1555given `wire`. (This input will probably be eliminated in favor
1556of a single global timer.)
1558`++wish` compiles a string of Hoon source. While just a
1559convenience, it's a very convenient convenience.
1561`++come` and `++load` are used by Arvo to reset itself (more
1562precisely, to shift the Arvo state from an old kernel to a new
1563one); there is no need to call them from C.
1565Now that we understand the Arvo kernel interface, let's look at
1566the `u3v` API. As usual, all the functions in `u3v` are
1567commented, but unfortunately it's hard to describe this API as
1568clean at present. The problem is that `u3v` remains design
1569coupled to the old `vere` event handling code written for `u2`.
1570But let's describe the functions you should be calling, assuming
1571you're not writing the next event system. There are only two.
1573`u3v_wish(str_c)` wraps the `++wish` functionality in a cache
1574(which is read-only unless you're on the surface road).
1576`u3v_do()` uses `wish` to provide a convenient interface for
1577calling Hoon kernel functions by name. Even more conveniently,
1578we tend to call `u3v_do()` with these convenient aliases:
1580 #define u3do(txt_c, arg) u3v_do(txt_c, arg)
1581 #define u3dc(txt_c, a, b) u3v_do(txt_c, u3nc(a, b))
1582 #define u3dt(txt_c, a, b, c) u3v_do(txt_c, u3nt(a, b, c))
1583 #define u3dq(txt_c, a, b, c, d) u3v_do(txt_c, u3nt(a, b, c, d))
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list