rusty-man 0.4.1

Command-line viewer for rustdoc documentation
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
// SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: MIT

//! Parses HTML files generated by rustdoc.
//!
//! For details on the format of the parsed HTML files, check the following items in the
//! `html::render` module of `librustdoc` (in the Rust source):
//! - The `krate` and `render_item` methods of the `Context` struct are the main entry points for
//!   the rendering.
//! - The `print_item` and `item_*`functions generate the HTML for an item (module, struct, …).
//! - The `AllTypes::print` function generates the HTML for the `all.html` page using the
//!   `print_entries` function.

mod util;

use std::path;

use anyhow::Context;
use markup5ever::local_name;

use crate::doc;

use util::NodeRefExt;

pub struct Parser {
    document: kuchiki::NodeRef,
}

impl Parser {
    pub fn from_file(path: impl AsRef<path::Path>) -> anyhow::Result<Parser> {
        use kuchiki::traits::TendrilSink;

        log::info!("Reading HTML from file '{}'", path.as_ref().display());
        let document = kuchiki::parse_html()
            .from_utf8()
            .from_file(path)
            .context("Could not read HTML file")?;
        log::info!("HTML file parsed successfully");

        Ok(Parser { document })
    }

    pub fn from_string(s: impl Into<String>) -> anyhow::Result<Parser> {
        use kuchiki::traits::TendrilSink;

        log::info!("Reading HTML from string");
        let document = kuchiki::parse_html()
            .from_utf8()
            .read_from(&mut s.into().as_bytes())
            .context("Could not read HTML string")?;
        log::info!("HTML string parsed successfully");

        Ok(Parser { document })
    }

    pub fn find_item(&self, item: &str) -> anyhow::Result<Option<String>> {
        let item = select(&self.document, "ul.docblock li a")?
            .find(|e| e.text_contents() == item)
            .and_then(|e| e.get_attribute("href"));
        Ok(item)
    }

    pub fn find_member(&self, name: &doc::Fqn) -> anyhow::Result<Option<doc::ItemType>> {
        let member = get_member(&self.document, name.last())?;
        if let Some(member) = member {
            let id = member
                .get_attribute("id")
                .with_context(|| format!("The member {} does not have an ID", name))?;
            let ty = id.splitn(2, '.').next().unwrap().parse()?;
            Ok(Some(ty))
        } else {
            Ok(None)
        }
    }

    pub fn parse_item_doc(&self, name: &doc::Fqn, ty: doc::ItemType) -> anyhow::Result<doc::Doc> {
        log::info!("Parsing item documentation for '{}'", name);
        let definition_selector = match ty {
            doc::ItemType::Constant => "pre.const",
            doc::ItemType::Function => "pre.fn",
            doc::ItemType::Typedef => "pre.typedef",
            _ => ".docblock.type-decl",
        };
        let definition = select_first(&self.document, definition_selector)?;
        let description = select_first(&self.document, "#main > .docblock:not(.type-decl)")?;

        let mut doc = doc::Doc::new(name.clone(), ty);
        doc.description = description.map(From::from);
        doc.definition = definition.map(From::from);

        let members = vec![
            get_variants(&self.document, name)?,
            get_fields(&self.document, name)?,
            get_assoc_types(&self.document, name)?,
            get_methods(&self.document, name)?,
            get_implementations(&self.document, name)?,
        ];
        for (ty, groups) in members.into_iter() {
            if !groups.is_empty() {
                doc.groups.insert(ty, groups);
            }
        }

        Ok(doc)
    }

    pub fn parse_member_doc(&self, name: &doc::Fqn, ty: doc::ItemType) -> anyhow::Result<doc::Doc> {
        log::info!("Parsing member documentation for '{}'", name);
        let heading = select_first(&self.document, &get_member_selector(ty, name.last()))?
            .with_context(|| format!("Could not find member {}", name))?;
        let code = select_first(heading.as_node(), "code")?
            .with_context(|| format!("The member {} does not have a definition", name))?;
        let docblock = heading.as_node().next_sibling();

        let mut doc = doc::Doc::new(name.clone(), ty);
        doc.definition = Some(code.into());
        doc.description = docblock.map(From::from);
        Ok(doc)
    }

