about summary refs log tree commit diff
path: root/tvix/nix-compat-derive/src/lib.rs
blob: 394473b1cbf87afdddc5436f93e81d3f1a8d85d4 (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
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
//! # Using derive
//!
//! 1. [Overview](#overview)
//! 3. [Attributes](#attributes)
//!     1. [Container attributes](#container-attributes)
//!         1. [`#[nix(from_str)]`](#nixfrom_str)
//!         2. [`#[nix(from = "FromType")]`](#nixfrom--fromtype)
//!         3. [`#[nix(try_from = "FromType")]`](#nixtry_from--fromtype)
//!         4. [`#[nix(into = "IntoType")]`](#nixinto--intotype)
//!         5. [`#[nix(try_into = "IntoType")]`](#nixtry_into--intotype)
//!         6. [`#[nix(display)]`](#nixdisplay)
//!         7. [`#[nix(display = "path")]`](#nixdisplay--path)
//!         8. [`#[nix(crate = "...")]`](#nixcrate--)
//!     2. [Variant attributes](#variant-attributes)
//!         1. [`#[nix(version = "range")]`](#nixversion--range)
//!     3. [Field attributes](#field-attributes)
//!         1. [`#[nix(version = "range")]`](#nixversion--range-1)
//!         2. [`#[nix(default)]`](#nixdefault)
//!         3. [`#[nix(default = "path")]`](#nixdefault--path)
//!
//! ## Overview
//!
//! This crate contains derive macros and function-like macros for implementing
//! `NixDeserialize` and `NixSerialize` with less boilerplate.
//!
//! ### Examples
//!
//! ```rust
//! # use nix_compat_derive::{NixDeserialize, NixSerialize};
//! #
//! #[derive(NixDeserialize, NixSerialize)]
//! struct Unnamed(u64, String);
//! ```
//!
//! ```rust
//! # use nix_compat_derive::{NixDeserialize, NixSerialize};
//! #
//! #[derive(NixDeserialize, NixSerialize)]
//! struct Fields {
//!     number: u64,
//!     message: String,
//! };
//! ```
//!
//! ```rust
//! # use nix_compat_derive::{NixDeserialize, NixSerialize};
//! #
//! #[derive(NixDeserialize, NixSerialize)]
//! struct Ignored;
//! ```
//!
//! ## Attributes
//!
//! To customize the derived trait implementations you can add
//! [attributes](https://doc.rust-lang.org/reference/attributes.html)
//! to containers, fields and variants.
//!
//! ```rust
//! # use nix_compat_derive::NixDeserialize;
//! #
//! #[derive(NixDeserialize)]
//! #[nix(crate="nix_compat")] // <-- This is a container attribute
//! struct Fields {
//!     number: u64,
//!     #[nix(version="..20")] // <-- This is a field attribute
//!     message: String,
//! };
//!
//! #[derive(NixDeserialize)]
//! #[nix(crate="nix_compat")] // <-- This is also a container attribute
//! enum E {
//!     #[nix(version="..10")] // <-- This is a variant attribute
//!     A(u64),
//!     #[nix(version="10..")] // <-- This is also a variant attribute
//!     B(String),
//! }
//! ```
//!
//! ### Container attributes
//!
//! ##### `#[nix(from_str)]`
//!
//! When `from_str` is specified the fields are all ignored and instead a
//! `String` is first deserialized and then `FromStr::from_str` is used
//! to convert this `String` to the container type.
//!
//! This means that the container must implement `FromStr` and the error
//! returned from the `from_str` must implement `Display`.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixDeserialize;
//! #
//! #[derive(NixDeserialize)]
//! #[nix(from_str)]
//! struct MyString(String);
//! impl std::str::FromStr for MyString {
//!     type Err = String;
//!     fn from_str(s: &str) -> Result<Self, Self::Err> {
//!         if s != "bad string" {
//!             Ok(MyString(s.to_string()))
//!         } else {
//!             Err("Got a bad string".to_string())
//!         }
//!     }
//! }
//! ```
//!
//! ##### `#[nix(from = "FromType")]`
//!
//! When `from` is specified the fields are all ignored and instead a
//! value of `FromType` is first deserialized and then `From::from` is
//! used to convert from this value to the container type.
//!
//! This means that the container must implement `From<FromType>` and
//! `FromType` must implement `NixDeserialize`.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixDeserialize;
//! #
//! #[derive(NixDeserialize)]
//! #[nix(from="usize")]
//! struct MyValue(usize);
//! impl From<usize> for MyValue {
//!     fn from(val: usize) -> Self {
//!         MyValue(val)
//!     }
//! }
//! ```
//!
//! ##### `#[nix(try_from = "FromType")]`
//!
//! With `try_from` a value of `FromType` is first deserialized and then
//! `TryFrom::try_from` is used to convert from this value to the container
//! type.
//!
//! This means that the container must implement `TryFrom<FromType>` and
//! `FromType` must implement `NixDeserialize`.
//! The error returned from `try_from` also needs to implement `Display`.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixDeserialize;
//! #
//! #[derive(NixDeserialize)]
//! #[nix(try_from="usize")]
//! struct WrongAnswer(usize);
//! impl TryFrom<usize> for WrongAnswer {
//!     type Error = String;
//!     fn try_from(val: usize) -> Result<Self, Self::Error> {
//!         if val != 42 {
//!             Ok(WrongAnswer(val))
//!         } else {
//!             Err("Got the answer to life the universe and everything".to_string())
//!         }
//!     }
//! }
//! ```
//!
//! ##### `#[nix(into = "IntoType")]`
//!
//! When `into` is specified the fields are all ignored and instead the
//! container type is converted to `IntoType` using `Into::into` and
//! `IntoType` is then serialized. Before converting `Clone::clone` is
//! called.
//!
//! This means that the container must implement `Into<IntoType>` and `Clone`
//! and `IntoType` must implement `NixSerialize`.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixSerialize;
//! #
//! #[derive(Clone, NixSerialize)]
//! #[nix(into="usize")]
//! struct MyValue(usize);
//! impl From<MyValue> for usize {
//!     fn from(val: MyValue) -> Self {
//!         val.0
//!     }
//! }
//! ```
//!
//! ##### `#[nix(try_into = "IntoType")]`
//!
//! When `try_into` is specified the fields are all ignored and instead the
//! container type is converted to `IntoType` using `TryInto::try_into` and
//! `IntoType` is then serialized. Before converting `Clone::clone` is
//! called.
//!
//! This means that the container must implement `TryInto<IntoType>` and
//! `Clone` and `IntoType` must implement `NixSerialize`.
//! The error returned from `try_into` also needs to implement `Display`.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixSerialize;
//! #
//! #[derive(Clone, NixSerialize)]
//! #[nix(try_into="usize")]
//! struct WrongAnswer(usize);
//! impl TryFrom<WrongAnswer> for usize {
//!     type Error = String;
//!     fn try_from(val: WrongAnswer) -> Result<Self, Self::Error> {
//!         if val.0 != 42 {
//!             Ok(val.0)
//!         } else {
//!             Err("Got the answer to life the universe and everything".to_string())
//!         }
//!     }
//! }
//! ```
//!
//! ##### `#[nix(display)]`
//!
//! When `display` is specified the fields are all ignored and instead the
//! container must implement `Display` and `NixWrite::write_display` is used to
//! write the container.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixSerialize;
//! # use std::fmt::{Display, Result, Formatter};
//! #
//! #[derive(NixSerialize)]
//! #[nix(display)]
//! struct WrongAnswer(usize);
//! impl Display for WrongAnswer {
//!     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
//!         write!(f, "Wrong Answer = {}", self.0)
//!     }
//! }
//! ```
//!
//! ##### `#[nix(display = "path")]`
//!
//! When `display` is specified the fields are all ignored and instead the
//! container the specified path must point to a function that is callable as
//! `fn(&T) -> impl Display`. The result from this call is then written with
//! `NixWrite::write_display`.
//! For example `default = "my_value"` would call `my_value(&self)` and `display =
//! "AType::empty"` would call `AType::empty(&self)`.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixSerialize;
//! # use std::fmt::{Display, Result, Formatter};
//! #
//! #[derive(NixSerialize)]
//! #[nix(display = "format_it")]
//! struct WrongAnswer(usize);
//! struct WrongDisplay<'a>(&'a WrongAnswer);
//! impl<'a> Display for WrongDisplay<'a> {
//!     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
//!         write!(f, "Wrong Answer = {}", self.0.0)
//!     }
//! }
//!
//! fn format_it(value: &WrongAnswer) -> impl Display + '_ {
//!     WrongDisplay(value)
//! }
//! ```
//!
//! ##### `#[nix(crate = "...")]`
//!
//! Specify the path to the `nix-compat` crate instance to use when referring
//! to the API in the generated code. This is usually not needed.
//!
//! ### Variant attributes
//!
//! ##### `#[nix(version = "range")]`
//!
//! Specifies the protocol version range where this variant is used.
//! When deriving an enum the `version` attribute is used to select which
//! variant of the enum to deserialize. The range is for minor version and
//! the version ranges of all variants combined must cover all versions
//! without any overlap or the first variant that matches is selected.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixDeserialize;
//! #
//! #[derive(NixDeserialize)]
//! enum Testing {
//!     #[nix(version="..=18")]
//!     OldVersion(u64),
//!     #[nix(version="19..")]
//!     NewVersion(String),
//! }
//! ```
//!
//! ### Field attributes
//!
//! ##### `#[nix(version = "range")]`
//!
//! Specifies the protocol version range where this field is included.
//! The range is for minor version. For example `version = "..20"`
//! includes the field in protocol versions `1.0` to `1.19` and skips
//! it in version `1.20` and above.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixDeserialize;
//! #
//! #[derive(NixDeserialize)]
//! struct Field {
//!     number: u64,
//!     #[nix(version="..20")]
//!     messsage: String,
//! }
//! ```
//!
//! ##### `#[nix(default)]`
//!
//! When a field is skipped because the active protocol version falls
//! outside the range specified in [`#[nix(version = "range")]`](#nixversion--range-1)
//! this attribute indicates that `Default::default()` should be used
//! to get a value for the field. This is also the default
//! when you only specify [`#[nix(version = "range")]`](#nixversion--range-1).
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixDeserialize;
//! #
//! #[derive(NixDeserialize)]
//! struct Field {
//!     number: u64,
//!     #[nix(version="..20", default)]
//!     messsage: String,
//! }
//! ```
//!
//! ##### `#[nix(default = "path")]`
//!
//! When a field is skipped because the active protocol version falls
//! outside the range specified in [`#[nix(version = "range")]`](#nixversion--range-1)
//! this attribute indicates that the function in `path` should be called to
//! get a default value for the field. The given function must be callable
//! as `fn() -> T`.
//! For example `default = "my_value"` would call `my_value()` and `default =
//! "AType::empty"` would call `AType::empty()`.
//!
//! ###### Example
//!
//! ```rust
//! # use nix_compat_derive::NixDeserialize;
//! #
//! #[derive(NixDeserialize)]
//! struct Field {
//!     number: u64,
//!     #[nix(version="..20", default="missing_string")]
//!     messsage: String,
//! }
//!
//! fn missing_string() -> String {
//!     "missing string".to_string()
//! }
//! ```

use internal::inputs::RemoteInput;
use proc_macro::TokenStream;
use syn::{parse_quote, DeriveInput};

mod de;
mod internal;
mod ser;

#[proc_macro_derive(NixDeserialize, attributes(nix))]
pub fn derive_nix_deserialize(item: TokenStream) -> TokenStream {
    let mut input = syn::parse_macro_input!(item as DeriveInput);
    let crate_path: syn::Path = parse_quote!(::nix_compat);
    de::expand_nix_deserialize(crate_path, &mut input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

#[proc_macro_derive(NixSerialize, attributes(nix))]
pub fn derive_nix_serialize(item: TokenStream) -> TokenStream {
    let mut input = syn::parse_macro_input!(item as DeriveInput);
    let crate_path: syn::Path = parse_quote!(::nix_compat);
    ser::expand_nix_serialize(crate_path, &mut input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Macro to implement `NixDeserialize` on a type.
/// Sometimes you can't use the deriver to implement `NixDeserialize`
/// (like when dealing with types in Rust standard library) but don't want
/// to implement it yourself. So this macro can be used for those situations
/// where you would derive using `#[nix(from_str)]`,
/// `#[nix(from = "FromType")]` or `#[nix(try_from = "FromType")]` if you
/// could.
///
/// #### Example
///
/// ```rust
/// # use nix_compat_derive::nix_deserialize_remote;
/// #
/// struct MyU64(u64);
///
/// impl From<u64> for MyU64 {
///     fn from(value: u64) -> Self {
///         Self(value)
///     }
/// }
///
/// nix_deserialize_remote!(#[nix(from="u64")] MyU64);
/// ```
#[proc_macro]
pub fn nix_deserialize_remote(item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as RemoteInput);
    let crate_path = parse_quote!(::nix_compat);
    de::expand_nix_deserialize_remote(crate_path, &input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Macro to implement `NixSerialize` on a type.
/// Sometimes you can't use the deriver to implement `NixSerialize`
/// (like when dealing with types in Rust standard library) but don't want
/// to implement it yourself. So this macro can be used for those situations
/// where you would derive using `#[nix(display)]`, `#[nix(display = "path")]`,
/// `#[nix(store_dir_display)]`, `#[nix(into = "IntoType")]` or
/// `#[nix(try_into = "IntoType")]` if you could.
///
/// #### Example
///
/// ```rust
/// # use nix_compat_derive::nix_serialize_remote;
/// #
/// #[derive(Clone)]
/// struct MyU64(u64);
///
/// impl From<MyU64> for u64 {
///     fn from(value: MyU64) -> Self {
///         value.0
///     }
/// }
///
/// nix_serialize_remote!(#[nix(into="u64")] MyU64);
/// ```
#[proc_macro]
pub fn nix_serialize_remote(item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as RemoteInput);
    let crate_path = parse_quote!(::nix_compat);
    ser::expand_nix_serialize_remote(crate_path, &input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}