1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use std::fmt::Debug;
use clap::ValueEnum;
use const_format::formatcp;
use super::{Find, LanguageScoper, QuerySource, TSLanguage, TSQuery, TSQueryError};
use crate::scoping::langs::IGNORE;
/// A compiled query for the Python language.
#[derive(Debug)]
pub struct CompiledQuery(super::CompiledQuery);
impl TryFrom<QuerySource> for CompiledQuery {
type Error = TSQueryError;
/// Create a new compiled query for the Python language.
///
/// # Errors
///
/// See the concrete type of the [`TSQueryError`](tree_sitter::QueryError)variant for when this method errors.
fn try_from(query: QuerySource) -> Result<Self, Self::Error> {
let q = super::CompiledQuery::from_source(&tree_sitter_python::LANGUAGE.into(), &query)?;
Ok(Self(q))
}
}
impl From<PreparedQuery> for CompiledQuery {
fn from(query: PreparedQuery) -> Self {
Self(super::CompiledQuery::from_prepared_query(
&tree_sitter_python::LANGUAGE.into(),
query.as_str(),
))
}
}
/// Prepared tree-sitter queries for Python.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum PreparedQuery {
/// Comments.
Comments,
/// Strings (raw, byte, f-strings; interpolation not included).
Strings,
/// Module names in imports (incl. periods; excl. `import`/`from`/`as`/`*`).
Imports,
/// Docstrings (not including multi-line strings).
DocStrings,
/// Function names, at the definition site.
FunctionNames,
/// Function calls.
FunctionCalls,
/// Class definitions (in their entirety).
Class,
/// Function definitions (*all* `def` block in their entirety).
Def,
/// Async function definitions (*all* `async def` block in their entirety).
AsyncDef,
/// Function definitions inside `class` bodies.
Methods,
/// Function definitions decorated as `classmethod` (excl. the decorator).
ClassMethods,
/// Function definitions decorated as `staticmethod` (excl. the decorator).
StaticMethods,
/// `with` blocks (in their entirety).
With,
/// `try` blocks (in their entirety).
Try,
/// `lambda` statements (in their entirety).
Lambda,
/// Global, i.e. module-level variables.
Globals,
/// Identifiers for variables (left-hand side of assignments).
VariableIdentifiers,
/// Types in type hints.
Types,
/// Identifiers (variable names, ...).
Identifiers,
}
impl PreparedQuery {
#[expect(clippy::too_many_lines)]
const fn as_str(self) -> &'static str {
match self {
Self::Comments => "(comment) @comment",
Self::Strings => "(string_content) @string",
Self::Imports => {
r"[
(import_statement
name: (dotted_name) @dn)
(import_from_statement
module_name: (dotted_name) @dn)
(import_from_statement
module_name: (dotted_name) @dn
(wildcard_import))
(import_statement(
aliased_import
name: (dotted_name) @dn))
(import_from_statement
module_name: (relative_import) @ri)
]"
}
Self::DocStrings => {
// Triple-quotes are also used for multi-line strings. So look only
// for stand-alone expressions, which are not part of some variable
// assignment.
formatcp!(
"
(
(expression_statement
(string
(string_start) @{0}
(string_content) @string
(#match? @{0} \"\\^\\\"\\\"\\\"\")
)
)
)
",
IGNORE
)
}
Self::FunctionNames => {
r"
(function_definition
name: (identifier) @function-name
)
"
}
Self::FunctionCalls => {
r"
(call
function: (identifier) @function-name
)
"
}
Self::Class => "(class_definition) @class",
Self::Def => "(function_definition) @def",
Self::AsyncDef => r#"((function_definition) @def (#match? @def "^async "))"#,
Self::Methods => {
r"
(class_definition
body: (block
[
(function_definition) @method
(decorated_definition definition: (function_definition)) @method
]
)
)
"
}
Self::ClassMethods => {
formatcp!(
"
(class_definition
body: (block
(decorated_definition
(decorator (identifier) @{0})
definition: (function_definition) @method
(#eq? @{0} \"classmethod\")
)
)
)",
IGNORE
)
}
Self::StaticMethods => {
formatcp!(
"
(class_definition
body: (block
(decorated_definition
(decorator (identifier) @{0})
definition: (function_definition) @method
(#eq? @{0} \"staticmethod\")
)
)
)",
IGNORE
)
}
Self::With => "(with_statement) @with",
Self::Try => "(try_statement) @try",
Self::Lambda => "(lambda) @lambda",
Self::Globals => {
"(module (expression_statement (assignment left: (identifier) @global)))"
}
Self::VariableIdentifiers => "(assignment left: (identifier) @identifier)",
Self::Types => "(type) @type",
Self::Identifiers => "(identifier) @identifier",
}
}
}
impl LanguageScoper for CompiledQuery {
fn lang() -> TSLanguage {
tree_sitter_python::LANGUAGE.into()
}
fn pos_query(&self) -> &TSQuery {
&self.0.positive_query
}
fn neg_query(&self) -> Option<&TSQuery> {
self.0.negative_query.as_ref()
}
}
impl Find for CompiledQuery {
fn extensions(&self) -> &'static [&'static str] {
&["py"]
}
fn interpreters(&self) -> Option<&'static [&'static str]> {
Some(&["python", "python3"])
}
}