    pub fn parse_module_doc(&self, name: &doc::Fqn) -> anyhow::Result<doc::Doc> {
        log::info!("Parsing module documentation for '{}'", name);
        let description = select_first(&self.document, ".docblock")?;

        let mut doc = doc::Doc::new(name.clone(), doc::ItemType::Module);
        doc.description = description.map(From::from);
        for item_type in MODULE_MEMBER_TYPES {
            let mut group = doc::MemberGroup::new(None);
            group.members = get_members(&self.document, name, *item_type)?;
            if !group.members.is_empty() {
                doc.groups.insert(*item_type, vec![group]);
            }
        }
        Ok(doc)
    }

    pub fn find_examples(&self) -> anyhow::Result<Vec<doc::Example>> {
        let examples = select(&self.document, ".rust-example-rendered")?;
        Ok(examples.map(|n| get_example(n.as_node())).collect())
    }
}

impl From<kuchiki::NodeRef> for doc::Text {
    fn from(node: kuchiki::NodeRef) -> doc::Text {
        doc::Text::from(&node)
    }
}

impl From<&kuchiki::NodeRef> for doc::Text {
    fn from(node: &kuchiki::NodeRef) -> doc::Text {
        doc::Text {
            plain: node_to_text(node),
            html: node.to_string(),
        }
    }
}

impl<T> From<kuchiki::NodeDataRef<T>> for doc::Text {
    fn from(node: kuchiki::NodeDataRef<T>) -> doc::Text {
        node.as_node().into()
    }
}

impl From<kuchiki::NodeRef> for doc::Code {
    fn from(node: kuchiki::NodeRef) -> doc::Code {
        doc::Code::from(&node)
    }
}

impl From<&kuchiki::NodeRef> for doc::Code {
    fn from(node: &kuchiki::NodeRef) -> doc::Code {
        doc::Code::new(node_to_text(node))
    }
}

impl<T> From<kuchiki::NodeDataRef<T>> for doc::Code {
    fn from(node: kuchiki::NodeDataRef<T>) -> doc::Code {
        node.as_node().into()
    }
}

fn node_to_text(node: &kuchiki::NodeRef) -> String {
    let mut s = String::new();
    push_node_to_text(&mut s, node);
    s.trim().to_string()
}

fn push_node_to_text(s: &mut String, node: &kuchiki::NodeRef) {
    if node.has_class("notable-traits") {
        // The notable-traits element lists informations about types in a code block.  But we only
        // want to extract the code, so we skip this element.
        return;
    }

    let is_docblock = node.has_class("docblock");

    let add_newline = if node.is_element(&local_name!("br")) {
        true
    } else if node.has_class("fmt-newline") || is_docblock {
        !s.is_empty() && !s.ends_with('\n')
    } else {
        false
    };
    if add_newline {
        s.push_str("\n");
    }

    if let Some(text) = node.as_text() {
        s.push_str(&text.borrow())
    }

    for child in node.children() {
        push_node_to_text(s, &child);
    }

    if is_docblock && !s.is_empty() && !s.ends_with('\n') {
        s.push_str("\n");
    }
}

fn select(
    element: &kuchiki::NodeRef,
    selector: &str,
) -> anyhow::Result<kuchiki::iter::Select<kuchiki::iter::Elements<kuchiki::iter::Descendants>>> {
    element
        .select(selector)
        .ok()
        .with_context(|| format!("Could not apply selector {}", selector))
}

fn it_select<I: kuchiki::iter::NodeIterator>(
    iter: I,
    selector: &str,
) -> anyhow::Result<kuchiki::iter::Select<kuchiki::iter::Elements<I>>> {
    iter.select(selector)
        .ok()
        .with_context(|| format!("Could not apply selector {}", selector))
}

fn select_first(
    element: &kuchiki::NodeRef,
    selector: &str,
) -> anyhow::Result<Option<kuchiki::NodeDataRef<kuchiki::ElementData>>> {
    select(element, selector).map(|mut i| i.next())
}

fn it_select_first<I: kuchiki::iter::NodeIterator>(
    iter: I,
    selector: &str,
) -> anyhow::Result<Option<kuchiki::NodeDataRef<kuchiki::ElementData>>> {
    it_select(iter, selector).map(|mut i| i.next())
}

fn get_example(node: &kuchiki::NodeRef) -> doc::Example {
    let description_element = node
        .parent()
        .as_ref()
        .and_then(NodeRefExt::previous_sibling_element);
    let description = description_element
        .and_then(|n| {
            if n.text_contents().ends_with(':') {
                Some(n)
            } else {
                None
            }
        })
        .map(From::from);
    doc::Example::new(description, node.into())
}

