fiasto 0.2.7

High-performance modern Wilkinson's formula parsing for statistical models. Parses R-style formulas into structured JSON metadata supporting linear models, mixed effects, and complex statistical specifications.
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use crate::internal::{ast::*, errors::ParseError, lexer::Token};

/// Parses a random effect term in the format (terms | grouping)
/// Supports various random effects syntax including:
/// - (1 | group) - Random intercepts
/// - (x | group) - Random slopes with intercepts
/// - (x || group) - Uncorrelated random effects
/// - (x |2| group) - Cross-parameter correlation
/// - (x | gr(group, cor = FALSE)) - Enhanced grouping
pub fn parse_random_effect<'a>(
    tokens: &'a [(Token, &'a str)],
    pos: &mut usize,
) -> Result<RandomEffect, ParseError> {
    // Expect opening parenthesis
    crate::internal::expect::expect(tokens, pos, |t| matches!(t, Token::FunctionStart), "(")?;

    // Parse the terms (left side of |)
    let terms = parse_random_terms(tokens, pos)?;

    // Parse the correlation type and grouping (right side of |)
    let (correlation, correlation_id) = parse_correlation_type(tokens, pos)?;
    let grouping = parse_grouping(tokens, pos)?;

    // Expect closing parenthesis
    crate::internal::expect::expect(tokens, pos, |t| matches!(t, Token::FunctionEnd), ")")?;

    Ok(RandomEffect {
        terms,
        grouping,
        correlation,
        correlation_id,
    })
}

/// Parses the terms on the left side of the | in a random effect
fn parse_random_terms<'a>(
    tokens: &'a [(Token, &'a str)],
    pos: &mut usize,
) -> Result<Vec<RandomTerm>, ParseError> {
    let mut terms = Vec::new();

    // Check for intercept suppression
    if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::One)) {
        // Check if followed by + or -
        if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Plus)) {
            // Parse additional terms
            while !crate::internal::matches::matches(tokens, pos, |t| {
                matches!(t, Token::Pipe | Token::DoublePipe)
            }) {
                terms.push(parse_random_term(tokens, pos)?);
                if !crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Plus)) {
                    break;
                }
            }
        } else {
            // Just intercept
            terms.push(RandomTerm::Column("1".to_string()));
        }
    } else if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Zero)) {
        // Check if followed by + (random slopes only)
        if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Plus)) {
            // Parse additional terms (no intercept)
            while !crate::internal::matches::matches(tokens, pos, |t| {
                matches!(t, Token::Pipe | Token::DoublePipe)
            }) {
                terms.push(parse_random_term(tokens, pos)?);
                if !crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Plus)) {
                    break;
                }
            }
        } else {
            // Just zero (no intercept) - but this should not happen in valid syntax
            // Zero should always be followed by + in random effects
            return Err(ParseError::Syntax(
                "expected '+' after '0' in random effects".into(),
            ));
        }
    } else if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Minus)) {
        // Check for -1 or -0 (intercept suppression)
        if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::One | Token::Zero))
        {
            terms.push(RandomTerm::SuppressIntercept);
        } else {
            return Err(ParseError::Syntax(
                "expected '1' or '0' after '-' for intercept suppression".into(),
            ));
        }
    } else {
        // Parse first term
        terms.push(parse_random_term(tokens, pos)?);

        // Parse additional terms
        while crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Plus)) {
            terms.push(parse_random_term(tokens, pos)?);
        }
    }

    Ok(terms)
}

