Repository Public
1//! ORIX Sonata2//! File: crates/sonata-compiler/src/loader.rs3//! Description: The file-backed SourceLoader used by the CLI and the app: project modules are4//! files under one root directory, and nothing outside it can be read.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_semantics::SourceLoader;10use std::collections::BTreeMap;11use std::path::{Path, PathBuf};1213/// Resolves `import a.b` to `<root>/a/b.sonata`.14///15/// Safety rules: every component of the module path is `[A-Za-z0-9_]+`; the resolved file,16/// after following symbolic links, must still be inside the root; files larger than 4 MiB are17/// refused. Overlays (unsaved editor buffers, keyed by module path) take precedence over disk.18#[derive(Clone, Debug, Default)]19pub struct DirLoader {20 root: Option<PathBuf>,21 pub overlays: BTreeMap<String, String>,22}2324impl DirLoader {25 pub fn new(root: impl AsRef<Path>) -> DirLoader {26 DirLoader { root: Some(root.as_ref().to_path_buf()), overlays: BTreeMap::new() }27 }28 /// A loader with overlays only: no file is ever read.29 pub fn overlays_only() -> DirLoader {30 DirLoader::default()31 }32 pub fn with_overlay(mut self, module: &str, text: &str) -> DirLoader {33 self.overlays.insert(module.to_string(), text.to_string());34 self35 }3637 /// The file a module path designates, when it is safe; `None` otherwise.38 pub fn path_of(&self, module: &str) -> Option<PathBuf> {39 let root = self.root.as_ref()?;40 let parts: Vec<&str> = module.split('.').collect();41 if parts.is_empty() || parts.iter().any(|p| p.is_empty() || !p.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')) {42 return None;43 }44 let mut path = root.clone();45 for p in &parts {46 path.push(p);47 }48 path.set_extension("sonata");49 let real = std::fs::canonicalize(&path).ok()?;50 let real_root = std::fs::canonicalize(root).ok()?;51 if real.starts_with(&real_root) {52 Some(real)53 } else {54 None55 }56 }57}5859impl SourceLoader for DirLoader {60 fn load(&self, module: &str) -> Option<String> {61 if let Some(text) = self.overlays.get(module) {62 return Some(text.clone());63 }64 let path = self.path_of(module)?;65 let meta = std::fs::metadata(&path).ok()?;66 if !meta.is_file() || meta.len() > sonata_lexer::MAX_SOURCE_BYTES as u64 {67 return None;68 }69 std::fs::read_to_string(&path).ok()70 }71}72