heraclitus_compiler/compiling/failing/
failure.rs

1//! This module contains Failure enum that is used to return errors from parser
2
3use crate::compiling::failing::message::Message;
4use crate::compiling::failing::position_info::PositionInfo;
5
6#[cfg(feature = "serde")]
7use serde::{Serialize, Deserialize};
8
9/// Failure enum
10/// 
11/// This enum returns two types of errors - `Quiet` and `Loud`.
12/// 
13/// The Quiet failure is used when some minor error occurs, but the parser can continue.
14/// It contains detailed information about the error such as token position and length.
15/// The example for that can be a syntax mismatch - the current token could be an actual
16/// valid token for the current context, but it's not the one that is expected.
17/// 
18/// The Loud failure is used when the parser cannot continue. It contains detailed information
19/// about the error such as token position and length, but also a message, comment and a full traceback.
20#[derive(Debug, Clone)]
21#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
22pub enum Failure {
23    /// Failure that is not important
24    Quiet(PositionInfo),
25    /// Failure that is important
26    Loud(Message)
27}
28
29impl Failure {
30    /// Returns true if this failure is quiet
31    pub fn is_quiet(&self) -> bool {
32        matches!(self, Failure::Quiet(_))
33    }
34
35    /// Returns true if this failure is loud
36    pub fn is_loud(&self) -> bool {
37        matches!(self, Failure::Loud(_))
38    }
39
40    /// Unwraps this failure into quiet failure
41    pub fn unwrap_quiet(self) -> PositionInfo {
42        match self {
43            Failure::Quiet(info) => info,
44            Failure::Loud(_) => panic!("Cannot quietly unwrap loud failure")
45        }
46    }
47
48    /// Unwraps this failure into loud failure
49    pub fn unwrap_loud(self) -> Message {
50        match self {
51            Failure::Quiet(_) => panic!("Cannot loudly unwrap quiet failure"),
52            Failure::Loud(message) => message
53        }
54    }
55}