File: derive_decode.md

package info (click to toggle)
rust-knuffel-derive 3.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 256 kB
  • sloc: makefile: 2
file content (769 lines) | stat: -rw-r--r-- 20,573 bytes parent folder | download | duplicates (2)
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
The derive is the most interesting part of the `knuffel` libary.

# Overview

This trait and derive is used to decode a single node of the KDL document.

There are few things that derive can be implemented for:
1. Structure with named or unnamed fields. Most of the text here is about this
   case.
2. A single-field [new type] wrapper around such structure `Wrapper(Inner)`
   where `Inner` implements `Decode` (this is a tuple struct with single
   argument without annotations).
3. Unit struct
4. [Enum](#enums), where each variant corresponds to a specific node name

[new type]: https://doc.rust-lang.org/rust-by-example/generics/new_types.html

There are three kinds of things can fit structure fields that must be
annotated appropriately: [arguments](#arguments), [properties](#properties)
and [children](#children). Unlike in `serde` and similar projects,
non-annotated fields are not decoded from source and are filled with
[`std::default::Default`].

All annotations are enclosed by `#[knuffel(..)]` attribute.

Both arguments and properties can decode [scalars](#scalars).

If structure only has `child` and `children` fields (see [below](#children)) it
can be used as a root document (the output of [`knuffel::parse`]). Or root of
the document can be `Vec<T> where T: Decode`.

[`knuffel::parse`]: fn.parse.html

Note: node name is usually not used in the structure decoding node, it's
matched either in parent or in an [enum](#enums).

# Arguments

Arguments are scalar values that are usually written on the same line with the
node name and are positional, i.e. they parsed and put into structure fields
in order.

The two Rust attributes to parse arguments are:
* `argument` -- to parse single argument
* `arguments` -- to parse sequence of arguments

Note: order of the structure fields matter. Fields marked as `arguments` can
be used only once and cannot be followed by `argument`.

For example, the following node:
```kdl
node "arg1" true 1 22 333
```
... can be parsed into the following structure:
```rust
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(argument)]
    first: String,
    #[knuffel(argument)]
    second: bool,
    #[knuffel(arguments)]
    numbers: Vec<u32>,
}
```

Arguments can be optional:
```rust
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(argument)]
    first: Option<String>,
    #[knuffel(argument)]
    second: Option<bool>,
}
```

In this case attribute may not exists:
```kdl
node "arg1"  // no `second` argument is okay
```
Or may be `null`:
```kdl
node null null
```

Note: due to limitations of the procedural macros in Rust, optional arguments
must use `Option` in this specific notation. Other variations like these:
```
use std::option::Option as Opt;
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(argument)]
    first: ::std::option::Option<String>,
    #[knuffel(argument)]
    second: Opt<bool>,
}
```
Do not work (they will always require `null` arguments).

The field marked as `arguments` can have any type that implements `FromIterator<T> where T: DecodeScalar`.

See [Scalars](#scalars) and [Common Attributes](#common-attributes) for more
information on decoding of values.

# Properties

Properties are scalar values that are usually written on the same line
prepended with name and equals `=` sign. They are parsed regardless of order,
although if the same argument is specified twice the latter value overrides
former.

The two Rust attributes to parse properties are:
* `property` -- to parse single argument
* `properties` -- to parse sequence of arguments

Note: order of the structure fields matter. Fields marked as `properties` can
be used only once and cannot be followed by `property`.

For example, the following node:
```kdl
node name="arg1" enabled=true a=1 b=2 c=3
```

Can be parsed into the following structure:
```rust
# use std::collections::HashMap;
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(property)]
    name: String,
    #[knuffel(property)]
    enabled: bool,
    #[knuffel(properties)]
    numbers: HashMap<String, u32>,
}
```

Properties can be optional:
```rust
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(property)]
    name: Option<String>,
    #[knuffel(property)]
    enabled: Option<bool>,
}
```

In this case property may not exists or may be set to `null`:
```kdl
node name=null
```

Note: due to limitations of the procedural macros in Rust, optional properties
must use `Option` in this specific notation. Other variations like this:
```rust
use std::option::Option as Opt;
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(property)]
    name: ::std::option::Option<String>,
    #[knuffel(property)]
    enabled: Opt<bool>,
}
```
Do not work (they will always require `property=null`).

By default, field name is renamed to use `kebab-case` in KDL file. So field
defined like this:
```rust
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(property)]
    plugin_name: String,
}
```
Parses the following:
```kdl
node plugin-name="my_plugin"
```

To rename a property in the source use `name=`:
```rust
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(property(name="pluginName"))]
    name: String,
}
```

The field marked as `properties` can have any type that implements
`FromIterator<(K, V)> where K: FromStr, V: DecodeScalar`.

See [Scalars](#scalars) and [Common Attributes](#common-attributes) for more
information on decoding of values.

# Scalars

There are additional attributes that define how scalar values are parsed:
* `str` -- uses [`FromStr`](std::str::FromStr) trait.
* `bytes` -- decodes binary strings, either by decoding `base64` if the `(base64)` type is specified in the source or by encoding string into `utf-8` if no type is specified. This is required since
* `default` -- described in [Common Attrbites](#common-attributes) section
  since it applies to nodes (non-scalar values) too.

All of them work on [properties](#properties) and [arguments](#arguments).

## Parsing Strings

The `str` marker is very useful for types coming from other libraries that
aren't supported by `knuffel` directly.

For example:
```rust
#[derive(knuffel::Decode)]
struct Server {
    #[knuffel(property, str)]
    listen: std::net::SocketAddr,
}
```
This will parse listening addresses that Rust stdlib supports, like this:
```kdl
server listen="127.0.0.1:8080"
```

## Parsing Bytes

Since in Rust sequence of ints and buffer of bytes cannot be distinguished on
the type level, there is a `bytes` marker that can be applied to parse scalar
as byte buffer.

For example:
```rust
#[derive(knuffel::Decode)]
struct Response {
    #[knuffel(argument, bytes)]
    body: Vec<u8>,
}
```

The value of `body` can be specified in two ways. Using `base64` string
(this requires `base64` feature enabled which is default):
```kdl
response (base64)"SGVsbG8gd29ybGQh"
```

While using base64 allows encoding any binary data, strings may also be used
and end up using utf-8 encoded in buffer. So the KDL above is equivalent to
the following:
```kdl
response "Hello world!"
```

The field don't have to be `Vec<u8>`, it may be any type that has
`TryInto<Vec<u8>>` (and hence also `Into<Vec<u8>>`) implementation. For
example
[`bstr::BString`](https://docs.rs/bstr/latest/bstr/struct.BString.html) and
[`bytes::Bytes`](https://docs.rs/bytes/latest/bytes/struct.Bytes.html) work too.


# Children

Nodes are fundamental blocks for data hierarchy in KDL. Here are some examples
of nodes:
```kdl
node1 "x" "y"
(my_type)node2 prop="value" {
    node3 1
    node4 2
}
```
There are four nodes in this example. Nodes typically start with identifier
which is called node name. Similarly to scalars, nodes can be prepended by type
name in parenthesis. The nodes `node3` and `node4` are children nodes with
respect to `node2`. So when `node2` is decoded its `child` and `children`
directives are interpreted to match `node3` and `node4`.

The two Rust attributes to parse children are:
* `child` -- to parse single child
* `children` -- to parse sequence of children

For example the follwing KDL:
```kdl
node {
    version 1
    plugin "xxx"
    datum "yyy"
}
```
... can be parsed by into the following structures:
```rust
#[derive(knuffel::Decode)]
enum Setting {
    Plugin(#[knuffel(argument)] String),
    Datum(#[knuffel(argument)] String),
}
#[derive(knuffel::Decode)]
struct Version {
    #[knuffel(argument)]
    number: u32
}
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(child)]
    version: Version,
    #[knuffel(children)]
    settings: Vec<Setting>
}
```

There is another form of children which is `children(name="something")`, that
allows filtering nodes by name:
```rust
#[derive(knuffel::Decode)]
struct NamedNode {
    #[knuffel(argument)]
    name: u32
}
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(children(name="plugin"))]
    plugins: Vec<NamedNode>,
    #[knuffel(children(name="datum"))]
    data: Vec<NamedNode>,
}
```

Note: we use same node type for `plugin` and `datum` nodes. Generally nodes do
not match on the actual node names, it's the job of the parent node to sort
out their children into the right buckets. Also see [Enums](#enums).

## Boolean Child Fields

Sometimes you want to track just the presence of the child in the node.

For example this document:
```kdl
plugin "first" {
    auto-start
}
plugin "second"
```
... can be parsed into the list of the following structures:
```rust
#[derive(knuffel::Decode)]
struct Plugin {
    #[knuffel(child)]
    auto_start: bool,
}
```
And in this case `auto-start` node may be omitted without an error even
though it's not wrapped into an `Option`.

No arguments, properties and children are allowed in the boolean nodes.

Note: due to limitations of the procedural macros in Rust, boolean children
must use `bool` in this specific notation. If you shadow `bool` type by some
import the results are undefined (knuffel will still think it's bool node, but
it may not work).


## Unwrapping

The `unwrap` attribute for `child` allows adding extra children in the KDL
document that aren't represented in the final structure, but they play
important role in making document readable.

It works by transforming the following:
```rust,ignore
#[derive(knuffel::Decode)]
struct Node {
    #[knuffel(child, unwrap(/* attributes */))]
    field: String,
}
```
... into something like this:
```
#[derive(knuffel::Decode)]
struct TmpChild {
    #[knuffel(/* attributes */)]
    field: String,
}
#[derive(knuffel::Decode)]
struct Node {
    #[knuffel(child)]
    field: TmpChild,
}
```
... and then unpacks `TmpChild` to put target type into the field.

Most of the attributes can be used in place of `/* attributes */`. Including:
1. `argument` (the most common, see [below](#properties-become-children)) and
   `arguments`
2. `property` (usually in the form of `property(name="other_name")` to
   avoid repetitive KDL) and `properties`
3. `child` and `children` (see example [below](#grouping-things))

Following are some nice examples of using `unwrap`.

### Properties Become Children

In nodes with many properties it might be convenient to put them into children instead.

So instead of this:
```kdl
plugin name="my-plugin" url="https://example.com" {}
```
... users can write this:
```kdl
plugin {
    name "my-plugin"
    url "https://example.com"
}
```

Here is the respective Rust structure:
```rust
#[derive(knuffel::Decode)]
struct Plugin {
    #[knuffel(child, unwrap(argument))]
    name: String,
    #[knuffel(child, unwrap(argument))]
    url: String,
}
```

You can read this like: `name` field parses a child that contains a single
argument of type `String`.

### Grouping Things

Sometimes instead of different kinds of nodes scattered around you may want to
group them.

So instead of this:
```kdl
plugin "a"
file "aa"
plugin "b"
file "bb"
```
You nave a KDL document like this:
```kdl
plugins {
    plugin "a"
    plugin "b"
}
files {
    file "aa"
    file "bb"
}
```
This can be parsed into the following structure:
```rust
# #[derive(knuffel::Decode)] struct Plugin {}
# #[derive(knuffel::Decode)] struct File {}
#[derive(knuffel::Decode)]
struct Document {
    #[knuffel(child, unwrap(children(name="plugin")))]
    plugins: Vec<Plugin>,
    #[knuffel(child, unwrap(children(name="file")))]
    files: Vec<File>,
}
```

You can read this like: `plugins` field parses a child that contains a set of
children named `plugin`.


## Root Document

Any structure that has only fields marked as `child` and `children` or
unmarked ones, can be used as the root of the document.

For example, this structure can:
```rust
# #[derive(knuffel::Decode)]
# struct NamedNode { #[knuffel(argument)] name: u32 }
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(child, unwrap(argument))]
    version: u32,
    #[knuffel(children(name="plugin"))]
    plugins: Vec<NamedNode>,
    #[knuffel(children(name="datum"))]
    data: Vec<NamedNode>,
}
```
On the other hand this one can **not** because it contains a `property`:
```rust
# #[derive(knuffel::Decode)]
# struct NamedNode { #[knuffel(argument)] name: u32 }
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(property)]
    version: u32,
    #[knuffel(children(name="plugin"))]
    plugins: Vec<NamedNode>,
    #[knuffel(children(name="datum"))]
    data: Vec<NamedNode>,
}
```
Note: attributes in the `unwrap` have no influence on whether structure can be
used to decode document.

Technically [DecodeChildren](traits/trait.DecodeChildren.html) trait will be
implemented for the structures that can be used as documents.


# Common Attributes

## Default

`default` attribute may be applied to any [arguments](#arguments),
[properties](#properties) or [children](#children).

There are two forms of it. Marker attribute:
```rust
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(property, default)]
    first: String,
}
```
Which means that `std::default::Default` should be used if field was not
filled otherwise (i.e. no such property encountered).

Another form is `default=value`:
```rust
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(property, default="unnamed".into())]
    name: String,
}
```
Any Rust expression can be used in this case.

Note, for optional properties `Some` should be included in the default value.
And for scalar values their value can be overriden by using `null`. The
definition like this:
```rust
#[derive(knuffel::Decode)]
struct MyNode {
    #[knuffel(property, default=Some("unnamed".into()))]
    name: Option<String>,
}
```
Parses these two nodes differently:
```kdl
node name=null
node
```
Will yield:
```rust
# struct MyNode { name: Option<String> }
let _ = vec![
    MyNode { name: None },
    MyNode { name: Some(String::from("unnamed")) },
];
```

# Flatten

Similarly to `flatten` flag in `serde`, this allows factoring out some
properties or children into another structure.

For example:
```rust
#[derive(knuffel::Decode, Default)]
struct Common {
    #[knuffel(child, unwrap(argument))]
    name: Option<String>,
    #[knuffel(child, unwrap(argument))]
    description: Option<String>
}
#[derive(knuffel::Decode)]
struct Plugin {
    #[knuffel(flatten(child))]
    common: Common,
    #[knuffel(child, unwrap(argument))]
    url: String,
}
```
This will parse the following:
```kdl
plugin {
    name "my-plugin"
    description "Some example plugin"
    url "https://example.org/plugin"
}
```

There are few limitations of the `flatten`:
1. All fields in target structure must be optional.
2. The target structure must implement [`Default`](std::default::Default)
3. Only children an properties can be factored out, not arguments in current
   implementation
4. You must specify which directives can be used in the target structure
    (i.e. `flatten(child, children, property, properties)`) and if `children`
    or `properties` are forwarded to the target structure, no more children
    and property attributes can be used in this structure following the
    `flatten` attribute.

We may lift some of these limitations later.

Technically [DecodePartial](traits/trait.DecodePartial.html) trait will be
implemented for the strucutures that can be used with the `flatten` attribute.


# Special Values

## Type Name

Here is the example of the node with the type name (the name in parens):
```kdl
(text)document name="New Document" { }
```

By default knuffel doesn't allow type names for nodes as these are quite rare.

To allow type names on specific node and to have the name stored use
`type_name` attribute:
```rust
#[derive(knuffel::Decode)]
struct Node {
    #[knuffel(type_name)]
    type_name: String,
}
```
Type name can be optional.

The field that is a target of `type_name` can be any type that implements
`FromStr`. This might be used to validate node type:
```rust
pub enum PluginType {
    Builtin,
    External,
}

impl std::str::FromStr for PluginType {
    type Err = Box<dyn std::error::Error + Send + Sync + 'static>;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "builtin" => Ok(PluginType::Builtin),
            "external" => Ok(PluginType::External),
            _ => Err("Plugin type name must be `builtin` or `external`")?,
        }
    }
}

#[derive(knuffel::Decode)]
struct Node {
    #[knuffel(type_name)]
    type_name: PluginType,
}
```

## Node Name

In knuffel, it's common that parent node, document or enum type checks the node name of the node, and node name is not stored or validated in the strucuture.

But for the cases where you need it, it's possible to store too:
```rust
#[derive(knuffel::Decode)]
struct Node {
    #[knuffel(node_name)]
    node_name: String,
}
```

You can use any type that implements `FromStr` to validate node name. Similarly to the example in the [type names](#type-name) section.

Node name always exists so optional node_name is not supported.

## Spans

The following definition:
```rust
use knuffel::span::Span;  // or LineSpan

#[derive(knuffel::Decode)]
#[knuffel(span_type=Span)]
struct Node {
    #[knuffel(span)]
    span: Span,  // This can be user type decoded from Span
}
```
Puts position of the node in the source code into the `span` field. Span
contains the whole node, starting from parenthesis that enclose type name if
present otherwise node name. Includes node children if exists and semicolon or
newline that ends the node (so includes any whitespace and coments before the
newline if node ends by a newline, but doesn't include anything after
semicolon).

The span value might be different than one used for parsing. In this case, it
should implement [`DecodeSpan`](traits/trait.DecodeSpan.html) trait.

Independenly of whether you use custom span type, or built-in one, you have to
specify `span_type` for the decoder, since there is no generic implementation
of the `DecodeSpan` for any type. See [Span Type](#span-type) for more info

# Enums

Enums are used to differentiate nodes by name when multiple kinds of nodes are
pushed to a single collection.

For example, to parse the following list of actions:
```kdl
create "xxx"
print-string "yyy" line=2
finish
```
The following enum might be used:
```rust
# #[derive(knuffel::Decode)] struct PrintString {}
#[derive(knuffel::Decode)]
enum Action {
    Create(#[knuffel(argument)] String),
    PrintString(PrintString),
    Finish,
    #[knuffel(skip)]
    InternalAction,
}
```

The following variants supported:
1. Single element tuple struct without arguments (`PrintString` in example),
   which forwards node parsing to the inner element.
2. Normal `argument`, `arguments`, `properties`, `children` fields (`Create`
   example)
3. Property fields with names `property(name="xxx")`
4. Unit structs, in this case no arguments, properties and children are
   expected in such node
5. Variant with `skip`, cannot be deserialized and can be in any form

Enum variant names are matches against node names converted into `kebab-case`.

# Container Attributes

## Span Type

Usually generated implemenation is for any span type:
```rust,ignore
impl Decode<S> for MyStruct {
   # ...
}
```
But if you want to use `span` argument, it's unlikely to be possible to
implement `DecodeSpan` for any type.

Use use `span_type=` for implemenation of specific type:
```rust
use knuffel::span::Span;  // or LineSpan

#[derive(knuffel::Decode)]
#[knuffel(span_type=Span)]
struct MyStruct {
    #[knuffel(span)]
    span: Span,
}
```
This will generate implementation like this:
```rust,ignore
impl Decode<Span> for MyStruct {
   # ...
}
```

See [Spans](#spans) section for more info about decoding spans.