groxide 0.1.0

Query Rust crate documentation from the terminal
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
use std::fmt::Write;

use serde::Serialize;

use crate::types::{DisplayItem, GroupedItems, IndexItem, TraitImplInfo};

/// JSON representation of a documented item (doc view).
#[derive(Debug, Serialize)]
pub(crate) struct JsonDocItem {
    /// Full item path.
    pub(crate) path: String,
    /// Item kind short name.
    pub(crate) kind: String,
    /// Rendered signature (empty string for modules).
    pub(crate) signature: String,
    /// Full doc comment (raw markdown, NOT stripped).
    pub(crate) doc: String,
    /// Feature gate name, or null.
    pub(crate) feature_gate: Option<String>,
    /// Original source path for re-exported items.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) reexported_from: Option<String>,
    /// Methods (for Type and Trait items).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) methods: Option<Vec<JsonMethod>>,
    /// Trait implementation paths (for Type items).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) trait_impls: Option<Vec<String>>,
    /// Enum variants (for Enum items).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) variants: Option<Vec<JsonVariant>>,
}

/// JSON representation of a method.
#[derive(Debug, Serialize)]
pub(crate) struct JsonMethod {
    /// Simple method name.
    pub(crate) name: String,
    /// Rendered method signature.
    pub(crate) signature: String,
    /// First sentence of docs.
    pub(crate) summary: String,
    /// Whether the method has a body (provided). Only on trait methods.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) has_body: Option<bool>,
}

/// JSON representation of an enum variant.
#[derive(Debug, Serialize)]
pub(crate) struct JsonVariant {
    /// Simple variant name.
    pub(crate) name: String,
    /// Rendered variant signature.
    pub(crate) signature: String,
    /// First sentence of docs.
    pub(crate) summary: String,
}

/// JSON representation of a list item (used in `--json --list` and container children).
#[derive(Debug, Serialize)]
pub(crate) struct JsonListItem {
    /// Full item path.
    pub(crate) path: String,
    /// Item kind short name.
    pub(crate) kind: String,
    /// Rendered signature.
    pub(crate) signature: String,
    /// First sentence of docs.
    pub(crate) summary: String,
    /// Original source path for re-exported items.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) reexported_from: Option<String>,
}

/// Renders a `DisplayItem` as JSON doc view (`--json`).
///
/// For modules/crate roots, produces JSON Lines: the item itself + one line per child.
/// For other items, produces a single JSON object.
pub(crate) fn render_json(display: &DisplayItem<'_>) -> String {
    match display {
        DisplayItem::Crate { item, children } | DisplayItem::Module { item, children } => {
            render_json_container(item, children)
        }
        DisplayItem::Type {
            item,
            methods,
            variants,
            trait_impls,
        } => render_json_type(item, methods, variants, trait_impls),
        DisplayItem::Trait {
            item,
            required_methods,
            provided_methods,
        } => render_json_trait(item, required_methods, provided_methods),
        DisplayItem::Leaf { item } => render_json_leaf(item),
    }
}

/// Renders ambiguous matches as JSON Lines.
///
/// Each line is a `JsonListItem` with path, kind, signature, summary.
pub(crate) fn render_json_ambiguous(items: &[&IndexItem]) -> String {
    let mut out = String::new();
    for item in items {
        let list_item = JsonListItem {
            path: item.path.clone(),
            kind: item.kind.short_name().to_string(),
            signature: item.signature.clone(),
            summary: item.summary.clone(),
            reexported_from: item.reexport_source.clone(),
        };
        let json = serde_json::to_string(&list_item).expect("invariant: JsonListItem serializes");
        let _ = writeln!(out, "{json}");
    }
    trim_trailing_newlines(&mut out);
    out
}

/// Renders a module or crate root as JSON Lines.
fn render_json_container(item: &IndexItem, children: &GroupedItems<'_>) -> String {
    let mut out = String::new();

    // First line: the container item itself
    let doc_item = JsonDocItem {
        path: item.path.clone(),
        kind: item.kind.short_name().to_string(),
        signature: item.signature.clone(),
        doc: item.docs.clone(),
        feature_gate: item.feature_gate.clone(),
        reexported_from: item.reexport_source.clone(),
        methods: None,
        trait_impls: None,
        variants: None,
    };
    let json = serde_json::to_string(&doc_item).expect("invariant: JsonDocItem serializes");
    let _ = writeln!(out, "{json}");

    // Subsequent lines: children as JsonListItem
    for group_items in children.values() {
        for child in group_items {
            let list_item = JsonListItem {
                path: child.path.clone(),
                kind: child.kind.short_name().to_string(),
                signature: child.signature.clone(),
                summary: child.summary.clone(),
                reexported_from: child.reexport_source.clone(),
            };
            let json =
                serde_json::to_string(&list_item).expect("invariant: JsonListItem serializes");
            let _ = writeln!(out, "{json}");
        }
    }

    trim_trailing_newlines(&mut out);
    out
}

