termosaic 0.3.0

Semantic, structured output for human, machine-text, and opaque-byte destinations
Documentation
use crate::{Doc, HumanText, TokenId, tokens};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ListKind {
    Ordered,
    Unordered,
}

#[derive(Clone, Debug)]
enum ListMarker {
    Ordered { start: u64, suffix: HumanText },
    Unordered(HumanText),
}

/// A semantic list with configurable markers and item separation.
#[derive(Clone, Debug)]
pub struct List {
    items: Vec<Doc>,
    marker: ListMarker,
    separator: Doc,
}

impl List {
    pub fn unordered(items: impl IntoIterator<Item = Doc>) -> Self {
        Self {
            items: items.into_iter().collect(),
            marker: ListMarker::Unordered(HumanText::sanitize("•")),
            separator: Doc::hard_line(),
        }
    }

    pub fn ordered(items: impl IntoIterator<Item = Doc>) -> Self {
        Self {
            items: items.into_iter().collect(),
            marker: ListMarker::Ordered {
                start: 1,
                suffix: HumanText::sanitize("."),
            },
            separator: Doc::hard_line(),
        }
    }

    pub fn marker(mut self, marker: impl AsRef<str>) -> Self {
        self.marker = ListMarker::Unordered(HumanText::sanitize(marker));
        self
    }

    pub fn start(mut self, start: u64) -> Self {
        let suffix = match self.marker {
            ListMarker::Ordered { suffix, .. } => suffix,
            ListMarker::Unordered(_) => HumanText::sanitize("."),
        };
        self.marker = ListMarker::Ordered { start, suffix };
        self
    }

    pub fn ordered_suffix(mut self, suffix: impl AsRef<str>) -> Self {
        let start = match self.marker {
            ListMarker::Ordered { start, .. } => start,
            ListMarker::Unordered(_) => 1,
        };
        self.marker = ListMarker::Ordered {
            start,
            suffix: HumanText::sanitize(suffix),
        };
        self
    }

    pub fn separator(mut self, separator: Doc) -> Self {
        self.separator = separator;
        self
    }

    pub fn kind(&self) -> ListKind {
        match self.marker {
            ListMarker::Ordered { .. } => ListKind::Ordered,
            ListMarker::Unordered(_) => ListKind::Unordered,
        }
    }

