1use 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
31fn 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
61pub 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
106fn 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
144pub 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
172pub 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
189pub 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
208fn 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
221pub 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
246pub 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 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
275pub 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 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 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}