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_span().as_str()[1..].parse() {
22                Ok(parsed) => match pair.as_rule() {
23                    Rule::format_spec_precision => opt.precision = Some(parsed),
24                    Rule::format_spec_width => opt.width = Some(parsed),
25                    _ => unreachable!(),
26                },
27                Err(err) => return Err(ParseError::ParseIntError(Refer::new(err, pair.into()))),
28            }
29        }
30
31        opt.src_ref = pair.into();
32
33        Ok(opt)
34    }
35}
36
37impl Parse for FormatString {
38    fn parse(pair: Pair) -> ParseResult<Self> {
39        let mut fs = Self::default();
40        for pair in pair.inner() {
41            match pair.as_rule() {
42                Rule::string_literal_inner => {
43                    fs.push_string(pair.as_span().as_str().to_string(), pair.into())
44                }
45                Rule::format_expression => fs.push_format_expr(FormatExpression::parse(pair)?),
46                _ => unreachable!(),
47            }
48        }
49
50        Ok(fs)
51    }
52}
53
54impl std::str::FromStr for FormatString {
55    type Err = ParseError;
56
57    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
58        Parser::parse_rule::<Self>(Rule::format_string, s, 0)
59    }
60}