const MODULE_MEMBER_TYPES: &[doc::ItemType] = &[
    doc::ItemType::ExternCrate,
    doc::ItemType::Import,
    doc::ItemType::Primitive,
    doc::ItemType::Module,
    doc::ItemType::Macro,
    doc::ItemType::Struct,
    doc::ItemType::Enum,
    doc::ItemType::Constant,
    doc::ItemType::Static,
    doc::ItemType::Trait,
    doc::ItemType::Function,
    doc::ItemType::Typedef,
    doc::ItemType::Union,
];

fn get_id_part(node: &kuchiki::NodeRef, i: usize) -> Option<String> {
    // id of format <type>.<name> (or <type>.<name>-<idx> for name collisions)
    if let Some(id) = node.get_attribute("id") {
        id.splitn(2, '.')
            .nth(i)
            .and_then(|s| s.splitn(2, '-').next())
            .map(ToOwned::to_owned)
    } else {
        None
    }
}

fn get_fields(
    document: &kuchiki::NodeRef,
    parent: &doc::Fqn,
) -> anyhow::Result<(doc::ItemType, Vec<doc::MemberGroup>)> {
    let ty = doc::ItemType::StructField;
    let mut fields = MemberDocs::new(parent, ty);
    let heading = select_first(document, &format!("#{}", get_item_group_id(ty)))?;

    let mut next = heading.as_ref().and_then(NodeRefExt::next_sibling_element);
    let mut name: Option<String> = None;
    let mut definition: Option<doc::Code> = None;

    while let Some(element) = &next {
        if element.is_element(&local_name!("span")) && element.has_class("structfield") {
            fields.push(&mut name, &mut definition, None)?;
            name = get_id_part(element, 1);
            definition = Some(element.into());
        } else if element.is_element(&local_name!("div")) {
            if element.has_class("docblock") {
                fields.push(&mut name, &mut definition, Some(element.into()))?;
            }
        } else {
            fields.push(&mut name, &mut definition, None)?;
            break;
        }
        next = element.next_sibling();
    }

    Ok((ty, fields.into_member_groups(None)))
}

fn get_methods(
    document: &kuchiki::NodeRef,
    parent: &doc::Fqn,
) -> anyhow::Result<(doc::ItemType, Vec<doc::MemberGroup>)> {
    let ty = doc::ItemType::Method;
    let mut groups: Vec<doc::MemberGroup> = Vec::new();

    // Rust < 1.45
    groups.append(&mut get_method_groups(
        document,
        parent,
        "methods".to_owned(),
        ty,
        &local_name!("h4"),
    )?);
    // Rust >= 1.45
    groups.append(&mut get_method_groups(
        document,
        parent,
        "implementations".to_owned(),
        ty,
        &local_name!("h4"),
    )?);

    let heading = select_first(document, "#deref-methods")?;
    if let Some(heading) = heading {
        let title = heading.as_node().text_contents();
        if let Some(impl_items) = heading.as_node().next_sibling() {
            let group = get_method_group(
                parent,
                Some(title),
                &impl_items,
                doc::ItemType::Method,
                &local_name!("h4"),
            )?;
            if let Some(group) = group {
                groups.push(group);
            }
        }
    }

    let heading = select_first(document, "#required-methods")?;
    if let Some(heading) = heading {
        if let Some(methods) = heading.as_node().next_sibling() {
            let title = "Required Methods".to_owned();
            let group = get_method_group(
                parent,
                Some(title),
                &methods,
                doc::ItemType::TyMethod,
                &local_name!("h3"),
            )?;
            if let Some(group) = group {
                groups.push(group);
            }
        }
    }

    let heading = select_first(document, "#provided-methods")?;
    if let Some(heading) = heading {
        if let Some(methods) = heading.as_node().next_sibling() {
            let title = "Provided Methods".to_owned();
            let group = get_method_group(
                parent,
                Some(title),
                &methods,
                doc::ItemType::TyMethod,
                &local_name!("h3"),
            )?;
            if let Some(group) = group {
                groups.push(group);
            }
        }
    }

    Ok((ty, groups))
}

fn get_assoc_types(
    document: &kuchiki::NodeRef,
    parent: &doc::Fqn,
) -> anyhow::Result<(doc::ItemType, Vec<doc::MemberGroup>)> {
    let ty = doc::ItemType::AssocType;
    let mut groups: Vec<doc::MemberGroup> = Vec::new();

    let heading = select_first(document, "#associated-types")?;
    if let Some(heading) = heading {
        if let Some(methods) = heading.as_node().next_sibling() {
            let group = get_method_group(
                parent,
                None,
                &methods,
                doc::ItemType::AssocType,
                &local_name!("h3"),
            )?;
            if let Some(group) = group {
                groups.push(group);
            }
        }
    }

    Ok((ty, groups))
}

