]> git.proxmox.com Git - rustc.git/blob - vendor/darling/README.md
New upstream version 1.37.0+dfsg1
[rustc.git] / vendor / darling / README.md
1 Darling
2 =======
3
4 [![Build Status](https://travis-ci.org/TedDriggs/darling.svg?branch=master)](https://travis-ci.org/TedDriggs/darling)
5 [![Latest Version](https://img.shields.io/crates/v/darling.svg)](https://crates.io/crates/darling)
6
7 `darling` is a crate for proc macro authors, which enables parsing attributes into structs. It is heavily inspired by `serde` both in its internals and in its API.
8
9 # Usage
10 `darling` provides a set of traits which can be derived or manually implemented.
11
12 1. `FromMeta` is used to extract values from a meta-item in an attribute. Implementations are likely reusable for many libraries, much like `FromStr` or `serde::Deserialize`. Trait implementations are provided for primitives, some std types, and some `syn` types.
13 2. `FromDeriveInput` is implemented or derived by each proc-macro crate which depends on `darling`. This is the root for input parsing; it gets access to the identity, generics, and visibility of the target type, and can specify which attribute names should be parsed or forwarded from the input AST.
14 3. `FromField` is implemented or derived by each proc-macro crate which depends on `darling`. Structs deriving this trait will get access to the identity (if it exists), type, and visibility of the field.
15 4. `FromVariant` is implemented or derived by each proc-macro crate which depends on `darling`. Structs deriving this trait will get access to the identity and contents of the variant, which can be transformed the same as any other `darling` input.
16
17 # Example
18
19 ```rust,ignore
20 #[macro_use]
21 extern crate darling;
22 extern crate syn;
23
24 #[derive(Default, FromMeta)]
25 #[darling(default)]
26 pub struct Lorem {
27 #[darling(rename = "sit")]
28 ipsum: bool,
29 dolor: Option<String>,
30 }
31
32 #[derive(FromDeriveInput)]
33 #[darling(from_ident, attributes(my_crate), forward_attrs(allow, doc, cfg))]
34 pub struct MyTraitOpts {
35 ident: syn::Ident,
36 attrs: Vec<syn::Attribute>,
37 lorem: Lorem,
38 }
39 ```
40
41 The above code will then be able to parse this input:
42
43 ```rust,ignore
44 /// A doc comment which will be available in `MyTraitOpts::attrs`.
45 #[derive(MyTrait)]
46 #[my_crate(lorem(dolor = "Hello", ipsum))]
47 pub struct ConsumingType;
48 ```
49
50 # Attribute Macros
51 Non-derive attribute macros are supported.
52 To parse arguments for attribute macros, derive `FromMeta` on the argument receiver type, then pass `&syn::AttributeArgs` to the `from_list` method.
53 This will produce a normal `darling::Result<T>` that can be used the same as a result from parsing a `DeriveInput`.
54
55 ## Macro Code
56 ```rust,ignore
57 use darling::FromMeta;
58 use syn::{AttributeArgs, ItemFn};
59 use proc_macro::TokenStream;
60
61 #[derive(Debug, FromMeta)]
62 pub struct MacroArgs {
63 #[darling(default)]
64 timeout_ms: Option<u16>,
65 path: String,
66 }
67
68 #[proc_macro_attribute]
69 fn your_attr(args: TokenStream, input: TokenStream) -> TokenStream {
70 let attr_args = parse_macro_input!(args as AttributeArgs);
71 let _input = parse_macro_input!(input as ItemFn);
72
73 let _args = match MacroArgs::from_list(&attr_args) {
74 Ok(v) => v,
75 Err(e) => { return e.write_errors(); }
76 };
77
78 // do things with `args`
79 unimplemented!()
80 }
81 ```
82
83 ## Consuming Code
84 ```rust,ignore
85 use your_crate::your_attr;
86
87 #[your_attr(path = "hello", timeout_ms = 15)]
88 fn do_stuff() {
89 println!("Hello");
90 }
91 ```
92
93 # Features
94 Darling's features are built to work well for real-world projects.
95
96 * **Defaults**: Supports struct- and field-level defaults, using the same path syntax as `serde`.
97 * **Field Renaming**: Fields can have different names in usage vs. the backing code.
98 * **Auto-populated fields**: Structs deriving `FromDeriveInput` and `FromField` can declare properties named `ident`, `vis`, `ty`, `attrs`, and `generics` to automatically get copies of the matching values from the input AST. `FromDeriveInput` additionally exposes `data` to get access to the body of the deriving type, and `FromVariant` exposes `fields`.
99 * **Mapping function**: Use `#[darling(map="path")]` to specify a function that runs on the result of parsing a meta-item field. This can change the return type, which enables you to parse to an intermediate form and convert that to the type you need in your struct.
100 * **Skip fields**: Use `#[darling(skip)]` to mark a field that shouldn't be read from attribute meta-items.
101 * **Multiple-occurrence fields**: Use `#[darling(multiple)]` on a `Vec` field to allow that field to appear multiple times in the meta-item. Each occurrence will be pushed into the `Vec`.
102 * **Span access**: Use `darling::util::SpannedValue` in a struct to get access to that meta item's source code span. This can be used to emit warnings that point at a specific field from your proc macro. In addition, you can use `darling::Error::write_errors` to automatically get precise error location details in most cases.