swiftlet 0.2.3

swiftlet is a high-performance text-parsing library for Rust, inspired by Python’s Lark.
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
use std::sync::Arc;
use swiftlet::error::{GrammarError, SwiftletError};
use swiftlet::grammar::Algorithm;
use swiftlet::{Ambiguity, ParserConfig, Swiftlet};

fn earley(start: &str) -> Arc<ParserConfig> {
    Arc::new(ParserConfig {
        algorithm: Algorithm::Earley,
        start: start.to_string(),
        ..Default::default()
    })
}

fn clr(start: &str) -> Arc<ParserConfig> {
    Arc::new(ParserConfig {
        algorithm: Algorithm::CLR,
        start: start.to_string(),
        ..Default::default()
    })
}

// ---------- RuleCompiler coverage ----------

#[test]
fn rule_compiler_maybe_in_rule_earley() {
    // Covers RuleCompiler::maybe() — `[...]` optional block in a rule body.
    let grammar = r#"
    start: greeting
    greeting: "hi" [name]
    name: WORD
    WORD: /\w+/
    %import WS
    %ignore WS
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(earley("start")).parse("hi").is_ok());
    assert!(s.parser(earley("start")).parse("hi Alice").is_ok());
}

#[test]
fn rule_compiler_maybe_in_rule_clr() {
    let grammar = r#"
    start: greeting
    greeting: "hi" [name]
    name: WORD
    WORD: /\w+/
    %import WS
    %ignore WS
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(clr("start")).parse("hi").is_ok());
    assert!(s.parser(clr("start")).parse("hi Alice").is_ok());
}

#[test]
fn rule_compiler_range_in_rule_is_exercised() {
    // Covers RuleCompiler::range() (lines 476-493). A range like "a".."z" in a
    // rule body produces `[a-z]` which get_symbol() classifies as NonTerminal
    // (contains lowercase chars), so grammar compilation fails with
    // RuleProductionNotFound — that's the expected behaviour.
    let grammar = "start: letter\nletter: \"a\"..\"z\"\n";
    let err = match Swiftlet::from_str(grammar) {
        Ok(_) => panic!("range-in-rule with lowercase chars should fail to compile"),
        Err(e) => e,
    };
    assert!(
        matches!(err, SwiftletError::Grammar(_)),
        "expected GrammarError, got: {:?}",
        err
    );
}

#[test]
fn rule_compiler_inline_regex_in_rule_earley() {
    // Covers RuleCompiler::regex() — inline regex pattern inside a rule.
    let grammar = r#"
    start: token
    token: /[a-z]+/
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(earley("start")).parse("hello").is_ok());
}

#[test]
fn rule_compiler_inline_regex_in_rule_clr() {
    let grammar = r#"
    start: token
    token: /[a-z]+/
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(clr("start")).parse("hello").is_ok());
}

#[test]
fn rule_compiler_rule_priority_earley() {
    // Covers RuleCompiler::rule() priority branch (tree.len() > 2).
    let grammar = r#"
    start: expr
    expr.1: keyword
    expr: NAME
    keyword: "select"
    NAME: /[a-z]+/
    %import WS
    %ignore WS
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(earley("start")).parse("select").is_ok());
    assert!(s.parser(earley("start")).parse("hello").is_ok());
}

#[test]
fn rule_compiler_or_expansion_cache_hit() {
    // Covers or_expansion cache path — same OR alternatives reused in multiple rules.
    let grammar = r#"
    start: a | b
    a: c | d
    b: c | d
    c: "x"
    d: "y"
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(earley("start")).parse("x").is_ok());
    assert!(s.parser(earley("start")).parse("y").is_ok());
}

#[test]
fn rule_compiler_inline_string_case_insensitive_in_rule() {
    // Covers RuleCompiler::string() case-insensitive path ("word"i in a rule).
    let grammar = r#"
    start: greeting
    greeting: "hello"i
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(earley("start")).parse("hello").is_ok());
    assert!(s.parser(earley("start")).parse("HELLO").is_ok());
    assert!(s.parser(earley("start")).parse("Hello").is_ok());
}

