microcad_lang/syntax/format_string/
format_expression.rs

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