/// Parses a single random term (column, function, or interaction)
fn parse_random_term<'a>(
    tokens: &'a [(Token, &'a str)],
    pos: &mut usize,
) -> Result<RandomTerm, ParseError> {
    let (tok, name_slice) = crate::internal::expect::expect(
        tokens,
        pos,
        |t| {
            matches!(
                t,
                Token::ColumnName | Token::FunctionStart | Token::Cs | Token::Mmc
            )
        },
        "ColumnName, FunctionStart, cs, or mmc",
    )?;

    match tok {
        Token::ColumnName => {
            // Check if this is followed by an interaction
            if crate::internal::matches::matches(tokens, pos, |t| {
                matches!(t, Token::InteractionOnly | Token::InteractionAndEffect)
            }) {
                let right_term = parse_random_term(tokens, pos)?;
                Ok(RandomTerm::Interaction {
                    left: Box::new(RandomTerm::Column(name_slice.to_string())),
                    right: Box::new(right_term),
                })
            } else {
                Ok(RandomTerm::Column(name_slice.to_string()))
            }
        }
        Token::FunctionStart => {
            // This should be handled by the main parser, not here
            Err(ParseError::Syntax(
                "unexpected function start in random term".into(),
            ))
        }
        Token::Cs => {
            // Parse cs() function
            crate::internal::expect::expect(
                tokens,
                pos,
                |t| matches!(t, Token::FunctionStart),
                "(",
            )?;

            // Parse the argument (can be 1, 0, or a column name)
            let (arg_tok, arg_str) = crate::internal::expect::expect(
                tokens,
                pos,
                |t| matches!(t, Token::One | Token::Zero | Token::ColumnName),
                "1, 0, or ColumnName",
            )?;

            let arg = match arg_tok {
                Token::One => crate::internal::ast::Argument::Integer(1),
                Token::Zero => crate::internal::ast::Argument::Integer(0),
                _ => crate::internal::ast::Argument::Ident(arg_str.to_string()),
            };

            crate::internal::expect::expect(tokens, pos, |t| matches!(t, Token::FunctionEnd), ")")?;
            Ok(RandomTerm::Function {
                name: "cs".to_string(),
                args: vec![arg],
            })
        }
        Token::Mmc => {
            // Parse mmc() function
            crate::internal::expect::expect(
                tokens,
                pos,
                |t| matches!(t, Token::FunctionStart),
                "(",
            )?;
            let mut args = Vec::new();

            // Parse first argument
            let (_, arg_name) = crate::internal::expect::expect(
                tokens,
                pos,
                |t| matches!(t, Token::ColumnName),
                "ColumnName",
            )?;
            args.push(crate::internal::ast::Argument::Ident(arg_name.to_string()));

            // Parse additional arguments
            while crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Comma)) {
                let (_, arg_name) = crate::internal::expect::expect(
                    tokens,
                    pos,
                    |t| matches!(t, Token::ColumnName),
                    "ColumnName",
                )?;
                args.push(crate::internal::ast::Argument::Ident(arg_name.to_string()));
            }

            crate::internal::expect::expect(tokens, pos, |t| matches!(t, Token::FunctionEnd), ")")?;
            Ok(RandomTerm::Function {
                name: "mmc".to_string(),
                args,
            })
        }
        _ => Err(ParseError::Unexpected {
            expected: "random term",
            found: Some(tok),
        }),
    }
}

/// Parses the correlation type (|, ||, or |ID|)
fn parse_correlation_type<'a>(
    tokens: &'a [(Token, &'a str)],
    pos: &mut usize,
) -> Result<(CorrelationType, Option<String>), ParseError> {
    if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::DoublePipe)) {
        Ok((CorrelationType::Uncorrelated, None))
    } else if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Pipe)) {
        // Check for cross-parameter correlation ID
        if let Some((Token::Integer, id_slice)) = tokens.get(*pos) {
            *pos += 1;
            if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Pipe)) {
                Ok((
                    CorrelationType::CrossParameter(id_slice.to_string()),
                    Some(id_slice.to_string()),
                ))
            } else {
                Err(ParseError::Syntax(
                    "expected second '|' after correlation ID".into(),
                ))
            }
        } else {
            Ok((CorrelationType::Correlated, None))
        }
    } else {
        Err(ParseError::Unexpected {
            expected: "| or ||",
            found: tokens.get(*pos).map(|(t, _)| t.clone()),
        })
    }
}