#[test]
fn rule_compiler_inline_string_case_insensitive_in_rule_clr() {
    let grammar = r#"
    start: greeting
    greeting: "hello"i
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(clr("start")).parse("HELLO").is_ok());
}

// ---------- load_grammar.rs coverage ----------

#[test]
fn load_grammar_returns_error_for_undefined_non_terminal() {
    // Covers RuleCompiler::get_grammar() error branch (lines 295-296 in transform.rs).
    let grammar = "start: undefined_rule\n";
    let err = match Swiftlet::from_str(grammar) {
        Ok(_) => panic!("expected error for undefined non-terminal"),
        Err(e) => e,
    };
    assert!(
        matches!(
            err,
            SwiftletError::Grammar(GrammarError::RuleProductionNotFound(_))
        ),
        "expected RuleProductionNotFound, got: {:?}",
        err
    );
}

#[test]
fn load_grammar_with_inline_literal_ignore_directive() {
    // Covers update_terminals else branch in load_grammar.rs (lines 175-179):
    // %ignore applied to a literal string that is NOT a common terminal name.
    let grammar = r#"
    start: WORD+
    WORD: /[a-zA-Z]+/
    %ignore " "
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(earley("start")).parse("hello world").is_ok());
}

#[test]
fn load_grammar_with_inline_literal_ignore_clr() {
    let grammar = r#"
    start: WORD+
    WORD: /[a-zA-Z]+/
    %ignore " "
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(clr("start")).parse("foo bar").is_ok());
}

// ---------- terminal compiler coverage ----------

#[test]
fn terminal_compiler_multiline_regex_flag() {
    // Covers TerminalCompiler::transform_regex() `m` (multiline) flag path (line 106).
    let grammar = r#"
    start: LINE+
    LINE: /^\w+/m
    %import (NEWLINE, WS_INLINE)
    %ignore WS_INLINE
    %ignore NEWLINE
    "#;
    // If the regex compiles, the grammar loads successfully.
    let result = Swiftlet::from_str(grammar);
    assert!(result.is_ok(), "multiline regex grammar should compile: {:?}", result.err());
}

// ---------- Earley explicit ambiguity coverage ----------

#[test]
fn earley_explicit_ambiguity_returns_ambiguity_tree() {
    // Covers Ambiguity::Explicit path — wraps all derivations under _ambiguity.
    let grammar = r#"
    start: expr
    expr: expr "+" expr
        | INT
    %import (WS, INT)
    %ignore WS
    "#;
    let config = Arc::new(ParserConfig {
        algorithm: Algorithm::Earley,
        ambiguity: Ambiguity::Explicit,
        start: "start".to_string(),
        debug: false,
    });
    let swiftlet = Swiftlet::from_str(grammar).unwrap();
    let result = swiftlet.parser(config).parse("1 + 2 + 3");
    assert!(result.is_ok(), "explicit ambiguity parse should succeed");
    let tree_str = result.unwrap().inline_text();
    assert!(
        tree_str.contains("_ambiguity") || tree_str.contains("start"),
        "unexpected tree: {}",
        tree_str
    );
}

// ---------- CLR shift-action error fallback ----------

#[test]
fn clr_parse_fails_cleanly_on_incomplete_input() {
    // Exercises the CLR shift_action / lookahead error path.
    let grammar = r#"
    start: A B
    A: "x"
    B: "y"
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    let err = s.parser(clr("start")).parse("x").unwrap_err();
    assert!(
        matches!(
            err,
            SwiftletError::Parse(_) | SwiftletError::Lexer(_)
        ),
        "unexpected error type: {:?}",
        err
    );
}

// ---------- fetch_terminals path coverage ----------

#[test]
fn grammar_with_ignore_uses_string_literal_form() {
    // Covers fetch_terminals() quoted-string strip path (line 22 in transform.rs).
    let grammar = r#"
    start: NAME
    NAME: /[a-zA-Z]+/
    %ignore ","
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(earley("start")).parse("hello").is_ok());
}

// ---------- Grammar with repeated terminal dedup ----------

