1mod analysis;
16pub(crate) mod checking;
17pub(crate) mod compile;
18mod resolve;
19
20pub use checking::{
21 ModuleCheckingReport, check_module, check_module_with_environment,
22 check_recovered_source_with_environment,
23};
24pub use compile::{CompiledModules, ModuleCompiler, PreparedRoot, RootCell};
25
26use std::{collections::HashMap, fmt, str::FromStr};
27
28use cel_parser::SourceSpan;
29
30use crate::{
31 AdamAstParser, ModuleDiagnostic, SourceId, SourceLabel, SourceLocation, SourceMap,
32 TypedTemplate, ast,
33};
34
35#[derive(Clone, Debug, Eq, Hash, PartialEq)]
41pub struct ModulePath(Vec<String>);
42
43impl FromStr for ModulePath {
44 type Err = ModuleDiagnostic;
46
47 fn from_str(path: &str) -> Result<Self, Self::Err> {
53 let segments: Vec<_> = path.split("::").collect();
54 if !segments.iter().all(|segment| valid_identifier(segment)) {
55 return Err(crate::composition::diagnostic("invalid module path"));
56 }
57 Ok(Self(segments.into_iter().map(str::to_owned).collect()))
58 }
59}
60
61#[cfg(test)]
62mod identifier_tests {
63 use super::*;
64
65 #[test]
67 fn module_paths_reject_literal_tokens() {
68 for path in ["true", "false", "a::true", "false::b"] {
69 assert!(path.parse::<ModulePath>().is_err(), "{path}");
70 }
71 for path in ["if", "else", "Δ::constraints"] {
72 assert_eq!(path.parse::<ModulePath>().unwrap().to_string(), path);
73 }
74 }
75}
76
77impl fmt::Display for ModulePath {
78 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
82 for (index, segment) in self.0.iter().enumerate() {
83 if index != 0 {
84 formatter.write_str("::")?;
85 }
86 formatter.write_str(segment)?;
87 }
88 Ok(())
89 }
90}
91
92pub(crate) fn valid_identifier(name: &str) -> bool {
96 if matches!(name, "" | "_" | "sheet" | "use" | "as") || name.starts_with("r#") {
97 return false;
98 }
99 let Ok(stream) = name.parse::<proc_macro2::TokenStream>() else {
100 return false;
101 };
102 let mut tokens = cel_parser::lex_lexer::LexLexer::new(stream.into_iter());
103 matches!(tokens.next(), Some(cel_parser::lex_lexer::Token::Identifier(ident)) if ident == name)
104 && tokens.next().is_none()
105}
106
107#[derive(Default)]
115pub struct ModuleSet {
116 entries: Vec<ModuleEntry>,
117 indices: HashMap<ModulePath, usize>,
118 sources: SourceMap,
119 native_binding: Option<cel_parser::checking::HostTypeBinding>,
120}
121
122struct ModuleEntry {
124 path: ModulePath,
125 source: Option<SourceId>,
126 imports: Vec<ast::UseDecl>,
127 definitions: Vec<Definition>,
128}
129
130struct Definition {
132 name: String,
133 body: DefinitionBody,
134}
135
136enum DefinitionBody {
138 Parsed {
139 sheet: Box<ast::Sheet>,
140 label: SourceLabel,
141 },
142 Native(TypedTemplate),
143}
144
145impl Definition {
146 fn label(&self) -> &SourceLabel {
148 match &self.body {
149 DefinitionBody::Parsed { label, .. } => label,
150 DefinitionBody::Native(template) => template.definition_label(),
151 }
152 }
153}
154
155impl ModuleSet {
156 pub fn set_native_binding(&mut self, binding: cel_parser::checking::HostTypeBinding) {
170 self.native_binding = Some(binding);
171 }
172
173 pub fn new() -> Self {
178 Self::default()
179 }
180
181 pub fn insert_source(
193 &mut self,
194 path: ModulePath,
195 file_name: &str,
196 source: &str,
197 ) -> Result<(), ModuleDiagnostic> {
198 if let Some(index) = self.indices.get(&path)
199 && self.entries[*index].source.is_some()
200 {
201 return Err(crate::composition::diagnostic(
202 "module already has a source file",
203 ));
204 }
205 let parsed = AdamAstParser::new()
206 .parse_module_str(source)
207 .map_err(|error| rejected_source_error(file_name, source, &error))?;
208 if let Some(error) = parsed.errors.first() {
209 return Err(rejected_source_error(file_name, source, error));
210 }
211 let owner = self.sources.insert(file_name, source);
212 let entry = self.entry(path);
213 entry.source = Some(owner.clone());
214 for item in parsed.items {
215 match item {
216 ast::ModuleItem::Use(import) => entry.imports.push(import),
217 ast::ModuleItem::Sheet(sheet) => entry.definitions.push(Definition {
218 name: sheet.name.clone(),
219 body: DefinitionBody::Parsed {
220 label: label(&owner, sheet.name_span, &sheet.name),
221 sheet: Box::new(sheet),
222 },
223 }),
224 ast::ModuleItem::Error(_) => unreachable!("recovered errors rejected above"),
225 }
226 }
227 Ok(())
228 }
229
230 pub fn insert_template(
246 &mut self,
247 path: ModulePath,
248 name: &str,
249 template: TypedTemplate,
250 ) -> Result<(), ModuleDiagnostic> {
251 if !valid_identifier(name) {
252 return Err(crate::composition::diagnostic("invalid definition name"));
253 }
254 let entry = self.entry(path);
255 if let Some(existing) = entry
256 .definitions
257 .iter()
258 .find(|definition| definition.name == name)
259 {
260 return Err(ModuleDiagnostic {
261 cause: None,
262 message: "duplicate local definition".into(),
263 labels: vec![
264 template.definition_label().clone(),
265 existing.label().clone(),
266 ],
267 });
268 }
269 entry.definitions.push(Definition {
270 name: name.into(),
271 body: DefinitionBody::Native(template),
272 });
273 Ok(())
274 }
275
276 pub fn check_resolution(&self) -> Result<(), Vec<ModuleDiagnostic>> {
294 resolve::resolve(self).map(|_| ())
295 }
296
297 fn entry(&mut self, path: ModulePath) -> &mut ModuleEntry {
301 let index = *self.indices.entry(path.clone()).or_insert_with(|| {
302 let index = self.entries.len();
303 self.entries.push(ModuleEntry {
304 path,
305 source: None,
306 imports: Vec::new(),
307 definitions: Vec::new(),
308 });
309 index
310 });
311 &mut self.entries[index]
312 }
313}
314
315fn label(source: &SourceId, span: ast::ExprSpan, text: &str) -> SourceLabel {
319 SourceLabel {
320 location: Some(SourceLocation {
321 source: source.clone(),
322 span: SourceSpan::from_proc_macro2_range(span.start, span.end),
323 }),
324 label: text.into(),
325 }
326}
327
328fn source_error(
332 source: &SourceId,
333 span: SourceSpan,
334 message: impl fmt::Display,
335) -> ModuleDiagnostic {
336 let message = message.to_string();
337 ModuleDiagnostic {
338 cause: None,
339 labels: vec![SourceLabel {
340 location: Some(SourceLocation {
341 source: source.clone(),
342 span,
343 }),
344 label: message.clone(),
345 }],
346 message,
347 }
348}
349
350fn parse_error(source: &SourceId, error: &crate::ParseError) -> ModuleDiagnostic {
354 let span = SourceSpan::from_proc_macro2_range(
355 error.span(),
356 error.end_span().unwrap_or_else(|| error.span()),
357 );
358 let mut diagnostic = source_error(source, span, error.message());
359 diagnostic
360 .labels
361 .extend(error.secondary().iter().map(|secondary| SourceLabel {
362 location: Some(SourceLocation {
363 source: source.clone(),
364 span: secondary.span,
365 }),
366 label: secondary.label.clone(),
367 }));
368 diagnostic
369}
370
371fn rejected_source_error(
375 file_name: &str,
376 text: &str,
377 error: &crate::ParseError,
378) -> ModuleDiagnostic {
379 let owner = SourceMap::new().insert(file_name, text);
380 parse_error(&owner, error)
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386
387 #[test]
389 fn rejected_source_revisions_do_not_enter_the_source_collection() {
390 let mut modules = ModuleSet::new();
391 let template = crate::CompositionBuilder::new(crate::TypeRegistry::new())
392 .finish()
393 .unwrap();
394 modules
395 .insert_template("app".parse().unwrap(), "helper", template)
396 .unwrap();
397 let mut retained_error = None;
398 for revision in 0..8usize {
399 let source = if revision % 2 == 0 {
400 format!("sheet broken( // revision {revision}")
401 } else {
402 format!("sheet broken {{ cell x: ; }} // revision {revision}")
403 };
404 let error = modules
405 .insert_source(
406 "app".parse().unwrap(),
407 &format!("rejected-{revision}.adm2"),
408 &source,
409 )
410 .unwrap_err();
411 assert_eq!(
412 modules.sources.sources().len(),
413 0,
414 "failed revision {revision} retained"
415 );
416 retained_error = Some(error);
417 }
418 modules
419 .insert_source(
420 "app".parse().unwrap(),
421 "accepted.adm2",
422 "sheet wrapper() { relationship helper(); }",
423 )
424 .unwrap();
425 assert_eq!(modules.sources.sources().len(), 1);
426 assert_eq!(modules.sources.sources()[0].file_name(), "accepted.adm2");
427 modules.check_resolution().unwrap();
428 drop(modules);
429
430 let error = retained_error.unwrap();
431 let location = error.labels[0].location.as_ref().unwrap();
432 assert_eq!(location.source.file_name(), "rejected-7.adm2");
433 assert_eq!(
434 location.source.text(),
435 "sheet broken { cell x: ; } // revision 7"
436 );
437 assert_eq!(
438 &location.source.text()[location.span.to_byte_range(location.source.text())],
439 ";"
440 );
441 }
442}