fn get_method_groups(
    document: &kuchiki::NodeRef,
    parent: &doc::Fqn,
    heading_id: String,
    ty: doc::ItemType,
    subheading_type: &markup5ever::LocalName,
) -> anyhow::Result<Vec<doc::MemberGroup>> {
    let mut groups: Vec<doc::MemberGroup> = Vec::new();
    let heading = select_first(document, &format!("#{}", heading_id))?;
    let mut next = heading.as_ref().and_then(NodeRefExt::next_sibling_element);
    while let Some(subheading) = &next {
        if subheading.is_element(&local_name!("h3")) && subheading.has_class("impl") {
            if let Some(title_element) = subheading.first_child() {
                let title = title_element.text_contents();
                next = subheading.next_sibling();
                if let Some(impl_items) = &next {
                    if impl_items.is_element(&local_name!("div"))
                        && impl_items.has_class("impl-items")
                    {
                        let group = get_method_group(
                            parent,
                            Some(title),
                            &impl_items,
                            ty,
                            &subheading_type,
                        )?;
                        if let Some(group) = group {
                            groups.push(group);
                        }
                        next = impl_items.next_sibling();
                    }
                }
            } else {
                next = None;
            }
        } else {
            next = None;
        }
    }
    Ok(groups)
}

fn get_method_group(
    parent: &doc::Fqn,
    title: Option<String>,
    impl_items: &kuchiki::NodeRef,
    ty: doc::ItemType,
    heading_type: &markup5ever::LocalName,
) -> anyhow::Result<Option<doc::MemberGroup>> {
    let mut methods = MemberDocs::new(parent, ty);

    let mut name: Option<String> = None;
    let mut definition: Option<doc::Code> = None;
    for element in impl_items.children() {
        if element.is_element(heading_type) && element.has_class("method") {
            methods.push(&mut name, &mut definition, None)?;
            name = get_id_part(&element, 1);
            definition = it_select_first(element.children(), "code")?.map(From::from);
        } else if element.is_element(&local_name!("div")) && element.has_class("docblock") {
            methods.push(&mut name, &mut definition, Some(element.into()))?;
        }
    }

    Ok(methods.into_member_group(title))
}

fn get_variants(
    document: &kuchiki::NodeRef,
    parent: &doc::Fqn,
) -> anyhow::Result<(doc::ItemType, Vec<doc::MemberGroup>)> {
    let ty = doc::ItemType::Variant;
    let mut variants = MemberDocs::new(parent, ty);
    let heading = select_first(document, &format!("#{}", get_item_group_id(ty)))?;

    let mut next = heading.as_ref().and_then(NodeRefExt::next_sibling_element);
    let mut name: Option<String> = None;
    let mut definition: Option<doc::Code> = None;
    while let Some(element) = &next {
        if element.is_element(&local_name!("div")) {
            if element.has_class("variant") {
                variants.push(&mut name, &mut definition, None)?;
                name = get_id_part(element, 1);
                definition = Some(element.into());
            } else if element.has_class("docblock") {
                variants.push(&mut name, &mut definition, Some(element.into()))?;
            }

            next = element.next_sibling();
        } else {
            variants.push(&mut name, &mut definition, None)?;
            break;
        }
    }

    Ok((ty, variants.into_member_groups(None)))
}

fn get_implementations(
    document: &kuchiki::NodeRef,
    parent: &doc::Fqn,
) -> anyhow::Result<(doc::ItemType, Vec<doc::MemberGroup>)> {
    let mut groups: Vec<doc::MemberGroup> = Vec::new();

    let group_data = vec![
        // Rust < 1.45
        ("Trait Implementations", "implementations-list"),
        // Rust >= 1.45
        ("Trait Implementations", "trait-implementations-list"),
        (
            "Auto Trait Implementations",
            "synthetic-implementations-list",
        ),
        ("Blanket Implementations", "blanket-implementations-list"),
    ];

    for (title, id) in group_data {
        if let Some(group) = get_implementation_group(document, parent, title, id)? {
            groups.push(group);
        }
    }

    Ok((doc::ItemType::Impl, groups))
}

