1use std::fs::{self, read_to_string};
10use std::path::{Path, PathBuf};
11
12use anyhow::{anyhow, Result};
13
14use super::{c, pnk, ForeignKind, ForeignLang, ForeignModule, ForeignModules};
15use crate::ast::RawAst;
16use crate::error::{format_errors, Diagnostic};
17
18pub trait Reader {
20 fn read(
29 &self,
30 src: &str,
31 file: &Path,
32 path: PathBuf,
33 includes: &[PathBuf],
34 ) -> Result<ForeignModule, String>;
35}
36
37fn reader(lang: ForeignLang, c: &c::Libclang) -> &dyn Reader {
39 match lang {
40 ForeignLang::C => c,
41 ForeignLang::Pancake => &pnk::Pancake,
42 }
43}
44
45pub fn parse(
51 src: &str,
52 file: &Path,
53 path: PathBuf,
54 lang: ForeignLang,
55 includes: &[PathBuf],
56) -> Result<ForeignModule, String> {
57 reader(lang, &c::Libclang::default()).read(src, file, path, includes)
58}
59
60pub fn load(
70 dir: &Path,
71 include: &Path,
72 extra: &[PathBuf],
73 rawast: &RawAst,
74) -> Result<ForeignModules> {
75 let mut includes = vec![dir.to_path_buf(), include.to_path_buf()];
76 includes.extend_from_slice(extra);
77 let c = c::Libclang::default();
78 let mut modules = ForeignModules::new();
79 let pds = rawast.system.protection_domains.iter();
80 for (pd, program) in pds.zip(&rawast.programs) {
81 let file = pd.fi.display().to_string();
82 for import in &program.imports {
83 let written = import.path.clone();
84 let span = import.span.clone();
85 let report = |msg: String| {
86 let mut diag = Diagnostic::at(msg, span.clone(), file.clone());
87 diag.resolve_source();
88 anyhow!("{}", format_errors(&[diag], &file))
89 };
90 let Some(kind) = ForeignKind::of(&written) else {
91 return Err(report(format!(
92 "import \"{}\": not a C or Pancake file",
93 written.display()
94 )));
95 };
96 let source = read_to_string(dir.join(&written)).map_err(|err| {
97 report(format!(
98 "import \"{}\": cannot read the file: {err}",
99 written.display()
100 ))
101 })?;
102 let (on_disk, path) = resolve(dir, &written).map_err(|err| {
103 report(format!(
104 "import \"{}\": cannot resolve the path: {err}",
105 written.display()
106 ))
107 })?;
108 let id = if let Some(id) = modules.module(&path) {
109 id
110 } else {
111 let module = reader(kind.lang(), &c)
112 .read(&source, &on_disk, path.clone(), &includes)
113 .map_err(|err| report(format!("import \"{}\": {err}", written.display())))?;
114 modules.insert(module)
115 };
116 modules.record(written, id);
117 }
118 }
119 modules.bind(rawast);
120 Ok(modules)
121}
122
123fn resolve(dir: &Path, written: &Path) -> std::io::Result<(PathBuf, PathBuf)> {
127 let file = fs::canonicalize(dir.join(written))?;
128 let root = fs::canonicalize(dir)?;
129 let identity = file
130 .strip_prefix(&root)
131 .map_or_else(|_| file.clone(), Path::to_path_buf);
132 Ok((file, identity))
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn pancake_is_read_without_a_toolchain() {
141 let m = parse(
142 "export fun 1 f(1 x) { return x; }",
143 Path::new("d.pnk"),
144 PathBuf::from("d.pnk"),
145 ForeignLang::Pancake,
146 &[],
147 )
148 .unwrap();
149 assert_eq!(m.exports.len(), 1);
150 assert_eq!(m.lang(), ForeignLang::Pancake);
151 }
152}