praxis-input-parser 0.2.0

The Praxis `read` DSL: template parsing, type synthesis, and parser plans.
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Constructor calls: one argument list, one shape check, one builder (§7.5).
//!
//! Two callers construct a `sep(",", int)`: the HIR bridge, walking the rowan
//! tree of `read sep(",", int)`, and [`crate::body`], parsing the text of a
//! capture body `{xs:sep(",", int)}`. They meet here: both produce a
//! [`CallArg`] list, and [`build_call`] is the only thing that turns one into a
//! [`ParserAst`]. Neither the shape rules nor the builders can drift from each
//! other, because there is one of each.

use crate::ast::{
    BlockItem, Constructor, InvalidRepeatCount, ParserAst, RepeatCount, SectionItem, Separator,
    SkipPolicy,
};
use crate::validate::{ArgKind, ValidationError, check_call};
use praxis_source::{DiagCode, Span};

/// One argument of a constructor call, as written (§7.5).
#[derive(Clone, Debug)]
pub enum CallArg {
    /// A positional parser expression.
    Parser(ParserAst),
    /// A positional string literal (`sep`'s separator, `one_of`'s set),
    /// **already decoded** by `praxis_syntax::literal::unquote_text`.
    String(String),
    /// A positional whole-number literal — the `N` of `repeated(P, N)`,
    /// **already decoded** by `praxis_syntax::numeric::parse_int_literal`.
    /// Still an `i64` here: whether a number is a usable count is
    /// [`RepeatCount`]'s question, and it is asked where the span is.
    Int(i64),
    /// A bare keyword flag: the `ragged` of `grid(P, ragged, fill: 0)`.
    Flag(String),
    /// A named argument `name: parser_expr`.
    Named { name: String, parser: ParserAst },
    /// A named argument whose value is a keyword rather than a parser:
    /// `skip: whitespace`, `fill: 0`.
    Keyword { name: String, value: String },
    /// A `name: repeated(...)` argument of a named `sections`. `count` is
    /// `Some` for the bounded `repeated(P, N)` and `None` for the greedy
    /// `repeated(P)` — the distinction the position rule below is entirely
    /// about.
    RepeatedTail {
        name: String,
        parser: ParserAst,
        count: Option<RepeatCount>,
    },
}

impl CallArg {
    /// This argument's shape, with the payload dropped — what [`check_call`]
    /// reads.
    #[must_use]
    pub fn kind(&self) -> ArgKind {
        match self {
            CallArg::Parser(_) => ArgKind::Parser,
            CallArg::String(_) => ArgKind::String,
            CallArg::Int(_) => ArgKind::Int,
            CallArg::Flag(f) => ArgKind::Flag(f.clone()),
            CallArg::Named { name, .. } => ArgKind::Named(name.clone()),
            // **Not `Named`.** A `skip:`/`fill:` keyword and a `name: parser`
            // argument are different shapes. Collapsing them onto one `ArgKind`
            // would leave `check_call` unable to tell them apart, so `block`,
            // `choice` and named `sections` would accept a keyword as a
            // well-shaped named argument their builders have nowhere to put.
            CallArg::Keyword { name, .. } => ArgKind::Keyword(name.clone()),
            CallArg::RepeatedTail { name, .. } => ArgKind::RepeatedTail(name.clone()),
        }
    }
}