/// Renders a type (struct/enum/union) as a single JSON object.
fn render_json_type(
    item: &IndexItem,
    methods: &[&IndexItem],
    variants: &[&IndexItem],
    trait_impls: &[TraitImplInfo],
) -> String {
    let json_methods: Vec<JsonMethod> = methods
        .iter()
        .map(|m| JsonMethod {
            name: m.name.clone(),
            signature: m.signature.clone(),
            summary: m.summary.clone(),
            has_body: None,
        })
        .collect();

    let json_variants: Vec<JsonVariant> = variants
        .iter()
        .map(|v| JsonVariant {
            name: v.name.clone(),
            signature: v.signature.clone(),
            summary: v.summary.clone(),
        })
        .collect();

    let json_trait_impls: Vec<String> =
        trait_impls.iter().map(|ti| ti.trait_path.clone()).collect();

    let doc_item = JsonDocItem {
        path: item.path.clone(),
        kind: item.kind.short_name().to_string(),
        signature: item.signature.clone(),
        doc: item.docs.clone(),
        feature_gate: item.feature_gate.clone(),
        reexported_from: item.reexport_source.clone(),
        methods: if json_methods.is_empty() {
            None
        } else {
            Some(json_methods)
        },
        trait_impls: if json_trait_impls.is_empty() {
            None
        } else {
            Some(json_trait_impls)
        },
        variants: if json_variants.is_empty() {
            None
        } else {
            Some(json_variants)
        },
    };

    serde_json::to_string(&doc_item).expect("invariant: JsonDocItem serializes")
}

/// Renders a trait as a single JSON object.
fn render_json_trait(
    item: &IndexItem,
    required_methods: &[&IndexItem],
    provided_methods: &[&IndexItem],
) -> String {
    let mut json_methods: Vec<JsonMethod> = Vec::new();

    for m in required_methods {
        json_methods.push(JsonMethod {
            name: m.name.clone(),
            signature: m.signature.clone(),
            summary: m.summary.clone(),
            has_body: Some(false),
        });
    }
    for m in provided_methods {
        json_methods.push(JsonMethod {
            name: m.name.clone(),
            signature: m.signature.clone(),
            summary: m.summary.clone(),
            has_body: Some(true),
        });
    }

    let doc_item = JsonDocItem {
        path: item.path.clone(),
        kind: item.kind.short_name().to_string(),
        signature: item.signature.clone(),
        doc: item.docs.clone(),
        feature_gate: item.feature_gate.clone(),
        reexported_from: item.reexport_source.clone(),
        methods: if json_methods.is_empty() {
            None
        } else {
            Some(json_methods)
        },
        trait_impls: None,
        variants: None,
    };

    serde_json::to_string(&doc_item).expect("invariant: JsonDocItem serializes")
}

/// Renders a leaf item as a single JSON object.
fn render_json_leaf(item: &IndexItem) -> String {
    let doc_item = JsonDocItem {
        path: item.path.clone(),
        kind: item.kind.short_name().to_string(),
        signature: item.signature.clone(),
        doc: item.docs.clone(),
        feature_gate: item.feature_gate.clone(),
        reexported_from: item.reexport_source.clone(),
        methods: None,
        trait_impls: None,
        variants: None,
    };

    serde_json::to_string(&doc_item).expect("invariant: JsonDocItem serializes")
}

/// Renders a recursive listing as JSON Lines.
///
/// Each item becomes one `JsonListItem` per line. Flat list, no grouping.
pub(crate) fn render_json_recursive(items: &[&IndexItem]) -> String {
    let mut out = String::new();
    for item in items {
        let list_item = JsonListItem {
            path: item.path.clone(),
            kind: item.kind.short_name().to_string(),
            signature: item.signature.clone(),
            summary: item.summary.clone(),
            reexported_from: item.reexport_source.clone(),
        };
        let json = serde_json::to_string(&list_item).expect("invariant: JsonListItem serializes");
        let _ = writeln!(out, "{json}");
    }
    trim_trailing_newlines(&mut out);
    out
}

