• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

examples/H03-May-2022-406283

src/H03-May-2022-19885

tests/H03-May-2022-1,169955

.cargo-checksum.jsonH A D03-May-202289 11

.cargo_vcs_info.jsonH A D01-Jan-197074 65

.gitignoreH A D30-Oct-201986 109

CHANGELOG.mdH A D30-Oct-20195.4 KiB11181

Cargo.lockH A D01-Jan-19704 KiB9382

Cargo.tomlH A D01-Jan-19701.3 KiB4639

Cargo.toml.orig-cargoH A D30-Oct-2019847 3529

LICENSEH A D20-Nov-20171 KiB2217

README.mdH A D15-Aug-20195.6 KiB11391

README.md

1Darling
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[![Rustc Version 1.31+](https://img.shields.io/badge/rustc-1.31+-lightgray.svg)](https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html)
7
8`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.
9
10# Benefits
11* Easy and declarative parsing of macro input - make your proc-macros highly controllable with minimal time investment.
12* Great validation and errors, no work required. When users of your proc-macro make a mistake, `darling` makes sure they get error markers at the right place in their source, and provides "did you mean" suggestions for misspelled fields.
13
14# Usage
15`darling` provides a set of traits which can be derived or manually implemented.
16
171. `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.
182. `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.
193. `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.
204. `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.
21
22## Additional Modules
23* `darling::ast` provides generic types for representing the AST.
24* `darling::usage` provides traits and functions for determining where type parameters and lifetimes are used in a struct or enum.
25* `darling::util` provides helper types with special `FromMeta` implementations, such as `IdentList`.
26
27# Example
28
29```rust,ignore
30#[macro_use]
31extern crate darling;
32extern crate syn;
33
34#[derive(Default, FromMeta)]
35#[darling(default)]
36pub struct Lorem {
37    #[darling(rename = "sit")]
38    ipsum: bool,
39    dolor: Option<String>,
40}
41
42#[derive(FromDeriveInput)]
43#[darling(from_ident, attributes(my_crate), forward_attrs(allow, doc, cfg))]
44pub struct MyTraitOpts {
45    ident: syn::Ident,
46    attrs: Vec<syn::Attribute>,
47    lorem: Lorem,
48}
49```
50
51The above code will then be able to parse this input:
52
53```rust,ignore
54/// A doc comment which will be available in `MyTraitOpts::attrs`.
55#[derive(MyTrait)]
56#[my_crate(lorem(dolor = "Hello", ipsum))]
57pub struct ConsumingType;
58```
59
60# Attribute Macros
61Non-derive attribute macros are supported.
62To parse arguments for attribute macros, derive `FromMeta` on the argument receiver type, then pass `&syn::AttributeArgs` to the `from_list` method.
63This will produce a normal `darling::Result<T>` that can be used the same as a result from parsing a `DeriveInput`.
64
65## Macro Code
66```rust,ignore
67use darling::FromMeta;
68use syn::{AttributeArgs, ItemFn};
69use proc_macro::TokenStream;
70
71#[derive(Debug, FromMeta)]
72pub struct MacroArgs {
73    #[darling(default)]
74    timeout_ms: Option<u16>,
75    path: String,
76}
77
78#[proc_macro_attribute]
79fn your_attr(args: TokenStream, input: TokenStream) -> TokenStream {
80    let attr_args = parse_macro_input!(args as AttributeArgs);
81    let _input = parse_macro_input!(input as ItemFn);
82
83    let _args = match MacroArgs::from_list(&attr_args) {
84        Ok(v) => v,
85        Err(e) => { return e.write_errors(); }
86    };
87
88    // do things with `args`
89    unimplemented!()
90}
91```
92
93## Consuming Code
94```rust,ignore
95use your_crate::your_attr;
96
97#[your_attr(path = "hello", timeout_ms = 15)]
98fn do_stuff() {
99    println!("Hello");
100}
101```
102
103# Features
104Darling's features are built to work well for real-world projects.
105
106* **Defaults**: Supports struct- and field-level defaults, using the same path syntax as `serde`.
107* **Field Renaming**: Fields can have different names in usage vs. the backing code.
108* **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`.
109* **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.
110* **Skip fields**: Use `#[darling(skip)]` to mark a field that shouldn't be read from attribute meta-items.
111* **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`.
112* **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.
113* **"Did you mean" suggestions**: Compile errors from derived darling trait impls include suggestions for misspelled fields.