fn get_implementation_group(
    document: &kuchiki::NodeRef,
    parent: &doc::Fqn,
    title: &str,
    list_id: &str,
) -> anyhow::Result<Option<doc::MemberGroup>> {
    let ty = doc::ItemType::Impl;
    let mut impls = MemberDocs::new(parent, ty);
    let list_div = select_first(document, &format!("#{}", list_id))?;

    if let Some(list_div) = list_div {
        for item in list_div.as_node().children() {
            if item.is_element(&local_name!("h3")) && item.has_class("impl") {
                let code = item.first_child();
                let a = code
                    .as_ref()
                    .and_then(|n| select_first(n, "a").transpose())
                    .transpose()?;
                let mut name = a.map(|n| n.as_node().text_contents());
                let mut definition = code.map(From::from);
                impls.push(&mut name, &mut definition, None)?;
            }
        }
    }

    impls.sort();

    Ok(impls.into_member_group(Some(title.to_owned())))
}

fn get_members(
    document: &kuchiki::NodeRef,
    parent: &doc::Fqn,
    ty: doc::ItemType,
) -> anyhow::Result<Vec<doc::Doc>> {
    let mut members: Vec<doc::Doc> = Vec::new();
    if let Some(table) = select_first(document, &format!("#{} + table", get_item_group_id(ty)))? {
        let items = select(table.as_node(), "td:first-child > :first-child")?;
        for item in items {
            let item_name = item.as_node().text_contents();
            let docblock = item.as_node().parent().and_then(|n| n.next_sibling());

            let mut doc = doc::Doc::new(parent.child(&item_name), ty);
            doc.description = docblock.map(From::from);
            members.push(doc);
        }
    }
    Ok(members)
}

const MEMBER_TYPES: &[doc::ItemType] = &[
    doc::ItemType::StructField,
    doc::ItemType::Variant,
    doc::ItemType::AssocType,
    doc::ItemType::AssocConst,
    doc::ItemType::Method,
];

fn get_member(
    document: &kuchiki::NodeRef,
    name: &str,
) -> anyhow::Result<Option<kuchiki::NodeDataRef<kuchiki::ElementData>>> {
    let selectors: Vec<_> = MEMBER_TYPES
        .iter()
        .map(|ty| get_member_selector(*ty, name))
        .collect();
    select_first(document, &selectors.join(", "))
}

fn get_member_selector(ty: doc::ItemType, name: &str) -> String {
    format!("#{}\\.{}", get_item_id(ty), name)
}

struct MemberDocs<'a> {
    docs: Vec<doc::Doc>,
    parent: &'a doc::Fqn,
    ty: doc::ItemType,
}

impl<'a> MemberDocs<'a> {
    pub fn new(parent: &'a doc::Fqn, ty: doc::ItemType) -> Self {
        Self {
            docs: Vec::new(),
            parent,
            ty,
        }
    }

    pub fn sort(&mut self) {
        self.docs.sort_by(|d1, d2| {
            d1.name
                .cmp(&d2.name)
                .then_with(|| d1.definition.cmp(&d2.definition))
        })
    }

    pub fn push(
        &mut self,
        name: &mut Option<String>,
        definition: &mut Option<doc::Code>,
        description: Option<doc::Text>,
    ) -> anyhow::Result<()> {
        let name = name.take();
        let definition = definition.take();

        if let Some(name) = name {
            let mut doc = doc::Doc::new(self.parent.child(&name), self.ty);
            doc.definition = definition;
            doc.description = description;
            self.docs.push(doc);
        }
        Ok(())
    }

    pub fn into_member_group(self, title: Option<String>) -> Option<doc::MemberGroup> {
        if self.docs.is_empty() {
            None
        } else {
            let mut group = doc::MemberGroup::new(title);
            group.members = self.docs;
            Some(group)
        }
    }

    pub fn into_member_groups(self, title: Option<String>) -> Vec<doc::MemberGroup> {
        self.into_member_group(title).into_iter().collect()
    }
}

impl<'a> From<MemberDocs<'a>> for Vec<doc::Doc> {
    fn from(md: MemberDocs<'a>) -> Self {
        md.docs
    }
}