/// Parses the grouping structure (right side of |)
fn parse_grouping<'a>(
    tokens: &'a [(Token, &'a str)],
    pos: &mut usize,
) -> Result<Grouping, ParseError> {
    let (tok, name_slice) = crate::internal::expect::expect(
        tokens,
        pos,
        |t| matches!(t, Token::ColumnName | Token::Gr | Token::Mm),
        "ColumnName, gr, or mm",
    )?;

    match tok {
        Token::ColumnName => {
            // Check for nested or interaction grouping
            if crate::internal::matches::matches(tokens, pos, |t| {
                matches!(t, Token::InteractionOnly)
            }) {
                let (_, right_name) = crate::internal::expect::expect(
                    tokens,
                    pos,
                    |t| matches!(t, Token::ColumnName),
                    "ColumnName",
                )?;
                Ok(Grouping::Interaction {
                    left: name_slice.to_string(),
                    right: right_name.to_string(),
                })
            } else if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Slash))
            {
                let (_, right_name) = crate::internal::expect::expect(
                    tokens,
                    pos,
                    |t| matches!(t, Token::ColumnName),
                    "ColumnName",
                )?;
                Ok(Grouping::Nested {
                    outer: name_slice.to_string(),
                    inner: right_name.to_string(),
                })
            } else {
                Ok(Grouping::Simple(name_slice.to_string()))
            }
        }
        Token::Gr => parse_gr_grouping(tokens, pos, name_slice),
        Token::Mm => parse_mm_grouping(tokens, pos),
        _ => Err(ParseError::Unexpected {
            expected: "grouping",
            found: Some(tok),
        }),
    }
}

/// Parses gr() grouping function
fn parse_gr_grouping<'a>(
    tokens: &'a [(Token, &'a str)],
    pos: &mut usize,
    _name_slice: &'a str,
) -> Result<Grouping, ParseError> {
    crate::internal::expect::expect(tokens, pos, |t| matches!(t, Token::FunctionStart), "(")?;

    let (_, group_name) = crate::internal::expect::expect(
        tokens,
        pos,
        |t| matches!(t, Token::ColumnName),
        "ColumnName",
    )?;

    let mut options = Vec::new();

    // Parse options if present
    if crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Comma)) {
        while !crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::FunctionEnd)) {
            options.push(parse_gr_option(tokens, pos)?);
            if !crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Comma)) {
                break;
            }
        }
    }

    crate::internal::expect::expect(tokens, pos, |t| matches!(t, Token::FunctionEnd), ")")?;

    Ok(Grouping::Gr {
        group: group_name.to_string(),
        options,
    })
}

/// Parses gr() function options
fn parse_gr_option<'a>(
    tokens: &'a [(Token, &'a str)],
    pos: &mut usize,
) -> Result<GrOption, ParseError> {
    let (tok, _name_slice) = crate::internal::expect::expect(
        tokens,
        pos,
        |t| {
            matches!(
                t,
                Token::Cor | Token::Id | Token::By | Token::Cov | Token::Dist
            )
        },
        "gr option",
    )?;

    crate::internal::expect::expect(tokens, pos, |t| matches!(t, Token::Equal), "=")?;

    match tok {
        Token::Cor => {
            let (value_tok, _value_str) = crate::internal::expect::expect(
                tokens,
                pos,
                |t| {
                    matches!(
                        t,
                        Token::True | Token::TrueUpper | Token::False | Token::FalseUpper
                    )
                },
                "true or false",
            )?;
            Ok(GrOption::Cor(matches!(
                value_tok,
                Token::True | Token::TrueUpper
            )))
        }
        Token::Id => {
            let (value_tok, value_str) = crate::internal::expect::expect(
                tokens,
                pos,
                |t| matches!(t, Token::ColumnName | Token::StringLiteral),
                "ID string",
            )?;
            let id_value = match value_tok {
                Token::StringLiteral => value_str.trim_matches('"').to_string(),
                _ => value_str.to_string(),
            };
            Ok(GrOption::Id(id_value))
        }
        Token::By => {
            let (value_tok, value_str) = crate::internal::expect::expect(
                tokens,
                pos,
                |t| matches!(t, Token::ColumnName | Token::Null | Token::NullUpper),
                "by variable or NULL",
            )?;
            let by_value = match value_tok {
                Token::Null | Token::NullUpper => None,
                _ => Some(value_str.to_string()),
            };
            Ok(GrOption::By(by_value))
        }
        Token::Cov => {
            let (value_tok, _value_str) = crate::internal::expect::expect(
                tokens,
                pos,
                |t| {
                    matches!(
                        t,
                        Token::True | Token::TrueUpper | Token::False | Token::FalseUpper
                    )
                },
                "true or false",
            )?;
            Ok(GrOption::Cov(matches!(
                value_tok,
                Token::True | Token::TrueUpper
            )))
        }
        Token::Dist => {
            let (value_tok, value_str) = crate::internal::expect::expect(
                tokens,
                pos,
                |t| matches!(t, Token::ColumnName | Token::StringLiteral),
                "distribution",
            )?;
            let dist_value = match value_tok {
                Token::StringLiteral => value_str.trim_matches('"').to_string(),
                _ => value_str.to_string(),
            };
            Ok(GrOption::Dist(dist_value))
        }
        _ => Err(ParseError::Unexpected {
            expected: "gr option",
            found: Some(tok),
        }),
    }
}

