pretty_text_parser 0.3.0

Parser for Bevy Pretty Text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use bevy::math::{Vec2, Vec3};
use bevy::reflect::Reflect;
use winnow::Parser;
use winnow::ascii::{multispace0, take_escaped};
use winnow::combinator::*;
use winnow::error::{ErrMode, StrContext};
use winnow::seq;
use winnow::token::{none_of, one_of};

use crate::ParserContext;
use crate::context::Error;

/// Trait for customizing how an argument is parsed for the dynamic effect trait.
///
/// [`ArgParser`] is implemented for a number of core rust and bevy types that
/// are useful in effects. Here is a table describing how these arguments are
/// translated into rust types:
/// | Rust Type | Input Format | Examples |
/// |-----------|--------------|----------|
/// | `f32` | Floating point number | `3.14`, `42`, `-1.5` |
/// | `f64` | Floating point number | `3.14159`, `42`, `-1.5` |
/// | `u8`, `u16`, `u32`, `u64`, `usize` | Unsigned integer | `42`, `255`, `1024` |
/// | `i8`, `i16`, `i32`, `i64`, `isize` | Signed integer | `42`, `-10`, `0` |
/// | `bool` | Boolean literal | `true`, `false` |
/// | `String` | Quoted string with escape sequences | `"hello"`, `"line\nbreak"`, `"quote\""` |
/// | `Vec2` | Tuple struct with two floats | `vec2(1.0, 2.0)`, `vec2(-3.5, 4.2)` |
/// | `Vec3` | Tuple struct with three floats | `vec3(1.0, 2.0, 3.0)`, `vec3(-1, 0, 1)` |
/// | `Option<T>` | Optional value wrapper | `some(42)`, `none`, `some("text")` |
/// | `Range<T>` | Bounded range | `1..10`, `3.14..6.28`, `0..100` |
/// | Duration (as milliseconds) | Number with optional unit suffix | `1000`, `1s`, `500ms`, `2m` |
/// | Duration (as seconds) | Number with optional unit suffix | `1`, `1s`, `500ms`, `2m` |
/// | Duration (as minutes) | Number with optional unit suffix | `1`, `60s`, `30000ms`, `1m` |
pub trait ArgParser: Sized {
    /// Parse `Self` from `input`.
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self>;
}

/// Trim whitespace surrounding `parser`.
///
/// ### Examples
/// - `  20` -> `20`
/// - `vec2(2, 3)  ` -> `vec2(2, 3)`
pub fn trim<'a, ParseNext, Output>(mut parser: ParseNext) -> impl Parser<&'a str, Output, Error>
where
    ParseNext: Parser<&'a str, Output, Error>,
{
    move |input: &mut &'a str| {
        multispace0(input)?;
        let result = parser.parse_next(input)?;
        multispace0(input)?;
        Ok(result)
    }
}

/// Parse fields of a tuple struct with `inner`.
///
/// Bubbles up errors from `inner` with [`ErrMode::cut`].
///
/// ### Examples
/// - `"vec2(2, 3)"` -> `inner("2, 3")`
/// - `"fixed(8.4)"` -> `inner("8.4")`
pub fn tuple_struct<'a, Inner, Out>(
    ident: &'static str,
    mut inner: Inner,
) -> impl Parser<&'a str, Out, Error>
where
    Inner: Parser<&'a str, Out, Error>,
{
    move |input: &mut &'a str| {
        (
            ident.label("struct ident").expected_str(ident),
            cut_err('(').label("opening delimiter").expected_char('('),
        )
            .parse_next(input)?;
        let inner = inner.parse_next(input).map_err(ErrMode::cut)?;
        cut_err(')')
            .label("closing delimiter")
            .expected_char(')')
            .parse_next(input)?;

        Ok(inner)
    }
}

impl<T: ArgParser> ArgParser for std::ops::Range<T> {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        range(input)
    }
}

/// Parse a bounded range from `input`.
///
/// ### Examples
/// - `12.4..19.2`
/// - `2..6`
pub fn range<T: ArgParser>(input: &mut &str) -> winnow::ModalResult<std::ops::Range<T>> {
    seq! {
        std::ops::Range {
            start: T::parse_arg,
            _: "..",
            end: T::parse_arg
        }
    }
    .parse_next(input)
}

