aboutsummaryrefslogtreecommitdiff
path: root/docs/pages/3-features/1-parser.md
blob: 75a83d839e38c069b25c568c0bfe1900a71971d0 (plain) (blame)
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
<h1 align="center">Parser</h1>
<p align="center">
    Mingling's Features
</p>

---

## Enable Feature

`parser` is a feature provided by **Mingling**. You can enable it in the following way:

```toml
[dependencies]
mingling = { 
    version = "...", 
    features = ["parser"] 
}
```

## Intro

`parser` provides the ability to transform user input into structured data. Its core concept is **pick**.

The following demonstrates the parsing approach without using a `Picker`:

```rust
#[chain]
fn parse_hello(prev: HelloEntry) -> NextProcess {
    let args = &*prev;
    let first = args.first().cloned().unwrap_or_else(|| "World".to_string());
    ParsedHello::new(first).to_render()
}
```

This is how it looks when using `Picker`:

```rust
#[chain]
fn parse_hello(prev: HelloEntry) -> NextProcess {
    // Create Picker
    let picker = Picker::<ThisProgram>::new(prev.inner);

    // Extract the first argument from the Picker, 
    //   fallback to "World" if it doesn't exist
    let first = picker
        .pick_or((), "World")
        .unpack_directly().0;

    ParsedHello::new(first).to_render()
}
```

You might notice that using `Picker` can sometimes make statements more verbose, but this is only when parsing a small number of arguments. What if we complicate the scenario?

Suppose we want to design the following commands:

```bash
# Eat 1 apple weighing at least 20
fruit eat Apple --min-weight 20

# Eat 10 apples weighing at least 20
fruit eat Apple --min-weight 20 --count 10

# Eat 1 apple weighing between 10 and 20
fruit eat Apple --min-weight 10 --max-weight 20

# Eat 1 apple weighing between 20 and 10 (incorrect logic)
fruit eat Apple --min-weight 20 --max-weight 10

# When no specific fruit is specified, eat banana
fruit eat --count 5
```

For this complex scenario, the `Picker` comes into play! 

We first design the type `ParsedEatFruit`

```rust
#[derive(Debug, Default, Groupped)]
struct ParsedEatFruit {
    count: i16,
    weight_range: (i16, i16),
    fruit_type: Fruit,
}

#[derive(Debug, Default, EnumTag)]
enum Fruit {
    #[default]
    Banana,
    Apple,
    Orange,
}
```

Then create the basic binary program `fruit`

```rust
use mingling::{
    EnumTag, Groupped,
    macros::{chain, dispatcher, gen_program, r_println, renderer},
    marker::NextProcess,
    parser::PickableEnum,
};

fn main() {
    let mut program = ThisProgram::new();
    program.with_dispatcher(FruitEatCommand);
    program.exec();
}

dispatcher!("eat",
    FruitEatCommand => FruitEatEntry);

#[derive(Debug, Default, Groupped)]
struct ParsedEatFruit {
    count: i16,
    weight_range: (i16, i16),
    fruit_type: Fruit,
}

#[derive(Debug, Default, EnumTag)]
enum Fruit {
    #[default]
    Banana,
    Apple,
    Orange,
}

// Implement PickableEnum for Fruit to make it pickable
impl PickableEnum for Fruit {}

#[chain]
fn parse_fruit_eat(prev: FruitEatEntry) -> NextProcess {
    // ...
}

#[renderer]
fn render_fruit_eat(prev: ParsedEatFruit) {
    let weight_str = match prev.weight_range {
        (min, max) if min == 0 && max > 0 => {
            format!("up to {}.", max)
        }
        (min, max) if min > 0 && max == 0 => {
            format!("at least {}.", min)
        }
        (min, max) if min > 0 && max > 0 && min != max => {
            format!("between {} and {}.", min, max)
        }
        (min, max) if min > 0 && max > 0 && min == max => {
            format!("exactly {}.", min)
        }
        _ => "unknown.".to_string(),
    };

    let fruit_type = if prev.count > 1 {
        format!("{}s", prev.fruit_type.enum_info().0)
    } else {
        prev.fruit_type.enum_info().0.to_string()
    };

    r_println!(
        "I ate {} {}, each weighing {}",
        prev.count,
        fruit_type,
        weight_str
    );
}

gen_program!();
```

Now focus on writing the logic for `parse_fruit_eat`:

> Review the business logic:
>
> 1 - The default fruit is Banana
>
> 2 - The default quantity is 1
>
> 3 - The default weight is (0, 0)
>
> 4 - When `max-weight` is less than `min-weight`, the business logic is in error

Before writing the code, define the error type `MinGreaterThanMax` and the related `Renderer`

```rust
pack!(MinGreaterThanMax = ());

#[renderer]
fn render_min_greater_than_max(_prev: MinGreaterThanMax) {
    r_println!("Error: min weight cannot be greater than max weight.");
}
```

