1use crate::lit::Lit;
2use crate::parser::{ParseError, ParseStream};
3use crate::{LexError, Parse, Span, Spanner};
4
5#[derive(Debug, Clone)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(into = "String"))]
7pub struct LitBool {
8 value: bool,
9 span: Span,
10}
11
12impl LitBool {
13 #[inline]
14 pub fn new(value: bool, span: Span) -> Self {
15 Self { value, span }
16 }
17
18 #[inline]
19 pub fn value(&self) -> bool {
20 self.value
21 }
22
23 #[inline]
24 pub fn repr(&self) -> &str {
25 if self.value { "true" } else { "false" }
26 }
27
28 #[inline]
29 pub fn span(&self) -> Span {
30 self.span
31 }
32
33 #[inline]
34 pub fn set_span(&mut self, span: Span) {
35 self.span = span;
36 }
37}
38
39impl PartialEq for LitBool {
40 fn eq(&self, other: &Self) -> bool {
41 self.value == other.value
42 }
43}
44
45impl Eq for LitBool {}
46
47impl std::hash::Hash for LitBool {
48 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
49 self.value.hash(state);
50 }
51}
52
53impl std::fmt::Display for LitBool {
54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 f.write_str(self.repr())
56 }
57}
58
59impl Spanner for LitBool {
60 fn span(&self) -> Span {
61 self.span
62 }
63}
64
65impl Parse for LitBool {
66 fn parse(stream: &mut ParseStream) -> Result<Self, ParseError> {
67 let at = stream.span();
68
69 match stream.parse::<Lit>()? {
70 Lit::Bool(v) => Ok(v),
71 _ => Err(LexError::new(at).message("expected bool literal").into()),
72 }
73 }
74}
75
76impl From<LitBool> for Lit {
77 fn from(value: LitBool) -> Self {
78 Self::Bool(value)
79 }
80}
81
82#[cfg(feature = "serde")]
83impl From<LitBool> for String {
84 fn from(value: LitBool) -> Self {
85 value.repr().to_string()
86 }
87}