lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
Documentation
//! Source-oriented diagnostics derived from workspace compilation failures.
//!
//! Diagnostic codes are short stage-prefixed identifiers such as `L0001` and
//! `P0001`. Locations are calculated from UTF-8 byte [`Span`] values. Message
//! text is human-readable and may evolve before the first public release.

use crate::{parsing::Span, runtime::WorkspaceError};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    Error,
    Warning,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceLocation {
    pub line: usize,
    pub column: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticLabel {
    pub path: String,
    pub span: Span,
    pub start: Option<SourceLocation>,
    pub end: Option<SourceLocation>,
    pub message: Option<String>,
    pub primary: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    pub severity: DiagnosticSeverity,
    pub code: &'static str,
    pub message: String,
    pub labels: Vec<DiagnosticLabel>,
    pub notes: Vec<String>,
    pub help: Vec<String>,
}

impl Diagnostic {
    pub fn error(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            severity: DiagnosticSeverity::Error,
            code,
            message: message.into(),
            labels: Vec::new(),
            notes: Vec::new(),
            help: Vec::new(),
        }
    }

    pub fn with_primary(
        mut self,
        path: impl Into<String>,
        span: Span,
        source: Option<&str>,
        message: impl Into<Option<String>>,
    ) -> Self {
        let (start, end) = source
            .map(|source| {
                (
                    location(source, span.start as usize),
                    location(source, span.end as usize),
                )
            })
            .map_or((None, None), |(start, end)| (Some(start), Some(end)));
        self.labels.push(DiagnosticLabel {
            path: path.into(),
            span,
            start,
            end,
            message: message.into(),
            primary: true,
        });
        self
    }

    pub fn with_secondary(
        mut self,
        path: impl Into<String>,
        span: Span,
        source: Option<&str>,
        message: impl Into<Option<String>>,
    ) -> Self {
        let (start, end) = source
            .map(|source| {
                (
                    location(source, span.start as usize),
                    location(source, span.end as usize),
                )
            })
            .map_or((None, None), |(start, end)| (Some(start), Some(end)));
        self.labels.push(DiagnosticLabel {
            path: path.into(),
            span,
            start,
            end,
            message: message.into(),
            primary: false,
        });
        self
    }
}

impl WorkspaceError {
    /// Converts this workspace error into source labels and user-facing notes.
    ///
    /// `fallback_path` and `source` are used when an internal error contains no
    /// complete source context.
    pub fn diagnostics(
        &self,
        fallback_path: Option<&str>,
        source: Option<&str>,
    ) -> Vec<Diagnostic> {
        workspace_error_diagnostics(self, fallback_path, source)
    }
}

/// Converts one workspace error into zero or more structured diagnostics.
pub fn workspace_error_diagnostics(
    error: &WorkspaceError,
    fallback_path: Option<&str>,
    source: Option<&str>,
) -> Vec<Diagnostic> {
    match error {
        WorkspaceError::Parse(failure) => {
            failure
                .lexical
                .iter()
                .map(|error| {
                    Diagnostic::error("L0001", format!("lexical error: {:?}", error.kind))
                        .with_primary(&failure.path, error.span, source, None)
                })
                .chain(failure.syntactic.iter().map(|error| {
                    Diagnostic::error("P0001", error.message.clone()).with_primary(
                        &failure.path,
                        error.span,
                        source,
                        None,
                    )
                }))
                .collect()
        }
        WorkspaceError::Body(errors) => errors
            .iter()
            .map(|error| {
                let diagnostic = Diagnostic::error("S0001", error.to_string());
                match (fallback_path, error.span()) {
                    (Some(path), Some(span)) => diagnostic.with_primary(path, span, source, None),
                    _ => diagnostic,
                }
            })
            .collect(),
        WorkspaceError::MissingScript { requested_by, path } => vec![Diagnostic::error(
            "M0001",
            format!("module `{requested_by}` requires missing source `{path}`"),
        )],
        WorkspaceError::Module(error) => {
            vec![Diagnostic::error("M0002", error.to_string())]
        }
        WorkspaceError::Dependencies(errors) => errors
            .iter()
            .map(|error| Diagnostic::error("M0003", error.to_string()))
            .collect(),
        WorkspaceError::RustTypes(errors) => errors
            .iter()
            .map(|error| {
                let mut diagnostic = Diagnostic::error("T0002", error.to_string());
                let (module, type_span, variant_span) = match error {
                    crate::rust_lib::RustTypeRegistrationError::MissingExportedVariant {
                        module,
                        type_span,
                        ..
                    } => (module, *type_span, None),
                    crate::rust_lib::RustTypeRegistrationError::UnregisteredContractVariant {
                        module,
                        type_span,
                        variant_span,
                        ..
                    }
                    | crate::rust_lib::RustTypeRegistrationError::VariantPayloadTypeMismatch {
                        module,
                        type_span,
                        variant_span,
                        ..
                    } => (module, *type_span, Some(*variant_span)),
                    _ => return diagnostic,
                };
                if fallback_path == Some(module.as_str()) {
                    diagnostic = diagnostic.with_primary(
                        module,
                        type_span,
                        source,
                        Some("native enum contract does not match Rust registration".into()),
                    );
                    if let Some(variant_span) = variant_span {
                        diagnostic = diagnostic.with_secondary(
                            module,
                            variant_span,
                            source,
                            Some("mismatching enum variant".into()),
                        );
                    }
                }
                diagnostic
            })
            .collect(),
        WorkspaceError::TypeMetadata(errors) => errors
            .iter()
            .map(|error| match error {
                crate::runtime::TypeMetadataError::InvalidNativeLayout {
                    path,
                    span,
                    variant_span,
                    reason,
                } => {
                    let mut diagnostic = Diagnostic::error("T0001", error.to_string());
                    if fallback_path == Some(path.module.as_str()) {
                        if let Some(span) = span {
                            diagnostic = diagnostic.with_primary(
                                &path.module,
                                *span,
                                source,
                                Some(format!("invalid native layout metadata: {reason}")),
                            );
                        }
                        if let Some(variant_span) = variant_span {
                            diagnostic = diagnostic.with_secondary(
                                &path.module,
                                *variant_span,
                                source,
                                Some("this variant participates in the invalid layout".into()),
                            );
                        }
                    }
                    diagnostic
                }
                _ => Diagnostic::error("T0001", error.to_string()),
            })
            .collect(),
        WorkspaceError::Jit(error) => vec![Diagnostic::error("J0001", error.to_string())],
        _ => vec![Diagnostic::error("R0001", error.to_string())],
    }
}