/// A duration expressed in milliseconds.
///
/// ### Examples
/// - `20` -> `20`
/// - `12s` -> `12 * 1000`
/// - `1.5ms` -> `1.5`
/// - `1m` -> `1 * 1000 * 60`
#[derive(Debug, Clone, Copy, PartialEq, Reflect)]
pub struct Milliseconds(pub f32);

impl ArgParser for Milliseconds {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        duration_millis(input).map(Self)
    }
}

/// Parse a duration from `input` and convert to milliseconds.
///
/// ### Examples
/// - `20` -> `20`
/// - `12s` -> `12 * 1000`
/// - `1.5ms` -> `1.5`
/// - `1m` -> `1 * 1000 * 60`
pub fn duration_millis(input: &mut &str) -> winnow::ModalResult<f32> {
    Ok(duration(input)?.into_millis())
}

/// A duration expressed in seconds.
///
/// ### Examples
/// - `20` -> `20`
/// - `12s` -> `12`
/// - `1.5ms` -> `1.5 / 1000`
/// - `1m` -> `1 * 60`
#[derive(Debug, Clone, Copy, PartialEq, Reflect)]
pub struct Seconds(pub f32);

impl ArgParser for Seconds {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        duration_secs(input).map(Self)
    }
}

/// Parse a duration from `input` and convert to seconds.
///
/// ### Examples
/// - `20` -> `20`
/// - `12s` -> `12`
/// - `1.5ms` -> `1.5 / 1000`
/// - `1m` -> `1 * 60`
pub fn duration_secs(input: &mut &str) -> winnow::ModalResult<f32> {
    Ok(duration(input)?.into_secs())
}

/// A duration expressed in minutes.
///
/// ### Examples
/// - `20` -> `20`
/// - `12s` -> `12 / 60`
/// - `1.5ms` -> `1.5 / 1000 / 60`
/// - `1m` -> `1`
#[derive(Debug, Clone, Copy, PartialEq, Reflect)]
pub struct Minutes(pub f32);

impl ArgParser for Minutes {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        duration_mins(input).map(Self)
    }
}

/// Parse a duration from `input` and convert to minutes.
///
/// ### Examples
/// - `20` -> `20`
/// - `12s` -> `12 / 60`
/// - `1.5ms` -> `1.5 / 1000 / 60`
/// - `1m` -> `1`
pub fn duration_mins(input: &mut &str) -> winnow::ModalResult<f32> {
    Ok(duration(input)?.into_mins())
}

struct Duration {
    value: f32,
    unit: Option<Unit>,
}

impl Duration {
    pub fn into_millis(self) -> f32 {
        match self.unit {
            Some(unit) => match unit {
                Unit::Milliseconds => self.value,
                Unit::Seconds => self.value * 1_000f32,
                Unit::Minutes => self.value * 1_000f32 * 60f32,
            },
            None => self.value,
        }
    }

    pub fn into_secs(self) -> f32 {
        match self.unit {
            Some(unit) => match unit {
                Unit::Milliseconds => self.value / 1_000f32,
                Unit::Seconds => self.value,
                Unit::Minutes => self.value * 60f32,
            },
            None => self.value,
        }
    }

    pub fn into_mins(self) -> f32 {
        match self.unit {
            Some(unit) => match unit {
                Unit::Milliseconds => self.value / 1_000f32 / 60f32,
                Unit::Seconds => self.value / 60f32,
                Unit::Minutes => self.value,
            },
            None => self.value,
        }
    }
}

fn duration(input: &mut &str) -> winnow::ModalResult<Duration> {
    seq! {
        Duration {
            value: f32::parse_arg,
            unit: opt(unit)
        }
    }
    .parse_next(input)
}

enum Unit {
    Milliseconds,
    Seconds,
    Minutes,
}

fn unit(input: &mut &str) -> winnow::ModalResult<Unit> {
    alt((
        "ms".map(|_| Unit::Milliseconds),
        "s".map(|_| Unit::Seconds),
        "m".map(|_| Unit::Minutes),
    ))
    .parse_next(input)
}