/// Removes trailing newlines from output.
fn trim_trailing_newlines(s: &mut String) {
    while s.ends_with('\n') {
        s.pop();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render::build_display_item;
    use crate::test_utils::make_item_full;
    use crate::types::{ChildRef, DocIndex, ItemKind, TraitImplInfo};

    // ---- JSON doc view for struct ----

    #[test]
    fn render_json_struct() {
        let mut index = DocIndex::new("mycrate".to_string(), "0.1.0".to_string());

        let m1 = make_item_full(
            "lock",
            "mycrate::Mutex::lock",
            ItemKind::Function,
            "pub fn lock(&self) -> MutexGuard<'_, T>",
            "Locks this mutex.",
            "Locks this mutex.",
        );
        let m2 = make_item_full(
            "new",
            "mycrate::Mutex::new",
            ItemKind::Function,
            "pub fn new(t: T) -> Self",
            "Creates a new lock.",
            "Creates a new lock.",
        );
        index.add_item(m1);
        index.add_item(m2);

        let mut struct_item = make_item_full(
            "Mutex",
            "mycrate::Mutex",
            ItemKind::Struct,
            "pub struct Mutex<T: ?Sized>",
            "An asynchronous Mutex-like type.",
            "An asynchronous Mutex-like type.",
        );
        struct_item.children = vec![
            ChildRef {
                index: 0,
                kind: ItemKind::Function,
                name: "lock".to_string(),
            },
            ChildRef {
                index: 1,
                kind: ItemKind::Function,
                name: "new".to_string(),
            },
        ];
        index.add_item(struct_item);

        index.trait_impls.insert(
            2,
            vec![
                TraitImplInfo {
                    trait_path: "Debug".to_string(),
                    is_synthetic: false,
                },
                TraitImplInfo {
                    trait_path: "Send".to_string(),
                    is_synthetic: true,
                },
            ],
        );

        let di = build_display_item(&index, 2, false, None);
        let output = render_json(&di);

        // Parse and verify it's valid JSON
        let parsed: serde_json::Value =
            serde_json::from_str(&output).expect("should be valid JSON");
        assert_eq!(parsed["path"], "mycrate::Mutex");
        assert_eq!(parsed["kind"], "struct");
        assert_eq!(parsed["signature"], "pub struct Mutex<T: ?Sized>");
        assert!(parsed["methods"].is_array());
        assert_eq!(parsed["methods"].as_array().unwrap().len(), 2);
        assert!(parsed["trait_impls"].is_array());
        assert_eq!(parsed["trait_impls"].as_array().unwrap().len(), 2);
        assert!(parsed["variants"].is_null() || parsed.get("variants").is_none());

        insta::assert_snapshot!(output);
    }

    // ---- JSON doc view for trait ----

    #[test]
    fn render_json_trait_view() {
        let mut index = DocIndex::new("mycrate".to_string(), "0.1.0".to_string());

        let mut req = make_item_full(
            "next",
            "mycrate::Iterator::next",
            ItemKind::Function,
            "fn next(&mut self) -> Option<Self::Item>",
            "Advances the iterator.",
            "Advances the iterator.",
        );
        req.has_body = false;

        let mut prov = make_item_full(
            "count",
            "mycrate::Iterator::count",
            ItemKind::Function,
            "fn count(self) -> usize",
            "Consumes the iterator.",
            "Consumes the iterator.",
        );
        prov.has_body = true;

        index.add_item(req);
        index.add_item(prov);

        let mut trait_item = make_item_full(
            "Iterator",
            "mycrate::Iterator",
            ItemKind::Trait,
            "pub trait Iterator",
            "An interface for dealing with iterators.",
            "An interface for dealing with iterators.",
        );
        trait_item.children = vec![
            ChildRef {
                index: 0,
                kind: ItemKind::Function,
                name: "next".to_string(),
            },
            ChildRef {
                index: 1,
                kind: ItemKind::Function,
                name: "count".to_string(),
            },
        ];
        index.add_item(trait_item);

        let di = build_display_item(&index, 2, false, None);
        let output = render_json(&di);

        let parsed: serde_json::Value =
            serde_json::from_str(&output).expect("should be valid JSON");
        assert_eq!(parsed["kind"], "trait");
        let methods = parsed["methods"].as_array().unwrap();
        assert_eq!(methods.len(), 2);
        // Required method has has_body: false
        assert_eq!(methods[0]["has_body"], false);
        // Provided method has has_body: true
        assert_eq!(methods[1]["has_body"], true);

        insta::assert_snapshot!(output);
    }

    // ---- JSON doc view for crate root (with top_level_items) ----

    #[test]
    fn render_json_crate_root_includes_top_level_items() {
        let mut index = DocIndex::new("mycrate".to_string(), "0.1.0".to_string());

        let struct_item = make_item_full(
            "Widget",
            "mycrate::Widget",
            ItemKind::Struct,
            "pub struct Widget",
            "A widget.",
            "A widget.",
        );
        let mod_item = make_item_full(
            "utils",
            "mycrate::utils",
            ItemKind::Module,
            "",
            "Utility helpers.",
            "Utility helpers.",
        );
        let fn_item = make_item_full(
            "process",
            "mycrate::process",
            ItemKind::Function,
            "pub fn process() -> u32",
            "Processes data.",
            "Processes data.",
        );

        index.add_item(struct_item);
        index.add_item(mod_item);
        index.add_item(fn_item);

        let mut crate_item = make_item_full(
            "mycrate",
            "mycrate",
            ItemKind::Module,
            "",
            "A test crate.",
            "A test crate.",
        );
        crate_item.children = vec![
            ChildRef {
                index: 0,
                kind: ItemKind::Struct,
                name: "Widget".to_string(),
            },
            ChildRef {
                index: 1,
                kind: ItemKind::Module,
                name: "utils".to_string(),
            },
            ChildRef {
                index: 2,
                kind: ItemKind::Function,
                name: "process".to_string(),
            },
        ];
        index.add_item(crate_item);

        let di = build_display_item(&index, 3, false, None);
        let output = render_json(&di);

        // Should be JSON Lines
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines.len(), 4); // 1 crate + 3 children

        // First line is the crate itself
        let first: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
        assert_eq!(first["path"], "mycrate");
        assert_eq!(first["kind"], "mod");
        assert!(first.get("doc").is_some()); // Has full doc field

        // Subsequent lines are children with summary
        let second: serde_json::Value = serde_json::from_str(lines[1]).unwrap();
        assert!(second.get("summary").is_some());
        assert!(second.get("doc").is_none()); // No doc field on list items

        insta::assert_snapshot!(output);
    }

    // ---- JSON ambiguous output (array as JSON Lines) ----

    #[test]
    fn render_json_ambiguous_output() {
        let item1 = make_item_full(
            "Error",
            "mycrate::de::Error",
            ItemKind::Trait,
            "pub trait Error: Sized",
            "When deserialization encounters an error.",
            "When deserialization encounters an error.",
        );
        let item2 = make_item_full(
            "Error",
            "mycrate::ser::Error",
            ItemKind::Trait,
            "pub trait Error: Sized",
            "When serialization encounters an error.",
            "When serialization encounters an error.",
        );

        let items: Vec<&IndexItem> = vec![&item1, &item2];
        let output = render_json_ambiguous(&items);

        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines.len(), 2);

        let first: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
        assert_eq!(first["path"], "mycrate::de::Error");
        assert_eq!(first["kind"], "trait");

        let second: serde_json::Value = serde_json::from_str(lines[1]).unwrap();
        assert_eq!(second["path"], "mycrate::ser::Error");

        insta::assert_snapshot!(output);
    }

    // ---- JSON reexported_from field ----

    #[test]
    fn render_json_leaf_includes_reexported_from() {
        let mut item = make_item_full(
            "Helper",
            "mycrate::Helper",
            ItemKind::Struct,
            "pub struct Helper",
            "A helper struct.",
            "A helper struct.",
        );
        item.reexport_source = Some("mycrate::inner::Helper".to_string());

        let di = DisplayItem::Leaf { item: &item };
        let output = render_json(&di);

        let parsed: serde_json::Value =
            serde_json::from_str(&output).expect("should be valid JSON");
        assert_eq!(parsed["reexported_from"], "mycrate::inner::Helper");

        insta::assert_snapshot!(output);
    }

    #[test]
    fn render_json_leaf_omits_reexported_from_when_none() {
        let item = make_item_full(
            "Widget",
            "mycrate::Widget",
            ItemKind::Struct,
            "pub struct Widget",
            "A widget.",
            "A widget.",
        );

        let di = DisplayItem::Leaf { item: &item };
        let output = render_json(&di);

        let parsed: serde_json::Value =
            serde_json::from_str(&output).expect("should be valid JSON");
        assert!(
            parsed.get("reexported_from").is_none(),
            "reexported_from should be omitted when None"
        );
    }
}