Skip to main content

microcad_lang/syntax/format_string/
format_expression.rs

1// Copyright © 2024-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Format expression syntax element
5
6use microcad_lang_base::{SrcRef, SrcReferrer, TreeDisplay, TreeState};
7
8use crate::syntax::*;
9
10/// Format expression including format specification.
11#[allow(dead_code)]
12#[derive(Clone, PartialEq)]
13pub struct FormatExpression {
14    /// Format specifier
15    pub spec: Option<FormatSpec>,
16    /// Expression to format
17    pub expression: Expression,
18    /// Source code reference
19    src_ref: SrcRef,
20}
21
22impl FormatExpression {
23    /// Create new format expression.
24    pub fn new(spec: Option<FormatSpec>, expression: Expression, src_ref: SrcRef) -> Self {
25        Self {
26            src_ref,
27            spec,
28            expression,
29        }
30    }
31}
32
33impl std::fmt::Display for FormatExpression {
34    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
35        if let Some(spec) = &self.spec {
36            write!(f, "{{{}:{}}}", spec, self.expression)
37        } else {
38            write!(f, "{{{}}}", self.expression)
39        }
40    }
41}
42
43impl std::fmt::Debug for FormatExpression {
44    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
45        if let Some(spec) = &self.spec {
46            write!(f, "{{{:?}:{:?}}}", spec, self.expression)
47        } else {
48            write!(f, "{{{:?}}}", self.expression)
49        }
50    }
51}
52
53impl SrcReferrer for FormatExpression {
54    fn src_ref(&self) -> SrcRef {
55        self.src_ref.clone()
56    }
57}
58
59impl TreeDisplay for FormatExpression {
60    fn tree_print(&self, f: &mut std::fmt::Formatter, mut depth: TreeState) -> std::fmt::Result {
61        writeln!(f, "{:depth$}FormatExpression:", "")?;
62        depth.indent();
63        if let Some(spec) = &self.spec {
64            spec.tree_print(f, depth)?;
65            self.expression.tree_print(f, depth)
66        } else {
67            self.expression.tree_print(f, depth)
68        }
69    }
70}