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, PartialEq)]
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 std::fmt::Debug for FormatExpression {
42    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
43        if let Some(spec) = &self.spec {
44            write!(f, "{{{:?}:{:?}}}", spec, self.expression)
45        } else {
46            write!(f, "{{{:?}}}", self.expression)
47        }
48    }
49}
50
51impl SrcReferrer for FormatExpression {
52    fn src_ref(&self) -> SrcRef {
53        self.src_ref.clone()
54    }
55}
56
57impl TreeDisplay for FormatExpression {
58    fn tree_print(&self, f: &mut std::fmt::Formatter, mut depth: TreeState) -> std::fmt::Result {
59        writeln!(f, "{:depth$}FormatExpression:", "")?;
60        depth.indent();
61        if let Some(spec) = &self.spec {
62            spec.tree_print(f, depth)?;
63            self.expression.tree_print(f, depth)
64        } else {
65            self.expression.tree_print(f, depth)
66        }
67    }
68}