Skip to main content

brokk_bifrost_python/
structural.rs

1//! Python structural spec: maps tree-sitter-python node types onto the
2//! normalized kind vocabulary and extracts role edges from AST fields.
3//! See `src/analyzer/structural/spec.rs` for the contract and
4//! `.agent/ISSUE_328_SEARCH_AST_EXECPLAN.md` for the design.
5
6use brokk_bifrost_core::analyzer::common::node_source_text;
7use brokk_bifrost_core::analyzer::structural::adapter_helpers::{
8    CalleeSpineStep, attach_argument_role_with_derived_name, attach_role_with_derived_name,
9    attach_terminal_callee, field_name_in_parent, nearest_ancestor, node_range,
10    terminal_callee_leaf,
11};
12use brokk_bifrost_core::analyzer::structural::callable::CallSiteContext;
13use brokk_bifrost_core::analyzer::structural::edges::{
14    DEEP_REFERENCE_EDGE_SUPPORT, ReferenceEdgeSupport,
15};
16use brokk_bifrost_core::analyzer::structural::facts::{
17    AssignmentSequenceKind, AssignmentShape, IntegerLiteralValue, Span,
18    decode_integer_literal_digits,
19};
20use brokk_bifrost_core::analyzer::structural::kinds::{NormalizedKind, Role};
21use brokk_bifrost_core::analyzer::structural::materialization::{
22    DeclarationMaterializationSupport, PYTHON_MATERIALIZATION_SUPPORT, SourceExportBinding,
23    SourceExportBindingKind, SourceExportFact, SourceExportFacts, SourceExportLocalDefinition,
24};
25use brokk_bifrost_core::analyzer::structural::occurrences::{
26    Namespace, OccurrenceRole, OccurrenceRoleSupport, module_path_occurrence_namespace,
27};
28use brokk_bifrost_core::analyzer::structural::resolution::{
29    BindingActivation, BindingKind, DEEP_LEXICAL_ENVIRONMENT_SUPPORT, HoistingClass,
30    LexicalEnvironmentSupport, ScopeFormation, default_scope_formation,
31};
32use brokk_bifrost_core::analyzer::structural::routes::{
33    CuratedExportSurface, DEEP_IDENTITY_AXES, IdentityRouteSupport, RouteHopKind,
34};
35use brokk_bifrost_core::analyzer::structural::spec::{EmbeddedLeafFact, RoleSink, StructuralSpec};
36use brokk_bifrost_core::analyzer::{Language, Range};
37use brokk_bifrost_core::cancellation::CancellationToken;
38use brokk_bifrost_core::hash::{HashMap, HashSet};
39use tree_sitter::Node;
40
41use crate::bindings::{
42    PythonDirectScopeBindingKind, python_direct_scope_bindings_bounded,
43    python_executable_scope_children,
44};
45use crate::imports::python_import_bindings_from_tree;
46use crate::syntax::{
47    expression_name_node, python_conditional_expression_operands,
48    python_deferred_annotation_identifier_ranges, python_keyword_argument_label,
49    python_node_is_in_annotation, python_plain_string_literal,
50};
51
52#[derive(Debug, Default)]
53pub struct PythonStructuralSpec;
54
55pub static PYTHON_STRUCTURAL_SPEC: PythonStructuralSpec = PythonStructuralSpec;
56
57/// Tree-sitter interleaves grammar extras (`comment`, `line_continuation`)
58/// between the operands of a Python node wherever whitespace is allowed. A
59/// backslash newline is the `line_continuation` extra, so an operand that is
60/// selected by position among every named child can land on an extra instead.
61/// Structural roles and shapes describe the operands, so selection skips extras.
62fn python_first_named_operand(node: Node<'_>) -> Option<Node<'_>> {
63    let mut cursor = node.walk();
64    node.named_children(&mut cursor)
65        .find(|child| !child.is_extra())
66}
67
68/// Peel Python's transparent type wrappers while ignoring grammar extras.
69pub(crate) fn python_unwrap_type(mut node: Node<'_>) -> Node<'_> {
70    while node.kind() == "type" {
71        let Some(operand) = python_first_named_operand(node) else {
72            break;
73        };
74        node = operand;
75    }
76    node
77}
78
79fn attach_python_argument_roles(sink: &mut RoleSink<'_>, arguments: Node<'_>) {
80    for index in 0..arguments.named_child_count() {
81        if !sink.should_continue() {
82            break;
83        }
84        let Some(argument) = arguments.named_child(index) else {
85            continue;
86        };
87        if argument.is_extra() {
88            continue;
89        }
90        match argument.kind() {
91            "keyword_argument" => {
92                if let (Some(keyword), Some(value)) = (
93                    argument.child_by_field_name("name"),
94                    argument.child_by_field_name("value"),
95                ) {
96                    sink.kwarg(keyword, value);
97                }
98            }
99            "list_splat" | "dictionary_splat" if python_literal_pack_arguments(argument, sink) => {}
100            _ => attach_argument_role_with_derived_name(sink, argument, expression_name_node),
101        }
102    }
103}
104
105pub(crate) fn python_parenthesized_expression_child(node: Node<'_>) -> Option<Node<'_>> {
106    assert_eq!(node.kind(), "parenthesized_expression");
107    let mut cursor = node.walk();
108    let mut children = node
109        .named_children(&mut cursor)
110        .filter(|child| !child.is_extra());
111    let child = children.next()?;
112    children.next().is_none().then_some(child)
113}
114
115fn python_unwrap_parenthesized(mut node: Node<'_>) -> Node<'_> {
116    while node.kind() == "parenthesized_expression" {
117        let Some(child) = python_parenthesized_expression_child(node) else {
118            break;
119        };
120        node = child;
121    }
122    node
123}
124
125/// Unwrap transparent grouping parentheses on a Python assignment target
126/// (`(value) = 1`, `(self.field) = 1`), stopping at real tuple unpacking
127/// patterns that carry a comma separator (`(a, b) = ...`, `(a,) = ...`).
128fn python_assignment_name_node<'tree>(target: Node<'tree>) -> Option<Node<'tree>> {
129    let mut current = target;
130    loop {
131        current = python_unwrap_parenthesized(current);
132        if current.kind() == "tuple_pattern" {
133            let mut cursor = current.walk();
134            let has_comma = current
135                .children(&mut cursor)
136                .any(|child| !child.is_named() && child.kind() == ",");
137            if has_comma {
138                return None;
139            }
140            let mut named_cursor = current.walk();
141            let mut children = current
142                .named_children(&mut named_cursor)
143                .filter(|child| !child.is_extra());
144            let only_child = children.next()?;
145            if children.next().is_some() {
146                return None;
147            }
148            current = only_child;
149            continue;
150        }
151        return expression_name_node(current);
152    }
153}
154
155/// Collect every bound name of a Python assignment target in source order,
156/// traversing tuple/list/starred unpacking targets and transparent grouping
157/// parentheses while leaving subscript targets unnamed.
158fn add_python_assignment_names(sink: &mut RoleSink<'_>, target: Node<'_>) {
159    let mut stack = vec![target];
160    while let Some(current) = stack.pop() {
161        let current = python_unwrap_parenthesized(current);
162        match current.kind() {
163            "tuple_pattern" | "pattern_list" | "list_pattern" | "list_splat_pattern"
164            | "splat_pattern" => {
165                let mut cursor = current.walk();
166                let mut children: Vec<_> = current
167                    .named_children(&mut cursor)
168                    .filter(|child| !child.is_extra())
169                    .collect();
170                children.reverse();
171                stack.extend(children);
172            }
173            _ => {
174                if let Some(name) = expression_name_node(current) {
175                    sink.add_name(name);
176                }
177            }
178        }
179    }
180}
181
182fn python_unstarred_sequence_shape(node: Node<'_>, starred_node_kinds: &[&str]) -> (u32, bool) {
183    let mut unstarred_count = 0u32;
184    let mut starred = false;
185    for index in 0..node.named_child_count() {
186        let child = node
187            .named_child(index)
188            .expect("named child index is below the named child count");
189        if child.is_extra() {
190            continue;
191        }
192        match child.kind() {
193            kind if starred_node_kinds.contains(&kind) => starred = true,
194            _ => unstarred_count += 1,
195        }
196    }
197    (unstarred_count, starred)
198}
199
200/// Expand only displays whose argument names and cardinality are known from
201/// syntax. Validate the entire pack before attaching any ordinary arguments.
202fn python_literal_pack_arguments(argument: Node<'_>, sink: &mut RoleSink<'_>) -> bool {
203    let Some(operand) = python_first_named_operand(argument) else {
204        return false;
205    };
206    let operand = python_unwrap_parenthesized(operand);
207    match (argument.kind(), operand.kind()) {
208        ("list_splat", "tuple" | "list") => {
209            let mut cursor = operand.walk();
210            let elements: Vec<_> = operand
211                .named_children(&mut cursor)
212                .filter(|child| !child.is_extra())
213                .collect();
214            if elements
215                .iter()
216                .any(|element| element.kind() == "list_splat")
217            {
218                return false;
219            }
220            for element in elements {
221                attach_argument_role_with_derived_name(sink, element, expression_name_node);
222            }
223            true
224        }
225        ("dictionary_splat", "dictionary") => {
226            let mut entries = Vec::new();
227            let mut indices = HashMap::default();
228            let mut cursor = operand.walk();
229            for pair in operand
230                .named_children(&mut cursor)
231                .filter(|child| !child.is_extra())
232            {
233                if pair.kind() != "pair" {
234                    return false;
235                }
236                let (Some(key), Some(value)) = (
237                    pair.child_by_field_name("key"),
238                    pair.child_by_field_name("value"),
239                ) else {
240                    return false;
241                };
242                let Some(name) = python_plain_string_literal(key, sink.source()) else {
243                    return false;
244                };
245                // Plain strings have no escapes. Select their content using
246                // grammar nodes, including the zero-width content of "".
247                let mut key_cursor = key.walk();
248                let Some(content) = key
249                    .named_children(&mut key_cursor)
250                    .find(|child| matches!(child.kind(), "string_content" | "string_end"))
251                else {
252                    return false;
253                };
254                let span = Span {
255                    start_byte: content.start_byte(),
256                    end_byte: content.start_byte() + name.len(),
257                };
258                // Dict construction overwrites duplicate keys without moving
259                // their insertion position. Only the retained value is passed.
260                if let Some(&index) = indices.get(name) {
261                    entries[index] = (span, value);
262                } else {
263                    indices.insert(name, entries.len());
264                    entries.push((span, value));
265                }
266            }
267            for (keyword, value) in entries {
268                sink.kwarg_span(keyword, value);
269            }
270            true
271        }
272        _ => false,
273    }
274}
275
276fn python_assignment_target_shape(node: Node<'_>) -> Option<(AssignmentSequenceKind, u32, bool)> {
277    let node = python_unwrap_parenthesized(node);
278    let kind = match node.kind() {
279        "tuple_pattern" | "pattern_list" => AssignmentSequenceKind::Tuple,
280        "list_pattern" => AssignmentSequenceKind::List,
281        _ => return None,
282    };
283    let (count, starred) =
284        python_unstarred_sequence_shape(node, &["list_splat_pattern", "splat_pattern"]);
285    Some((kind, count, starred))
286}
287
288fn python_assignment_value_shape(node: Node<'_>) -> Option<(AssignmentSequenceKind, u32, bool)> {
289    let node = python_unwrap_parenthesized(node);
290    let kind = match node.kind() {
291        "tuple" | "expression_list" => AssignmentSequenceKind::Tuple,
292        "list" => AssignmentSequenceKind::List,
293        _ => return None,
294    };
295    let (count, starred) = python_unstarred_sequence_shape(node, &["list_splat"]);
296    Some((kind, count, starred))
297}
298
299fn python_assignment_shape(node: Node<'_>) -> Option<AssignmentShape> {
300    if node.kind() != "assignment" {
301        return None;
302    }
303    let (target_kind, target_unstarred_count, target_starred) =
304        python_assignment_target_shape(node.child_by_field_name("left")?)?;
305    let (value_kind, value_unstarred_count, value_starred) =
306        python_assignment_value_shape(node.child_by_field_name("right")?)?;
307    Some(AssignmentShape {
308        target_kind,
309        value_kind,
310        target_unstarred_count,
311        value_unstarred_count,
312        target_starred,
313        value_starred,
314    })
315}
316
317fn python_integer_literal_value(node: Node<'_>, source: &str) -> Option<IntegerLiteralValue> {
318    if node.kind() != "integer" {
319        return None;
320    }
321
322    let text = node_source_text(node, source).as_bytes();
323    let (radix, digits) = match (text.first(), text.get(1)) {
324        (Some(b'0'), Some(b'b' | b'B')) => (2u32, &text[2..]),
325        (Some(b'0'), Some(b'o' | b'O')) => (8u32, &text[2..]),
326        (Some(b'0'), Some(b'x' | b'X')) => (16u32, &text[2..]),
327        _ => (10u32, text),
328    };
329    decode_integer_literal_digits(radix, digits)
330}
331
332#[derive(Debug, PartialEq, Eq)]
333enum PythonDictionaryKeyValue {
334    String(String),
335    Integer { negative: bool, magnitude: String },
336    Boolean(bool),
337    None,
338}
339
340impl PythonDictionaryKeyValue {
341    fn equals(&self, other: &Self) -> bool {
342        match (self, other) {
343            (Self::String(left), Self::String(right)) => left == right,
344            (Self::None, Self::None) => true,
345            (
346                Self::Integer {
347                    negative: left_negative,
348                    magnitude: left_magnitude,
349                },
350                Self::Integer {
351                    negative: right_negative,
352                    magnitude: right_magnitude,
353                },
354            ) => left_negative == right_negative && left_magnitude == right_magnitude,
355            (Self::Boolean(value), Self::Boolean(other)) => value == other,
356            (
357                Self::Boolean(value),
358                Self::Integer {
359                    negative,
360                    magnitude,
361                },
362            )
363            | (
364                Self::Integer {
365                    negative,
366                    magnitude,
367                },
368                Self::Boolean(value),
369            ) => !negative && magnitude == if *value { "1" } else { "0" },
370            _ => false,
371        }
372    }
373}
374
375fn python_string_key_value(node: Node<'_>, source: &str) -> Option<String> {
376    if node.kind() == "concatenated_string" {
377        let mut value = String::new();
378        let mut cursor = node.walk();
379        for part in node
380            .named_children(&mut cursor)
381            .filter(|part| !part.is_extra())
382        {
383            if part.kind() != "string" {
384                return None;
385            }
386            value.push_str(&python_string_key_value(part, source)?);
387        }
388        return Some(value);
389    }
390    if node.kind() != "string" {
391        return None;
392    }
393
394    let mut raw = false;
395    let mut content = String::new();
396    let mut cursor = node.walk();
397    for child in node.children(&mut cursor) {
398        match child.kind() {
399            "string_start" => {
400                let start = node_source_text(child, source).as_bytes();
401                let prefix_end = start
402                    .iter()
403                    .position(|byte| matches!(byte, b'\'' | b'"'))
404                    .unwrap_or(start.len());
405                let prefix = std::str::from_utf8(&start[..prefix_end]).ok()?;
406                if !prefix.bytes().all(|byte| byte.is_ascii_alphabetic()) {
407                    return None;
408                }
409                let prefix = prefix.to_ascii_lowercase();
410                if prefix.contains('b') || prefix.contains('f') {
411                    return None;
412                }
413                raw = prefix.contains('r');
414            }
415            "string_content" => content.push_str(node_source_text(child, source)),
416            "escape_sequence" => content.push_str(node_source_text(child, source)),
417            "string_end" => {}
418            _ => return None,
419        }
420    }
421    python_decode_string_content(&content, raw)
422}
423
424fn python_decode_string_content(content: &str, raw: bool) -> Option<String> {
425    if raw {
426        return Some(content.to_owned());
427    }
428    let mut chars = content.chars().peekable();
429    let mut decoded = String::with_capacity(content.len());
430    while let Some(character) = chars.next() {
431        if character != '\\' {
432            decoded.push(character);
433            continue;
434        }
435        let escaped = chars.next()?;
436        let replacement = match escaped {
437            '\n' => continue,
438            '\r' => {
439                chars.next_if_eq(&'\n')?;
440                continue;
441            }
442            '\\' => '\\',
443            '\'' => '\'',
444            '"' => '"',
445            'a' => '\u{0007}',
446            'b' => '\u{0008}',
447            'f' => '\u{000c}',
448            'n' => '\n',
449            'r' => '\r',
450            't' => '\t',
451            'v' => '\u{000b}',
452            'x' => python_escape_codepoint(&mut chars, 2)?,
453            'u' => python_escape_codepoint(&mut chars, 4)?,
454            'U' => python_escape_codepoint(&mut chars, 8)?,
455            'N' => return None,
456            '0'..='7' => {
457                let mut value = escaped.to_digit(8)?;
458                for _ in 0..2 {
459                    let Some(next) = chars.peek().copied().filter(char::is_ascii_digit) else {
460                        break;
461                    };
462                    let Some(digit) = next.to_digit(8) else {
463                        break;
464                    };
465                    chars.next();
466                    value = value * 8 + digit;
467                }
468                char::from_u32(value)?
469            }
470            other => {
471                decoded.push('\\');
472                other
473            }
474        };
475        decoded.push(replacement);
476    }
477    Some(decoded)
478}
479
480fn python_escape_codepoint(
481    chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
482    digits: usize,
483) -> Option<char> {
484    let mut value = 0u32;
485    for _ in 0..digits {
486        value = value
487            .checked_mul(16)?
488            .checked_add(chars.next()?.to_digit(16)?)?;
489    }
490    char::from_u32(value)
491}
492
493fn python_dictionary_key_value(node: Node<'_>, source: &str) -> Option<PythonDictionaryKeyValue> {
494    let node = python_unwrap_parenthesized(node);
495    if matches!(node.kind(), "string" | "concatenated_string") {
496        return python_string_key_value(node, source).map(PythonDictionaryKeyValue::String);
497    }
498    if matches!(node.kind(), "true" | "false") {
499        return Some(PythonDictionaryKeyValue::Boolean(node.kind() == "true"));
500    }
501    if node.kind() == "none" {
502        return Some(PythonDictionaryKeyValue::None);
503    }
504
505    let (integer, negative) = if node.kind() == "unary_operator" {
506        let operator = node.child_by_field_name("operator")?;
507        match node_source_text(operator, source) {
508            "+" => (
509                python_unwrap_parenthesized(node.child_by_field_name("argument")?),
510                false,
511            ),
512            "-" => (
513                python_unwrap_parenthesized(node.child_by_field_name("argument")?),
514                true,
515            ),
516            _ => return None,
517        }
518    } else {
519        (node, false)
520    };
521    let value = python_integer_literal_value(integer, source)?;
522    let magnitude = value.decimal?;
523    let negative = negative && magnitude != "0";
524    Some(PythonDictionaryKeyValue::Integer {
525        negative,
526        magnitude,
527    })
528}
529
530fn python_duplicate_dictionary_key(node: Node<'_>, source: &str) -> Option<bool> {
531    if node.kind() != "pair" {
532        return None;
533    }
534    let dictionary = node
535        .parent()
536        .filter(|parent| parent.kind() == "dictionary")?;
537    let current_key = python_dictionary_key_value(node.child_by_field_name("key")?, source)?;
538    let mut earlier_unknown = false;
539    let mut all_entries = dictionary.walk();
540    let has_unpacked_entry = dictionary
541        .named_children(&mut all_entries)
542        .any(|entry| !entry.is_extra() && entry.kind() != "pair");
543    let mut cursor = dictionary.walk();
544    for entry in dictionary.named_children(&mut cursor) {
545        if entry.id() == node.id() {
546            return if earlier_unknown || has_unpacked_entry {
547                None
548            } else {
549                Some(false)
550            };
551        }
552        match entry.kind() {
553            "pair" => {
554                let previous_key = entry
555                    .child_by_field_name("key")
556                    .and_then(|key| python_dictionary_key_value(key, source));
557                if previous_key
558                    .as_ref()
559                    .is_some_and(|previous| current_key.equals(previous))
560                {
561                    return Some(true);
562                }
563                earlier_unknown |= previous_key.is_none();
564            }
565            _ if entry.is_extra() => {}
566            _ => {
567                earlier_unknown = true;
568            }
569        }
570    }
571    None
572}
573
574#[derive(Clone, Copy)]
575pub struct PythonComparisonShape<'tree> {
576    pub operator_count: usize,
577    pub operand_count: usize,
578    pub left: Option<Node<'tree>>,
579    pub right: Option<Node<'tree>>,
580    pub operator: Option<Node<'tree>>,
581}
582
583/// Read comparison operands and operator tokens from the grammar node. Python
584/// comparison operators are repeated fields; named operator aliases such as
585/// `is not` are distinguished from operands by their field name.
586pub fn python_comparison_shape(node: Node<'_>) -> PythonComparisonShape<'_> {
587    let mut operator_count = 0usize;
588    let mut operand_count = 0usize;
589    let mut left = None;
590    let mut right = None;
591    let mut operator = None;
592    visit_python_comparison_children(node, |child, is_operator| {
593        if is_operator {
594            operator_count += 1;
595            operator.get_or_insert(child);
596        } else if child.is_named() && !child.is_extra() {
597            operand_count += 1;
598            if left.is_none() {
599                left = Some(child);
600            } else if right.is_none() {
601                right = Some(child);
602            }
603        }
604        true
605    });
606    debug_assert!(
607        node.has_error() || operand_count == operator_count.saturating_add(1),
608        "well-formed Python comparison must have one more operand than operators: {node:?}"
609    );
610    PythonComparisonShape {
611        operator_count,
612        operand_count,
613        left,
614        right,
615        operator,
616    }
617}
618
619/// Shared grammar-field traversal for singular roles and transient domains.
620pub(crate) fn visit_python_comparison_children<'tree>(
621    node: Node<'tree>,
622    mut visit: impl FnMut(Node<'tree>, bool) -> bool,
623) -> bool {
624    let mut cursor = node.walk();
625    if cursor.goto_first_child() {
626        loop {
627            if !visit(cursor.node(), cursor.field_name() == Some("operators")) {
628                return false;
629            }
630            if !cursor.goto_next_sibling() {
631                break;
632            }
633        }
634    }
635    true
636}
637
638/// Whether a wrapper is a constant form used by comparison-of-constants:
639/// parenthesized scalar literals and unary signs over numeric literals. This
640/// deliberately does not fold arbitrary expressions such as `1 + 2`.
641fn python_comparison_constant(node: Node<'_>) -> bool {
642    let mut current = node;
643    let mut signed = false;
644    loop {
645        match current.kind() {
646            "parenthesized_expression" => {
647                let Some(expression) = python_parenthesized_expression_child(current) else {
648                    return false;
649                };
650                current = expression;
651            }
652            "unary_operator" => {
653                if !current
654                    .child_by_field_name("operator")
655                    .is_some_and(|operator| matches!(operator.kind(), "+" | "-"))
656                {
657                    return false;
658                }
659                let Some(argument) = current.child_by_field_name("argument") else {
660                    return false;
661                };
662                signed = true;
663                current = argument;
664            }
665            "integer" | "float" => return true,
666            "true" | "false" | "none" => return !signed,
667            "string" | "concatenated_string" => {
668                return !signed && python_plain_string_constant(current);
669            }
670            _ => return false,
671        }
672    }
673}
674
675/// Accept ordinary string tokens and implicit literal concatenation, but not
676/// interpolated strings. Tree structure, rather than source-text scanning,
677/// distinguishes the interpolation form.
678fn python_plain_string_constant(node: Node<'_>) -> bool {
679    let mut pending = vec![node];
680    let mut saw_string = false;
681    while let Some(current) = pending.pop() {
682        match current.kind() {
683            "string" => {
684                saw_string = true;
685                let mut cursor = current.walk();
686                if current
687                    .named_children(&mut cursor)
688                    .any(|child| child.kind() == "interpolation")
689                {
690                    return false;
691                }
692            }
693            "concatenated_string" => {
694                let mut cursor = current.walk();
695                let mut parts = 0;
696                for child in current.named_children(&mut cursor) {
697                    if child.kind() != "string" {
698                        return false;
699                    }
700                    parts += 1;
701                    pending.push(child);
702                }
703                if parts == 0 {
704                    return false;
705                }
706            }
707            _ => return false,
708        }
709    }
710    saw_string
711}
712
713/// Grammar node-type → normalized kind. Every name here must exist in the
714/// tree-sitter-python grammar; `tests::python_kind_table_matches_grammar`
715/// asserts that, so a grammar bump that renames a node fails loudly.
716pub const PYTHON_KIND_TABLE: &[(&str, NormalizedKind)] = &[
717    ("call", NormalizedKind::Call),
718    ("attribute", NormalizedKind::FieldAccess),
719    ("function_definition", NormalizedKind::Function),
720    ("lambda", NormalizedKind::Lambda),
721    ("await", NormalizedKind::Await),
722    ("yield", NormalizedKind::Yield),
723    ("module", NormalizedKind::Module),
724    ("class_definition", NormalizedKind::Class),
725    ("assignment", NormalizedKind::Assignment),
726    ("binary_operator", NormalizedKind::BinaryExpression),
727    ("boolean_operator", NormalizedKind::BinaryExpression),
728    ("comparison_operator", NormalizedKind::Comparison),
729    ("assert_statement", NormalizedKind::Assertion),
730    ("conditional_expression", NormalizedKind::If),
731    // These wrappers are emitted as literals only for supported constant
732    // forms; `should_extract` rejects computed or interpolated expressions.
733    ("parenthesized_expression", NormalizedKind::Literal),
734    ("unary_operator", NormalizedKind::Literal),
735    // The implicit `__exit__` of a `with` statement runs at the construct's
736    // own exit, so the statement is the source fact the resource-lifecycle
737    // selector names for that release.
738    ("with_statement", NormalizedKind::ResourceRelease),
739    ("import_statement", NormalizedKind::Import),
740    ("import_from_statement", NormalizedKind::Import),
741    ("identifier", NormalizedKind::Identifier),
742    ("string", NormalizedKind::StringLiteral),
743    ("concatenated_string", NormalizedKind::StringLiteral),
744    ("integer", NormalizedKind::NumericLiteral),
745    ("float", NormalizedKind::NumericLiteral),
746    ("true", NormalizedKind::BooleanLiteral),
747    ("false", NormalizedKind::BooleanLiteral),
748    ("none", NormalizedKind::NullLiteral),
749    ("return_statement", NormalizedKind::Return),
750    ("raise_statement", NormalizedKind::Throw),
751    ("except_clause", NormalizedKind::Catch),
752    ("if_statement", NormalizedKind::If),
753    ("for_statement", NormalizedKind::ForLoop),
754    ("list", NormalizedKind::ListLiteral),
755    ("set", NormalizedKind::CollectionLiteral),
756    ("dictionary", NormalizedKind::CollectionLiteral),
757    ("tuple", NormalizedKind::TupleLiteral),
758    ("pair", NormalizedKind::ObjectProperty),
759    ("while_statement", NormalizedKind::WhileLoop),
760    // Python's indented suite.
761    ("block", NormalizedKind::Block),
762    ("decorator", NormalizedKind::Decorator),
763    ("comment", NormalizedKind::Comment),
764];
765
766/// Attach `decorators` edges for a definition wrapped in Python's
767/// `decorated_definition` node (which itself is not normalized).
768fn attach_decorators(sink: &mut RoleSink<'_>, definition: Node<'_>) {
769    let Some(parent) = definition.parent() else {
770        return;
771    };
772    if parent.kind() != "decorated_definition" {
773        return;
774    }
775    for index in 0..parent.named_child_count() {
776        let Some(child) = parent.named_child(index) else {
777            continue;
778        };
779        if child.kind() == "decorator" {
780            attach_role_with_derived_name(sink, Role::Decorator, child, expression_name_node);
781        }
782    }
783}
784
785static PYTHON_OCCURRENCE_ROLE_SUPPORT: OccurrenceRoleSupport = OccurrenceRoleSupport::NONE
786    .supported(OccurrenceRole::DeclarationName)
787    .supported(OccurrenceRole::Binder)
788    .supported(OccurrenceRole::LabelOrKey)
789    .supported(OccurrenceRole::TypeOperand)
790    .supported(OccurrenceRole::PathSegment)
791    .supported(OccurrenceRole::ImportAlias)
792    .supported(OccurrenceRole::ImportTarget)
793    .supported(OccurrenceRole::ReceiverPosition)
794    .supported(OccurrenceRole::MemberPosition)
795    .supported(OccurrenceRole::ValueReference)
796    .supported(OccurrenceRole::GlobalDirective)
797    .supported(OccurrenceRole::NonlocalDirective);
798
799/// Whether a `dotted_name` names an imported module rather than an ordinary
800/// attribute chain, which decides whether its tail is an import target.
801///
802/// `relative_import` is the wrapper the grammar puts around the module name of
803/// `from .impl import x`. It is the same import target as the `pkg.impl` of
804/// `from pkg.impl import x`, so it passes through like the other wrappers.
805fn python_dotted_name_is_import(dotted_name: Node<'_>) -> bool {
806    let mut current = dotted_name;
807    loop {
808        let Some(parent) = current.parent() else {
809            return false;
810        };
811        match parent.kind() {
812            "import_statement" | "import_from_statement" | "future_import_statement" => {
813                return true;
814            }
815            "aliased_import" | "dotted_name" | "relative_import" => current = parent,
816            _ => return false,
817        }
818    }
819}
820
821/// Classify one Python identifier token by its AST position.
822///
823/// Python has no separate type-identifier node, so annotation operands are
824/// recognized by their enclosing `type` node — the same field the parser uses
825/// to separate `def f(x: T)`'s binder from its annotation.
826fn python_occurrence_role(node: Node<'_>) -> Option<OccurrenceRole> {
827    if node.kind() != "identifier" {
828        return None;
829    }
830    let parent = node.parent()?;
831    let field = field_name_in_parent(parent, node);
832    let role = match parent.kind() {
833        "global_statement" => OccurrenceRole::GlobalDirective,
834        "nonlocal_statement" => OccurrenceRole::NonlocalDirective,
835        "function_definition" | "class_definition" if field == Some("name") => {
836            OccurrenceRole::DeclarationName
837        }
838        // Every annotation, return type and type-alias operand is wrapped in a
839        // `type` node; `generic_type`/`type_parameter` nest inside one.
840        "type" | "generic_type" | "type_parameter" | "constrained_type" | "union_type" => {
841            OccurrenceRole::TypeOperand
842        }
843        "parameters"
844        | "lambda_parameters"
845        | "typed_parameter"
846        | "list_splat_pattern"
847        | "dictionary_splat_pattern"
848        | "tuple_pattern"
849        | "list_pattern"
850        | "pattern_list"
851        | "as_pattern_target" => OccurrenceRole::Binder,
852        "default_parameter" | "typed_default_parameter" if field == Some("name") => {
853            OccurrenceRole::Binder
854        }
855        "for_statement" | "for_in_clause" if field == Some("left") => OccurrenceRole::Binder,
856        "assignment" if field == Some("left") => OccurrenceRole::Binder,
857        "keyword_argument" if python_keyword_argument_label(node) => OccurrenceRole::LabelOrKey,
858        "attribute" => match field {
859            Some("attribute") => OccurrenceRole::MemberPosition,
860            Some("object") => OccurrenceRole::ReceiverPosition,
861            _ => OccurrenceRole::ValueReference,
862        },
863        "aliased_import" if field == Some("alias") => OccurrenceRole::ImportAlias,
864        "import_from_statement" if field == Some("name") => OccurrenceRole::ImportTarget,
865        "dotted_name" => {
866            let is_tail =
867                parent.named_child(parent.named_child_count().saturating_sub(1)) == Some(node);
868            match (is_tail, python_dotted_name_is_import(parent)) {
869                (true, true) => OccurrenceRole::ImportTarget,
870                (true, false) => OccurrenceRole::ValueReference,
871                (false, _) => OccurrenceRole::PathSegment,
872            }
873        }
874        _ => OccurrenceRole::ValueReference,
875    };
876    Some(role)
877}
878
879/// Whether `node` is the identifier token that binds one formal parameter.
880///
881/// Tree-sitter uses a bare identifier directly under `parameters` or
882/// `lambda_parameters`, and wrapper nodes for annotations, defaults, and
883/// splats. The shared label helper selects the exact name child for each
884/// wrapper so identifiers in annotations/default values do not become
885/// parameter facts.
886fn python_identifier_is_parameter(node: Node<'_>) -> bool {
887    if node.kind() != "identifier" {
888        return false;
889    }
890    let mut current = node;
891    while let Some(parent) = current.parent() {
892        match parent.kind() {
893            "parameters" | "lambda_parameters" => return true,
894            "typed_parameter"
895            | "default_parameter"
896            | "typed_default_parameter"
897            | "list_splat_pattern"
898            | "dictionary_splat_pattern"
899            | "keyword_separator" => {
900                if crate::declarations::python_parameter_label_node(parent) != Some(node) {
901                    return false;
902                }
903                current = parent;
904            }
905            _ => return false,
906        }
907    }
908    false
909}
910
911/// The binding one Python binder token introduces, and the interval it is in
912/// effect over.
913///
914/// Python's function locals are scope-categorical rather than positional: a
915/// name assigned anywhere in a function body is a local of that function for
916/// the whole body, which is why a read above the assignment is an
917/// `UnboundLocalError` rather than a read of an outer name. That is exactly
918/// `ScopeWide`. The one positional exception is a comprehension target, which
919/// lives in the comprehension's own implicit scope; the same exception
920/// `analyzer::python::bindings` records as `PythonComprehensionBinding`.
921fn python_binding_activation(binder: Node<'_>, scope: Range) -> Option<BindingActivation> {
922    // A binder outside every form below is an ordinary assignment target --
923    // the members of a module-level or block-level `a, b = ...` pattern list,
924    // for example -- and Python's scope-categorical rule makes it a local of
925    // its declaring scope for the whole scope. Answering `None` here made the
926    // whole file's lexical environment incomplete as soon as one such binder
927    // existed (scripts/test-cost/greedy.py's `s, k = heapq.heappop(heap)` at
928    // module scope), which failed every code-smells gate that derived it.
929    let Some(form) = nearest_ancestor(binder, |kind| {
930        matches!(
931            kind,
932            "parameters"
933                | "lambda_parameters"
934                | "assignment"
935                | "for_statement"
936                | "for_in_clause"
937                | "as_pattern"
938                | "list_comprehension"
939                | "set_comprehension"
940                | "dictionary_comprehension"
941                | "generator_expression"
942        )
943    }) else {
944        return Some(BindingActivation {
945            kind: BindingKind::Local,
946            hoisting: HoistingClass::ScopeWide,
947            activation: scope,
948        });
949    };
950    match form.kind() {
951        "parameters" | "lambda_parameters" => Some(BindingActivation {
952            kind: BindingKind::Parameter,
953            hoisting: HoistingClass::ScopeWide,
954            activation: scope,
955        }),
956        "assignment" => Some(BindingActivation {
957            kind: BindingKind::Local,
958            hoisting: HoistingClass::ScopeWide,
959            activation: scope,
960        }),
961        "for_in_clause" => {
962            // A comprehension clause binds only inside the comprehension.
963            let comprehension = nearest_ancestor(form, |kind| {
964                matches!(
965                    kind,
966                    "list_comprehension"
967                        | "set_comprehension"
968                        | "dictionary_comprehension"
969                        | "generator_expression"
970                )
971            })?;
972            Some(BindingActivation {
973                kind: BindingKind::LoopVariable,
974                hoisting: HoistingClass::DeclaredHead,
975                activation: node_range(comprehension),
976            })
977        }
978        "for_statement" => Some(BindingActivation {
979            kind: BindingKind::LoopVariable,
980            hoisting: HoistingClass::ScopeWide,
981            activation: scope,
982        }),
983        "as_pattern" => Some(BindingActivation {
984            kind: BindingKind::PatternBinder,
985            hoisting: HoistingClass::ScopeWide,
986            activation: scope,
987        }),
988        _ => Some(BindingActivation {
989            kind: BindingKind::Local,
990            hoisting: HoistingClass::ScopeWide,
991            activation: scope,
992        }),
993    }
994}
995
996/// The text one plain string literal denotes, or `None` when the literal is
997/// not plain: an f-string interpolation, an escape sequence this reader does
998/// not decode, or an implicit concatenation. `None` is never an empty name --
999/// it is "this value is computed", which makes the whole surface unreadable.
1000/// Whether every member of a curated surface was read from the parse tree.
1001#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1002enum ReadableSurface {
1003    Yes,
1004    No,
1005}
1006
1007#[derive(Debug, Clone)]
1008struct PythonExportMember {
1009    name: String,
1010    range: Range,
1011}
1012
1013/// Collect the members of an `__all__` value into `names`, reporting whether
1014/// every member was readable. Only a list or tuple display of plain string
1015/// literals is; anything else is a value the source computes.
1016fn python_collect_all_members(
1017    value: Node<'_>,
1018    source: &str,
1019    members: &mut Vec<PythonExportMember>,
1020) -> ReadableSurface {
1021    if !matches!(value.kind(), "list" | "tuple") {
1022        return ReadableSurface::No;
1023    }
1024    let mut readable = ReadableSurface::Yes;
1025    let mut cursor = value.walk();
1026    for element in value
1027        .named_children(&mut cursor)
1028        .filter(|element| !element.is_extra())
1029    {
1030        match python_plain_string_literal(element, source) {
1031            Some(text) => {
1032                members.push(PythonExportMember {
1033                    name: text.to_owned(),
1034                    range: node_range(element),
1035                });
1036            }
1037            None => readable = ReadableSurface::No,
1038        }
1039    }
1040    readable
1041}
1042
1043fn python_module_export_bindings(
1044    root: Node<'_>,
1045    source: &str,
1046) -> HashMap<Box<str>, SourceExportBinding> {
1047    let mut bindings = Vec::new();
1048    let mut stack = vec![root];
1049    while let Some(node) = stack.pop() {
1050        for binding in python_direct_scope_bindings_bounded(node, source, || true)
1051            .expect("unbounded Python module binding scan completes")
1052        {
1053            let name = node_source_text(binding.declaration, source);
1054            if name.is_empty() {
1055                continue;
1056            }
1057            let kind = match binding.kind {
1058                PythonDirectScopeBindingKind::ClassDeclaration => SourceExportBindingKind::Class,
1059                PythonDirectScopeBindingKind::FunctionDeclaration => {
1060                    SourceExportBindingKind::Function
1061                }
1062                PythonDirectScopeBindingKind::Import => SourceExportBindingKind::Import,
1063                PythonDirectScopeBindingKind::Other => SourceExportBindingKind::Binding,
1064            };
1065            bindings.push(SourceExportBinding {
1066                name: name.to_owned(),
1067                kind,
1068                range: node_range(binding.declaration),
1069            });
1070        }
1071        stack.extend(python_executable_scope_children(node));
1072    }
1073    bindings.sort_unstable_by_key(|binding| binding.range.start_byte);
1074    let mut by_name = HashMap::default();
1075    for binding in bindings {
1076        by_name
1077            .entry(binding.name.clone().into())
1078            .or_insert(binding);
1079    }
1080    by_name
1081}
1082
1083fn python_call_function_name<'a>(node: Node<'_>, source: &'a str) -> Option<&'a str> {
1084    if node.kind() != "call" {
1085        return None;
1086    }
1087    let function = node.child_by_field_name("function")?;
1088    (function.kind() == "identifier").then(|| node_source_text(function, source))
1089}
1090
1091fn python_current_module_expression(
1092    expression: Node<'_>,
1093    source: &str,
1094    sys_bindings: &HashSet<Box<str>>,
1095    module_aliases: &HashSet<Box<str>>,
1096) -> bool {
1097    let expression = python_unwrap_parenthesized(expression);
1098    if expression.kind() == "identifier"
1099        && module_aliases.contains(node_source_text(expression, source))
1100    {
1101        return true;
1102    }
1103    if expression.kind() == "subscript"
1104        && let (Some(value), Some(subscript)) = (
1105            expression.child_by_field_name("value"),
1106            expression.child_by_field_name("subscript"),
1107        )
1108        && subscript.kind() == "identifier"
1109        && node_source_text(subscript, source) == "__name__"
1110        && value.kind() == "attribute"
1111        && value
1112            .child_by_field_name("attribute")
1113            .is_some_and(|attribute| node_source_text(attribute, source) == "modules")
1114        && value.child_by_field_name("object").is_some_and(|object| {
1115            object.kind() == "identifier" && sys_bindings.contains(node_source_text(object, source))
1116        })
1117    {
1118        return true;
1119    }
1120    python_call_function_name(expression, source) == Some("__import__")
1121        && expression
1122            .child_by_field_name("arguments")
1123            .and_then(python_first_named_operand)
1124            .is_some_and(|argument| {
1125                argument.kind() == "identifier" && node_source_text(argument, source) == "__name__"
1126            })
1127}
1128
1129fn python_module_definition_is_dynamic(root: Node<'_>, source: &str) -> bool {
1130    let sys_bindings: HashSet<Box<str>> = python_import_bindings_from_tree(root, source)
1131        .into_iter()
1132        .filter(|binding| binding.qualified_name == "sys")
1133        .map(|binding| binding.local_name.into_boxed_str())
1134        .collect();
1135    let mut assignments = Vec::new();
1136    let mut pending = vec![root];
1137    while let Some(node) = pending.pop() {
1138        if node.kind() == "assignment"
1139            && let (Some(left), Some(right)) = (
1140                node.child_by_field_name("left"),
1141                node.child_by_field_name("right"),
1142            )
1143            && left.kind() == "identifier"
1144        {
1145            assignments.push((node.start_byte(), left, right));
1146        }
1147        let mut cursor = node.walk();
1148        pending.extend(node.named_children(&mut cursor));
1149    }
1150    assignments.sort_unstable_by_key(|(start, _, _)| *start);
1151    let mut module_aliases = HashSet::default();
1152    for (_, left, right) in assignments {
1153        if python_current_module_expression(right, source, &sys_bindings, &module_aliases) {
1154            module_aliases.insert(node_source_text(left, source).into());
1155        }
1156    }
1157
1158    let mut pending = vec![root];
1159    while let Some(node) = pending.pop() {
1160        if node.kind() == "wildcard_import"
1161            || python_call_function_name(node, source) == Some("globals")
1162        {
1163            return true;
1164        }
1165        if python_call_function_name(node, source) == Some("setattr")
1166            && node
1167                .child_by_field_name("arguments")
1168                .and_then(python_first_named_operand)
1169                .is_some_and(|object| {
1170                    python_current_module_expression(object, source, &sys_bindings, &module_aliases)
1171                })
1172        {
1173            return true;
1174        }
1175        let mut cursor = node.walk();
1176        pending.extend(node.named_children(&mut cursor));
1177    }
1178    root.has_error()
1179}
1180
1181/// Parse the source-backed member rows for the module's explicit `__all__`.
1182///
1183/// Known literals are retained if another member makes the complete surface
1184/// unreadable. The materialization query then returns those useful rows and
1185/// reports that absence of additional rows is not proof of completeness.
1186fn python_source_export_facts(root: Node<'_>, source: &str) -> SourceExportFacts {
1187    let names_all = |node: Option<Node<'_>>| {
1188        node.is_some_and(|node| {
1189            node.kind() == "identifier" && node_source_text(node, source) == "__all__"
1190        })
1191    };
1192    let mut members = Vec::new();
1193    let mut stated = false;
1194    let mut readable = ReadableSurface::Yes;
1195    let module_bindings = python_module_export_bindings(root, source);
1196    let definitions_complete = !python_module_definition_is_dynamic(root, source);
1197    let mut cursor = root.walk();
1198    for statement in root.named_children(&mut cursor) {
1199        if statement.kind() == "ERROR"
1200            && crate::syntax::python_contains_all_identifier(statement, source)
1201        {
1202            stated = true;
1203            readable = ReadableSurface::No;
1204            continue;
1205        }
1206        if statement.kind() != "expression_statement" {
1207            continue;
1208        }
1209        let mut inner = statement.walk();
1210        for expression in statement.named_children(&mut inner) {
1211            match expression.kind() {
1212                "ERROR" if crate::syntax::python_contains_all_identifier(expression, source) => {
1213                    stated = true;
1214                    readable = ReadableSurface::No;
1215                }
1216                "assignment" | "augmented_assignment" => {
1217                    if !names_all(expression.child_by_field_name("left")) {
1218                        continue;
1219                    }
1220                    stated = true;
1221                    let Some(value) = expression.child_by_field_name("right") else {
1222                        let mut cursor = expression.walk();
1223                        let has_assignment_operator = expression
1224                            .children(&mut cursor)
1225                            .any(|child| child.kind() == "=");
1226                        let annotation_only = expression.kind() == "assignment"
1227                            && expression.child_by_field_name("type").is_some()
1228                            && !has_assignment_operator
1229                            && !expression.has_error();
1230                        if !annotation_only {
1231                            readable = ReadableSurface::No;
1232                        }
1233                        continue;
1234                    };
1235                    if expression.kind() == "assignment" {
1236                        members.clear();
1237                        readable = ReadableSurface::Yes;
1238                    }
1239                    let extends = expression.kind() == "assignment"
1240                        || expression
1241                            .child_by_field_name("operator")
1242                            .is_some_and(|operator| operator.kind() == "+=");
1243                    if !extends {
1244                        members.clear();
1245                    }
1246                    if !extends
1247                        || python_collect_all_members(value, source, &mut members)
1248                            == ReadableSurface::No
1249                    {
1250                        readable = ReadableSurface::No;
1251                    }
1252                }
1253                "call" => {
1254                    let Some(function) = expression.child_by_field_name("function") else {
1255                        continue;
1256                    };
1257                    if function.kind() == "attribute"
1258                        && names_all(function.child_by_field_name("object"))
1259                    {
1260                        stated = true;
1261                        members.clear();
1262                        readable = ReadableSurface::No;
1263                    }
1264                }
1265                _ => {}
1266            }
1267        }
1268    }
1269
1270    let mut names = HashSet::default();
1271    let exports = if stated {
1272        members
1273            .into_iter()
1274            .filter(|member| names.insert(member.name.clone()))
1275            .map(|member| {
1276                let local_definition = match module_bindings.get(member.name.as_str()) {
1277                    Some(binding) => SourceExportLocalDefinition::Defined {
1278                        binding: binding.clone(),
1279                    },
1280                    None if definitions_complete => SourceExportLocalDefinition::Undefined,
1281                    None => SourceExportLocalDefinition::Unknown,
1282                };
1283                SourceExportFact {
1284                    range: member.range,
1285                    exported_name: member.name,
1286                    local_definition,
1287                }
1288            })
1289            .collect()
1290    } else {
1291        Vec::new()
1292    };
1293    SourceExportFacts {
1294        exports,
1295        declared: stated,
1296        complete: !stated || readable == ReadableSurface::Yes,
1297        definitions_complete,
1298    }
1299}
1300
1301/// The names a Python module curates as its public surface: the value of its
1302/// module-level `__all__`.
1303///
1304/// Only the module's own statements are read. An `__all__` inside a function
1305/// is a local rather than the module's surface, and a name the module binds
1306/// conditionally is still bound by the statement this reader already sees.
1307/// A statement that assigns, extends, or mutates `__all__` with anything but a
1308/// list or tuple of plain string literals makes the surface unreadable: the
1309/// remaining members are unknown, while known literal members are retained.
1310fn python_curated_export_surface(root: Node<'_>, source: &str) -> CuratedExportSurface {
1311    let facts = python_source_export_facts(root, source);
1312    if !facts.declared {
1313        return CuratedExportSurface::Absent;
1314    }
1315    let names = facts
1316        .exports
1317        .into_iter()
1318        .map(|export| export.exported_name)
1319        .collect();
1320    if facts.complete {
1321        CuratedExportSurface::Listed(names)
1322    } else {
1323        CuratedExportSurface::PartiallyListed(names)
1324    }
1325}
1326
1327/// Which indirection relation one Python import token participates in.
1328///
1329/// Python's grammar names no re-export, so the relation follows the explicit
1330/// re-export rules the typing ecosystem already enforces (PEP 484 stub
1331/// semantics, applied by pyright and mypy in strict mode), which makes this
1332/// relation agree with what a type checker calls public:
1333///
1334/// 1. A name on the module's `__all__` is a re-export of whatever binding the
1335///    module gives that name.
1336/// 2. The redundant-alias forms `from x import y as y` and `import x as x`
1337///    are re-exports.
1338/// 3. `from x import *` is one star hop that forwards the public surface of
1339///    `x`; the expansion is the import machinery's work, not this producer's,
1340///    so the hop is recorded on the module reference and nothing is
1341///    enumerated here.
1342/// 4. Every other import is an ordinary import, including a plain
1343///    `from .impl import helper` in a package `__init__.py` that states no
1344///    `__all__`. The facade convention alone does not make a name public, and
1345///    a consumer that wants every name a facade imports already has the
1346///    import relation.
1347///
1348/// `None` is the answer for a name whose membership only an unreadable
1349/// `__all__` could settle; the file's relations then report incomplete rather
1350/// than guessing either way.
1351fn python_indirection_relation(
1352    token: Node<'_>,
1353    source: &str,
1354    surface: &CuratedExportSurface,
1355) -> Option<RouteHopKind> {
1356    let statement = nearest_ancestor(token, |kind| {
1357        matches!(
1358            kind,
1359            "import_statement" | "import_from_statement" | "future_import_statement"
1360        )
1361    })?;
1362    // The statement's own child that holds this token: a `module_name` field,
1363    // or one `name` field of the import list.
1364    let mut clause = token;
1365    while let Some(parent) = clause.parent() {
1366        if parent.id() == statement.id() {
1367            break;
1368        }
1369        clause = parent;
1370    }
1371
1372    if field_name_in_parent(statement, clause) == Some("module_name") {
1373        // `from x import a` binds `a`, not `x`, so the module reference
1374        // forwards nothing -- unless the import is the star form, whose one
1375        // hop forwards the whole surface of `x`.
1376        let mut cursor = statement.walk();
1377        let star = statement
1378            .children(&mut cursor)
1379            .any(|child| child.kind() == "wildcard_import");
1380        return Some(if star {
1381            RouteHopKind::ReExport
1382        } else {
1383            RouteHopKind::Import
1384        });
1385    }
1386
1387    let bound = match clause.kind() {
1388        "aliased_import" => {
1389            let name = clause.child_by_field_name("name")?;
1390            let alias = clause.child_by_field_name("alias")?;
1391            if node_source_text(name, source) == node_source_text(alias, source) {
1392                return Some(RouteHopKind::ReExport);
1393            }
1394            alias
1395        }
1396        // `import a.b.c` binds the top package `a`; `from m import a` binds
1397        // the single-segment name the import list spells.
1398        "dotted_name" if statement.kind() == "import_statement" => clause.named_child(0)?,
1399        "dotted_name" => clause,
1400        _ => return None,
1401    };
1402    match surface.lists(node_source_text(bound, source)) {
1403        Some(true) => Some(RouteHopKind::ReExport),
1404        Some(false) => Some(RouteHopKind::Import),
1405        None => None,
1406    }
1407}
1408
1409/// Grammar steps for the shared call-callee spine. A value expression has no step.
1410pub fn callee_spine_step(kind: &str) -> Option<CalleeSpineStep> {
1411    use CalleeSpineStep::{Field, Name};
1412    match kind {
1413        "identifier" => Some(Name),
1414        "attribute" => Some(Field("attribute")),
1415        _ => None,
1416    }
1417}
1418
1419impl StructuralSpec for PythonStructuralSpec {
1420    fn language(&self) -> Language {
1421        Language::Python
1422    }
1423
1424    fn supports_boolean_literal_value(&self) -> bool {
1425        true
1426    }
1427
1428    fn supports_string_literal_parenthesized(&self) -> bool {
1429        true
1430    }
1431
1432    fn supports_string_literal_value(&self) -> bool {
1433        true
1434    }
1435
1436    fn string_literal_value(&self, node: Node<'_>, source: &str) -> Option<String> {
1437        python_string_key_value(node, source)
1438    }
1439
1440    fn supports_assignment_shape(&self) -> bool {
1441        true
1442    }
1443
1444    fn assignment_shape(&self, node: Node<'_>) -> Option<AssignmentShape> {
1445        python_assignment_shape(node)
1446    }
1447
1448    fn supports_integer_literal_value(&self) -> bool {
1449        true
1450    }
1451
1452    fn integer_literal_value(&self, node: Node<'_>, source: &str) -> Option<IntegerLiteralValue> {
1453        python_integer_literal_value(node, source)
1454    }
1455
1456    fn supports_duplicate_dictionary_keys(&self) -> bool {
1457        true
1458    }
1459
1460    fn duplicate_dictionary_key(&self, node: Node<'_>, source: &str) -> Option<bool> {
1461        python_duplicate_dictionary_key(node, source)
1462    }
1463
1464    fn string_literal_parenthesized(&self, node: Node<'_>) -> Option<bool> {
1465        if !matches!(node.kind(), "string" | "concatenated_string") {
1466            return None;
1467        }
1468        let mut current = node;
1469        let mut parenthesized = false;
1470        while let Some(parent) = current.parent() {
1471            if parent.kind() != "parenthesized_expression" {
1472                break;
1473            }
1474            assert_eq!(python_parenthesized_expression_child(parent), Some(current));
1475            current = parent;
1476            parenthesized = true;
1477        }
1478        Some(parenthesized)
1479    }
1480
1481    fn reference_edge_support(&self) -> &ReferenceEdgeSupport {
1482        &DEEP_REFERENCE_EDGE_SUPPORT
1483    }
1484
1485    fn identity_route_support(&self) -> &IdentityRouteSupport {
1486        // `import x as y` is an alias, and `python_indirection_relation`
1487        // states which imports re-export (issue #1649).
1488        static SUPPORT: IdentityRouteSupport = DEEP_IDENTITY_AXES
1489            .supported_relation(RouteHopKind::Alias)
1490            .supported_relation(RouteHopKind::Import)
1491            .supported_relation(RouteHopKind::Export)
1492            .supported_relation(RouteHopKind::ReExport)
1493            .supported_relation(RouteHopKind::NestedOwner);
1494        &SUPPORT
1495    }
1496
1497    /// Python's one qualified-path chain is `dotted_name`, which is flat
1498    /// rather than left-nested: its named children are the segments in order.
1499    fn qualified_path_root<'tree>(&self, token: Node<'tree>) -> Option<Node<'tree>> {
1500        if token.kind() != "identifier" {
1501            return None;
1502        }
1503        token
1504            .parent()
1505            .filter(|parent| parent.kind() == "dotted_name")
1506    }
1507
1508    fn path_segment_tokens<'tree>(&self, root: Node<'tree>) -> Vec<Node<'tree>> {
1509        if root.kind() != "dotted_name" {
1510            return Vec::new();
1511        }
1512        let mut cursor = root.walk();
1513        root.named_children(&mut cursor)
1514            .filter(|child| child.kind() == "identifier")
1515            .collect()
1516    }
1517
1518    fn curated_export_surface(&self, root: Node<'_>, source: &str) -> CuratedExportSurface {
1519        python_curated_export_surface(root, source)
1520    }
1521
1522    fn indirection_relation(
1523        &self,
1524        token: Node<'_>,
1525        source: &str,
1526        surface: &CuratedExportSurface,
1527    ) -> Option<RouteHopKind> {
1528        python_indirection_relation(token, source, surface)
1529    }
1530
1531    fn scope_formation(&self, kind: NormalizedKind) -> ScopeFormation {
1532        match kind {
1533            // The normalized module fact is the file root, not a nested scope.
1534            // Top-level imports and assignments belong to the synthetic file scope.
1535            NormalizedKind::Module => ScopeFormation::NotAScope,
1536            // Python blocks do not introduce local-variable scopes. Names
1537            // assigned in an if/loop/try body remain function or module locals.
1538            NormalizedKind::Block | NormalizedKind::ForLoop | NormalizedKind::WhileLoop => {
1539                ScopeFormation::NotAScope
1540            }
1541            _ => default_scope_formation(kind),
1542        }
1543    }
1544
1545    fn extra_emitted_kinds(&self) -> &'static [NormalizedKind] {
1546        // Refinement and embedded regex facts beyond the grammar kind table.
1547        &[
1548            NormalizedKind::ComparisonChain,
1549            NormalizedKind::Method,
1550            NormalizedKind::Parameter,
1551            NormalizedKind::RegexAlternation,
1552            NormalizedKind::RegexAnchor,
1553            NormalizedKind::RegexCharacterClass,
1554            NormalizedKind::RegexCharacterRange,
1555            NormalizedKind::RegexEscape,
1556            NormalizedKind::RegexGroup,
1557            NormalizedKind::RegexIncomplete,
1558            NormalizedKind::RegexLiteral,
1559            NormalizedKind::RegexPattern,
1560            NormalizedKind::RegexQuantifier,
1561            NormalizedKind::RegexRiskBackspaceEscape,
1562            NormalizedKind::RegexRiskBadTag,
1563            NormalizedKind::RegexRiskDuplicateClassCharacter,
1564            NormalizedKind::RegexRiskExponential,
1565            NormalizedKind::RegexRiskHostname,
1566            NormalizedKind::RegexRiskIncompleteSpecialGroup,
1567            NormalizedKind::RegexRiskPolynomial,
1568            NormalizedKind::RegexRiskRange,
1569            NormalizedKind::RegexRiskUnmatchableCaret,
1570            NormalizedKind::RegexRiskUnmatchableDollar,
1571            NormalizedKind::RegexSequence,
1572            NormalizedKind::RegexWildcard,
1573        ]
1574    }
1575
1576    fn kind_table(&self) -> &'static [(&'static str, NormalizedKind)] {
1577        PYTHON_KIND_TABLE
1578    }
1579
1580    fn refine_kind(
1581        &self,
1582        node: Node<'_>,
1583        kind: NormalizedKind,
1584        _enclosing: Option<NormalizedKind>,
1585        _source: &str,
1586        _context: &CallSiteContext,
1587    ) -> NormalizedKind {
1588        match kind {
1589            NormalizedKind::Identifier if python_identifier_is_parameter(node) => {
1590                NormalizedKind::Parameter
1591            }
1592            NormalizedKind::Function if crate::syntax::python_method_owner(node).is_some() => {
1593                NormalizedKind::Method
1594            }
1595            NormalizedKind::Comparison if python_comparison_shape(node).operator_count > 1 => {
1596                NormalizedKind::ComparisonChain
1597            }
1598            _ => kind,
1599        }
1600    }
1601
1602    fn should_extract(&self, node: Node<'_>, kind: NormalizedKind) -> bool {
1603        if kind == NormalizedKind::Module && node.byte_range().is_empty() {
1604            return false;
1605        }
1606        match node.kind() {
1607            "parenthesized_expression" | "unary_operator" => {
1608                kind == NormalizedKind::Literal && python_comparison_constant(node)
1609            }
1610            _ => kind != NormalizedKind::Assignment || node.child_by_field_name("right").is_some(),
1611        }
1612    }
1613
1614    fn supports_kind(&self, kind: NormalizedKind) -> bool {
1615        brokk_bifrost_core::analyzer::structural::spec::supports_kind_from_table(
1616            kind,
1617            &[
1618                NormalizedKind::Method,
1619                // Module facts select the parser's file root for Python policies.
1620                NormalizedKind::Module,
1621                NormalizedKind::Parameter,
1622                NormalizedKind::SyntaxError,
1623                NormalizedKind::ComparisonChain,
1624                NormalizedKind::RegexPattern,
1625                NormalizedKind::RegexSequence,
1626                NormalizedKind::RegexGroup,
1627                NormalizedKind::RegexAlternation,
1628                NormalizedKind::RegexCharacterClass,
1629                NormalizedKind::RegexCharacterRange,
1630                NormalizedKind::RegexQuantifier,
1631                NormalizedKind::RegexAnchor,
1632                NormalizedKind::RegexEscape,
1633                NormalizedKind::RegexLiteral,
1634                NormalizedKind::RegexWildcard,
1635                NormalizedKind::RegexRiskHostname,
1636                NormalizedKind::RegexRiskRange,
1637                NormalizedKind::RegexRiskBadTag,
1638                NormalizedKind::RegexRiskExponential,
1639                NormalizedKind::RegexIncomplete,
1640                NormalizedKind::RegexRiskBackspaceEscape,
1641                NormalizedKind::RegexRiskDuplicateClassCharacter,
1642                NormalizedKind::RegexRiskUnmatchableCaret,
1643                NormalizedKind::RegexRiskUnmatchableDollar,
1644                NormalizedKind::RegexRiskIncompleteSpecialGroup,
1645                NormalizedKind::RegexRiskPolynomial,
1646            ],
1647            self.kind_table(),
1648        )
1649    }
1650
1651    fn occurrence_role_support(&self) -> &OccurrenceRoleSupport {
1652        &PYTHON_OCCURRENCE_ROLE_SUPPORT
1653    }
1654
1655    fn lexical_environment_support(&self) -> &LexicalEnvironmentSupport {
1656        &DEEP_LEXICAL_ENVIRONMENT_SUPPORT
1657    }
1658
1659    fn materialization_support(&self) -> &DeclarationMaterializationSupport {
1660        &PYTHON_MATERIALIZATION_SUPPORT
1661    }
1662
1663    fn source_export_facts(&self, root: Node<'_>, source: &str) -> Option<SourceExportFacts> {
1664        Some(python_source_export_facts(root, source))
1665    }
1666
1667    fn binding_activation(&self, binder: Node<'_>, scope: Range) -> Option<BindingActivation> {
1668        python_binding_activation(binder, scope)
1669    }
1670
1671    /// Python only classifies a scope segment inside a `dotted_name`, and every
1672    /// non-tail segment of a dotted name is a module.
1673    fn occurrence_namespace(
1674        &self,
1675        role: OccurrenceRole,
1676        declares: Option<NormalizedKind>,
1677    ) -> Option<Namespace> {
1678        module_path_occurrence_namespace(role, declares)
1679    }
1680
1681    fn embedded_leaf_facts(
1682        &self,
1683        node: Node<'_>,
1684        kind: NormalizedKind,
1685        source: &str,
1686        cancellation: Option<&CancellationToken>,
1687    ) -> Vec<EmbeddedLeafFact> {
1688        if kind == NormalizedKind::Module {
1689            return crate::regex::module_assigned_facts(node, source);
1690        }
1691        if kind == NormalizedKind::Call {
1692            return crate::regex::embedded_facts(node, source);
1693        }
1694        if kind != NormalizedKind::StringLiteral {
1695            return Vec::new();
1696        }
1697
1698        let mut facts = crate::regex::embedded_facts(node, source);
1699        if node.kind() != "string" || !python_node_is_in_annotation(node) {
1700            return facts;
1701        }
1702
1703        facts.extend(
1704            python_deferred_annotation_identifier_ranges(node, source, cancellation)
1705                .unwrap_or_default()
1706                .into_iter()
1707                .map(|range| EmbeddedLeafFact {
1708                    kind: NormalizedKind::Identifier,
1709                    range,
1710                    parent: None,
1711                    construct: None,
1712                    occurrence_role: Some(OccurrenceRole::TypeOperand),
1713                }),
1714        );
1715        facts
1716    }
1717
1718    fn comparison_operator_spans(
1719        &self,
1720        node: Node<'_>,
1721        step: &mut dyn FnMut() -> bool,
1722    ) -> Option<Vec<Span>> {
1723        if !step() || node.kind() != "comparison_operator" || node.has_error() || node.is_missing()
1724        {
1725            return None;
1726        }
1727        let mut operators = Vec::new();
1728        let mut operands = 0usize;
1729        let complete = visit_python_comparison_children(node, |child, is_operator| {
1730            if !step() || child.is_missing() || child.has_error() {
1731                return false;
1732            }
1733            if is_operator {
1734                if child.start_byte() >= child.end_byte() {
1735                    return false;
1736                }
1737                operators.push(Span {
1738                    start_byte: child.start_byte(),
1739                    end_byte: child.end_byte(),
1740                });
1741            } else if child.is_named() && !child.is_extra() {
1742                operands += 1;
1743            }
1744            true
1745        });
1746        (complete
1747            && !operators.is_empty()
1748            && operands == operators.len().saturating_add(1)
1749            && step())
1750        .then_some(operators)
1751    }
1752
1753    fn extract(&self, node: Node<'_>, kind: NormalizedKind, sink: &mut RoleSink<'_>) {
1754        if let Some(role) = python_occurrence_role(node) {
1755            sink.occurrence_role(node, role);
1756        }
1757        match kind {
1758            NormalizedKind::Call => {
1759                if let Some(function) = node.child_by_field_name("function") {
1760                    // A call's own name is its callee's, so
1761                    // { "kind": "call", "name": "eval" } reads naturally.
1762                    attach_terminal_callee(
1763                        sink,
1764                        function,
1765                        terminal_callee_leaf(function, callee_spine_step),
1766                    );
1767                    if function.kind() == "attribute"
1768                        && let Some(object) = function.child_by_field_name("object")
1769                    {
1770                        attach_role_with_derived_name(
1771                            sink,
1772                            Role::Receiver,
1773                            object,
1774                            expression_name_node,
1775                        );
1776                    }
1777                }
1778                if let Some(arguments) = node.child_by_field_name("arguments") {
1779                    attach_python_argument_roles(sink, arguments);
1780                }
1781            }
1782            NormalizedKind::FieldAccess => {
1783                if let Some(attribute) = node.child_by_field_name("attribute") {
1784                    sink.set_name(attribute);
1785                    sink.role_named(Role::Field, attribute, attribute);
1786                }
1787                if let Some(object) = node.child_by_field_name("object") {
1788                    attach_role_with_derived_name(sink, Role::Object, object, expression_name_node);
1789                }
1790            }
1791            NormalizedKind::Function | NormalizedKind::Method | NormalizedKind::Class => {
1792                if let Some(name) = node.child_by_field_name("name") {
1793                    sink.set_name(name);
1794                }
1795                attach_decorators(sink, node);
1796            }
1797            NormalizedKind::Assignment => {
1798                if let Some(left) = node.child_by_field_name("left") {
1799                    attach_role_with_derived_name(
1800                        sink,
1801                        Role::Left,
1802                        left,
1803                        python_assignment_name_node,
1804                    );
1805                    add_python_assignment_names(sink, left);
1806                }
1807                if let Some(right) = node.child_by_field_name("right") {
1808                    attach_role_with_derived_name(sink, Role::Right, right, expression_name_node);
1809                }
1810            }
1811            NormalizedKind::BinaryExpression => {
1812                if let Some(left) = node.child_by_field_name("left") {
1813                    attach_role_with_derived_name(sink, Role::Left, left, expression_name_node);
1814                }
1815                if let Some(right) = node.child_by_field_name("right") {
1816                    attach_role_with_derived_name(sink, Role::Right, right, expression_name_node);
1817                }
1818                if let Some(operator) = node.child_by_field_name("operator") {
1819                    sink.role_named(Role::Operator, operator, operator);
1820                }
1821            }
1822            NormalizedKind::Comparison => {
1823                let shape = python_comparison_shape(node);
1824                if shape.operator_count == 1 && shape.operand_count == 2 {
1825                    if let Some(left) = shape.left {
1826                        attach_role_with_derived_name(sink, Role::Left, left, expression_name_node);
1827                    }
1828                    if let Some(right) = shape.right {
1829                        attach_role_with_derived_name(
1830                            sink,
1831                            Role::Right,
1832                            right,
1833                            expression_name_node,
1834                        );
1835                    }
1836                    if let Some(operator) = shape.operator {
1837                        sink.role_named(Role::Operator, operator, operator);
1838                    }
1839                }
1840            }
1841            NormalizedKind::Assertion => {
1842                if let Some(test) = python_first_named_operand(node) {
1843                    sink.role(Role::Test, test);
1844                }
1845            }
1846            NormalizedKind::If => {
1847                // The grammar names the `if` statement condition, but its
1848                // conditional expression has no fields: its three named
1849                // operands are value, condition, and alternative. Grammar
1850                // extras (`comment`, `line_continuation`) can be interleaved
1851                // between them, so select among the operands (#4797).
1852                let test = if node.kind() == "conditional_expression" {
1853                    let [consequence, test, alternative] =
1854                        python_conditional_expression_operands(node)
1855                            .expect("conditional expression operands");
1856                    sink.role(Role::Consequence, consequence);
1857                    sink.role(Role::Alternative, alternative);
1858                    Some(test)
1859                } else {
1860                    node.child_by_field_name("condition")
1861                };
1862                if let Some(test) = test {
1863                    sink.role(Role::Test, test);
1864                }
1865            }
1866            NormalizedKind::Return => {
1867                if let Some(value) = python_first_named_operand(node) {
1868                    sink.role(Role::Value, value);
1869                }
1870            }
1871            NormalizedKind::Throw => {
1872                if let Some(value) = python_first_named_operand(node) {
1873                    sink.role(Role::Value, value);
1874                }
1875            }
1876            NormalizedKind::Import => match node.kind() {
1877                "import_from_statement" => {
1878                    if let Some(module) = node.child_by_field_name("module_name") {
1879                        sink.role_named(Role::Module, module, module);
1880                    }
1881                }
1882                _ => {
1883                    for index in 0..node.named_child_count() {
1884                        if !sink.should_continue() {
1885                            break;
1886                        }
1887                        let Some(child) = node.named_child(index) else {
1888                            continue;
1889                        };
1890                        match child.kind() {
1891                            "dotted_name" => sink.role_named(Role::Module, child, child),
1892                            "aliased_import" => {
1893                                if let Some(name) = child.child_by_field_name("name") {
1894                                    sink.role_named(Role::Module, name, name);
1895                                }
1896                            }
1897                            _ => {}
1898                        }
1899                    }
1900                }
1901            },
1902            NormalizedKind::Identifier | NormalizedKind::Parameter => sink.set_name(node),
1903            NormalizedKind::Decorator => {
1904                if let Some(name) = python_first_named_operand(node)
1905                    .map(python_unwrap_parenthesized)
1906                    .and_then(expression_name_node)
1907                {
1908                    sink.set_name(name);
1909                }
1910                if let Some(call) = python_first_named_operand(node)
1911                    .map(python_unwrap_parenthesized)
1912                    .filter(|child| child.kind() == "call")
1913                    && let Some(arguments) = call.child_by_field_name("arguments")
1914                {
1915                    attach_python_argument_roles(sink, arguments);
1916                }
1917            }
1918            NormalizedKind::ForLoop => {
1919                if let Some(right) = node.child_by_field_name("right") {
1920                    attach_role_with_derived_name(
1921                        sink,
1922                        Role::Iterable,
1923                        right,
1924                        expression_name_node,
1925                    );
1926                }
1927            }
1928            NormalizedKind::CollectionLiteral
1929            | NormalizedKind::TupleLiteral
1930            | NormalizedKind::ListLiteral => {
1931                for index in 0..node.named_child_count() {
1932                    let Some(child) = node.named_child(index) else {
1933                        continue;
1934                    };
1935                    if child.is_extra() {
1936                        continue;
1937                    }
1938                    let element = python_unwrap_parenthesized(child);
1939                    attach_role_with_derived_name(
1940                        sink,
1941                        Role::Element,
1942                        element,
1943                        expression_name_node,
1944                    );
1945                }
1946            }
1947            NormalizedKind::ObjectProperty => {
1948                if let Some(key) = node.child_by_field_name("key") {
1949                    sink.role(Role::Key, key);
1950                }
1951                if let Some(value) = node.child_by_field_name("value") {
1952                    sink.role(Role::Value, value);
1953                }
1954            }
1955            NormalizedKind::StringLiteral if node.kind() == "concatenated_string" => {
1956                for index in 0..node.named_child_count() {
1957                    let Some(part) = node.named_child(index) else {
1958                        continue;
1959                    };
1960                    if part.kind() == "string" {
1961                        sink.role(Role::Part, part);
1962                    }
1963                }
1964            }
1965            _ => {}
1966        }
1967    }
1968}
1969
1970#[cfg(test)]
1971mod tests {
1972    use super::*;
1973    use brokk_bifrost_test_macros::hardwon;
1974
1975    fn node_of_kind<'tree>(root: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
1976        let mut pending = vec![root];
1977        while let Some(node) = pending.pop() {
1978            if node.kind() == kind {
1979                return Some(node);
1980            }
1981            let mut cursor = node.walk();
1982            pending.extend(node.named_children(&mut cursor));
1983        }
1984        None
1985    }
1986
1987    fn string_literal_parenthesization(root: Node<'_>) -> (usize, usize) {
1988        let mut pending = vec![root];
1989        let mut string_count = 0;
1990        let mut parenthesized_count = 0;
1991        while let Some(node) = pending.pop() {
1992            if matches!(node.kind(), "string" | "concatenated_string") {
1993                string_count += 1;
1994                if PYTHON_STRUCTURAL_SPEC
1995                    .string_literal_parenthesized(node)
1996                    .expect("Python string-literal parenthesization is supported")
1997                {
1998                    parenthesized_count += 1;
1999                }
2000            }
2001            let mut cursor = node.walk();
2002            pending.extend(node.named_children(&mut cursor));
2003        }
2004        (string_count, parenthesized_count)
2005    }
2006
2007    fn parse_python(source: &str) -> tree_sitter::Tree {
2008        crate::declarations::parse_python_tree(source).expect("Python source tree")
2009    }
2010
2011    #[test]
2012    #[hardwon(
2013        "6b123df7cc68: quicksilver round 6 on brokk-bifrost-python: __all__ replacement retained old exports"
2014    )]
2015    fn qs6_all_replacement_and_extension() {
2016        for (source, expected) in [
2017            ("__all__ = ['old']\n__all__ = ['new']\n", vec!["new"]),
2018            (
2019                "__all__ = ['old']\n__all__ += ['new']\n",
2020                vec!["old", "new"],
2021            ),
2022            ("__all__ = computed\n__all__ = ['new']\n", vec!["new"]),
2023        ] {
2024            let tree = parse_python(source);
2025            let facts = python_source_export_facts(tree.root_node(), source);
2026            assert_eq!(
2027                facts
2028                    .exports
2029                    .iter()
2030                    .map(|e| e.exported_name.as_str())
2031                    .collect::<Vec<_>>(),
2032                expected
2033            );
2034            assert!(facts.complete, "{source}: {facts:?}");
2035        }
2036    }
2037
2038    #[test]
2039    #[hardwon(
2040        "6b123df7cc68: quicksilver round 6 on brokk-bifrost-python: named extras made literal exports and concatenations unreadable"
2041    )]
2042    fn qs6_literal_extras_grammar_boundary() {
2043        let source =
2044            "__all__ = [\n 'first', # comment\n 'second',\n]\nVALUE = ('a' # comment\n 'b')\n";
2045        let tree = parse_python(source);
2046        assert!(!tree.root_node().has_error());
2047        let facts = python_source_export_facts(tree.root_node(), source);
2048        assert!(facts.complete, "{facts:?}");
2049        assert_eq!(
2050            facts
2051                .exports
2052                .iter()
2053                .map(|e| e.exported_name.as_str())
2054                .collect::<Vec<_>>(),
2055            ["first", "second"]
2056        );
2057        let concat = node_of_kind(tree.root_node(), "concatenated_string").unwrap();
2058        assert_eq!(
2059            python_string_key_value(concat, source).as_deref(),
2060            Some("ab")
2061        );
2062    }
2063
2064    #[test]
2065    fn qs6_structural_literal_grammar_matrix() {
2066        // Expected values follow CPython ast literal values; f/named-escape
2067        // strings remain unsupported rather than inventing a decoded value.
2068        for (literal, expected) in [
2069            (r#""{{key}}""#, Some("{{key}}")),
2070            (r#""{key}""#, Some("{key}")),
2071            (r#"f"{{key}}""#, None),
2072            (r#"f"plain""#, None),
2073            (r#"f"{key}""#, None),
2074            (r#""\N{LATIN CAPITAL LETTER A}""#, None),
2075            (r#""A""#, Some("A")),
2076            (
2077                r#""\n{LATIN CAPITAL LETTER A}""#,
2078                Some("\n{LATIN CAPITAL LETTER A}"),
2079            ),
2080        ] {
2081            let source = format!("value = {literal}\n");
2082            let tree = parse_python(&source);
2083            let node = node_of_kind(tree.root_node(), "string").unwrap();
2084            assert_eq!(
2085                python_string_key_value(node, &source).as_deref(),
2086                expected,
2087                "{literal}"
2088            );
2089        }
2090        for (rhs, kind, count, starred) in [
2091            ("[1, 2]", AssignmentSequenceKind::List, 2, false),
2092            ("(1, 2)", AssignmentSequenceKind::Tuple, 2, false),
2093            ("1, 2", AssignmentSequenceKind::Tuple, 2, false),
2094            ("[1, *items]", AssignmentSequenceKind::List, 1, true),
2095            ("(1, *items)", AssignmentSequenceKind::Tuple, 1, true),
2096        ] {
2097            let source = format!("a, *b = {rhs}\n");
2098            let tree = parse_python(&source);
2099            let assignment = node_of_kind(tree.root_node(), "assignment").unwrap();
2100            assert_eq!(
2101                python_assignment_value_shape(assignment.child_by_field_name("right").unwrap()),
2102                Some((kind, count, starred)),
2103                "{rhs}"
2104            );
2105        }
2106        for (value, constant) in [
2107            ("((True))", true),
2108            ("(False)", true),
2109            ("((None))", true),
2110            ("-None", false),
2111            ("-1", true),
2112            ("f'{value}'", false),
2113        ] {
2114            let source = format!("left == {value}\n");
2115            let tree = parse_python(&source);
2116            let comparison = node_of_kind(tree.root_node(), "comparison_operator").unwrap();
2117            let operand = comparison.named_child(1).unwrap();
2118            assert_eq!(python_comparison_constant(operand), constant, "{value}");
2119        }
2120    }
2121
2122    #[test]
2123    fn qs6_source_export_namespace_shapes() {
2124        for (statement, dynamic) in [
2125            ("", false),
2126            (
2127                "import sys as runtime\nsetattr(runtime.modules[__name__], 'late', 1)\n",
2128                true,
2129            ),
2130            ("setattr(__import__(__name__), 'late', 1)\n", true),
2131            (
2132                "import sys as runtime\nalias = runtime.modules[__name__]\nsetattr(alias, 'late', 1)\n",
2133                true,
2134            ),
2135            ("globals()['late'] = 1\n", true),
2136        ] {
2137            let source = format!("__all__ = ['late']\n{statement}");
2138            let tree = parse_python(&source);
2139            let facts = python_source_export_facts(tree.root_node(), &source);
2140            assert_eq!(facts.definitions_complete, !dynamic, "{source}");
2141            assert!(
2142                matches!(
2143                    facts.exports[0].local_definition,
2144                    SourceExportLocalDefinition::Unknown
2145                ) == dynamic,
2146                "{facts:?}"
2147            );
2148            if !dynamic {
2149                assert!(matches!(
2150                    facts.exports[0].local_definition,
2151                    SourceExportLocalDefinition::Undefined
2152                ));
2153            }
2154        }
2155        let source = "__all__ =\n";
2156        let tree = parse_python(source);
2157        assert!(!python_source_export_facts(tree.root_node(), source).definitions_complete);
2158    }
2159
2160    #[test]
2161    fn qs6_binding_kind_grammar_inventory() {
2162        let source = "def run(parameter):\n scalar = 1\n left, right = (1, 2)\n for loop in ():\n  pass\n values = [comp for comp in ()]\n";
2163        let tree = parse_python(source);
2164        let mut pending = vec![tree.root_node()];
2165        let mut found = Vec::new();
2166        while let Some(node) = pending.pop() {
2167            if node.kind() == "identifier" {
2168                let text = node_source_text(node, source);
2169                if text == "comp" && node.parent().unwrap().kind() != "for_in_clause" {
2170                    continue;
2171                }
2172                if let Some(expected) = match text {
2173                    "parameter" => Some(BindingKind::Parameter),
2174                    "scalar" | "left" | "right" => Some(BindingKind::Local),
2175                    "loop" | "comp" => Some(BindingKind::LoopVariable),
2176                    _ => None,
2177                } {
2178                    let activation =
2179                        python_binding_activation(node, node_range(tree.root_node())).unwrap();
2180                    assert_eq!(activation.kind, expected, "{text}: {}", node.to_sexp());
2181                    found.push(text);
2182                }
2183            }
2184            let mut cursor = node.walk();
2185            pending.extend(node.named_children(&mut cursor));
2186        }
2187        assert_eq!(found.len(), 6);
2188    }
2189
2190    #[test]
2191    fn missing_python_all_value_is_incomplete_after_parser_recovery() {
2192        let source = "__all__ =\n";
2193        let mut parser = tree_sitter::Parser::new();
2194        parser
2195            .set_language(&tree_sitter_python::LANGUAGE.into())
2196            .expect("Python parser");
2197        let tree = parser.parse(source, None).expect("Python source tree");
2198        let root = tree.root_node();
2199        let facts = python_source_export_facts(root, source);
2200
2201        assert!(facts.declared, "recovered AST: {}", root.to_sexp());
2202        assert!(!facts.complete, "recovered AST: {}", root.to_sexp());
2203    }
2204
2205    #[test]
2206    fn parenthesized_string_literals_allow_comment_children() {
2207        for (case, source) in [
2208            (
2209                "one comment between concatenated strings",
2210                "VALUE = (\n    r\"\\.\"  # dot\n    r\"(?!-)\"\n)\n",
2211            ),
2212            (
2213                "several comments between concatenated strings",
2214                "VALUE = (\n    r\"a\"  # first\n    # between\n    r\"b\"  # second\n    # trailing\n)\n",
2215            ),
2216            (
2217                "comment before the string",
2218                "VALUE = (\n    # starts below\n    r\"value\"\n)\n",
2219            ),
2220            (
2221                "nested parentheses with a comment",
2222                "VALUE = (\n    (\n        # nested\n        r\"value\"  # closes inner value\n    )\n)\n",
2223            ),
2224        ] {
2225            let tree = parse_python(source);
2226            let root = tree.root_node();
2227            assert!(!root.has_error(), "{case}: {}", root.to_sexp());
2228            let (string_count, parenthesized_count) = string_literal_parenthesization(root);
2229            assert!(string_count > 0, "{case}: {}", root.to_sexp());
2230            assert!(parenthesized_count > 0, "{case}: {}", root.to_sexp());
2231        }
2232
2233        let tree = parse_python("VALUE = (\n    # comment\n    1  # trailing comment\n)\n");
2234        let mut pending = vec![tree.root_node()];
2235        let parenthesized = loop {
2236            let node = pending.pop().expect("parenthesized expression exists");
2237            if node.kind() == "parenthesized_expression" {
2238                break node;
2239            }
2240            let mut cursor = node.walk();
2241            pending.extend(node.named_children(&mut cursor));
2242        };
2243        assert!(python_comparison_constant(parenthesized));
2244        assert_eq!(python_unwrap_parenthesized(parenthesized).kind(), "integer");
2245    }
2246
2247    #[test]
2248    #[hardwon(
2249        "#4797: a backslash continuation before `else` counted as a fourth conditional-expression operand"
2250    )]
2251    fn conditional_expression_selects_condition_past_extras() {
2252        for (case, source) in [
2253            (
2254                "line continuation",
2255                "def f(a, b):\n    return a if b \\\n        else c\n",
2256            ),
2257            (
2258                "comment",
2259                "def f(a, b, c):\n    return (a if b\n            # why not\n            else c)\n",
2260            ),
2261            (
2262                "plain",
2263                "def f(a, b, c):\n    return (a if b\n            else c)\n",
2264            ),
2265        ] {
2266            let tree = parse_python(source);
2267            let root = tree.root_node();
2268            assert!(!root.has_error(), "{case}: {}", root.to_sexp());
2269            let conditional = node_of_kind(root, "conditional_expression").unwrap_or_else(|| {
2270                panic!("{case}: no conditional expression in {}", root.to_sexp())
2271            });
2272            let test = python_conditional_expression_operands(conditional)
2273                .expect("conditional expression operands")[1];
2274            assert_eq!(test.kind(), "identifier", "{case}");
2275            assert_eq!(
2276                test.utf8_text(source.as_bytes()).unwrap(),
2277                "b",
2278                "{case}: {}",
2279                root.to_sexp()
2280            );
2281        }
2282    }
2283
2284    #[test]
2285    #[hardwon(
2286        "#4797: a line continuation inside parentheses hid the sole operand from the parenthesization check"
2287    )]
2288    fn parenthesized_expression_skips_line_continuation() {
2289        let source = "VALUE = (\n    \"value\"\\\n)\n";
2290        let tree = parse_python(source);
2291        let root = tree.root_node();
2292        assert!(!root.has_error(), "{}", root.to_sexp());
2293        let string = node_of_kind(root, "string").expect("string literal");
2294        assert_eq!(
2295            PYTHON_STRUCTURAL_SPEC.string_literal_parenthesized(string),
2296            Some(true),
2297            "{}",
2298            root.to_sexp()
2299        );
2300    }
2301
2302    #[test]
2303    #[hardwon("#4797: a line continuation in a dict literal disabled duplicate-key detection")]
2304    fn duplicate_dictionary_key_skips_extras() {
2305        let source = "D = {1: 2, \\\n 1: 3}\n";
2306        let tree = parse_python(source);
2307        let root = tree.root_node();
2308        assert!(!root.has_error(), "{}", root.to_sexp());
2309        let dictionary = node_of_kind(root, "dictionary").expect("dictionary literal");
2310        let mut cursor = dictionary.walk();
2311        let pairs: Vec<Node<'_>> = dictionary
2312            .named_children(&mut cursor)
2313            .filter(|child| child.kind() == "pair")
2314            .collect();
2315        assert_eq!(pairs.len(), 2, "{}", root.to_sexp());
2316        assert_eq!(
2317            PYTHON_STRUCTURAL_SPEC.duplicate_dictionary_key(pairs[1], source),
2318            Some(true),
2319            "{}",
2320            root.to_sexp()
2321        );
2322    }
2323
2324    #[test]
2325    fn django_domain_validator_strings_parse_without_parenthesization_panics() {
2326        let source = r#"
2327class DomainNameValidator(RegexValidator):
2328    message = _("Enter a valid domain name.")
2329    ul = "\u00a1-\uffff"  # Unicode letters range (must not be a raw string).
2330    # Host patterns.
2331    hostname_re = (
2332        r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?"
2333    )
2334    # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1.
2335    domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(?<!-))*"
2336    # Top-level domain.
2337    tld_no_fqdn_re = (
2338        r"\."  # dot
2339        r"(?!-)"  # can't start with a dash
2340        r"(?:[a-z" + ul + "-]{2,63}"  # domain label
2341        r"|xn--[a-z0-9]{1,59})"  # or punycode label
2342        r"(?<!-)"  # can't end with a dash
2343    )
2344    tld_re = tld_no_fqdn_re + r"\.?"
2345    ascii_only_hostname_re = r"[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?"
2346    ascii_only_domain_re = r"(?:\.(?!-)[a-zA-Z0-9-]{1,63}(?<!-))*"
2347    ascii_only_tld_re = (
2348        r"\."  # dot
2349        r"(?!-)"  # can't start with a dash
2350        r"(?:[a-zA-Z0-9-]{2,63})"  # domain label
2351        r"(?<!-)"  # can't end with a dash
2352        r"\.?"  # may have a trailing dot
2353    )
2354"#;
2355        let tree = parse_python(source);
2356        let root = tree.root_node();
2357        assert!(!root.has_error(), "{}", root.to_sexp());
2358        let (string_count, parenthesized_count) = string_literal_parenthesization(root);
2359        assert!(string_count > 0, "{}", root.to_sexp());
2360        assert!(parenthesized_count > 0, "{}", root.to_sexp());
2361    }
2362
2363    #[test]
2364    fn decoded_string_values_match_python_escape_and_concatenation_semantics() {
2365        for (source, expected) in [
2366            (
2367                r#"MIDDLEWARE = "\x64jango.middleware.csrf.CsrfViewMiddleware""#,
2368                Some("django.middleware.csrf.CsrfViewMiddleware"),
2369            ),
2370            (
2371                r#"MIDDLEWARE = "django.middleware.csrf." "CsrfViewMiddleware""#,
2372                Some("django.middleware.csrf.CsrfViewMiddleware"),
2373            ),
2374            (
2375                r#"MIDDLEWARE = b"django.middleware.csrf.CsrfViewMiddleware""#,
2376                None,
2377            ),
2378        ] {
2379            let mut parser = tree_sitter::Parser::new();
2380            parser
2381                .set_language(&tree_sitter_python::LANGUAGE.into())
2382                .expect("Python parser");
2383            let tree = parser.parse(source, None).expect("Python source tree");
2384            let mut pending = vec![tree.root_node()];
2385            let assignment = loop {
2386                let node = pending.pop().expect("Python tree has an assignment");
2387                if node.kind() == "assignment" {
2388                    break node;
2389                }
2390                let mut cursor = node.walk();
2391                pending.extend(node.named_children(&mut cursor));
2392            };
2393            let value = assignment
2394                .child_by_field_name("right")
2395                .expect("assignment value");
2396            assert_eq!(
2397                python_string_key_value(value, source).as_deref(),
2398                expected,
2399                "{}",
2400                tree.root_node().to_sexp()
2401            );
2402        }
2403    }
2404    #[test]
2405    fn qs6_flat_import_paths_follow_grammar_fields_and_byte_ranges() {
2406        let source = "# \u{e9}\nimport alpha.beta.gamma as alias\nfrom alpha.beta import gamma\nalpha.beta\n";
2407        let tree = parse_python(source);
2408        let root = tree.root_node();
2409        assert!(!root.has_error(), "{}", root.to_sexp());
2410        let import = root.named_child(1).unwrap();
2411        assert_eq!(import.kind(), "import_statement");
2412        let aliased = import.child_by_field_name("name").unwrap();
2413        assert_eq!(aliased.kind(), "aliased_import");
2414        let dotted = aliased.child_by_field_name("name").unwrap();
2415        assert_eq!(dotted.kind(), "dotted_name");
2416        let tokens = PYTHON_STRUCTURAL_SPEC.path_segment_tokens(dotted);
2417        let start = source.find("alpha").unwrap();
2418        assert_eq!(
2419            tokens
2420                .iter()
2421                .map(|node| (node.kind(), node.byte_range()))
2422                .collect::<Vec<_>>(),
2423            vec![
2424                ("identifier", start..start + 5),
2425                ("identifier", start + 6..start + 10),
2426                ("identifier", start + 11..start + 16)
2427            ]
2428        );
2429        for token in tokens {
2430            assert_eq!(
2431                PYTHON_STRUCTURAL_SPEC.qualified_path_root(token),
2432                Some(dotted)
2433            );
2434        }
2435        let alias = aliased.child_by_field_name("alias").unwrap();
2436        assert_eq!(node_source_text(alias, source), "alias");
2437        assert!(PYTHON_STRUCTURAL_SPEC.qualified_path_root(alias).is_none());
2438        let from = root.named_child(2).unwrap();
2439        let module = from.child_by_field_name("module_name").unwrap();
2440        assert_eq!(module.kind(), "dotted_name");
2441        assert_eq!(
2442            PYTHON_STRUCTURAL_SPEC
2443                .path_segment_tokens(module)
2444                .iter()
2445                .map(|n| node_source_text(*n, source))
2446                .collect::<Vec<_>>(),
2447            vec!["alpha", "beta"]
2448        );
2449        let attribute = root.named_child(3).unwrap().named_child(0).unwrap();
2450        assert_eq!(attribute.kind(), "attribute");
2451        assert!(
2452            PYTHON_STRUCTURAL_SPEC
2453                .path_segment_tokens(attribute)
2454                .is_empty()
2455        );
2456        assert!(
2457            PYTHON_STRUCTURAL_SPEC
2458                .qualified_path_root(attribute.child_by_field_name("attribute").unwrap())
2459                .is_none()
2460        );
2461    }
2462
2463    #[test]
2464    fn qs6_syntactic_reexports_obey_redundant_aliases_and_all_membership() {
2465        for (all, listed, ordinary) in [
2466            ("", Some(RouteHopKind::Import), Some(RouteHopKind::Import)),
2467            (
2468                "__all__ = ['z']\n",
2469                Some(RouteHopKind::ReExport),
2470                Some(RouteHopKind::Import),
2471            ),
2472            ("__all__ = dynamic()\n", None, None),
2473        ] {
2474            let source = format!(
2475                "# \u{e9}\nimport a.b\nimport x as x\nfrom x import y as y\nfrom x import y as z\nfrom x import *\n{all}"
2476            );
2477            let tree = parse_python(&source);
2478            let root = tree.root_node();
2479            assert!(!root.has_error(), "{}", root.to_sexp());
2480            let surface = PYTHON_STRUCTURAL_SPEC.curated_export_surface(root, &source);
2481            for (index, field, expected) in [
2482                (1, "name", ordinary),
2483                (2, "name", Some(RouteHopKind::ReExport)),
2484                (3, "name", Some(RouteHopKind::ReExport)),
2485                (4, "name", listed),
2486                (5, "module_name", Some(RouteHopKind::ReExport)),
2487            ] {
2488                let clause = root
2489                    .named_child(index)
2490                    .unwrap()
2491                    .child_by_field_name(field)
2492                    .unwrap();
2493                let name = if clause.kind() == "aliased_import" {
2494                    clause.child_by_field_name("name").unwrap()
2495                } else {
2496                    clause
2497                };
2498                assert_eq!(name.kind(), "dotted_name");
2499                let token = name.named_child(0).unwrap();
2500                assert_eq!(token.kind(), "identifier");
2501                assert_eq!(
2502                    PYTHON_STRUCTURAL_SPEC.indirection_relation(token, &source, &surface),
2503                    expected,
2504                    "{}",
2505                    clause.to_sexp()
2506                );
2507            }
2508        }
2509    }
2510}