nash-parse 0.6.1

Parser for the nash programming language
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
use bumpalo::collections::Vec as BumpVec;
use nash_region::{Located, Position, Region};
use nash_source::{Block, Budget, Expect, Test, TestBody, Tests, ViaBinder};

use crate::Parser;
use crate::error::{self, Test as TestErr, Tests as TestsErr};

impl<'a> Parser<'a> {
    pub(crate) fn tests_block(&mut self) -> Result<&'a Tests<'a>, error::Module<'a>> {
        self.in_context(
            |bump, error, row, col| error::Module::Tests(bump.alloc(error), row, col),
            |parser| parser.keyword_tests(error::Module::BadEnd),
            |parser| {
                let tests_end = parser.get_position();
                parser.chomp(TestsErr::Space)?;
                if parser.is_eof() || parser.col() == 1 {
                    return Ok(parser.alloc(Tests {
                        imports: &[],
                        tests: &[],
                    }));
                }
                parser.check_indent(tests_end.line, tests_end.column, TestsErr::IndentStart)?;
                parser.with_indent(|parser| {
                    let imports = parser.specialize(
                        |bump, error, row, col| TestsErr::Import(bump.alloc(error), row, col),
                        |parser| parser.imports(),
                    )?;
                    let mut tests = BumpVec::new_in(parser.bump);

                    loop {
                        if parser.is_eof() || parser.col() < parser.indent() {
                            break;
                        }
                        parser.check_aligned(TestsErr::Alignment)?;
                        let test = parser.specialize(
                            |bump, error, row, col| TestsErr::Test(bump.alloc(error), row, col),
                            |parser| parser.test_item(),
                        )?;
                        tests.push(test);
                    }

                    Ok(parser.alloc(Tests {
                        imports,
                        tests: tests.into_bump_slice(),
                    }))
                })
            },
        )
    }

    fn test_item(&mut self) -> Result<&'a Located<Test<'a>>, TestErr<'a>> {
        let start = self.get_position();
        let is_prop = self.one_of(
            TestErr::NameStart,
            vec![
                Box::new(|parser: &mut Parser<'a>| {
                    parser.keyword_test(TestErr::NameStart)?;
                    Ok(false)
                }),
                Box::new(|parser: &mut Parser<'a>| {
                    parser.keyword_prop(TestErr::NameStart)?;
                    Ok(true)
                }),
            ],
        )?;
        self.chomp_and_check_indent(TestErr::Space, TestErr::IndentName)?;
        let name_start = self.get_position();
        let name_str = self.string_literal(TestErr::NameStart, TestErr::Name)?;
        let name = self.add_end(name_start, name_str);
        self.chomp_and_check_indent(TestErr::Space, TestErr::IndentEquals)?;
        let expect = self.test_expect(is_prop)?;
        let budget = self.test_budget()?;
        self.word1(b'=', TestErr::Equals)?;
        self.chomp_and_check_indent(TestErr::Space, TestErr::IndentBody)?;
        let (body, end) = if is_prop {
            self.prop_body()?
        } else {
            let (block, end) = self.test_block()?;
            (TestBody::Unit(block), end)
        };
        self.chomp(TestErr::Space)?;
        Ok(self.alloc(Located::at(
            Region::new(start, end),
            Test {
                name,
                expect,
                budget,
                body,
            },
        )))
    }

    fn test_block(&mut self) -> Result<(&'a Block<'a>, Position), TestErr<'a>> {
        self.keyword_do(TestErr::Do)?;
        self.chomp_and_check_indent(TestErr::Space, TestErr::IndentBody)?;
        let parent_indent = self.indent();
        let (stmts, last, end) = self.specialize(
            |bump, error, row, col| TestErr::Body(bump.alloc(error), row, col),
            |parser| parser.with_indent(|parser| parser.do_body(parent_indent)),
        )?;
        Ok((self.alloc(Block { stmts, last }), end))
    }

    fn test_expect(&mut self, is_prop: bool) -> Result<Expect, TestErr<'a>> {
        self.one_of_with_fallback(
            vec![Box::new(|parser: &mut Parser<'a>| {
                parser.keyword_fail(TestErr::Equals)?;
                parser.chomp_and_check_indent(TestErr::Space, TestErr::IndentEquals)?;
                let (row, col) = parser.position();
                parser.one_of_with_fallback(
                    vec![Box::new(|parser: &mut Parser<'a>| {
                        parser.keyword_once(TestErr::OnceOnUnitTest)?;
                        if !is_prop {
                            return Err(TestErr::OnceOnUnitTest(row, col));
                        }
                        parser.chomp_and_check_indent(TestErr::Space, TestErr::IndentEquals)?;
                        Ok(Expect::FailOnce)
                    })],
                    Expect::Fail,
                )
            })],
            Expect::Pass,
        )
    }

    fn test_budget(&mut self) -> Result<Option<Budget>, TestErr<'a>> {
        self.one_of_with_fallback(
            vec![Box::new(|parser: &mut Parser<'a>| {
                parser.keyword_within(TestErr::Equals)?;
                parser.chomp_and_check_indent(TestErr::Space, TestErr::WithinOpen)?;
                let opening = parser.get_position();
                parser.word1(b'(', TestErr::WithinOpen)?;
                parser.chomp_and_check_indent(TestErr::Space, TestErr::WithinKind)?;
                let first = parser.budget_entry()?;
                parser.chomp_and_check_indent(TestErr::Space, |r, c| {
                    TestErr::WithinEnd(opening, r, c)
                })?;
                let budget = parser.one_of(
                    |r, c| TestErr::WithinEnd(opening, r, c),
                    vec![
                        Box::new(|parser: &mut Parser<'a>| {
                            parser.word1(b',', |r, c| TestErr::WithinEnd(opening, r, c))?;
                            parser.chomp_and_check_indent(TestErr::Space, TestErr::WithinKind)?;
                            let (row, col) = parser.position();
                            let second = parser.budget_entry()?;
                            parser.chomp_and_check_indent(TestErr::Space, |r, c| {
                                TestErr::WithinEnd(opening, r, c)
                            })?;
                            parser.word1(b')', |r, c| TestErr::WithinEnd(opening, r, c))?;
                            match (first, second) {
                                (Budget::Cpu(cpu), Budget::Mem(mem))
                                | (Budget::Mem(mem), Budget::Cpu(cpu)) => {
                                    Ok(Budget::Both { cpu, mem })
                                }
                                _ => Err(TestErr::WithinDuplicate(row, col)),
                            }
                        }),
                        Box::new(|parser: &mut Parser<'a>| {
                            parser.word1(b')', |r, c| TestErr::WithinEnd(opening, r, c))?;
                            Ok(first)
                        }),
                    ],
                )?;
                parser.chomp_and_check_indent(TestErr::Space, TestErr::IndentEquals)?;
                Ok(Some(budget))
            })],
            None,
        )
    }

    fn budget_entry(&mut self) -> Result<Budget, TestErr<'a>> {
        let constructor = self.one_of(
            TestErr::WithinKind,
            vec![
                Box::new(|parser: &mut Parser<'a>| {
                    parser.keyword_cpu(TestErr::WithinKind)?;
                    Ok(Budget::Cpu as fn(i128) -> Budget)
                }),
                Box::new(|parser: &mut Parser<'a>| {
                    parser.keyword_mem(TestErr::WithinKind)?;
                    Ok(Budget::Mem as fn(i128) -> Budget)
                }),
            ],
        )?;
        self.chomp_and_check_indent(TestErr::Space, TestErr::WithinKind)?;
        let number = self.number_literal(TestErr::WithinKind, TestErr::WithinNumber)?;
        Ok(constructor(number))
    }

    fn prop_body(&mut self) -> Result<(TestBody<'a>, Position), TestErr<'a>> {
        self.keyword_let(TestErr::Let)?;
        let (binders, binders_end) = self.with_backset_indent(3, |parser| {
            parser.chomp_and_check_indent(TestErr::Space, TestErr::IndentBinder)?;
            parser.with_indent(|parser| {
                let mut binders = BumpVec::new_in(parser.bump);
                let (first, mut end) = parser.via_binder()?;
                binders.push(first);

                loop {
                    if parser.next_is_keyword(b"in") || parser.col() < parser.indent() {
                        break;
                    }
                    parser.check_aligned(TestErr::BinderAlignment)?;
                    let (binder, binder_end) = parser.via_binder()?;
                    binders.push(binder);
                    end = binder_end;
                }
                Ok((binders.into_bump_slice(), end))
            })
        })?;
        self.check_indent(binders_end.line, binders_end.column, TestErr::IndentIn)?;
        self.keyword_in(TestErr::In)?;
        self.chomp_and_check_indent(TestErr::Space, TestErr::IndentBody)?;
        let (body, end) = self.test_block()?;
        Ok((TestBody::Prop { binders, body }, end))
    }

    fn via_binder(&mut self) -> Result<(&'a Located<ViaBinder<'a>>, Position), TestErr<'a>> {
        let start = self.get_position();
        let pattern = self.specialize(
            |bump, error, row, col| TestErr::Pattern(bump.alloc(error), row, col),
            |parser| parser.pattern_term(),
        )?;
        self.chomp_and_check_indent(TestErr::Space, TestErr::Via)?;
        self.keyword_via(TestErr::Via)?;
        self.chomp_and_check_indent(TestErr::Space, TestErr::IndentBinder)?;
        let (fuzzer, end) = self.specialize(
            |bump, error, row, col| TestErr::Fuzzer(bump.alloc(error), row, col),
            |parser| parser.expression(),
        )?;
        Ok((
            self.alloc(Located::at(
                Region::new(start, end),
                ViaBinder { pattern, fuzzer },
            )),
            end,
        ))
    }

    fn next_is_keyword(&self, keyword: &[u8]) -> bool {
        let remaining = self.remaining();
        remaining.starts_with(keyword)
            && remaining
                .get(keyword.len())
                .is_none_or(|byte| !byte.is_ascii_alphanumeric() && *byte != b'_')
    }
}

