[ty] Share parameter layouts for stub bodies with docstrings (#30984)

## Summary

Single-threaded checks used 0.38% fewer instructions on discord.py,
0.86% fewer on Black, and 0.90% fewer on FastAPI. On discord.py, we
reused an existing parameter layout 2,841 more times, mostly in stubs.
We didn't see a clear change in elapsed time.

We share the binding and declaration tables for functions whose bodies
contain only `pass` or `...`. A leading docstring prevents us from
sharing those tables, even though it doesn't introduce any bindings.

```python
def send(message: str) -> None:
    """Send a message to the channel."""
    ...
```

We now look past the docstring when deciding whether to share a layout,
including when it’s the only statement in the body. We still visit the
docstring and record its scope and reachability. Each parameter remains
bound to its own function.
This commit is contained in:
Charlie Marsh
2026-11-27 08:25:18 -05:00
committed by GitHub
parent 7b3746e595
commit b5fdb45bf0
3 changed files with 39 additions and 5 deletions
+8 -3
View File
@@ -3176,7 +3176,7 @@ impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> {
self.flow_restore(included_path)
}
fn declare_parameters(&mut self, parameters: &'ast ast::Parameters, is_stub_body: bool) {
fn declare_parameters(&mut self, parameters: &'ast ast::Parameters, parameter_only: bool) {
let nodes = parameters
.iter_non_variadic_params()
.map(ParameterDefinitionNodeRef::Parameter)
@@ -3192,7 +3192,7 @@ impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> {
.as_deref()
.map(ParameterDefinitionNodeRef::VariadicKeywordParameter),
);
if is_stub_body {
if parameter_only {
let parameters = nodes
.map(|node| self.declare_stub_parameter(node))
.collect();
@@ -3915,7 +3915,12 @@ impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> {
builder.push_scope(NodeWithScopeRef::Function(function_def));
builder.declare_parameters(parameters, ast::helpers::is_stub_body(body));
// A leading docstring does not change any bindings. Still visit
// it below to record its scope and statement range.
let rest = ast::helpers::body_without_leading_docstring(body);
let parameter_only = (!body.is_empty() && rest.is_empty())
|| ast::helpers::is_stub_body(rest);
builder.declare_parameters(parameters, parameter_only);
let mut first_parameter_name = parameters
.iter_non_variadic_params()
+29 -1
View File
@@ -1628,11 +1628,39 @@ def f(a: str, /, b: str, c: int = 1, *args, d: int = 2, **kwargs):
);
}
#[test]
fn stub_layouts_preserve_type_checking_ranges() {
let TestCase { db, file } = test_case(
"from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n def f(): 'doc'; pass; ...\n def g(): ...; pass\ndef h(): 'doc'",
);
let file = program_file(&db, file);
let index = semantic_index(&db, file);
let module = parsed_module(&db, file.python_file(&db)).load(&db);
let ast::Stmt::If(block) = &module.suite()[1] else {
panic!("expected a TYPE_CHECKING block");
};
for (stmt, guarded) in [
(&block.body[0], true),
(&block.body[1], true),
(&module.suite()[2], false),
] {
let ast::Stmt::FunctionDef(function) = stmt else {
panic!("expected a function");
};
let scope = index.node_scope(NodeWithScopeRef::Function(function));
let mut reference = Box::new(UseDefMapBuilder::new(ScopeKind::Function));
for statement in &function.body {
reference.record_range_reachability(statement.range(), guarded);
}
assert_eq!(index.use_def_map(scope), &reference.finish());
}
}
#[test]
fn stub_parameter_bindings_belong_to_their_own_function() {
let TestCase { db, file } = test_case(
"def first(a, /, *rest: int, b: str, **options): ...\n\
def second(c, /, *values: float, d: bytes, **kwargs): pass",
def second(c, /, *values: float, d: bytes, **kwargs): 'doc'; pass",
);
let file = program_file(&db, file);
let index = semantic_index(&db, file);
+2 -1
View File
@@ -972,7 +972,8 @@ pub(super) struct UseDefMapInterner {
stub_layouts: FxHashMap<SmallVec<[bool; 8]>, StubParameterLayout>,
}
/// Binding and declaration tables for a function whose body contains only `pass` or `...`.
/// Binding and declaration tables for a function whose body contains only an optional
/// docstring and zero or more `pass` or `...` statements.
/// Each distinct parameter binds its symbol once. An annotated parameter also declares it.
/// These functions share a layout because the tables refer to definitions by scope-local index.
///