Skip to main content

carve/
render_carve_error.rs

1//! Typed refusals from the canonical Carve writer.
2
3use std::cell::{Cell, RefCell};
4use std::fmt;
5
6/// The canonical writer cannot spell an AST node without changing it.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct SourceUnspellable {
9    node_type: &'static str,
10    reason: &'static str,
11}
12
13impl SourceUnspellable {
14    pub(crate) fn new(node_type: &'static str, reason: &'static str) -> Self {
15        Self { node_type, reason }
16    }
17
18    /// AST node type the writer could not spell.
19    pub fn node_type(&self) -> &'static str {
20        self.node_type
21    }
22    /// Stable reason for the refusal.
23    pub fn reason(&self) -> &'static str {
24        self.reason
25    }
26}
27
28impl fmt::Display for SourceUnspellable {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        write!(
31            f,
32            "the Carve renderer cannot spell {}: {}",
33            self.node_type, self.reason
34        )
35    }
36}
37
38impl std::error::Error for SourceUnspellable {}
39
40/// A typed reason the canonical Carve writer refused a tree.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum RenderCarveError {
43    /// Tree nesting exceeded the writer's depth limit.
44    Depth(crate::RenderDepthError),
45    /// A tree shape has no faithful Carve source spelling.
46    SourceUnspellable(SourceUnspellable),
47}
48
49impl fmt::Display for RenderCarveError {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self {
52            Self::Depth(error) => error.fmt(f),
53            Self::SourceUnspellable(error) => error.fmt(f),
54        }
55    }
56}
57
58impl std::error::Error for RenderCarveError {
59    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
60        match self {
61            Self::Depth(error) => Some(error),
62            Self::SourceUnspellable(error) => Some(error),
63        }
64    }
65}
66
67impl From<crate::RenderDepthError> for RenderCarveError {
68    fn from(error: crate::RenderDepthError) -> Self {
69        Self::Depth(error)
70    }
71}
72
73/// Why the canonical Carve writer produced no source.
74///
75/// `--carve` and `carve fmt` parse and re-serialize a whole document, so they
76/// can be stopped by the profile the options carry OR by the writer itself. The
77/// writer's refusal used to be unwrapped with an `expect` claiming a parsed tree
78/// never reaches it. That claim holds for the DEPTH ceiling, which sits above
79/// the parse cap, and not for a round-trip refusal: one level past the cap the
80/// over-cap flattening hands the writer a code node whose value carries the
81/// ladder's indentation, which the block layer strips on the way back out, and
82/// the CLI aborted with exit 101 on valid input (carve-rs#2326).
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub enum CarveWriteError {
85    /// The profile refused a node, or the source exceeded its `max_length`.
86    Profile(crate::ProfileViolationError),
87    /// The writer cannot spell the tree the parser built.
88    Render(RenderCarveError),
89}
90
91impl fmt::Display for CarveWriteError {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        match self {
94            Self::Profile(error) => error.fmt(f),
95            Self::Render(error) => error.fmt(f),
96        }
97    }
98}
99
100impl std::error::Error for CarveWriteError {
101    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
102        match self {
103            Self::Profile(error) => Some(error),
104            Self::Render(error) => Some(error),
105        }
106    }
107}
108
109impl From<crate::ProfileViolationError> for CarveWriteError {
110    fn from(error: crate::ProfileViolationError) -> Self {
111        Self::Profile(error)
112    }
113}
114
115impl From<RenderCarveError> for CarveWriteError {
116    fn from(error: RenderCarveError) -> Self {
117        Self::Render(error)
118    }
119}
120
121thread_local! {
122    static UNSPELLABLE: Cell<Option<(&'static str, &'static str)>> = const { Cell::new(None) };
123    static NESTED_SAME_KIND: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) };
124}
125
126/// The inner spans of an unspellable same-kind nesting, for the HTML importer.
127pub(crate) fn record_nested_same_kind(spans: Vec<usize>) {
128    NESTED_SAME_KIND.with(|cell| cell.borrow_mut().extend(spans));
129}
130
131pub(crate) fn take_nested_same_kind() -> Vec<usize> {
132    NESTED_SAME_KIND.with(|cell| std::mem::take(&mut *cell.borrow_mut()))
133}
134
135pub(crate) fn clear_unspellable() {
136    UNSPELLABLE.with(|cell| cell.set(None));
137}
138
139pub(crate) fn record_unspellable(node_type: &'static str, reason: &'static str) {
140    UNSPELLABLE.with(|cell| {
141        if cell.get().is_none() {
142            cell.set(Some((node_type, reason)));
143        }
144    });
145}
146
147pub(crate) fn record_unspellable_list_nesting(reason: &'static str) {
148    // The parse cap is the document-level refusal even if a child failed first.
149    UNSPELLABLE.with(|cell| cell.set(Some(("document", reason))));
150}
151
152pub(crate) struct SourceSpellWatch {
153    previous: Option<(&'static str, &'static str)>,
154}
155
156impl SourceSpellWatch {
157    pub(crate) fn new() -> Self {
158        NESTED_SAME_KIND.with(|cell| cell.borrow_mut().clear());
159        Self {
160            previous: UNSPELLABLE.with(|cell| cell.replace(None)),
161        }
162    }
163
164    pub(crate) fn error(&self) -> Option<RenderCarveError> {
165        UNSPELLABLE.with(|cell| {
166            cell.get().map(|(node_type, reason)| {
167                RenderCarveError::SourceUnspellable(SourceUnspellable::new(node_type, reason))
168            })
169        })
170    }
171}
172
173impl Drop for SourceSpellWatch {
174    fn drop(&mut self) {
175        UNSPELLABLE.with(|cell| cell.set(self.previous));
176    }
177}