ctb_formats_dcdata/format_spec/
formatter.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Text formatter and canonical printer for format specification expressions.
21//!
22//! Emits unambiguous format expression strings with minimal, necessary parentheses
23//! adhering to the associativity and grouping rules of `docs/file-info.md`.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace module prelude"
29)]
30use crate::utilities::*;
31
32use std::fmt;
33
34use super::ast::{FormatExpr, FormatOp};
35
36impl fmt::Display for FormatExpr {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        write!(f, "{}", format_expr(self))
39    }
40}
41
42/// Formats a `FormatExpr` into its canonical text representation.
43#[must_use]
44pub fn format_expr(expr: &FormatExpr) -> String {
45    format_expr_inner(expr, None, false)
46}
47
48/// Formats a `FormatExpr` wrapped in a `@chain(...)` directive.
49#[must_use]
50pub fn format_chain_directive(expr: &FormatExpr) -> String {
51    format!("@chain({})", format_expr(expr))
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55enum ParentContext {
56    Operational(FormatOp),
57    Union,
58    Intersection,
59}
60
61fn format_expr_inner(
62    expr: &FormatExpr,
63    parent_ctx: Option<ParentContext>,
64    is_right_child_of_op: bool,
65) -> String {
66    match expr {
67        FormatExpr::Dc(shorthand) => shorthand.to_string(),
68        FormatExpr::NamedType(name) => name.clone(),
69        FormatExpr::Convert(left, right) => {
70            let left_str = format_expr_inner(
71                left,
72                Some(ParentContext::Operational(FormatOp::Convert)),
73                false,
74            );
75            let right_str = format_expr_inner(
76                right,
77                Some(ParentContext::Operational(FormatOp::Convert)),
78                true,
79            );
80            let res = format!("{left_str} > {right_str}");
81            wrap_operational(
82                res,
83                FormatOp::Convert,
84                parent_ctx,
85                is_right_child_of_op,
86            )
87        }
88        FormatExpr::Transmute(left, right) => {
89            let left_str = format_expr_inner(
90                left,
91                Some(ParentContext::Operational(FormatOp::Transmute)),
92                false,
93            );
94            let right_str = format_expr_inner(
95                right,
96                Some(ParentContext::Operational(FormatOp::Transmute)),
97                true,
98            );
99            let res = format!("{left_str} ! {right_str}");
100            wrap_operational(
101                res,
102                FormatOp::Transmute,
103                parent_ctx,
104                is_right_child_of_op,
105            )
106        }
107        FormatExpr::Transform(left, right) => {
108            let left_str = format_expr_inner(
109                left,
110                Some(ParentContext::Operational(FormatOp::Transform)),
111                false,
112            );
113            let right_str = format_expr_inner(
114                right,
115                Some(ParentContext::Operational(FormatOp::Transform)),
116                true,
117            );
118            let res = format!("{left_str} : {right_str}");
119            wrap_operational(
120                res,
121                FormatOp::Transform,
122                parent_ctx,
123                is_right_child_of_op,
124            )
125        }
126        FormatExpr::Union(children) => {
127            let parts: Vec<String> = children
128                .iter()
129                .map(|child| {
130                    format_expr_inner(child, Some(ParentContext::Union), false)
131                })
132                .collect();
133            let res = parts.join(" & ");
134            match parent_ctx {
135                Some(
136                    ParentContext::Operational(_) | ParentContext::Intersection,
137                ) => format!("({res})"),
138                _ => res,
139            }
140        }
141        FormatExpr::Intersection(children) => {
142            let parts: Vec<String> = children
143                .iter()
144                .map(|child| {
145                    format_expr_inner(
146                        child,
147                        Some(ParentContext::Intersection),
148                        false,
149                    )
150                })
151                .collect();
152            let res = parts.join(" | ");
153            match parent_ctx {
154                Some(ParentContext::Operational(_) | ParentContext::Union) => {
155                    format!("({res})")
156                }
157                _ => res,
158            }
159        }
160        FormatExpr::Apply { target, params } => {
161            let target_str = format_expr_inner(target, None, false);
162            let mut param_strs = Vec::new();
163            for param in params {
164                let val_str = match &param.value {
165                    super::ast::ParamValue::Integer(n) => n.to_string(),
166                    super::ast::ParamValue::Dc(dc) => dc.to_string(),
167                    super::ast::ParamValue::Ident(id) => id.clone(),
168                    super::ast::ParamValue::String(s) => {
169                        format!("\"{}\"", s.replace('"', "\\\""))
170                    }
171                    super::ast::ParamValue::Expr(e) => format_expr(e),
172                };
173                param_strs.push(format!("{}={val_str}", param.name));
174            }
175            format!("{target_str}({})", param_strs.join(", "))
176        }
177    }
178}
179
180fn wrap_operational(
181    s: String,
182    current_op: FormatOp,
183    parent_ctx: Option<ParentContext>,
184    is_right_child_of_op: bool,
185) -> String {
186    if is_right_child_of_op {
187        return format!("({s})");
188    }
189    match parent_ctx {
190        Some(ParentContext::Operational(parent_op))
191            if parent_op != current_op =>
192        {
193            format!("({s})")
194        }
195        Some(ParentContext::Union | ParentContext::Intersection) => {
196            format!("({s})")
197        }
198        _ => s,
199    }
200}