Skip to main content

Parsed

Struct Parsed 

Source
pub struct Parsed { /* private fields */ }
Expand description

The result of parsing a docstring.

Owns the source text and the root SyntaxNode, and records the Style the docstring was parsed as (the root node kind is the style-neutral SyntaxKind::DOCUMENT).

Implementations§

Source§

impl Parsed

Source

pub fn edit(&self) -> Edits<'_>

Start an empty edit list anchored on this parse result.

See the edit module docs for the model and an end-to-end example.

Source§

impl Parsed

Source

pub fn to_model(&self) -> Docstring

Convert to the normalized model IR (Docstring).

This is the third read lens, next to the Document view and the raw CST: it drops byte positions and normalizes the text, which is what makes it the input to emit. The style is dispatched on internally — a Google and a NumPy docstring with the same content produce the same model.

use pydocstring::parse::parse;

let model = parse("Summary.\n\nArgs:\n    x (int): The value.\n").to_model();
assert_eq!(model.summary.as_deref(), Some("Summary."));
Source§

impl Parsed

Source

pub fn replace( &self, pattern: &Pattern, template: &str, ) -> Result<String, RewriteError>

Replace every match of pattern in this document with template rendered against that match’s captures, returning the new source.

Matches are found globally with Pattern::matches (all readings, document order, non-overlapping). Style-strict: a pattern of a different style, or one that matches nothing, returns the source unchanged. See the module docs for the template and re-indentation semantics.

§Errors

RewriteError::UnknownMetavar if the template names a metavariable a match’s reading did not bind.

Source

pub fn replace_in( &self, pattern: &Pattern, anchor: &SyntaxNode, template: &str, ) -> Result<String, RewriteError>

Like replace, but scoped to anchor’s subtree via Pattern::matches_in: the anchor’s grammar selects the readings, so the same pattern rewrites $TYPE-shaped entries under a Raises: anchor and $NAME-shaped ones under an Args: anchor. An anchor that is not a node of this document’s tree matches nothing (the source is returned unchanged).

Source§

impl Parsed

Source

pub fn new(source: String, root: SyntaxNode, style: Style) -> Self

Creates a new Parsed from source text, root node, and source style.

§Invariants

A Parsed is expected to originate from one of this crate’s parsers (parse or a per-style parse_* function). Constructing one by hand is possible but the tree must then uphold the laws the parsers guarantee and downstream consumers rely on:

  • every element’s range lies within source and within its parent’s range, and siblings appear in source order (containment/ordering);
  • a node’s children plus trivia tokens exactly cover the node’s range (coverage — pinned corpus-wide in tests/trivia.rs);
  • token text is a slice of source (no synthesized text, see the source-backed decision on issue #42);
  • zero-length elements are missing placeholders and nothing else.

A hand-built tree that violates these laws produces unspecified (but memory-safe) results from the typed views, the visitor, and to_model.

Source

pub fn source(&self) -> &str

The full source text.

Examples found in repository?
examples/parse_google.rs (line 35)
7fn main() {
8    let docstring = r#"
9Calculate the area of a rectangle.
10
11This function takes the width and height of a rectangle
12and returns its area.
13
14Args:
15    width (float): The width of the rectangle.
16    height (float): The height of the rectangle.
17
18Returns:
19    float: The area of the rectangle.
20
21Raises:
22    ValueError: If width or height is negative.
23"#;
24
25    let parsed = parse_google(docstring);
26
27    println!("╔══════════════════════════════════════════════════╗");
28    println!("║          Google-style Docstring Example          ║");
29    println!("╚══════════════════════════════════════════════════╝");
30
31    println!();
32
33    // Display: raw source text
34    println!("── raw text ────────────────────────────────────────");
35    println!("{}", parsed.source());
36
37    println!();
38
39    // pretty_print: structured AST
40    println!("── parsed AST ──────────────────────────────────────");
41    print!("{}", parsed.pretty_print());
42}
More examples
Hide additional examples
examples/parse_numpy.rs (line 49)
8fn main() {
9    let docstring = r#"
10Calculate the area of a rectangle.
11
12This function takes the width and height of a rectangle
13and returns its area.
14
15Parameters
16----------
17width : float
18    The width of the rectangle.
19height : float
20    The height of the rectangle.
21
22Returns
23-------
24float
25    The area of the rectangle.
26
27Raises
28------
29ValueError
30    If width or height is negative.
31
32Examples
33--------
34>>> calculate_area(5.0, 3.0)
3515.0
36"#;
37
38    let parsed = parse_numpy(docstring);
39    let doc = Document::new(&parsed);
40
41    println!("╔══════════════════════════════════════════════════╗");
42    println!("║          NumPy-style Docstring Example           ║");
43    println!("╚══════════════════════════════════════════════════╝");
44
45    println!();
46
47    // Display: raw source text
48    println!("── raw text ────────────────────────────────────────");
49    println!("{}", doc.syntax().range().source_text(parsed.source()));
50
51    println!();
52
53    // pretty_print: structured AST
54    println!("── parsed AST ──────────────────────────────────────");
55    print!("{}", parsed.pretty_print());
56}
Source

pub fn root(&self) -> &SyntaxNode

The root node of the syntax tree.

Source

pub fn style(&self) -> Style

The style this docstring was parsed as.

Examples found in repository?
examples/parse_auto.rs (line 17)
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}
Source

