Repository Public
1//! ORIX Sonata2//! File: crates/sonata-ir/src/diag.rs3//! Description: Source spans and structured diagnostics shared by the compiler, CLI, LSP and editor.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use serde::{Deserialize, Serialize};910/// Index of a source file inside a compilation (see `SourceMap` in the compiler). 0 is the root file.11pub type FileId = u32;1213/// A half-open byte range `[start, end)` in a UTF-8 source file.14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]15pub struct Span {16 pub file: FileId,17 pub start: u32,18 pub end: u32,19}2021impl Span {22 pub const fn new(file: FileId, start: u32, end: u32) -> Span {23 Span { file, start, end }24 }25 /// Smallest span covering both (same file assumed; keeps `self.file`).26 pub fn to(self, other: Span) -> Span {27 Span { file: self.file, start: self.start.min(other.start), end: self.end.max(other.end) }28 }29 pub fn len(self) -> u32 {30 self.end.saturating_sub(self.start)31 }32 pub fn is_empty(self) -> bool {33 self.end <= self.start34 }35 pub fn contains(self, offset: u32) -> bool {36 offset >= self.start && offset < self.end37 }38}3940#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]41#[serde(rename_all = "lowercase")]42pub enum Severity {43 Error,44 Warning,45 Info,46 Hint,47}4849/// A text edit that is safe to apply automatically.50#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]51pub struct Fix {52 pub title: String,53 pub span: Span,54 pub replacement: String,55}5657/// A secondary location attached to a diagnostic ("first defined here").58#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]59pub struct Related {60 pub span: Span,61 pub message: String,62}6364/// A structured diagnostic.65///66/// Code ranges (stable, documented in `Documentation/spec/diagnostics.md`):67/// `L0xxx` lexer, `P1xxx` parser, `S2xxx` symbols and scopes, `T3xxx` types and units,68/// `M4xxx` musical validation, `G5xxx` DSP graph, `Q6xxx` quotas, `I7xxx` imports and modules.69#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]70pub struct Diagnostic {71 pub code: String,72 pub severity: Severity,73 pub span: Span,74 pub message: String,75 #[serde(default, skip_serializing_if = "Option::is_none")]76 pub suggestion: Option<String>,77 #[serde(default, skip_serializing_if = "Option::is_none")]78 pub fix: Option<Fix>,79 #[serde(default, skip_serializing_if = "Vec::is_empty")]80 pub related: Vec<Related>,81}8283impl Diagnostic {84 pub fn new(severity: Severity, code: &str, span: Span, message: impl Into<String>) -> Diagnostic {85 Diagnostic { code: code.to_string(), severity, span, message: message.into(), suggestion: None, fix: None, related: Vec::new() }86 }87 pub fn error(code: &str, span: Span, message: impl Into<String>) -> Diagnostic {88 Self::new(Severity::Error, code, span, message)89 }90 pub fn warning(code: &str, span: Span, message: impl Into<String>) -> Diagnostic {91 Self::new(Severity::Warning, code, span, message)92 }93 pub fn with_suggestion(mut self, s: impl Into<String>) -> Diagnostic {94 self.suggestion = Some(s.into());95 self96 }97 pub fn with_fix(mut self, title: impl Into<String>, span: Span, replacement: impl Into<String>) -> Diagnostic {98 self.fix = Some(Fix { title: title.into(), span, replacement: replacement.into() });99 self100 }101 pub fn with_related(mut self, span: Span, message: impl Into<String>) -> Diagnostic {102 self.related.push(Related { span, message: message.into() });103 self104 }105 pub fn is_error(&self) -> bool {106 self.severity == Severity::Error107 }108}109110/// 1-based line and column (column counted in Unicode scalar values) of a byte offset.111#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]112pub struct LineCol {113 pub line: u32,114 pub column: u32,115}116117/// Precomputed line starts of one source text, for offset to line/column conversion.118#[derive(Clone, Debug)]119pub struct LineIndex {120 starts: Vec<u32>,121}122123impl LineIndex {124 pub fn new(text: &str) -> LineIndex {125 let mut starts = vec![0u32];126 for (i, b) in text.bytes().enumerate() {127 if b == b'\n' {128 starts.push(i as u32 + 1);129 }130 }131 LineIndex { starts }132 }133 pub fn line_count(&self) -> usize {134 self.starts.len()135 }136 pub fn line_start(&self, line0: usize) -> Option<u32> {137 self.starts.get(line0).copied()138 }139 pub fn line_col(&self, text: &str, offset: u32) -> LineCol {140 let offset = (offset as usize).min(text.len());141 let line = match self.starts.binary_search(&(offset as u32)) {142 Ok(i) => i,143 Err(i) => i - 1,144 };145 let start = self.starts[line] as usize;146 let mut end = offset;147 while end > start && !text.is_char_boundary(end) {148 end -= 1;149 }150 LineCol { line: line as u32 + 1, column: text[start..end].chars().count() as u32 + 1 }151 }152 /// UTF-16 column (0-based line and character), as the Language Server Protocol requires.153 pub fn utf16_position(&self, text: &str, offset: u32) -> (u32, u32) {154 let offset = (offset as usize).min(text.len());155 let line = match self.starts.binary_search(&(offset as u32)) {156 Ok(i) => i,157 Err(i) => i - 1,158 };159 let start = self.starts[line] as usize;160 let mut end = offset;161 while end > start && !text.is_char_boundary(end) {162 end -= 1;163 }164 (line as u32, text[start..end].encode_utf16().count() as u32)165 }166 /// Byte offset of a 0-based line and UTF-16 character position (clamped to the line).167 pub fn offset_of_utf16(&self, text: &str, line: u32, character: u32) -> u32 {168 let Some(&start) = self.starts.get(line as usize) else { return text.len() as u32 };169 let end = self.starts.get(line as usize + 1).map(|e| *e as usize).unwrap_or(text.len());170 let mut units = 0u32;171 for (i, ch) in text[start as usize..end].char_indices() {172 if units >= character || ch == '\n' {173 return start + i as u32;174 }175 units += ch.len_utf16() as u32;176 }177 end as u32178 }179}180181#[cfg(test)]182mod tests {183 use super::*;184185 #[test]186 fn line_col_handles_unicode() {187 let text = "tempo 120bpm\n// é𝄞x\nkey D minor";188 let idx = LineIndex::new(text);189 assert_eq!(idx.line_count(), 3);190 assert_eq!(idx.line_col(text, 0), LineCol { line: 1, column: 1 });191 let x = text.find('x').unwrap() as u32;192 assert_eq!(idx.line_col(text, x), LineCol { line: 2, column: 6 });193 // é = 1 UTF-16 unit, 𝄞 = 2 units.194 assert_eq!(idx.utf16_position(text, x), (1, 6));195 assert_eq!(idx.offset_of_utf16(text, 1, 6), x);196 assert_eq!(idx.offset_of_utf16(text, 9, 0), text.len() as u32);197 }198199 #[test]200 fn diagnostic_serialises_compactly() {201 let d = Diagnostic::error("T3001", Span::new(0, 1, 4), "expected a duration").with_suggestion("write 1/4");202 let j = serde_json::to_string(&d).unwrap();203 assert!(j.contains("\"severity\":\"error\""));204 assert!(!j.contains("related"));205 assert_eq!(serde_json::from_str::<Diagnostic>(&j).unwrap(), d);206 }207}208