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
#![warn(clippy::all)]
#![warn(clippy::pedantic)]

//! This crate derives [visitor pattern](https://rust-unofficial.github.io/patterns/patterns/behavioural/visitor.html)
//! for arbitrary data structures. This pattern is particularly useful when dealing with complex nested data structures,
//! abstract trees and hierarchies of all kinds.
//!
//! The main building blocks of this crate are two derivable traits:
//! - [Visitor] implementations walk through a data structures and accumulates some information;
//! - [Drive] implementations are data structures that know how to drive a visitor through themselves.
//!
//! Please refer to these traits' documentation for more details.
//!
//! ## Example
//!
//! ```
//! use derive_visitor::{Visitor, Drive};
//!
//! #[derive(Drive)]
//! struct Directory {
//!     #[drive(skip)]
//!     name: String,
//!     items: Vec<DirectoryItem>,
//! }
//!
//! #[derive(Drive)]
//! enum DirectoryItem {
//!     File(File),
//!     Directory(Directory),
//! }
//!
//! #[derive(Drive)]
//! struct File {
//!     #[drive(skip)]
//!     name: String,
//! }
//!
//! #[derive(Visitor, Default)]
//! #[visitor(File(enter), Directory(enter))]
//! struct Counter {
//!     files: u32,
//!     directories: u32
//! }
//!
//! impl Counter {
//!     fn enter_file(&mut self, _file: &File) {
//!         self.files += 1;
//!     }
//!     fn enter_directory(&mut self, _directory: &Directory) {
//!         self.directories += 1;
//!     }
//! }
//!
//! let mut counter = Counter::default();
//!
//! let example_directory = Directory {
//!     name: "root".into(),
//!     items: vec![
//!         DirectoryItem::Directory(
//!             Directory {
//!                 name: "home".into(),
//!                 items: vec![
//!                     DirectoryItem::File(File { name: "README.md".into() }),
//!                     DirectoryItem::File(File { name: "Star Wars.mov".into() })
//!                 ]
//!             }
//!         ),
//!         DirectoryItem::Directory(
//!             Directory { name: "downloads".into(), items: vec![] }
//!         )
//!     ],
//! };
//!
//! example_directory.drive(&mut counter);
//!
//! assert_eq!(counter.files, 2);
//! assert_eq!(counter.directories, 3);
//! ```

/// See [Drive].
pub use derive_visitor_macros::Drive;

/// See [Visitor].
pub use derive_visitor_macros::Visitor;

use std::{
    any::Any,
    cell::Cell,
    collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque},
};

/// An interface for visiting arbitrary data structures.
///
/// A visitor receives items that implement [Any], and can use dynamic dispatch
/// to downcast them to particular types that it is interested in. In the classal
/// visitor pattern, a Visitor has a set of separate methods to deal with each particular
/// item type. This behavior can be implemented automatically using derive.
///
/// ## Derivable
///
/// This trait can be derived for any struct or enum. By default, the derived implementation
/// does nothing. You need to explicitly specify what item types and / or events your visitor
/// is interested in, using top-level attribute:
///
/// ```ignore
/// #[derive(Visitor)]
/// #[visitor(Directory, File)]
/// struct NameValidator {
///     errors: Vec<InvalidNameError>,
/// }
///
/// impl NameValidator {
///     fn enter_directory(&mut self, item: &Directory) {
///         // ...your logic here
///     }
///     fn exit_directory(&mut self, item: &Directory) {
///         // ...your logic here
///     }
///     fn enter_file(&mut self, item: &File) {
///         // ...your logic here
///     }
///     fn exit_file(&mut self, item: &File) {
///         // ...your logic here
///     }
/// }
/// ```
///
/// ## Macro attributes
///
/// If your visitor is only interested in entering or exiting a particular type, but not both,
/// you can configure the derived implementation to only call enter / exit, respectively:
///
/// ```ignore
/// #[derive(Visitor)]
/// #[visitor(Directory(enter), File(exit))]
/// struct NameValidator {
///     errors: Vec<InvalidNameError>,
/// }
///
/// impl NameValidator {
///     fn enter_directory(&mut self, item: &Directory) {
///         // ...your logic here
///     }
///     fn exit_file(&mut self, item: &File) {
///         // ...your logic here
///     }
/// }
/// ```
///
/// You can also provide custom method names for each type / event:
///
/// ```ignore
/// #[derive(Visitor)]
/// #[visitor(Directory(enter="custom_enter_directory", exit="custom_exit_directory"), File)]
/// struct NameValidator {
///     errors: Vec<InvalidNameError>,
/// }
///
/// impl NameValidator {
///     fn custom_enter_directory(&mut self, item: &Directory) {
///         // ...your logic here
///     }
///     fn custom_exit_directory(&mut self, item: &Directory) {
///         // ...your logic here
///     }
///     fn enter_file(&mut self, item: &File) {
///         // ...your logic here
///     }
///     fn exit_file(&mut self, item: &File) {
///         // ...your logic here
///     }
/// }
/// ```
pub trait Visitor {
    fn visit(&mut self, item: &dyn Any, event: Event);
}

