microcad_lang/syntax/format_string/
format_spec.rs

1// Copyright © 2024-2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Format Specification syntax element
5
6use crate::{src_ref::*, syntax::*};
7
8/// Format specification.
9#[derive(Clone, Debug, Default)]
10pub struct FormatSpec {
11    /// Precision for number formatting.
12    pub precision: Option<u32>,
13    /// Alignment width (leading zeros).
14    pub width: Option<u32>,
15    /// Source code reference.
16    pub src_ref: SrcRef,
17}
18
19impl SrcReferrer for FormatSpec {
20    fn src_ref(&self) -> SrcRef {
21        self.src_ref.clone()
22    }
23}
24
25impl std::fmt::Display for FormatSpec {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        match (self.width, self.precision) {
28            (Some(width), Some(precision)) => write!(f, "0{width}.{precision}"),
29            (None, Some(precision)) => write!(f, ".{precision}"),
30            (Some(width), None) => write!(f, "0{width}"),
31            _ => Ok(()),
32        }
33    }
34}
35
36impl TreeDisplay for FormatSpec {
37    fn tree_print(&self, f: &mut std::fmt::Formatter, depth: TreeState) -> std::fmt::Result {
38        match (self.width, self.precision) {
39            (Some(width), Some(precision)) => {
40                writeln!(f, "{:depth$}FormatSpec: 0{width}.{precision}", "")
41            }
42            (None, Some(precision)) => writeln!(f, "{:depth$}FormatSpec: .{precision}", ""),
43            (Some(width), None) => writeln!(f, "{:depth$}FormatSpec:  0{width}", ""),
44            _ => Ok(()),
45        }
46    }
47}