fn get_item_id(ty: doc::ItemType) -> &'static str {
    use doc::ItemType;

    match ty {
        ItemType::Module => "mod",
        ItemType::ExternCrate => "externcrate",
        ItemType::Import => "import",
        ItemType::Struct => "struct",
        ItemType::Union => "union",
        ItemType::Enum => "enum",
        ItemType::Function => "fn",
        ItemType::Typedef => "type",
        ItemType::Static => "static",
        ItemType::Trait => "trait",
        ItemType::Impl => "impl",
        ItemType::TyMethod => "tymethod",
        ItemType::Method => "method",
        ItemType::StructField => "structfield",
        ItemType::Variant => "variant",
        ItemType::Macro => "macro",
        ItemType::Primitive => "primitive",
        ItemType::AssocType => "associatedtype",
        ItemType::Constant => "constant",
        ItemType::AssocConst => "associatedconstant",
        ItemType::ForeignType => "foreigntype",
        ItemType::Keyword => "keyword",
        ItemType::OpaqueTy => "opaque",
        ItemType::ProcAttribute => "attr",
        ItemType::ProcDerive => "derive",
        ItemType::TraitAlias => "traitalias",
    }
}

fn get_item_group_id(ty: doc::ItemType) -> &'static str {
    use doc::ItemType;

    match ty {
        ItemType::Module => "modules",
        ItemType::ExternCrate => "extern-crates",
        ItemType::Import => "imports",
        ItemType::Struct => "structs",
        ItemType::Enum => "enums",
        ItemType::Function => "functions",
        ItemType::Typedef => "types",
        ItemType::Static => "statics",
        ItemType::Trait => "traits",
        ItemType::Impl => "impls",
        ItemType::TyMethod => "required-methods",
        ItemType::Method => "methods",
        ItemType::StructField => "fields",
        ItemType::Variant => "variants",
        ItemType::Macro => "macros",
        ItemType::Primitive => "primitives",
        ItemType::AssocType => "associated-types",
        ItemType::Constant => "constants",
        ItemType::AssocConst => "associated-consts",
        ItemType::Union => "unions",
        ItemType::ForeignType => "foreign-types",
        ItemType::Keyword => "keywords",
        ItemType::OpaqueTy => "opaque-types",
        ItemType::ProcAttribute => "proc-attributes",
        ItemType::ProcDerive => "proc-derives",
        ItemType::TraitAlias => "trait-aliases",
    }
}

#[cfg(test)]
mod tests {
    use crate::doc;
    use crate::test_utils::with_rustdoc;

    #[test]
    fn test_find_item() {
        with_rustdoc("*", |_, path| {
            let path = path.join("kuchiki").join("all.html");
            let parser = super::Parser::from_file(path).unwrap();

            assert_eq!(None, parser.find_item("foobar").unwrap());
            assert_eq!(
                Some("struct.NodeRef.html".to_owned()),
                parser.find_item("NodeRef").unwrap()
            );
        });
    }

    #[test]
    fn test_parse_item_doc() {
        with_rustdoc("*", |_, path| {
            let path = path.join("kuchiki").join("struct.NodeRef.html");
            let name: doc::Fqn = "kuchiki::NodeRef".to_owned().into();
            let doc = super::Parser::from_file(path)
                .unwrap()
                .parse_item_doc(&name, doc::ItemType::Struct)
                .unwrap();

            assert_eq!(name, doc.name);
            assert_eq!(doc::ItemType::Struct, doc.ty);
            assert!(doc.definition.is_some());
            assert!(doc.description.is_some());
        });
    }

    #[test]
    fn test_find_member() {
        with_rustdoc("*", |_, path| {
            let path = path.join("kuchiki").join("struct.NodeDataRef.html");
            let name: doc::Fqn = "kuchiki::NodeDataRef::as_node".to_owned().into();
            let ty = super::Parser::from_file(path)
                .unwrap()
                .find_member(&name)
                .unwrap();
            assert_eq!(Some(doc::ItemType::Method), ty);
        });
    }

    #[test]
    fn test_parse_member_doc() {
        with_rustdoc("*", |_, path| {
            let path = path.join("kuchiki").join("struct.NodeDataRef.html");
            let name: doc::Fqn = "kuchiki::NodeDataRef::as_node".to_owned().into();
            let doc = super::Parser::from_file(path)
                .unwrap()
                .parse_member_doc(&name, doc::ItemType::Method)
                .unwrap();

            assert_eq!(name, doc.name);
            assert_eq!(doc::ItemType::Method, doc.ty);
            let definition = doc.definition.unwrap();
            assert_eq!(
                doc::Code::new("pub fn as_node(&self) -> &NodeRef".to_owned()),
                definition
            );
            assert!(doc.description.is_some());
        });
    }
}