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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// SPDX-License-Identifier: CC0-1.0

//! Parsing Errors

use santiago::lexer::Lexeme;
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::{error, fmt, iter};

use crate::types;

use super::Position;

/// A set of errors found in a human-readable encoding of a Simplicity program.
#[derive(Clone, Debug, Default)]
pub struct ErrorSet {
    context: Option<Arc<str>>,
    line_map: Arc<Mutex<Vec<usize>>>,
    errors: BTreeMap<Option<Position>, Vec<Error>>,
}

impl<T> From<santiago::parser::ParseError<T>> for ErrorSet {
    fn from(e: santiago::parser::ParseError<T>) -> Self {
        let lex = e.at.map(|rc| (*rc).clone());
        match lex.as_ref().map(|lex| &lex.position).map(Position::from) {
            Some(pos) => ErrorSet::single(pos, Error::ParseFailed(lex)),
            None => ErrorSet::single_no_position(Error::ParseFailed(lex)),
        }
    }
}

impl From<santiago::lexer::LexerError> for ErrorSet {
    fn from(e: santiago::lexer::LexerError) -> Self {
        ErrorSet::single(e.position, Error::LexFailed(e.message))
    }
}

impl ErrorSet {
    /// Constructs a new empty error set.
    pub fn new() -> Self {
        ErrorSet::default()
    }

    /// Returns the first (and presumably most important) error in the set, if it
    /// is non-empty, along with its position.
    pub fn first_error(&self) -> Option<(Option<Position>, &Error)> {
        self.errors.iter().next().map(|(a, b)| (*a, &b[0]))
    }

    /// Return an iterator over the errors in the error set.
    pub fn iter(&self) -> impl Iterator<Item = &Error> {
        self.errors.values().flatten()
    }

    /// Constructs a new error set with a single error in it.
    pub fn single<P: Into<Position>, E: Into<Error>>(position: P, err: E) -> Self {
        let mut errors = BTreeMap::default();
        errors.insert(Some(position.into()), vec![err.into()]);
        ErrorSet {
            context: None,
            line_map: Arc::new(Mutex::new(vec![])),
            errors,
        }
    }

    /// Constructs a new error set with a single error in it.
    pub fn single_no_position<E: Into<Error>>(err: E) -> Self {
        let mut errors = BTreeMap::default();
        errors.insert(None, vec![err.into()]);
        ErrorSet {
            context: None,
            line_map: Arc::new(Mutex::new(vec![])),
            errors,
        }
    }

    /// Adds an error to the error set.
    pub fn add<P: Into<Position>, E: Into<Error>>(&mut self, position: P, err: E) {
        self.errors
            .entry(Some(position.into()))
            .or_default()
            .push(err.into());
    }

    /// Adds an error to the error set.
    pub fn add_no_position<E: Into<Error>>(&mut self, err: E) {
        self.errors.entry(None).or_default().push(err.into());
    }

    /// Merges another set of errors into the current set.
    ///
    /// # Panics
    ///
    /// Panics if the two sets have different contexts attached.
    pub fn merge(&mut self, other: &Self) {
        match (self.context.as_ref(), other.context.as_ref()) {
            (None, None) => {}
            (Some(_), None) => {}
            (None, Some(b)) => self.context = Some(Arc::clone(b)),
            (Some(a), Some(b)) => {
                assert_eq!(a, b, "cannot merge error sets for different source input");
            }
        };

        for (pos, errs) in &other.errors {
            self.errors
                .entry(*pos)
                .or_default()
                .extend(errs.iter().cloned());
        }
    }

    /// Attaches the input code to the error set, so that error messages can include
    /// line numbers etc.
    ///
    /// # Panics
    ///
    /// Panics if it is called twice on the same error set. You should call this once
    /// with the complete input code.
    pub fn add_context(&mut self, s: Arc<str>) {
        if self.context.is_some() {
            panic!("tried to add context to the same error context twice");
        }
        self.context = Some(s);
    }

    /// Returns a boolean indicating whether the set is empty.
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Returns the number of errors currently in the set.
    pub fn len(&self) -> usize {
        self.errors.len()
    }

    /// Converts the error set into a result.
    ///
    /// If the set is empty, returns Ok with the given value. Otherwise
    /// returns Err with itself.
    pub fn into_result<T>(self, ok: T) -> Result<T, Self> {
        if self.is_empty() {
            Ok(ok)
        } else {
            Err(self)
        }
    }

    /// Converts the error set into a result.
    ///
    /// If the set is empty, returns Ok with the result of calling the given closure.
    /// Otherwise returns Err with itself.
    pub fn into_result_with<T, F: FnOnce() -> T>(self, okfn: F) -> Result<T, Self> {
        if self.is_empty() {
            Ok(okfn())
        } else {
            Err(self)
        }
    }
}

impl error::Error for ErrorSet {
    fn cause(&self) -> Option<&(dyn error::Error + 'static)> {
        match self.first_error()?.1 {
            Error::Bad2ExpNumber(..) => None,
            Error::BadWordLength { .. } => None,
            Error::EntropyInsufficient { .. } => None,
            Error::EntropyTooMuch { .. } => None,
            Error::HoleAtCommitTime { .. } => None,
            Error::HoleFilledAtCommitTime => None,
            Error::NameIllegal(_) => None,
            Error::NameIncomplete(_) => None,
            Error::NameMissing(_) => None,
            Error::NameRepeated(_) => None,
            Error::NoMain => None,
            Error::ParseFailed(_) => None,
            Error::LexFailed(_) => None,
            Error::NumberOutOfRange(_) => None,
            Error::TypeCheck(ref e) => Some(e),
            Error::Undefined(_) => None,
            Error::UnknownJet(_) => None,
            Error::WitnessDisconnectRepeated { .. } => None,
        }
    }
}