pub fn line_col(&self, offset: TextSize) -> LineColumn

Convert a byte offset to a LineColumn position.

lineno is 1-based; col is the 0-based byte column within the line.

col is a byte column, so it composes with every other offset in this API (offset - col is the start of the line). It is not a display width and not an indent: reconstructing indentation as " ".repeat(col) over-indents a line containing a multi-byte character and turns a tab into a space. Use line_indent for that.

Source

pub fn line_indent(&self, offset: TextSize) -> &str

The leading whitespace of the line that offset falls on.

This is the indent an edit anchored there has to match, handed back as the literal bytes to copy — which is the only form that survives both a tab-indented docstring and a line whose text is not ASCII. A column cannot express either: " ".repeat(col) replaces a tab with a space, and counts a é twice.

use pydocstring::parse::parse;
use pydocstring::text::TextSize;

let parsed = parse("Summary.\n\nArgs:\n\tx (int): The value.\n");
let x = parsed.source().find("x (int)").unwrap();
assert_eq!(parsed.line_indent(TextSize::new(x as u32)), "\t");
Source

pub fn pretty_print(&self) -> String

Produce a Biome-style pretty-printed representation of the tree.

This is a debugging aid: the exact output format is not stable and may change in any release — do not parse or snapshot it in downstream code.

Examples found in repository?
examples/parse_auto.rs (line 29)
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}
More examples
Hide additional examples
examples/parse_google.rs (line 41)
7fn main() {
8    let docstring = r#"
9Calculate the area of a rectangle.
10
11This function takes the width and height of a rectangle
12and returns its area.
13
14Args:
15    width (float): The width of the rectangle.
16    height (float): The height of the rectangle.
17
18Returns:
19    float: The area of the rectangle.
20
21Raises:
22    ValueError: If width or height is negative.
23"#;
24
25    let parsed = parse_google(docstring);
26
27    println!("╔══════════════════════════════════════════════════╗");
28    println!("║          Google-style Docstring Example          ║");
29    println!("╚══════════════════════════════════════════════════╝");
30
31    println!();
32
33    // Display: raw source text
34    println!("── raw text ────────────────────────────────────────");
35    println!("{}", parsed.source());
36
37    println!();
38
39    // pretty_print: structured AST
40    println!("── parsed AST ──────────────────────────────────────");
41    print!("{}", parsed.pretty_print());
42}
examples/parse_numpy.rs (line 55)
8fn main() {
9    let docstring = r#"
10Calculate the area of a rectangle.
11
12This function takes the width and height of a rectangle
13and returns its area.
14
15Parameters
16----------
17width : float
18    The width of the rectangle.
19height : float
20    The height of the rectangle.
21
22Returns
23-------
24float
25    The area of the rectangle.
26
27Raises
28------
29ValueError
30    If width or height is negative.
31
32Examples
33--------
34>>> calculate_area(5.0, 3.0)
3515.0
36"#;
37
38    let parsed = parse_numpy(docstring);
39    let doc = Document::new(&parsed);
40
41    println!("╔══════════════════════════════════════════════════╗");
42    println!("║          NumPy-style Docstring Example           ║");
43    println!("╚══════════════════════════════════════════════════╝");
44
45    println!();
46
47    // Display: raw source text
48    println!("── raw text ────────────────────────────────────────");
49    println!("{}", doc.syntax().range().source_text(parsed.source()));
50
51    println!();
52
53    // pretty_print: structured AST
54    println!("── parsed AST ──────────────────────────────────────");
55    print!("{}", parsed.pretty_print());
56}

Trait Implementations§

Source§

impl Clone for Parsed

Source§

fn clone(&self) -> Parsed

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Parsed

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Parsed

Source§

impl PartialEq for Parsed

Source§

fn eq(&self, other: &Parsed) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Parsed

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.