litrs/bool/
mod.rs

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