microcad_lang/parse/
format_string.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4use crate::{parse::*, parser::*, syntax::*};
5
6impl Parse for FormatExpression {
7    fn parse(pair: Pair) -> ParseResult<Self> {
8        Ok(Self::new(
9            crate::find_rule_opt!(pair, format_spec),
10            crate::find_rule!(pair, expression)?,
11            pair.into(),
12        ))
13    }
14}
15
16impl Parse for FormatSpec {
17    fn parse(pair: Pair) -> ParseResult<Self> {
18        let mut opt = FormatSpec::default();
19
20        for pair in pair.inner() {
21            match pair.as_rule() {
22                Rule::format_spec_precision => {
23                    opt.precision = Some(pair.as_span().as_str()[1..].parse()?)
24                }
25                Rule::format_spec_width => opt.width = Some(pair.as_span().as_str()[1..].parse()?),
26                _ => unreachable!(),
27            }
28        }
29
30        opt.src_ref = pair.into();
31
32        Ok(opt)
33    }
34}
35
36impl Parse for FormatString {
37    fn parse(pair: Pair) -> ParseResult<Self> {
38        let mut fs = Self::default();
39        for pair in pair.inner() {
40            match pair.as_rule() {
41                Rule::string_literal_inner => {
42                    fs.push_string(pair.as_span().as_str().to_string(), pair.into())
43                }
44                Rule::format_expression => fs.push_format_expr(FormatExpression::parse(pair)?),
45                _ => unreachable!(),
46            }
47        }
48
49        Ok(fs)
50    }
51}
52
53impl std::str::FromStr for FormatString {
54    type Err = ParseError;
55
56    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
57        Parser::parse_rule::<Self>(Rule::format_string, s, 0)
58    }
59}