erg_parser/
error.rs

1//! defines `ParseError` and others.
2//!
3//! パーサーが出すエラーを定義
4use std::fmt;
5
6use erg_common::error::{
7    ErrorCore, ErrorDisplay, ErrorKind::*, Location, MultiErrorDisplay, SubMessage,
8};
9use erg_common::io::Input;
10use erg_common::style::{Attribute, Color, StyledStr, StyledString, StyledStrings, THEME};
11use erg_common::traits::Stream;
12use erg_common::{fmt_iter, fmt_vec_split_with, impl_display_and_error, impl_stream, switch_lang};
13
14use crate::ast::Module;
15use crate::token::TokenKind;
16
17#[derive(Debug)]
18pub struct LexError(Box<ErrorCore>); // ErrorCore is large, so use Box
19
20impl fmt::Display for LexError {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        write!(f, "LexError({})", self.0)
23    }
24}
25
26impl std::error::Error for LexError {}
27
28#[cfg(feature = "pylib")]
29impl std::convert::From<LexError> for pyo3::PyErr {
30    fn from(err: LexError) -> pyo3::PyErr {
31        pyo3::exceptions::PyOSError::new_err(err.to_string())
32    }
33}
34
35impl From<ErrorCore> for LexError {
36    fn from(core: ErrorCore) -> Self {
37        Self(Box::new(core))
38    }
39}
40
41impl From<LexError> for ErrorCore {
42    fn from(err: LexError) -> Self {
43        *err.0
44    }
45}
46
47impl LexError {
48    pub fn loc(&self) -> Location {
49        self.0.loc
50    }
51}
52
53#[cfg_attr(feature = "pylib", pyo3::pyclass)]
54#[derive(Debug)]
55pub struct LexErrors(Vec<LexError>);
56
57impl_stream!(LexErrors, LexError);
58
59impl fmt::Display for LexErrors {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        write!(f, "LexErrors({})", fmt_iter(self.0.iter()))
62    }
63}
64
65impl std::error::Error for LexErrors {}
66
67#[cfg(feature = "pylib")]
68impl std::convert::From<LexErrors> for pyo3::PyErr {
69    fn from(errs: LexErrors) -> pyo3::PyErr {
70        pyo3::exceptions::PyOSError::new_err(errs[0].to_string())
71    }
72}
73
74const ERR: Color = THEME.colors.error;
75const WARN: Color = THEME.colors.warning;
76const HINT: Color = THEME.colors.hint;
77#[cfg(not(feature = "pretty"))]
78const ATTR: Attribute = Attribute::Bold;
79#[cfg(feature = "pretty")]
80const ATTR: Attribute = Attribute::Underline;
81
82impl LexError {
83    pub fn new(core: ErrorCore) -> Self {
84        Self(Box::new(core))
85    }
86
87    pub fn set_hint<S: Into<String>>(&mut self, hint: S) {
88        if let Some(sub_msg) = self.0.sub_messages.get_mut(0) {
89            sub_msg.set_hint(hint)
90        }
91    }
92
93    /* Parser Bug */
94    pub fn compiler_bug(errno: usize, loc: Location, fn_name: &str, line: u32) -> Self {
95        let mut err = Self::new(ErrorCore::bug(errno, loc, fn_name, line));
96        err.set_hint("parser bug");
97        err
98    }
99
100    pub fn feature_error(errno: usize, loc: Location, name: &str) -> Self {
101        let main_msg = switch_lang!(
102            "japanese" => format!("この機能({name})はまだ正式に提供されていません"),
103            "simplified_chinese" => format!("此功能({name})尚未实现"),
104            "traditional_chinese" => format!("此功能({name})尚未實現"),
105            "english" => format!("this feature({name}) is not implemented yet"),
106        );
107        let main_msg = StyledStr::new(&main_msg, Some(ERR), Some(ATTR)).to_string();
108        Self::new(ErrorCore::new(
109            vec![SubMessage::only_loc(loc)],
110            main_msg,
111            errno,
112            FeatureError,
113            loc,
114        ))
115    }
116
117    pub fn invalid_none_match(errno: usize, loc: Location, fn_name: &str, line: u32) -> Self {
118        let mut err = Self::new(ErrorCore::bug(errno, loc, fn_name, line));
119        err.set_hint("None is got");
120        err
121    }
122
123    pub fn failed_to_analyze_block(errno: usize, loc: Location) -> LexError {
124        Self::new(ErrorCore::new(
125            vec![],
126            switch_lang!(
127                "japanese" => "ブロックの解析に失敗しました",
128                "simplified_chinese" => "无法解析块",
129                "traditional_chinese" => "無法解析塊",
130                "english" => "failed to parse a block",
131            ),
132            errno,
133            CompilerSystemError,
134            loc,
135        ))
136    }
137
138    pub fn unexpected_token_error(errno: usize, loc: Location, found: &str) -> ParseError {
139        let mut fnd = StyledStrings::default();
140        switch_lang!(
141            "japanese" =>fnd.push_str("予期しないトークンです: "),
142            "simplified_chinese" => fnd.push_str("意外的token: "),
143            "traditional_chinese" => fnd.push_str("意外的token: "),
144            "english" => fnd.push_str("unexpected token: "),
145        );
146        fnd.push_str_with_color(found, ERR);
147        let main_msg = switch_lang!(
148            "japanese" => "無効な構文です",
149            "simplified_chinese" => "无效的语法",
150            "traditional_chinese" => "無效的語法",
151            "english" => "invalid syntax",
152        );
153        Self::new(ErrorCore::new(
154            vec![SubMessage::ambiguous_new(loc, vec![fnd.to_string()], None)],
155            main_msg,
156            errno,
157            CompilerSystemError,
158            loc,
159        ))
160    }
161
162    /* Parser Errors */
163    pub fn simple_syntax_error(errno: usize, loc: Location) -> Self {
164        Self::new(ErrorCore::new(
165            vec![SubMessage::only_loc(loc)],
166            switch_lang!(
167                "japanese" => "不正な構文です",
168                "simplified_chinese" => "无效的语法",
169                "traditional_chinese" => "無效的語法",
170                "english" => "invalid syntax",
171            ),
172            errno,
173            SyntaxError,
174            loc,
175        ))
176    }
177
178    pub fn expect_next_line_error(errno: usize, loc: Location, caused: &str) -> Self {
179        Self::new(ErrorCore::new(
180            vec![SubMessage::ambiguous_new(
181                loc,
182                vec![caused.to_string()],
183                None,
184            )],
185            switch_lang!(
186                "japanese" => "ブロックが期待されていますが、EOFが与えられました",
187                "simplified_chinese" => "该块是预期的,但是是 EOF",
188                "traditional_chinese" => "該塊是預期的,但是是 EOF",
189                "english" => "The block is expected, but is EOF",
190            ),
191            errno,
192            ExpectNextLine,
193            loc,
194        ))
195    }
196
197    pub fn syntax_error<S: Into<String>>(
198        errno: usize,
199        loc: Location,
200        desc: S,
201        hint: Option<String>,
202    ) -> Self {
203        Self::new(ErrorCore::new(
204            vec![SubMessage::ambiguous_new(loc, vec![], hint)],
205            desc,
206            errno,
207            SyntaxError,
208            loc,
209        ))
210    }
211
212    pub fn unexpected_token<S: fmt::Display>(
213        errno: usize,
214        loc: Location,
215        expected: S,
216        got: TokenKind,
217    ) -> Self {
218        Self::new(ErrorCore::new(
219            vec![SubMessage::ambiguous_new(loc, vec![], None)],
220            switch_lang!(
221                "japanese" => format!("{expected}が期待されましたが、{got}となっています"),
222                "simplified_chinese" => format!("期望: {expected},得到: {got}"),
223                "traditional_chinese" => format!("期望: {expected},得到: {got}"),
224                "english" => format!("expected: {expected}, got: {got}"),
225            ),
226            errno,
227            SyntaxError,
228            loc,
229        ))
230    }
231
232    pub fn invalid_chunk_error(errno: usize, loc: Location) -> LexError {
233        let msg = switch_lang!(
234            "japanese" => "無効な構文です",
235            "simplified_chinese" => "无效的语法",
236            "traditional_chinese" => "無效的語法",
237            "english" => "invalid syntax",
238        );
239        let hint = switch_lang!(
240            "japanese" => "セミコロンを追加するか改行をしてください",
241            "simplified_chinese" => "应该添加分号或换行符",
242            "traditional_chinese" => "應該添加分號或換行符",
243            "english" => "semicolon or newline should be added",
244        )
245        .to_string();
246        Self::syntax_error(errno, loc, msg, Some(hint))
247    }
248
249    pub fn syntax_warning<S: Into<String>>(
250        errno: usize,
251        loc: Location,
252        desc: S,
253        hint: Option<String>,
254    ) -> Self {
255        Self::new(ErrorCore::new(
256            vec![SubMessage::ambiguous_new(loc, vec![], hint)],
257            desc,
258            errno,
259            SyntaxWarning,
260            loc,
261        ))
262    }
263
264    pub fn invalid_definition_of_last_block(errno: usize, loc: Location) -> LexError {
265        Self::syntax_error(
266            errno,
267            loc,
268            switch_lang!(
269                "japanese" => "ブロックの終端で変数を定義することは出来ません",
270                "simplified_chinese" => "无法在块的末尾定义变量",
271                "traditional_chinese" => "無法在塊的末尾定義變量",
272                "english" => "cannot define a variable at the end of a block",
273            ),
274            None,
275        )
276    }
277
278    pub fn invalid_token_error(
279        errno: usize,
280        loc: Location,
281        main_msg: &str,
282        expect: &str,
283        found: &str,
284    ) -> LexError {
285        let expect = StyledStr::new(expect, Some(HINT), Some(ATTR));
286        let expect = switch_lang!(
287                "japanese" => format!("予期したトークン: {expect}"),
288                "simplified_chinese" => format!("期望: {expect}"),
289                "traditional_chinese" => format!("期望: {expect}"),
290                "english" => format!("expect: {expect}"),
291        );
292        let found = StyledStr::new(found, Some(ERR), Some(ATTR));
293        let found = switch_lang!(
294                "japanese" => format!("与えられた: {found}"),
295                "simplified_chinese" => format!("但找到: {found}"),
296                "traditional_chinese" => format!("但找到: {found}"),
297                "english" => format!("but found: {found}"),
298        );
299        Self::new(ErrorCore::new(
300            vec![SubMessage::ambiguous_new(loc, vec![expect, found], None)],
301            main_msg,
302            errno,
303            SyntaxError,
304            loc,
305        ))
306    }
307
308    pub fn invalid_seq_elems_error<S: fmt::Display>(
309        errno: usize,
310        loc: Location,
311        expected: &[S],
312        got: TokenKind,
313    ) -> LexError {
314        let hint = switch_lang!(
315            "japanese" => format!("{}が期待されましたが、{got}が与えれられました", fmt_vec_split_with(expected, " または ")),
316            "simplified_chinese" => format!("期望: {},但找到: {got}", fmt_vec_split_with(expected, " 或 ")),
317            "traditional_chinese" => format!("期望: {},但找到: {got}", fmt_vec_split_with(expected, " 或 ")),
318            "english" => format!("expect: {}, got: {got}", fmt_vec_split_with(expected, " or ")),
319        );
320        let msg = switch_lang!(
321            "japanese" => "要素の列挙の仕方が不正です",
322            "simplified_chinese" => "无效的Sequential元素声明",
323            "traditional_chinese" => "無效的Sequential元素聲明",
324            "english" => "invalid sequential elements declaration",
325        );
326        Self::syntax_error(errno, loc, msg, Some(hint))
327    }
328
329    pub fn invalid_record_element_err(errno: usize, loc: Location) -> LexError {
330        let msg = switch_lang!(
331            "japanese" => "レコード型要素の列挙の仕方が不正です",
332            "simplified_chinese" => "无效的Record类型元素声明",
333            "traditional_chinese" => "無效的Record類型元素聲明",
334            "english" => "invalid record type element declarations",
335        )
336        .to_string();
337        let hint = switch_lang!(
338            "japanese" => {
339                let record = StyledStr::new("レコード型", Some(HINT), Some(ATTR));
340                let var = StyledStr::new("属性", Some(HINT), Some(ATTR));
341                let def = StyledStr::new("属性=リテラル", Some(HINT), Some(ATTR));
342                let obj = StyledStr::new("属性=オブジェクト", Some(HINT), Some(ATTR));
343                format!("{record}では{var}か{def}、{obj}のみ宣言することができます")
344            },
345            "simplified_chinese" => {
346                let record = StyledStr::new("Record类型", Some(HINT), Some(ATTR));
347                let var = StyledStr::new("属性", Some(HINT), Some(ATTR));
348                let def = StyledStr::new("属性=lit", Some(HINT), Some(ATTR));
349                let obj = StyledStr::new("属性=object", Some(HINT), Some(ATTR));
350                format!("{record}中只能声明 {var}、{def} 或 {obj}")
351            },
352            "traditional_chinese" => {
353                let record = StyledStr::new("Record類型", Some(HINT), Some(ATTR));
354                let var = StyledStr::new("屬性", Some(HINT), Some(ATTR));
355                let def = StyledStr::new("屬性=lit", Some(HINT), Some(ATTR));
356                let obj = StyledStr::new("屬性=object", Some(HINT), Some(ATTR));
357                format!("{record}中只能声明 {var}、{def} 或 {obj}")
358            },
359            "english" => {
360                let record = StyledStr::new("Record", Some(HINT), Some(ATTR));
361                let var = StyledStr::new("attr", Some(HINT), Some(ATTR));
362                let def = StyledStr::new("attr=lit", Some(HINT), Some(ATTR));
363                let obj = StyledStr::new("attr=object", Some(HINT), Some(ATTR));
364                format!("only {var}, {def} or {obj} can be declared in {record}")
365            },
366        );
367        Self::syntax_error(errno, loc, msg, Some(hint))
368    }
369
370    pub fn invalid_data_pack_definition(errno: usize, loc: Location, fnd: &str) -> ParseError {
371        let msg = switch_lang!(
372            "japanese" => "データクラスの中身が異なります",
373            "simplified_chinese" => "数据类的内容无效",
374            "traditional_chinese" => "數據類的內容無效",
375            "english" => "invalid contents of data class",
376        );
377        let expt = StyledStr::new("Record Type", Some(HINT), Some(ATTR));
378        let expect = switch_lang!(
379            "japanese" => format!("予期した型: {expt}"),
380            "simplified_chinese" => format!("期望的类型: {expt}"),
381            "traditional_chinese" => format!("期望的類型: {expt}"),
382            "english" => format!("expect type: {expt}"),
383        );
384        let fnd = StyledStr::new(fnd, Some(ERR), Some(ATTR));
385        let found = switch_lang!(
386            "japanese" => format!("与えられた型: {fnd}"),
387            "simplified_chinese" => format!("但找到: {fnd}"),
388            "traditional_chinese" => format!("但找到: {fnd}"),
389            "english" => format!("but found: {fnd}"),
390        );
391        let sub = SubMessage::ambiguous_new(loc, vec![expect, found], None);
392        Self::new(ErrorCore::new(vec![sub], msg, errno, SyntaxError, loc))
393    }
394
395    pub fn expect_keyword(errno: usize, loc: Location) -> ParseError {
396        let msg = switch_lang!(
397            "japanese" => "キーワードが指定されていません",
398            "simplified_chinese" => "未指定关键字",
399            "traditional_chinese" => "未指定關鍵字",
400            "english" => "keyword is not specified",
401        );
402        let keyword = StyledStr::new("keyword", Some(HINT), Some(ATTR));
403        let sub_msg = switch_lang!(
404            "japanese" => format!("予期した: {keyword}"),
405            "simplified_chinese" => format!("期望: {keyword}"),
406            "traditional_chinese" => format!("期望: {keyword}"),
407            "english" => format!("expect: {keyword}"),
408        );
409        let sub = SubMessage::ambiguous_new(loc, vec![sub_msg], None);
410        Self::new(ErrorCore::new(vec![sub], msg, errno, SyntaxError, loc))
411    }
412
413    pub fn invalid_non_default_parameter(errno: usize, loc: Location) -> ParseError {
414        let msg = switch_lang!(
415            "japanese" => "非デフォルト引数はデフォルト引数の後に指定できません",
416            "simplified_chinese" => "默认实参后面跟着非默认实参",
417            "traditional_chinese" => "默認實參後面跟著非默認實參",
418            "english" => "non-default argument follows default argument",
419        );
420
421        let walrus = StyledStr::new(":=", Some(HINT), Some(ATTR));
422        let sub_msg = switch_lang!(
423            "japanese" => format!("{walrus}を使用してください"),
424            "simplified_chinese" => format!("应该使用{walrus}"),
425            "traditional_chinese" => format!("應該使用{walrus}"),
426            "english" => format!("{walrus} should be used"),
427        );
428        let sub = SubMessage::ambiguous_new(loc, vec![sub_msg], None);
429        Self::new(ErrorCore::new(vec![sub], msg, errno, SyntaxError, loc))
430    }
431
432    pub fn invalid_colon_style(errno: usize, loc: Location) -> ParseError {
433        let desc = switch_lang!(
434            "japanese" => "コロンの後ろでカンマを使った区切りは使うことができません",
435            "simplified_chinese" => "冒号后不能使用逗号分隔符",
436            "traditional_chinese" => "冒號後不能使用逗號分隔符",
437            "english" => "comma delimiters cannot be used after a colon",
438        );
439        let hint = switch_lang!(
440            "japanese" => "カンマを削除してください",
441            "simplified_chinese" => "应该去掉逗号",
442            "traditional_chinese" => "應該去掉逗號",
443            "english" => "comma should be removed",
444        )
445        .to_string();
446        Self::syntax_error(errno, loc, desc, Some(hint))
447    }
448
449    pub fn unclosed_error(errno: usize, loc: Location, closer: &str, ty: &str) -> ParseError {
450        let msg = switch_lang!(
451            "japanese" => format!("{ty}が{closer}で閉じられていません"),
452            "simplified_chinese" => format!("{ty}没有用{closer}关闭"),
453            "traditional_chinese" => format!("{ty}没有用{closer}關閉"),
454            "english" => format!("{ty} is not closed with a {closer}"),
455        );
456
457        let closer = StyledStr::new(closer, Some(HINT), Some(ATTR));
458        let sub_msg = switch_lang!(
459            "japanese" => format!("{closer}を追加してください"),
460            "simplified_chinese" => format!("{closer}应该被添加"),
461            "traditional_chinese" => format!("{closer}應該被添加"),
462            "english" => format!("{closer} should be added"),
463        );
464
465        let sub = SubMessage::ambiguous_new(loc, vec![sub_msg], None);
466        Self::new(ErrorCore::new(vec![sub], msg, errno, SyntaxError, loc))
467    }
468
469    pub fn expect_method_error(errno: usize, loc: Location) -> ParseError {
470        let mut expect = StyledStrings::default();
471        switch_lang!(
472            "japanese" => expect.push_str("予期した: "),
473            "simplified_chinese" => expect.push_str("期望: "),
474            "traditional_chinese" => expect.push_str("期望: "),
475            "english" => expect.push_str("expect: "),
476        );
477        expect.push_str_with_color_and_attr(
478            switch_lang!(
479                "japanese" => "メソッド",
480                "simplified_chinese" => "方法",
481                "traditional_chinese" => "方法",
482                "english" => "method",
483            ),
484            HINT,
485            ATTR,
486        );
487        let sub_msg = SubMessage::ambiguous_new(loc, vec![expect.to_string()], None);
488        let main_msg = switch_lang!(
489            "japanese" => "クラスメソッドの定義が必要です",
490            "simplified_chinese" => "需要类方法定义",
491            "traditional_chinese" => "需要類方法定義",
492            "english" => "class method definitions are needed",
493        );
494        Self::new(ErrorCore::new(
495            vec![sub_msg],
496            main_msg,
497            errno,
498            SyntaxError,
499            loc,
500        ))
501    }
502
503    pub fn expect_accessor(errno: usize, loc: Location) -> ParseError {
504        let msg = switch_lang!(
505            "japanese" => "無効な構文です",
506            "simplified_chinese" => "无效的语法",
507            "traditional_chinese" => "無效的語法",
508            "english" => "invalid syntax",
509        );
510        let sub_msg = switch_lang!(
511            "japanese" => "アクセッサ―が期待されています",
512            "simplified_chinese" => "期望存取器",
513            "traditional_chinese" => "期望存取器",
514            "english" => "expect accessor",
515        )
516        .to_string();
517        let sub = SubMessage::ambiguous_new(loc, vec![sub_msg], None);
518        Self::new(ErrorCore::new(vec![sub], msg, errno, SyntaxError, loc))
519    }
520
521    pub fn invalid_acc_chain(errno: usize, loc: Location, found: &str) -> ParseError {
522        let expt = switch_lang!(
523            "japanese" => {
524                let method = StyledStr::new("メソッド", Some(HINT), Some(ATTR));
525                let lit = StyledStr::new("NatLit", Some(HINT), Some(ATTR));
526                let newline = StyledStr::new("改行", Some(HINT), Some(ATTR));
527                let arr = StyledStr::new("リスト", Some(HINT), Some(ATTR));
528                format!("予期: {method}、{lit}、{newline}、{arr}")
529            },
530            "simplified_chinese" => {
531                let method = StyledStr::new("方法", Some(HINT), Some(ATTR));
532                let lit = StyledStr::new("NatLit", Some(HINT), Some(ATTR));
533                let newline = StyledStr::new("换行", Some(HINT), Some(ATTR));
534                let arr = StyledStr::new("数组", Some(HINT), Some(ATTR));
535                format!("期望: {method}, {lit}, {newline}, {arr}")
536            },
537            "traditional_chinese" => {
538                let method = StyledStr::new("方法", Some(HINT), Some(ATTR));
539                let lit = StyledStr::new("NatLit", Some(HINT), Some(ATTR));
540                let newline = StyledStr::new("换行", Some(HINT), Some(ATTR));
541                let arr = StyledStr::new("數組", Some(HINT), Some(ATTR));
542                format!("期望: {method}, {lit}, {newline}, {arr}")
543            },
544            "english" => {
545                let method = StyledStr::new("method", Some(HINT), Some(ATTR));
546                let lit = StyledStr::new("NatLit", Some(HINT), Some(ATTR));
547                let newline = StyledStr::new("newline", Some(HINT), Some(ATTR));
548                let arr = StyledStr::new("list", Some(HINT), Some(ATTR));
549                format!("expect: {method}, {lit}, {newline}, {arr}")
550            },
551        );
552
553        let fnd = switch_lang!(
554            "japanese" =>format!("与えられた: {}", StyledStr::new(found, Some(ERR), None)),
555            "simplified_chinese" => format!("但找到: {}", StyledStr::new(found, Some(ERR), None)),
556            "traditional_chinese" => format!("但找到: {}", StyledStr::new(found, Some(ERR), None)),
557            "english" => format!("but found: {}", StyledStr::new(found, Some(ERR), None)),
558        );
559        let sub = SubMessage::ambiguous_new(loc, vec![expt, fnd], None);
560        let msg = switch_lang!(
561            "japanese" => "無効なアクセス呼び出しです",
562            "simplified_chinese" => "无效的访问调用",
563            "traditional_chinese" => "無效的訪問調用",
564            "english" => "invalid access call",
565        )
566        .to_string();
567        Self::new(ErrorCore::new(vec![sub], msg, errno, SyntaxError, loc))
568    }
569
570    pub fn expect_type_specified(errno: usize, loc: Location) -> ParseError {
571        let msg = switch_lang!(
572            "japanese" => "型指定が不正です",
573            "traditional_chinese" => "无效的类型说明",
574            "simplified_chinese" => "無效的類型說明",
575            "english" => "invalid type specification",
576        );
577        Self::syntax_error(errno, loc, msg, None)
578    }
579
580    pub fn duplicate_elem_warning(errno: usize, loc: Location, elem: String) -> Self {
581        let elem = StyledString::new(elem, Some(WARN), Some(Attribute::Underline));
582        Self::new(ErrorCore::new(
583            vec![SubMessage::only_loc(loc)],
584            switch_lang!(
585                "japanese" => format!("重複する要素です: {elem}"),
586                "simplified_chinese" => format!("{elem}"),
587                "traditional_chinese" => format!("{elem}"),
588                "english" => format!("duplicated element: {elem}"),
589            ),
590            errno,
591            SyntaxWarning,
592            loc,
593        ))
594    }
595}
596
597pub type LexResult<T> = Result<T, LexError>;
598
599pub type ParseError = LexError;
600pub type ParseErrors = LexErrors;
601pub type ParseWarning = LexError;
602pub type ParseWarnings = LexErrors;
603pub type ParseResult<T> = Result<T, ()>;
604
605#[derive(Debug)]
606pub struct DesugaringError {
607    pub core: ErrorCore,
608}
609
610impl DesugaringError {
611    pub const fn new(core: ErrorCore) -> Self {
612        Self { core }
613    }
614}
615
616#[derive(Debug)]
617pub struct DesugaringErrors(Vec<DesugaringError>);
618
619impl_stream!(DesugaringErrors, DesugaringError);
620
621pub type DesugaringResult<T> = Result<T, DesugaringError>;
622
623#[derive(Debug)]
624pub struct ParserRunnerError {
625    pub core: ErrorCore,
626    pub input: Input,
627}
628
629impl_display_and_error!(ParserRunnerError);
630
631impl ErrorDisplay for ParserRunnerError {
632    fn core(&self) -> &ErrorCore {
633        &self.core
634    }
635    fn input(&self) -> &Input {
636        &self.input
637    }
638    fn caused_by(&self) -> &str {
639        ""
640    }
641    fn ref_inner(&self) -> Option<&Self> {
642        None
643    }
644}
645
646impl ParserRunnerError {
647    pub const fn new(core: ErrorCore, input: Input) -> Self {
648        Self { core, input }
649    }
650}
651
652impl From<ParserRunnerError> for LexError {
653    fn from(err: ParserRunnerError) -> Self {
654        Self::new(err.core)
655    }
656}
657
658#[derive(Debug)]
659pub struct ParserRunnerErrors(Vec<ParserRunnerError>);
660
661impl std::error::Error for ParserRunnerErrors {}
662
663impl_stream!(ParserRunnerErrors, ParserRunnerError);
664
665impl MultiErrorDisplay<ParserRunnerError> for ParserRunnerErrors {}
666
667impl From<ParserRunnerErrors> for LexErrors {
668    fn from(errs: ParserRunnerErrors) -> Self {
669        Self(errs.0.into_iter().map(LexError::from).collect())
670    }
671}
672
673impl fmt::Display for ParserRunnerErrors {
674    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
675        self.fmt_all(f)
676    }
677}
678
679impl ParserRunnerErrors {
680    pub fn convert(input: &Input, errs: ParseErrors) -> Self {
681        Self(
682            errs.into_iter()
683                .map(|err| ParserRunnerError::new(*err.0, input.clone()))
684                .collect(),
685        )
686    }
687}
688
689pub type ParserRunnerResult<T> = Result<T, ParserRunnerError>;
690
691pub type LexerRunnerError = ParserRunnerError;
692pub type LexerRunnerErrors = ParserRunnerErrors;
693pub type ParserRunnerWarning = ParserRunnerError;
694pub type ParserRunnerWarnings = ParserRunnerErrors;
695pub type LexerRunnerResult<T> = Result<T, LexerRunnerError>;
696
697#[derive(Debug)]
698pub struct CompleteArtifact<A = Module, Es = ParseErrors> {
699    pub ast: A,
700    pub warns: Es,
701}
702
703impl<A, Es> CompleteArtifact<A, Es> {
704    pub fn new(ast: A, warns: Es) -> Self {
705        Self { ast, warns }
706    }
707
708    pub fn map<U>(self, f: impl FnOnce(A) -> U) -> CompleteArtifact<U, Es> {
709        CompleteArtifact {
710            ast: f(self.ast),
711            warns: self.warns,
712        }
713    }
714}
715
716#[derive(Debug)]
717pub struct IncompleteArtifact<A = Module, Es = ParseErrors> {
718    pub ast: Option<A>,
719    pub warns: Es,
720    pub errors: Es,
721}
722
723impl<A> From<ParserRunnerErrors> for IncompleteArtifact<A, ParserRunnerErrors> {
724    fn from(value: ParserRunnerErrors) -> IncompleteArtifact<A, ParserRunnerErrors> {
725        IncompleteArtifact::new(None, ParserRunnerErrors::empty(), value)
726    }
727}
728
729impl<A> From<LexErrors> for IncompleteArtifact<A, ParseErrors> {
730    fn from(value: LexErrors) -> IncompleteArtifact<A, ParseErrors> {
731        IncompleteArtifact::new(None, ParseErrors::empty(), value)
732    }
733}
734
735impl<A, Es> IncompleteArtifact<A, Es> {
736    pub fn new(ast: Option<A>, warns: Es, errors: Es) -> Self {
737        Self { ast, warns, errors }
738    }
739
740    pub fn map_errs<U>(self, f: impl Fn(Es) -> U) -> IncompleteArtifact<A, U> {
741        IncompleteArtifact {
742            ast: self.ast,
743            warns: f(self.warns),
744            errors: f(self.errors),
745        }
746    }
747
748    pub fn map_mod<U>(self, f: impl FnOnce(A) -> U) -> IncompleteArtifact<U, Es> {
749        IncompleteArtifact {
750            ast: self.ast.map(f),
751            warns: self.warns,
752            errors: self.errors,
753        }
754    }
755}
756
757#[derive(Debug)]
758pub struct ErrorArtifact<Es = ParseErrors> {
759    pub warns: Es,
760    pub errors: Es,
761}
762
763impl<Es> ErrorArtifact<Es> {
764    pub fn new(warns: Es, errors: Es) -> ErrorArtifact<Es> {
765        Self { warns, errors }
766    }
767}