#[test]
fn grammar_with_multiple_terminals_deduplicates_correctly() {
    // Exercises the terminal sort + dedup path in load_grammar.rs.
    let grammar = r#"
    start: A B C
    A: "aa"
    B: "bb"
    C: "cc"
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(earley("start")).parse("aabbcc").is_ok());
    assert!(s.parser(clr("start")).parse("aabbcc").is_ok());
}

// ---------- Expandable-rule (?rule) coverage ----------

#[test]
fn rule_compiler_expandable_rule_earley() {
    // Covers origin_apply() `?` expand branch (line 262 transform.rs) and
    // wrap_contribution() expand path (line 570 earley.rs).
    let grammar = r#"
    start: value
    ?value: number | word
    number: INT
    word: WORD
    WORD: /[a-z]+/
    %import (WS, INT)
    %ignore WS
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    // ?value expands inline — neither a "value" nor "_ambiguity" tree node appears.
    let result = s.parser(earley("start")).parse("42").unwrap();
    let text = result.inline_text();
    assert!(
        !text.contains("Tree(\"value\""),
        "?value should be expanded away, got: {}",
        text
    );
    let result2 = s.parser(earley("start")).parse("hello").unwrap();
    let text2 = result2.inline_text();
    assert!(!text2.contains("Tree(\"value\""), "?value should expand: {}", text2);
}

#[test]
fn rule_compiler_expandable_rule_clr() {
    let grammar = r#"
    start: value
    ?value: number | word
    number: INT
    word: WORD
    WORD: /[a-z]+/
    %import (WS, INT)
    %ignore WS
    "#;
    let s = Swiftlet::from_str(grammar).unwrap();
    assert!(s.parser(clr("start")).parse("99").is_ok());
    assert!(s.parser(clr("start")).parse("abc").is_ok());
}

// ---------- Explicit ambiguity — verify _ambiguity node ----------

#[test]
fn earley_explicit_ambiguity_produces_ambiguity_node_for_ambiguous_input() {
    // Covers earley.rs finalize_explicit_parse when multiple derivations exist.
    let grammar = r#"
    start: expr
    expr: expr "+" expr
        | INT
    %import (WS, INT)
    %ignore WS
    "#;
    let config = Arc::new(ParserConfig {
        algorithm: Algorithm::Earley,
        ambiguity: Ambiguity::Explicit,
        start: "start".to_string(),
        debug: false,
    });
    let swiftlet = Swiftlet::from_str(grammar).unwrap();
    // "1 + 2 + 3" is genuinely ambiguous: (1+2)+3 or 1+(2+3)
    let result = swiftlet.parser(config).parse("1 + 2 + 3").unwrap();
    let text = result.inline_text();
    // With explicit ambiguity, multiple derivations are wrapped in an _ambiguity node.
    assert!(
        text.contains("_ambiguity"),
        "expected _ambiguity wrapper for ambiguous parse, got: {}",
        text
    );
}

// ---------- Earley contribution_all expand / alias paths ----------

#[test]
fn earley_explicit_ambiguity_with_expandable_rule() {
    // Covers contribution_all() expand path (line 662 earley.rs).
    let grammar = r#"
    start: expr
    expr: expr "+" expr | base
    ?base: INT
    %import (WS, INT)
    %ignore WS
    "#;
    let config = Arc::new(ParserConfig {
        algorithm: Algorithm::Earley,
        ambiguity: Ambiguity::Explicit,
        start: "start".to_string(),
        debug: false,
    });
    let swiftlet = Swiftlet::from_str(grammar).unwrap();
    let result = swiftlet.parser(config).parse("1 + 2 + 3");
    assert!(result.is_ok(), "explicit ambiguity with ?base should succeed: {:?}", result.err());
}

// ---------- CLR parser errors ----------

#[test]
fn clr_fails_on_unknown_token_at_start() {
    // Exercises CLR parse() initial lookahead handling.
    let grammar = r#"
    start: INT
    %import INT
    "#;
    let err = Swiftlet::from_str(grammar)
        .unwrap()
        .parser(clr("start"))
        .parse("abc")
        .unwrap_err();
    assert!(matches!(err, SwiftletError::Parse(_) | SwiftletError::Lexer(_)));
}