microcad_lang/syntax/literal/
mod.rs

1// Copyright © 2024-2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! µcad literal syntax elements
5
6mod number_literal;
7mod units;
8
9pub use number_literal::*;
10pub use units::*;
11
12use crate::{src_ref::*, syntax::*, ty::*, value::Value};
13
14/// Literal of any kind.
15#[derive(Clone, PartialEq)]
16pub enum Literal {
17    /// Integer literal
18    Integer(Refer<i64>),
19    /// Number literal
20    Number(NumberLiteral),
21    /// Boolean literal
22    Bool(Refer<bool>),
23}
24
25impl Literal {
26    /// Return value of literal.
27    pub fn value(&self) -> Value {
28        match self {
29            Self::Integer(value) => Value::Integer(*value.clone()),
30            Self::Number(value) => value.value(),
31            Self::Bool(value) => Value::Bool(*value.clone()),
32        }
33    }
34}
35
36impl SrcReferrer for Literal {
37    fn src_ref(&self) -> SrcRef {
38        match self {
39            Literal::Number(n) => n.src_ref(),
40            Literal::Integer(i) => i.src_ref(),
41            Literal::Bool(b) => b.src_ref(),
42        }
43    }
44}
45
46impl crate::ty::Ty for Literal {
47    fn ty(&self) -> Type {
48        match self {
49            Literal::Integer(_) => Type::Integer,
50            Literal::Number(n) => n.ty(),
51            Literal::Bool(_) => Type::Bool,
52        }
53    }
54}
55
56impl std::fmt::Display for Literal {
57    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
58        match self {
59            Literal::Integer(i) => write!(f, "{i}"),
60            Literal::Number(n) => write!(f, "{n}"),
61            Literal::Bool(b) => write!(f, "{b}"),
62        }
63    }
64}
65
66impl From<Literal> for Value {
67    fn from(literal: Literal) -> Self {
68        literal.value()
69    }
70}
71
72impl TreeDisplay for Literal {
73    fn tree_print(&self, f: &mut std::fmt::Formatter, depth: TreeState) -> std::fmt::Result {
74        write!(f, "{:depth$}Literal: ", "")?;
75        match self {
76            Literal::Integer(i) => writeln!(f, "{i}"),
77            Literal::Number(n) => writeln!(f, "{n}"),
78            Literal::Bool(b) => writeln!(f, "{b}"),
79        }
80    }
81}