/// Parses mm() multi-membership grouping function
fn parse_mm_grouping<'a>(
    tokens: &'a [(Token, &'a str)],
    pos: &mut usize,
) -> Result<Grouping, ParseError> {
    crate::internal::expect::expect(tokens, pos, |t| matches!(t, Token::FunctionStart), "(")?;

    let mut groups = Vec::new();

    // Parse first group
    let (_, group_name) = crate::internal::expect::expect(
        tokens,
        pos,
        |t| matches!(t, Token::ColumnName),
        "ColumnName",
    )?;
    groups.push(group_name.to_string());

    // Parse additional groups
    while crate::internal::matches::matches(tokens, pos, |t| matches!(t, Token::Comma)) {
        let (_, group_name) = crate::internal::expect::expect(
            tokens,
            pos,
            |t| matches!(t, Token::ColumnName),
            "ColumnName",
        )?;
        groups.push(group_name.to_string());
    }

    crate::internal::expect::expect(tokens, pos, |t| matches!(t, Token::FunctionEnd), ")")?;

    Ok(Grouping::Mm { groups })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::internal::lexer::Token;

    #[test]
    fn test_parse_simple_random_effect() {
        let tokens = vec![
            (Token::FunctionStart, "("),
            (Token::One, "1"),
            (Token::Pipe, "|"),
            (Token::ColumnName, "group"),
            (Token::FunctionEnd, ")"),
        ];
        let mut pos = 0;

        let result = parse_random_effect(&tokens, &mut pos);
        assert!(result.is_ok());
        let random_effect = result.unwrap();
        assert_eq!(random_effect.terms.len(), 1);
        assert!(matches!(random_effect.terms[0], RandomTerm::Column(ref name) if name == "1"));
        assert!(matches!(random_effect.grouping, Grouping::Simple(ref name) if name == "group"));
        assert!(matches!(
            random_effect.correlation,
            CorrelationType::Correlated
        ));
    }

    #[test]
    fn test_parse_uncorrelated_random_effect() {
        let tokens = vec![
            (Token::FunctionStart, "("),
            (Token::ColumnName, "x"),
            (Token::DoublePipe, "||"),
            (Token::ColumnName, "group"),
            (Token::FunctionEnd, ")"),
        ];
        let mut pos = 0;

        let result = parse_random_effect(&tokens, &mut pos);
        assert!(result.is_ok());
        let random_effect = result.unwrap();
        assert_eq!(random_effect.terms.len(), 1);
        assert!(matches!(random_effect.terms[0], RandomTerm::Column(ref name) if name == "x"));
        assert!(matches!(
            random_effect.correlation,
            CorrelationType::Uncorrelated
        ));
    }

    #[test]
    fn test_parse_gr_grouping() {
        let tokens = vec![
            (Token::FunctionStart, "("),
            (Token::One, "1"),
            (Token::Pipe, "|"),
            (Token::Gr, "gr"),
            (Token::FunctionStart, "("),
            (Token::ColumnName, "group"),
            (Token::Comma, ","),
            (Token::Cor, "cor"),
            (Token::Equal, "="),
            (Token::False, "false"),
            (Token::FunctionEnd, ")"),
            (Token::FunctionEnd, ")"),
        ];
        let mut pos = 0;

        let result = parse_random_effect(&tokens, &mut pos);
        assert!(result.is_ok());
        let random_effect = result.unwrap();
        assert!(
            matches!(random_effect.grouping, Grouping::Gr { ref group, ref options } if group == "group" && options.len() == 1)
        );
    }
}