Skip to main content

pine_core/
library.rs

1//! Resolving `import`ed libraries to their source.
2
3use std::collections::HashMap;
4
5/// Loads the source of a library by its import path.
6pub trait LibraryLoader {
7    fn load_library(&self, path: &str) -> Result<String, String>;
8}
9
10/// A [`LibraryLoader`] backed by an in-memory set of named sources: register a
11/// library's text under a path and `import <path>` resolves against it.
12#[derive(Debug, Default, Clone)]
13pub struct FileResolver {
14    files: HashMap<String, String>,
15}
16
17impl FileResolver {
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    /// Register `source` under `path` in place.
23    pub fn add(&mut self, path: &str, source: &str) {
24        self.files.insert(path.to_string(), source.to_string());
25    }
26
27    /// Register `source` under `path`, returning self for chaining.
28    pub fn with_file(mut self, path: &str, source: &str) -> Self {
29        self.add(path, source);
30        self
31    }
32}
33
34impl LibraryLoader for FileResolver {
35    fn load_library(&self, path: &str) -> Result<String, String> {
36        self.files
37            .get(path)
38            .cloned()
39            .ok_or_else(|| format!("no library registered for '{path}'"))
40    }
41}