/// Build the [`ParserAst`] for `ctor(args…)`, or report every reason it cannot
/// be built.
///
/// **Nothing is built before the shape is checked** (IP-07): the argument list
/// goes through [`check_call`] first, so by the time an arm below runs it has
/// exactly the arguments §7.5 gives that constructor and there is nothing left
/// for it to drop.
///
/// # Errors
/// A non-empty [`ValidationError`] list. Each carries the [`DiagCode`] the
/// caller reports it under.
pub fn build_call(
    ctor: Constructor,
    args: Vec<CallArg>,
    span: Span,
) -> Result<ParserAst, Vec<ValidationError>> {
    if ctor == Constructor::Repeated {
        // `repeated(...)` is not a parser in its own right — it is the marker
        // on a named argument of a `sections` call, saying that the field takes
        // a *group* of sections rather than one. Anywhere else there is nothing
        // for it to repeat over, so it is reported rather than dropped (IP-09).
        return Err(vec![ValidationError {
            span,
            code: DiagCode::MisplacedRepeatedTail,
            message: "`repeated(...)` is only a named argument of a `sections` call".to_string(),
        }]);
    }

    let kinds: Vec<ArgKind> = args.iter().map(CallArg::kind).collect();
    let shape_errors = check_call(ctor, &kinds, span);
    if !shape_errors.is_empty() {
        return Err(shape_errors);
    }

    let internal = |what: &str| {
        vec![ValidationError {
            span,
            code: DiagCode::InvalidConstructorArgument,
            message: format!("`{}` {what}", ctor.keyword()),
        }]
    };
    // **A `_ => {}` arm in a builder is how an argument disappears** (IP-07).
    // Every arm below is exhaustive over what its shape admits, and an argument
    // it does not know is *reported* rather than dropped. It should be
    // unreachable — `check_call` has already run — and the point is precisely
    // that if it ever is reachable, it is visible.
    let unexpected = |arg: &CallArg| {
        vec![ValidationError {
            span,
            code: DiagCode::InvalidConstructorArgument,
            message: format!(
                "`{}` does not take {}",
                ctor.keyword(),
                arg.kind().describe()
            ),
        }]
    };

    match ctor {
        Constructor::Lines
        | Constructor::Csv
        | Constructor::Ws
        | Constructor::Matrix
        | Constructor::Optional
        | Constructor::Scan => {
            let child = Box::new(sole_parser(args).ok_or_else(|| internal("needs one parser"))?);
            Ok(match ctor {
                Constructor::Lines => ParserAst::Lines { child, span },
                Constructor::Csv => ParserAst::Csv { child, span },
                Constructor::Ws => ParserAst::Ws { child, span },
                Constructor::Matrix => ParserAst::Matrix { child, span },
                Constructor::Optional => ParserAst::Optional { child, span },
                _ => ParserAst::Scan { child, span },
            })
        }
        Constructor::Sections => {
            // One name, two shapes: `sections(P)` is homogeneous,
            // `sections(name: P, …)` is the heterogeneous form.
            if kinds
                .iter()
                .any(|k| matches!(k, ArgKind::Named(_) | ArgKind::RepeatedTail(_)))
            {
                build_sections_named(args, span)
            } else {
                Ok(ParserAst::Sections {
                    child: Box::new(sole_parser(args).ok_or_else(|| internal("needs one parser"))?),
                    span,
                })
            }
        }
        Constructor::Sep => {
            let mut separator = None;
            let mut child = None;
            for arg in args {
                match arg {
                    CallArg::String(s) => separator = Some(s),
                    CallArg::Parser(p) => child = Some(p),
                    other => return Err(unexpected(&other)),
                }
            }
            // An empty separator is the one separator that can never advance a
            // cursor (IP-10), so `Separator::new` refuses it rather than
            // letting a missing one default to `String::new()`.
            let separator = Separator::new(separator.as_deref().unwrap_or("")).map_err(|_| {
                vec![ValidationError {
                    span,
                    code: DiagCode::EmptySeparator,
                    message: "`sep` needs a non-empty separator: an empty one never advances"
                        .to_string(),
                }]
            })?;
            Ok(ParserAst::Sep {
                separator,
                child: Box::new(child.ok_or_else(|| internal("needs an element parser"))?),
                span,
            })
        }
        Constructor::OneOf => {
            let mut chars = None;
            for arg in args {
                match arg {
                    CallArg::String(s) => chars = Some(s),
                    other => return Err(unexpected(&other)),
                }
            }
            Ok(ParserAst::OneOf {
                chars: chars.ok_or_else(|| internal("needs a character set"))?,
                span,
            })
        }
        Constructor::Chars => {
            let mut child = None;
            let mut skip = SkipPolicy::Whitespace;
            for arg in args {
                match arg {
                    CallArg::Parser(p) => child = Some(p),
                    // The keyword's name comes from the constructor, not from a
                    // literal here: `Constructor::keyword_arg` is the one place
                    // that says `chars` takes `skip:`.
                    CallArg::Keyword { name, value }
                        if Some(name.as_str()) == ctor.keyword_arg() =>
                    {
                        // An unrecognized policy is reported rather than left at
                        // the default, so `skip: wihtespace` cannot silently
                        // run as `whitespace`.
                        skip = SkipPolicy::from_keyword(&value).ok_or_else(|| {
                            vec![ValidationError {
                                span,
                                code: DiagCode::InvalidConstructorArgument,
                                // The three names alone are a trap: nothing in
                                // them says `newlines` is the *broader* policy.
                                // Each one states what it skips.
                                message: format!(
                                    "`skip: {value}` is not a skip policy — `none` (skips {}), \
                                     `whitespace` (skips {}) or `newlines` (skips {})",
                                    SkipPolicy::None.skips(),
                                    SkipPolicy::Whitespace.skips(),
                                    SkipPolicy::Newlines.skips(),
                                ),
                            }]
                        })?;
                    }
                    other => return Err(unexpected(&other)),
                }
            }
            Ok(ParserAst::Characters {
                child: Box::new(child.ok_or_else(|| internal("needs a character parser"))?),
                skip,
                span,
            })
        }
        Constructor::Grid => {
            let mut child = None;
            let mut fill = None;
            for arg in args {
                match arg {
                    CallArg::Parser(p) => child = Some(p),
                    // `fill:` is spelled by `Constructor::keyword_arg` and not
                    // here, so the name this arm reads and the name the front
                    // ends mint cannot drift apart.
                    CallArg::Keyword { name, value }
                        if Some(name.as_str()) == ctor.keyword_arg() =>
                    {
                        // The value arrives as raw source text, so the decode
                        // lives here, once, and both front ends agree:
                        // `fill: "-"` reaches the plan as `-` and not as
                        // `"\"-\""`, quotes and all (IP-08's rule for every
                        // other parser string literal).
                        let decoded = praxis_syntax::literal::unquote_text(&value);
                        // **A keyword argument's value is part of its shape**,
                        // as `chars`'s `skip:` value is. An empty `fill:` is
                        // the same unrepresentable value IP-10 refuses one
                        // field over, where `Separator::new` rejects an empty
                        // separator because it never advances: a cell of no
                        // characters pads nothing.
                        if decoded.is_empty() {
                            return Err(vec![ValidationError {
                                span,
                                code: DiagCode::InvalidConstructorArgument,
                                message: "`fill:` needs a value to pad a short row with — an \
                                          empty one fills nothing"
                                    .to_string(),
                            }]);
                        }
                        fill = Some(decoded);
                    }
                    // `ragged` carries nothing: it exists so the shape table
                    // can *require* it beside `fill:`. Matched here rather than
                    // swept up by a wildcard, so it is a decision and not a
                    // leak — and matched against `Constructor::flag_arg`, so
                    // the flag is `grid`'s and not a bare word this arm agrees
                    // with by coincidence.
                    CallArg::Flag(f) if Some(f.as_str()) == ctor.flag_arg() => {}
                    other => return Err(unexpected(&other)),
                }
            }
            let child = Box::new(child.ok_or_else(|| internal("needs a cell parser"))?);
            Ok(match fill {
                Some(fill) => ParserAst::GridRagged { child, fill, span },
                None => ParserAst::Grid { child, span },
            })
        }
        Constructor::Block => {
            let mut items = Vec::with_capacity(args.len());
            for arg in args {
                match arg {
                    CallArg::Parser(p) => items.push(BlockItem::Positional(p)),
                    CallArg::Named { name, parser } => {
                        items.push(BlockItem::Named { name, parser })
                    }
                    other => return Err(unexpected(&other)),
                }
            }
            Ok(ParserAst::Block { items, span })
        }
        Constructor::Choice => {
            let mut cases = Vec::with_capacity(args.len());
            for arg in args {
                match arg {
                    CallArg::Named { name, parser } => cases.push((name, parser)),
                    other => return Err(unexpected(&other)),
                }
            }
            Ok(ParserAst::Choice { cases, span })
        }
        // Refused at the top, before the shape check.
        Constructor::Repeated => Err(internal("is not a parser")),
    }
}

