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
impl Parsed
Sourcepub fn to_model(&self) -> Docstring
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
impl Parsed
Sourcepub fn replace(
&self,
pattern: &Pattern,
template: &str,
) -> Result<String, RewriteError>
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.
Sourcepub fn replace_in(
&self,
pattern: &Pattern,
anchor: &SyntaxNode,
template: &str,
) -> Result<String, RewriteError>
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
impl Parsed
Sourcepub fn new(source: String, root: SyntaxNode, style: Style) -> Self
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
sourceand 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.
Sourcepub fn source(&self) -> &str
pub fn source(&self) -> &str
The full source text.
Examples found in repository?
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
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}Sourcepub fn root(&self) -> &SyntaxNode
pub fn root(&self) -> &SyntaxNode
The root node of the syntax tree.
Sourcepub fn style(&self) -> Style
pub fn style(&self) -> Style
The style this docstring was parsed as.
Examples found in repository?
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}Sourcepub fn line_col(&self, offset: TextSize) -> LineColumn
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.
Sourcepub fn line_indent(&self, offset: TextSize) -> &str
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");Sourcepub fn pretty_print(&self) -> String
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?
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
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}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}