1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use crate::json::Value;
use std::fmt;
use std::rc::Rc;
/// A JS `invariant` failure (or another error JS throws), carrying the same
/// message. Invariants that only a bug in a node implementation can break
/// panic instead, as `RefCell` does; the ones a document can break return
/// this.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LexicalError {
message: String,
warning: Option<Rc<LexicalWarning>>,
}
impl LexicalError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
warning: None,
}
}
pub fn message(&self) -> &str {
&self.message
}
/// `warning` as the error `onWarn` receives, with its message.
pub fn from_warning(warning: LexicalWarning) -> Self {
Self {
message: warning.message.clone(),
warning: Some(Rc::new(warning)),
}
}
/// The [`LexicalWarning`] this error is, as JS's
/// `error instanceof LexicalWarning`.
pub fn warning(&self) -> Option<&LexicalWarning> {
self.warning.as_deref()
}
}
/// `LexicalWarning`: a warning with a stable code, passed to the editor's
/// `onWarn` (as the [`LexicalError`] [`LexicalError::from_warning`] makes,
/// whose [`warning`](LexicalError::warning) it is) by packages that report
/// recoverable, warn-level conditions. The code is namespaced by the package that reports it
/// (`"@example/pkg/some-condition"`); a `match` over codes needs a default
/// arm, since packages may add codes in any release.
#[derive(Clone, Debug, PartialEq)]
pub struct LexicalWarning {
/// What happened, namespaced by the package that reports it.
pub code: String,
/// For people; it may change.
pub message: String,
/// Details for programs, documented with each code.
pub data: Option<Value>,
}
impl Eq for LexicalWarning {}
impl LexicalWarning {
/// `name`.
pub const NAME: &'static str = "LexicalWarning";
/// `new LexicalWarning(code, message, data)`.
pub fn new(code: impl Into<String>, message: impl Into<String>, data: Option<Value>) -> Self {
Self {
code: code.into(),
message: message.into(),
data,
}
}
}
impl fmt::Display for LexicalWarning {
/// `String(warning)`: `LexicalWarning: <message>`.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", Self::NAME, self.message)
}
}
impl std::error::Error for LexicalWarning {}
impl fmt::Display for LexicalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for LexicalError {}
/// `invariant(cond, message, ...args)`: returns a [`LexicalError`] from the
/// enclosing function unless `cond` holds.
macro_rules! invariant {
($cond:expr, $($message:tt)+) => {
if !$cond {
return Err($crate::LexicalError::new(format!($($message)+)));
}
};
}
pub(crate) use invariant;