SPB Git

Repository Public

services.rs 42.4 KB 918 lines rust

1//! ORIX Sonata2//! File: crates/sonata-compiler/src/services.rs3//! Description: Language services shared by the editor and the LSP: syntax classes,4//! completion, hover, go-to-definition, references, document symbols and signature help.5//! Plain functions over (source, offset); they never evaluate the composition.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use crate::{Location, SourceEntry, SourceMap};11use serde::Serialize;12use sonata_ir::{Registry, Span, Unit};13use sonata_lexer::{is_keyword, lex, NoteLit, Token, TokenKind};14use sonata_parser::ast::{Item, Param, ARTICULATIONS};15use sonata_parser::format::expr_text;16use sonata_semantics::builtins::{self, BUILTINS, CONSTANTS};17use sonata_semantics::{index_symbols, load_modules, DefKind, ModuleSet, SourceLoader, SymbolIndex, STD_MODULES, TYPE_NAMES};1819/// Syntax classes, as documented in the C header (`sonata_highlight`).20pub mod class {21    pub const KEYWORD: u32 = 0;22    pub const IDENTIFIER: u32 = 1;23    pub const NUMBER: u32 = 2;24    pub const UNIT: u32 = 3;25    pub const NOTE: u32 = 4;26    pub const STRING: u32 = 5;27    pub const COMMENT: u32 = 6;28    pub const OPERATOR: u32 = 7;29    pub const PUNCTUATION: u32 = 8;30    pub const TYPE: u32 = 9;31    pub const FUNCTION: u32 = 10;32    pub const PARAMETER: u32 = 11;33    pub const INSTRUMENT: u32 = 12;34    pub const ERROR: u32 = 13;35}3637/// Words that act as keywords in some position without being reserved.38const CONTEXT_WORDS: &[&str] = &["duration", "velocity", "tie", "bend", "ramp", "of", "pre", "bypass"];3940/// Classifies every token and comment of a source: `(byte start, byte length, class)`,41/// ordered by position, never overlapping. Purely lexical, so it is fast and total: it works42/// on any text, valid or not.43pub fn highlight(source: &str) -> Vec<(u32, u32, u32)> {44    let lexed = lex(source, 0);45    let toks = &lexed.tokens;46    let mut out: Vec<(u32, u32, u32)> = Vec::with_capacity(toks.len() + lexed.comments.len());47    for c in &lexed.comments {48        out.push((c.span.start, c.span.len(), class::COMMENT));49    }50    for d in lexed.diagnostics.iter().filter(|d| d.code == "L0001") {51        out.push((d.span.start, d.span.len(), class::ERROR));52    }53    let word = |i: usize| -> Option<&str> {54        match toks.get(i).map(|t| &t.kind) {55            Some(TokenKind::Ident(s)) => Some(s.as_str()),56            _ => None,57        }58    };59    for (i, t) in toks.iter().enumerate() {60        let (start, len) = (t.span.start, t.span.len());61        let prev = if i > 0 { Some(&toks[i - 1].kind) } else { None };62        let next = toks.get(i + 1).map(|n| (&n.kind, n.nl_before));63        match &t.kind {64            TokenKind::Eof => {}65            TokenKind::Number { unit, .. } => {66                // The unit suffix is the trailing non-digit part of the literal.67                let text = source.get(start as usize..t.span.end as usize).unwrap_or("");68                let digits = text.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '_')).unwrap_or(text.len()) as u32;69                if unit.is_some() && digits < len {70                    out.push((start, digits, class::NUMBER));71                    out.push((start + digits, len - digits, class::UNIT));72                } else {73                    out.push((start, len, class::NUMBER));74                }75            }76            TokenKind::Str(_) => out.push((start, len, class::STRING)),77            TokenKind::Note(_) | TokenKind::PitchClass(_) => out.push((start, len, class::NOTE)),78            TokenKind::Ident(w) => {79                let after_colon = matches!(prev, Some(TokenKind::Colon));80                // A reserved word used as an argument label (`in: x`) is a label, not a keyword.81                let label = matches!(next, Some((TokenKind::Colon, _))) && !matches!(prev, Some(TokenKind::LBrace) | None);82                let names_instrument = (i > 0 && word(i - 1) == Some("instrument")) || (after_colon && i >= 3 && word(i - 3) == Some("instrument"));83                let names_function = (i > 0 && matches!(word(i - 1), Some("fn") | Some("pattern"))) || matches!(next, Some((TokenKind::LParen, false)));84                let cls = if matches!(w.as_str(), "and" | "or" | "not") {85                    class::OPERATOR86                } else if is_keyword(w) && !label {87                    class::KEYWORD88                } else if names_instrument {89                    class::INSTRUMENT90                } else if names_function {91                    class::FUNCTION92                } else if label && matches!(prev, Some(TokenKind::LParen) | Some(TokenKind::Comma)) {93                    class::PARAMETER94                } else if TYPE_NAMES.contains(&w.as_str())95                    && (after_colon || matches!(prev, Some(TokenKind::Arrow) | Some(TokenKind::Lt) | Some(TokenKind::Comma)))96                {97                    class::TYPE98                } else if CONTEXT_WORDS.contains(&w.as_str()) || ARTICULATIONS.contains(&w.as_str()) {99                    class::KEYWORD100                } else {101                    class::IDENTIFIER102                };103                out.push((start, len, cls));104            }105            TokenKind::LParen106            | TokenKind::RParen107            | TokenKind::LBrace108            | TokenKind::RBrace109            | TokenKind::LBracket110            | TokenKind::RBracket111            | TokenKind::Comma112            | TokenKind::Colon113            | TokenKind::Semi114            | TokenKind::Dot => out.push((start, len, class::PUNCTUATION)),115            _ => out.push((start, len, class::OPERATOR)),116        }117    }118    out.sort_by_key(|t| (t.0, t.1));119    // Drop anything overlapping an earlier triple (error runs inside tokens cannot happen, but120    // the guarantee is cheap).121    let mut end = 0u32;122    out.retain(|t| {123        if t.1 == 0 || t.0 < end {124            return false;125        }126        end = t.0 + t.1;127        true128    });129    out130}131132#[derive(Clone, Debug, PartialEq, Eq, Serialize)]133pub struct Completion {134    pub label: String,135    /// `keyword`, `function`, `pattern`, `constant`, `variable`, `instrument`, `engine`,136    /// `effect`, `preset`, `parameter`, `type`, `module`, `bus`, `node`, `value`.137    pub kind: &'static str,138    pub detail: String,139    /// Text to insert (the label, sometimes with `: ` or `(`).140    pub insert: String,141}142143#[derive(Clone, Debug, PartialEq, Eq, Serialize)]144pub struct Hover {145    pub start: u32,146    pub end: u32,147    /// Markdown.148    pub text: String,149}150151#[derive(Clone, Debug, PartialEq, Eq, Serialize)]152pub struct DocumentSymbol {153    pub name: String,154    pub kind: DefKind,155    pub detail: String,156    pub range: Location,157    pub selection: Location,158    pub children: Vec<DocumentSymbol>,159}160161#[derive(Clone, Debug, PartialEq, Eq, Serialize)]162pub struct ParameterInfo {163    pub label: String,164    pub doc: String,165}166167#[derive(Clone, Debug, PartialEq, Eq, Serialize)]168pub struct SignatureHelp {169    pub label: String,170    pub doc: String,171    pub parameters: Vec<ParameterInfo>,172    pub active_parameter: u32,173}174175/// What encloses a position, from the token stream alone (so it works mid-edit).176#[derive(Clone, Debug, PartialEq)]177enum Block {178    Top,179    Composition,180    Track,181    Audio,182    Bus,183    Master,184    Effects,185    InstrumentDef { model: Option<String> },186    Graph,187    Points,188    Function,189    Pattern,190}191192struct Context {193    block: Block,194    /// Innermost unclosed call: callee name, index of its `(` token.195    call: Option<(String, usize)>,196    /// Tokens strictly before the word being typed.197    before: usize,198    prefix: String,199    prefix_start: u32,200    statement_start: bool,201}202203fn word_at(toks: &[Token], i: usize) -> Option<&str> {204    match toks.get(i).map(|t| &t.kind) {205        Some(TokenKind::Ident(s)) => Some(s.as_str()),206        _ => None,207    }208}209210fn context(source: &str, toks: &[Token], offset: u32) -> Context {211    // The word being typed ends at the cursor.212    let bytes = source.as_bytes();213    let mut start = (offset as usize).min(bytes.len());214    while start > 0 && (bytes[start - 1].is_ascii_alphanumeric() || bytes[start - 1] == b'_' || bytes[start - 1] == b'#') {215        start -= 1;216    }217    let prefix = source.get(start..(offset as usize).min(bytes.len())).unwrap_or("").to_string();218    let before = toks.iter().take_while(|t| t.span.end as usize <= start && !matches!(t.kind, TokenKind::Eof)).count();219    let mut blocks: Vec<Block> = vec![Block::Top];220    let mut calls: Vec<Option<(String, usize)>> = Vec::new();221    let mut i = 0;222    while i < before {223        match &toks[i].kind {224            TokenKind::LBrace => {225                // Header: first word of the statement that opens this brace.226                let mut s = i;227                while s > 0 && !toks[s].nl_before && !matches!(toks[s - 1].kind, TokenKind::LBrace | TokenKind::RBrace | TokenKind::Semi) {228                    s -= 1;229                }230                let parent = blocks.last().cloned().unwrap_or(Block::Top);231                let block = match word_at(toks, s) {232                    Some("composition") => Block::Composition,233                    Some("instrument") if parent == Block::Composition => Block::Track,234                    Some("instrument") => Block::InstrumentDef { model: None },235                    Some("audio") => Block::Audio,236                    Some("bus") => Block::Bus,237                    Some("master") => Block::Master,238                    Some("effects") => Block::Effects,239                    Some("graph") => Block::Graph,240                    Some("automate") => Block::Points,241                    Some("fn") => Block::Function,242                    Some("pattern") => Block::Pattern,243                    _ if s < i && toks[s..i].iter().any(|t| matches!(&t.kind, TokenKind::Ident(w) if w == "bend")) => Block::Points,244                    _ => parent,245                };246                blocks.push(block);247            }248            TokenKind::RBrace if blocks.len() > 1 => {249                blocks.pop();250            }251            TokenKind::RBrace => {}252            TokenKind::LParen => {253                let callee = if i > 0 && !toks[i].nl_before { word_at(toks, i - 1).map(|w| (w.to_string(), i)) } else { None };254                calls.push(callee);255            }256            TokenKind::RParen => {257                calls.pop();258            }259            TokenKind::Ident(w) if w == "model" => {260                if let (Some(Block::InstrumentDef { model }), Some(m)) = (blocks.last_mut(), word_at(toks, i + 1)) {261                    if i + 1 < before {262                        *model = Some(m.to_string());263                    }264                }265            }266            _ => {}267        }268        i += 1;269    }270    let gap = source.get(toks.get(before.wrapping_sub(1)).map(|t| t.span.end as usize).unwrap_or(0)..start).unwrap_or("");271    let statement_start = before == 0 || gap.contains('\n') || matches!(toks[before - 1].kind, TokenKind::LBrace | TokenKind::RBrace | TokenKind::Semi);272    Context {273        block: blocks.pop().unwrap_or(Block::Top),274        call: calls.into_iter().rev().flatten().next(),275        before,276        prefix,277        prefix_start: start as u32,278        statement_start,279    }280}281282/// Effect kind of a call in an `effects { }` block: `delay(…)` or `delay echo(…)`.283fn effect_of_call<'t>(toks: &'t [Token], open: usize, registry: &Registry) -> Option<&'t str> {284    let direct = if open >= 1 { word_at(toks, open - 1) } else { None };285    if let Some(w) = direct.filter(|w| registry.effect(w).is_some()) {286        return Some(w);287    }288    let before = if open >= 2 && !toks[open - 1].nl_before { word_at(toks, open - 2) } else { None };289    before.filter(|w| registry.effect(w).is_some())290}291292/// The dotted name ending just before token index `end` on the same line (`osc1.wave`).293fn dotted_before(toks: &[Token], end: usize) -> Option<String> {294    let mut i = end.checked_sub(1)?;295    let mut parts = vec![word_at(toks, i)?.to_string()];296    while i >= 2 && matches!(toks[i - 1].kind, TokenKind::Dot) && !toks[i].nl_before && !toks[i - 1].nl_before {297        match word_at(toks, i - 2) {298            Some(w) => parts.push(w.to_string()),299            None => break,300        }301        i -= 2;302    }303    parts.reverse();304    Some(parts.join("."))305}306307fn unit_text(u: Unit) -> &'static str {308    match u {309        Unit::Scalar => "number",310        Unit::Ratio => "ratio",311        Unit::Decibel => "dB",312        Unit::Hertz => "Hz",313        Unit::Seconds => "s",314        Unit::Semitones => "st",315        Unit::Count => "integer",316        Unit::Degrees => "deg",317        Unit::HertzList => "list of Hz",318        Unit::ScalarList => "list of numbers",319        Unit::Choice => "choice",320    }321}322323fn param_detail(p: &sonata_ir::ParamDesc) -> String {324    match p.unit {325        Unit::Choice => format!("{} (default {}) — {}", p.choices.join(" | "), p.default_choice.clone().unwrap_or_default(), p.doc),326        Unit::HertzList | Unit::ScalarList => format!("{} — {}", unit_text(p.unit), p.doc),327        u => format!("{} in [{}, {}], default {} — {}", unit_text(u), p.min, p.max, p.default, p.doc),328    }329}330331fn params_label(ps: &[Param]) -> Vec<ParameterInfo> {332    ps.iter()333        .map(|p| {334            let mut label = p.name.name.clone();335            if let Some(t) = &p.ty {336                label.push_str(": ");337                label.push_str(&t.name.name);338            }339            if let Some(d) = &p.default {340                label.push_str(" = ");341                label.push_str(&expr_text(d));342            }343            ParameterInfo { label, doc: String::new() }344        })345        .collect()346}347348fn source_map(set: &ModuleSet) -> SourceMap {349    SourceMap {350        files: set.files.iter().map(|f| SourceEntry { name: f.name.clone(), text: f.text.clone(), lines: f.lines.clone(), is_std: f.is_std }).collect(),351    }352}353354/// Language services bound to a registry. [`Services::new`] uses the registry of this build.355pub struct Services<'r> {356    pub registry: &'r Registry,357}358359impl Default for Services<'static> {360    fn default() -> Self {361        Services::new()362    }363}364365impl Services<'static> {366    pub fn new() -> Services<'static> {367        Services { registry: crate::registry() }368    }369}370371const MODIFIERS: &[&str] = &["duration", "velocity", "tie", "bend"];372373impl<'r> Services<'r> {374    pub fn with_registry(registry: &'r Registry) -> Services<'r> {375        Services { registry }376    }377378    fn index(&self, root_name: &str, source: &str, loader: &dyn SourceLoader) -> (ModuleSet, SymbolIndex) {379        crate::on_big_stack(|| {380            let set = load_modules(root_name, source, loader, 16);381            let index = index_symbols(&set, self.registry);382            (set, index)383        })384    }385386    /// Completion candidates at a byte offset, most relevant kinds first.387    pub fn completions(&self, root_name: &str, source: &str, offset: u32, loader: &dyn SourceLoader) -> Vec<Completion> {388        let (set, index) = self.index(root_name, source, loader);389        let toks = &set.files[0].parsed.tokens;390        let cx = context(source, toks, offset);391        let mut out: Vec<Completion> = Vec::new();392        let mut add = |label: &str, kind: &'static str, detail: &str, insert: Option<String>| {393            out.push(Completion { label: label.to_string(), kind, detail: detail.to_string(), insert: insert.unwrap_or_else(|| label.to_string()) })394        };395        let prev = if cx.before > 0 { Some(&toks[cx.before - 1]) } else { None };396        let prev_word = prev.and_then(|t| if let TokenKind::Ident(w) = &t.kind { Some(w.as_str()) } else { None });397        let prev2_word = if cx.before > 1 { word_at(toks, cx.before - 2) } else { None };398        let same_line = !cx.statement_start;399        let engine_of = |model: &Option<String>| model.as_ref().and_then(|m| self.registry.engine(m));400        let mut expression = false;401402        if matches!(prev.map(|t| &t.kind), Some(TokenKind::Dot)) && same_line {403            if prev2_word == Some("import")404                || (cx.before > 2405                    && toks[..cx.before].iter().rev().take_while(|t| !t.nl_before).any(|t| matches!(&t.kind, TokenKind::Ident(w) if w == "import")))406            {407                for (m, _) in STD_MODULES {408                    if let Some(rest) = m.strip_prefix("std.") {409                        add(rest, "module", m, None);410                    }411                }412            } else if prev2_word == Some("note") && cx.block == Block::Graph {413                for (n, d) in [414                    ("freq", "fundamental in Hz, pitch bend included"),415                    ("pitch", "MIDI pitch"),416                    ("velocity", "velocity in [0, 1]"),417                    ("gate", "1 while held, 0 after note-off"),418                    ("time", "seconds since note-on"),419                ] {420                    add(n, "value", d, None);421                }422            } else {423                for (n, d) in [424                    ("len", "List: number of elements"),425                    ("first", "List: first element"),426                    ("last", "List: last element"),427                    ("midi", "Pitch: MIDI number"),428                    ("octave", "Pitch: octave"),429                    ("class", "Pitch: pitch class 0–11"),430                    ("hz", "Pitch: frequency"),431                ] {432                    add(n, "value", d, None);433                }434            }435        } else if prev_word == Some("import") && same_line {436            for (m, _) in STD_MODULES {437                add(m, "module", "standard library", None);438            }439        } else if prev_word == Some("model") && same_line {440            for e in &self.registry.engines {441                add(&e.model, "engine", &format!("{} — {}", e.title, e.method), None);442            }443        } else if prev_word == Some("preset") && same_line {444            if let Block::InstrumentDef { model } = &cx.block {445                for p in engine_of(model).map(|e| e.presets.as_slice()).unwrap_or(&[]) {446                    add(&p.name, "preset", &p.doc, None);447                }448            }449        } else if matches!(prev.map(|t| &t.kind), Some(TokenKind::Colon)) && cx.before >= 3 && word_at(toks, cx.before - 3) == Some("instrument") && same_line {450            for d in index.defs.iter().filter(|d| d.kind == DefKind::Instrument) {451                add(&d.name, "instrument", &d.detail, None);452            }453            for e in self.registry.engines.iter().filter(|e| e.model != "patch") {454                add(&e.model, "engine", &format!("{} (engine)", e.title), None);455            }456        } else if prev_word == Some("key") && same_line {457            for pc in ["C", "C#", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"] {458                add(pc, "value", "tonic", None);459            }460        } else if matches!(prev.map(|t| &t.kind), Some(TokenKind::PitchClass(_))) && prev2_word == Some("key") && same_line {461            for m in builtins::mode_names() {462                add(m, "value", "mode", None);463            }464        } else if prev_word == Some("articulation") && same_line {465            for a in ARTICULATIONS {466                add(a, "value", "articulation", None);467            }468        } else if matches!(prev_word, Some("output") | Some("send")) && same_line {469            for d in index.defs.iter().filter(|d| d.kind == DefKind::Bus && d.scope.map(|s| s.file == 0 && s.contains(offset)).unwrap_or(false)) {470                add(&d.name, "bus", &d.detail, None);471            }472            if prev_word == Some("output") {473                add("master", "bus", "the master bus", None);474            }475        } else if prev_word == Some("automate") && same_line {476            add("gain", "parameter", "fader level in dB", None);477            add("pan", "parameter", "pan in [-1, 1]", None);478            add("instrument", "parameter", "instrument.<parameter>", Some("instrument.".into()));479            for e in &self.registry.effects {480                add(&e.kind, "effect", &format!("{}.<parameter>", e.kind), Some(format!("{}.", e.kind)));481            }482        } else if prev_word == Some("default") && same_line {483            add("duration", "keyword", "default note duration of the track", None);484            add("velocity", "keyword", "default velocity of the track", None);485        } else if cx.block == Block::Effects && same_line && cx.call.is_none() && prev_word.map(|w| self.registry.effect(w).is_some()).unwrap_or(false) {486            for p in self.registry.effect(prev_word.unwrap_or("")).map(|e| e.presets.as_slice()).unwrap_or(&[]) {487                add(&p.name, "preset", &p.doc, None);488            }489        } else if cx.block == Block::Effects && cx.call.is_none() {490            if cx.statement_start {491                add("bypass", "keyword", "declare the effect bypassed", None);492            }493            for e in &self.registry.effects {494                add(&e.kind, "effect", &format!("{} — {}", e.title, e.doc), None);495            }496        } else if matches!(prev.map(|t| &t.kind), Some(TokenKind::Arrow))497            || (matches!(prev.map(|t| &t.kind), Some(TokenKind::Colon))498                && (prev2_word.is_some()499                    && cx.call.as_ref().map(|(_, open)| *open > 1 && matches!(word_at(toks, open - 2), Some("fn") | Some("pattern"))).unwrap_or(false)500                    || (cx.before >= 3 && matches!(word_at(toks, cx.before - 3), Some("let") | Some("const")))))501        {502            for t in TYPE_NAMES {503                add(t, "type", "type", None);504            }505        } else if cx.statement_start {506            let (keywords, with_expr): (&[&str], bool) = match &cx.block {507                Block::Top => (&["import", "const", "let", "fn", "pattern", "instrument", "composition"], false),508                Block::Composition => {509                    (&["tempo", "key", "signature", "seed", "swing", "tuning", "instrument", "audio", "bus", "master", "marker", "at", "let", "const"], false)510                }511                Block::Track | Block::Pattern => (512                    &[513                        "play",514                        "chord",515                        "rest",516                        "sequence",517                        "voice",518                        "parallel",519                        "at",520                        "repeat",521                        "for",522                        "if",523                        "tuplet",524                        "transpose",525                        "swing",526                        "tempo",527                        "signature",528                        "marker",529                        "let",530                        "const",531                        "default",532                        "gain",533                        "pan",534                        "mute",535                        "solo",536                        "output",537                        "send",538                        "articulation",539                        "score_transposition",540                        "effects",541                        "automate",542                    ],543                    false,544                ),545                Block::Audio => (&["clip", "gain", "pan", "mute", "solo", "output", "send", "effects", "automate"], false),546                Block::Bus => (&["gain", "pan", "mute", "output", "send", "effects", "automate"], false),547                Block::Master => (&["sample_rate", "peak_limit", "gain", "effects", "automate"], false),548                Block::Function => (&["let", "const", "if", "for", "repeat", "return"], true),549                Block::InstrumentDef { .. } => (&["model", "preset", "graph"], false),550                Block::Graph => (&["node", "out"], false),551                Block::Effects | Block::Points => (&[], true),552            };553            for k in keywords {554                add(k, "keyword", "", None);555            }556            if matches!(cx.block, Block::Track | Block::Pattern | Block::Composition) {557                for d in index.defs.iter().filter(|d| d.kind == DefKind::Pattern) {558                    add(&d.name, "pattern", &d.detail, Some(format!("{}(", d.name)));559                }560            }561            if let Block::InstrumentDef { model } = &cx.block {562                if let Some(e) = engine_of(model) {563                    let mut slots: Vec<&str> = Vec::new();564                    for p in &e.params {565                        match p.name.split_once('.') {566                            Some((slot, _)) if !slots.contains(&slot) && !e.params.iter().any(|q| q.name == slot) => {567                                slots.push(slot);568                                add(slot, "parameter", "slot", None);569                            }570                            _ => {}571                        }572                        add(&p.name, "parameter", &param_detail(p), None);573                    }574                }575            }576            expression = with_expr;577        } else {578            expression = true;579        }580581        if expression {582            // Named arguments of the enclosing call.583            if let Some((callee, _)) = &cx.call {584                let after_sep = matches!(prev.map(|t| &t.kind), Some(TokenKind::LParen) | Some(TokenKind::Comma));585                if after_sep {586                    if cx.block == Block::Effects {587                        let open = cx.call.as_ref().map(|c| c.1).unwrap_or(0);588                        if let Some(e) = effect_of_call(toks, open, self.registry).and_then(|k| self.registry.effect(k)) {589                            for p in &e.params {590                                add(&p.name, "parameter", &param_detail(p), Some(format!("{}: ", p.name)));591                            }592                            if !e.params.iter().any(|p| p.name == "mix") {593                                add("mix", "parameter", &format!("dry/wet in [0, 1], default {}", e.default_mix), Some("mix: ".into()));594                            }595                        }596                    } else if cx.block == Block::Graph {597                        if let Some(n) = self.registry.patch_node(callee) {598                            for p in &n.ports {599                                add(&p.name, "parameter", &format!("{} — {}", unit_text(p.unit), p.doc), Some(format!("{}: ", p.name)));600                            }601                        }602                    } else if let Block::InstrumentDef { model } = &cx.block {603                        // Arguments of a slot: `excitation pluck(` → parameters `excitation.*`.604                        let open = cx.call.as_ref().map(|c| c.1).unwrap_or(0);605                        if let (Some(e), Some(slot)) = (engine_of(model), if open >= 2 { word_at(toks, open - 2) } else { None }) {606                            let prefix = format!("{slot}.");607                            for p in e.params.iter().filter(|p| p.name.starts_with(&prefix)) {608                                let short = &p.name[prefix.len()..];609                                add(short, "parameter", &param_detail(p), Some(format!("{short}: ")));610                            }611                        }612                    }613                    for file in &set.files {614                        for item in &file.parsed.file.items {615                            let params = match item {616                                Item::Fn(f) if f.name.name == *callee => &f.params,617                                Item::Pattern(p) if p.name.name == *callee => &p.params,618                                _ => continue,619                            };620                            for p in params {621                                add(&p.name.name, "parameter", "argument", Some(format!("{}: ", p.name.name)));622                            }623                        }624                    }625                }626            }627            // Play modifiers continue a `play` or `chord` line.628            let line_start = toks[..cx.before].iter().rposition(|t| t.nl_before).unwrap_or(0);629            if matches!(word_at(toks, line_start), Some("play") | Some("chord")) && cx.before > line_start + 1 && cx.call.is_none() {630                for m in MODIFIERS {631                    add(m, "keyword", "play modifier", None);632                }633                for a in ARTICULATIONS {634                    add(a, "keyword", "articulation", None);635                }636            }637            if cx.block == Block::Graph {638                add("note", "value", "note.freq, note.pitch, note.velocity, note.gate, note.time", None);639                for n in &self.registry.patch_nodes {640                    add(&n.kind, "node", &format!("{} — {}", n.category, n.doc), Some(format!("{}(", n.kind)));641                }642            }643            if let Block::InstrumentDef { model } = &cx.block {644                // Choice values of the parameter being set.645                if let (Some(e), Some(w)) = (engine_of(model), dotted_before(toks, cx.before)) {646                    if let Some(p) = e.params.iter().find(|p| p.name == w && p.unit == Unit::Choice) {647                        for c in &p.choices {648                            add(c, "value", &format!("choice of {}", p.name), None);649                        }650                    }651                }652            }653            // Names in scope: locals visible here, then top-level definitions, then built-ins.654            for d in index.defs.iter().rev() {655                let visible = match d.scope {656                    Some(s) => s.file == 0 && s.contains(offset.saturating_sub(1).max(s.start)) && d.span.end <= cx.prefix_start,657                    None => true,658                };659                if !visible {660                    continue;661                }662                match d.kind {663                    DefKind::Variable | DefKind::Parameter | DefKind::Node => add(&d.name, "variable", &d.detail, None),664                    DefKind::Constant => add(&d.name, "constant", &d.detail, None),665                    DefKind::Function => add(&d.name, "function", &d.detail, Some(format!("{}(", d.name))),666                    _ => {}667                }668            }669            for b in BUILTINS {670                add(b.name, "function", b.signature, Some(format!("{}(", b.name)));671            }672            for c in CONSTANTS {673                add(c, "constant", "built-in", None);674            }675            for k in ["true", "false", "if", "not", "and", "or"] {676                add(k, "keyword", "", None);677            }678        }679680        let p = cx.prefix.to_ascii_lowercase();681        out.retain(|c| c.label.to_ascii_lowercase().starts_with(&p));682        // First occurrence wins (inner scopes were added first), order is otherwise kept.683        let mut seen = std::collections::HashSet::new();684        out.retain(|c| seen.insert(c.label.clone()));685        out686    }687688    /// Hover text for the token at a byte offset.689    pub fn hover(&self, root_name: &str, source: &str, offset: u32, loader: &dyn SourceLoader) -> Option<Hover> {690        let (set, index) = self.index(root_name, source, loader);691        let toks = &set.files[0].parsed.tokens;692        let i = toks.iter().position(|t| t.span.start <= offset && offset < t.span.end)?;693        let t = &toks[i];694        let make = |text: String| Some(Hover { start: t.span.start, end: t.span.end, text });695        match &t.kind {696            TokenKind::Note(n) => {697                let NoteLit { .. } = n;698                let midi = n.midi();699                let hz = 440.0 * ((midi as f64 - 69.0) / 12.0).exp2();700                make(format!("**{}** — MIDI {midi}, {hz:.2} Hz (A4 = 440 Hz)", sonata_parser::format::note_text(*n)))701            }702            TokenKind::PitchClass(p) => make(format!("**{}** — pitch class {}", sonata_parser::format::pitch_class_text(*p), p.pitch_class())),703            TokenKind::Ident(w) => {704                let prev = if i > 0 { word_at(toks, i - 1) } else { None };705                let cx = context(source, toks, t.span.end);706                if prev == Some("model") {707                    if let Some(e) = self.registry.engine(w) {708                        return make(format!(709                            "**{}** — engine `{}` ({})\n\n{}\n\nMethod: {}. Range: MIDI {}–{}.",710                            e.title, e.model, e.family, e.doc, e.method, e.range.0, e.range.1711                        ));712                    }713                }714                if cx.block == Block::Effects {715                    if let Some(e) = self.registry.effect(w) {716                        let params: Vec<String> = e.params.iter().map(|p| format!("- `{}`: {}", p.name, param_detail(p))).collect();717                        return make(format!(718                            "**{}** — effect `{}` ({})\n\n{}\n\n{}\n- `mix`: dry/wet, default {}",719                            e.title,720                            e.kind,721                            e.category,722                            e.doc,723                            params.join("\n"),724                            e.default_mix725                        ));726                    }727                    if let Some((_, open)) = &cx.call {728                        if let Some(p) = effect_of_call(toks, *open, self.registry)729                            .and_then(|k| self.registry.effect(k))730                            .and_then(|e| e.params.iter().find(|p| p.name == *w))731                        {732                            return make(format!("`{}` — {}", p.name, param_detail(p)));733                        }734                    }735                }736                if let Block::InstrumentDef { model: Some(m) } = &cx.block {737                    if let Some(p) = self.registry.engine(m).and_then(|e| e.params.iter().find(|p| p.name == *w)) {738                        return make(format!("`{}` — {}", p.name, param_detail(p)));739                    }740                }741                if cx.block == Block::Graph {742                    if let Some(n) = self.registry.patch_node(w) {743                        let ports: Vec<String> =744                            n.ports.iter().map(|p| format!("- `{}`: {} (default {}) — {}", p.name, unit_text(p.unit), p.default, p.doc)).collect();745                        return make(format!("**{}** — patch node `{}` ({})\n\n{}\n\n{}", n.title, n.kind, n.category, n.doc, ports.join("\n")));746                    }747                }748                if let Some(d) = index.definition_at(0, offset).map(|k| &index.defs[k]) {749                    let origin = set.file(d.span.file).filter(|f| f.id != 0).map(|f| format!("\n\nDefined in `{}`.", f.name)).unwrap_or_default();750                    return make(format!("```sonata\n{}\n```{origin}", d.detail));751                }752                if let Some(b) = builtins::find(w) {753                    return make(format!("```sonata\n{}\n```\n\n{}", b.signature, b.doc));754                }755                if let Some(v) = builtins::constant(w) {756                    return make(format!("`{w}` — built-in constant ({})", v.type_name()));757                }758                if TYPE_NAMES.contains(&w.as_str()) {759                    return make(format!("`{w}` — type"));760                }761                None762            }763            _ => None,764        }765    }766767    /// Where the name at a byte offset is defined.768    pub fn definition(&self, root_name: &str, source: &str, offset: u32, loader: &dyn SourceLoader) -> Option<Location> {769        let (set, index) = self.index(root_name, source, loader);770        let d = index.definition_at(0, offset)?;771        Some(source_map(&set).locate(index.defs[d].span))772    }773774    /// Every use of the name at a byte offset, the definition first.775    pub fn references(&self, root_name: &str, source: &str, offset: u32, loader: &dyn SourceLoader) -> Vec<Location> {776        let (set, index) = self.index(root_name, source, loader);777        let Some(d) = index.definition_at(0, offset) else { return Vec::new() };778        let map = source_map(&set);779        let mut spans: Vec<Span> = vec![index.defs[d].span];780        spans.extend(index.references_to(d));781        spans.sort_by_key(|s| (s.file, s.start));782        spans.dedup();783        let mut out: Vec<Location> = spans.into_iter().map(|s| map.locate(s)).collect();784        // Definition first.785        let def_span = index.defs[d].span;786        if let Some(pos) = out.iter().position(|l| l.file_id == def_span.file && l.start == def_span.start) {787            let def = out.remove(pos);788            out.insert(0, def);789        }790        out791    }792793    /// Outline of the root file: top-level definitions, with tracks and buses under their composition.794    pub fn document_symbols(&self, root_name: &str, source: &str, loader: &dyn SourceLoader) -> Vec<DocumentSymbol> {795        let (set, index) = self.index(root_name, source, loader);796        let map = source_map(&set);797        fn build(index: &SymbolIndex, map: &SourceMap, parent: Option<usize>) -> Vec<DocumentSymbol> {798            let mut out: Vec<DocumentSymbol> = index799                .defs800                .iter()801                .enumerate()802                .filter(|(_, d)| {803                    d.span.file == 0804                        && d.parent == parent805                        && !matches!(d.kind, DefKind::Parameter | DefKind::Variable | DefKind::Node)806                        && (parent.is_some() || d.scope.is_none())807                })808                .map(|(i, d)| DocumentSymbol {809                    name: d.name.clone(),810                    kind: d.kind,811                    detail: d.detail.clone(),812                    range: map.locate(d.full_span),813                    selection: map.locate(d.span),814                    children: build(index, map, Some(i)),815                })816                .collect();817            out.sort_by_key(|s| s.range.start);818            out819        }820        build(&index, &map, None)821    }822823    /// Signature of the call the cursor is in, with the active parameter.824    pub fn signature_help(&self, root_name: &str, source: &str, offset: u32, loader: &dyn SourceLoader) -> Option<SignatureHelp> {825        let (set, _) = self.index(root_name, source, loader);826        let toks = &set.files[0].parsed.tokens;827        let cx = context(source, toks, offset);828        let (callee, open) = cx.call.clone()?;829        // Active parameter: commas at depth 0 since the opening parenthesis, or the name being given.830        let mut depth = 0i32;831        let mut active = 0u32;832        let mut named: Option<String> = None;833        let upto = toks.iter().take_while(|t| t.span.end <= offset && !matches!(t.kind, TokenKind::Eof)).count();834        for j in open + 1..upto {835            match &toks[j].kind {836                TokenKind::LParen | TokenKind::LBracket | TokenKind::LBrace => depth += 1,837                TokenKind::RParen | TokenKind::RBracket | TokenKind::RBrace => depth -= 1,838                TokenKind::Comma if depth == 0 => {839                    active += 1;840                    named = None;841                }842                TokenKind::Colon if depth == 0 => named = word_at(toks, j - 1).map(str::to_string),843                _ => {}844            }845        }846        let pick = |params: &[ParameterInfo]| -> u32 {847            match &named {848                Some(n) => params849                    .iter()850                    .position(|p| p.label == *n || p.label.starts_with(&format!("{n}:")) || p.label.starts_with(&format!("{n} ")))851                    .map(|p| p as u32)852                    .unwrap_or(active),853                None => active,854            }855        };856        for file in &set.files {857            for item in &file.parsed.file.items {858                let (kw, name, params) = match item {859                    Item::Fn(f) if f.name.name == callee => ("fn", &f.name.name, &f.params),860                    Item::Pattern(p) if p.name.name == callee => ("pattern", &p.name.name, &p.params),861                    _ => continue,862                };863                let parameters = params_label(params);864                let label = format!("{kw} {name}({})", parameters.iter().map(|p| p.label.as_str()).collect::<Vec<_>>().join(", "));865                return Some(SignatureHelp { label, doc: String::new(), active_parameter: pick(&parameters), parameters });866            }867        }868        if cx.block == Block::Effects {869            if let Some(e) = effect_of_call(toks, open, self.registry).and_then(|k| self.registry.effect(k)) {870                let mut parameters: Vec<ParameterInfo> = e.params.iter().map(|p| ParameterInfo { label: p.name.clone(), doc: param_detail(p) }).collect();871                if !e.params.iter().any(|p| p.name == "mix") {872                    parameters.push(ParameterInfo { label: "mix".into(), doc: format!("dry/wet in [0, 1], default {}", e.default_mix) });873                }874                let label = format!("{}({})", e.kind, parameters.iter().map(|p| format!("{}: …", p.label)).collect::<Vec<_>>().join(", "));875                return Some(SignatureHelp { label, doc: e.doc.clone(), active_parameter: pick(&parameters), parameters });876            }877        }878        if cx.block == Block::Graph {879            if let Some(n) = self.registry.patch_node(&callee) {880                let parameters: Vec<ParameterInfo> = n881                    .ports882                    .iter()883                    .map(|p| ParameterInfo { label: p.name.clone(), doc: format!("{} (default {}) — {}", unit_text(p.unit), p.default, p.doc) })884                    .collect();885                let label = format!("{}({})", n.kind, parameters.iter().map(|p| p.label.as_str()).collect::<Vec<_>>().join(", "));886                return Some(SignatureHelp { label, doc: n.doc.clone(), active_parameter: pick(&parameters), parameters });887            }888        }889        let b = builtins::find(&callee)?;890        let inner = b.signature.split_once('(').and_then(|(_, r)| r.rsplit_once(')')).map(|(a, _)| a).unwrap_or("");891        let parameters: Vec<ParameterInfo> =892            inner.split(',').map(str::trim).filter(|s| !s.is_empty()).map(|s| ParameterInfo { label: s.to_string(), doc: String::new() }).collect();893        Some(SignatureHelp {894            label: b.signature.to_string(),895            doc: b.doc.to_string(),896            active_parameter: active.min(parameters.len().saturating_sub(1) as u32),897            parameters,898        })899    }900901    /// One entry point returning JSON, for the C ABI. `kind`: `completion`, `hover`,902    /// `definition`, `references`, `symbols`, `signature`. Unknown kinds give `null`.903    pub fn query(&self, kind: &str, root_name: &str, source: &str, offset: u32, loader: &dyn SourceLoader) -> String {904        fn json<T: Serialize>(v: &T) -> String {905            serde_json::to_string(v).unwrap_or_else(|_| "null".into())906        }907        match kind {908            "completion" => json(&self.completions(root_name, source, offset, loader)),909            "hover" => json(&self.hover(root_name, source, offset, loader)),910            "definition" => json(&self.definition(root_name, source, offset, loader)),911            "references" => json(&self.references(root_name, source, offset, loader)),912            "symbols" => json(&self.document_symbols(root_name, source, loader)),913            "signature" => json(&self.signature_help(root_name, source, offset, loader)),914            _ => "null".into(),915        }916    }917}918
Files main
Menu

Theme