Skip to main content

microcad_lang/lower/ir/format_string/
mod.rs

1// Copyright © 2024-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! µcad format expression syntax elements
5
6mod format_expression;
7mod format_spec;
8
9pub use format_expression::*;
10pub use format_spec::*;
11
12use microcad_lang_base::{Refer, SrcRef, SrcReferrer};
13use microcad_lang_proc_macros::SrcReferrer;
14
15/// Format string item.
16#[derive(Debug, Clone)]
17pub enum FormatStringInner {
18    /// String literal.
19    String(Refer<String>),
20    /// Format expression.
21    FormatExpression(Box<FormatExpression>),
22}
23
24impl SrcReferrer for FormatStringInner {
25    fn src_ref(&self) -> SrcRef {
26        match self {
27            FormatStringInner::String(s) => s.src_ref(),
28            FormatStringInner::FormatExpression(e) => e.src_ref(),
29        }
30    }
31}
32
33/// Format string.
34#[derive(Default, Clone, Debug, SrcReferrer)]
35pub struct FormatString(pub Refer<Vec<FormatStringInner>>);
36
37impl FormatString {
38    /// Insert a string.
39    pub fn push_string(&mut self, s: String, src_ref: SrcRef) {
40        self.0
41            .push(FormatStringInner::String(Refer::new(s, src_ref)));
42    }
43
44    /// Insert a format expression
45    pub fn push_format_expr(&mut self, expr: FormatExpression) {
46        self.0
47            .push(FormatStringInner::FormatExpression(Box::new(expr)));
48    }
49
50    /// Return the number of sections (inserted elements)
51    pub fn section_count(&self) -> usize {
52        self.0.len()
53    }
54}
55
56impl From<Refer<String>> for FormatString {
57    fn from(value: Refer<String>) -> Self {
58        FormatString(Refer {
59            src_ref: value.src_ref,
60            value: vec![FormatStringInner::String(value)],
61        })
62    }
63}
64
65impl std::fmt::Display for FormatString {
66    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
67        write!(f, r#"""#)?;
68        for elem in &*self.0 {
69            match elem {
70                FormatStringInner::String(s) => write!(f, "{}", s.value)?,
71                FormatStringInner::FormatExpression(expr) => write!(f, "{expr}")?,
72            }
73        }
74        write!(f, r#"""#)?;
75        Ok(())
76    }
77}