Now start writing the logic:

```rust
#[chain]
fn parse_fruit_eat(prev: FruitEatEntry) -> NextProcess {
    let picker = Picker::new(prev.inner);
    let mut min_weight: i16 = 0;
    let parsed = picker
        .pick_or(["--count", "-n"], 1)
        .pick::<i16>("--min-weight") // default: 0
        .after(|min| {
            // Copy `min` to external variable
            min_weight = min;
            min
        })
        .pick_or::<i16>("--max-weight", min_weight) // default: min_weight
        .after_or_route(|max| {
            // Check if `max` is valid
            if max < &min_weight {
                Err(MinGreaterThanMax::default())
            } else {
                Ok(max.clone())
            }
        })
        .pick(())
        // Since there's a possibility of being routed, 
        //   don't use `unpack_directly`
        .unpack(); 
 
    match parsed {
        Ok((count, min_weight, max_weight, fruit_type)) => {
            let parsed = ParsedEatFruit {
                count,
                weight_range: (min_weight, max_weight),
                fruit_type,
            };
 
            AnyOutput::new(parsed).route_renderer()
        }
        Err(route) => route.to_render(),
    }
}
```

Complete code:

```rust
use mingling::{
    AnyOutput, EnumTag, Groupped,
    macros::{chain, dispatcher, gen_program, pack, r_println, renderer},
    marker::NextProcess,
    parser::{PickableEnum, Picker},
};

fn main() {
    let mut program = ThisProgram::new();
    program.with_dispatcher(FruitEatCommand);
    program.exec();
}

dispatcher!("eat",
    FruitEatCommand => FruitEatEntry);

#[derive(Debug, Default, Groupped)]
struct ParsedEatFruit {
    count: i16,
    weight_range: (i16, i16),
    fruit_type: Fruit,
}

#[derive(Debug, Default, EnumTag)]
enum Fruit {
    #[default]
    Banana,
    Apple,
    Orange,
}

impl PickableEnum for Fruit {}

pack!(MinGreaterThanMax = ());

#[chain]
fn parse_fruit_eat(prev: FruitEatEntry) -> NextProcess {
    let picker = Picker::new(prev.inner);
    let mut min_weight: i16 = 0;
    let parsed = picker
        .pick_or(["--count", "-n"], 1)
        .pick::<i16>("--min-weight") // default: 0
        .after(|min| {
            // Copy `min` to external variable
            min_weight = min;
            min
        })
        .pick_or::<i16>("--max-weight", min_weight) // default: min_weight
        .after_or_route(|max| {
            // Check if `max` is valid
            if max < &min_weight {
                Err(MinGreaterThanMax::default())
            } else {
                Ok(max.clone())
            }
        })
        .pick(())
        .unpack();

    match parsed {
        Ok((count, min_weight, max_weight, fruit_type)) => {
            let parsed = ParsedEatFruit {
                count,
                weight_range: (min_weight, max_weight),
                fruit_type,
            };

            AnyOutput::new(parsed).route_renderer()
        }
        Err(route) => route.to_render(),
    }
}

#[renderer]
fn render_min_greater_than_max(_prev: MinGreaterThanMax) {
    r_println!("Error: min weight cannot be greater than max weight.");
}

#[renderer]
fn render_fruit_eat(prev: ParsedEatFruit) {
    let weight_str = match prev.weight_range {
        (min, max) if min == 0 && max > 0 => {
            format!("up to {}.", max)
        }
        (min, max) if min > 0 && max == 0 => {
            format!("at least {}.", min)
        }
        (min, max) if min > 0 && max > 0 && min != max => {
            format!("between {} and {}.", min, max)
        }
        (min, max) if min > 0 && max > 0 && min == max => {
            format!("exactly {}.", min)
        }
        _ => "unknown.".to_string(),
    };

    let fruit_type = if prev.count > 1 {
        format!("{}s", prev.fruit_type.enum_info().0)
    } else {
        prev.fruit_type.enum_info().0.to_string()
    };

    r_println!(
        "I ate {} {}, each weighing {}",
        prev.count,
        fruit_type,
        weight_str
    );
}

gen_program!();
```

Now compile the program and run it:

```bash
cargo install --path ./
```

Running results:

```bash
~> fruit eat Apple --min-weight 20
I ate 1 Apple, each weighing exactly 20.

~> fruit eat Apple --min-weight 20 --count 10
I ate 10 Apples, each weighing exactly 20.

~> fruit eat Apple --min-weight 10 --max-weight 20
I ate 1 Apple, each weighing between 10 and 20.

~> fruit eat Apple --min-weight 20 --max-weight 10
Error: min weight cannot be greater than max weight.

~> fruit eat --count 5
I ate 5 Bananas, each weighing unknown.
```