Skip to main content

text_document/
error.rs

1//! The public error type for the `text-document` API.
2//!
3//! Every fallible public function returns [`Result<T>`], i.e.
4//! `Result<T, DocumentError>`. Unlike the previous opaque
5//! `anyhow::Result`, callers can now match on [`DocumentError`] to react
6//! to specific failure categories (a cursor used outside a table, a
7//! lookup that found nothing, an out-of-range index, …).
8//!
9//! Errors originating deep inside the backend crates arrive as
10//! [`DocumentError::Internal`] via the `From<anyhow::Error>` bridge, so
11//! propagation with `?` continues to work unchanged.
12
13use thiserror::Error;
14
15/// Errors returned by the public `text-document` API.
16///
17/// The `Display` text is the original human-readable message (for
18/// [`TransientEdits`](DocumentError::TransientEdits), its reason's); the variant
19/// carries the machine-matchable category. Marked `#[non_exhaustive]` so
20/// new categories can be added without breaking callers — match with a
21/// `_` arm.
22#[derive(Debug, Error)]
23#[non_exhaustive]
24pub enum DocumentError {
25    /// A referenced entity (block, cell, document, …) does not exist.
26    #[error("{0}")]
27    NotFound(String),
28
29    /// An operation was attempted with the cursor in the wrong structural
30    /// context (e.g. a table operation while not inside a table).
31    #[error("{0}")]
32    InvalidCursorContext(String),
33
34    /// An index or position was outside the valid range.
35    #[error("{0}")]
36    OutOfRange(String),
37
38    /// The arguments were individually valid but invalid in combination
39    /// (e.g. a selection spanning multiple frames, mismatched tables).
40    #[error("{0}")]
41    InvalidArgument(String),
42
43    /// The requested operation is not available in this build — e.g. [`crate::TextDocument::to_pdf`]
44    /// called against a `text-document` build that did not enable the `pdf` cargo feature.
45    #[error("{0}")]
46    Unsupported(String),
47
48    /// Refused because of the document's [transient edits](crate::transient): the
49    /// [`TransientRefusal`] says which case it is.
50    #[error("{0}")]
51    TransientEdits(TransientRefusal),
52
53    /// Any other error propagated from the backend layers.
54    #[error(transparent)]
55    Internal(anyhow::Error),
56}
57
58/// Why the document's [transient edits](crate::transient) refused an operation
59/// ([`DocumentError::TransientEdits`]). Marked `#[non_exhaustive]`: match with a `_` arm.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
61#[non_exhaustive]
62pub enum TransientRefusal {
63    /// A transient edit whose selection a removal would not take as it stands: one across a
64    /// table's cells, or one holding part of a table and text outside it, which
65    /// [`TextCursor::set_position`](crate::TextCursor::set_position) never leaves but
66    /// another cursor's edit can
67    /// ([`TextCursor::insert_text_transient`](crate::TextCursor::insert_text_transient) and
68    /// its siblings). Nothing changes.
69    #[error(
70        "a transient edit must change one run of text: this selection crosses a table's \
71         cells, or holds part of a table and text outside it"
72    )]
73    CrossesTableCells,
74    /// A transient edit while a load in place
75    /// ([`TextDocument::set_djot`](crate::TextDocument::set_djot) and its siblings) is still
76    /// writing the document. Nothing changes.
77    #[error("a load in place is writing the document: no transient edit is made until it ends")]
78    LoadInPlace,
79    /// A transient edit while another write to the document's store is open, which the
80    /// store refuses so that the recorded content the transient edits are made over is
81    /// whole. The one write of this document left open across its calls is a load in place,
82    /// reported as [`LoadInPlace`](Self::LoadInPlace) before the store is asked; this is the
83    /// store's own refusal of any other. Nothing changes.
84    #[error("a write to the document is in progress: no transient edit is made until it ends")]
85    WriteInProgress,
86    /// A commit of transient edits made in more than one place, which would replace the
87    /// recorded text between them as well
88    /// ([`TextCursor::commit_transient_text`](crate::TextCursor::commit_transient_text)).
89    /// The transient edits stay as they were.
90    #[error(
91        "the transient edits changed the document in more than one place: committing them \
92         would replace the recorded text between them"
93    )]
94    CommitInSeveralPlaces,
95    /// A [`TextCursor::replace`](crate::TextCursor::replace) whose range held only
96    /// transient text: the revert it begins with took that text away, and nothing is
97    /// replaced.
98    #[error("the range held only transient text, which was reverted: nothing to replace")]
99    RangeOfTransientTextOnly,
100    /// A recorded write that found transient edits outstanding when it began, which the
101    /// document's store refuses before anything is written. Every write this crate offers
102    /// reverts them first, so they were made since, by another thread between that revert
103    /// and the write. Nothing is recorded, and an open edit block keeps what it holds.
104    #[error(
105        "transient edits are outstanding: the document's store refuses a recorded write over them"
106    )]
107    LayerOutstanding,
108}
109
110impl From<anyhow::Error> for DocumentError {
111    /// [`DocumentError::Internal`], except for the store's refusals anywhere in the error's
112    /// chain: a write over outstanding transient edits is
113    /// [`TransientRefusal::LayerOutstanding`], a transient write refused is
114    /// [`TransientRefusal::WriteInProgress`].
115    fn from(error: anyhow::Error) -> Self {
116        use common::database::rope_store::{TransientEditsOutstanding, TransientWriteRefused};
117        for cause in error.chain() {
118            if cause.downcast_ref::<TransientEditsOutstanding>().is_some() {
119                return DocumentError::TransientEdits(TransientRefusal::LayerOutstanding);
120            }
121            if let Some(refused) = cause.downcast_ref::<TransientWriteRefused>() {
122                return DocumentError::TransientEdits((*refused).into());
123            }
124        }
125        DocumentError::Internal(error)
126    }
127}
128
129impl From<common::database::rope_store::TransientWriteRefused> for TransientRefusal {
130    /// The store's refusal to begin a transient write. Both of its cases are another write
131    /// in progress on the store: a transient one (which the document's lock keeps from
132    /// happening) or a recorded one.
133    fn from(_: common::database::rope_store::TransientWriteRefused) -> Self {
134        TransientRefusal::WriteInProgress
135    }
136}
137
138/// Result alias used throughout the public API.
139pub type Result<T> = std::result::Result<T, DocumentError>;