Skip to main content

fic/
frontend.rs

1//! The front end: a project parsed ([`parse`]), resolved ([`resolve`]) and
2//! typed ([`front_end`]), printing the progress lines. Contracts
3//! ([`contracts`]), information flow and WF2 run only for the targets that
4//! need them.
5//!
6//! The `.fis` is the project. [`parse_sources`] finds it (the one read of
7//! the directory), parses it, binds each protection domain to its `.fi`
8//! (`<name>.fi` beside the `.fis`), and parses those in PD order; a `.fi`
9//! no PD names is never opened. The parser decides nothing about an
10//! imported file: its kind follows from its extension, which
11//! [`check_imports`] rejects or accepts as the program is bound.
12
13use std::collections::HashSet;
14use std::fs::{read_dir, read_to_string};
15use std::path::{Path, PathBuf};
16
17use anyhow::{anyhow, bail, Context, Result};
18
19use crate::ast::{Program, RawAst, System};
20use crate::error::Diagnostic;
21use crate::foreign::contract::ContractTable;
22use crate::foreign::{
23    export, extract as extract_contracts, load as load_foreign, ForeignKind, ForeignModules,
24};
25use crate::microkit::EntryPoints;
26use crate::parser::{format_errors, parse_program, parse_system};
27use crate::rast::{self, Env, Rast};
28use crate::tast::{self, Tast, TyEnv};
29use crate::wfcheck::check_tail_rec;
30
31/// The one `.fis` of `dir`, and the stems of the `.fi` files beside it
32/// (seen in the same listing, kept for the stray warning).
33fn discover(dir: &Path) -> Result<(PathBuf, Vec<String>)> {
34    let entries =
35        read_dir(dir).with_context(|| format!("failed to read directory {}", dir.display()))?;
36    let mut fis_files = Vec::new();
37    let mut stems = Vec::new();
38    for entry in entries {
39        let path = entry.context("failed to read directory entry")?.path();
40        match path.extension().and_then(|e| e.to_str()) {
41            Some("fis") => fis_files.push(path),
42            Some("fi") => {
43                if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
44                    stems.push(stem.to_owned());
45                }
46            }
47            _ => {}
48        }
49    }
50    if fis_files.is_empty() {
51        bail!("no .fis file found in Fiducia directory");
52    }
53    if fis_files.len() > 1 {
54        let names: Vec<_> = fis_files.iter().map(|p| p.display().to_string()).collect();
55        bail!("multiple .fis files found: {}", names.join(", "));
56    }
57    stems.sort();
58    Ok((fis_files.remove(0), stems))
59}
60
61/// Parse a project: the `.fis`, then each protection domain's `.fi`, in
62/// PD order, each file read once.
63///
64/// # Errors
65///
66/// In this order, the first stopping the stage: the `.fis` does not
67/// parse; a protection domain has no `<name>.fi` or is declared more than
68/// once (all reported together); a `.fi` does not parse or imports a file
69/// fic cannot read.
70pub fn parse_sources(dir: &Path) -> Result<RawAst> {
71    let (fis_path, stems) = discover(dir)?;
72    let fis_text = read_to_string(&fis_path)
73        .with_context(|| format!("failed to read {}", fis_path.display()))?;
74    let fis_filename = fis_path.display().to_string();
75    let mut system = parse_system(&fis_text)
76        .map_err(|errors| anyhow!("{}", format_errors(&errors, &fis_filename)))?;
77    system.filename = fis_filename;
78    bind(dir, &mut system, &fis_text)?;
79    for stem in stems {
80        if system.protection_domains.iter().all(|pd| pd.name != stem) {
81            let file = dir.join(format!("{stem}.fi"));
82            eprintln!(
83                "{}",
84                Diagnostic::warn_at(
85                    format!("{stem}.fi implements no protection domain: not parsed"),
86                    0..0,
87                    file.display().to_string(),
88                )
89            );
90        }
91    }
92    let mut programs = Vec::with_capacity(system.protection_domains.len());
93    for pd in &system.protection_domains {
94        let fi_filename = pd.fi.display().to_string();
95        let text =
96            read_to_string(&pd.fi).with_context(|| format!("failed to read {fi_filename}"))?;
97        let program = parse_program(&text)
98            .map_err(|errors| anyhow!("{}", format_errors(&errors, &fi_filename)))?;
99        check_imports(&program, &text)
100            .map_err(|errors| anyhow!("{}", format_errors(&errors, &fi_filename)))?;
101        programs.push(program);
102    }
103    Ok(RawAst { system, programs })
104}
105
106/// Bind each protection domain to `<name>.fi` beside the `.fis`. A PD
107/// declared again is dropped from the list, so programs and PDs stay
108/// one-to-one; it and a PD whose file does not exist are reported
109/// together, at their declarations.
110fn bind(dir: &Path, system: &mut System, fis_text: &str) -> Result<()> {
111    let mut errors = Vec::new();
112    let mut seen = HashSet::new();
113    let mut pds = Vec::with_capacity(system.protection_domains.len());
114    for mut pd in system.protection_domains.drain(..) {
115        if !seen.insert(pd.name.clone()) {
116            errors.push(Diagnostic::new(
117                format!("protection domain '{}' declared more than once", pd.name),
118                pd.span.clone(),
119                fis_text.to_owned(),
120            ));
121            continue;
122        }
123        pd.fi = dir.join(format!("{}.fi", pd.name));
124        if !pd.fi.is_file() {
125            errors.push(Diagnostic::new(
126                format!(
127                    "protection domain '{}' has no program: no {}.fi",
128                    pd.name, pd.name
129                ),
130                pd.span.clone(),
131                fis_text.to_owned(),
132            ));
133        }
134        pds.push(pd);
135    }
136    system.protection_domains = pds;
137    if errors.is_empty() {
138        Ok(())
139    } else {
140        Err(anyhow!("{}", format_errors(&errors, &system.filename)))
141    }
142}
143
144/// Check a program's imports are of files fic can read, by their
145/// extension ([`ForeignKind::of`]): the one place that rejects one. `text`
146/// is the program's source, for the diagnostics.
147///
148/// # Errors
149///
150/// An import of a file fic cannot read, at the import.
151pub fn check_imports(program: &Program, text: &str) -> Result<(), Vec<Diagnostic>> {
152    let mut errors = Vec::new();
153    for import in &program.imports {
154        if ForeignKind::of(&import.path).is_none() {
155            errors.push(Diagnostic::new(
156                format!(
157                    "import \"{}\": not a C or Pancake file",
158                    import.path.display()
159                ),
160                import.span.clone(),
161                text.to_owned(),
162            ));
163        }
164    }
165    if errors.is_empty() {
166        Ok(())
167    } else {
168        Err(errors)
169    }
170}
171
172/// Build `ast`'s data layer, printing its warnings: the environment holding
173/// it (`rast::build_data`) and the same typed (`tast::build_data`),
174/// what the system and the programs are built on.
175///
176/// # Errors
177///
178/// A struct or const that does not resolve or type.
179pub fn data_layer(rawast: &RawAst) -> Result<(Env, TyEnv)> {
180    let (env, mut warnings) = rast::build_data(rawast)?;
181    let (tenv, more) = tast::build_data(&env)?;
182    warnings.0.extend(more.0);
183    if !warnings.is_empty() {
184        eprintln!("{warnings}");
185    }
186    Ok((env, tenv))
187}
188
189/// Parse a Fiducia directory and load what its programs import:
190/// [`parse_sources`], its [`data_layer`] built and its headers written, then
191/// the imports read, with `includes` after the project's own include path.
192/// Returns the AST, the imports and the data layer.
193pub fn parse(dir: &Path, includes: &[PathBuf]) -> Result<(RawAst, ForeignModules, Env, TyEnv)> {
194    let rawast = parse_sources(dir)?;
195    let (env, tenv) = data_layer(&rawast)?;
196    let include = write_include(dir, &rawast, &tenv)?;
197    let foreign = load_foreign(dir, &include, includes, &rawast)?;
198
199    eprintln!(
200        "  \u{2713} Parsed 1 system + {} program files + {} foreign module(s)",
201        rawast.programs.len(),
202        foreign.len()
203    );
204
205    Ok((rawast, foreign, env, tenv))
206}
207
208/// Write `include/gen/` from the typed data layer `tenv`
209/// ([`crate::foreign::export`]); return `<project>/include`.
210fn write_include(dir: &Path, rawast: &RawAst, tenv: &TyEnv) -> Result<PathBuf> {
211    let include = export(dir, rawast, tenv)?;
212    if include.join("gen").is_dir() {
213        eprintln!(
214            "  \u{2713} Wrote the data-layer headers to {}",
215            include.join("gen").display()
216        );
217    }
218    Ok(include)
219}
220
221/// Build the resolved AST on the data layer, `env` and `tenv` typed: the
222/// system (resolved and typed), the programs, then the vaddrs, each stage's
223/// faults reported before the next. Returns it and the system typed, for
224/// typing the programs.
225pub fn resolve(
226    rawast: &RawAst,
227    foreign: &mut ForeignModules,
228    env: Env,
229    tenv: TyEnv,
230) -> Result<(Rast, TyEnv)> {
231    let (env, mut warnings) = rast::build_system(rawast, env)?;
232    let (tenv, more) = tast::build_system(&env, tenv)?;
233    warnings.0.extend(more.0);
234    let (rast, more) = rast::build_programs(rawast, env, foreign)?;
235    warnings.0.extend(more.0);
236    let rast = rast::lay_out(rast)?;
237    if !warnings.is_empty() {
238        eprintln!("{warnings}");
239    }
240    eprintln!("  \u{2713} Resolved names");
241    eprintln!("  \u{2713} Resolved mapping vaddrs");
242    eprintln!("  \u{2713} Built the resolved AST");
243    Ok((rast, tenv))
244}
245
246/// Run the passes in order on the data layer: [`resolve`], typing (every
247/// program on the typed system), then the process bodies' shape checks.
248pub fn front_end(
249    rawast: &RawAst,
250    foreign: &mut ForeignModules,
251    env: Env,
252    tenv: TyEnv,
253) -> Result<Tast> {
254    let (rast, tenv) = resolve(rawast, foreign, env, tenv)?;
255    let (tast, warnings) = tast::build_programs(rast, tenv)?;
256    if !warnings.is_empty() {
257        eprintln!("{warnings}");
258    }
259    eprintln!("  \u{2713} Built the typed AST");
260
261    check_tail_rec(&tast)?;
262    eprintln!("  \u{2713} Checked process bodies (tail references)");
263
264    // Every PD is a Microkit PD: its program binds both kernel entry
265    // points, whatever else it does.
266    for (pd, body) in tast.bodies.iter_enumerated() {
267        EntryPoints::resolve(&tast.tenv.pds[pd].name, &body.entries)?
268            .check_protected(&tast.tenv, pd)?;
269    }
270    eprintln!("  \u{2713} Bound the kernel entry points of every protection domain");
271
272    Ok(tast)
273}
274
275/// Every called foreign function's contract, lifted from its notation,
276/// with the call sites checked against them.
277pub fn contracts(tast: &Tast, foreign: &ForeignModules) -> Result<ContractTable> {
278    let contracts = extract_contracts(tast, foreign)?;
279    for (lang, n) in contracts.function_counts() {
280        eprintln!("  \u{2713} Read {n} {lang} contract(s)");
281    }
282    Ok(contracts)
283}
284
285#[cfg(test)]
286mod tests {
287    use std::fs;
288
289    use super::*;
290
291    /// A project directory holding `files`, in a temp dir of its own.
292    fn project(name: &str, files: &[(&str, &str)]) -> PathBuf {
293        let dir = std::env::temp_dir().join(format!("fic-frontend-{name}-{}", std::process::id()));
294        let _ = fs::remove_dir_all(&dir);
295        fs::create_dir_all(&dir).unwrap();
296        for (file, text) in files {
297            fs::write(dir.join(file), text).unwrap();
298        }
299        dir
300    }
301
302    const FIS: &str = "ProtectionDomain a(1);\nProtectionDomain b(2);\n";
303
304    #[test]
305    fn programs_are_bound_in_pd_order_whatever_the_files_order() {
306        let dir = project(
307            "order",
308            &[("sys.fis", FIS), ("b.fi", "x: int;"), ("a.fi", "")],
309        );
310        let rawast = parse_sources(&dir).expect("parses");
311        let pds = &rawast.system.protection_domains;
312        assert_eq!(rawast.programs.len(), 2);
313        assert_eq!(pds[0].fi, dir.join("a.fi"));
314        assert_eq!(pds[1].fi, dir.join("b.fi"));
315        assert!(
316            rawast.programs[0].vars.is_empty(),
317            "{:?}",
318            rawast.programs[0].vars
319        );
320        assert_eq!(rawast.programs[1].vars.len(), 1);
321    }
322
323    #[test]
324    fn a_pd_without_a_fi_and_a_duplicate_pd_are_reported_together() {
325        let dir = project(
326            "missing",
327            &[
328                (
329                    "sys.fis",
330                    "ProtectionDomain a(1);\nProtectionDomain b(2);\nProtectionDomain a(3);\n",
331                ),
332                ("a.fi", ""),
333            ],
334        );
335        let err = parse_sources(&dir)
336            .expect_err("b has no file, a twice")
337            .to_string();
338        assert!(
339            err.contains("protection domain 'b' has no program: no b.fi"),
340            "{err}"
341        );
342        assert!(
343            err.contains("protection domain 'a' declared more than once"),
344            "{err}"
345        );
346        // Both point into the .fis: the missing one at `b`, the duplicate
347        // at the second `a`.
348        assert!(err.contains("sys.fis:2:"), "{err}");
349        assert!(err.contains("sys.fis:3:"), "{err}");
350    }
351
352    #[test]
353    fn a_stray_fi_is_neither_parsed_nor_fatal() {
354        let dir = project(
355            "stray",
356            &[
357                ("sys.fis", FIS),
358                ("a.fi", ""),
359                ("b.fi", ""),
360                ("scratch.fi", "this is not a program {{{"),
361            ],
362        );
363        let rawast = parse_sources(&dir).expect("the stray is not parsed");
364        assert_eq!(rawast.programs.len(), 2);
365    }
366
367    #[test]
368    fn an_import_of_a_file_fic_cannot_read_is_rejected_at_the_import() {
369        let dir = project(
370            "rs",
371            &[
372                ("sys.fis", "ProtectionDomain a(1);\n"),
373                ("a.fi", "import \"driver.rs\" as driver;\n"),
374            ],
375        );
376        let err = parse_sources(&dir)
377            .expect_err("no reader for .rs")
378            .to_string();
379        assert!(
380            err.contains("import \"driver.rs\": not a C or Pancake file"),
381            "{err}"
382        );
383        assert!(err.contains("a.fi:1:"), "{err}");
384    }
385
386    #[test]
387    fn imports_of_every_readable_kind_are_bound() {
388        let dir = project(
389            "kinds",
390            &[
391                ("sys.fis", "ProtectionDomain a(1);\n"),
392                (
393                    "a.fi",
394                    "import \"x.h\" as h;\nimport \"y.c\" as c;\nimport \"z.pnk\" as p;\n",
395                ),
396            ],
397        );
398        let rawast = parse_sources(&dir).expect("parses");
399        let kinds: Vec<_> = rawast.programs[0]
400            .imports
401            .iter()
402            .map(|i| ForeignKind::of(&i.path))
403            .collect();
404        assert_eq!(
405            kinds,
406            [
407                Some(ForeignKind::CHeader),
408                Some(ForeignKind::CSource),
409                Some(ForeignKind::Pancake)
410            ]
411        );
412    }
413}