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, Default, PartialEq)]
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 std::fmt::Debug for FormatSpec {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(f, "{self}")
39    }
40}
41
42impl TreeDisplay for FormatSpec {
43    fn tree_print(&self, f: &mut std::fmt::Formatter, depth: TreeState) -> std::fmt::Result {
44        match (self.width, self.precision) {
45            (Some(width), Some(precision)) => {
46                writeln!(f, "{:depth$}FormatSpec: 0{width}.{precision}", "")
47            }
48            (None, Some(precision)) => writeln!(f, "{:depth$}FormatSpec: .{precision}", ""),
49            (Some(width), None) => writeln!(f, "{:depth$}FormatSpec:  0{width}", ""),
50            _ => Ok(()),
51        }
52    }
53}