1use std::collections::{HashMap, HashSet};
23use std::ops::Range;
24
25use serde::Serialize;
26
27use crate::ast::{ArraySize, ChannelKind, MemoryRegionDecl, ProtectionDomainDecl, RawAst, Type};
28use crate::base::{
29 ArrayLen, Buffer, ChanId, ChannelEnd, Composition, ConstId, FfnId, IdVec, Idx, LocalVarId,
30 Mapping, MappingId, MrId, PdId, StructId, TypeRef,
31};
32use crate::error::{Diagnostic, Diagnostics};
33use crate::foreign::ForeignModules;
34
35use super::data::resolve_data;
36use super::program::resolve_program;
37use super::system::resolve_system;
38use super::validation::{mapped_buffers, shared_buffers};
39use super::{mkids, vaddr};
40use super::{Bodies, Expr};
41
42#[derive(Debug, Clone, Serialize)]
44pub struct Rast {
45 pub env: Env,
47 pub bodies: Bodies,
49}
50
51#[derive(Debug, Clone, Serialize)]
54pub struct Env {
55 pub file: String,
57 pub mrs: IdVec<MrId, MemoryRegionDecl>,
59 pub pds: IdVec<PdId, ProtectionDomainDecl>,
61 pub chans: IdVec<ChanId, Channel>,
63 pub structs: IdVec<StructId, Struct>,
65 pub consts: IdVec<ConstId, Const>,
67 pub composition: Option<Composition>,
69 pub irq_ids: IdVec<PdId, Option<u32>>,
73 pub locals: IdVec<PdId, LocalVars>,
76 pub mappings: IdVec<MappingId, Mapping>,
80 pub ffis: IdVec<FfnId, ForeignFn>,
83}
84
85#[derive(Debug, Clone, Serialize)]
90pub struct ForeignFn {
91 pub name: String,
93 pub params: Vec<TypeRef>,
95 pub ret: Option<TypeRef>,
97 pub variadic: bool,
99}
100
101#[derive(Debug, Clone, Serialize)]
103pub struct Channel {
104 pub name: String,
106 pub kind: ChannelKind,
108 pub sender: ChannelEnd,
110 pub receiver: ChannelEnd,
112 pub buffer: Option<Buffer>,
114 pub payload: Option<TypeRef>,
116 pub span: Range<usize>,
118}
119
120#[derive(Debug, Clone, Serialize)]
122pub struct Struct {
123 pub name: String,
125 pub packed: bool,
127 pub fields: Vec<Field>,
129 pub span: Range<usize>,
131}
132
133#[derive(Debug, Clone, Serialize)]
135pub struct Field {
136 pub name: String,
138 pub ty: TypeRef,
140 pub span: Range<usize>,
142}
143
144#[derive(Debug, Clone, Serialize)]
146pub struct Const {
147 pub name: String,
149 pub ty: TypeRef,
151 pub value: Expr,
153 pub span: Range<usize>,
155}
156
157#[derive(Debug, Clone, Serialize)]
159pub struct LocalVar {
160 pub name: String,
162 pub ty: TypeRef,
164 pub span: Range<usize>,
166}
167
168pub type LocalVars = IdVec<LocalVarId, LocalVar>;
170
171pub fn build(
198 rawast: &RawAst,
199 env: Env,
200 foreign: &mut ForeignModules,
201) -> Result<(Rast, Diagnostics), Diagnostics> {
202 let (env, mut warnings) = build_system(rawast, env)?;
203 let (rast, more) = build_programs(rawast, env, foreign)?;
204 warnings.0.extend(more.0);
205 let rast = lay_out(rast)?;
206 Ok((rast, warnings))
207}
208
209pub fn build_data(rawast: &RawAst) -> Result<(Env, Diagnostics), Diagnostics> {
218 let mut errors = Vec::new();
219 let system = &rawast.system;
220 let file = system.filename.as_str();
221 let structs = system.structs.iter().map(|s| (s.name.as_str(), &s.span));
222 reject_duplicates("struct", structs, file, &mut errors);
223 let consts = system.consts.iter().map(|c| (c.name.as_str(), &c.span));
224 reject_duplicates("constant", consts, file, &mut errors);
225 let names = Names::new(rawast);
226 let mut env = Env {
227 file: rawast.system.filename.clone(),
228 mrs: IdVec::new(),
229 pds: IdVec::new(),
230 chans: IdVec::new(),
231 structs: IdVec::new(),
232 consts: IdVec::new(),
233 composition: None,
234 irq_ids: IdVec::new(),
235 locals: IdVec::new(),
236 mappings: IdVec::new(),
237 ffis: IdVec::new(),
238 };
239 resolve_data(&rawast.system, &names, &mut env, &mut errors);
240 let warnings = Diagnostics::warnings(&mut errors);
241 Diagnostics::finish(errors, (env, warnings))
242}
243
244pub fn build_system(rawast: &RawAst, mut env: Env) -> Result<(Env, Diagnostics), Diagnostics> {
256 let mut errors = Vec::new();
257 let system = &rawast.system;
258 let file = system.filename.as_str();
259 let mrs = system.memory_regions.iter();
260 reject_duplicates(
261 "memory region",
262 mrs.map(|m| (m.name.as_str(), &m.span)),
263 file,
264 &mut errors,
265 );
266 let pds = system.protection_domains.iter();
267 reject_duplicates(
268 "protection domain",
269 pds.map(|p| (p.name.as_str(), &p.span)),
270 file,
271 &mut errors,
272 );
273 let chans = system.channels.iter().map(|c| (c.name.as_str(), &c.span));
274 reject_duplicates("channel", chans, file, &mut errors);
275 let names = Names::new(rawast);
276 let ids = mkids::allocate(rawast, &names, &mut errors);
277 resolve_system(&rawast.system, &names, &ids, &mut env, &mut errors);
278 shared_buffers(&env, &mut errors);
279 let warnings = Diagnostics::warnings(&mut errors);
280 Diagnostics::finish(errors, (env, warnings))
281}
282
283pub fn build_programs(
292 rawast: &RawAst,
293 mut env: Env,
294 foreign: &mut ForeignModules,
295) -> Result<(Rast, Diagnostics), Diagnostics> {
296 let mut errors = Vec::new();
297 foreign.ffis = IdVec::new();
300 let names = Names::new(rawast);
301 let bodies = resolve_programs(rawast, &names, &mut env, foreign, &mut errors);
302 mapped_buffers(&env, &mut errors);
303 let warnings = Diagnostics::warnings(&mut errors);
304 Diagnostics::finish(errors, (Rast { env, bodies }, warnings))
305}
306
307pub fn lay_out(mut rast: Rast) -> Result<Rast, Diagnostics> {
316 let mut errors = Vec::new();
317 vaddr::allocate(&mut rast.env, &mut errors);
318 Diagnostics::finish(errors, rast)
319}
320
321fn resolve_programs(
324 rawast: &RawAst,
325 names: &Names<'_>,
326 env: &mut Env,
327 foreign: &mut ForeignModules,
328 errors: &mut Vec<Diagnostic>,
329) -> Bodies {
330 let mut bodies = Bodies::default();
331 let pds = &rawast.system.protection_domains;
332 if !rawast.programs.is_empty() && rawast.programs.len() != pds.len() {
336 errors.push(Diagnostic::at(
337 format!(
338 "{} programs for {} protection domains",
339 rawast.programs.len(),
340 pds.len()
341 ),
342 0..0,
343 rawast.system.filename.clone(),
344 ));
345 }
346 for (index, (decl, program)) in pds.iter().zip(&rawast.programs).enumerate() {
347 let pd = PdId::new(index);
348 if names.pds.get(decl.name.as_str()) != Some(&pd) {
349 continue;
352 }
353 bodies.push(resolve_program(pd, program, env, names, foreign, errors));
354 }
355 bodies
356}
357
358pub(super) struct Names<'s> {
361 pub mrs: HashMap<&'s str, MrId>,
362 pub pds: HashMap<&'s str, PdId>,
363 pub chans: HashMap<&'s str, ChanId>,
364 pub structs: HashMap<&'s str, StructId>,
365 pub consts: HashMap<&'s str, ConstId>,
366}
367
368impl<'s> Names<'s> {
369 fn new(rawast: &'s RawAst) -> Self {
370 let system = &rawast.system;
371 Self {
372 mrs: index(system.memory_regions.iter().map(|m| m.name.as_str())),
373 pds: index(system.protection_domains.iter().map(|p| p.name.as_str())),
374 chans: index(system.channels.iter().map(|c| c.name.as_str())),
375 structs: index(system.structs.iter().map(|s| s.name.as_str())),
376 consts: index(system.consts.iter().map(|c| c.name.as_str())),
377 }
378 }
379}
380
381pub(super) fn reject_duplicates<'s>(
384 kind: &str,
385 decls: impl Iterator<Item = (&'s str, &'s Range<usize>)>,
386 file: &str,
387 errors: &mut Vec<Diagnostic>,
388) {
389 let mut seen = HashSet::new();
390 for (name, span) in decls {
391 if !seen.insert(name) {
392 errors.push(Diagnostic::at(
393 format!("{kind} '{name}' declared more than once"),
394 span.clone(),
395 file,
396 ));
397 }
398 }
399}
400
401pub(super) fn index<'s, I: Idx>(names: impl Iterator<Item = &'s str>) -> HashMap<&'s str, I> {
403 let mut map = HashMap::new();
404 for (i, name) in names.enumerate() {
405 map.entry(name).or_insert_with(|| I::new(i));
406 }
407 map
408}
409
410pub(super) fn type_ref(ty: &Type, names: &Names<'_>) -> Result<TypeRef, String> {
413 Ok(match ty {
414 Type::Primitive(p) => TypeRef::Prim(*p),
415 Type::Struct(name) => match names.structs.get(name.as_str()) {
416 Some(&id) => TypeRef::Struct(id),
417 None => return Err(format!("struct '{name}' is not declared")),
418 },
419 Type::Array { elem, size } => TypeRef::Array {
420 elem: Box::new(type_ref(elem, names)?),
421 len: array_len(size, names)?,
422 },
423 })
424}
425
426pub(super) fn array_len(size: &ArraySize, names: &Names<'_>) -> Result<ArrayLen, String> {
429 Ok(match size {
430 ArraySize::Lit(n) => ArrayLen::Lit(*n),
431 ArraySize::Named(c) => match names.consts.get(c.as_str()) {
432 Some(&id) => ArrayLen::Const(id),
433 None => return Err(format!("constant '{c}' is not declared")),
434 },
435 })
436}
437
438#[cfg(test)]
440pub(crate) fn built(
441 fis: &str,
442 programs: &[(&str, &str)],
443) -> Result<(Rast, Diagnostics), Diagnostics> {
444 built_with(fis, programs, &[])
445}
446
447#[cfg(test)]
451pub(crate) fn built_with(
452 fis: &str,
453 programs: &[(&str, &str)],
454 modules: &[(&str, &str)],
455) -> Result<(Rast, Diagnostics), Diagnostics> {
456 let rawast = ast_of(fis, programs);
457 let (env, mut warnings) = build_data(&rawast)?;
458 let (rast, more) = build(&rawast, env, &mut store(&rawast, modules))?;
459 warnings.0.extend(more.0);
460 Ok((rast, warnings))
461}
462
463#[cfg(test)]
467pub(crate) fn store(rawast: &RawAst, modules: &[(&str, &str)]) -> ForeignModules {
468 use std::path::Path;
469
470 use crate::foreign::{parse as parse_foreign, ForeignLang};
471
472 let mut foreign = ForeignModules::new();
473 for (path, source) in modules {
474 let lang = if Path::new(path).extension().is_some_and(|x| x == "pnk") {
475 ForeignLang::Pancake
476 } else {
477 ForeignLang::C
478 };
479 let module = parse_foreign(source, Path::new(path), Path::new(path).into(), lang, &[])
480 .unwrap_or_else(|e| panic!("failed to read {path} (a .h needs libclang): {e}"));
481 foreign.insert(module);
482 }
483 foreign.bind(rawast);
484 foreign
485}
486
487#[cfg(test)]
496fn least_program(system: &crate::ast::System, pd: &ProtectionDomainDecl) -> String {
497 let head = if let Some(irq) = pd.irq {
498 format!("irq?{irq} -> Notified()")
499 } else if let Some(ch) = system.channels.iter().find(|c| {
500 c.receiver == pd.name || (c.kind == crate::ast::ChannelKind::AsyncBi && c.sender == pd.name)
501 }) {
502 let binder = if ch.buffer.is_some() { "x" } else { "" };
503 format!("{}?{binder} -> Notified()", ch.name)
504 } else {
505 "Skip".to_owned()
506 };
507 format!(
508 "@bind(microkit.init)\nproc Init() {{ Skip; }}\n\
509 @bind(microkit.notified)\nproc Notified() {{ {head}; }}\n"
510 )
511}
512
513#[cfg(test)]
514pub(crate) fn ast_of(fis: &str, programs: &[(&str, &str)]) -> RawAst {
515 use crate::parser::{parse_program, parse_system};
516
517 let mut system = parse_system(fis).expect("fis parses");
518 system.filename = "test.fis".to_owned();
519 let given = programs;
520 for pd in &mut system.protection_domains {
521 pd.fi = format!("{}.fi", pd.name).into();
522 }
523 let programs = system
524 .protection_domains
525 .iter()
526 .filter(|_| !given.is_empty())
527 .map(|pd| {
528 let src = given
529 .iter()
530 .find(|(name, _)| *name == pd.name)
531 .map_or_else(|| least_program(&system, pd), |(_, src)| (*src).to_owned());
532 parse_program(&src).expect("fi parses")
533 })
534 .collect();
535 RawAst { system, programs }
536}
537
538#[cfg(test)]
539mod tests {
540 use std::path::Path;
541
542 use super::*;
543
544 const FIS: &str = "
545 struct Slot { tag: byte; }
546 const N: uint32 = 4;
547 MemoryRegion buf(0x1000);
548 ProtectionDomain client(100);
549 ProtectionDomain server(200);
550 Chan link = client <-> server;
551 ";
552
553 #[test]
554 fn duplicate_system_declarations_are_each_reported_at_the_later_one() {
555 let fis = "MemoryRegion buf(0x1000);
556 MemoryRegion buf(0x2000);
557 ProtectionDomain a(100);
558 ProtectionDomain a(101);
559 ProtectionDomain b(102);
560 Chan link = a --> b;
561 Chan link = a --> b;";
562 let err = built(fis, &[]).expect_err("three duplicates");
563 let text = err.to_string();
564 for expected in [
565 "memory region 'buf' declared more than once",
566 "protection domain 'a' declared more than once",
567 "channel 'link' declared more than once",
568 ] {
569 assert!(text.contains(expected), "missing `{expected}` in:\n{text}");
570 }
571 assert_eq!(text.matches("declared more than once").count(), 3, "{text}");
572 let seconds = [
574 fis.rfind("MemoryRegion buf").unwrap(),
575 fis.rfind("ProtectionDomain a").unwrap(),
576 fis.rfind("Chan link").unwrap(),
577 ];
578 for d in err
579 .0
580 .iter()
581 .filter(|d| d.message().contains("more than once"))
582 {
583 assert_eq!(d.filename(), Some("test.fis"));
584 let start = d.span().start;
585 assert!(
586 seconds.iter().any(|&s| start <= s && s < start + 40),
587 "span start {start} does not sit on a second declaration"
588 );
589 }
590 }
591
592 #[test]
593 fn the_sixty_fourth_protection_domain_is_one_too_many() {
594 let max = PdId::MAX.index() + 1;
595 let pds = |n: usize| {
596 (0..n).fold(String::new(), |fis, i| {
597 fis + &format!("ProtectionDomain pd{i}({});", 100 + i)
598 })
599 };
600 built(&pds(max), &[]).expect("63 protection domains fit");
601 let err = built(&pds(max + 1), &[]).expect_err("the 64th does not");
602 let text = err.to_string();
603 assert!(
604 text.contains(
605 "protection domain 'pd63' is one too many: at most 63 protection domains"
606 ),
607 "{text}"
608 );
609 assert_eq!(err.0.len(), 1, "{text}");
610 }
611
612 #[test]
613 fn a_constant_without_an_upper_case_name_is_warned_about() {
614 let (Rast { .. }, warnings) = built(
615 "const rounds: int = 5;\nconst Limit: int = 1;\nconst SLOT_2: int = 2;\n\
616 ProtectionDomain a(1);",
617 &[],
618 )
619 .expect("a warning, not an error");
620 let messages: Vec<&str> = warnings.0.iter().map(Diagnostic::message).collect();
621 assert_eq!(
622 messages,
623 [
624 "constant 'rounds' should have an upper-case name: 'ROUNDS'",
625 "constant 'Limit' should have an upper-case name: 'LIMIT'",
626 ]
627 );
628 assert_eq!(warnings.0[0].filename(), Some("test.fis"));
629 }
630
631 #[test]
632 fn duplicate_program_declarations_are_reported_in_that_file() {
633 let fi = r#"import "c/a.h" as io;
634 import "c/b.h" as io;
635 Mapping m(buf, "rw");
636 Mapping m(buf, "r");
637 counter: uint32;
638 counter: uint32;
639 evt tick: counter = 1;
640 evt tick: counter = 2;
641 proc Init() { Skip; }
642 proc Init() { Skip; }"#;
643 let err = built(FIS, &[("client", fi)]).expect_err("duplicates");
644 let duplicates: Vec<_> = err
645 .0
646 .iter()
647 .filter(|d| d.message().contains("declared more than once"))
648 .collect();
649 let text: Vec<&str> = duplicates.iter().map(|d| d.message()).collect();
650 for expected in [
651 "import alias 'io' declared more than once",
652 "mapping 'm' declared more than once",
653 "variable 'counter' declared more than once",
654 "event 'tick' declared more than once",
655 "process 'Init' declared more than once",
656 ] {
657 assert!(text.contains(&expected), "missing `{expected}` in {text:?}");
658 }
659 assert_eq!(duplicates.len(), 5, "{text:?}");
660 assert!(duplicates.iter().all(|d| d.filename() == Some("client.fi")));
661 }
662
663 #[test]
664 fn duplicate_system_structs_and_consts_are_reported() {
665 let fis = "struct S { a: byte; }
666 struct S { b: byte; }
667 const N: uint32 = 1;
668 const N: uint32 = 2;";
669 let text = built(fis, &[]).expect_err("duplicates").to_string();
670 assert!(
671 text.contains("struct 'S' declared more than once"),
672 "{text}"
673 );
674 assert!(
675 text.contains("constant 'N' declared more than once"),
676 "{text}"
677 );
678 }
679
680 #[test]
681 fn programs_are_indexed_by_their_pd() {
682 let (Rast { env, bodies }, _) = built(
684 "ProtectionDomain a(1);\nProtectionDomain b(2);",
685 &[("b", "x: int;"), ("a", "")],
686 )
687 .expect("builds");
688 assert_eq!((env.locals.len(), bodies.len()), (2, 2));
689 assert!(env.locals[PdId::new(0)].is_empty());
690 assert_eq!(env.locals[PdId::new(1)].len(), 1);
691 assert_eq!(env.pds[PdId::new(1)].fi, Path::new("b.fi"));
692 }
693
694 #[test]
695 fn a_project_out_of_step_with_its_pds_is_rejected() {
696 let mut rawast = ast_of(
699 "ProtectionDomain a(1);\nProtectionDomain b(2);",
700 &[("a", ""), ("b", "")],
701 );
702 rawast.programs.pop();
703 let (env, _) = build_data(&rawast).expect("builds the data layer");
704 let err = build(&rawast, env, &mut ForeignModules::new()).expect_err("one program short");
705 assert!(
706 err.to_string()
707 .contains("1 programs for 2 protection domains"),
708 "{err}"
709 );
710 }
711
712 #[test]
713 fn the_same_name_across_kinds_is_legal() {
714 let fis = "MemoryRegion a(0x1000);
715 ProtectionDomain a(100);
716 ProtectionDomain b(101);
717 Chan a = a --> b;";
718 assert!(built(fis, &[]).is_ok());
719 }
720}