Repository Public
1//! ORIX Sonata2//! File: crates/sonata-semantics/src/modules.rs3//! Description: Module loading: the embedded standard library, project imports through a4//! SourceLoader, cycle and depth checks, the language version header.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_ir::{Diagnostic, FileId, LineIndex, Span, LANGUAGE_VERSION};10use sonata_parser::ast::Item;11use sonata_parser::{edit_distance, parse, Parsed};12use std::collections::HashMap;13use std::sync::Arc;1415/// The standard library, written in Sonata and embedded in the compiler.16pub const STD_MODULES: &[(&str, &str)] = &[17 ("std.music", include_str!("../../../StandardLibrary/std/music.sonata")),18 ("std.instruments", include_str!("../../../StandardLibrary/std/instruments.sonata")),19 ("std.effects", include_str!("../../../StandardLibrary/std/effects.sonata")),20];2122/// Modules that are always in scope, whether imported or not.23pub const PRELUDE: &[&str] = &["std.music", "std.instruments", "std.effects"];2425/// Gives the compiler the text of project modules. `module` is the dotted import path26/// (`lib.drums`); the host maps it to a file under the project root (`lib/drums.sonata`).27/// The language itself has no file access: this trait is the only door. Loaders are `Sync`28/// because the compiler runs its analysis on a dedicated thread with a large stack.29pub trait SourceLoader: Sync {30 fn load(&self, module: &str) -> Option<String>;31}3233/// A loader that knows no module (single-file compilation).34pub struct NoLoader;35impl SourceLoader for NoLoader {36 fn load(&self, _module: &str) -> Option<String> {37 None38 }39}4041/// An in-memory loader, for tests and for editors holding unsaved buffers.42#[derive(Default, Clone, Debug)]43pub struct MapLoader {44 pub modules: HashMap<String, String>,45}46impl MapLoader {47 pub fn with(mut self, module: &str, text: &str) -> MapLoader {48 self.modules.insert(module.to_string(), text.to_string());49 self50 }51}52impl SourceLoader for MapLoader {53 fn load(&self, module: &str) -> Option<String> {54 self.modules.get(module).cloned()55 }56}5758/// One loaded source file.59#[derive(Clone, Debug)]60pub struct SourceFile {61 pub id: FileId,62 /// Root file name as given by the caller, or the dotted module path.63 pub name: String,64 pub text: Arc<str>,65 pub parsed: Arc<Parsed>,66 pub is_std: bool,67 pub lines: Arc<LineIndex>,68}6970/// Every file of one compilation. File 0 is the root.71#[derive(Clone, Debug, Default)]72pub struct ModuleSet {73 pub files: Vec<SourceFile>,74 /// Import diagnostics (I7xxx). Lexer and parser diagnostics stay in each file's `parsed`.75 pub diagnostics: Vec<Diagnostic>,76}7778impl ModuleSet {79 pub fn file(&self, id: FileId) -> Option<&SourceFile> {80 self.files.get(id as usize)81 }82 pub fn by_name(&self, name: &str) -> Option<&SourceFile> {83 self.files.iter().find(|f| f.name == name)84 }85}8687/// Parses a file, possibly reusing an earlier result. The key is `(name, id, text)`.88pub type ParseFn<'a> = dyn FnMut(&str, FileId, &str) -> Arc<Parsed> + 'a;8990/// Loads the root source, the prelude and every transitive import.91pub fn load_modules(root_name: &str, source: &str, loader: &dyn SourceLoader, max_depth: u32) -> ModuleSet {92 load_modules_with(root_name, source, loader, max_depth, &mut |_, id, text| Arc::new(parse(text, id)))93}9495pub fn load_modules_with(root_name: &str, source: &str, loader: &dyn SourceLoader, max_depth: u32, parse_fn: &mut ParseFn) -> ModuleSet {96 let mut set = ModuleSet::default();97 let mut ids: HashMap<String, FileId> = HashMap::new();98 add_file(&mut set, root_name, source, false, parse_fn);99 for name in PRELUDE {100 let text = STD_MODULES.iter().find(|(n, _)| n == name).map(|(_, t)| *t).unwrap_or("");101 let id = add_file(&mut set, name, text, true, parse_fn);102 ids.insert(name.to_string(), id);103 }104 let mut stack = vec![root_name.to_string()];105 visit(&mut set, &mut ids, 0, loader, max_depth, &mut stack, parse_fn);106 for name in PRELUDE {107 if let Some(id) = ids.get(*name).copied() {108 let mut stack = vec![name.to_string()];109 visit(&mut set, &mut ids, id, loader, max_depth, &mut stack, parse_fn);110 }111 }112 set113}114115fn add_file(set: &mut ModuleSet, name: &str, text: &str, is_std: bool, parse_fn: &mut ParseFn) -> FileId {116 let id = set.files.len() as FileId;117 let parsed = parse_fn(name, id, text);118 if let Some(v) = &parsed.file.version {119 let ours: Vec<u32> = LANGUAGE_VERSION.split('.').filter_map(|p| p.parse().ok()).collect();120 let (major, minor) = (ours.first().copied().unwrap_or(0), ours.get(1).copied().unwrap_or(0));121 if (v.major, v.minor) > (major, minor) {122 set.diagnostics.push(123 Diagnostic::error(124 "I7004",125 v.span,126 format!("this file asks for Sonata {}.{}, but this toolchain implements {LANGUAGE_VERSION}", v.major, v.minor),127 )128 .with_suggestion("update ORIX Sonata, or lower the version line if the file only uses older features"),129 );130 }131 }132 set.files.push(SourceFile { id, name: name.to_string(), text: Arc::from(text), parsed, is_std, lines: Arc::new(LineIndex::new(text)) });133 id134}135136fn visit(137 set: &mut ModuleSet,138 ids: &mut HashMap<String, FileId>,139 file: FileId,140 loader: &dyn SourceLoader,141 max_depth: u32,142 stack: &mut Vec<String>,143 parse_fn: &mut ParseFn,144) {145 let parsed = set.files[file as usize].parsed.clone();146 for item in &parsed.file.items {147 let Item::Import(imp) = item else { continue };148 let name = imp.dotted();149 if let Some(pos) = stack.iter().position(|s| *s == name) {150 let mut chain: Vec<&str> = stack[pos..].iter().map(String::as_str).collect();151 chain.push(&name);152 set.diagnostics.push(153 Diagnostic::error("I7002", imp.span, format!("import cycle: {}", chain.join(" → ")))154 .with_suggestion("move the shared definitions into a module that imports neither"),155 );156 continue;157 }158 if ids.contains_key(&name) {159 continue;160 }161 if stack.len() as u32 > max_depth {162 set.diagnostics.push(Diagnostic::error("I7003", imp.span, format!("imports are nested deeper than {max_depth} levels")));163 continue;164 }165 let std_text = STD_MODULES.iter().find(|(n, _)| *n == name).map(|(_, t)| t.to_string());166 let is_std = std_text.is_some();167 let text = match std_text {168 Some(t) => Some(t),169 None if name.starts_with("std.") || name == "std" => None,170 None => loader.load(&name),171 };172 let Some(text) = text else {173 let mut d = Diagnostic::error("I7001", imp.span, format!("module '{name}' was not found"));174 let known: Vec<&str> = STD_MODULES.iter().map(|(n, _)| *n).collect();175 let best = known.iter().map(|k| (edit_distance(&name, k), *k)).min();176 d = match best {177 Some((dist, k)) if dist <= 3 => {178 let path_span = Span::new(imp.span.file, imp.path.first().map(|p| p.span.start).unwrap_or(imp.span.start), imp.span.end);179 d.with_suggestion(format!("did you mean '{k}'?")).with_fix(format!("import {k}"), path_span, k)180 }181 _ => d.with_suggestion(format!(182 "standard modules are {}; project modules are files next to the project root (a.b = a/b.sonata)",183 known.join(", ")184 )),185 };186 set.diagnostics.push(d);187 continue;188 };189 let id = add_file(set, &name, &text, is_std, parse_fn);190 ids.insert(name.clone(), id);191 stack.push(name);192 visit(set, ids, id, loader, max_depth, stack, parse_fn);193 stack.pop();194 }195}196