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
// sphinxcontrib_rust - Sphinx extension for the Rust programming language
// Copyright (C) 2024  Munir Contractor
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Module for the various Sphinx directives for the Rust domain.
//!
//! The module primarily provides the
//! :rust:enum:`~sphinx-rustdocgen::directives::Directive`, which implements the
//! various directives using directive specific structs. The enum and all
//! directive specific structs implement both
//! :rust:trait:`~sphinx-rustdocgen::formats::RstContent` and
//! :rust:trait:`~sphinx-rustdocgen::formats::MdContent` traits.
//! It also provides the
//! :rust:enum:`~sphinx-rustdocgen::directives::DirectiveOption` enum, which
//! implements the various options of the directive.
//!
//! The output of the directives is parsed by the
//! :py:class:`sphinxcontrib_rust.directives.RustDirective` within the Python
//! extension.

mod crate_directive;
mod enum_directive;
mod executable_directive;
mod foreign_mod;
mod function_directive;
mod impl_directive;
mod macro_directive;
mod module_directive;
mod struct_directive;
mod trait_directive;
mod type_directive;
mod use_directive;
mod variable_directive;

use std::fmt::{Display, Formatter};
use std::str::FromStr;

use serde::Deserialize;
use syn::{Attribute, Expr, ForeignItem, ImplItem, Item, Lit, TraitItem, Visibility};

pub(crate) use crate::directives::crate_directive::CrateDirective;
pub(crate) use crate::directives::enum_directive::EnumDirective;
pub(crate) use crate::directives::executable_directive::ExecutableDirective;
pub(crate) use crate::directives::foreign_mod::ForeignModDirective;
pub(crate) use crate::directives::function_directive::FunctionDirective;
pub(crate) use crate::directives::impl_directive::ImplDirective;
pub(crate) use crate::directives::macro_directive::MacroDirective;
pub(crate) use crate::directives::module_directive::ModuleDirective;
pub(crate) use crate::directives::struct_directive::StructDirective;
pub(crate) use crate::directives::trait_directive::TraitDirective;
pub(crate) use crate::directives::type_directive::TypeDirective;
pub(crate) use crate::directives::use_directive::UseDirective;
pub(crate) use crate::directives::variable_directive::VariableDirective;
use crate::formats::{MdDirective, MdOption, RstDirective, RstOption};
use crate::nodes::Node;

/// The Sphinx directives that are implemented by the Rust domain.
#[derive(Clone, Debug)]
pub(crate) enum Directive {
    Crate(CrateDirective),
    Enum(EnumDirective),
    Executable(ExecutableDirective),
    ForeignMod(ForeignModDirective),
    Function(FunctionDirective),
    Impl(ImplDirective),
    Macro(MacroDirective),
    Module(ModuleDirective),
    Struct(StructDirective),
    Trait(TraitDirective),
    Type(TypeDirective),
    Use(UseDirective),
    Variable(VariableDirective),
}

impl Directive {
    fn name(&self) -> &str {
        match self {
            Directive::Crate(c) => &c.name,
            Directive::Enum(e) => &e.name,
            Directive::Executable(e) => &e.name,
            Directive::ForeignMod(_) => "",
            Directive::Function(f) => &f.name,
            Directive::Impl(i) => &i.name,
            Directive::Macro(m) => &m.name,
            Directive::Module(m) => &m.name,
            Directive::Struct(s) => &s.name,
            Directive::Trait(t) => &t.name,
            Directive::Type(t) => &t.name,
            Directive::Use(_) => {
                unreachable!("name is used for sorting, which is not done for UseDirective")
            }
            Directive::Variable(v) => &v.name,
        }
    }

