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
use nom::{
    branch::alt,
    bytes::{
        complete::tag,
        complete::{take_till1, take_until, take_while1},
    },
    character::complete::{char, line_ending, multispace0, space0},
    combinator::{cut, map, opt, rest, verify},
    error::context,
    multi::many1,
    sequence::{delimited, pair, preceded, terminated},
    AsChar, IResult,
};
use std::fmt::Display;

fn parse_valid_string(i: &str) -> IResult<&str, &str> {
    let spaces_and_symbols = "\t /-_@.,%#'";
    take_while1(move |c: char| c.is_alphanumeric() || spaces_and_symbols.contains(c))(i)
}

/// Parse comments in the form of:
/// ```recp
/// /* */
/// ```
fn parse_comment(i: &str) -> IResult<&str, &str> {
    delimited(
        tag("/*"),
        map(take_until("*/"), |v: &str| v.trim()),
        preceded(tag("*/"), space0),
    )(i)
}

/// Parse curly braces delimited utf-8
///
/// ```recp
/// {salt}
/// {tomatoes}
/// ```
fn parse_curly(i: &str) -> IResult<&str, &str> {
    delimited(
        char('{'),
        map(cut(parse_valid_string), |v| v.trim()),
        context("missing closing }", cut(char('}'))),
    )(i)
}

/// The amount of an ingredient must be numeric
/// with a few symbols allowed.
/// ```recp
/// 1
/// 3.2
/// 3,2
/// 3_000_000
/// 2/3
/// ```
fn parse_quantity(i: &str) -> IResult<&str, &str> {
    let spaces_and_symbols = ".,/_";
    context(
        "not a valid amount",
        cut(verify(
            take_while1(move |c: char| c.is_numeric() || spaces_and_symbols.contains(c)),
            |s: &str| {
                // NEXT: Can this be improved?
                let has_repeated_symbols = s
                    .as_bytes()
                    .windows(2)
                    .any(|v| v[0] == v[1] && spaces_and_symbols.contains(v[0].as_char()));
                let last_char = &s[s.len() - 1..];
                !spaces_and_symbols.contains(last_char) && !has_repeated_symbols
            },
        )),
    )(i)
}

/// Parse units like kg, kilograms, pinch, etc.
fn parse_unit(i: &str) -> IResult<&str, &str> {
    parse_valid_string(i)
}

/// Ingredient amounts are surrounded by parenthesis
fn parse_ingredient_amount(i: &str) -> IResult<&str, (Option<&str>, Option<&str>)> {
    delimited(
        tag("("),
        pair(opt(parse_quantity), opt(preceded(space0, parse_unit))),
        context("missing closing )", cut(tag(")"))),
    )(i)
}

/// Ingredients come in these formats:
/// ```recp
/// {quinoa}(200gr)
/// {tomatoes}(2)
/// {sweet potatoes}(2)
/// ```
fn parse_ingredient(i: &str) -> IResult<&str, (&str, Option<(Option<&str>, Option<&str>)>)> {
    pair(parse_curly, opt(parse_ingredient_amount))(i)
}

/// Materials format:
/// ```recp
/// &{pot}
/// &{small jar}
/// &{stick}
/// ```
fn parse_material(i: &str) -> IResult<&str, &str> {
    preceded(tag("&"), parse_curly)(i)
}

/// Materials format:
/// ```recp
/// t{25 minutes}
/// t{10 sec}
/// ```
fn parse_timer(i: &str) -> IResult<&str, &str> {
    preceded(tag("t"), parse_curly)(i)
}

/// Parse a reference to another recipe
/// ```recp
/// @{woile/special-tomato-sauce}
/// @{woile/special-tomato-sauce}(100 ml)
/// ```
fn parse_recipe_ref(i: &str) -> IResult<&str, (&str, Option<(Option<&str>, Option<&str>)>)> {
    preceded(tag("@"), pair(parse_curly, opt(parse_ingredient_amount)))(i)
}

/// We separate the tokens into words
fn parse_word(i: &str) -> IResult<&str, &str> {
    let multispace = " \t\r\n";
    take_till1(move |c| multispace.contains(c))(i)
}

/// We need to identify the spaces, and use them as tokens.
/// They are useful to rebuild the recipe
fn parse_space(i: &str) -> IResult<&str, &str> {
    let multispace = " \t\r\n";
    take_while1(move |c| multispace.contains(c))(i)
}

