SPB Git

Repository Public

lib.rs 7.1 KB 166 lines rust

1//! ORIX Sonata2//! File: crates/sonata-semantics/src/lib.rs3//! Description: Symbol resolution, type and unit checking, musical validation, evaluation to Musical IR.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78pub mod builtins;9mod eval;10mod exec;11mod instr;12pub mod modules;13pub mod resolve;14pub mod testing;15pub mod value;1617pub use eval::{Quotas, SplitMix64, TYPE_NAMES};18pub use exec::{asset_path_problem, SAMPLE_RATES};19pub use modules::{load_modules, load_modules_with, MapLoader, ModuleSet, NoLoader, SourceFile, SourceLoader, PRELUDE, STD_MODULES};20pub use resolve::{Def, DefKind, Ref, SymbolIndex};2122use eval::{Analyzer, Global, GlobalKind};23use sonata_ir::{Diagnostic, Program, Registry, Severity};24use sonata_parser::ast::Item;25use std::collections::HashMap;2627/// Options of the semantic analysis.28#[derive(Clone, Debug, Default, PartialEq)]29pub struct Options {30    pub quotas: Quotas,31    /// Title of the composition to compile; the first one of the root file when `None`.32    pub composition: Option<String>,33}3435/// Result of the semantic analysis of a module set.36#[derive(Clone, Debug)]37pub struct Analysis {38    /// The compiled composition; `None` when there is an error or no composition.39    pub program: Option<Program>,40    /// Every diagnostic of the compilation (lexer, parser, imports, semantics), ordered by41    /// file then position, without duplicates.42    pub diagnostics: Vec<Diagnostic>,43    /// False when the root file is a module (no composition).44    pub has_composition: bool,45    pub symbols: SymbolIndex,46    /// Evaluation steps consumed (see `Quotas::max_steps`).47    pub steps: u64,48}4950impl Analysis {51    pub fn has_errors(&self) -> bool {52        self.diagnostics.iter().any(|d| d.severity == Severity::Error)53    }54}5556/// Analyses a loaded module set against a registry and evaluates the composition.57pub fn analyze(set: &ModuleSet, registry: &Registry, options: &Options) -> Analysis {58    let mut diagnostics: Vec<Diagnostic> = Vec::new();59    for f in &set.files {60        diagnostics.extend(f.parsed.diagnostics.iter().cloned());61    }62    diagnostics.extend(set.diagnostics.iter().cloned());63    let syntax_errors = diagnostics.iter().any(|d| d.is_error());6465    let mut an = Analyzer::new(set, registry, options.quotas.clone());66    let globals = collect_globals(set, &mut diagnostics);67    let (symbols, resolve_diags) = resolve::resolve(set, registry, &globals);68    an.globals = globals;6970    let root = set.files.first();71    let compositions: Vec<&sonata_parser::ast::Composition> =72        root.map(|f| f.parsed.file.items.iter().filter_map(|i| if let Item::Composition(c) = i { Some(c) } else { None }).collect()).unwrap_or_default();73    let has_composition = !compositions.is_empty();74    let mut program = None;75    if !syntax_errors {76        diagnostics.extend(resolve_diags);77        let chosen = match &options.composition {78            None => compositions.first().copied(),79            Some(title) => {80                let found = compositions.iter().find(|c| &c.title.value == title).copied();81                if found.is_none() {82                    let titles: Vec<String> = compositions.iter().map(|c| format!("\"{}\"", c.title.value)).collect();83                    let span = root.map(|f| f.parsed.file.span).unwrap_or_default();84                    an.report(85                        Diagnostic::error("S2010", sonata_ir::Span::new(span.file, 0, 0), format!("no composition is titled \"{title}\""))86                            .with_suggestion(format!("compositions in this file: {}", if titles.is_empty() { "none".into() } else { titles.join(", ") })),87                    );88                }89                found90            }91        };92        if let Some(c) = chosen {93            if let Ok(p) = an.run_composition(c) {94                program = Some(p);95            }96        }97        // Surface errors of every project definition, used or not. Done after the composition98        // so tempo-synced parameters of its instruments saw its tempo.99        for file in set.files.iter().filter(|f| !f.is_std) {100            for item in &file.parsed.file.items {101                match item {102                    Item::Let(l) => {103                        let _ = an.lookup(&l.name.name, l.name.span);104                    }105                    Item::Instrument(d) => {106                        let _ = an.resolve_instrument(&d.name);107                    }108                    _ => {}109                }110            }111        }112        diagnostics.append(&mut an.diags);113    }114    // Order and deduplicate (the resolver and the evaluator may report the same unknown name).115    diagnostics.sort_by(|a, b| (a.span.file, a.span.start, a.span.end, &a.code).cmp(&(b.span.file, b.span.start, b.span.end, &b.code)));116    diagnostics.dedup_by(|b, a| a.code == b.code && a.span == b.span);117    if diagnostics.iter().any(|d| d.is_error()) {118        program = None;119    }120    Analysis { program, diagnostics, has_composition, symbols, steps: an.steps }121}122123/// Top-level definitions of every file. Project definitions shadow the standard library.124fn collect_globals<'a>(set: &'a ModuleSet, diagnostics: &mut Vec<Diagnostic>) -> HashMap<&'a str, Global<'a>> {125    let mut globals: HashMap<&str, Global> = HashMap::new();126    let mut ordered: Vec<&modules::SourceFile> = set.files.iter().filter(|f| f.is_std).collect();127    ordered.extend(set.files.iter().filter(|f| !f.is_std));128    for file in ordered {129        for item in &file.parsed.file.items {130            let (name, kind) = match item {131                Item::Let(l) => (&l.name, GlobalKind::Value(l)),132                Item::Fn(f) => (&f.name, GlobalKind::Fn(f)),133                Item::Pattern(p) => (&p.name, GlobalKind::Pattern(p)),134                Item::Instrument(d) => (&d.name, GlobalKind::Instrument(d)),135                _ => continue,136            };137            if let Some(prev) = globals.get(name.name.as_str()) {138                if prev.is_std == file.is_std {139                    diagnostics.push(140                        Diagnostic::error("S2002", name.span, format!("'{}' is defined twice", name.name)).with_related(prev.name_span, "first defined here"),141                    );142                    continue;143                }144            }145            if sonata_semantics_reserved(&name.name) {146                diagnostics.push(Diagnostic::error("S2002", name.span, format!("'{}' is a built-in name and cannot be redefined", name.name)));147                continue;148            }149            globals.insert(name.name.as_str(), Global { kind, file: file.id, is_std: file.is_std, name_span: name.span });150        }151    }152    globals153}154155/// The symbol index alone (definitions and references), without evaluating anything.156/// Works on sources with syntax errors: this is what the editor services use while typing.157pub fn index_symbols(set: &ModuleSet, registry: &Registry) -> SymbolIndex {158    let mut scratch = Vec::new();159    let globals = collect_globals(set, &mut scratch);160    resolve::resolve(set, registry, &globals).0161}162163fn sonata_semantics_reserved(name: &str) -> bool {164    builtins::find(name).is_some() || matches!(name, "pi" | "tau" | "on" | "off" | "note")165}166
Files main
Menu

Theme