    /// Create the appropriate directive from the provided ``syn::Item``
    ///
    /// Args:
    ///     :parent_path: The parent path of the item.
    ///     :item: The item to parse into a directive.
    ///
    /// Returns:
    ///     An option a :rust:enum:`sphinx-rustdocgen::directives::Directive`
    ///     variant.
    fn from_item(
        parent_path: &str,
        item: &Item,
        inherited_visibility: &Option<&Visibility>,
    ) -> Option<Directive> {
        match item {
            Item::Const(c) => Some(VariableDirective::from_const(
                parent_path,
                c,
                inherited_visibility,
            )),
            Item::Enum(e) => Some(EnumDirective::from_item(
                parent_path,
                e,
                inherited_visibility,
            )),
            Item::ExternCrate(_) => None,
            Item::Fn(f) => Some(FunctionDirective::from_item(
                parent_path,
                f,
                inherited_visibility,
            )),
            Item::ForeignMod(f) => Some(ForeignModDirective::from_item(
                parent_path,
                f,
                inherited_visibility,
            )),
            Item::Impl(i) => Some(ImplDirective::from_item(
                parent_path,
                i,
                inherited_visibility,
            )),
            Item::Macro(m) => MacroDirective::from_item(parent_path, m),
            Item::Mod(m) => ModuleDirective::from_item(parent_path, m),
            Item::Static(s) => Some(VariableDirective::from_static(
                parent_path,
                s,
                inherited_visibility,
            )),
            Item::Struct(s) => Some(StructDirective::from_item(
                parent_path,
                s,
                inherited_visibility,
            )),
            Item::Trait(t) => Some(TraitDirective::from_item(
                parent_path,
                t,
                inherited_visibility,
            )),
            Item::TraitAlias(t) => Some(TraitDirective::from_alias(
                parent_path,
                t,
                inherited_visibility,
            )),
            Item::Type(t) => Some(TypeDirective::from_item(
                parent_path,
                t,
                inherited_visibility,
            )),
            Item::Union(u) => Some(StructDirective::from_union(
                parent_path,
                u,
                inherited_visibility,
            )),
            Item::Use(u) => Some(UseDirective::from_item(parent_path, u)),
            Item::Verbatim(_) => None,
            i => panic!("Unexpected item: {:?}", i),
        }
    }

    /// Create the appropriate directives from the provided ``syn::Item``
    /// iterator.
    ///
    /// Args:
    ///     :parent_path: The parent path of the items.
    ///     :items: The items to parse into a directive.
    ///
    /// Returns:
    ///     An vec of :rust:enum:`sphinx-rustdocgen::directives::Directive`
    ///     variants.
    fn from_items<'a, T: Iterator<Item = &'a Item>>(
        parent_path: &str,
        items: T,
        inherited_visibility: &Option<&Visibility>,
    ) -> Vec<Directive> {
        items
            .filter_map(|i| Self::from_item(parent_path, i, inherited_visibility))
            .collect()
    }

    /// Create the appropriate directive from the provided ``syn::ImplItem``
    ///
    /// Args:
    ///     :parent_path: The path of the impl block which defines the item.
    ///     :item: The impl item to parse into a directive.
    ///
    /// Returns:
    ///     An option a :rust:enum:`sphinx-rustdocgen::directives::Directive`
    ///     variant.
    fn from_impl_item(
        parent_path: &str,
        item: &ImplItem,
        inherited_visibility: &Option<&Visibility>,
    ) -> Option<Directive> {
        match item {
            ImplItem::Const(c) => Some(VariableDirective::from_impl_const(
                parent_path,
                c,
                inherited_visibility,
            )),
            ImplItem::Fn(f) => Some(FunctionDirective::from_impl_item(
                parent_path,
                f,
                inherited_visibility,
            )),
            ImplItem::Type(t) => Some(TypeDirective::from_impl_item(
                parent_path,
                t,
                inherited_visibility,
            )),
            ImplItem::Macro(_) | ImplItem::Verbatim(_) => None,
            i => panic!("Unexpected impl item: {:?}", i),
        }
    }

    /// Create the appropriate directives from the provided ``syn::ImplItem``
    /// iterator.
    ///
    /// Args:
    ///     :parent_path: The path of the impl block which defines the items.
    ///     :items: The impl items to parse into a directive.
    ///
    /// Returns:
    ///     An vec of :rust:enum:`sphinx-rustdocgen::directives::Directive`
    ///     variants.
    fn from_impl_items<'a, T: Iterator<Item = &'a ImplItem>>(
        parent_path: &str,
        items: T,
        inherited_visibility: &Option<&Visibility>,
    ) -> Vec<Directive> {
        items
            .filter_map(|i| Self::from_impl_item(parent_path, i, inherited_visibility))
            .collect()
    }

