Skip to main content

fic/ast/
program.rs

1//! `.fi` program AST nodes: the [`Program`], its imports, memory mappings
2//! and entry-point bindings.
3
4use std::fmt::{self, Display, Formatter};
5use std::ops::Range;
6use std::path::PathBuf;
7
8use serde::Serialize;
9
10use super::event::EvtDecl;
11use super::infoflow::SecurityLabel;
12use super::process::ProcessDecl;
13use super::statement::VarDecl;
14use super::types::{Address, Permission};
15
16/// A parsed `.fi` program — a protection domain implementation.
17///
18/// Contains imports (external C/Pancake files), memory mappings, and variable declarations.
19///
20/// ```
21/// let prog = fic::parser::parse_program(r#"import "eth.c" as eth;"#).unwrap();
22/// assert_eq!(prog.imports.len(), 1);
23/// ```
24#[derive(Debug, Clone, Serialize)]
25pub struct Program {
26    /// External file imports.
27    pub imports: Vec<Import>,
28    /// Memory mapping declarations.
29    pub mappings: Vec<MappingDecl>,
30    /// Local variable declarations: the program's, its PD's state.
31    pub vars: Vec<VarDecl>,
32    /// Computation event declarations from one or more `Events:` sections.
33    pub events: Vec<EvtDecl>,
34    /// Sub-process declarations from one or more `Process:` sections.
35    pub processes: Vec<ProcessDecl>,
36    /// Platform entry-point bindings, resolved to the owning process as each
37    /// `@bind`-annotated process is parsed; a `(platform, entry)` is bound by
38    /// at most one process, the parser rejecting the second.
39    pub entry_bindings: Vec<EntryBinding>,
40}
41
42/// One resolved platform entry-point binding: `@bind(<platform>.<entry>)` on
43/// the process at [`Self::process`] (an index into [`Program::processes`]).
44#[derive(Debug, Clone, Serialize)]
45pub struct EntryBinding {
46    /// Platform namespace, e.g. `microkit`.
47    pub platform: String,
48    /// Entry point within the platform, e.g. `init` / `notified`.
49    pub entry: String,
50    /// Index into [`Program::processes`] of the bound process.
51    pub process: usize,
52}
53
54/// An import declaration referencing an external implementation file.
55///
56/// ## `import` Declaration (`.fi`)
57///
58/// Imports an external C or Pancake source file and binds it to a local
59/// alias.
60///
61/// ```text
62/// import "path/to/file.c"   as alias;
63/// import "path/to/file.h"   as alias;
64/// import "path/to/file.pnk" as alias;
65/// ```
66///
67/// Only `.c`, `.h`, and `.pnk` extensions are accepted: the languages fic
68/// has a reader for, so every call resolves to a function it has read.
69/// The alias is used to call functions from the imported file at runtime.
70///
71/// A `.h` import is the *separate-driver* form: the generated translation
72/// unit `#include`s the header (declarations only) and the paired sibling
73/// `.c` (e.g. `eth.h` → `eth.c`) is compiled and linked alongside it. A
74/// `.c` import is the legacy *inlined* form: the driver source is textually
75/// `#include`d into the generated unit (single translation unit).
76///
77/// ```text
78/// import "eth.h"     as eth;   // separate driver: include eth.h, link eth.c
79/// import "eth.c"     as eth;   // inlined driver: #include <eth.c>
80/// import "uart.pnk"  as uart;  // Pancake translation unit
81/// ```
82///
83/// The alias is the name a program uses at call sites (`eth.send(..)`):
84/// it names the file only while the program's calls are resolved.
85///
86/// Language reference: [Imports](https://fiducia-lang.github.io/docs/lang-spec/items/imports-and-mappings.html#imports),
87/// [Foreign Functions](https://fiducia-lang.github.io/docs/lang-spec/ffi/foreign-functions.html).
88///
89/// The parser records the path as written and decides nothing about the
90/// file: what it is follows from its extension
91/// ([`ForeignKind::of`](crate::foreign::ForeignKind::of)), which the front
92/// end checks as it binds the program, and the file it names is the
93/// loaded-modules store's to say
94/// ([`ForeignModules::module`](crate::foreign::ForeignModules::module)).
95#[derive(Debug, Clone, Serialize)]
96pub struct Import {
97    /// The imported file, as written (relative to the project directory).
98    pub path: PathBuf,
99    /// The alias call sites use: `alias.fn(..)`.
100    pub alias: String,
101    /// Byte span of the whole `import ... ;` declaration.
102    pub span: Range<usize>,
103}
104
105/// Memory mapping declaration.
106///
107/// ## `Mapping` Declaration (`.fi`)
108///
109/// Maps a declared memory region into this protection domain's virtual address space.
110///
111/// ```text
112/// [High|Low] Mapping name(memRegion [, vaddr], "perms" [, cached]);
113/// ```
114///
115/// | Parameter   | Type    | Required | Default | Description |
116/// |-------------|---------|----------|---------|-------------|
117/// | `memRegion` | ident   | yes      | —       | Name of a `MemoryRegion` declared in the `.fis` file |
118/// | `vaddr`     | hex     | no       | auto    | Virtual address; auto-allocated if omitted |
119/// | `"perms"`   | string  | yes      | —       | Permission string: `"r"`, `"rw"`, `"rx"`, `"rwx"`, `"x"`, `"wx"` |
120/// | `cached`    | bool    | no       | true    | Whether the mapping uses the CPU cache |
121///
122/// The security label must be ≥ the mapped region's label (no `High`→`Low` downgrade).
123///
124/// ```text
125/// Mapping ring_buf(ring_buffer_outer, 0x3_000_000, "rw");         // fixed vaddr
126/// Mapping pkt_buf(packet_buffer_outer, "rw", true);               // auto vaddr, cached
127/// High Mapping secret(high_region, "r");                          // High mapping
128/// Low  Mapping io(mmio_region, 0x2_000_000, "rw", false);        // uncached MMIO
129/// ```
130///
131/// Language reference: [Mappings](https://fiducia-lang.github.io/docs/lang-spec/items/imports-and-mappings.html#mappings).
132#[derive(Debug, Clone, Serialize)]
133pub struct MappingDecl {
134    /// Information flow security label (defaults to `Low`).
135    pub security_label: SecurityLabel,
136    /// Mapping name.
137    pub name: String,
138    /// Name of the memory region to map.
139    pub mem_region: String,
140    /// Optional fixed virtual address.
141    pub vaddr: Option<Address>,
142    /// Access permissions (r, rw, rx, rwx, etc.).
143    pub perms: Permission,
144    /// Whether the mapping is cached.
145    pub cached: bool,
146    /// Byte offset of `mem_region` identifier in the source.
147    pub mem_region_offset: usize,
148    /// Byte offset of the vaddr value (or closing paren if absent).
149    pub vaddr_offset: usize,
150    /// Byte span of the entire declaration in the source.
151    pub span: Range<usize>,
152}
153
154impl Display for MappingDecl {
155    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
156        write!(
157            f,
158            "region: {}, security: {}, perms: {}, cached: {}",
159            self.mem_region, self.security_label, self.perms, self.cached
160        )
161    }
162}