/// Build the `name: repeated(P)` / `name: repeated(P, N)` marker of a named
/// `sections` (§7.5).
///
/// `repeated(...)` is not a parser in its own right — it is the marker on a
/// named argument of a `sections` call, and the field's parser is the `P`. §7.5
/// gives the marker a parser and an optional count. That is the whole rule, and
/// it lives here for the same reason [`build_call`] does: **both front ends
/// must apply it**.
///
/// The shape check is [`check_call`]'s, like every other constructor's, so
/// ADR-073's "nothing is built before the shape is checked" covers the marker
/// too and the two front ends cannot disagree about it.
///
/// # Errors
/// A non-empty [`ValidationError`] list: `ConstructorArity` (I022) for a wrong
/// count of arguments, `InvalidConstructorArgument` (I014) for a wrong kind or
/// an unusable count.
pub fn build_repeated_tail(
    name: String,
    args: Vec<CallArg>,
    span: Span,
) -> Result<CallArg, Vec<ValidationError>> {
    let kinds: Vec<ArgKind> = args.iter().map(CallArg::kind).collect();
    let shape_errors = check_call(Constructor::Repeated, &kinds, span);
    if !shape_errors.is_empty() {
        return Err(shape_errors);
    }

    let bad = |message: String| {
        vec![ValidationError {
            span,
            code: DiagCode::InvalidConstructorArgument,
            message,
        }]
    };

    let mut args = args.into_iter();
    let parser = match args.next() {
        Some(CallArg::Parser(parser)) => parser,
        Some(other) => {
            return Err(bad(format!(
                "`repeated`'s first argument must be a parser, but it is {}",
                other.kind().describe()
            )));
        }
        // `check_call` has already reported the empty list.
        None => return Err(bad("`repeated` needs a parser".to_string())),
    };
    let count = match args.next() {
        None => None,
        Some(CallArg::Int(n)) => Some(RepeatCount::new(n).map_err(|why| {
            bad(match why {
                InvalidRepeatCount::NotPositive => "`repeated`'s count must be at least 1 — a \
                                                   group of no sections parses nothing"
                    .to_string(),
                InvalidRepeatCount::TooLarge => {
                    "`repeated`'s count must fit in 32 bits".to_string()
                }
            })
        })?),
        Some(other) => {
            return Err(bad(format!(
                "`repeated`'s count must be a whole-number literal, but it is {} — the parser \
                 plan is built when the program is compiled, so the count cannot be a parser or \
                 a variable",
                other.kind().describe()
            )));
        }
    };
    Ok(CallArg::RepeatedTail {
        name,
        parser,
        count,
    })
}

