Skip to main content

mq_lang/
module.rs

1pub mod error;
2pub mod resolver;
3
4use crate::{
5    Arena, ArenaId, Program, Shared, SharedCell, TokenArena,
6    ast::{
7        node::{self as ast, Node},
8        parser::Parser,
9    },
10    lexer::{self, Lexer},
11    module::{
12        error::ModuleError,
13        resolver::{DefaultModuleResolver, ModuleResolver},
14    },
15    root_token_arena,
16};
17use rustc_hash::{FxHashMap, FxHashSet};
18use smol_str::SmolStr;
19use std::{borrow::Cow, cell::RefCell, path::PathBuf, sync::LazyLock};
20
21use crate::Token;
22
23struct BuiltinCache {
24    /// Every token of the pristine arena, starting with its dummy EOF token.
25    tokens: Shared<Vec<Token>>,
26    module: Module,
27}
28
29thread_local! {
30    static BUILTIN_CACHE: RefCell<Option<BuiltinCache>> = const { RefCell::new(None) };
31}
32
33/// Id of a module name in the module-name arena.
34pub type ModuleId = ArenaId<ModuleName>;
35
36type ModuleName = SmolStr;
37
38/// Marks module names registered from `.mqc` programs; never part of a real module name.
39const PRECOMPILED_NAME_PREFIX: char = '\0';
40type StandardModules = FxHashMap<SmolStr, fn() -> &'static str>;
41
42impl<T: ModuleResolver> Default for ModuleLoader<T> {
43    fn default() -> Self {
44        Self::new(T::default())
45    }
46}
47
48fn get_module_name(name: &str) -> Cow<'static, str> {
49    // For common module names, use static strings to avoid allocation
50    match name {
51        "cbor" => Cow::Borrowed("cbor.mq"),
52        "csv" => Cow::Borrowed("csv.mq"),
53        "fuzzy" => Cow::Borrowed("fuzzy.mq"),
54        "gron" => Cow::Borrowed("gron.mq"),
55        "html" => Cow::Borrowed("html.mq"),
56        "json" => Cow::Borrowed("json.mq"),
57        "md" => Cow::Borrowed("md.mq"),
58        "section" => Cow::Borrowed("section.mq"),
59        "semver" => Cow::Borrowed("semver.mq"),
60        "test" => Cow::Borrowed("test.mq"),
61        "table" => Cow::Borrowed("table.mq"),
62        "toml" => Cow::Borrowed("toml.mq"),
63        "toon" => Cow::Borrowed("toon.mq"),
64        "xml" => Cow::Borrowed("xml.mq"),
65        "yaml" => Cow::Borrowed("yaml.mq"),
66        _ => Cow::Owned(format!("{}.mq", name)),
67    }
68}
69
70/// Loads, caches and tracks the source of modules through a [`ModuleResolver`].
71#[derive(Debug, Clone)]
72pub struct ModuleLoader<T: ModuleResolver = DefaultModuleResolver> {
73    /// Ids of the modules this loader has loaded.
74    pub(crate) loaded_modules: FxHashSet<ModuleId>,
75    /// Maps module ids to the specifiers they were loaded by. Shared with every loader derived from this one (`clone`,
76    /// `with_same_resolver`), so a token's `module_id` means the same module in all of them.
77    module_names: Shared<SharedCell<Arena<ModuleName>>>,
78    #[cfg(feature = "debugger")]
79    pub(crate) source_code: Option<String>,
80    source_cache: FxHashMap<ModuleId, String>,
81    /// Sources of modules registered from `.mqc` programs, keyed by the id their tokens carry.
82    #[cfg(feature = "mqc")]
83    precompiled_sources: FxHashMap<ModuleId, Shared<str>>,
84    /// The id registered for each `.mqc` module name and source.
85    #[cfg(feature = "mqc")]
86    precompiled_ids: FxHashMap<(SmolStr, Shared<str>), ModuleId>,
87    /// Parsed builtin AST tied to the token arena it was created in, shared by derived loaders.
88    builtin_module_cache: Option<(TokenArena, Shared<Module>)>,
89    /// Parsed `Module`s, so `reload_cached` can reuse an AST already parsed by this loader
90    /// instead of reparsing its cached source.
91    module_ast_cache: FxHashMap<ModuleId, Module>,
92    resolver: T,
93    /// Tracks sub-module loading depth; HTTP imports are blocked when this is greater than zero.
94    #[cfg(feature = "http-import")]
95    http_depth: usize,
96}
97
98/// A file module a [`ModuleLoader`] resolved.
99#[cfg(feature = "mqc")]
100pub(crate) struct ResolvedModule<'a> {
101    /// The display name, which is also the default import alias (e.g. `csv`).
102    pub(crate) name: String,
103    /// The path given to `import`/`include`, which identifies the module.
104    pub(crate) specifier: String,
105    pub(crate) source: &'a str,
106}
107
108/// A loaded module and its top-level definitions.
109#[derive(Debug, Clone, PartialEq)]
110pub struct Module {
111    /// The module name.
112    pub name: String,
113    /// `def` nodes in the module.
114    pub functions: Program,
115    /// Nested `module` nodes.
116    pub modules: Program,
117    /// `let` and `var` nodes in the module.
118    pub vars: Program,
119}
120
121impl Module {
122    /// Name of the builtin module.
123    pub const BUILTIN_MODULE: &str = "builtin";
124    /// Name of the top-level (query) module.
125    pub const TOP_LEVEL_MODULE: &str = "top-level";
126    /// Id of the top-level module.
127    pub const TOP_LEVEL_MODULE_ID: ArenaId<ModuleName> = ArenaId::new(0);
128}
129
130/// Source of the modules bundled with mq, by name.
131pub static STANDARD_MODULES: LazyLock<StandardModules> = LazyLock::new(|| {
132    let mut map = FxHashMap::default();
133
134    macro_rules! std_module {
135        ($name:ident) => {
136            std_module!($name, stringify!($name));
137        };
138        ($name:ident, $key:expr) => {
139            fn $name() -> &'static str {
140                include_str!(concat!("../modules/", $key, ".mq"))
141            }
142            map.insert(SmolStr::new($key), $name as fn() -> &'static str);
143        };
144    }
145
146    std_module!(cbor);
147    std_module!(csv);
148    std_module!(fuzzy);
149    std_module!(gron);
150    std_module!(html);
151    std_module!(json);
152    std_module!(md);
153    std_module!(section);
154    std_module!(semver);
155    std_module!(test);
156    std_module!(table);
157    std_module!(toml);
158    std_module!(toon);
159    std_module!(xml);
160    std_module!(yaml);
161
162    map
163});
164
165/// Source of the builtin module.
166pub const BUILTIN_FILE: &str = include_str!("../builtin.mq");
167
168impl<T: ModuleResolver> ModuleLoader<T> {
169    /// Creates a loader that resolves modules with `resolver`.
170    pub fn new(resolver: T) -> Self {
171        let mut loaded_modules = FxHashSet::default();
172        loaded_modules.insert(Module::TOP_LEVEL_MODULE_ID);
173        let mut module_names = Arena::new(10);
174        module_names.alloc(Module::TOP_LEVEL_MODULE.into());
175
176        Self {
177            loaded_modules,
178            module_names: Shared::new(SharedCell::new(module_names)),
179            #[cfg(feature = "debugger")]
180            source_code: None,
181            source_cache: FxHashMap::default(),
182            #[cfg(feature = "mqc")]
183            precompiled_sources: FxHashMap::default(),
184            #[cfg(feature = "mqc")]
185            precompiled_ids: FxHashMap::default(),
186            builtin_module_cache: None,
187            module_ast_cache: FxHashMap::default(),
188            resolver,
189            #[cfg(feature = "http-import")]
190            http_depth: 0,
191        }
192    }
193
194    pub(crate) fn with_same_resolver(&self) -> Self {
195        // Built directly: `new` would allocate a module-name arena only to replace it.
196        let mut loaded_modules = FxHashSet::default();
197        loaded_modules.insert(Module::TOP_LEVEL_MODULE_ID);
198        Self {
199            loaded_modules,
200            module_names: Shared::clone(&self.module_names),
201            #[cfg(feature = "debugger")]
202            source_code: None,
203            source_cache: FxHashMap::default(),
204            #[cfg(feature = "mqc")]
205            precompiled_sources: FxHashMap::default(),
206            #[cfg(feature = "mqc")]
207            precompiled_ids: FxHashMap::default(),
208            builtin_module_cache: self.builtin_module_cache.clone(),
209            module_ast_cache: FxHashMap::default(),
210            resolver: self.resolver.clone(),
211            #[cfg(feature = "http-import")]
212            http_depth: 0,
213        }
214    }
215
216    /// Returns the id of `name`, registering it first if it has none yet.
217    fn module_id_of(&self, name: &str) -> ModuleId {
218        #[cfg(not(feature = "sync"))]
219        let mut names = self.module_names.borrow_mut();
220        #[cfg(feature = "sync")]
221        let mut names = self.module_names.write().unwrap();
222
223        let position = names.iter().position(|n| n == name);
224        match position {
225            Some(id) => id.into(),
226            None => names.alloc(SmolStr::new(name)),
227        }
228    }
229
230    /// Returns the id `name` has, or would get if registered now.
231    fn peek_module_id_of(&self, name: &str) -> ModuleId {
232        #[cfg(not(feature = "sync"))]
233        let names = self.module_names.borrow();
234        #[cfg(feature = "sync")]
235        let names = self.module_names.read().unwrap();
236
237        names.iter().position(|n| n == name).unwrap_or(names.len()).into()
238    }
239
240    fn is_loaded(&self, key: &str) -> bool {
241        self.loaded_modules.contains(&self.peek_module_id_of(key))
242    }
243
244    /// Returns the display name of a module, which is also its default import alias.
245    #[cold]
246    pub fn module_name(&self, module_id: ModuleId) -> Cow<'static, str> {
247        match self.module_key(module_id) {
248            Cow::Owned(key) => Cow::Owned(self.resolver.canonical_name(&key).to_string()),
249            name => name,
250        }
251    }
252
253    /// Returns the specifier a module was loaded by, which identifies it within this loader.
254    #[cold]
255    fn module_key(&self, module_id: ModuleId) -> Cow<'static, str> {
256        match module_id {
257            Module::TOP_LEVEL_MODULE_ID => Cow::Borrowed(Module::TOP_LEVEL_MODULE),
258            _ => {
259                #[cfg(not(feature = "sync"))]
260                let names = self.module_names.borrow();
261                #[cfg(feature = "sync")]
262                let names = self.module_names.read().unwrap();
263
264                names
265                    .get(module_id)
266                    .map(|s| Cow::Owned(s.strip_prefix(PRECOMPILED_NAME_PREFIX).unwrap_or(s).to_string()))
267                    .unwrap_or_else(|| Cow::Borrowed("<unknown>"))
268            }
269        }
270    }
271
272    /// Resolves `module_name` to the path it would be loaded from.
273    pub fn get_module_path(&self, module_name: &str) -> Result<String, ModuleError> {
274        self.resolver.get_path(module_name)
275    }
276
277    /// Resolves the module `module_id` to the path it was loaded from.
278    pub fn module_path(&self, module_id: ModuleId) -> Result<String, ModuleError> {
279        self.resolver.get_path(&self.module_key(module_id))
280    }
281
282    /// Sets the top-level source returned for debugging.
283    #[cfg(feature = "debugger")]
284    pub fn set_source_code(&mut self, source_code: String) {
285        self.source_code = Some(source_code);
286    }
287
288    /// The resolver search paths.
289    pub fn search_paths(&self) -> Vec<PathBuf> {
290        self.resolver.search_paths()
291    }
292
293    /// Replaces the resolver search paths.
294    pub fn set_search_paths(&mut self, paths: Vec<PathBuf>) {
295        self.resolver.set_search_paths(paths);
296    }
297
298    /// Parses `code` and registers it as module `module_name`.
299    pub fn load(&mut self, module_name: &str, code: &str, token_arena: TokenArena) -> Result<Module, ModuleError> {
300        self.load_keyed(module_name, module_name, code, token_arena)
301    }
302
303    /// Loads `code` as the module identified by `key`, named `module_name`.
304    fn load_keyed(
305        &mut self,
306        key: &str,
307        module_name: &str,
308        code: &str,
309        token_arena: TokenArena,
310    ) -> Result<Module, ModuleError> {
311        if self.is_loaded(key) {
312            return Err(ModuleError::AlreadyLoaded(Cow::Owned(key.to_string())));
313        }
314
315        // Registered before parsing so an error inside this module can still name its file.
316        let module_id = self.module_id_of(key);
317        let program = Self::parse_program(code, module_id, token_arena)?;
318
319        self.register_loaded(module_id, module_name, &program)
320    }
321
322    /// Registers an already parsed program as module `module_name`.
323    pub fn load_from_ast(&mut self, module_name: &str, program: &mut Program) -> Result<Module, ModuleError> {
324        if self.is_loaded(module_name) {
325            return Err(ModuleError::AlreadyLoaded(Cow::Owned(module_name.to_string())));
326        }
327        let module_id = self.module_id_of(module_name);
328        self.register_loaded(module_id, module_name, program)
329    }
330
331    fn register_loaded(
332        &mut self,
333        module_id: ModuleId,
334        module_name: &str,
335        program: &[Shared<Node>],
336    ) -> Result<Module, ModuleError> {
337        let module = Self::classify_module(module_name, program)?;
338        self.loaded_modules.insert(module_id);
339        self.module_ast_cache.insert(module_id, module.clone());
340        Ok(module)
341    }
342
343    fn classify_module(module_name: &str, program: &[Shared<Node>]) -> Result<Module, ModuleError> {
344        let modules = program
345            .iter()
346            .filter(|node| {
347                matches!(
348                    &node.expr,
349                    ast::Expr::Include(_) | ast::Expr::Module(_, _) | ast::Expr::Import(_, _)
350                )
351            })
352            .cloned()
353            .collect::<Program>();
354
355        let functions = program
356            .iter()
357            .filter(|node| matches!(&node.expr, ast::Expr::Def(..)))
358            .cloned()
359            .collect::<Program>();
360
361        let vars = program
362            .iter()
363            .filter(|node| matches!(&node.expr, ast::Expr::Let(..)))
364            .cloned()
365            .collect::<Program>();
366
367        let expected_len = functions.len() + modules.len() + vars.len();
368
369        if program.len() != expected_len {
370            return Err(ModuleError::InvalidModule);
371        }
372
373        Ok(Module {
374            name: module_name.to_string(),
375            functions,
376            modules,
377            vars,
378        })
379    }
380
381    pub(crate) fn reload_cached(&mut self, module_path: &str, token_arena: TokenArena) -> Result<Module, ModuleError> {
382        // Already parsed by this same loader (e.g. a prelude pre-pass ran ahead of the real
383        // compile): reuse that AST instead of reparsing the cached source from scratch.
384        let module_id = self.peek_module_id_of(module_path);
385        if let Some(module) = self.module_ast_cache.get(&module_id) {
386            return Ok(module.clone());
387        }
388        let code = self
389            .source_cache
390            .get(&module_id)
391            .cloned()
392            .ok_or_else(|| ModuleError::NotFound(Cow::Owned(module_path.to_string())))?;
393        let program = Self::parse_program(&code, module_id, token_arena)?;
394        self.register_loaded(module_id, self.resolver.canonical_name(module_path), &program)
395    }
396
397    /// The short name a module path is registered under.
398    pub fn canonical_name<'a>(&self, module_path: &'a str) -> &'a str {
399        self.resolver.canonical_name(module_path)
400    }
401
402    /// Resolves, parses and registers the module at `module_path`.
403    pub fn load_from_file(&mut self, module_path: &str, token_arena: TokenArena) -> Result<Module, ModuleError> {
404        // Check before resolving to avoid unnecessary I/O (disk read or network fetch)
405        // when the same module is imported more than once. Modules are keyed by the full
406        // specifier: remote modules sharing a short name are still different modules.
407        if self.is_loaded(module_path) {
408            return Err(ModuleError::AlreadyLoaded(Cow::Owned(module_path.to_string())));
409        }
410        let program = self.resolve(module_path)?;
411        let module_id = self.module_id_of(module_path);
412        self.source_cache.insert(module_id, program.clone());
413        let name = self.resolver.canonical_name(module_path).to_owned();
414        self.load_keyed(module_path, &name, &program, token_arena)
415    }
416
417    /// Returns every file module this loader resolved, sorted by specifier.
418    #[cfg(feature = "mqc")]
419    pub(crate) fn resolved_modules(&self) -> Vec<ResolvedModule<'_>> {
420        let mut modules: Vec<_> = self
421            .source_cache
422            .iter()
423            .map(|(id, source)| {
424                let specifier = self.module_key(*id).into_owned();
425                ResolvedModule {
426                    name: self.resolver.canonical_name(&specifier).to_string(),
427                    specifier,
428                    source,
429                }
430            })
431            .collect();
432        modules.sort_unstable_by(|a, b| a.specifier.cmp(&b.specifier));
433        modules
434    }
435
436    /// Registers a module's source for diagnostics without loading it.
437    #[cfg(feature = "mqc")]
438    pub(crate) fn register_module_source(&mut self, name: &str, source: String) -> ModuleId {
439        match name {
440            Module::TOP_LEVEL_MODULE => Module::TOP_LEVEL_MODULE_ID,
441            Module::BUILTIN_MODULE => self.module_id_of(name),
442            _ => {
443                // Each distinct source gets its own id, so programs loaded earlier keep
444                // their own text. The prefix keeps name lookups from ever resolving to it.
445                let key = SmolStr::new(format!("{PRECOMPILED_NAME_PREFIX}{name}"));
446                let source: Shared<str> = Shared::from(source);
447                if let Some(id) = self.precompiled_ids.get(&(key.clone(), Shared::clone(&source))) {
448                    return *id;
449                }
450                #[cfg(not(feature = "sync"))]
451                let id = self.module_names.borrow_mut().alloc(key.clone());
452                #[cfg(feature = "sync")]
453                let id = self.module_names.write().unwrap().alloc(key.clone());
454                self.precompiled_sources.insert(id, Shared::clone(&source));
455                self.precompiled_ids.insert((key, source), id);
456                id
457            }
458        }
459    }
460
461    /// Returns the source code of `module_name` from the resolver.
462    pub fn resolve(&self, module_name: &str) -> Result<String, ModuleError> {
463        #[cfg(feature = "http-import")]
464        if self.http_depth > 0
465            && (resolver::http_import::is_remote_url(module_name) || resolver::http_import::is_github_url(module_name))
466        {
467            return Err(ModuleError::HttpImportNotAllowed(std::borrow::Cow::Owned(
468                module_name.to_string(),
469            )));
470        }
471        self.resolver.resolve(module_name)
472    }
473
474    /// Signals that sub-module loading has begun; HTTP imports are blocked while depth > 0.
475    #[cfg(feature = "http-import")]
476    pub fn push_http_boundary(&mut self) {
477        self.http_depth = self.http_depth.saturating_add(1);
478    }
479
480    /// Signals that sub-module loading has ended.
481    #[cfg(feature = "http-import")]
482    pub fn pop_http_boundary(&mut self) {
483        self.http_depth = self.http_depth.saturating_sub(1);
484    }
485
486    pub(crate) fn load_builtin(&mut self, token_arena: TokenArena) -> Result<Module, ModuleError> {
487        // The builtin module outlives any one query, so its tokens stay in the engine's arena.
488        let token_arena = root_token_arena(&token_arena);
489        if self.is_loaded(Module::BUILTIN_MODULE) {
490            return Err(ModuleError::AlreadyLoaded(Cow::Borrowed(Module::BUILTIN_MODULE)));
491        }
492
493        if let Some((cached_arena, module)) = &self.builtin_module_cache
494            && Shared::ptr_eq(cached_arena, &token_arena)
495        {
496            let module_id = self.module_id_of(Module::BUILTIN_MODULE);
497            self.loaded_modules.insert(module_id);
498            return Ok(Module::clone(module));
499        }
500
501        // Cache is only valid when both arenas are in their initial state (builtin
502        // module_id == 1, tokens right after the dummy EOF) and the arena's only token is the
503        // cache's first token. Fall back to full parse otherwise.
504        let builtin_id_is_one = self.peek_module_id_of(Module::BUILTIN_MODULE) == 1.into();
505        let pristine = self.loaded_modules.len() == 1 && builtin_id_is_one && {
506            #[cfg(not(feature = "sync"))]
507            {
508                token_arena.borrow().len() == 1
509            }
510            #[cfg(feature = "sync")]
511            {
512                token_arena.read().unwrap().len() == 1
513            }
514        };
515
516        if pristine {
517            let cached = BUILTIN_CACHE.with(|cache| {
518                cache
519                    .borrow()
520                    .as_ref()
521                    .map(|cache| (Shared::clone(&cache.tokens), cache.module.clone()))
522            });
523
524            let cached = cached.filter(|(tokens, _)| {
525                #[cfg(not(feature = "sync"))]
526                let arena = token_arena.borrow();
527                #[cfg(feature = "sync")]
528                let arena = token_arena.read().unwrap();
529                arena.iter().eq(tokens.first())
530            });
531
532            if let Some((tokens, module)) = cached {
533                {
534                    #[cfg(not(feature = "sync"))]
535                    let mut arena = token_arena.borrow_mut();
536                    #[cfg(feature = "sync")]
537                    let mut arena = token_arena.write().unwrap();
538                    *arena = Arena::with_base(Shared::clone(&tokens));
539                }
540                let module_id = self.module_id_of(Module::BUILTIN_MODULE);
541                self.loaded_modules.insert(module_id);
542                self.builtin_module_cache = Some((token_arena, Shared::new(module.clone())));
543                return Ok(module);
544            }
545        }
546
547        let module = self.load(Module::BUILTIN_MODULE, BUILTIN_FILE, Shared::clone(&token_arena))?;
548        self.builtin_module_cache = Some((Shared::clone(&token_arena), Shared::new(module.clone())));
549
550        if pristine {
551            let tokens = {
552                #[cfg(not(feature = "sync"))]
553                let arena = token_arena.borrow();
554                #[cfg(feature = "sync")]
555                let arena = token_arena.read().unwrap();
556                Shared::new(arena.to_vec())
557            };
558
559            BUILTIN_CACHE.with(|cache| {
560                *cache.borrow_mut() = Some(BuiltinCache {
561                    tokens,
562                    module: module.clone(),
563                });
564            });
565        }
566
567        Ok(module)
568    }
569
570    /// Source code of the module, using the stored top-level source for the top-level module.
571    #[cfg(feature = "debugger")]
572    pub fn get_source_code_for_debug(&self, module_id: ModuleId) -> Result<String, ModuleError> {
573        #[cfg(feature = "mqc")]
574        if let Some(source) = self.precompiled_sources.get(&module_id) {
575            return Ok(source.to_string());
576        }
577        let name = self.module_key(module_id);
578        match name.as_ref() {
579            Module::TOP_LEVEL_MODULE => Ok(self.source_code.clone().unwrap_or_default()),
580            Module::BUILTIN_MODULE => Ok(BUILTIN_FILE.to_string()),
581            module_name => {
582                if let Some(cached) = self.source_cache.get(&module_id) {
583                    return Ok(cached.clone());
584                }
585                self.resolve(module_name)
586            }
587        }
588    }
589
590    /// Source code of the module, using `source_code` for the top-level module.
591    #[cold]
592    pub fn get_source_code(&self, module_id: ModuleId, source_code: String) -> Result<String, ModuleError> {
593        #[cfg(feature = "mqc")]
594        if let Some(source) = self.precompiled_sources.get(&module_id) {
595            return Ok(source.to_string());
596        }
597        let name = self.module_key(module_id);
598        match name.as_ref() {
599            Module::TOP_LEVEL_MODULE => Ok(source_code),
600            Module::BUILTIN_MODULE => Ok(BUILTIN_FILE.to_string()),
601            module_name => {
602                if let Some(cached) = self.source_cache.get(&module_id) {
603                    return Ok(cached.clone());
604                }
605                self.resolve(module_name)
606            }
607        }
608    }
609
610    /// Returns the display filename for a module (e.g. `"builtin.mq"`, `"csv.mq"`, `""` for top-level).
611    #[cold]
612    pub fn module_file_name(&self, module_id: ModuleId) -> String {
613        let name = self.module_name(module_id);
614        match name.as_ref() {
615            Module::TOP_LEVEL_MODULE => String::new(),
616            other => get_module_name(other).to_string(),
617        }
618    }
619
620    fn parse_program(code: &str, module_id: ModuleId, token_arena: TokenArena) -> Result<Program, ModuleError> {
621        let tokens = Lexer::new(lexer::Options::default()).tokenize(code, module_id)?;
622        let mut token_arena = {
623            #[cfg(not(feature = "sync"))]
624            {
625                token_arena.borrow_mut()
626            }
627
628            #[cfg(feature = "sync")]
629            {
630                token_arena.write().unwrap()
631            }
632        };
633
634        let program = Parser::new(tokens.iter(), &mut token_arena, module_id).parse()?;
635
636        Ok(program)
637    }
638}
639
640#[cfg(feature = "http-import-ureq")]
641impl ModuleLoader<DefaultModuleResolver> {
642    /// Replaces the HTTP resolver's domain allowlist.
643    pub fn set_http_allowed_domains(&mut self, domains: Vec<String>) {
644        self.resolver.set_allowed_domains(domains);
645    }
646
647    /// Enables or disables HTTP module imports outright, independent of the domain allowlist.
648    pub fn set_http_import_enabled(&mut self, enabled: bool) {
649        self.resolver.set_http_import_enabled(enabled);
650    }
651
652    /// Clears all locally-cached HTTP module files.
653    ///
654    /// Call this once before processing to force a re-fetch of all cached modules.
655    pub fn clear_http_cache(&self) -> Result<(), error::ModuleError> {
656        self.resolver.clear_http_cache()
657    }
658
659    /// Clears all HTTP module cache including versioned modules and lock files.
660    pub fn clear_http_cache_all(&self) -> Result<(), error::ModuleError> {
661        self.resolver.clear_http_cache_all()
662    }
663
664    /// Enables or disables the `mq.lock` integrity check/update for HTTP imports.
665    pub fn set_lockfile_enabled(&mut self, enabled: bool) {
666        self.resolver.set_lockfile_enabled(enabled);
667    }
668
669    /// When `true`, a URL with no existing `mq.lock` entry is a hard error instead of being
670    /// recorded as a new entry.
671    pub fn set_lockfile_frozen(&mut self, frozen: bool) {
672        self.resolver.set_lockfile_frozen(frozen);
673    }
674
675    /// Sets the path used for `mq.lock`.
676    pub fn set_lockfile_path(&mut self, path: std::path::PathBuf) {
677        self.resolver.set_lockfile_path(path);
678    }
679}
680
681#[cfg(test)]
682mod tests {
683    use crate::{
684        Range, Shared, SharedCell, Token, TokenKind,
685        ast::node::{self as ast, IdentWithToken, Param},
686        module::resolver::DefaultModuleResolver,
687        token_alloc,
688    };
689    use rstest::{fixture, rstest};
690    use smallvec::smallvec;
691    use thin_vec::{ThinVec, thin_vec};
692
693    use super::{Module, ModuleError, ModuleLoader};
694
695    #[fixture]
696    fn token_arena() -> Shared<SharedCell<crate::arena::Arena<Token>>> {
697        Shared::new(SharedCell::new(crate::arena::Arena::new(10)))
698    }
699
700    /// Arena that mirrors the engine's initial state: one dummy EOF token at index 0.
701    /// Required to exercise the "pristine" cache path in `load_builtin`.
702    #[fixture]
703    fn pristine_token_arena() -> Shared<SharedCell<crate::arena::Arena<Token>>> {
704        let arena = Shared::new(SharedCell::new(crate::arena::Arena::new(2048)));
705        token_alloc(
706            &arena,
707            Token {
708                kind: TokenKind::Eof,
709                range: Range::default(),
710                module_id: Module::TOP_LEVEL_MODULE_ID,
711            },
712        );
713        arena
714    }
715
716    #[rstest]
717    #[case::load1("test".to_string(), Err(ModuleError::InvalidModule))]
718    #[case::load2("let test = \"value\"".to_string(), Ok(Module{
719        name: "test".to_string(),
720        functions: ThinVec::new(),
721        modules: ThinVec::new(),
722        vars: thin_vec![
723            Shared::new(ast::Node{token_id: 0.into(), expr: ast::Expr::Let(
724                ast::Pattern::Ident(IdentWithToken::new_with_token("test", Some(1.into()))),
725                Shared::new(ast::Node{token_id: 3.into(), expr: ast::Expr::Literal(ast::Literal::String("value".into()))})
726            )})],
727    }))]
728    #[case::load3("def test(): 1;".to_string(), Ok(Module{
729        name: "test".to_string(),
730        modules: ThinVec::new(),
731        functions: thin_vec![
732            Shared::new(ast::Node{token_id: 0.into(), expr: ast::Expr::Def(
733            IdentWithToken::new_with_token("test", Some(3.into())),
734            ThinVec::new(),
735            thin_vec![
736                Shared::new(ast::Node{token_id: 2.into(), expr: ast::Expr::Literal(ast::Literal::Number(1.into()))})
737            ]
738            )})],
739        vars: ThinVec::new(),
740    }))]
741    #[case::load4("def test(a, b): add(a, b);".to_string(), Ok(Module{
742        name: "test".to_string(),
743        modules: ThinVec::new(),
744        functions: thin_vec![
745            Shared::new(ast::Node{token_id: 0.into(), expr: ast::Expr::Def(
746                IdentWithToken::new_with_token("test", Some(7.into())),
747                thin_vec![
748                    Param::new(IdentWithToken::new_with_token("a", Some(1.into()))),
749                    Param::new(IdentWithToken::new_with_token("b", Some(2.into()))),
750                ],
751                thin_vec![
752                    Shared::new(ast::Node{token_id: 6.into(), expr: ast::Expr::Call(
753                    IdentWithToken::new_with_token("add", Some(6.into())),
754                    smallvec![
755                        Shared::new(ast::Node{token_id: 4.into(),
756                            expr:
757                                ast::Expr::Ident(IdentWithToken::new_with_token("a", Some(4.into())))
758                                }),
759                        Shared::new(ast::Node{token_id: 5.into(),
760                            expr:
761                                ast::Expr::Ident(IdentWithToken::new_with_token("b", Some(5.into())))
762                            })
763                    ],
764                )})]
765            )})],
766        vars: ThinVec::new(),
767    }))]
768    fn test_load(
769        token_arena: Shared<SharedCell<crate::arena::Arena<Token>>>,
770        #[case] program: String,
771        #[case] expected: Result<Module, ModuleError>,
772    ) {
773        assert_eq!(
774            ModuleLoader::new(DefaultModuleResolver::default()).load("test", &program, token_arena),
775            expected
776        );
777    }
778
779    #[rstest]
780    #[case::load_standard_csv("csv", Ok(Module {
781        name: "csv".to_string(),
782        functions: ThinVec::new(),
783        modules: ThinVec::new(), // Assuming the csv.mq only contains definitions or is empty for this test
784        vars: ThinVec::new(),
785    }))]
786    fn test_load_standard_module(
787        token_arena: Shared<SharedCell<crate::arena::Arena<Token>>>,
788        #[case] module_name: &str,
789        #[case] expected: Result<Module, ModuleError>,
790    ) {
791        let mut loader = ModuleLoader::new(DefaultModuleResolver::default());
792        let result = loader.load_from_file(module_name, token_arena.clone());
793        // Only check that loading does not return NotFound error and returns Some(Module)
794        match expected {
795            Ok(_) => {
796                assert!(result.is_ok(), "Expected Ok, got {:?}", result);
797                assert_eq!(result.unwrap().name, module_name);
798            }
799            Err(ref e) => {
800                assert_eq!(result.unwrap_err(), *e);
801            }
802        }
803    }
804
805    #[test]
806    fn test_standard_modules_contains_csv() {
807        assert!(super::STANDARD_MODULES.contains_key("csv"));
808        let csv_content = super::STANDARD_MODULES.get("csv").unwrap()();
809        assert!(csv_content.contains("")); // Just check it's a string, optionally check for expected content
810    }
811
812    #[test]
813    fn test_standard_modules_contains_md() {
814        assert!(super::STANDARD_MODULES.contains_key("md"));
815        let md_content = super::STANDARD_MODULES.get("md").unwrap()();
816        assert!(md_content.contains("def doc("));
817    }
818
819    #[test]
820    fn test_load_builtin_idempotent() {
821        let token_arena = token_arena();
822        let mut loader = ModuleLoader::new(DefaultModuleResolver::default());
823        assert!(loader.load_builtin(Shared::clone(&token_arena)).is_ok());
824        // Second call on the same loader must return AlreadyLoaded, not corrupt state.
825        assert!(matches!(
826            loader.load_builtin(Shared::clone(&token_arena)),
827            Err(ModuleError::AlreadyLoaded(_))
828        ));
829    }
830
831    #[test]
832    fn test_load_builtin_reuses_ast_for_the_same_token_arena() {
833        let token_arena = token_arena();
834        let mut loader = ModuleLoader::new(DefaultModuleResolver::default());
835        let original = loader.load_builtin(Shared::clone(&token_arena)).unwrap();
836        #[cfg(not(feature = "sync"))]
837        let token_count = token_arena.borrow().len();
838        #[cfg(feature = "sync")]
839        let token_count = token_arena.read().unwrap().len();
840
841        let mut reused_loader = loader.with_same_resolver();
842        let reused = reused_loader.load_builtin(Shared::clone(&token_arena)).unwrap();
843
844        #[cfg(not(feature = "sync"))]
845        assert_eq!(token_arena.borrow().len(), token_count);
846        #[cfg(feature = "sync")]
847        assert_eq!(token_arena.read().unwrap().len(), token_count);
848        assert_eq!(reused, original);
849    }
850
851    #[test]
852    fn test_load_builtin_non_pristine_falls_back_to_parse() {
853        // Load another module first so the arenas are no longer in their initial state.
854        let token_arena = token_arena();
855        let mut loader = ModuleLoader::new(DefaultModuleResolver::default());
856        loader
857            .load("other", "def dummy(): 1;", Shared::clone(&token_arena))
858            .expect("should load other module");
859
860        // load_builtin must still succeed even though the arenas are non-pristine.
861        let result = loader.load_builtin(Shared::clone(&token_arena));
862        assert!(result.is_ok(), "load_builtin failed on non-pristine state: {result:?}");
863
864        let module = result.unwrap();
865        assert_eq!(module.name, Module::BUILTIN_MODULE);
866    }
867
868    /// Token arena size must be the same whether the builtin module was loaded from a fresh
869    /// parse or replayed from the thread-local cache.
870    #[rstest]
871    fn test_load_builtin_cache_arena_size_consistent(
872        pristine_token_arena: Shared<SharedCell<crate::arena::Arena<Token>>>,
873    ) {
874        let arena1 = pristine_token_arena;
875        let mut loader1 = ModuleLoader::new(DefaultModuleResolver::default());
876        loader1.load_builtin(Shared::clone(&arena1)).unwrap();
877        #[cfg(not(feature = "sync"))]
878        let size1 = arena1.borrow().len();
879        #[cfg(feature = "sync")]
880        let size1 = arena1.read().unwrap().len();
881
882        let arena2 = Shared::new(SharedCell::new(crate::arena::Arena::new(2048)));
883        token_alloc(
884            &arena2,
885            Token {
886                kind: TokenKind::Eof,
887                range: Range::default(),
888                module_id: Module::TOP_LEVEL_MODULE_ID,
889            },
890        );
891        let mut loader2 = ModuleLoader::new(DefaultModuleResolver::default());
892        loader2.load_builtin(Shared::clone(&arena2)).unwrap();
893        #[cfg(not(feature = "sync"))]
894        let size2 = arena2.borrow().len();
895        #[cfg(feature = "sync")]
896        let size2 = arena2.read().unwrap().len();
897
898        assert_eq!(size1, size2, "arena size must match between cache and fresh parse");
899        assert!(size1 > 1, "builtin tokens must be added to the arena");
900    }
901
902    /// An arena whose only token differs from the cached first token must keep that token.
903    #[rstest]
904    fn test_load_builtin_cache_skipped_when_first_token_differs(
905        pristine_token_arena: Shared<SharedCell<crate::arena::Arena<Token>>>,
906    ) {
907        let mut loader1 = ModuleLoader::new(DefaultModuleResolver::default());
908        loader1.load_builtin(pristine_token_arena).unwrap();
909
910        let custom = Token {
911            kind: TokenKind::Eof,
912            range: Range {
913                start: crate::Position { line: 7, column: 3 },
914                end: crate::Position { line: 7, column: 3 },
915            },
916            module_id: Module::TOP_LEVEL_MODULE_ID,
917        };
918        let arena = Shared::new(SharedCell::new(crate::arena::Arena::new(2048)));
919        token_alloc(&arena, custom.clone());
920        let mut loader2 = ModuleLoader::new(DefaultModuleResolver::default());
921        loader2.load_builtin(Shared::clone(&arena)).unwrap();
922
923        #[cfg(not(feature = "sync"))]
924        let arena = arena.borrow();
925        #[cfg(feature = "sync")]
926        let arena = arena.read().unwrap();
927        assert_eq!(arena.iter().next(), Some(&custom));
928        assert!(arena.len() > 1, "builtin tokens must be added to the arena");
929    }
930
931    /// The module returned from cache must have the same function/var counts as a fresh parse.
932    #[rstest]
933    fn test_load_builtin_cache_module_counts_consistent(
934        pristine_token_arena: Shared<SharedCell<crate::arena::Arena<Token>>>,
935    ) {
936        let mut loader1 = ModuleLoader::new(DefaultModuleResolver::default());
937        let module1 = loader1.load_builtin(pristine_token_arena).unwrap();
938
939        let arena2 = Shared::new(SharedCell::new(crate::arena::Arena::new(2048)));
940        token_alloc(
941            &arena2,
942            Token {
943                kind: TokenKind::Eof,
944                range: Range::default(),
945                module_id: Module::TOP_LEVEL_MODULE_ID,
946            },
947        );
948        let mut loader2 = ModuleLoader::new(DefaultModuleResolver::default());
949        let module2 = loader2.load_builtin(arena2).unwrap();
950
951        assert_eq!(module1.name, module2.name);
952        assert_eq!(module1.functions.len(), module2.functions.len());
953        assert_eq!(module1.vars.len(), module2.vars.len());
954        assert_eq!(module1.modules.len(), module2.modules.len());
955    }
956
957    #[rstest]
958    fn test_module_ids_are_shared_with_derived_loaders(
959        pristine_token_arena: Shared<SharedCell<crate::arena::Arena<Token>>>,
960    ) {
961        let parent = ModuleLoader::new(DefaultModuleResolver::default());
962        let mut first = parent.with_same_resolver();
963        let mut second = parent.with_same_resolver();
964
965        // Loaded in a different order in each derived loader.
966        first
967            .load("a", "def f(): 1;", Shared::clone(&pristine_token_arena))
968            .unwrap();
969        first
970            .load("b", "def f(): 1;", Shared::clone(&pristine_token_arena))
971            .unwrap();
972        second
973            .load("b", "def f(): 1;", Shared::clone(&pristine_token_arena))
974            .unwrap();
975        second
976            .load("a", "def f(): 1;", Shared::clone(&pristine_token_arena))
977            .unwrap();
978
979        let a = first.module_id_of("a");
980        let b = first.module_id_of("b");
981        assert_ne!(a, b);
982        assert_eq!(second.module_id_of("a"), a);
983        assert_eq!(second.module_id_of("b"), b);
984        assert_eq!(parent.module_name(a), "a");
985        assert_eq!(parent.module_name(b), "b");
986    }
987
988    #[rstest]
989    fn test_failed_load_still_registers_module_name(
990        pristine_token_arena: Shared<SharedCell<crate::arena::Arena<Token>>>,
991    ) {
992        let parent = ModuleLoader::new(DefaultModuleResolver::default());
993        let mut child = parent.with_same_resolver();
994
995        assert!(child.load("broken", "def f(:", pristine_token_arena).is_err());
996
997        let id = child.peek_module_id_of("broken");
998        assert_eq!(parent.module_name(id), "broken");
999        assert_eq!(parent.module_file_name(id), "broken.mq");
1000    }
1001
1002    /// After load_builtin, the builtin module must be registered at loaded_modules index 1
1003    /// (TOP_LEVEL_MODULE is always 0).
1004    #[rstest]
1005    fn test_load_builtin_module_registered_at_id_one(
1006        pristine_token_arena: Shared<SharedCell<crate::arena::Arena<Token>>>,
1007    ) {
1008        let mut loader = ModuleLoader::new(DefaultModuleResolver::default());
1009        loader.load_builtin(pristine_token_arena).unwrap();
1010
1011        assert_eq!(loader.loaded_modules.len(), 2);
1012        assert!(loader.is_loaded(Module::BUILTIN_MODULE));
1013    }
1014
1015    /// All tokens injected from cache must carry module_id == 1 (BUILTIN_MODULE_ID),
1016    /// so that error diagnostics resolve to the builtin source file rather than garbage.
1017    #[rstest]
1018    fn test_load_builtin_cache_tokens_have_builtin_module_id(
1019        pristine_token_arena: Shared<SharedCell<crate::arena::Arena<Token>>>,
1020    ) {
1021        let mut loader1 = ModuleLoader::new(DefaultModuleResolver::default());
1022        loader1.load_builtin(pristine_token_arena).unwrap();
1023
1024        // Second pristine load: this is the cache-hit path.
1025        let arena2 = Shared::new(SharedCell::new(crate::arena::Arena::new(2048)));
1026        token_alloc(
1027            &arena2,
1028            Token {
1029                kind: TokenKind::Eof,
1030                range: Range::default(),
1031                module_id: Module::TOP_LEVEL_MODULE_ID,
1032            },
1033        );
1034        let mut loader2 = ModuleLoader::new(DefaultModuleResolver::default());
1035        loader2.load_builtin(Shared::clone(&arena2)).unwrap();
1036
1037        let builtin_module_id: crate::ModuleId = 1.into();
1038        #[cfg(not(feature = "sync"))]
1039        let arena = arena2.borrow();
1040        #[cfg(feature = "sync")]
1041        let arena = arena2.read().unwrap();
1042        for token in arena.iter().skip(1) {
1043            assert_eq!(
1044                token.module_id, builtin_module_id,
1045                "cached builtin token must have BUILTIN_MODULE_ID"
1046            );
1047        }
1048    }
1049
1050    #[cfg(feature = "http-import")]
1051    #[rstest]
1052    #[case("https://example.com/foo.mq")]
1053    #[case("http://example.com/foo.mq")]
1054    #[case("github.com/alice/mymod")]
1055    fn test_resolve_http_blocked_inside_module(#[case] url: &str) {
1056        let mut loader = ModuleLoader::new(DefaultModuleResolver::new(vec![]));
1057        loader.push_http_boundary();
1058        assert!(matches!(loader.resolve(url), Err(ModuleError::HttpImportNotAllowed(_))));
1059    }
1060
1061    #[cfg(feature = "http-import")]
1062    #[rstest]
1063    #[case("csv")]
1064    #[case("local_module")]
1065    fn test_resolve_non_http_not_blocked_inside_module(#[case] name: &str) {
1066        let mut loader = ModuleLoader::new(DefaultModuleResolver::new(vec![]));
1067        loader.push_http_boundary();
1068        assert!(!matches!(
1069            loader.resolve(name),
1070            Err(ModuleError::HttpImportNotAllowed(_))
1071        ));
1072    }
1073
1074    #[cfg(feature = "http-import")]
1075    #[rstest]
1076    #[case("https://example.com/foo.mq")]
1077    #[case("github.com/alice/mod")]
1078    fn test_pop_http_boundary_restores_access(#[case] url: &str) {
1079        let mut loader = ModuleLoader::new(DefaultModuleResolver::new(vec![]));
1080        loader.push_http_boundary();
1081        assert!(matches!(loader.resolve(url), Err(ModuleError::HttpImportNotAllowed(_))));
1082        loader.pop_http_boundary();
1083        assert!(!matches!(
1084            loader.resolve(url),
1085            Err(ModuleError::HttpImportNotAllowed(_))
1086        ));
1087    }
1088
1089    #[cfg(feature = "http-import")]
1090    #[rstest]
1091    #[case("github.com/alice/mod", 2)]
1092    #[case("https://example.com/foo.mq", 3)]
1093    fn test_nested_boundaries_block_until_all_popped(#[case] url: &str, #[case] depth: usize) {
1094        let mut loader = ModuleLoader::new(DefaultModuleResolver::new(vec![]));
1095        for _ in 0..depth {
1096            loader.push_http_boundary();
1097        }
1098        assert!(matches!(loader.resolve(url), Err(ModuleError::HttpImportNotAllowed(_))));
1099        for _ in 0..depth - 1 {
1100            loader.pop_http_boundary();
1101            assert!(matches!(loader.resolve(url), Err(ModuleError::HttpImportNotAllowed(_))));
1102        }
1103        loader.pop_http_boundary();
1104        assert!(!matches!(
1105            loader.resolve(url),
1106            Err(ModuleError::HttpImportNotAllowed(_))
1107        ));
1108    }
1109
1110    #[cfg(feature = "http-import")]
1111    #[rstest]
1112    #[case("https://example.com/foo.mq")]
1113    fn test_pop_at_zero_does_not_underflow(#[case] url: &str) {
1114        let mut loader = ModuleLoader::new(DefaultModuleResolver::new(vec![]));
1115        loader.pop_http_boundary();
1116        assert!(!matches!(
1117            loader.resolve(url),
1118            Err(ModuleError::HttpImportNotAllowed(_))
1119        ));
1120    }
1121}