Skip to main content

fic/rast/
program.rs

1//! Resolving one `.fi` program: its imports (each alias to the file the
2//! store read, in scope while its bodies are resolved), mappings (into
3//! [`Env::mappings`](super::Env::mappings)), locals, events, processes and
4//! entry points, each in its own arena. A called foreign function joins
5//! [`Env::ffis`](super::Env::ffis) at its first call, its signature
6//! lowered to fic's types, and the store records where it is.
7//!
8//! A program's items are reachable only from that program, so their ids
9//! index the program's arenas and need no PD beside them; a mapping, which
10//! a channel's buffer has too, is the environment's and names its PD. Events and
11//! processes each own the table of their body's variables (`body.rs`).
12
13use std::cell::RefCell;
14use std::collections::{BTreeSet, HashMap};
15use std::mem::take;
16
17use std::ops::Range;
18
19use crate::ast::{self, Type};
20use crate::base::{Entry, IdVec, Idx, Mapping, MappingId, ModuleId, PdId, ProcId, TypeRef};
21use crate::error::Diagnostic;
22use crate::foreign::pnk::{ENTRY_POINTS, MAX_EXPORT_ARGS};
23use crate::foreign::{ForeignKind, ForeignLang, ForeignModule, ForeignModules};
24
25use super::body;
26use super::env::{index, reject_duplicates, type_ref, Names};
27use super::scope::{Called, Outer};
28use super::{Body, Env, LocalVar, ProcBody};
29
30/// Build `pd`'s body from its `.fi`, pushing its locals into `env.locals`,
31/// its mappings into `env.mappings` and each foreign function it is the
32/// first to call into `env.ffis` (where it is, into `foreign.ffis`): the
33/// declarations, then the bodies
34/// (`body.rs`), processes before events so an event naming a process
35/// variable gets a hint.
36pub(super) fn resolve_program<'s>(
37    pd: PdId,
38    p: &'s ast::Program,
39    env: &mut Env,
40    names: &Names<'s>,
41    foreign: &mut ForeignModules,
42    errors: &mut Vec<Diagnostic>,
43) -> Body {
44    let file = env.pds[pd].fi.display().to_string();
45    let mut cx = Cx {
46        names,
47        file: &file,
48        errors,
49    };
50    declarations(p, &mut cx);
51    let mut locals = IdVec::new();
52    let aliases = imports(pd, p, foreign, &mut cx);
53    // The program's mappings take the next ids of `env.mappings`, in
54    // source order.
55    let base = env.mappings.len();
56    for m in &p.mappings {
57        if let Some(m) = mapping(m, pd, &mut cx) {
58            env.mappings.push(m);
59        }
60    }
61    for v in &p.vars {
62        match cx.ty(&v.type_name) {
63            Ok(ty) => {
64                locals.push(LocalVar {
65                    name: v.var_name.clone(),
66                    ty,
67                    span: v.span.clone(),
68                });
69            }
70            Err(message) => cx.error(message, &v.span),
71        }
72    }
73    let entries = p
74        .entry_bindings
75        .iter()
76        .map(|b| Entry {
77            platform: b.platform.clone(),
78            entry: b.entry.clone(),
79            process: ProcId::new(b.process),
80        })
81        .collect();
82    let called = RefCell::new(Called {
83        sigs: take(&mut env.ffis),
84        at: take(&mut foreign.ffis),
85    });
86    let resolved = Resolved {
87        aliases,
88        entries,
89        mappings: base,
90        foreign,
91        called: &called,
92    };
93    let (body, paddr_reads) = rast(p, resolved, &mut cx);
94    let Called { sigs, at } = called.into_inner();
95    env.ffis = sigs;
96    foreign.ffis = at;
97    for m in paddr_reads {
98        env.mappings[m].paddr_read = true;
99    }
100    env.locals.push(locals);
101    body
102}
103
104/// What a program's bodies are resolved against beyond its declarations:
105/// its import aliases, its entries, where its mappings start in
106/// `env.mappings`, the loaded files, and the foreign functions called so
107/// far.
108struct Resolved<'s, 'a> {
109    aliases: HashMap<&'s str, ModuleId>,
110    entries: Vec<Entry>,
111    mappings: usize,
112    foreign: &'a ForeignModules,
113    called: &'a RefCell<Called>,
114}
115
116/// Lower every process and event of `p`, each its signature beside its
117/// body, into the program's [`Body`] with its entries.
118fn rast<'s>(
119    p: &'s ast::Program,
120    resolved: Resolved<'s, '_>,
121    cx: &mut Cx<'_, 's>,
122) -> (Body, BTreeSet<MappingId>) {
123    let Resolved {
124        aliases,
125        entries,
126        mappings,
127        foreign,
128        called,
129    } = resolved;
130    let mut outer = Outer {
131        names: cx.names,
132        file: cx.file,
133        locals: index(p.vars.iter().map(|v| v.var_name.as_str())),
134        mappings: index::<MappingId>(p.mappings.iter().map(|m| m.name.as_str()))
135            .into_iter()
136            .map(|(name, m)| (name, MappingId::new(mappings + m.index())))
137            .collect(),
138        events: index(p.events.iter().map(|e| e.name.as_str())),
139        processes: index(p.processes.iter().map(|q| q.name.as_str())),
140        arity: (
141            p.processes.iter().map(|q| q.params.len()).collect(),
142            p.events.iter().map(|e| e.carriers.len()).collect(),
143        ),
144        aliases,
145        foreign,
146        called,
147        process_vars: HashMap::new(),
148        paddr_reads: RefCell::new(BTreeSet::new()),
149    };
150    let processes: IdVec<ProcId, ProcBody> = p
151        .processes
152        .iter()
153        .enumerate()
154        .map(|(i, ast)| {
155            let entry = entries.iter().any(|e| e.process.index() == i);
156            body::process(ast, entry, &outer, cx.errors)
157        })
158        .collect();
159    for (body, ast) in processes.iter().zip(&p.processes) {
160        for local in body.body_vars.iter() {
161            outer
162                .process_vars
163                .entry(local.name.clone())
164                .or_insert_with(|| ast.name.clone());
165        }
166    }
167    let events = p
168        .events
169        .iter()
170        .map(|ast| body::event(ast, &outer, cx.errors))
171        .collect();
172    let paddr_reads = outer.paddr_reads.into_inner();
173    let body = Body {
174        events,
175        processes,
176        entries,
177    };
178    (body, paddr_reads)
179}
180
181/// What building one program reads and reports to.
182struct Cx<'a, 's> {
183    names: &'a Names<'s>,
184    file: &'a str,
185    errors: &'a mut Vec<Diagnostic>,
186}
187
188impl Cx<'_, '_> {
189    fn error(&mut self, message: String, span: &Range<usize>) {
190        self.errors
191            .push(Diagnostic::at(message, span.clone(), self.file));
192    }
193
194    fn ty(&self, ty: &Type) -> Result<TypeRef, String> {
195        type_ref(ty, self.names)
196    }
197}
198
199/// Each import's alias, to the file the store read for it, the first
200/// import of an alias winning; each Pancake file's exports checked at the
201/// project's first import of it.
202fn imports<'s>(
203    pd: PdId,
204    p: &'s ast::Program,
205    foreign: &ForeignModules,
206    cx: &mut Cx<'_, '_>,
207) -> HashMap<&'s str, ModuleId> {
208    let mut out = HashMap::new();
209    for import in &p.imports {
210        if ForeignKind::of(&import.path).is_none() {
211            cx.error(
212                format!(
213                    "import \"{}\": not a C or Pancake file",
214                    import.path.display()
215                ),
216                &import.span,
217            );
218            continue;
219        }
220        let Some(module) = foreign.module(&import.path) else {
221            cx.error(
222                format!(
223                    "import '{}': \"{}\" was not read",
224                    import.alias,
225                    import.path.display()
226                ),
227                &import.span,
228            );
229            continue;
230        };
231        let in_earlier_pd = foreign
232            .links
233            .iter()
234            .take(pd.index())
235            .flatten()
236            .any(|l| l.module == module);
237        let in_this_one = out.values().any(|&m| m == module);
238        if !in_earlier_pd && !in_this_one {
239            exports(&import.alias, &foreign.modules[module], cx);
240        }
241        out.entry(import.alias.as_str()).or_insert(module);
242    }
243    out
244}
245
246/// Every export of a Pancake file, called or not (cake compiles the whole
247/// file): within the arguments C can pass one, and not named like a
248/// Microkit entry point the generated C defines. Each is reported at the
249/// export, in its file.
250fn exports(alias: &str, module: &ForeignModule, cx: &mut Cx<'_, '_>) {
251    if module.lang() != ForeignLang::Pancake {
252        return;
253    }
254    let file = module.file.display().to_string();
255    for f in &module.exports {
256        let arity = f.params.len();
257        if arity > MAX_EXPORT_ARGS {
258            cx.errors.push(Diagnostic::at(
259                format!(
260                    "Pancake export `{}` (imported as `{alias}`) takes {arity} arguments; \
261                     C can call an exported Pancake function with at most \
262                     {MAX_EXPORT_ARGS} (a CakeML limit)",
263                    f.name
264                ),
265                f.span.clone(),
266                file.clone(),
267            ));
268        }
269        if ENTRY_POINTS.contains(&f.name.as_str()) {
270            cx.errors.push(Diagnostic::at(
271                format!(
272                    "Pancake export `{}` (imported as `{alias}`) clashes with the \
273                     Microkit entry point the generated C defines under that name — \
274                     rename the export",
275                    f.name
276                ),
277                f.span.clone(),
278                file.clone(),
279            ));
280        }
281    }
282}
283
284/// Reject a program's duplicate declarations, each kind its own namespace.
285fn declarations(p: &ast::Program, cx: &mut Cx<'_, '_>) {
286    let file = cx.file;
287    let errors = &mut *cx.errors;
288    let imports = p.imports.iter().map(|i| (i.alias.as_str(), &i.span));
289    reject_duplicates("import alias", imports, file, errors);
290    let mappings = p.mappings.iter().map(|m| (m.name.as_str(), &m.span));
291    reject_duplicates("mapping", mappings, file, errors);
292    let locals = p.vars.iter().map(|v| (v.var_name.as_str(), &v.span));
293    reject_duplicates("variable", locals, file, errors);
294    let events = p.events.iter().map(|e| (e.name.as_str(), &e.span));
295    reject_duplicates("event", events, file, errors);
296    let processes = p.processes.iter().map(|q| (q.name.as_str(), &q.span));
297    reject_duplicates("process", processes, file, errors);
298}
299
300/// A mapping, its region resolved and its vaddr read from the layout.
301fn mapping(m: &ast::MappingDecl, pd: PdId, cx: &mut Cx<'_, '_>) -> Option<Mapping> {
302    let Some(&region) = cx.names.mrs.get(m.mem_region.as_str()) else {
303        let at = m.mem_region_offset..m.mem_region_offset + m.mem_region.len();
304        cx.error(
305            format!("memory region '{}' is not declared", m.mem_region),
306            &at,
307        );
308        return None;
309    };
310    Some(Mapping {
311        pd,
312        name: m.name.clone(),
313        region,
314        // A written vaddr; the rest are allocated once every program is
315        // resolved (`vaddr.rs`).
316        vaddr: m.vaddr.map_or(0, |a| a.value()),
317        pinned: m.vaddr.is_some(),
318        perms: m.perms,
319        cached: m.cached,
320        label: m.security_label,
321        paddr_read: false,
322        span: m.span.clone(),
323    })
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329    use crate::base::{
330        BodyVarId, BodyVarKind, EventId, FfnId, LocalVarId, ModuleId, MrId, PdId, StructId,
331    };
332    use crate::error::Diagnostics;
333    use crate::rast::env::{ast_of, build, build_data, built, built_with, store};
334    use crate::rast::{ExprKind, Rast, Stmt};
335
336    const FIS: &str = "struct Slot { seq: uint16; }
337        MemoryRegion mr(0x1000);
338        ProtectionDomain a(1);
339        ProtectionDomain b(2);";
340
341    /// The one import, `x.pnk`, exporting `f` and `h`.
342    const X_PNK: &str = "export fun 1 f(1 x) { return x; }\nexport fun 1 h(1 x) { return x; }";
343
344    /// The programs resolved against `x.pnk`.
345    fn resolved(programs: &[(&str, &str)]) -> Result<(Rast, Diagnostics), Diagnostics> {
346        built_with(FIS, programs, &[("x.pnk", X_PNK)])
347    }
348
349    const A: &str = r#"import "x.pnk" as x;
350        Mapping m(mr, "rw");
351        d: uint8;
352        s: Slot;
353        @bind(microkit.init)
354        proc Init() { Skip; }
355        @bind(microkit.notified)
356        proc Notified() { Skip; }
357        proc Helper(k: int) { Skip; }
358        evt e.|p: Slot|: x.f(p);"#;
359
360    #[test]
361    fn declarations_are_built_in_source_order() {
362        let (Rast { env, bodies }, _) = resolved(&[("a", A)]).expect("builds");
363        let p = &bodies[PdId::new(0)];
364        assert_eq!(env.pds[PdId::new(0)].name, "a");
365        assert_eq!(env.locals.len(), 2, "one per PD, b's empty");
366        let names: Vec<_> = p.processes.iter().map(|q| q.sig.name.as_str()).collect();
367        assert_eq!(names, ["Init", "Notified", "Helper"]);
368        let entries: Vec<_> = p
369            .entries
370            .iter()
371            .map(|e| (e.entry.as_str(), e.process))
372            .collect();
373        assert_eq!(
374            entries,
375            [("init", ProcId::new(0)), ("notified", ProcId::new(1))]
376        );
377    }
378
379    #[test]
380    fn a_struct_type_names_the_system_struct() {
381        let env = resolved(&[("a", A)]).expect("builds").0.env;
382        assert_eq!(
383            env.locals[PdId::new(0)][LocalVarId::new(1)].ty,
384            TypeRef::Struct(StructId::new(0))
385        );
386    }
387
388    #[test]
389    fn an_unknown_region_or_alias_is_reported_where_it_is_written() {
390        let fi = r#"Mapping m(nowhere, "rw");
391            @bind(microkit.init)
392            proc Init() { Skip; }
393            @bind(microkit.notified)
394            proc Notified() { Skip; }
395            evt e: y.f();"#;
396        let err = built(FIS, &[("a", fi)]).expect_err("rejected");
397        let at: Vec<(&str, &str)> = err
398            .0
399            .iter()
400            .map(|d| (d.message(), fi[d.span().start..].trim_start()))
401            .collect();
402        for (message, written) in [
403            ("memory region 'nowhere' is not declared", "nowhere"),
404            ("event 'e': import alias 'y' is not declared", "y.f"),
405        ] {
406            assert!(
407                at.iter()
408                    .any(|(m, s)| m.contains(message) && s.starts_with(written)),
409                "`{message}` not at `{written}` in {at:#?}"
410            );
411        }
412    }
413
414    #[test]
415    fn mapping_has_its_region_and_allocated_vaddr() {
416        let env = resolved(&[("a", A)]).expect("builds").0.env;
417        let m = &env.mappings[MappingId::new(0)];
418        assert_eq!((m.pd, m.region), (PdId::new(0), MrId::new(0)));
419        assert!(m.vaddr > 0);
420    }
421
422    #[test]
423    fn parameters_and_carriers_open_their_bodys_locals() {
424        let (Rast { bodies, .. }, _) = resolved(&[("a", A)]).expect("builds");
425        let b = &bodies[PdId::new(0)];
426        // The signature has the types; the body's first vars the names.
427        assert_eq!(b.processes[ProcId::new(2)].sig.params.len(), 1);
428        let helper = &b.processes[ProcId::new(2)];
429        assert_eq!(helper.body_vars[BodyVarId::new(0)].kind, BodyVarKind::Param);
430        assert!(helper.body_vars[BodyVarId::new(0)].ty.is_none());
431        assert_eq!(b.events[EventId::new(0)].sig.carriers.len(), 1);
432        let e = &b.events[EventId::new(0)];
433        assert_eq!(e.body_vars[BodyVarId::new(0)].name, "p");
434        assert_eq!(e.body_vars[BodyVarId::new(0)].kind, BodyVarKind::Carrier);
435    }
436
437    #[test]
438    fn every_pancake_export_is_checked_at_its_declaration() {
439        // Neither is called: cake compiles the whole file.
440        let pnk = "export fun 1 five(1 a, 1 b, 1 c, 1 d, 1 e) { return a; }\n\
441                   export fun 1 notified(1 ch) { return ch; }\n";
442        let fi = r#"import "x.pnk" as x;
443            import "x.pnk" as y;
444            @bind(microkit.init)
445            proc Init() { Skip; }
446            @bind(microkit.notified)
447            proc Notified() { Skip; }"#;
448        // Imported three times, reported once.
449        let b = fi.replace("import \"x.pnk\" as y;", "");
450        let err =
451            built_with(FIS, &[("a", fi), ("b", &b)], &[("x.pnk", pnk)]).expect_err("rejected");
452        assert_eq!(err.0.len(), 2, "{err}");
453        let at = |needle: &str| {
454            let d = err
455                .0
456                .iter()
457                .find(|d| d.message().contains(needle))
458                .unwrap_or_else(|| panic!("`{needle}` not in {err}"));
459            assert_eq!(d.filename(), Some("x.pnk"));
460            &pnk[d.span().start..]
461        };
462        assert!(at("`five` (imported as `x`) takes 5 arguments").starts_with("export fun 1 five"));
463        assert!(at("at most 4").starts_with("export fun 1 five"));
464        assert!(
465            at("`notified` (imported as `x`) clashes with the Microkit entry point")
466                .starts_with("export fun 1 notified")
467        );
468    }
469
470    #[test]
471    fn a_function_called_under_two_aliases_is_one_ffi() {
472        let b = r#"import "x.pnk" as y;
473            @bind(microkit.init)
474            proc Init() { Skip; }
475            @bind(microkit.notified)
476            proc Notified() { Skip; }
477            evt g: y.f(1);"#;
478        let (Rast { env, bodies }, _) = resolved(&[("a", A), ("b", b)]).expect("builds");
479        // `h` is never called.
480        assert_eq!(env.ffis.len(), 1);
481        let callee = |p: usize| {
482            let Stmt::Call(call) = &bodies[PdId::new(p)].events[EventId::new(0)].body[0] else {
483                panic!("a call");
484            };
485            let ExprKind::Call { callee, .. } = call.kind else {
486                panic!("a call");
487            };
488            callee
489        };
490        assert_eq!(callee(0), callee(1));
491    }
492
493    #[test]
494    fn a_call_resolves_to_the_read_function_or_is_reported() {
495        let rawast = ast_of(FIS, &[("a", A)]);
496        let mut foreign = store(&rawast, &[("x.pnk", X_PNK)]);
497        let (env, _) = build_data(&rawast).expect("builds the data layer");
498        let (Rast { env, bodies }, _) = build(&rawast, env, &mut foreign).expect("builds");
499        let b = &bodies[PdId::new(0)];
500        let Stmt::Call(call) = &b.events[EventId::new(0)].body[0] else {
501            panic!("x.f(p)");
502        };
503        let ExprKind::Call { callee, .. } = &call.kind else {
504            panic!("a call");
505        };
506        assert_eq!(*callee, FfnId::new(0));
507        assert_eq!(env.ffis[*callee].name, "f");
508        // The store says where it is.
509        assert_eq!(foreign.ffis[*callee].module, ModuleId::new(0));
510        assert_eq!(foreign.function(*callee).1.name, "f");
511        // The module is loaded but declares no `g`.
512        let e = resolved(&[("a", &A.replace("x.f(p)", "x.g(p)"))])
513            .expect_err("rejected")
514            .to_string();
515        assert!(
516            e.contains("event 'e': foreign function 'x.g' is not declared"),
517            "{e}"
518        );
519        // The module was never read: only a test reaches this, the driver
520        // fails in `load` first.
521        let e = built(FIS, &[("a", A)]).expect_err("rejected").to_string();
522        assert!(e.contains("import 'x': \"x.pnk\" was not read"), "{e}");
523    }
524}