Skip to main content

microcad_lang/syntax/literal/
number_literal.rs

1// Copyright © 2024-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Number literal syntax element
5
6use microcad_lang_base::{SrcRef, SrcReferrer};
7
8use crate::{syntax::*, ty::*, value::*};
9
10/// Number literal.
11#[derive(Clone, PartialEq)]
12pub struct NumberLiteral(pub f64, pub Unit, pub SrcRef);
13
14impl NumberLiteral {
15    /// Returns the actual value of the literal
16    pub fn normalized_value(&self) -> f64 {
17        self.1.normalize(self.0)
18    }
19
20    /// return unit
21    pub fn unit(&self) -> Unit {
22        self.1
23    }
24
25    /// Return value for number literal
26    pub fn value(&self) -> Value {
27        match self.1.ty() {
28            Type::Quantity(quantity_type) => {
29                Value::Quantity(Quantity::new(self.normalized_value(), quantity_type))
30            }
31            _ => unreachable!(),
32        }
33    }
34}
35
36impl crate::ty::Ty for NumberLiteral {
37    fn ty(&self) -> Type {
38        self.1.ty()
39    }
40}
41
42impl SrcReferrer for NumberLiteral {
43    fn src_ref(&self) -> literal::SrcRef {
44        self.2.clone()
45    }
46}
47
48impl std::fmt::Display for NumberLiteral {
49    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
50        write!(f, "{}{}", self.0, self.1)
51    }
52}
53
54impl From<NumberLiteral> for Value {
55    fn from(literal: NumberLiteral) -> Self {
56        literal.value()
57    }
58}