aboutsummaryrefslogtreecommitdiff
path: root/docs/pages/2-basic/4-chain.md
blob: 0fd375aab70c3065ca8fd04c4e5c00bf83a69cbf (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
<h1 align="center">Chain</h1>
<p align="center">
    Mingling's Basic Components
</p>

---

## Intro

Like `Dispatcher`, `Chain` is also a core concept in building the entire **Mingling** framework. It is used to receive a dispatch of one type and convert it into another type.

```rust
dispatcher!("hello",
    HelloCommand => HelloEntry);

// Define intermediate type ParsedHello, internally a String
pack!(ParsedHello = String);

// Define chain parse_hello (expands to ParseHello)
// Declare conversion from HelloEntry
#[chain]
fn parse_hello(prev: HelloEntry) -> NextProcess {
    // Take the inner reference of HelloEntry
    let args = &*prev;

    // Extract the first argument, use default value "World"
    //   if it doesn't exist
    let first = args.first().cloned().unwrap_or_else(|| "World".to_string());

    // Pack the extracted argument into ParsedHello and
    //   dispatch to the next chain
    ParsedHello::new(first).to_chain()
}
```

> **About NextProcess**
>
> `NextProcess` is a marker type in **Mingling**, from `mingling::marker`.
>
> It serves no functional purpose other than to simplify the declaration of chain functions. After the `chain!` macro expands, `NextProcess` will be replaced with `mingling::ChainProcess<ThisProgram>`.

## Manual Impl

You can also manually implement the basic `Chain` for finer control.

However, please note that within the `chain!` macro, a `register_type!` macro is executed. This macro does not expand to any content; it only informs the `gen_program` context that this type exists.

```rust
dispatcher!("hello",
    HelloCommand => HelloEntry);
 
pack!(ParsedHello = String);
 
struct ParseHello;
impl Chain<ThisProgram> for ParseHello {
    type Previous = HelloEntry;
    fn proc(prev: Self::Previous) 
        -> ChainProcess<ThisProgram> 
    {
        let args = &*prev;
        let first = args
            .first()
            .cloned()
            .unwrap_or_else(|| 
                "World".to_string()
            );
        ParsedHello::new(first).to_chain()
    }
}
 
// Register chain to the context
register_chain!(HelloEntry);
```

## 💡 Next Page
> **Basic Component** - Renderer [Go](./pages/2-basic/5-renderer)