fn parse_metadata(i: &str) -> IResult<&str, (&str, &str)> {
    preceded(
        terminated(tag(">>"), space0),
        pair(
            take_while1(|c| c != ':'),
            preceded(terminated(tag(":"), space0), take_until("\n")),
        ),
    )(i)
}

/// The backstory is separated by `---`, and it consumes till the end
/// ```recp
/// my recipe bla with {ingredient1}
/// ---
/// This recipe was given by my grandma
/// ```
fn parse_backstory(i: &str) -> IResult<&str, &str> {
    preceded(
        delimited(
            preceded(line_ending, multispace0),
            tag("---"),
            preceded(line_ending, multispace0),
        ),
        rest,
    )(i)
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Token<'a> {
    Metadata {
        key: &'a str,
        value: &'a str,
    },
    Ingredient {
        name: &'a str,
        quantity: Option<&'a str>,
        unit: Option<&'a str>,
    },
    // Reference to another recipe
    RecipeRef {
        name: &'a str,
        quantity: Option<&'a str>,
        unit: Option<&'a str>,
    },
    Timer(&'a str),
    Material(&'a str),
    Word(&'a str),
    Space(&'a str),
    Comment(&'a str),
    Backstory(&'a str),
}

impl Display for Token<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Token::Ingredient {
                name,
                quantity: _,
                unit: _,
            } => write!(f, "{}", name),
            Token::RecipeRef {
                name,
                quantity: _,
                unit: _,
            } => write!(f, "\"{}\"", name),
            Token::Backstory(v)
            | Token::Timer(v)
            | Token::Material(v)
            | Token::Word(v)
            | Token::Space(v) => {
                write!(f, "{}", v)
            }
            Token::Metadata { key: _, value: _ } => Ok(()),
            Token::Comment(_) => Ok(()),
        }
    }
}

/// It returns a list with the parsed tokens
///
/// This function is useful if you want to build your own render on
/// top of recipe-lang
///
/// Example:
///
/// ```
/// use recipe_parser::parse;
///
/// let input = "Take the {potatoe}(1) and boil it";
/// let result = parse(input).expect("recipe could not be parsed");
///
/// println!("{result:?}");
/// ```
pub fn parse(i: &str) -> IResult<&str, Vec<Token>> {
    many1(alt((
        map(parse_metadata, |(key, value)| Token::Metadata {
            key,
            value,
        }),
        map(parse_material, |m| Token::Material(m)),
        map(parse_timer, |t| Token::Timer(t)),
        // Because ingredient doesn't have a prefix before the curly braces, e.g: `&{}`
        // it must always be parsed after timer and material
        map(parse_ingredient, |(name, amount)| {
            let mut quantity = None;
            let mut unit = None;
            if let Some((_quantity, _unit)) = amount {
                quantity = _quantity;
                unit = _unit;
            };

            Token::Ingredient {
                name,
                quantity,
                unit,
            }
        }),
        map(parse_recipe_ref, |(name, amount)| {
            let mut quantity = None;
            let mut unit = None;
            if let Some((_quantity, _unit)) = amount {
                quantity = _quantity;
                unit = _unit;
            };

            Token::RecipeRef {
                name,
                quantity,
                unit,
            }
        }),
        map(parse_backstory, |v| Token::Backstory(v)),
        map(parse_comment, |v| Token::Comment(v)),
        map(parse_word, |v| Token::Word(v)),
        map(parse_space, |v| Token::Space(v)),
    )))(i)
}

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

    #[rstest]
    #[case("salt", "salt")]
    #[case("sweet potato", "sweet potato")]
    #[case("ToMaToeS", "ToMaToeS")]
    #[case("1/2 lemon", "1/2 lemon")]
    #[case("my-best-sauce", "my-best-sauce")]
    #[case("1.2", "1.2")]
    #[case("1,2", "1,2")]
    #[case("1_200", "1_200")]
    #[case("@woile", "@woile")]
    #[case("10%", "10%")]
    #[case("#vegan", "#vegan")]
    #[case("mango's", "mango's")]
    fn test_parse_valid_string(#[case] input: &str, #[case] expected: &str) {
        let (_, valid_str) = parse_valid_string(input).unwrap();
        assert_eq!(valid_str, expected)
    }
    #[rstest]
    #[case("{salt}", "salt")]
    #[case("{black pepper}", "black pepper")]
    #[case("{smashed potatoes}", "smashed potatoes")]
    #[case("{15 minutes}", "15 minutes")]
    #[case("{   15 minutes  }", "15 minutes")]
    fn test_parse_curly_ok(#[case] input: &str, #[case] expected: &str) {
        let (_, content) = parse_curly(input).expect("to work");
        assert_eq!(expected, content);
    }

    #[rstest]
    #[case("{}")]
    #[case("{unclosed")]
    fn test_parse_curly_wrong(#[case] input: &str) {
        let res = parse_curly(input);
        assert!(res.is_err());

        let err = res.unwrap_err();
        assert!(matches!(err, nom::Err::Failure(_)));
    }

    #[rstest]
    #[case("200", "200")]
    #[case("2.1", "2.1")]
    #[case("2_1", "2_1")]
    #[case("2,1", "2,1")]
    #[case("2.1", "2.1")]
    #[case("1/2", "1/2")]
    #[case(".2", ".2")]
    fn test_parse_quantity_ok(#[case] input: &str, #[case] expected: &str) {
        let (_, content) = parse_quantity(input).expect("to work");
        assert_eq!(expected, content);
    }

    #[rstest]
    #[case("2.")]
    #[case("2..0")]
    #[case("2,,0")]
    #[case("2//0")]
    fn test_parse_quantity_invalid(#[case] input: &str) {
        // TODO: Add verify function to validate the last char
        let res = parse_quantity(input);
        let err = res.unwrap_err();
        assert!(matches!(err, nom::Err::Failure(_)));
    }

    #[rstest]
    #[case("(200gr)", (Some("200"), Some("gr")))]
    #[case("(1/2)", (Some("1/2"), None))]
    #[case("(100 gr)", (Some("100"), Some("gr")))]
    #[case("(10 ml)", (Some("10"), Some("ml")))]
    #[case("(1.5 cups)", (Some("1.5"), Some("cups")))]
    fn test_parse_ingredient_amount_ok(
        #[case] input: &str,
        #[case] expected: (Option<&str>, Option<&str>),
    ) {
        let (_, content) = parse_ingredient_amount(input).expect("to work");
        assert_eq!(expected, content);
    }

    #[rstest]
    #[case("()")]
    #[case("(unclosed")]
    fn test_parse_ingredient_amount_wrong(#[case] input: &str) {
        let res = parse_ingredient_amount(input);

        println!("{res:?}");
        assert!(res.is_err());
        // let err = res.unwrap_err();
    }

    #[rstest]
    #[case("{sweet potato}(200gr)", "sweet potato", Some((Some("200"),Some("gr"))))]
    #[case("{sweet potato}", "sweet potato", None)]
    fn test_parse_ingredient_ok(
        #[case] input: &str,
        #[case] expected_ingredient: &str,
        #[case] expected_amount: Option<(Option<&str>, Option<&str>)>,
    ) {
        let (_, (ingredient, amount)) = parse_ingredient(input).unwrap();
        assert_eq!(expected_ingredient, ingredient);
        assert_eq!(expected_amount, amount);
    }

    #[rstest]
    #[case("&{pot}", "pot")]
    #[case("&{small jar}", "small jar")]
    #[case("&{stick}", "stick")]
    #[case("&{bricks}", "bricks")]
    fn test_parse_material_ok(#[case] input: &str, #[case] expected: &str) {
        let (_, material) = parse_material(input).expect("Failed to parse material");
        assert_eq!(material, expected)
    }

    #[rstest]
    #[case("t{1 minute}", "1 minute")]
    fn test_parse_timer_ok(#[case] input: &str, #[case] expected: &str) {
        let (_, timer) = parse_timer(input).expect("Failed to parse timer");
        assert_eq!(timer, expected)
    }

    #[rstest]
    #[case("@{woile/tomato-sauce}(200gr)", "woile/tomato-sauce", Some((Some("200"),Some("gr"))))]
    #[case("@{woile/tomato-sauce}", "woile/tomato-sauce", None)]
    #[case("@{special stew}", "special stew", None)]
    fn test_parse_recipe_ok(
        #[case] input: &str,
        #[case] expected_recipe: &str,
        #[case] expected_amount: Option<(Option<&str>, Option<&str>)>,
    ) {
        let (_, (recipe, amount)) = parse_recipe_ref(input).unwrap();
        assert_eq!(expected_recipe, recipe);
        assert_eq!(expected_amount, amount);
    }

    #[rstest]
    #[case(">> tags: vegan\n", ("tags", "vegan"))]
    #[case(">> key: pepe\n", ("key", "pepe"))]
    #[case(">>key: pepe\n", ("key", "pepe"))]
    #[case(">>    key: pepe\n", ("key", "pepe"))]
    #[case(">>    key:     pepe\n", ("key", "pepe"))]
    #[case(">>    key:\t\tpepe\n", ("key", "pepe"))]
    #[case(">>    key:pepe\n", ("key", "pepe"))]
    fn test_parse_metadata_ok(#[case] input: &str, #[case] expected: (&str, &str)) {
        let (_, metadata) = parse_metadata(input).expect("Failed to parse metadata");
        assert_eq!(metadata, expected)
    }

    #[rstest]
    #[case("/* */", "")]
    #[case("/* hello */", "hello")]
    #[case("/* multi\nline\ncomment */", "multi\nline\ncomment")]
    fn test_parse_comment_ok(#[case] input: &str, #[case] expected: &str) {
        let (_, comment) = parse_comment(input).expect("failed to parse comment");
        assert_eq!(comment, expected)
    }

    #[rstest]
    #[case("\n---\nwhat a backstory", "what a backstory")]
    #[case("\n   ---\nwhat a backstory", "what a backstory")]
    #[case("\n   ---\n\nwhat a backstory", "what a backstory")]
    #[case("\n   ---\n\nthis is **markdown**", "this is **markdown**")]
    #[case("\n   ---\n\nthis is [markdown](url)", "this is [markdown](url)")]
    fn test_parse_backstory_ok(#[case] input: &str, #[case] expected: &str) {
        let (_, backsotry) = parse_backstory(input).expect("failed to parse backstory");
        assert_eq!(backsotry, expected)
    }

    #[rstest]
    #[case("\n---    \nwhat a backstory")]
    fn test_parse_backstory_fail(#[case] input: &str) {
        let out = parse_backstory(input);
        assert!(out.is_err())
    }

    #[test]
    fn test_parse_ok() {
        let input = "Boil the quinoa for t{5 minutes} in a &{pot}.\nPut the boiled {quinoa}(200gr) in the base of the bowl.";
        let expected = "Boil the quinoa for 5 minutes in a pot.\nPut the boiled quinoa in the base of the bowl.";
        let (_, recipe) = parse(input).expect("parsing recipe failed");
        let fmt_recipe = recipe
            .iter()
            .fold(String::new(), |acc, val| format!("{acc}{val}"));
        println!("{}", fmt_recipe);

        assert_eq!(expected, fmt_recipe)
    }

    #[test]
    fn test_parse_meta_ok() {
        let input = ">> name: story\nBoil the quinoa for t{5 minutes} in a &{pot}.\nPut the boiled {quinoa}(200gr) in the base of the bowl.";
        let expected = "Boil the quinoa for 5 minutes in a pot.\nPut the boiled quinoa in the base of the bowl.";
        let (_, recipe) = parse(input).expect("parsing recipe failed");
        let fmt_recipe = recipe
            .iter()
            .fold(String::new(), |acc, val| format!("{acc}{val}"));
        println!("{}", fmt_recipe);

        assert_eq!(expected, fmt_recipe.trim())
    }

    #[test]
    fn test_recipe_with_comment_ok() {
        let input = "Boil the {quinoa} /* don't do it! */ for t{5 minutes}";
        let expected = "Boil the quinoa for 5 minutes";
        let (_, recipe) = parse(input).expect("parsing recipe failed");
        let fmt_recipe = recipe
            .iter()
            .fold(String::new(), |acc, val| format!("{acc}{val}"));
        println!("{}", fmt_recipe);

        assert_eq!(expected, fmt_recipe)
    }

    #[test]
    fn test_invalid_recipes() {
        let input = "this is an {invalid recipe";
        let result = parse(input);
        assert!(result.is_err());
        println!("{result:?}");
        let err = result.unwrap_err();

        println!("type: {:?}", err);
    }

    #[test]
    fn test_recipe_with_recipe_reference() {
        let input = "use the @{woile/magic-hummus}(200gr)";
        let expected = "use the \"woile/magic-hummus\"";
        let (_, recipe) = parse(input).unwrap();
        let fmt_recipe = recipe
            .iter()
            .fold(String::new(), |acc, val| format!("{acc}{val}"));
        assert_eq!(expected, fmt_recipe)
    }
}