#[cfg(test)]
mod tests {
    use bumpalo::Bump;
    use indoc::indoc;

    use crate::Parser;

    macro_rules! assert_tests_module_snapshot {
        ($input:expr) => {{
            let input = indoc!($input);
            let bump = Bump::new();
            let source = bump.alloc_str(input);
            let mut parser = Parser::new(&bump, source);
            let module = parser.module().expect("expected successful module parse");
            insta::with_settings!({
                description => format!("Code:\n\n{}", input),
                omit_expression => true,
            }, {
                insta::assert_debug_snapshot!(module);
            });
        }};
    }

    #[test]
    fn complete_tests_block() {
        assert_tests_module_snapshot!(
            r#"
            module Main exposing (main)

            main = 1

            tests
                import Fuzz exposing (int, listOf)

                test "lt is strict" = do
                    assert (not (lt 1 1))

                test "fails" fail = do
                    assert (1 / 0 == 0)

                test "budget" within (cpu 1000, mem 50) = do
                    assert True

                prop "antisym" fail once within (mem 5) =
                    let
                        a via int
                        b via int
                    in
                    do
                        label "x"
                        assert (compare a b == invert (compare b a))

                prop "sorted" =
                    let xs via listOf int in
                    do
                        let
                            ys = sort xs
                        n <- length ys
                        assert (n == length xs)
        "#
        );
    }

