litrs/bool/
mod.rs

1use std::fmt;
2
3use crate::{ParseError, err::{perr, ParseErrorKind::*}};
4
5
6/// A bool literal: `true` or `false`. Also see [the reference][ref].
7///
8/// Notice that, strictly speaking, from Rust point of view "boolean literals" are not
9/// actual literals but [keywords].
10///
11/// [ref]: https://doc.rust-lang.org/reference/expressions/literal-expr.html#boolean-literal-expressions
12/// [keywords]: https://doc.rust-lang.org/reference/keywords.html#strict-keywords
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum BoolLit {
15    False,
16    True,
17}
18
19impl BoolLit {
20    /// Parses the input as a bool literal. Returns an error if the input is
21    /// invalid or represents a different kind of literal.
22    pub fn parse(s: &str) -> Result<Self, ParseError> {
23        match s {
24            "false" => Ok(Self::False),
25            "true" => Ok(Self::True),
26            _ => Err(perr(None, InvalidLiteral)),
27        }
28    }
29
30    /// Returns the actual Boolean value of this literal.
31    pub fn value(self) -> bool {
32        match self {
33            Self::False => false,
34            Self::True => true,
35        }
36    }
37
38    /// Returns the literal as string.
39    pub fn as_str(&self) -> &'static str {
40        match self {
41            Self::False => "false",
42            Self::True => "true",
43        }
44    }
45}
46
47impl fmt::Display for BoolLit {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.pad(self.as_str())
50    }
51}
52
53
54#[cfg(test)]
55mod tests;