Skip to main content

parse_auto/
parse_auto.rs

1//! Example: Auto-detecting docstring style with `parse()`
2//!
3//! Demonstrates the unified `parse()` entry point, which detects the style
4//! automatically and returns a `Parsed` result. The root node kind is always
5//! the style-neutral `DOCUMENT`; `Parsed::style()` reports the detected style:
6//!
7//! - `Style::Google` — Google style (section headers ending with `:`)
8//! - `Style::NumPy`  — NumPy style (section headers with `---` underlines)
9//! - `Style::Plain`  — no recognised section markers (summary/extended
10//!   summary only, or unrecognised styles such as Sphinx)
11
12use pydocstring::parse::Style;
13use pydocstring::parse::parse;
14
15fn show(label: &str, input: &str) {
16    let parsed = parse(input);
17    let style_label = match parsed.style() {
18        Style::Google => "Google",
19        Style::NumPy => "NumPy",
20        Style::Plain => "Plain",
21        // `Style` is #[non_exhaustive]: future styles land here.
22        _ => "Unknown",
23    };
24
25    println!(
26        "── {} → {} ──────────────────────────────────────────",
27        label, style_label
28    );
29    print!("{}", parsed.pretty_print());
30    println!();
31}
32
33fn main() {
34    println!("╔══════════════════════════════════════════════════╗");
35    println!("║        Auto-detecting Docstring Style            ║");
36    println!("╚══════════════════════════════════════════════════╝");
37    println!();
38
39    show(
40        "Google",
41        r#"
42Calculate the area of a rectangle.
43
44Args:
45    width (float): The width of the rectangle.
46    height (float): The height of the rectangle.
47
48Returns:
49    float: The area of the rectangle.
50"#,
51    );
52
53    show(
54        "NumPy",
55        r#"
56Calculate the area of a rectangle.
57
58Parameters
59----------
60width : float
61    The width of the rectangle.
62height : float
63    The height of the rectangle.
64
65Returns
66-------
67float
68    The area of the rectangle.
69"#,
70    );
71
72    show("Plain (summary only)", "Calculate the area of a rectangle.");
73
74    show(
75        "Plain (summary + extended)",
76        r#"
77Calculate the area of a rectangle.
78
79Takes width and height as arguments and returns their product.
80Negative values will raise a ValueError.
81"#,
82    );
83}