impl fmt::Display for ErrorSet {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut line_map = self.line_map.lock().unwrap();
        if line_map.is_empty() {
            if let Some(ref s) = self.context {
                *line_map = iter::repeat(0)
                    .take(2)
                    .chain(
                        s.char_indices()
                            .filter_map(|(n, ch)| if ch == '\n' { Some(n) } else { None }),
                    )
                    .collect();
            }
        }

        for (pos, errs) in &self.errors {
            if let Some(pos) = pos {
                for err in errs {
                    if let Some(ref s) = self.context {
                        let end = line_map.get(pos.line + 1).copied().unwrap_or(s.len());
                        let line = &s[line_map[pos.line] + 1..end];
                        writeln!(f, "{:5} | {}", pos.line, line)?;
                        writeln!(f, "      | {:>width$}", "^", width = pos.column)?;
                        writeln!(f, "      \\-- {}", err)?;
                        writeln!(f)?;
                    } else {
                        writeln!(f, "{:4}:{:2}: {}", pos.line, pos.column, err,)?;
                        writeln!(f)?;
                    }
                }
            } else {
                for err in errs {
                    writeln!(f, "Error: {}", err)?;
                }
            }
        }
        Ok(())
    }
}

/// An individual error.
///
/// Generally this structure should not be used on its own, but only wrapped in an
/// [`ErrorSet`]. This is because in the human-readable encoding errors it is usually
/// possible to continue past individual errors, and the user would prefer to see as
/// many as possible at once.
#[derive(Clone, Debug)]
pub enum Error {
    /// A number of the form 2^y was used as a type but y was not an allowed value
    Bad2ExpNumber(u32),
    /// A constant word had a length which was not an allowable power of 2
    BadWordLength { bit_length: usize },
    /// A "fail" node was provided with less than 128 bits of entropy
    EntropyInsufficient { bit_length: usize },
    /// A "fail" node was provided with more than 512 bits of entropy
    EntropyTooMuch { bit_length: usize },
    /// When converting to a `CommitNode`, there were unfilled holes which prevent
    /// us from knowing the whole program.
    HoleAtCommitTime {
        name: Arc<str>,
        arrow: types::arrow::Arrow,
    },
    /// When converting to a `CommitNode`, a disconnect node had an actual node rather
    /// than a hole.
    HoleFilledAtCommitTime,
    /// An expression name was not allowed to be used as a name.
    NameIllegal(Arc<str>),
    /// An expression was given a type, but no actual expression was provided.
    NameIncomplete(Arc<str>),
    /// An expression was referenced but did not refer to anything.
    NameMissing(Arc<str>),
    /// An expression name was used for multiple expressions.
    NameRepeated(Arc<str>),
    /// Program did not have a `main` expression
    NoMain,
    /// Parsing failed (the parser provides us some extra information, but beyond
    /// the line and column, it does not seem very useful to a user, so we drop it).
    ParseFailed(Option<Lexeme>),
    /// Lexing failed; here santiago provides us an error message which is useful
    LexFailed(String),
    /// A number was parsed in some context but was out of range.
    NumberOutOfRange(String),
    /// Simplicity type-checking error
    TypeCheck(types::Error),
    /// Expression referred to an undefined symbol
    Undefined(String),
    /// A given jet is not a known jet
    UnknownJet(String),
    /// A witness or disconnect node was accessible from multiple paths.
    WitnessDisconnectRepeated { name: Arc<str>, count: usize },
}

impl From<types::Error> for Error {
    fn from(e: types::Error) -> Self {
        Error::TypeCheck(e)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::BadWordLength { bit_length } => {
                write!(f, "word length {} is not a valid power of 2", bit_length)
            }
            Error::Bad2ExpNumber(exp) => {
                write!(f, "types may be 2^n for n a power of 2, but not 2^{}", exp)
            }
            Error::EntropyInsufficient { bit_length } => write!(
                f,
                "fail node has insufficient entropy ({} bits, need 128)",
                bit_length
            ),
            Error::EntropyTooMuch { bit_length } => write!(
                f,
                "fail node has too much entropy ({} bits, max 512)",
                bit_length
            ),
            Error::HoleAtCommitTime {
                ref name,
                ref arrow,
            } => write!(
                f,
                "unfilled hole ?{} at commitment time; type arrow {}",
                name, arrow
            ),
            Error::HoleFilledAtCommitTime => {
                f.write_str("disconnect node has a non-hole child at commit time")
            }
            Error::NameIllegal(ref s) => {
                write!(f, "name `{}` is not allowed in this context", s)
            }
            Error::NameIncomplete(ref s) => write!(f, "name `{}` has no expression", s),
            Error::NameMissing(ref s) => {
                write!(f, "name `{}` is referred to but does not exist", s)
            }
            Error::NameRepeated(ref s) => write!(f, "name `{}` occured mulitple times", s),
            Error::NoMain => f.write_str("program does not define `main`"),
            Error::NumberOutOfRange(ref n) => {
                write!(f, "number {} was out of allowable range", n)
            }
            Error::ParseFailed(None) => f.write_str("could not parse"),
            Error::ParseFailed(Some(ref lex)) => write!(f, "could not parse `{}`", lex.raw),
            Error::LexFailed(ref msg) => write!(f, "could not parse: {}", msg),
            Error::TypeCheck(ref e) => fmt::Display::fmt(e, f),
            Error::Undefined(ref s) => write!(f, "reference to undefined symbol `{}`", s),
            Error::UnknownJet(ref s) => write!(f, "unknown jet `{}`", s),
            Error::WitnessDisconnectRepeated { ref name, count } => write!(
                f,
                "witness/disconnect node {} was accessible by {} distinct paths from the same root",
                name, count,
            ),
        }
    }
}