/// Defines whether an item is being entered or exited by a visitor.
pub enum Event {
    Enter,
    Exit,
}

/// A data structure that can drive a [visitor](Visitor) through iself.
///
/// Derive or implement this trait for any type that you want to be able to
/// traverse with a visitor.
///
/// `Drive` is implemented for most wrapping and collection types from [std],
/// as long as their wrapped / item type implements `Drive`.
///
/// ## Derivable
///
/// This trait can be derived for any struct or enum.
/// By default, the derived implementation will make the visitor enter `self`,
/// then drive it through every field of `self`, and finally make it exit `self`:
///
/// ```ignore
/// #[derive(Drive)]
/// struct Directory {
///     #[drive(skip)]
///     name: String,
///     items: Vec<DirectoryItem>,
/// }
///
/// #[derive(Drive)]
/// enum DirectoryItem {
///     File(File),
///     Directory(Directory),
/// }
///
/// #[derive(Drive)]
/// struct File {
///     #[drive(skip)]
///     name: String,
/// }
/// ```
///
/// ## Implementing manually
///
/// The following code snippet is roughly equivalent to the implementations
/// that would be derived in the example above:
///
/// ```ignore
/// impl Drive for Directory {
///     fn drive<V: Visitor>(&self, visitor: &mut V) {
///         visitor.visit(self, Event::Enter);
///         self.items.drive(visitor);
///         visitor.visit(self, Event::Exit);
///     }
/// }
///
/// impl Drive for DirectoryItem {
///     fn drive<V: Visitor>(&self, visitor: &mut V) {
///         visitor.visit(self, Event::Enter);
///         match self {
///             Self::File(file) => {
///                 file.drive(visitor);
///             },
///             Self::Directory(directory) => {
///                 directory.drive(visitor);
///             }
///         }
///         visitor.visit(self, Event::Exit);
///     }
/// }
///
/// impl Drive for File {
///     fn drive<V: Visitor>(&self, visitor: &mut V) {
///         visitor.visit(self, Event::Enter);
///         visitor.visit(self, Event::Exit);
///     }
/// }
/// ```
///
/// ## Macro attributes
///
/// The derived implementation of `Drive` can be customized using attributes:
///
/// ### `#[drive(skip)]`
///
/// If applied to a field or an enum variant, the derived implementation won't
/// drive the visitor through that field / variant.
///
/// If applied to a struct or an enum itself, the derived implementation will
/// drive the visitor through the type's fields / variants, but won't make it
/// enter or exit the type itself.
///
/// ### `#[drive(with="path")]`
///
/// Drive a visitor through a field using a custom function.
/// The function must have the following signature: `fn<V: Visitor>(&T, &mut V)`.
///
/// In the example below, this attribute is used to customize driving through a [Vec]:
///
/// ```ignore
/// #[derive(Drive)]
/// struct Book {
///     title: String,
///     #[drive(with="reverse_vec_driver")]
///     chapters: Vec<Chapter>,
/// }
///
/// fn reverse_vec_driver<T, V: Visitor>(vec: &Vec<T>, visitor: &mut V) {
///     for item in vec.iter().rev() {
///         item.drive(visitor);
///     }
/// }
/// ```
pub trait Drive: Any {
    fn drive<V: Visitor>(&self, visitor: &mut V);
}