    /// Create the appropriate directive from the provided ``syn::TraitItem``
    ///
    /// Args:
    ///     :parent_path: The path of the trait which defines the items.
    ///     :item: The trait item to parse into a directive.
    ///
    /// Returns:
    ///     An option a :rust:enum:`sphinx-rustdocgen::directives::Directive`
    ///     variant.
    fn from_trait_item(
        parent_path: &str,
        item: &TraitItem,
        inherited_visibility: &Option<&Visibility>,
    ) -> Option<Directive> {
        match item {
            TraitItem::Const(c) => Some(VariableDirective::from_trait_const(
                parent_path,
                c,
                inherited_visibility,
            )),
            TraitItem::Fn(f) => Some(FunctionDirective::from_trait_item(
                parent_path,
                f,
                inherited_visibility,
            )),
            TraitItem::Type(t) => Some(TypeDirective::from_trait_item(
                parent_path,
                t,
                inherited_visibility,
            )),
            TraitItem::Macro(_) | TraitItem::Verbatim(_) => None,
            i => panic!("Unexpected trait item: {:?}", i),
        }
    }

    /// Create the appropriate directives from the provided ``syn::TraitItem``
    /// iterator.
    ///
    /// Args:
    ///     :parent_path: The path of the trait which defines the items.
    ///     :items: The trait items to parse into a directive.
    ///
    /// Returns:
    ///     An vec of :rust:enum:`sphinx-rustdocgen::directives::Directive`
    ///     variants.
    fn from_trait_items<'a, T: Iterator<Item = &'a TraitItem>>(
        parent_path: &str,
        items: T,
        inherited_visibility: &Option<&Visibility>,
    ) -> Vec<Directive> {
        items
            .filter_map(|i| Self::from_trait_item(parent_path, i, inherited_visibility))
            .collect()
    }

    fn from_extern_item(
        parent_path: &str,
        item: &ForeignItem,
        inherited_visibility: &Option<&Visibility>,
    ) -> Option<Directive> {
        match item {
            ForeignItem::Fn(f) => Some(FunctionDirective::from_extern(
                parent_path,
                f,
                inherited_visibility,
            )),
            ForeignItem::Static(s) => Some(VariableDirective::from_extern_static(
                parent_path,
                s,
                inherited_visibility,
            )),
            ForeignItem::Type(t) => Some(TypeDirective::from_extern(
                parent_path,
                t,
                inherited_visibility,
            )),
            _ => None,
        }
    }

    fn from_extern_items<'a, T: Iterator<Item = &'a ForeignItem>>(
        parent_path: &str,
        items: T,
        inherited_visibility: &Option<&Visibility>,
    ) -> Vec<Directive> {
        items
            .filter_map(|i| Self::from_extern_item(parent_path, i, inherited_visibility))
            .collect()
    }
}

impl Display for Directive {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let value = match self {
            Directive::Crate(_) => "crate",
            Directive::Enum(_) => "enum",
            Directive::Executable(_) => "executable",
            Directive::ForeignMod(_) => "",
            Directive::Function(_) => "function",
            Directive::Impl(_) => "impl",
            Directive::Macro(_) => "macro",
            Directive::Module(_) => "module",
            Directive::Struct(_) => "struct",
            Directive::Trait(_) => "trait",
            Directive::Type(_) => "type",
            Directive::Use(_) => "use",
            Directive::Variable(_) => "variable",
        };
        write!(f, "{value}")
    }
}

