dbt-antlr-codegen 0.10.0

ANTLR v4 grammar compiler and Rust source generator
Documentation
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Konstantin Vyatkin
use std::fmt;
use std::io;
use std::ops::Range;
use std::path::PathBuf;

/// Broad category of a generator failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
    Configuration,
    Compilation,
    Generation,
    Filesystem,
}

/// Severity of one grammar diagnostic.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Severity {
    Warning,
    Error,
}

/// A grammar compiler diagnostic.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Diagnostic {
    code: &'static str,
    severity: Severity,
    message: String,
    path: PathBuf,
    line: Option<usize>,
    column: Option<usize>,
    byte_span: Option<Range<usize>>,
}

impl Diagnostic {
    #[cfg(feature = "generator")]
    pub(crate) fn new(
        code: &'static str,
        severity: Severity,
        message: String,
        path: PathBuf,
        position: Option<(usize, usize)>,
        byte_span: Option<Range<usize>>,
    ) -> Self {
        Self {
            code,
            severity,
            message,
            path,
            line: position.map(|(line, _)| line),
            column: position.map(|(_, column)| column),
            byte_span,
        }
    }

    pub const fn code(&self) -> &'static str {
        self.code
    }

    pub const fn severity(&self) -> Severity {
        self.severity
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    pub fn path(&self) -> &std::path::Path {
        &self.path
    }

    pub const fn line(&self) -> Option<usize> {
        self.line
    }

    pub const fn column(&self) -> Option<usize> {
        self.column
    }

    /// Half-open UTF-8 byte range of the primary subject within [`Self::path`].
    ///
    /// Returns `None` when the diagnostic has no source-backed primary subject.
    pub fn byte_span(&self) -> Option<Range<usize>> {
        self.byte_span.clone()
    }
}

/// Shows the diagnostic as `warning[G4S078]: path:line:column: message`, the
/// format that the command line writes to stderr.
impl fmt::Display for Diagnostic {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let severity = match self.severity {
            Severity::Warning => "warning",
            Severity::Error => "error",
        };
        write!(
            formatter,
            "{severity}[{}]: {}",
            self.code,
            self.path.display()
        )?;
        if let (Some(line), Some(column)) = (self.line, self.column) {
            write!(formatter, ":{line}:{column}")?;
        }
        write!(formatter, ": {}", self.message)
    }
}

/// Structured error returned by the emission entry points.
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    message: String,
    diagnostics: Vec<Diagnostic>,
    source: Option<io::Error>,
}

impl Error {
    #[cfg(feature = "generator")]
    pub(crate) const fn compilation(message: String, diagnostics: Vec<Diagnostic>) -> Self {
        Self {
            kind: ErrorKind::Compilation,
            message,
            diagnostics,
            source: None,
        }
    }

    pub(crate) fn generation(source: io::Error) -> Self {
        let kind = if matches!(
            source.kind(),
            io::ErrorKind::NotFound
                | io::ErrorKind::PermissionDenied
                | io::ErrorKind::AlreadyExists
                | io::ErrorKind::ReadOnlyFilesystem
        ) {
            ErrorKind::Filesystem
        } else {
            ErrorKind::Generation
        };
        Self {
            kind,
            message: source.to_string(),
            diagnostics: Vec::new(),
            source: Some(source),
        }
    }

    pub const fn kind(&self) -> ErrorKind {
        self.kind
    }

    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_ref()
            .map(|source| -> &(dyn std::error::Error + 'static) { source })
    }
}

impl From<io::Error> for Error {
    fn from(source: io::Error) -> Self {
        Self::generation(source)
    }
}

/// Errors of the emission layer.
#[derive(Debug, thiserror::Error)]
pub enum EmitError {
    /// The grammar failed to compile.
    #[cfg(feature = "generator")]
    #[error("grammar compilation failed: {0}")]
    Compile(#[from] Error),
    /// The template failed to load or render.
    #[cfg(feature = "generator")]
    #[error("template rendering failed: {0}")]
    Template(#[from] minijinja::Error),
    /// The grammar uses a construct the emission layer does not support
    /// yet (left recursion, embedded actions, sempreds, labels).
    #[cfg(feature = "generator")]
    #[error("unsupported grammar construct: {0}")]
    Unsupported(String),
    /// The generator configuration is invalid.
    #[error("invalid generator configuration: {0}")]
    Config(String),
    /// A pinned release binary could not be downloaded, verified, or run.
    #[cfg(feature = "download")]
    #[error("pinned release binary failed: {0}")]
    Download(String),
    /// An output directory or file could not be written.
    #[error("cannot write {path}: {source}")]
    Write {
        /// Path that could not be written.
        path: PathBuf,
        /// Underlying I/O error.
        source: io::Error,
    },
}