impl ArgParser for f32 {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        // handle floats before ranges
        if let Some(range_pos) = input.find("..") {
            let prefix = &input[..range_pos];
            if !prefix.is_empty() && prefix.chars().all(|c| c == '-' || c.is_ascii_digit()) {
                return winnow::ascii::dec_int::<_, i32, _>
                    .map(|v| v as f32)
                    .label("float")
                    .parse_next(input);
            }
        }
        winnow::ascii::float.label("float").parse_next(input)
    }
}

impl ArgParser for f64 {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        // handle floats before ranges
        if let Some(range_pos) = input.find("..") {
            let prefix = &input[..range_pos];
            if !prefix.is_empty() && prefix.chars().all(|c| c == '-' || c.is_ascii_digit()) {
                return winnow::ascii::dec_int::<_, i64, _>
                    .label("float")
                    .map(|v| v as f64)
                    .parse_next(input);
            }
        }
        winnow::ascii::float.label("float").parse_next(input)
    }
}

macro_rules! primitive_parser {
    ($ty:ty, $parser:ident) => {
        impl ArgParser for $ty {
            fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
                winnow::ascii::$parser
                    .context(StrContext::Label(stringify!($ty)))
                    .parse_next(input)
            }
        }
    };
    ($ty:ty, $parser:ident => $label:expr) => {
        impl ArgParser for $ty {
            fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
                winnow::ascii::$parser
                    .context(StrContext::Label($label))
                    .parse_next(input)
            }
        }
    };
}

primitive_parser!(u8, dec_uint);
primitive_parser!(u16, dec_uint);
primitive_parser!(u32, dec_uint);
primitive_parser!(u64, dec_uint);
primitive_parser!(usize, dec_uint);

primitive_parser!(i8, dec_int);
primitive_parser!(i16, dec_int);
primitive_parser!(i32, dec_int);
primitive_parser!(i64, dec_int);
primitive_parser!(isize, dec_int);

impl ArgParser for bool {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        alt(("true".map(|_| true), "false".map(|_| false)))
            .label("bool")
            .expected_str("true")
            .expected_str("false")
            .parse_next(input)
    }
}

impl ArgParser for String {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        delimited(
            '"',
            take_escaped(
                none_of(['\\', '"']),
                '\\',
                one_of(['"', '\\', 'n', 't', 'r']),
            ),
            '"',
        )
        .map(str::to_string)
        .label("string")
        .parse_next(input)
    }
}

impl<T: ArgParser> ArgParser for Option<T> {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        alt((
            tuple_struct("some", T::parse_arg.map(Option::Some)),
            "none".map(|_| None),
            fail.label("option")
                .expected_str("none")
                .expected_str("some( /* value */ )"),
        ))
        .parse_next(input)
    }
}

impl ArgParser for Vec2 {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        cut_err(tuple_struct(
            "vec2",
            seq!(
                trim(winnow::ascii::float),
                _: ',',
                trim(winnow::ascii::float),
            ),
        ))
        .map(|(x, y)| Vec2::new(x, y))
        .parse_next(input)
    }
}

impl ArgParser for Vec3 {
    fn parse_arg(input: &mut &str) -> winnow::ModalResult<Self> {
        cut_err(tuple_struct(
            "vec3",
            seq!(
                trim(winnow::ascii::float),
                _: ',',
                trim(winnow::ascii::float),
                _: ',',
                trim(winnow::ascii::float),
            ),
        ))
        .map(|(x, y, z)| Vec3::new(x, y, z))
        .parse_next(input)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[track_caller]
    fn parse<T: ArgParser + PartialEq + std::fmt::Debug>(v: T, mut str: &str) {
        let vp = T::parse_arg(&mut str).unwrap();
        assert_eq!(v, vp);
    }

    #[test]
    fn simple() {
        parse(3.4, "3.4");
        parse(44u32, "44");
        parse(Vec2::new(1.9, 2.3), "vec2(1.9, 2.3)");
        parse(7u32..9, "7..9");
        parse(4.37..9.73, "4.37..9.73");
        parse(4.1..9.0, "4.1..9");
        parse(Some(3), "some(3)");
        parse::<Option<u32>>(None, "none");
        parse(true, "true");
        parse(false, "false");
        parse(String::from("Hello, World!"), "\"Hello, World!\"");
        parse(String::from("Hello, \nWorld!"), "\"Hello, \nWorld!\"");
    }
}