impl RstDirective for Directive {
    fn get_rst_text(self, level: usize, max_visibility: &DirectiveVisibility) -> Vec<String> {
        match self {
            Directive::Crate(c) => c.get_rst_text(level, max_visibility),
            Directive::Enum(e) => e.get_rst_text(level, max_visibility),
            Directive::Executable(e) => e.get_rst_text(level, max_visibility),
            Directive::ForeignMod(f) => f.get_rst_text(level, max_visibility),
            Directive::Function(f) => f.get_rst_text(level, max_visibility),
            Directive::Impl(i) => i.get_rst_text(level, max_visibility),
            Directive::Macro(m) => m.get_rst_text(level, max_visibility),
            Directive::Module(m) => m.get_rst_text(level, max_visibility),
            Directive::Struct(s) => s.get_rst_text(level, max_visibility),
            Directive::Trait(t) => t.get_rst_text(level, max_visibility),
            Directive::Type(t) => t.get_rst_text(level, max_visibility),
            Directive::Use(u) => u.get_rst_text(level, max_visibility),
            Directive::Variable(v) => v.get_rst_text(level, max_visibility),
        }
    }
}

impl MdDirective for Directive {
    fn get_md_text(self, fence_size: usize, max_visibility: &DirectiveVisibility) -> Vec<String> {
        match self {
            Directive::Crate(c) => c.get_md_text(fence_size, max_visibility),
            Directive::Enum(e) => e.get_md_text(fence_size, max_visibility),
            Directive::Executable(e) => e.get_md_text(fence_size, max_visibility),
            Directive::ForeignMod(f) => f.get_md_text(fence_size, max_visibility),
            Directive::Function(f) => f.get_md_text(fence_size, max_visibility),
            Directive::Impl(i) => i.get_md_text(fence_size, max_visibility),
            Directive::Macro(m) => m.get_md_text(fence_size, max_visibility),
            Directive::Module(m) => m.get_md_text(fence_size, max_visibility),
            Directive::Struct(s) => s.get_md_text(fence_size, max_visibility),
            Directive::Trait(t) => t.get_md_text(fence_size, max_visibility),
            Directive::Type(t) => t.get_md_text(fence_size, max_visibility),
            Directive::Use(u) => u.get_md_text(fence_size, max_visibility),
            Directive::Variable(v) => v.get_md_text(fence_size, max_visibility),
        }
    }

    fn fence_size(&self) -> usize {
        match self {
            Directive::Crate(c) => c.fence_size(),
            Directive::Enum(e) => e.fence_size(),
            Directive::Executable(e) => e.fence_size(),
            Directive::ForeignMod(f) => f.fence_size(),
            Directive::Function(f) => f.fence_size(),
            Directive::Impl(i) => i.fence_size(),
            Directive::Macro(m) => m.fence_size(),
            Directive::Module(m) => m.fence_size(),
            Directive::Struct(s) => s.fence_size(),
            Directive::Trait(t) => t.fence_size(),
            Directive::Type(t) => t.fence_size(),
            Directive::Use(u) => u.fence_size(),
            Directive::Variable(v) => v.fence_size(),
        }
    }
}

/// Extract the docstring from the attrs of an item.
///
/// Args:
///     :attrs: ``syn::attr::Attribute`` vec.
///
/// Returns:
///     A vec of strings, where each string is a line of a documentation
///     comment. If there are no documentation comments, an empty vec is
///     returned.
pub(crate) fn extract_doc_from_attrs(attrs: &Vec<Attribute>) -> Vec<String> {
    let mut content = Vec::new();
    for attr in attrs {
        if attr.path().segments.is_empty() || attr.path().segments[0].ident != "doc" {
            continue;
        }

        if let Expr::Lit(e) = &attr.meta.require_name_value().unwrap().value {
            if let Lit::Str(d) = &e.lit {
                let line = d.value();
                content.push(line.strip_prefix(' ').unwrap_or(&line).to_string());
            }
        }
    }
    content
}

/// DRY macro to check which visibility value to pass to inner items.
#[macro_export]
macro_rules! visibility_to_inherit {
    ($directive:expr, $inherited:expr) => {
        match $directive {
            Visibility::Inherited => $inherited,
            _ => Some(&$directive),
        }
    };
}