fn location(source: &str, offset: usize) -> SourceLocation {
    let mut offset = offset.min(source.len());
    while !source.is_char_boundary(offset) {
        offset -= 1;
    }
    let prefix = &source[..offset];
    let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
    let column = prefix
        .rsplit_once('\n')
        .map_or(prefix.chars().count(), |(_, line)| line.chars().count())
        + 1;
    SourceLocation { line, column }
}

#[cfg(test)]
mod tests {
    use crate::{
        parsing::{SourceFile, Span, parse_file},
        runtime::{
            DiagnosticSeverity, NativeLayoutErrorKind, SourceLocation, TypeMetadataError,
            WorkspaceError, workspace_error_diagnostics,
        },
        semantic::{BodyAnalysisError, CanonicalSymbolPath},
    };

    #[test]
    fn parse_diagnostic_contains_path_span_and_line_column() {
        let source = "pub acs run: fn() -> i32 {\n    return @\n}";
        let error = WorkspaceError::Parse(
            parse_file(SourceFile {
                path: "engine://scripts/main.lt",
                text: source,
            })
            .unwrap_err(),
        );
        let diagnostics = workspace_error_diagnostics(&error, None, Some(source));
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].severity, DiagnosticSeverity::Error);
        let label = &diagnostics[0].labels[0];
        assert_eq!(label.path, "engine://scripts/main.lt");
        assert_eq!(label.start.unwrap().line, 2);
    }

    #[test]
    fn native_layout_diagnostic_labels_the_type_contract() {
        let source = "pub acs Broken: enum { var First var Second }";
        let span = Span::new(0, source.len() as u32);
        let variant_start = source.find("var Second").unwrap() as u32;
        let variant_span = Span::new(variant_start, variant_start + "var Second".len() as u32);
        let error = WorkspaceError::TypeMetadata(vec![TypeMetadataError::InvalidNativeLayout {
            path: CanonicalSymbolPath {
                module: "native://broken.lt".into(),
                local: "Broken".into(),
            },
            span: Some(span),
            variant_span: Some(variant_span),
            reason: NativeLayoutErrorKind::DuplicateTag { tag: 0 },
        }]);
        let diagnostics = error.diagnostics(Some("native://broken.lt"), Some(source));
        assert_eq!(diagnostics[0].code, "T0001");
        assert!(diagnostics[0].message.contains("duplicate physical tag 0"));
        let label = &diagnostics[0].labels[0];
        assert_eq!(label.path, "native://broken.lt");
        assert_eq!(label.span, span);
        assert_eq!(label.start.unwrap(), SourceLocation { line: 1, column: 1 });
        assert!(
            label
                .message
                .as_deref()
                .unwrap()
                .contains("duplicate physical tag 0")
        );
        let secondary = &diagnostics[0].labels[1];
        assert!(!secondary.primary);
        assert_eq!(secondary.span, variant_span);
    }

    #[test]
    fn rust_enum_contract_diagnostic_labels_the_type_and_variant() {
        let source = "pub acs Native: enum {\n    var Empty\n    var Value u8\n}";
        let type_span = Span::new(0, source.len() as u32);
        let start = source.find("var Value u8").unwrap() as u32;
        let variant_span = Span::new(start, start + "var Value u8".len() as u32);
        let error = WorkspaceError::RustTypes(vec![
            crate::rust_lib::RustTypeRegistrationError::VariantPayloadTypeMismatch {
                module: "native://contract.lt".into(),
                type_: "Native".into(),
                variant: "Value".into(),
                type_span,
                variant_span,
            },
        ]);
        let diagnostics = error.diagnostics(Some("native://contract.lt"), Some(source));
        assert_eq!(diagnostics[0].code, "T0002");
        assert_eq!(diagnostics[0].labels.len(), 2);
        assert!(diagnostics[0].labels[0].primary);
        assert!(!diagnostics[0].labels[1].primary);
        assert_eq!(diagnostics[0].labels[1].span, variant_span);
        assert_eq!(diagnostics[0].labels[1].start.unwrap().line, 3);
    }

    #[test]
    fn semantic_diagnostic_uses_fallback_module_source_context() {
        let source = "let value: i32\nreturn value";
        let error = WorkspaceError::Body(vec![BodyAnalysisError::UninitializedLocal {
            name: "value".into(),
            span: Span::new(22, 27),
        }]);
        let diagnostics = error.diagnostics(Some("engine://main.lt"), Some(source));
        assert_eq!(diagnostics[0].code, "S0001");
        assert!(diagnostics[0].message.contains("value"));
        let label = &diagnostics[0].labels[0];
        assert_eq!(label.path, "engine://main.lt");
        assert_eq!(label.start.unwrap().line, 2);
    }
}