impl<K, Val> Drive for BTreeMap<K, Val>
where
    K: Drive,
    Val: Drive,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        for (key, value) in self.iter() {
            key.drive(visitor);
            value.drive(visitor);
        }
    }
}

impl<T> Drive for BTreeSet<T>
where
    T: Drive,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        self.iter().for_each(|item| item.drive(visitor));
    }
}

impl<T> Drive for BinaryHeap<T>
where
    T: Drive,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        self.iter().for_each(|item| item.drive(visitor));
    }
}

impl<T> Drive for Box<T>
where
    T: Drive,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        (**self).drive(visitor);
    }
}

impl<T> Drive for Cell<T>
where
    T: Drive + Copy,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        self.get().drive(visitor);
    }
}

impl<K, Val, S> Drive for HashMap<K, Val, S>
where
    K: Drive,
    Val: Drive,
    S: 'static,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        for (key, value) in self.iter() {
            key.drive(visitor);
            value.drive(visitor);
        }
    }
}

impl<T, S> Drive for HashSet<T, S>
where
    T: Drive,
    S: 'static,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        self.iter().for_each(|item| item.drive(visitor));
    }
}

impl<T> Drive for LinkedList<T>
where
    T: Drive,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        self.iter().for_each(|item| item.drive(visitor));
    }
}

impl<T> Drive for Option<T>
where
    T: Drive,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        if let Some(value) = self {
            value.drive(visitor);
        }
    }
}

impl<T> Drive for Vec<T>
where
    T: Drive,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        self.iter().for_each(|item| item.drive(visitor));
    }
}

impl<T> Drive for VecDeque<T>
where
    T: Drive,
{
    fn drive<V: Visitor>(&self, visitor: &mut V) {
        self.iter().for_each(|item| item.drive(visitor));
    }
}

impl Drive for () {
    fn drive<V: Visitor>(&self, _visitor: &mut V) {}
}

macro_rules! tuple_impls {
    ( $( $( $type:ident ),+ => $( $field:tt ),+ )+ ) => {
        $(
            impl<$( $type ),+> Drive for ($($type,)+)
            where
                $(
                    $type: Drive
                ),+
            {
                fn drive<V: Visitor>(&self, visitor: &mut V) {
                    $(
                        self.$field.drive(visitor);
                    )+
                }
            }
        )+
    };
}

tuple_impls! {
    T0 => 0
    T0, T1 => 0, 1
    T0, T1, T2 => 0, 1, 2
    T0, T1, T2, T3 => 0, 1, 2, 3
    T0, T1, T2, T3, T4 => 0, 1, 2, 3, 4
    T0, T1, T2, T3, T4, T5 => 0, 1, 2, 3, 4, 5
    T0, T1, T2, T3, T4, T5, T6 => 0, 1, 2, 3, 4, 5, 6
    T0, T1, T2, T3, T4, T5, T6, T7 => 0, 1, 2, 3, 4, 5, 6, 7
}

impl<T> Drive for [T; 0]
where
    T: Drive,
{
    fn drive<V: Visitor>(&self, _visitor: &mut V) {}
}

macro_rules! array_impls {
    ( $( $len:expr => $( $field:expr ),+ )+ ) => {
        $(
            impl<T> Drive for [T; $len]
            where
                T: Drive
            {
                fn drive<V: Visitor>(&self, visitor: &mut V) {
                    $(
                        self[$field].drive(visitor);
                    )+
                }
            }
        )+
    };
}

array_impls! {
    1 => 0
    2 => 0, 1
    3 => 0, 1, 2
    4 => 0, 1, 2, 3
    5 => 0, 1, 2, 3, 4
    6 => 0, 1, 2, 3, 4, 5
    7 => 0, 1, 2, 3, 4, 5, 6
    8 => 0, 1, 2, 3, 4, 5, 6, 7
}