1use crate::imports::{self, ImportBlock, ImportForm, ImportStatement};
4use serde::{Deserialize, Serialize};
5use std::collections::{HashMap, HashSet};
6use tree_sitter::Node;
7
8#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
12pub struct CallBinding {
13 pub byte_start: usize,
14 pub byte_end: usize,
15 pub target: Option<(String, String)>,
16}
17
18#[derive(Clone, PartialEq, Eq)]
19enum Binding {
20 Imported {
21 module: String,
22 symbol: Option<String>,
23 prefix: String,
24 },
25 LocalDefinition {
26 symbol: String,
27 position: usize,
28 class: bool,
29 },
30 Shadowed,
31}
32
33struct Scope {
34 parent: Option<usize>,
35 class: bool,
36 owner: String,
37 classes: Vec<String>,
38 names: HashMap<String, Binding>,
39}
40
41struct Extractor<'a> {
42 source: &'a str,
43 scopes: Vec<Scope>,
44 imports: Vec<ImportStatement>,
45 module_imports: HashSet<(usize, usize)>,
46 declarations: HashMap<String, usize>,
47 calls: Vec<(Node<'a>, usize)>,
48 module_only: bool,
49}
50
51pub struct Extraction {
52 pub imports: ImportBlock,
53 pub bindings: Vec<CallBinding>,
54 pub owners: HashMap<usize, Vec<String>>,
55}
56
57pub fn extract(source: &str, root: Node<'_>) -> Extraction {
58 let mut extractor = Extractor::new(source, false);
59 extractor.visit(root, 0);
60 let mut bindings: Vec<_> = extractor
61 .calls
62 .iter()
63 .filter_map(|(call, scope)| {
64 let callee = call.child_by_field_name("function")?;
65 let parts = source[callee.byte_range()]
66 .split('.')
67 .map(str::trim)
68 .collect::<Vec<_>>();
69 if parts.iter().any(|part| {
70 part.is_empty() || !part.chars().all(|c| c == '_' || c.is_alphanumeric())
71 }) {
72 return None;
73 }
74 let binding = extractor.lookup(*scope, parts[0])?;
75 let target = match binding {
76 Binding::LocalDefinition { symbol, class, .. }
77 if parts.len() == 1
78 && (!*class || extractor.declarations.get(symbol) == Some(&1)) =>
79 {
80 Some((String::new(), symbol.clone()))
81 }
82 Binding::Imported {
83 module,
84 symbol: Some(symbol),
85 ..
86 } if parts.len() == 1 => Some((module.clone(), symbol.clone())),
87 Binding::Imported {
88 module,
89 symbol: None,
90 prefix,
91 } => {
92 let prefix = prefix.split('.').collect::<Vec<_>>();
93 (parts.len() == prefix.len() + 1 && parts.starts_with(&prefix))
94 .then(|| (module.clone(), parts.last().unwrap().to_string()))
95 }
96 _ => None,
97 };
98 Some(CallBinding {
99 byte_start: call.start_byte(),
100 byte_end: call.end_byte(),
101 target,
102 })
103 })
104 .collect();
105 bindings.sort_by_key(|binding| (binding.byte_start, binding.byte_end));
106 Extraction {
107 imports: ImportBlock {
108 imports: extractor.imports,
109 byte_range: None,
110 },
111 bindings,
112 owners: extractor
113 .calls
114 .iter()
115 .map(|(call, scope)| {
116 let mut owners = vec![extractor.scopes[*scope].owner.clone()];
117 let mut parent = extractor.scopes[*scope].parent;
118 while let Some(id) = parent {
122 let enclosing = &extractor.scopes[id];
123 if !enclosing.class
124 && enclosing.owner != super::TOP_LEVEL_SYMBOL
125 && !owners.contains(&enclosing.owner)
126 {
127 owners.push(enclosing.owner.clone());
128 }
129 parent = enclosing.parent;
130 }
131 (call.start_byte(), owners)
132 })
133 .collect(),
134 }
135}
136
137pub fn reexports(source: &str, root: Node<'_>) -> Vec<ImportStatement> {
138 let mut extractor = Extractor::new(source, true);
139 extractor.visit(root, 0);
140 let mut reexports = Vec::new();
141 for import in &extractor.imports {
142 if !extractor
143 .module_imports
144 .contains(&(import.byte_range.start, import.byte_range.end))
145 {
146 continue;
147 }
148 let ImportForm::Python {
149 from_import: true,
150 named,
151 } = &import.form
152 else {
153 continue;
154 };
155 let named = named.iter().filter(|specifier| {
156 let local = imports::specifier_local_name(specifier);
157 matches!(extractor.scopes[0].names.get(local), Some(Binding::Imported { module, symbol: Some(symbol), .. })
158 if module == &import.module_path && symbol == imports::specifier_imported_name(specifier))
159 }).cloned().collect::<Vec<_>>();
160 if !named.is_empty() {
161 let mut exported = import.clone();
162 exported.names = named.clone();
163 exported.form = ImportForm::Python {
164 from_import: true,
165 named,
166 };
167 reexports.push(exported);
168 }
169 }
170 reexports
171}
172
173impl<'a> Extractor<'a> {
174 fn new(source: &'a str, module_only: bool) -> Self {
175 Self {
176 source,
177 scopes: vec![Scope {
178 parent: None,
179 class: false,
180 owner: super::TOP_LEVEL_SYMBOL.to_string(),
181 classes: Vec::new(),
182 names: HashMap::new(),
183 }],
184 imports: Vec::new(),
185 module_imports: HashSet::new(),
186 declarations: HashMap::new(),
187 calls: Vec::new(),
188 module_only,
189 }
190 }
191
192 fn bind(&mut self, scope: usize, name: &str, binding: Binding) {
193 self.scopes[scope]
194 .names
195 .entry(name.to_string())
196 .and_modify(|previous| {
197 if *previous != binding {
198 *previous = Binding::Shadowed;
199 }
200 })
201 .or_insert(binding);
202 }
203
204 fn lookup(&self, scope: usize, name: &str) -> Option<&Binding> {
205 let mut current = Some(scope);
206 while let Some(id) = current {
207 let frame = &self.scopes[id];
208 if id == scope || !frame.class {
210 if let Some(binding) = frame.names.get(name) {
211 return Some(binding);
212 }
213 }
214 current = frame.parent;
215 }
216 None
217 }
218
219 fn visit(&mut self, root: Node<'a>, scope: usize) {
226 let mut pending = vec![(root, scope)];
227 while let Some((node, scope)) = pending.pop() {
228 let start = pending.len();
229 self.visit_node(node, scope, &mut pending);
230 pending[start..].reverse();
231 }
232 }
233
234 fn visit_node(&mut self, node: Node<'a>, scope: usize, pending: &mut Vec<(Node<'a>, usize)>) {
238 if matches!(
239 node.kind(),
240 "function_definition" | "class_definition" | "lambda"
241 ) {
242 if let Some(name) = node.child_by_field_name("name") {
243 let mut path = self.scopes[scope].classes.clone();
244 path.push(self.source[name.byte_range()].to_string());
245 *self.declarations.entry(path.join("::")).or_default() += 1;
249 self.bind(
250 scope,
251 &self.source[name.byte_range()],
252 Binding::LocalDefinition {
253 symbol: path.join("::"),
254 position: node.start_byte(),
255 class: node.kind() == "class_definition",
256 },
257 );
258 }
259 if self.module_only {
260 let body = node.child_by_field_name("body");
263 for child in node.named_children(&mut node.walk()) {
264 if Some(child) != body {
265 pending.push((child, scope));
266 }
267 }
268 return;
269 }
270 let id = self.scopes.len();
271 let mut classes = self.scopes[scope].classes.clone();
272 let owner = if let Some(name) = node.child_by_field_name("name") {
273 let name = &self.source[name.byte_range()];
274 let mut path = classes.clone();
275 path.push(name.to_string());
276 if node.kind() == "class_definition" {
277 classes.push(name.to_string());
278 }
279 path.join("::")
280 } else {
281 self.scopes[scope].owner.clone()
282 };
283 self.scopes.push(Scope {
284 parent: Some(scope),
285 class: node.kind() == "class_definition",
286 owner,
287 classes,
288 names: HashMap::new(),
289 });
290 if let Some(parameters) = node.child_by_field_name("parameters") {
291 for parameter in parameters.named_children(&mut parameters.walk()) {
292 let name = if parameter.kind() == "identifier" {
293 Some(parameter)
294 } else {
295 parameter
296 .child_by_field_name("name")
297 .or_else(|| parameter.named_child(0))
298 };
299 if let Some(name) = name.filter(|n| n.kind() == "identifier") {
300 self.bind(id, &self.source[name.byte_range()], Binding::Shadowed);
301 }
302 }
303 }
304 let body = node.child_by_field_name("body");
307 for child in node.named_children(&mut node.walk()) {
308 pending.push((child, if Some(child) == body { id } else { scope }));
309 }
310 return;
311 }
312 if let Some(import) = imports::parse_py_import_node(self.source, &node) {
313 self.import(scope, import);
314 return;
315 }
316 if matches!(
317 node.kind(),
318 "assignment" | "augmented_assignment" | "for_statement" | "named_expression"
319 ) {
320 if let Some(left) = node
321 .child_by_field_name("left")
322 .or_else(|| node.child_by_field_name("name"))
323 {
324 self.shadow_pattern(left, scope);
325 }
326 }
327 if node.kind() == "as_pattern" {
328 if let Some(alias) = node.child_by_field_name("alias") {
329 self.shadow_pattern(alias, scope);
330 }
331 }
332 if node.kind() == "delete_statement" {
333 for child in node.named_children(&mut node.walk()) {
334 self.shadow_pattern(child, scope);
335 }
336 }
337 if node.kind() == "call" && !self.module_only {
338 self.calls.push((node, scope));
339 }
340 pending.extend(
341 node.named_children(&mut node.walk())
342 .map(|child| (child, scope)),
343 );
344 }
345
346 fn shadow_pattern(&mut self, root: Node<'a>, scope: usize) {
350 let mut pending = vec![root];
351 while let Some(node) = pending.pop() {
352 if node.kind() == "identifier" {
353 self.bind(scope, &self.source[node.byte_range()], Binding::Shadowed);
354 } else if matches!(
355 node.kind(),
356 "pattern_list" | "tuple_pattern" | "list_pattern" | "as_pattern_target"
357 ) {
358 pending.extend(node.named_children(&mut node.walk()));
359 }
360 }
361 }
362
363 fn import(&mut self, scope: usize, import: ImportStatement) {
364 if scope == 0 {
365 self.module_imports
366 .insert((import.byte_range.start, import.byte_range.end));
367 }
368 let ImportForm::Python { from_import, named } = &import.form else {
369 return;
370 };
371 if *from_import {
372 for specifier in named {
373 self.bind(
374 scope,
375 imports::specifier_local_name(specifier),
376 Binding::Imported {
377 module: import.module_path.clone(),
378 symbol: Some(imports::specifier_imported_name(specifier).to_string()),
379 prefix: String::new(),
380 },
381 );
382 }
383 self.imports.push(import);
384 } else {
385 for specifier in named {
386 let module = imports::specifier_imported_name(specifier);
387 let local = imports::specifier_local_name(specifier);
388 let aliased = local != module;
389 let name = if aliased {
390 local
391 } else {
392 module.split('.').next().unwrap_or(module)
393 };
394 self.bind(
395 scope,
396 name,
397 Binding::Imported {
398 module: module.to_string(),
399 symbol: None,
400 prefix: if aliased {
401 local.to_string()
402 } else {
403 module.to_string()
404 },
405 },
406 );
407 let mut normalized = import.clone();
408 normalized.module_path = module.to_string();
409 normalized.namespace_import = Some(if aliased {
410 local.to_string()
411 } else {
412 name.to_string()
413 });
414 self.imports.push(normalized);
415 }
416 }
417 }
418}
419aft_store::heap_bytes_of_fields!(CallBinding {
420 byte_start,
421 byte_end,
422 target,
423});