MCPcopy Create free account
hub / github.com/astral-sh/ruff / attribute_docstring

Function attribute_docstring

crates/ty_python_core/src/definition.rs:237–264  ·  view source on GitHub ↗

Extract a docstring from an attribute. This is a non-standardized but popular-and-supported-by-sphinx kind of docstring where you just place the docstring underneath an assignment to an attribute and that counts as docs. This is annoying to extract because we have a reference to (part of) an assignment statement and we need to find the statement *after it*, which is easy to say but not something

(
    module: &'a ParsedModuleRef,
    assign_lvalue: &Expr,
)

Source from the content-addressed store, hash-verified

235/// and we need to find the statement *after it*, which is easy to say but not something the
236/// AST wants to encourage.
237fn attribute_docstring<'a>(
238 module: &'a ParsedModuleRef,
239 assign_lvalue: &Expr,
240) -> Option<&'a ast::ExprStringLiteral> {
241 // Find all the ancestors of the assign lvalue
242 let covering_node = covering_node(module.syntax().into(), assign_lvalue.range());
243 // The assignment is the closest parent statement
244 let assign = covering_node.find_first(AnyNodeRef::is_statement).ok()?;
245 let parent = assign.parent()?;
246 let assign_node = assign.node();
247
248 // The docs must be the next statement
249 let parent_body = suite(assign_node, parent)?;
250 let next_stmt = parent_body.next_sibling()?;
251
252 // Require the docstring to be a standalone expression.
253 let ast::Stmt::Expr(ast::StmtExpr {
254 value,
255 range: _,
256 node_index: _,
257 }) = next_stmt
258 else {
259 return None;
260 };
261
262 // Only match string literals.
263 value.as_string_literal_expr()
264}
265
266/// One or more [`Definition`]s.
267#[derive(Debug, Default, PartialEq, Eq, get_size2::GetSize)]

Callers 1

docstringMethod · 0.85

Calls 10

covering_nodeFunction · 0.85
syntaxMethod · 0.80
find_firstMethod · 0.80
next_siblingMethod · 0.80
suiteFunction · 0.50
rangeMethod · 0.45
okMethod · 0.45
parentMethod · 0.45
nodeMethod · 0.45

Tested by

no test coverage detected