    #[test]
    fn tests_without_imports() {
        assert_tests_module_snapshot!(
            r#"
            module Main exposing (..)

            tests
                test "truth" = do
                    assert True
        "#
        );
    }

    #[test]
    fn tests_with_imports_only() {
        assert_tests_module_snapshot!(
            r#"
            module Main exposing (..)

            tests
                import Fuzz exposing (int)
        "#
        );
    }

    #[test]
    fn nested_monadic_do_in_test_block() {
        assert_tests_module_snapshot!(
            r#"
            module Main exposing (..)

            tests
                test "nested do" = do
                    r <- do
                        x <- action
                        pure x
                    assert r
        "#
        );
    }

    #[test]
    fn syntax_overview_acceptance() {
        assert_tests_module_snapshot!(
            r#"
            validator module Vesting exposing (main)

            import Cardano.Tx exposing (Tx, Output)

            type Datum = Datum { owner : Bytes, deadline : Int }

            type step 'a = Done 'a | Next int 'a

            type alias acc = { total : int, seen : list Int }

            trait Eq 'a => Ord 'a where
                compare : 'a -> 'a -> ordering

                lt : 'a -> 'a -> bool
                lt a b = compare a b == LT

            impl Ord int where
                compare = Builtin.compareInteger

            @derive(Eq, Show, ToData, FromData)
            type Redeemer = Claim | Cancel

            main : Datum -> Redeemer -> Data -> unit
            main datum redeemer ctx =
                case redeemer of
                    Claim -> assert (lower datum.deadline < currentSlot ctx)
                    Cancel -> assert (signedBy ctx datum.owner)

            tests
                import Fuzz exposing (int, listOf)

                test "lt is strict" = do
                    assert (not (lt 1 1))

                prop "compare is antisymmetric" =
                    let
                        a via int
                        b via int
                    in
                    do
                        label (if a < b then "lt" else "ge")
                        assert (compare a b == invert (compare b a))

                prop "division by zero fails" fail =
                    let x via int in
                    do
                        assert (x / 0 == 0)
        "#
        );
    }
}