/// Enum for the values of the
/// :rust:struct:`~sphinx-rustdocgen::directives::DirectiveOption::Vis` option
///
/// The enum is ordered ``Pub < Crate < Pvt``, so it can be efficiently
/// compared for filtering. Note that ordering here is opposite to that of the
/// visibility itself.
#[derive(Clone, Copy, Debug, Default, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub(crate) enum DirectiveVisibility {
    #[default]
    Pub = 0,
    Crate = 1,
    Pvt = 2,
}

impl DirectiveVisibility {
    fn effective_visibility(
        visibility: &Visibility,
        inherited_visibility: &Option<&Visibility>,
    ) -> DirectiveVisibility {
        match visibility {
            Visibility::Public(_) => DirectiveVisibility::Pub,
            Visibility::Restricted(v) => {
                let path = &v.path;
                if path.segments.len() == 1 && path.segments.first().unwrap().ident == "crate" {
                    DirectiveVisibility::Crate
                }
                else {
                    DirectiveVisibility::Pvt
                }
            }
            Visibility::Inherited => match inherited_visibility {
                None => DirectiveVisibility::Pvt,
                Some(v) => Self::effective_visibility(v, &None),
            },
        }
    }
}

impl Display for DirectiveVisibility {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            DirectiveVisibility::Pub => f.write_str("pub"),
            DirectiveVisibility::Crate => f.write_str("crate"),
            DirectiveVisibility::Pvt => f.write_str("pvt"),
        }
    }
}

impl FromStr for DirectiveVisibility {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.to_lowercase();
        if s == "pub" {
            Ok(DirectiveVisibility::Pub)
        }
        else if s == "crate" {
            Ok(DirectiveVisibility::Crate)
        }
        else if s == "pvt" {
            Ok(DirectiveVisibility::Pvt)
        }
        else {
            Err(format!("Invalid value for visibility: {s}"))
        }
    }
}

/// Check the options to determine if the visibility of a directive matches
/// the specified max visibility and return empty Vec if not.
///
/// This macro should be used within a function and will cause it to return
/// early when the visibility of the options provided does not meet the
/// specified max.
///
/// Args:
///     :options: A vec of ``DirectiveOption``
///     :max: The maximum visibility that should be included in the output.
#[macro_export]
macro_rules! check_visibility {
    ($options:expr, $max:expr) => {{
        for option in $options.iter() {
            if let DirectiveOption::Vis(v) = option {
                if v > $max {
                    return Vec::new();
                }
            }
        }
    }};
}

/// The different index entry types.
///
/// This corresponds to the Python enum
/// :py:class:`sphinxcontrib_rust.items.SphinxIndexEntryType`.
#[derive(Copy, Clone, Debug)]
#[repr(i8)]
pub(crate) enum IndexEntryType {
    None = -1,
    Normal = 0,
    WithSubEntries = 1,
    SubEntry = 2,
}

/// Enum to represent the various options for the directives.
///
/// The enum implements the
/// :rust:trait:`~sphinx-rustdocgen::formats::RstContent` and
/// :rust:trait:`~sphinx-rustdocgen::formats::MdContent` traits for easily
/// converting the options to required text.
#[derive(Clone, Debug)]
pub(crate) enum DirectiveOption {
    /// The ``:index:`` option
    Index(IndexEntryType),
    /// The ``:vis:`` option.
    Vis(DirectiveVisibility),
    /// The ``:layout:`` option.
    Layout(Vec<Node>),
    /// The ``:toc:`` option.
    Toc(String),
}

impl RstOption for DirectiveOption {
    fn get_rst_text(&self, indent: &str) -> Option<String> {
        Some(match self {
            DirectiveOption::Index(i) => {
                format!("{indent}:index: {}", *i as i8)
            }
            DirectiveOption::Vis(v) => {
                format!("{indent}:vis: {v}")
            }
            DirectiveOption::Toc(t) => {
                format!("{indent}:toc: {t}")
            }
            DirectiveOption::Layout(lines) => {
                format!("{indent}:layout: {}", serde_json::to_string(lines).unwrap())
            }
        })
    }
}

