Skip to main content

fic/c_backend/
unit.rs

1//! The interim C backend: each protection domain's `ccfg::Orchestration`
2//! printed as one freestanding C translation unit driving Microkit's event
3//! loop — a threaded state machine over the Ccfg's locations. Never trusted:
4//! the mainline target is the LLVM backend, and this one is the readable
5//! reference and the differential-testing oracle. This file is the unit
6//! around the machine (headers, state, runtime, event functions, the Pancake
7//! section); the machine itself is `machine.rs`.
8//!
9//! ## Design restrictions (interim)
10//!
11//! - The `init` graph must not receive (Lean's `initRecvFree`). The
12//!   `notified` graph is receive-headed (`wfcheck::check_recv_headed`),
13//!   which keeps `fic_run` from spinning at the head.
14//! - An unbuffered `Chan` carries no value (Microkit notify is a bare
15//!   signal): its events are `c!` and `c?`. A buffered channel runs on
16//!   filib's ring (`ring.rs`): a send copies its value in, a receive copies
17//!   the head into its binder.
18//! - Imported C files are textually `#include`d into the generated unit, so
19//!   driver signatures are checked against the real definitions. A fic
20//!   name C or the unit already has is renamed (`names.rs`).
21//! - Emitted C stays in the `CompCert` subset (assignments, `switch`, loops,
22//!   calls, fixed-size types) to keep the verified-backend door open.
23//!
24//! ## Trace hook
25//!
26//! `-DFIC_TRACE` enables a ring log of `(kind, channel, value)` events — the
27//! shared alphabet for execution-vs-UPPAAL differential testing.
28//!
29//! ## Debug builds
30//!
31//! `-DFIC_DEBUG`, which the image build passes for the `debug` profile,
32//! reports a notification no arm took: `fic_drop` counts it (`fic_dropped`)
33//! and prints a line. A release image has neither.
34
35use std::collections::HashSet;
36use std::fmt::Write as _;
37use std::fs;
38use std::path::Path;
39
40use anyhow::{bail, Context, Result};
41
42use crate::base::{BodyVarKind, DbgArg, EventId, MappingId};
43use crate::ccfg::graph::Edge;
44use crate::ccfg::system::{Orchestration, System};
45use crate::foreign::c::header::{c_decl, c_ty};
46use crate::foreign::calls::call_sites;
47use crate::foreign::{ForeignKind, ForeignLang, ForeignModules};
48use crate::tast::{ProgramView, Stmt, Tast, Ty};
49
50use super::dbg::{line, message, Print, DECLS};
51use super::machine::{
52    binders, c_call, c_expr, graphs, indent, init_entry, member, notified_entry, protected_entry,
53    run_fn,
54};
55use super::names::{CView, Spelling};
56use super::ring;
57
58/// One generated output file.
59#[derive(Debug)]
60pub struct CFile {
61    /// File name relative to the generated-sources directory
62    /// (e.g. `eth_outer.c`).
63    pub name: String,
64    /// Full file content.
65    pub content: String,
66}
67
68impl CFile {
69    /// Write the file into `dir`.
70    pub fn write(&self, dir: &Path) -> Result<()> {
71        let path = dir.join(&self.name);
72        fs::write(&path, &self.content)
73            .with_context(|| format!("failed to write {}", path.display()))
74    }
75}
76
77/// Generate the C sources for a validated Fiducia project: one `.c`
78/// translation unit per protection domain. The units include
79/// [`DATA_HEADER`].
80///
81/// Kernel entry points are selected by `@bind` (see
82/// [`crate::microkit`]): the process bound to `microkit.init`
83/// becomes `init()`, and the one bound to `microkit.notified` becomes the
84/// `notified()` event loop. The process *name* is not special.
85///
86/// The declarations, types and bodies are `tast`'s and the graphs the
87/// Ccfg's.
88///
89/// # Errors
90///
91/// A PD that does not bind both entry points, or an `init` process that
92/// receives.
93pub fn generate(tast: &Tast, ccfg: &System, foreign: &ForeignModules) -> Result<Vec<CFile>> {
94    let tenv = &tast.tenv;
95    let mut files = Vec::new();
96    let has_data = !tenv.structs.is_empty() || !tenv.consts.is_empty();
97    let data_header = has_data.then(|| DATA_HEADER.to_string());
98
99    for (id, pd) in tenv.pds.iter_enumerated() {
100        let names = ProgramView::new(tast, id);
101        let content = pd_unit(
102            names,
103            foreign,
104            &ccfg.programs[id],
105            ccfg,
106            data_header.as_deref(),
107        )?;
108        files.push(CFile {
109            name: format!("{}.c", pd.name),
110            content,
111        });
112    }
113
114    Ok(files)
115}
116
117/// How C includes the data layer ([`crate::foreign::export`] writes it).
118pub const DATA_HEADER: &str = "gen/types.h";
119
120/// One program's unit, over its graphs.
121fn pd_unit(
122    view: ProgramView<'_>,
123    foreign: &ForeignModules,
124    orchestration: &Orchestration,
125    system: &System,
126    data_header: Option<&str>,
127) -> Result<String> {
128    let spelling = Spelling::new(view, foreign);
129    let names = CView {
130        view,
131        spelling: &spelling,
132        rings: &system.rings,
133        messages: &system.messages,
134    };
135    let body = view.body();
136    let pd = &view.tenv.pds[view.pd];
137    let files = foreign.linked(view.pd);
138    if orchestration.init.edges.iter().any(Edge::blocks) {
139        bail!(
140            "{}: the `microkit.init` process must not contain channel receives \
141             or IRQ awaits (Microkit init runs before any event delivery)",
142            pd.name
143        );
144    }
145
146    let mut out = String::new();
147    let _ = writeln!(
148        out,
149        "/* Generated by fic from {}.fi — do not edit. */",
150        pd.name
151    );
152    out.push_str(
153        "#include <microkit.h>\n#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n",
154    );
155    if let Some(h) = data_header {
156        let _ = writeln!(out, "#include \"{h}\"");
157    }
158    out.push('\n');
159    out.push_str(DECLS);
160    out.push('\n');
161    out.push_str(&loader_symbols(names));
162    out.push_str(&machine_state(names, orchestration));
163    out.push_str(&runtime());
164    out.push_str(&prototypes(names));
165
166    let mut includes = String::new();
167    for file in files {
168        let path = file.path.display();
169        let _ = match file.kind {
170            // Separate driver: its `.c` is compiled and linked alongside.
171            ForeignKind::CHeader => writeln!(includes, "#include \"{path}\""),
172            // Inlined driver. Angle form, so an import named like the PD
173            // resolves to the project directory, not `build/gen/`.
174            ForeignKind::CSource => writeln!(includes, "#include <{path}>"),
175            // No `#include`: CakeML compiles it to its own object, declared
176            // in `pancake_section`.
177            ForeignKind::Pancake => continue,
178        };
179    }
180    if !includes.is_empty() {
181        let _ = write!(out, "/* ── Imported driver ── */\n{includes}\n");
182    }
183    // After the imports: a driver reaches a channel only through `!`/`?`.
184    out.push_str(&ring::decls(names));
185
186    let pancake = files.iter().any(|f| f.kind == ForeignKind::Pancake);
187    if pancake {
188        out.push_str(&pancake_section(names.view, foreign));
189    }
190
191    if !body.events.is_empty() {
192        out.push_str("/* ── Computation events ── */\n");
193        for (id, _) in body.events.iter_enumerated() {
194            out.push_str(&evt_fn(names, id));
195            out.push('\n');
196        }
197    }
198
199    out.push_str(&run_fn(names, orchestration));
200
201    out.push_str("/* ── Microkit entry points ── */\n");
202    out.push_str(&init_entry(orchestration, pancake));
203    out.push('\n');
204    out.push_str(&notified_entry(names, &orchestration.notified));
205    if let Some(protected) = &orchestration.protected {
206        out.push('\n');
207        out.push_str(&protected_entry(names, protected));
208    }
209
210    Ok(out)
211}
212
213/// The platform's symbols, non-`static` and non-`const` so drivers can
214/// `extern` them: each channel's id in this PD (the channel's name), the
215/// IRQ's (`irq`), each mapping's `_vaddr`/`_size`, all defined with the
216/// values fic allocated; and the one only the loader knows, patched in:
217/// `m_paddr` for each mapping the program reads `m.paddr` of. A channel's
218/// buffer is not exported: only filib reaches it, through `fic_rings`. A
219/// symbol whose name C or the unit already has is `var_<name>`.
220fn loader_symbols(names: CView<'_>) -> String {
221    let mut out = String::from("/* ── Platform symbols ── */\n");
222    for (chan, _, end) in names.ends() {
223        let _ = writeln!(
224            out,
225            "uint64_t {} = {}; /* channel id */",
226            names.c_chan(chan),
227            end.id
228        );
229    }
230    if let Some(irq) = names.irq_id() {
231        let _ = writeln!(out, "uint64_t irq = {irq}; /* IRQ channel id */");
232    }
233    let buffers: HashSet<MappingId> = names
234        .view
235        .tenv
236        .chans
237        .iter()
238        .filter_map(|c| c.buffer.as_ref())
239        .flat_map(|b| [b.sender, b.receiver])
240        .collect();
241    for (_, m) in names.mappings().filter(|(id, _)| !buffers.contains(id)) {
242        let _ = writeln!(
243            out,
244            "uintptr_t {} = {:#x}; /* mapping `{}` */\nuint64_t {} = {:#x};",
245            names.c_mapping(m, "vaddr"),
246            m.vaddr,
247            m.name,
248            names.c_mapping(m, "size"),
249            names.tenv.mrs[m.region].size.value()
250        );
251        if m.paddr_read {
252            let _ = writeln!(
253                out,
254                "uintptr_t {}; /* its region's physical address */",
255                names.c_mapping(m, "paddr")
256            );
257        }
258    }
259    out.push('\n');
260    out
261}
262
263/// The location enum, the resume point, and all static state: locals (Γ),
264/// hoisted process-body declarations, and receive binders (Σ(c)).
265fn machine_state(names: CView<'_>, orchestration: &Orchestration) -> String {
266    let mut out = String::from("/* ── Machine state ── */\nenum fic_loc_t {\n");
267    for (graph, ccfg) in graphs(orchestration) {
268        for (l, name) in &ccfg.names {
269            let _ = writeln!(out, "    {}, /* {name} */", member(graph, *l));
270        }
271    }
272    out.push_str("};\nstatic enum fic_loc_t fic_loc; /* the resume point */\n");
273
274    // Variables: locals in declaration order, then process-body
275    // declarations (hoisted — they survive across activations), then
276    // receive binders, each typed as its channel's payload.
277    let mut seen: HashSet<String> = HashSet::new();
278    for v in names.view.locals().iter() {
279        let c = names.spelling.var(&v.name);
280        if seen.insert(c.to_string()) {
281            let _ = writeln!(out, "static {};", c_decl(names.view.tenv, &v.ty, &c));
282        }
283    }
284    for decl in names.body().processes.iter() {
285        for v in decl
286            .body_vars
287            .iter()
288            .filter(|v| v.kind == BodyVarKind::Decl)
289        {
290            let c = names.c_body_var(v);
291            if seen.insert(c.to_string()) {
292                let _ = writeln!(out, "static {};", c_decl(names.view.tenv, &v.ty, &c));
293            }
294        }
295    }
296    let protected = orchestration.protected.iter();
297    for (chan, binder) in std::iter::once(&orchestration.notified)
298        .chain(protected)
299        .flat_map(|g| binders(names, g))
300    {
301        let c = names.c_body_var(binder);
302        if seen.insert(c.to_string()) {
303            let _ = writeln!(
304                out,
305                "static {}; /* receive binder on {chan} */",
306                c_decl(names.view.tenv, &binder.ty, &c)
307            );
308        }
309    }
310    out.push('\n');
311    out
312}
313
314/// The tiny generated runtime: trace ring, unexpected-event drop counter,
315/// and the divergence sink.
316fn runtime() -> String {
317    let dropped = message("dropped unexpected event");
318    let hang = message("divergence (hang)");
319    format!(
320        r"/* ── fic runtime ── */
321#define FIC_EV_RECV 0
322#define FIC_EV_SEND 1
323#define FIC_EV_IRQ_AWAIT 2
324#define FIC_EV_IRQ_ACK 3
325#ifdef FIC_TRACE
326#ifndef FIC_TRACE_CAP
327#define FIC_TRACE_CAP 256
328#endif
329struct fic_trace_entry {{ uint8_t kind; uint8_t chan; uint64_t val; }};
330struct fic_trace_entry fic_trace_buf[FIC_TRACE_CAP];
331unsigned fic_trace_len;
332static void fic_trace(uint8_t kind, uint64_t chan, uint64_t val) {{
333    struct fic_trace_entry *e = &fic_trace_buf[fic_trace_len % FIC_TRACE_CAP];
334    e->kind = kind;
335    e->chan = (uint8_t)chan;
336    e->val = val;
337    fic_trace_len++;
338}}
339#else
340static void fic_trace(uint8_t kind, uint64_t chan, uint64_t val) {{
341    (void)kind;
342    (void)chan;
343    (void)val;
344}}
345#endif
346
347#ifdef FIC_DEBUG
348static unsigned fic_dropped;
349static void fic_drop(microkit_channel ch) {{
350    (void)ch;
351    fic_dropped++;
352    {dropped}
353}}
354#else
355#define fic_drop(ch) ((void)(ch))
356#endif
357
358/* Divergence (Omega): report once, then make no further progress. */
359static void fic_hang(void) {{
360    {hang}
361    for (;;) {{}}
362}}
363
364"
365    )
366}
367
368/// Forward declarations for the generated functions, so definition order
369/// never matters.
370fn prototypes(names: CView<'_>) -> String {
371    let mut out = String::from("/* ── Forward declarations ── */\n");
372    for (id, evt) in names.body().events.iter_enumerated() {
373        let _ = writeln!(
374            out,
375            "static void {}({});",
376            names.spelling.event(&evt.sig.name),
377            params(names, id)
378        );
379    }
380    out.push_str("static void fic_run(enum fic_loc_t at);\n\n");
381    out
382}
383
384/// Render a computation event as a C function. Carriers become
385/// parameters; the body's assignments and calls translate directly, a
386/// `dbg` through the platform's debug calls.
387fn evt_fn(names: CView<'_>, id: EventId) -> String {
388    let evt = &names.body().events[id];
389    let mut body = String::new();
390    for stmt in &evt.body {
391        let line = match stmt {
392            Stmt::Decl(id) => {
393                let local = &evt.body_vars[*id];
394                // Aggregates (structs, arrays) zero-init with `{0}`; scalars `0`.
395                let init = if matches!(local.ty, Ty::Prim(_) | Ty::Addr(_)) {
396                    "0"
397                } else {
398                    "{0}"
399                };
400                let decl = c_decl(names.view.tenv, &local.ty, &names.c_body_var(local));
401                format!("{decl} = {init};")
402            }
403            Stmt::Assign { target, rhs, .. } => format!(
404                "{} = {};",
405                names.c_var(&evt.body_vars, *target),
406                c_expr(names, &evt.body_vars, rhs)
407            ),
408            Stmt::Call(call) => format!("{};", c_call(names, &evt.body_vars, call)),
409            Stmt::Dbg { args, .. } => {
410                let args: Vec<Print> = args
411                    .iter()
412                    .map(|arg| match arg {
413                        DbgArg::Text(t) => Print::Text(t.clone()),
414                        DbgArg::Expr(e) => {
415                            let c = c_expr(names, &evt.body_vars, e);
416                            match e.ty.integer() {
417                                None => Print::Bool(c),
418                                Some(p) if p.is_signed() => Print::Int(c),
419                                Some(_) => Print::Uint(c),
420                            }
421                        }
422                    })
423                    .collect();
424                line(&args).join("\n")
425            }
426        };
427        body.push_str(&line);
428        body.push('\n');
429    }
430    if body.is_empty() {
431        body.push_str("/* no statements */\n");
432    }
433    format!(
434        "static void {}({}) {{\n{}}}\n",
435        names.spelling.event(&names.body().events[id].sig.name),
436        params(names, id),
437        indent(&body, 1)
438    )
439}
440
441/// Render an event's carrier list as a C parameter list.
442fn params(names: CView<'_>, id: EventId) -> String {
443    let carriers = names.body().events[id].sig.carriers.len();
444    if carriers == 0 {
445        return "void".to_string();
446    }
447    names.body().events[id]
448        .body_vars
449        .iter()
450        .take(carriers)
451        .map(|carrier| c_decl(names.view.tenv, &carrier.ty, &names.c_body_var(carrier)))
452        .collect::<Vec<_>>()
453        .join(", ")
454}
455
456/// Pancake memory per PD, in bytes: the `@base` heap, then the Pancake stack
457/// (au-ts/sddf's sizes).
458const PANCAKE_HEAP_BYTES: usize = 10 * 1024;
459const PANCAKE_STACK_BYTES: usize = 10 * 1024;
460
461/// The C side of a PD's Pancake imports: prototypes for the exports the
462/// program calls (a `.pnk` has no header to include), and the runtime
463/// contract `cml_main` expects — its memory, and `cml_exit`/`cml_err`.
464fn pancake_section(names: ProgramView<'_>, foreign: &ForeignModules) -> String {
465    let body = names.body();
466    let mut out =
467        String::from("/* ── Pancake imports: compiled by CakeML, linked alongside ── */\n");
468    let mut declared = HashSet::new();
469    for site in call_sites(body) {
470        let f = &names.tenv.ffis[site.callee];
471        if foreign.function(site.callee).0.lang() != ForeignLang::Pancake {
472            continue;
473        }
474        let name = f.name.as_str();
475        if !declared.insert(name) {
476            continue;
477        }
478        let sig = &f.sig;
479        let ret = sig
480            .ret
481            .as_ref()
482            .map_or_else(|| "void".to_string(), |t| c_ty(names.tenv, t));
483        let params = if sig.params.is_empty() {
484            "void".to_string()
485        } else {
486            sig.params
487                .iter()
488                .map(|t| c_ty(names.tenv, t))
489                .collect::<Vec<_>>()
490                .join(", ")
491        };
492        let _ = writeln!(out, "{ret} {name}({params});");
493    }
494
495    let exited = message("Pancake exited");
496    let error = message("Pancake runtime error");
497    let heap_words = PANCAKE_HEAP_BYTES / 8;
498    let stack_words = PANCAKE_STACK_BYTES / 8;
499    let _ = write!(
500        out,
501        "\n\
502         /* CakeML runtime: init() hands cml_main() its heap (@base) and\n \
503         * stack, and no export may be called before that. */\n\
504         extern void *cml_heap;\n\
505         extern void *cml_stack;\n\
506         extern void *cml_stackend;\n\
507         extern void cml_main(void);\n\
508         #define FIC_PNK_HEAP_WORDS {heap_words}\n\
509         #define FIC_PNK_STACK_WORDS {stack_words}\n\
510         static uint64_t fic_pnk_mem[FIC_PNK_HEAP_WORDS + FIC_PNK_STACK_WORDS]\n    \
511         __attribute__((aligned(16)));\n\
512         \n\
513         /* Called by CakeML-compiled code on exit or on a runtime error.\n \
514         * Must not return: report, then fault. */\n\
515         __attribute__((noreturn)) void cml_exit(int code) {{\n    \
516         (void)code;\n    \
517         {exited}\n    \
518         __builtin_trap();\n\
519         }}\n\
520         __attribute__((noreturn)) void cml_err(int code) {{\n    \
521         (void)code;\n    \
522         {error}\n    \
523         __builtin_trap();\n\
524         }}\n\n"
525    );
526    out
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532    use std::path::PathBuf;
533
534    use anyhow::anyhow;
535
536    use crate::ast::RawAst;
537    use crate::ccfg::build as build_ccfg;
538    use crate::foreign::{ForeignLang, ForeignModules};
539    use crate::frontend::data_layer;
540    use crate::parser::parse_foreign;
541    use crate::rast::build as build_rast;
542    use crate::rast::env::ast_of;
543    use crate::tast::build as build_tast;
544
545    /// A Fiducia project from inline sources, every protection domain
546    /// given no program implemented by an empty one.
547    fn project(fis: &str, programs: &[(&str, &str)]) -> RawAst {
548        ast_of(fis, programs)
549    }
550
551    /// The front end over `foreign`, then the C files.
552    fn generated(rawast: &RawAst, mut foreign: ForeignModules) -> Result<Vec<CFile>> {
553        foreign.bind(rawast);
554        let (env, tenv) = data_layer(rawast).expect("data layer");
555        let (rast, _) = build_rast(rawast, env, &mut foreign).expect("resolved AST");
556        let (tast, _) = build_tast(rast, tenv).map_err(|e| anyhow!("{e}"))?;
557        let ccfg = build_ccfg(&tast)?;
558        generate(&tast, &ccfg, &foreign)
559    }
560
561    /// The C files of a project that imports nothing.
562    fn emit(rawast: &RawAst) -> Result<Vec<CFile>> {
563        generated(rawast, ForeignModules::new())
564    }
565
566    /// As [`emit`], with `io.pnk` read as a Pancake module, as the driver
567    /// would.
568    fn emit_with_pancake(rawast: &mut RawAst, pnk: &str) -> Result<Vec<CFile>> {
569        emit_with(rawast, "io.pnk", pnk)
570    }
571
572    /// As [`emit`], with `source` read as the imported file `path` (a
573    /// `.pnk` by the Pancake reader, a `.c` or `.h` through libclang), as
574    /// the driver would.
575    fn emit_with(rawast: &mut RawAst, path: &str, source: &str) -> Result<Vec<CFile>> {
576        let written = PathBuf::from(path);
577        let lang = if written.extension().is_some_and(|x| x == "pnk") {
578            ForeignLang::Pancake
579        } else {
580            ForeignLang::C
581        };
582        let mut store = ForeignModules::new();
583        store.insert(
584            parse_foreign(source, &written, written.clone(), lang, &[])
585                .unwrap_or_else(|e| panic!("failed to read {path} (a .c needs libclang): {e}")),
586        );
587        generated(rawast, store)
588    }
589
590    /// A PD calling a Pancake module in all three positions: a statement, an
591    /// assigned value, and a guard.
592    const PANCAKE_PD: &str = "x: uint;\n\
593         evt hello: io.say();\n\
594         evt bump: x = io.inc(x);\n\
595         import \"io.pnk\" as io;\n\
596         @bind(microkit.init)\n\
597         proc Init() { Skip; }\n\
598         @bind(microkit.notified)\n\
599         proc Notified() {\n\
600             o2d? -> Handle();\n\
601             Notified();\n\
602         }\n\
603         proc Handle() {\n\
604             hello -> bump -> Skip;\n\
605             [io.more(x) != 0] d2i! -> Skip\n\
606          default Skip;\n\
607         }";
608
609    #[test]
610    fn a_name_c_already_has_is_renamed() {
611        let mut rawast = project(
612            "ProtectionDomain a(10);\nProtectionDomain b(20);\nChan c = a <-> b;",
613            &[(
614                "a",
615                "import \"io.pnk\" as io;\n\
616                 inc: uint;\n\
617                 n: uint;\n\
618                 evt bump.|return: uint|: inc = io.inc(return);\n\
619                 @bind(microkit.init)\n\
620                 proc Init() { Skip; }\n\
621                 @bind(microkit.notified)\n\
622                 proc Notified() { c? -> bump.n -> Notified(); }",
623            )],
624        );
625        let files = emit_with_pancake(
626            &mut rawast,
627            "export fun 1 inc(1 r) { return r + 1; }\nexport fun 1 evt_bump() { return 0; }\n",
628        )
629        .unwrap();
630        let c = unit(&files, "a.c");
631        // A global named like an imported function.
632        assert!(c.contains("static uint64_t var_inc;"), "{c}");
633        // A carrier named like a C keyword.
634        assert!(
635            c.contains("static void var_evt_bump(uint64_t var_return)"),
636            "{c}"
637        );
638        assert!(c.contains("var_inc = inc(var_return);"), "{c}");
639        // An event whose function name an import already has.
640        assert!(c.contains("var_evt_bump(n);"), "{c}");
641    }
642
643    /// Each value prints through filib by its type, an integer at full
644    /// width, signed or unsigned, then the line ends; the text escaped for C.
645    #[test]
646    fn dbg_prints_through_filib_by_type() {
647        let rawast = project(
648            "ProtectionDomain a(10);",
649            &[(
650                "a",
651                "n: int;\n\
652                 b: byte;\n\
653                 u: uint64;\n\
654                 evt tick: { dbg(\"n=\\\"\", n, b, u, n > 0); n = n + 1; }\n\
655                 @bind(microkit.init)\n\
656                 proc Init() { tick -> Skip; }\n\
657                 @bind(microkit.notified)\n\
658                 proc Notified() { Skip; }",
659            )],
660        );
661        let files = emit(&rawast).unwrap();
662        let c = unit(&files, "a.c");
663        // Signed and unsigned at full width, a bool by value, then the end.
664        assert!(
665            c.contains(
666                "fi_dbg_str(\"n=\\\"\", 3);\n    \
667                 fi_dbg_int((int64_t)(n));\n    \
668                 fi_dbg_uint((uint64_t)(b));\n    \
669                 fi_dbg_uint((uint64_t)(u));\n    \
670                 if ((n) > (0)) fi_dbg_str(\"true\", 4); else fi_dbg_str(\"false\", 5);\n    \
671                 fi_dbg_end();\n    \
672                 n = (n) + (1);"
673            ),
674            "{c}"
675        );
676        // The unit declares filib's calls, and prints its own lines with them.
677        assert!(c.contains("void fi_dbg_int(int64_t v);"), "{c}");
678        assert!(c.contains("fi_dbg_str(\"init\", 4); fi_dbg_end();"), "{c}");
679        assert!(!c.contains("microkit_dbg"), "{c}");
680    }
681
682    fn unit<'a>(files: &'a [CFile], name: &str) -> &'a str {
683        &files
684            .iter()
685            .find(|f| f.name == name)
686            .unwrap_or_else(|| panic!("missing generated file {name}"))
687            .content
688    }
689
690    /// The text of one `case` in `fic_run`.
691    fn run_case_of<'a>(c: &'a str, member: &str) -> &'a str {
692        let run = c
693            .split("static void fic_run(enum fic_loc_t at) {")
694            .nth(1)
695            .unwrap();
696        let start = run
697            .find(&format!("case {member}:"))
698            .unwrap_or_else(|| panic!("no case for {member}"));
699        let rest = &run[start..];
700        let end = rest[5..].find("case ").map_or(rest.len(), |i| i + 5);
701        &rest[..end]
702    }
703
704    /// The text of `notified()`.
705    fn notified_of(c: &str) -> &str {
706        c.split("void notified(microkit_channel ch) {")
707            .nth(1)
708            .unwrap()
709    }
710
711    const FORWARDER_FIS: &str = "ProtectionDomain a(10);\n\
712                                 ProtectionDomain b(20);\n\
713                                 ProtectionDomain dd(30);\n\
714                                 Chan o2d = a <-> dd;\n\
715                                 Chan d2i = dd <-> b;";
716
717    /// [`FORWARDER_FIS`] with both channels buffered, each carrying a
718    /// `uint8`.
719    const BUFFERED_FORWARDER_FIS: &str = "MemoryRegion ring_a(0x1000);\n\
720                                          MemoryRegion ring_b(0x1000);\n\
721                                          ProtectionDomain a(10);\n\
722                                          ProtectionDomain b(20);\n\
723                                          ProtectionDomain dd(30);\n\
724                                          Chan o2d = a --> dd via ring_a<uint8>;\n\
725                                          Chan d2i = dd --> b via ring_b<uint8>;";
726
727    /// Two buffered channels into `dd`, each carrying a `uint8`.
728    const BUFFERED_JOIN_FIS: &str = "MemoryRegion ring_a(0x1000);\n\
729                                     MemoryRegion ring_b(0x1000);\n\
730                                     ProtectionDomain a(10);\n\
731                                     ProtectionDomain b(20);\n\
732                                     ProtectionDomain dd(30);\n\
733                                     Chan left = a --> dd via ring_a<uint8>;\n\
734                                     Chan right = b --> dd via ring_b<uint8>;";
735
736    #[test]
737    fn forwarder_machine() {
738        let files = emit(&project(
739            BUFFERED_FORWARDER_FIS,
740            &[(
741                "dd",
742                "@bind(microkit.init)\n\
743                 proc Init() { Skip; }\n\
744                 @bind(microkit.notified)\n\
745                 proc Notified() { o2d?pkt -> d2i!pkt -> Notified(); }",
746            )],
747        ))
748        .unwrap();
749        let c = unit(&files, "dd.c");
750
751        // Every location of both graphs is an enum member, named.
752        assert!(c.contains("FIC_LOC_INIT_0, /* Init */"));
753        assert!(c.contains("FIC_LOC_0, /* Notified */"));
754        assert!(c.contains("FIC_LOC_2, /* L2 */"));
755        assert!(!c.contains("FIC_LOC_DONE"));
756        // The head parks; the receive is dispatched and resumes after it.
757        assert!(run_case_of(c, "FIC_LOC_0").contains("fic_loc = FIC_LOC_0; return;"));
758        let dispatch = notified_of(c);
759        // A buffered receive tests the ring, not the notification.
760        assert!(dispatch.contains("if (fi_recv(o2d, &pkt, sizeof pkt)) {"));
761        assert!(dispatch.contains("fic_run(FIC_LOC_2);"));
762        // The send runs inline, then back to the head.
763        let l2 = run_case_of(c, "FIC_LOC_2");
764        assert!(l2.contains("(void)fi_send(d2i, &fic_v, sizeof fic_v);"));
765        assert!(l2.contains("at = FIC_LOC_0; continue;"));
766        // Σ(o2d) is its buffer's type.
767        assert!(c.contains("static uint8_t pkt; /* receive binder on o2d */"));
768        // init runs its graph.
769        assert!(c.contains("void init(void)"));
770        assert!(c.contains("fic_run(FIC_LOC_INIT_0);"));
771        // Channel ids are globals defined with this PD's ids.
772        assert!(c.contains("uint64_t o2d = 0; /* channel id */"));
773        assert!(c.contains("uint64_t d2i = 1; /* channel id */"));
774    }
775
776    /// `client` calls `server` on the `Sync` channel `req`.
777    #[test]
778    fn a_sync_send_is_a_ppcall_and_protected_answers_it() {
779        let files = emit(&project(
780            "ProtectionDomain client(10);\n\
781             ProtectionDomain server(20);\n\
782             Sync Chan req = client --> server;",
783            &[
784                (
785                    "client",
786                    "@bind(microkit.init) proc Init() { Skip; }\n\
787                     @bind(microkit.notified) proc Notified() { req! -> Skip; }",
788                ),
789                (
790                    "server",
791                    "evt served: dbg(\"served\");\n\
792                     @bind(microkit.init) proc Init() { Skip; }\n\
793                     @bind(microkit.notified) proc Notified() { Skip; }\n\
794                     @bind(microkit.protected) proc Serve() { req? -> served -> Serve(); }",
795                ),
796            ],
797        ))
798        .unwrap();
799        let client = unit(&files, "client.c");
800        assert!(
801            client.contains("microkit_ppcall((microkit_channel)req, microkit_msginfo_new(0, 0));"),
802            "{client}"
803        );
804        assert!(!client.contains("fic_notify(req)"), "{client}");
805        assert!(!client.contains("protected("), "{client}");
806
807        let server = unit(&files, "server.c");
808        let entry = server
809            .split("microkit_msginfo protected(microkit_channel ch, microkit_msginfo msginfo) {")
810            .nth(1)
811            .unwrap_or_else(|| panic!("no protected entry:\n{server}"));
812        assert!(
813            entry.contains("if (ch == (microkit_channel)req) {"),
814            "{entry}"
815        );
816        assert!(entry.contains("fic_run(FIC_LOC_PROT_2);"), "{entry}");
817        assert!(
818            entry.contains("return microkit_msginfo_new(0, 0);"),
819            "{entry}"
820        );
821        // `serve` loops back to the head, which returns: notified's resume
822        // point stays where it was.
823        assert!(run_case_of(server, "FIC_LOC_PROT_2").contains("at = FIC_LOC_PROT_0; continue;"));
824        let head = run_case_of(server, "FIC_LOC_PROT_0");
825        assert!(head.contains("return;"), "{head}");
826        assert!(!head.contains("fic_loc"), "{head}");
827        let exit = run_case_of(server, "FIC_LOC_PROT_1");
828        assert!(!exit.contains("fic_loc"), "{exit}");
829    }
830
831    /// `client` sends a `Pair` on the `Sync Chan<Pair>` `ask`: two message
832    /// registers out, and back into the binder in `protected()`.
833    #[test]
834    fn a_sync_value_goes_in_the_message_registers() {
835        let files = emit(&project(
836            "struct Pair { a: int32; b: int64; }\n\
837             ProtectionDomain client(10);\n\
838             ProtectionDomain server(20);\n\
839             Sync Chan<Pair> ask = client --> server;",
840            &[
841                (
842                    "client",
843                    "p: Pair;\n\
844                     @bind(microkit.init) proc Init() { Skip; }\n\
845                     @bind(microkit.notified) proc Notified() { ask!p -> Skip; }",
846                ),
847                (
848                    "server",
849                    "@bind(microkit.init) proc Init() { Skip; }\n\
850                     @bind(microkit.notified) proc Notified() { Skip; }\n\
851                     @bind(microkit.protected) proc Serve() { ask?q -> Serve(); }",
852                ),
853            ],
854        ))
855        .unwrap();
856        let client = unit(&files, "client.c");
857        for line in [
858            "struct Pair fic_v = p;",
859            "uint64_t fic_mr[2] = {0};",
860            "char *fic_p = (char *)fic_mr;",
861            // `a`, then `b` past `a`'s 4 bytes of padding, which stay zero.
862            "__builtin_memcpy(fic_p + 0, &(fic_v.a), 4);",
863            "__builtin_memcpy(fic_p + 8, &(fic_v.b), 8);",
864            "microkit_mr_set(0, fic_mr[0]);",
865            "microkit_mr_set(1, fic_mr[1]);",
866            "(void)microkit_ppcall((microkit_channel)ask, microkit_msginfo_new(0, 2));",
867        ] {
868            assert!(client.contains(line), "missing {line:?} in\n{client}");
869        }
870        let server = unit(&files, "server.c");
871        // The binder is a static, and protected() fills it before running.
872        assert!(
873            server.contains("static struct Pair q; /* receive binder on ask */"),
874            "{server}"
875        );
876        let entry = server.split("microkit_msginfo protected(").nth(1).unwrap();
877        for line in [
878            "fic_mr[0] = microkit_mr_get(0);",
879            "fic_mr[1] = microkit_mr_get(1);",
880            "__builtin_memcpy(&q, fic_mr, 16);",
881        ] {
882            assert!(entry.contains(line), "missing {line:?} in\n{entry}");
883        }
884    }
885
886    /// An array of padded structs is copied in a loop, field by field; a
887    /// value with no padding is one copy.
888    #[test]
889    fn a_sync_value_skips_its_padding() {
890        let send = |payload: &str, decl: &str| {
891            let files = emit(&project(
892                &format!(
893                    "struct Pair {{ a: int32; b: int64; }}\n\
894                     ProtectionDomain client(10);\n\
895                     ProtectionDomain server(20);\n\
896                     Sync Chan<{payload}> ask = client --> server;"
897                ),
898                &[
899                    (
900                        "client",
901                        &format!(
902                            "{decl}\n\
903                             @bind(microkit.init) proc Init() {{ Skip; }}\n\
904                             @bind(microkit.notified) proc Notified() {{ ask!p -> Skip; }}"
905                        ),
906                    ),
907                    (
908                        "server",
909                        "@bind(microkit.init) proc Init() { Skip; }\n\
910                         @bind(microkit.notified) proc Notified() { Skip; }\n\
911                         @bind(microkit.protected) proc Serve() { ask?q -> Serve(); }",
912                    ),
913                ],
914            ))
915            .unwrap();
916            unit(&files, "client.c").to_string()
917        };
918        let pairs = send("Pair[2]", "p: Pair[2];");
919        for line in [
920            "for (size_t fic_i0 = 0; fic_i0 < 2; fic_i0++) {",
921            "__builtin_memcpy(fic_p + fic_i0 * 16 + 0, &((p)[fic_i0].a), 4);",
922            "__builtin_memcpy(fic_p + fic_i0 * 16 + 8, &((p)[fic_i0].b), 8);",
923        ] {
924            assert!(pairs.contains(line), "missing {line:?} in\n{pairs}");
925        }
926        let word = send("int64", "p: int64;");
927        assert!(
928            word.contains("__builtin_memcpy(fic_p + 0, &(fic_v), 8);"),
929            "{word}"
930        );
931    }
932
933    #[test]
934    fn an_exit_returns_at_the_notified_head() {
935        let files = emit(&project(
936            FORWARDER_FIS,
937            &[(
938                "dd",
939                "@bind(microkit.init)\n\
940                 proc Init() { Skip; }\n\
941                 @bind(microkit.notified)\n\
942                 proc Notified() { o2d? -> d2i! -> Skip; }",
943            )],
944        ))
945        .unwrap();
946        let c = unit(&files, "dd.c");
947        assert!(run_case_of(c, "FIC_LOC_INIT_1").contains("fic_loc = FIC_LOC_0; return;"));
948        assert!(run_case_of(c, "FIC_LOC_1").contains("fic_loc = FIC_LOC_0; return;"));
949        // A receive-headed notified dispatches straight away.
950        assert!(!notified_of(c).contains("fic_run(FIC_LOC_0)"), "{c}");
951    }
952
953    /// A notified with no receive runs once per notification, and returns.
954    #[test]
955    fn a_notified_without_a_receive_runs_once_and_returns() {
956        let files = emit(&project(
957            FORWARDER_FIS,
958            &[(
959                "dd",
960                "evt tick: {}\n\
961                 @bind(microkit.init)\n\
962                 proc Init() { Skip; }\n\
963                 @bind(microkit.notified)\n\
964                 proc Notified() { tick -> Skip; }",
965            )],
966        ))
967        .unwrap();
968        let c = unit(&files, "dd.c");
969        assert!(
970            run_case_of(c, "FIC_LOC_INIT_1").contains("fic_loc = FIC_LOC_0; return;"),
971            "{c}"
972        );
973        assert!(
974            run_case_of(c, "FIC_LOC_1").contains("fic_loc = FIC_LOC_0; return;"),
975            "{c}"
976        );
977        let entry = notified_of(c);
978        assert!(
979            entry.contains(
980                "if (fic_loc == FIC_LOC_0) {\n        fic_run(FIC_LOC_0);\n        return;\n    }"
981            ),
982            "{entry}"
983        );
984    }
985
986    #[test]
987    fn typed_channel_payload_types_binder() {
988        // A channel declaring `via buf<Slot>` types the receive binder as
989        // `struct Slot` — a nested communication type, the datadiode's
990        // message/slot pair. The payload is not transported, so the binder is
991        // neither zero-assigned (a struct can't take `= 0`) nor traced/cast
992        // as a scalar — both fall back to a 0 trace.
993        let fis = "struct Message { length: uint16; offset: uint32; }\n\
994                   struct Slot { flags: uint16; msg: Message; }\n\
995                   ProtectionDomain a(10);\n\
996                   ProtectionDomain b(20);\n\
997                   ProtectionDomain dd(30);\n\
998                   MemoryRegion ring_a(0x1000);\n\
999                   MemoryRegion ring_b(0x1000);\n\
1000                   Chan o2d = a --> dd via ring_a<Slot>;\n\
1001                   Chan d2i = dd --> b via ring_b<Slot>;";
1002        let files = emit(&project(
1003            fis,
1004            &[(
1005                "dd",
1006                "@bind(microkit.init)\n\
1007                 proc Init() { Skip; }\n\
1008                 @bind(microkit.notified)\n\
1009                 proc Notified() { o2d?pkt -> d2i!pkt -> Notified(); }",
1010            )],
1011        ))
1012        .unwrap();
1013        let c = unit(&files, "dd.c");
1014
1015        assert!(c.contains("static struct Slot pkt; /* receive binder on o2d */"));
1016        assert!(!c.contains("static uint8_t pkt"));
1017        assert!(!c.contains("pkt = 0;"));
1018        assert!(c.contains("if (fi_recv(o2d, &pkt, sizeof pkt)) {"));
1019        assert!(c.contains("struct Slot fic_v = pkt;"));
1020        // Slot has padding (after `flags`, and after `msg.length`), so it
1021        // goes field by field into a zeroed buffer: none of dd's stack
1022        // reaches the ring.
1023        for line in [
1024            "static char fic_b[12];",
1025            "__builtin_memset(fic_b, 0, sizeof fic_b);",
1026            "__builtin_memcpy(fic_b + 0, &(fic_v.flags), 2);",
1027            "__builtin_memcpy(fic_b + 4, &(fic_v.msg.length), 2);",
1028            "__builtin_memcpy(fic_b + 8, &(fic_v.msg.offset), 4);",
1029            "(void)fi_send(d2i, fic_b, sizeof fic_b);",
1030        ] {
1031            assert!(c.contains(line), "missing {line:?} in\n{c}");
1032        }
1033        // 0x1000 bytes: the 16-byte header, then 340 slots of the 12-byte
1034        // Slot (msg at 4), in the rings table at o2d's id (0).
1035        assert!(c.contains("const struct fi_ring fic_rings[64] = {\n    [0] = { (void *)0x"));
1036        assert!(c.contains(", 340u, 12u }, /* o2d in `ring_a` */"));
1037        assert!(c.contains("fic_trace(FIC_EV_SEND, d2i, 0);"));
1038        assert!(!c.contains("(uint64_t)(pkt)"));
1039    }
1040
1041    #[test]
1042    fn binder_reused_at_another_type_is_rejected() {
1043        let fis = "struct Slot { flags: uint16; }\n\
1044                   ProtectionDomain a(10);\n\
1045                   ProtectionDomain b(20);\n\
1046                   ProtectionDomain dd(30);\n\
1047                   MemoryRegion ring_a(0x1000);\n\
1048                   MemoryRegion ring_b(0x1000);\n\
1049                   Chan o2d = a --> dd via ring_a<Slot>;\n\
1050                   Chan d2i = dd --> b via ring_b<uint8>;";
1051        let err = emit(&project(
1052            fis,
1053            &[(
1054                "dd",
1055                "@bind(microkit.init)\n\
1056                 proc Init() { Skip; }\n\
1057                 @bind(microkit.notified)\n\
1058                 proc Notified() { o2d?m -> Skip [] d2i?m -> Skip; Notified(); }",
1059            )],
1060        ))
1061        .unwrap_err()
1062        .to_string();
1063        // The typed AST rejects it before the C backend's own check.
1064        assert!(
1065            err.contains("receive binder 'm' is bound on 'o2d' as 'Slot' but on 'd2i' as 'uint8'"),
1066            "got: {err}"
1067        );
1068    }
1069
1070    #[test]
1071    fn a_buffer_region_has_no_loader_symbols() {
1072        let fis = "struct Slot { flags: uint16; }\n\
1073                   ProtectionDomain a(10);\n\
1074                   ProtectionDomain dd(30);\n\
1075                   ProtectionDomain other(40);\n\
1076                   MemoryRegion ring(0x1000);\n\
1077                   Chan o2d = a --> dd via ring<Slot>;\n\
1078                   Chan x = dd <-> other;";
1079        let on_o2d = "@bind(microkit.init)\n\
1080                      proc Init() { Skip; }\n\
1081                      @bind(microkit.notified)\n\
1082                      proc Notified() { o2d?p -> Notified(); }";
1083        let on_x = "@bind(microkit.init)\n\
1084                    proc Init() { Skip; }\n\
1085                    @bind(microkit.notified)\n\
1086                    proc Notified() { x? -> Notified(); }";
1087        // `a` sends on `o2d` but never uses it: the symbols follow the
1088        // declaration.
1089        let on_a = "@bind(microkit.init)\n\
1090                    proc Init() { Skip; }\n\
1091                    @bind(microkit.notified)\n\
1092                    proc Notified() { Skip; }";
1093        let files = emit(&project(
1094            fis,
1095            &[("a", on_a), ("dd", on_o2d), ("other", on_x)],
1096        ))
1097        .unwrap();
1098
1099        // The buffer is filib's alone: its ring is in `fic_rings`, and no
1100        // `_vaddr`/`_size` symbol names it for a driver.
1101        for endpoint in ["a.c", "dd.c", "other.c"] {
1102            let c = unit(&files, endpoint);
1103            assert!(
1104                !c.contains("ring_vaddr") && !c.contains("ring_size"),
1105                "{endpoint}: {c}"
1106            );
1107        }
1108        assert!(unit(&files, "dd.c").contains("/* o2d in `ring` */"));
1109    }
1110
1111    #[test]
1112    fn a_program_without_both_entry_points_has_no_unit() {
1113        // `a` binds nothing: every PD is a Microkit PD and must.
1114        let err = emit(&project(FORWARDER_FIS, &[("a", "")]))
1115            .expect_err("rejected")
1116            .to_string();
1117        assert!(
1118            err.contains("`a` is missing mandatory kernel entry point(s)"),
1119            "{err}"
1120        );
1121    }
1122
1123    #[test]
1124    fn a_mapping_vaddr_is_its_symbol_defined_with_the_laid_out_address() {
1125        let fis = format!("MemoryRegion mr(0x1000);\n{FORWARDER_FIS}");
1126        let files = emit(&project(
1127            &fis,
1128            &[(
1129                "dd",
1130                "Mapping m(mr, \"rw\");\n\
1131                 x: Address;\n\
1132                 evt a: x = m.vaddr;\n\
1133                 @bind(microkit.init)\n\
1134                 proc Init() { Skip; }\n\
1135                 @bind(microkit.notified)\n\
1136                 proc Notified() { o2d? -> a -> Notified(); }",
1137            )],
1138        ))
1139        .unwrap();
1140        let c = unit(&files, "dd.c");
1141        assert!(c.contains("x = m_vaddr;"), "{c}");
1142        assert!(c.contains("uintptr_t m_vaddr = 0x"), "{c}");
1143        assert!(c.contains("uint64_t m_size = 0x1000;"), "{c}");
1144        assert!(!c.contains("(m).vaddr"), "{c}");
1145    }
1146
1147    #[test]
1148    fn a_mapping_paddr_is_the_load_patched_symbol_declared_only_when_read() {
1149        let fis = format!("MemoryRegion mr(0x1000);\n{FORWARDER_FIS}");
1150        let fi = |body: &str| {
1151            format!(
1152                "Mapping m(mr, \"rw\");\n\
1153                 x: Address;\n\
1154                 evt a: {body};\n\
1155                 @bind(microkit.init)\n\
1156                 proc Init() {{ Skip; }}\n\
1157                 @bind(microkit.notified)\n\
1158                 proc Notified() {{ o2d? -> a -> Notified(); }}"
1159            )
1160        };
1161        let files = emit(&project(&fis, &[("dd", &fi("x = m.paddr"))])).unwrap();
1162        let c = unit(&files, "dd.c");
1163        assert!(c.contains("uintptr_t m_paddr;"), "{c}");
1164        assert!(c.contains("x = m_paddr;"), "{c}");
1165
1166        let files = emit(&project(&fis, &[("dd", &fi("x = m.vaddr"))])).unwrap();
1167        assert!(!unit(&files, "dd.c").contains("m_paddr"));
1168    }
1169
1170    #[test]
1171    fn computational_choice_with_default() {
1172        let mut rawast = project(
1173            FORWARDER_FIS,
1174            &[(
1175                "dd",
1176                "rx: bool;\n\
1177                 evt probe: rx = extc.poll();\n\
1178                 import \"ext.c\" as extc;\n\
1179                 @bind(microkit.init)\n\
1180                 proc Init() { Skip; }\n\
1181                 @bind(microkit.notified)\n\
1182                 proc Notified() {\n\
1183                     o2d? -> Handle();\n\
1184                     Notified();\n\
1185                 }\n\
1186                 proc Handle() {\n\
1187                     probe -> Skip;\n\
1188                     [rx] d2i! -> Skip\n\
1189                  [] [!rx] Div\n\
1190                  default Skip;\n\
1191                 }",
1192            )],
1193        );
1194        let files = emit_with(
1195            &mut rawast,
1196            "ext.c",
1197            "#include <stdbool.h>\nbool poll(void);\n",
1198        )
1199        .unwrap();
1200        let c = unit(&files, "dd.c");
1201
1202        // The helper is inlined at the location its reference reaches.
1203        assert!(c.contains("FIC_LOC_2, /* Handle */"));
1204        assert!(run_case_of(c, "FIC_LOC_2").contains("evt_probe();"));
1205        // The choice is a guard chain with Lean's default guard, then hang.
1206        let choice = run_case_of(c, "FIC_LOC_3");
1207        assert!(choice.contains("if (rx) {"), "{choice}");
1208        assert!(choice.contains("fic_notify(d2i);"));
1209        assert!(choice.contains("if (!(rx)) {"));
1210        assert!(choice.contains("if (!(((rx) && (true)) || (((!(rx)) && (true)) || (false)))) {"));
1211        assert!(choice.contains("at = FIC_LOC_0; continue;"));
1212        assert!(choice.contains("fic_hang(); /* no edge enabled */"));
1213        assert!(c.contains("rx = poll();"));
1214        assert!(c.contains("#include <ext.c>"));
1215    }
1216
1217    /// An inlined `.c` import is in the unit's translation unit, so the
1218    /// unit declares filib's ring and its calls only after it: a driver
1219    /// reaches a channel only through `!` and `?`.
1220    #[test]
1221    fn the_ring_calls_are_declared_after_the_imports() {
1222        let mut rawast = project(
1223            BUFFERED_FORWARDER_FIS,
1224            &[(
1225                "dd",
1226                "rx: bool;\n\
1227                 evt probe: rx = extc.poll();\n\
1228                 import \"ext.c\" as extc;\n\
1229                 @bind(microkit.init)\n\
1230                 proc Init() { Skip; }\n\
1231                 @bind(microkit.notified)\n\
1232                 proc Notified() { o2d?pkt -> probe -> d2i!pkt -> Notified(); }",
1233            )],
1234        );
1235        let files = emit_with(
1236            &mut rawast,
1237            "ext.c",
1238            "#include <stdbool.h>\nbool poll(void);\n",
1239        )
1240        .unwrap();
1241        let c = unit(&files, "dd.c");
1242        let import = c.find("#include <ext.c>").expect("imports");
1243        assert!(import < c.find("struct fi_ring {").expect("declares the ring"));
1244        assert!(import < c.find("bool fi_send(").expect("declares fi_send"));
1245    }
1246
1247    #[test]
1248    fn div_hangs() {
1249        let files = emit(&project(
1250            FORWARDER_FIS,
1251            &[(
1252                "dd",
1253                "@bind(microkit.init)\n\
1254                 proc Init() { Skip; }\n\
1255                 @bind(microkit.notified)\n\
1256                 proc Notified() { o2d? -> Div; }",
1257            )],
1258        ))
1259        .unwrap();
1260        let c = unit(&files, "dd.c");
1261        assert!(run_case_of(c, "FIC_LOC_2").contains("fic_hang();\n            return;"));
1262        assert!(c.contains("FIC_LOC_3, /* hang */"));
1263        assert!(run_case_of(c, "FIC_LOC_3").contains("fic_hang();"));
1264    }
1265
1266    #[test]
1267    fn tail_reference_is_a_back_edge() {
1268        let files = emit(&project(
1269            FORWARDER_FIS,
1270            &[(
1271                "dd",
1272                "done: bool;\n\
1273                 @bind(microkit.init)\n\
1274                 proc Init() { Skip; }\n\
1275                 @bind(microkit.notified)\n\
1276                 proc Notified() { o2d? -> Drain(); Notified(); }\n\
1277                 proc Drain() {\n\
1278                     [done] Skip\n\
1279                  default (d2i! -> Drain());\n\
1280                 }",
1281            )],
1282        ))
1283        .unwrap();
1284        let c = unit(&files, "dd.c");
1285        let drain = run_case_of(c, "FIC_LOC_2");
1286        assert!(drain.starts_with("case FIC_LOC_2: /* Drain */"));
1287        assert!(drain.contains("if (done) {"));
1288        assert!(drain.contains("if (!(((done) && (true)) || (false))) {"));
1289        assert!(drain.contains("at = FIC_LOC_2; continue;"), "{drain}");
1290    }
1291
1292    #[test]
1293    fn unguarded_edge_ends_the_chain() {
1294        let files = emit(&project(
1295            FORWARDER_FIS,
1296            &[(
1297                "dd",
1298                "b: bool;\n\
1299                 evt a: b = true;\n\
1300                 @bind(microkit.init)\n\
1301                 proc Init() { Skip; }\n\
1302                 @bind(microkit.notified)\n\
1303                 proc Notified() { o2d? -> Step(); Notified(); }\n\
1304                 proc Step() { a -> Skip [] [b] d2i! -> Skip default Skip; }",
1305            )],
1306        ))
1307        .unwrap();
1308        let c = unit(&files, "dd.c");
1309        let step = run_case_of(c, "FIC_LOC_2");
1310        assert!(
1311            step.contains("evt_a();\n            at = FIC_LOC_0; continue;"),
1312            "{step}"
1313        );
1314        // Nothing after the unguarded edge: no guard test, no park, no hang.
1315        assert!(!step.contains("if ("), "{step}");
1316        assert!(!step.contains("fic_hang"), "{step}");
1317    }
1318
1319    #[test]
1320    fn mixed_location_runs_the_computation_first_then_parks() {
1321        let files = emit(&project(
1322            FORWARDER_FIS,
1323            &[(
1324                "dd",
1325                "g: bool;\n\
1326                 evt a: g = true;\n\
1327                 @bind(microkit.init)\n\
1328                 proc Init() { Skip; }\n\
1329                 @bind(microkit.notified)\n\
1330                 proc Notified() { Loop(); }\n\
1331                 proc Loop() { [g] o2d? -> Loop() [] [!g] a -> Loop(); }",
1332            )],
1333        ))
1334        .unwrap();
1335        let c = unit(&files, "dd.c");
1336        let head = run_case_of(c, "FIC_LOC_0");
1337        assert!(head.contains("if (!(g)) {"));
1338        assert!(
1339            head.contains("evt_a();\n                at = FIC_LOC_0; continue;"),
1340            "{head}"
1341        );
1342        assert!(head.contains("/* mixed location: park after the computation */"));
1343        assert!(head.contains("fic_loc = FIC_LOC_0; return;"));
1344        // The receive's guard is evaluated at dispatch time.
1345        assert!(notified_of(c).contains("if ((g) && ch == (microkit_channel)o2d) {"));
1346    }
1347
1348    /// filib's precondition: every `fi_send`/`fi_recv` names a channel whose
1349    /// `fic_rings` entry the unit fills, and an unbuffered send is
1350    /// `fic_notify`.
1351    #[test]
1352    fn every_channel_call_has_its_ring() {
1353        let files = emit(&project(
1354            BUFFERED_FORWARDER_FIS,
1355            &[(
1356                "dd",
1357                "@bind(microkit.init)\n\
1358                 proc Init() { Skip; }\n\
1359                 @bind(microkit.notified)\n\
1360                 proc Notified() { o2d?pkt -> d2i!pkt -> Notified(); }",
1361            )],
1362        ))
1363        .unwrap();
1364        let c = unit(&files, "dd.c");
1365        let table = c.split("fic_rings[64] = {").nth(1).expect("table");
1366        let table = table.split("};").next().unwrap();
1367        let mut calls = 0;
1368        for call in ["fi_send(", "fi_recv("] {
1369            for rest in c.split(call).skip(1) {
1370                let chan = rest.split(',').next().unwrap();
1371                if chan.contains("microkit_channel") {
1372                    continue; // the prototype
1373                }
1374                calls += 1;
1375                assert!(
1376                    table.contains(&format!("/* {chan} in `")),
1377                    "{chan}: {table}"
1378                );
1379            }
1380        }
1381        assert_eq!(calls, 2, "{c}");
1382    }
1383
1384    /// A buffered receive beside a `default` is a receive as any other: with
1385    /// no guard of its own it closes the `default`, and the PD parks there.
1386    #[test]
1387    fn a_buffered_receive_beside_a_default_parks() {
1388        let files = emit(&project(
1389            BUFFERED_JOIN_FIS,
1390            &[(
1391                "dd",
1392                "evt drop: {}\n\
1393                 @bind(microkit.init)\n\
1394                 proc Init() { Skip; }\n\
1395                 @bind(microkit.notified)\n\
1396                 proc Notified() { left?x -> Pair(); }\n\
1397                 proc Pair() { right?y -> Notified() default drop -> Notified(); }",
1398            )],
1399        ))
1400        .unwrap();
1401        let c = unit(&files, "dd.c");
1402        assert!(!c.contains("fi_ready"), "{c}");
1403        let pair = run_case_of(c, "FIC_LOC_2");
1404        assert!(pair.contains("if (!((true) || (false))) {"), "{pair}");
1405        assert!(pair.contains("fic_loc = FIC_LOC_2; return;"), "{pair}");
1406        assert!(
1407            notified_of(c).contains("if (fi_recv(right, &y, sizeof y)) {"),
1408            "{c}"
1409        );
1410    }
1411
1412    #[test]
1413    fn a_buffered_receiver_drains_its_ring_and_keeps_waiting_values() {
1414        let files = emit(&project(
1415            BUFFERED_FORWARDER_FIS,
1416            &[(
1417                "dd",
1418                "@bind(microkit.init)\n\
1419                 proc Init() { Skip; }\n\
1420                 @bind(microkit.notified)\n\
1421                 proc Notified() { o2d?pkt -> d2i!pkt -> Notified(); }",
1422            )],
1423        ))
1424        .unwrap();
1425        let c = unit(&files, "dd.c");
1426
1427        // Each end is in the rings table, over its own mapping; nothing is
1428        // bound in init().
1429        assert!(c.contains("    [0] = { (void *)0x"));
1430        assert!(c.contains(", 4080u, 1u }, /* d2i in `ring_b` */"));
1431        let init = c.split("void init(void) {").nth(1).expect("init");
1432        assert!(
1433            !c.contains("fi_bind") && !init.split("fic_run(").next().unwrap().contains("fic_rings")
1434        );
1435        // The dispatch repeats until nothing fires. No arm here tests the
1436        // notification, so none takes it.
1437        let notified = notified_of(c);
1438        assert!(notified.contains("microkit_channel fic_ev = ch;"));
1439        assert!(notified.contains("} while (fic_more);"));
1440        assert!(!notified.contains("fic_ev = (microkit_channel)-1;"));
1441        // A value waiting for a receive is not a dropped event.
1442        assert!(notified
1443            .contains("if (fic_ev != (microkit_channel)-1 && !(ch == (microkit_channel)o2d)) {"));
1444        // A send notifies only if it went in; it traces the value it copied.
1445        let l2 = run_case_of(c, "FIC_LOC_2");
1446        assert!(l2.contains("uint8_t fic_v = pkt;"));
1447        assert!(l2.contains("fic_trace(FIC_EV_SEND, d2i, (uint64_t)fic_v);"));
1448        assert!(l2.contains("(void)fi_send(d2i, &fic_v, sizeof fic_v);"));
1449    }
1450
1451    /// #635: a buffered arm listed first, with a value waiting, fires before
1452    /// the notification's arm.
1453    #[test]
1454    fn a_notification_stays_until_its_arm_takes_it() {
1455        let files = emit(&project(
1456            "MemoryRegion ring_a(0x1000);\n\
1457             ProtectionDomain a(10);\n\
1458             ProtectionDomain b(20);\n\
1459             ProtectionDomain dd(30, 42);\n\
1460             Chan data = a --> dd via ring_a<uint8>;\n\
1461             Chan poke = b <-> dd;",
1462            &[(
1463                "dd",
1464                "@bind(microkit.init)\n\
1465                 proc Init() { Skip; }\n\
1466                 @bind(microkit.notified)\n\
1467                 proc Notified() {\n\
1468                     data?x -> Skip [] irq?42 -> irq!42 -> Skip [] poke? -> Skip;\n\
1469                     Notified();\n\
1470                 }",
1471            )],
1472        ))
1473        .unwrap();
1474        let notified: String = notified_of(unit(&files, "dd.c"))
1475            .split_whitespace()
1476            .collect::<Vec<_>>()
1477            .join(" ");
1478        // Source order: the buffered arm is tried first.
1479        let ring = notified
1480            .find("if (fi_recv(data, ")
1481            .expect("the buffered arm");
1482        let irq = "if (fic_ev == (microkit_channel)irq) { fic_ev = (microkit_channel)-1;";
1483        let poke = "if (fic_ev == (microkit_channel)poke) { fic_ev = (microkit_channel)-1;";
1484        assert!(
1485            ring < notified.find(irq).expect("the IRQ arm takes it"),
1486            "{notified}"
1487        );
1488        assert!(notified.contains(poke), "{notified}");
1489        // Nothing else clears it: no pass ends by forgetting it.
1490        assert_eq!(
1491            notified.matches("fic_ev = (microkit_channel)-1;").count(),
1492            2
1493        );
1494        // One that no arm took is dropped; a debug build reports it.
1495        assert!(notified.contains(
1496            "#ifdef FIC_DEBUG /* Not taken: dropped, unless a ring's, whose value waits there. */ \
1497             if (fic_ev != (microkit_channel)-1 && !(ch == (microkit_channel)data)) \
1498             { fic_drop(ch); } #endif"
1499        ));
1500        // A release build has no counter and no call.
1501        let c = unit(&files, "dd.c");
1502        assert!(c.contains("#ifdef FIC_DEBUG\nstatic unsigned fic_dropped;"));
1503        assert!(c.contains("#else\n#define fic_drop(ch) ((void)(ch))\n#endif"));
1504    }
1505
1506    #[test]
1507    fn an_unbuffered_unit_has_no_ring() {
1508        let files = emit(&project(
1509            FORWARDER_FIS,
1510            &[(
1511                "dd",
1512                "@bind(microkit.init)\n\
1513                 proc Init() { Skip; }\n\
1514                 @bind(microkit.notified)\n\
1515                 proc Notified() { o2d? -> d2i! -> Notified(); }",
1516            )],
1517        ))
1518        .unwrap();
1519        let c = unit(&files, "dd.c");
1520        assert!(
1521            !c.contains("fi_send")
1522                && c.contains("void fic_notify(")
1523                && c.contains("fic_rings[64] = {{0}};")
1524        );
1525        assert!(!c.contains("fic_ev") && !c.contains("fic_more"));
1526        assert!(notified_of(c).contains("if (ch == (microkit_channel)o2d)"));
1527        assert!(notified_of(c).contains("fic_run(FIC_LOC_2); return;"));
1528    }
1529
1530    #[test]
1531    fn blocking_choice_dispatches_both_channels() {
1532        let files = emit(&project(
1533            BUFFERED_JOIN_FIS,
1534            &[(
1535                "dd",
1536                "@bind(microkit.init)\n\
1537                 proc Init() { Skip; }\n\
1538                 @bind(microkit.notified)\n\
1539                 proc Notified() {\n\
1540                     left?x -> Skip\n\
1541                  [] right?y -> Skip;\n\
1542                     Notified();\n\
1543                 }",
1544            )],
1545        ))
1546        .unwrap();
1547        let c = unit(&files, "dd.c");
1548        let dispatch = notified_of(c);
1549        assert!(dispatch.contains("if (fi_recv(left, "));
1550        assert!(dispatch.contains("if (fi_recv(right, "));
1551        // Both arms live under the one resume point.
1552        assert_eq!(dispatch.matches("case FIC_LOC_").count(), 1);
1553        assert!(c.contains("static uint8_t x; /* receive binder on left */"));
1554        assert!(c.contains("static uint8_t y; /* receive binder on right */"));
1555    }
1556
1557    #[test]
1558    fn non_tail_blocking_helper_is_inlined() {
1559        // A first reference to a helper flattens it in place: the receive
1560        // resumes at the location that continues the caller's sequence.
1561        let files = emit(&project(
1562            FORWARDER_FIS,
1563            &[(
1564                "dd",
1565                "@bind(microkit.init)\n\
1566                 proc Init() { Skip; }\n\
1567                 @bind(microkit.notified)\n\
1568                 proc Notified() { Wait(); d2i! -> Skip; }\n\
1569                 proc Wait() { o2d? -> Skip; }",
1570            )],
1571        ))
1572        .unwrap();
1573        let c = unit(&files, "dd.c");
1574        assert!(notified_of(c).contains("fic_run(FIC_LOC_2); return;"));
1575        let after = run_case_of(c, "FIC_LOC_2");
1576        assert!(after.contains("fic_notify(d2i);"));
1577        assert!(after.contains("at = FIC_LOC_1; continue;"));
1578    }
1579
1580    #[test]
1581    fn receive_in_init_is_rejected() {
1582        let err = emit(&project(
1583            FORWARDER_FIS,
1584            &[(
1585                "dd",
1586                "@bind(microkit.init)\n\
1587                 proc Init() { o2d? -> Skip; }\n\
1588                 @bind(microkit.notified)\n\
1589                 proc Notified() { o2d? -> Notified(); }",
1590            )],
1591        ))
1592        .unwrap_err()
1593        .to_string();
1594        assert!(
1595            err.contains("must not contain channel receives"),
1596            "got: {err}"
1597        );
1598    }
1599
1600    #[test]
1601    fn event_params_come_from_the_signature() {
1602        let files = emit(&project(
1603            FORWARDER_FIS,
1604            &[(
1605                "dd",
1606                "total: uint16;\n\
1607                 evt bump.|n: uint16|: total = total + n;\n\
1608                 @bind(microkit.init)\n\
1609                 proc Init() { Skip; }\n\
1610                 @bind(microkit.notified)\n\
1611                 proc Notified() { o2d? -> bump.total -> Notified(); }",
1612            )],
1613        ))
1614        .unwrap();
1615        let c = unit(&files, "dd.c");
1616        assert!(c.contains("static uint16_t total;"));
1617        assert!(c.contains("static void evt_bump(uint16_t n);"));
1618        assert!(c.contains("static void evt_bump(uint16_t n) {"));
1619        assert!(run_case_of(c, "FIC_LOC_2").contains("evt_bump(total);"));
1620    }
1621
1622    #[test]
1623    fn units_include_the_data_layer() {
1624        let rawast = project(
1625            "struct Rbd { flags: uint16; length: uint16; addr: uint32; }\n\
1626             const RBD_COUNT: uint = 64;\n\
1627             ProtectionDomain a(10);",
1628            &[(
1629                "a",
1630                "@bind(microkit.init) proc Init() { Skip; }\n\
1631                 @bind(microkit.notified) proc Notified() { Skip; }",
1632            )],
1633        );
1634        let files = emit(&rawast).unwrap();
1635        // Units include the data layer; it is not one of their files.
1636        assert!(unit(&files, "a.c").contains("#include \"gen/types.h\""));
1637        assert!(files
1638            .iter()
1639            .all(|f| Path::new(&f.name).extension().is_some_and(|x| x == "c")));
1640    }
1641
1642    #[test]
1643    fn system_header_is_gen_types_h_whatever_the_fis_is_named() {
1644        let mut rawast = project(
1645            "struct Packet { id: uint32; }\n\
1646             ProtectionDomain a(10);\n\
1647             ProtectionDomain dd(30);\n\
1648             Chan o2d = a <-> dd;",
1649            &[(
1650                "dd",
1651                "@bind(microkit.init)\n\
1652                 proc Init() { Skip; }\n\
1653                 @bind(microkit.notified)\n\
1654                 proc Notified() { o2d? -> Notified(); }",
1655            )],
1656        );
1657        rawast.system.filename = "proj/dd.fis".into();
1658        let files = emit(&rawast).unwrap();
1659        // Stub and program units both pull in the one system header.
1660        assert!(unit(&files, "a.c").contains("#include \"gen/types.h\""));
1661        assert!(unit(&files, "dd.c").contains("#include \"gen/types.h\""));
1662    }
1663
1664    #[test]
1665    fn bind_selects_entry() {
1666        // `@bind(microkit.notified)` — not the process name or declaration
1667        // order — selects the notification handler. Here the bound handler
1668        // is declared second and named `Handler`; `Other` is never
1669        // referenced, so nothing of it is generated.
1670        let files = emit(&project(
1671            BUFFERED_JOIN_FIS,
1672            &[(
1673                "dd",
1674                "@bind(microkit.init)\n\
1675                 proc Init() { Skip; }\n\
1676                 proc Other() { left?x -> Other(); }\n\
1677                 @bind(microkit.notified)\n\
1678                 proc Handler() { right?y -> Handler(); }",
1679            )],
1680        ))
1681        .unwrap();
1682        let c = unit(&files, "dd.c");
1683        assert!(c.contains("FIC_LOC_0, /* Handler */"));
1684        let dispatch = notified_of(c);
1685        assert!(dispatch.contains("if (fi_recv(right, "));
1686        assert!(!dispatch.contains("fi_recv(left, "));
1687        assert!(c.contains("static uint8_t y; /* receive binder on right */"));
1688        assert!(!c.contains("static uint8_t x;"));
1689    }
1690
1691    #[test]
1692    fn irq_await_and_ack() {
1693        let files = emit(&project(
1694            "ProtectionDomain eth(99, 42);\n\
1695             ProtectionDomain dd(30);\n\
1696             Chan o2d = eth <-> dd;",
1697            &[(
1698                "eth",
1699                "@bind(microkit.init)\n\
1700                 proc Init() { Skip; }\n\
1701                 @bind(microkit.notified)\n\
1702                 proc Notified() { irq?42 -> o2d! -> irq!42 -> Notified(); }",
1703            )],
1704        ))
1705        .unwrap();
1706        let c = unit(&files, "eth.c");
1707        // The IRQ takes the PD's first id; the channel the next.
1708        assert!(c.contains("uint64_t irq = 0; /* IRQ channel id */"));
1709        assert!(c.contains("uint64_t o2d = 1; /* channel id */"));
1710        let dispatch = notified_of(c);
1711        assert!(dispatch.contains("if (ch == (microkit_channel)irq)"));
1712        assert!(dispatch.contains("fic_trace(FIC_EV_IRQ_AWAIT, irq, 42);"));
1713        assert!(c.contains("microkit_irq_ack((microkit_channel)irq);"));
1714    }
1715
1716    #[test]
1717    fn init_graph_runs_before_the_handler() {
1718        let files = emit(&project(
1719            FORWARDER_FIS,
1720            &[(
1721                "dd",
1722                "@bind(microkit.init)\n\
1723                 proc Init() { d2i! -> Skip; }\n\
1724                 @bind(microkit.notified)\n\
1725                 proc Notified() { o2d? -> Notified(); }",
1726            )],
1727        ))
1728        .unwrap();
1729        let c = unit(&files, "dd.c");
1730        let boot = run_case_of(c, "FIC_LOC_INIT_0");
1731        assert!(boot.contains("fic_notify(d2i);"));
1732        assert!(boot.contains("at = FIC_LOC_INIT_1; continue;"));
1733    }
1734
1735    #[test]
1736    fn pancake_import_declares_the_called_exports_and_sets_up_cakeml() {
1737        let mut rawast = project(FORWARDER_FIS, &[("dd", PANCAKE_PD)]);
1738        let files = emit_with_pancake(
1739            &mut rawast,
1740            "export fun 1 say() { return 0; }\n\
1741             export fun 1 inc(1 r) { return r + 1; }\n\
1742             export fun 1 more(1 r) { return r < 5; }\n\
1743             export fun 1 unused(1 a, 1 b) { return a; }\n",
1744        )
1745        .expect("a Pancake import is supported");
1746        let c = unit(&files, "dd.c");
1747
1748        // One prototype per called export, in Pancake's word type; an export
1749        // nothing calls gets none.
1750        assert!(c.contains("uint64_t say(void);"), "{c}");
1751        assert!(c.contains("uint64_t inc(uint64_t);"), "{c}");
1752        assert!(c.contains("uint64_t more(uint64_t);"), "{c}");
1753        assert!(!c.contains("unused("), "{c}");
1754
1755        // The CakeML runtime contract.
1756        assert!(c.contains("extern void *cml_heap;"));
1757        assert!(c.contains("extern void cml_main(void);"));
1758        assert!(c.contains("__attribute__((noreturn)) void cml_exit(int code)"));
1759        assert!(c.contains("__attribute__((noreturn)) void cml_err(int code)"));
1760        assert!(c.contains("__builtin_trap();"));
1761
1762        // init() hands CakeML its memory and runs cml_main() before the init
1763        // graph — no export may be entered earlier.
1764        let init = c.split("void init(void) {").nth(1).unwrap();
1765        let main_at = init.find("cml_main();").expect("init runs cml_main");
1766        let run_at = init.find("fic_run(").unwrap();
1767        assert!(main_at < run_at, "{init}");
1768        assert!(init.contains("cml_stack = fic_pnk_mem + FIC_PNK_HEAP_WORDS;"));
1769
1770        // A PD without Pancake imports carries none of it.
1771        let stub = unit(&files, "a.c");
1772        assert!(!stub.contains("cml_"), "{stub}");
1773    }
1774}