/// The single positional parser of a call `check_call` has already accepted.
fn sole_parser(args: Vec<CallArg>) -> Option<ParserAst> {
    match args.into_iter().next() {
        Some(CallArg::Parser(p)) => Some(p),
        _ => None,
    }
}

/// Build a heterogeneous `sections(name: P, …, tail: repeated(P))` (§7.5).
///
/// §7.5: "`repeated(parser)` may appear only as the final named argument."
/// Both halves are checked here (IP-09): at most one unbounded tail, and it
/// last. `args` is in source order, which is what makes "final" a checkable
/// claim.
///
/// **The position rule is the unbounded form's alone.** `repeated(P)` consumes
/// every section that is left, so a field after it could never match — that is
/// what "final" is an argument *from*, and it is no argument at all about
/// `repeated(P, N)`, which consumes exactly `N` and leaves the rest. A counted
/// group is an ordinary named argument in every respect, including being
/// allowed to be the last one.
fn build_sections_named(args: Vec<CallArg>, span: Span) -> Result<ParserAst, Vec<ValidationError>> {
    let unbounded: Vec<usize> = args
        .iter()
        .enumerate()
        .filter(|(_, a)| matches!(a, CallArg::RepeatedTail { count: None, .. }))
        .map(|(i, _)| i)
        .collect();
    if unbounded.len() > 1 {
        return Err(vec![ValidationError {
            span,
            code: DiagCode::MisplacedRepeatedTail,
            message: "`sections` takes at most one unbounded `repeated(...)` tail".to_string(),
        }]);
    }
    if let Some(&at) = unbounded.first()
        && at != args.len() - 1
    {
        return Err(vec![ValidationError {
            span,
            code: DiagCode::MisplacedRepeatedTail,
            message: "an unbounded `repeated(...)` tail may appear only as the final named \
                          argument: it consumes every remaining section, so nothing can \
                          follow it — write `repeated(P, N)` for a group of N sections, which can"
                .to_string(),
        }]);
    }

    let mut fields: Vec<SectionItem> = Vec::new();
    let mut repeated_tail: Option<(String, Box<ParserAst>)> = None;
    for arg in args {
        match arg {
            CallArg::Named { name, parser } => fields.push(SectionItem::One { name, parser }),
            CallArg::RepeatedTail {
                name,
                parser,
                count: Some(count),
            } => fields.push(SectionItem::Counted {
                name,
                count,
                parser,
            }),
            CallArg::RepeatedTail {
                name,
                parser,
                count: None,
            } => {
                repeated_tail = Some((name, Box::new(parser)));
            }
            // `check_call` has already refused a positional, a string or a
            // keyword here — and this reports rather than drops, because a
            // `_ => {}` is how a field vanishes from a record in silence.
            other => {
                return Err(vec![ValidationError {
                    span,
                    code: DiagCode::InvalidConstructorArgument,
                    message: format!("`sections` does not take {}", other.kind().describe()),
                }]);
            }
        }
    }
    Ok(ParserAst::SectionsNamed {
        fields,
        repeated_tail,
        span,
    })
}