impl MdOption for DirectiveOption {
    fn get_md_text(&self) -> Option<String> {
        Some(match self {
            DirectiveOption::Index(i) => {
                format!(":index: {}", *i as i8)
            }
            DirectiveOption::Vis(v) => {
                format!(":vis: {v}")
            }
            DirectiveOption::Toc(t) => {
                format!(":toc: {t}")
            }
            DirectiveOption::Layout(lines) => {
                format!(":layout: {}", serde_json::to_string(lines).unwrap())
            }
        })
    }
}

macro_rules! push_sorted {
    ($sorted:expr, $items:expr, $name:expr) => {{
        if !$items.is_empty() {
            $items.sort_by(|a, b| a.name().cmp(b.name()));
            $sorted.push(($name, $items));
        }
    }};
}

/// Named tuple type for the output of :rust:fn:`order_items`.
///
/// The elements are:
///
/// * The list of the modules that should be added to toctree.
/// * The list of document section titles and the directives within them.
/// * The list of use directives to include within the document.
type DocStructure = (
    Vec<ModuleDirective>,
    Vec<(&'static str, Vec<Directive>)>,
    Vec<UseDirective>,
);

/// Order the items for documentation
///
/// The items are ordered using the following rules:
///
/// 1. If the item is a module without content, it is removed and a link to the
///    module is added to the ``toctree``. If there are no such module, the
///    ``toctree`` isn't added.
/// 2. Each directive is then separated by type and ordered alphabetically
///    except for ``impl`` directives.
/// 3. All ``impl`` blocks associated with a struct or enum are ordered after
///    it, starting with the associated ``impl`` block, followed by trait
///    ``impl`` blocks in alphabetical order.
///
/// Returns:
///    An vec of module directives that have no items and a vec of
///    section names with their directives.
fn order_items(items: Vec<Directive>) -> DocStructure {
    let mut enums = vec![];
    let mut fns = vec![];
    let mut impls = vec![];
    let mut macros = vec![];
    let mut toc_tree_modules = vec![];
    let mut defined_modules = vec![];
    let mut structs = vec![];
    let mut traits = vec![];
    let mut types = vec![];
    let mut uses = vec![];
    let mut vars = vec![];

    for item in items {
        match item {
            Directive::Crate(_) => {
                unreachable!("Unexpected crate directive as an item")
            }
            Directive::Enum(e) => enums.push(Directive::Enum(e)),
            Directive::Executable(_) => {
                unreachable!("Unexpected executable directive as an item")
            }
            Directive::ForeignMod(f) => {
                for item in f.items {
                    match item {
                        Directive::Function(f) => fns.push(Directive::Function(f)),
                        Directive::Type(t) => types.push(Directive::Type(t)),
                        Directive::Variable(v) => vars.push(Directive::Variable(v)),
                        _ => {
                            unreachable!("Foreign mod should not have any other item types")
                        }
                    }
                }
            }
            Directive::Function(f) => fns.push(Directive::Function(f)),
            Directive::Impl(i) => impls.push(Directive::Impl(i)),
            Directive::Macro(m) => macros.push(Directive::Macro(m)),
            Directive::Module(m) => {
                if m.items.is_empty() {
                    toc_tree_modules.push(m)
                }
                else {
                    defined_modules.push(Directive::Module(m))
                }
            }
            Directive::Struct(s) => structs.push(Directive::Struct(s)),
            Directive::Trait(t) => traits.push(Directive::Trait(t)),
            Directive::Type(t) => types.push(Directive::Type(t)),
            Directive::Use(u) => uses.push(u),
            Directive::Variable(v) => vars.push(Directive::Variable(v)),
        }
    }

    impls.sort_by(|a, b| a.name().cmp(b.name()));

    let mut sorted = Vec::new();
    push_sorted!(sorted, defined_modules, "Inline Modules");
    push_sorted!(sorted, types, "Types");
    push_sorted!(sorted, vars, "Variables");
    push_sorted!(sorted, macros, "Macros");
    push_sorted!(sorted, fns, "Functions");

    push_sorted!(sorted, traits, "Traits");
    push_sorted!(sorted, enums, "Enums");
    push_sorted!(sorted, structs, "Structs and Unions");
    push_sorted!(sorted, impls, "Impls");

    (toc_tree_modules, sorted, uses)
}