    pub fn into_doc(self) -> Result<Doc, ComponentError> {
        if self.items.is_empty() {
            return Ok(Doc::empty());
        }
        let kind = self.kind();
        let mut rendered = Vec::with_capacity(self.items.len());
        for (index, item) in self.items.into_iter().enumerate() {
            let marker = match &self.marker {
                ListMarker::Unordered(marker) => marker.as_str().to_owned(),
                ListMarker::Ordered { start, suffix } => {
                    let offset = u64::try_from(index).map_err(|_| {
                        ComponentError::OrderedListIndexOverflow {
                            start: *start,
                            index,
                        }
                    })?;
                    let ordinal = start.checked_add(offset).ok_or(
                        ComponentError::OrderedListIndexOverflow {
                            start: *start,
                            index,
                        },
                    )?;
                    format!("{ordinal}{}", suffix.as_str())
                }
            };
            let marker = Doc::token_text(tokens::LIST_MARKER, marker);
            let item = Doc::token(
                tokens::LIST_ITEM,
                Doc::concat([marker, Doc::text(" "), Doc::align(item)]),
            );
            rendered.push(item);
        }
        let body = Doc::join(self.separator, rendered);
        let kind = match kind {
            ListKind::Ordered => tokens::LIST_ORDERED,
            ListKind::Unordered => tokens::LIST_UNORDERED,
        };
        Ok(Doc::tokens([tokens::LIST, kind], body))
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PairKind {
    KeyValue,
    LabelValue,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PairLayout {
    Adaptive,
    Inline,
    Stacked,
}

/// A semantic key/value or human label/value pair.
#[derive(Clone, Debug)]
pub struct Pair {
    kind: PairKind,
    key: Doc,
    value: Doc,
    separator: Doc,
    layout: PairLayout,
    indent: u16,
}

impl Pair {
    pub fn key_value(key: Doc, value: Doc) -> Self {
        Self {
            kind: PairKind::KeyValue,
            key,
            value,
            separator: Doc::text("="),
            layout: PairLayout::Adaptive,
            indent: 2,
        }
    }

    pub fn label_value(label: Doc, value: Doc) -> Self {
        Self {
            kind: PairKind::LabelValue,
            key: label,
            value,
            separator: Doc::text(":"),
            layout: PairLayout::Adaptive,
            indent: 2,
        }
    }

    pub fn separator(mut self, separator: Doc) -> Self {
        self.separator = separator;
        self
    }

    pub fn layout(mut self, layout: PairLayout) -> Self {
        self.layout = layout;
        self
    }

    pub fn indent(mut self, indent: u16) -> Self {
        self.indent = indent;
        self
    }

    pub fn into_doc(self) -> Doc {
        let (kind, key_role) = match self.kind {
            PairKind::KeyValue => (tokens::PAIR_KEY_VALUE, tokens::PAIR_KEY),
            PairKind::LabelValue => (tokens::PAIR_LABEL_VALUE, tokens::PAIR_LABEL),
        };
        let key = Doc::token(key_role, self.key);
        let separator = Doc::token(tokens::PAIR_SEPARATOR, self.separator);
        let value = Doc::token(tokens::PAIR_VALUE, self.value);
        let boundary = match self.layout {
            PairLayout::Adaptive => Doc::line(),
            PairLayout::Inline => Doc::text(" "),
            PairLayout::Stacked => Doc::hard_line(),
        };
        let body = Doc::group(Doc::concat([
            key,
            separator,
            Doc::nest(self.indent, Doc::concat([boundary, value])),
        ]));
        Doc::tokens([tokens::PAIR, kind], body)
    }
}

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

impl DiagnosticLevel {
    pub const fn token(self) -> crate::TokenId {
        match self {
            Self::Note => tokens::DIAGNOSTIC_NOTE,
            Self::Info => tokens::DIAGNOSTIC_INFO,
            Self::Warning => tokens::DIAGNOSTIC_WARNING,
            Self::Error => tokens::DIAGNOSTIC_ERROR,
        }
    }

    pub const fn label(self) -> &'static str {
        match self {
            Self::Note => "note",
            Self::Info => "info",
            Self::Warning => "warning",
            Self::Error => "error",
        }
    }
}

/// A semantic diagnostic with optional code, details, and hints.
#[derive(Clone, Debug)]
pub struct Diagnostic {
    level_token: TokenId,
    label: Doc,
    message: Doc,
    code: Option<Doc>,
    details: Vec<Doc>,
    hints: Vec<Doc>,
    indent: u16,
}

impl Diagnostic {
    pub fn new(level: DiagnosticLevel, message: Doc) -> Self {
        Self {
            level_token: level.token(),
            label: Doc::text(level.label()),
            message,
            code: None,
            details: Vec::new(),
            hints: Vec::new(),
            indent: 2,
        }
    }

    pub fn note(message: Doc) -> Self {
        Self::new(DiagnosticLevel::Note, message)
    }

    pub fn info(message: Doc) -> Self {
        Self::new(DiagnosticLevel::Info, message)
    }

    pub fn warning(message: Doc) -> Self {
        Self::new(DiagnosticLevel::Warning, message)
    }

    pub fn error(message: Doc) -> Self {
        Self::new(DiagnosticLevel::Error, message)
    }

    pub fn label(mut self, label: Doc) -> Self {
        self.label = label;
        self
    }

    pub fn level_token(mut self, token: TokenId) -> Self {
        self.level_token = token;
        self
    }

    pub fn code(mut self, code: Doc) -> Self {
        self.code = Some(code);
        self
    }

    pub fn detail(mut self, detail: Doc) -> Self {
        self.details.push(detail);
        self
    }

    pub fn hint(mut self, hint: Doc) -> Self {
        self.hints.push(hint);
        self
    }

    pub fn indent(mut self, indent: u16) -> Self {
        self.indent = indent;
        self
    }

    pub fn into_doc(self) -> Doc {
        let mut prefix = vec![Doc::token(tokens::DIAGNOSTIC_LABEL, self.label)];
        if let Some(code) = self.code {
            prefix.extend([
                Doc::text("["),
                Doc::token(tokens::DIAGNOSTIC_CODE, code),
                Doc::text("]"),
            ]);
        }
        prefix.push(Doc::text(":"));
        prefix.push(Doc::nest(
            self.indent,
            Doc::concat([
                Doc::line(),
                Doc::token(tokens::DIAGNOSTIC_MESSAGE, self.message),
            ]),
        ));
        let mut parts = vec![Doc::group(Doc::concat(prefix))];
        for detail in self.details {
            parts.extend([
                Doc::hard_line(),
                Doc::nest(self.indent, Doc::token(tokens::DIAGNOSTIC_DETAIL, detail)),
            ]);
        }
        for hint in self.hints {
            let hint = Pair::label_value(Doc::text("hint"), hint)
                .indent(self.indent)
                .into_doc();
            parts.extend([
                Doc::hard_line(),
                Doc::nest(self.indent, Doc::token(tokens::DIAGNOSTIC_HINT, hint)),
            ]);
        }
        Doc::tokens([tokens::DIAGNOSTIC, self.level_token], Doc::concat(parts))
    }
}

#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum ComponentError {
    #[error("ordered list starting at {start} cannot represent item index {index}")]
    OrderedListIndexOverflow { start: u64, index: usize },
}