dissolve-python 0.3.0

A tool to dissolve deprecated calls in Python codebases
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
// Copyright (C) 2024 Jelmer Vernooij <jelmer@samba.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Collection functionality for @replace_me decorated functions using Ruff parser.

use crate::core::types::*;
use anyhow::Result;
use rustpython_parser::{parse, Mode};
use rustpython_ast::located::*;
use rustpython_ast::Ranged;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

pub struct RuffDeprecatedFunctionCollector {
    module_name: String,
    _file_path: Option<PathBuf>,
    replacements: HashMap<String, ReplaceInfo>,
    unreplaceable: HashMap<String, UnreplaceableNode>,
    imports: Vec<ImportInfo>,
    inheritance_map: HashMap<String, Vec<String>>,
    class_methods: HashMap<String, HashSet<String>>,
    class_stack: Vec<String>,
    source: String,
    builtins: HashSet<String>,
}

impl RuffDeprecatedFunctionCollector {
    pub fn new(module_name: String, file_path: Option<&Path>) -> Self {
        Self {
            module_name,
            _file_path: file_path.map(Path::to_path_buf),
            replacements: HashMap::new(),
            unreplaceable: HashMap::new(),
            imports: Vec::new(),
            inheritance_map: HashMap::new(),
            class_methods: HashMap::new(),
            class_stack: Vec::new(),
            source: String::new(),
            builtins: Self::get_all_builtins(),
        }
    }

    /// Collect from source string
    pub fn collect_from_source(mut self, source: String) -> Result<CollectorResult> {
        self.source = source;
        let parsed = parse(&self.source, Mode::Module)?;

        match parsed.into_syntax() {
            Mod::Module(module) => {
                for stmt in &module.body {
                    self.visit_stmt(stmt);
                }
            }
            Mod::Expression(_) => {
                // Not handling expression mode
            }
        }

        Ok(CollectorResult {
            replacements: self.replacements,
            unreplaceable: self.unreplaceable,
            imports: self.imports,
            inheritance_map: self.inheritance_map,
            class_methods: self.class_methods,
        })
    }

    /// Build the full object path including module and class names
    fn build_full_path(&self, name: &str) -> String {
        let mut parts = Vec::with_capacity(2 + self.class_stack.len());
        parts.push(self.module_name.as_str());
        parts.extend(self.class_stack.iter().map(|s| s.as_str()));
        parts.push(name);
        parts.join(".")
    }

    /// Build a qualified name from an expression (e.g., module.Class)
    fn build_qualified_name_from_expr(&self, expr: &Expr) -> String {
        match expr {
            Expr::Name(name) => {
                // Simple name - assume it's in the current module
                format!("{}.{}", self.module_name, name.id)
            }
            Expr::Attribute(attr) => {
                // Handle nested attributes like a.b.c
                // Build the string from right to left to avoid reverse
                let mut result = attr.attr.to_string();
                let mut current = &*attr.value;

                loop {
                    match current {
                        Expr::Name(name) => {
                            // Prepend the final name
                            result = format!("{}.{}", name.id, result);
                            break;
                        }
                        Expr::Attribute(inner_attr) => {
                            // Prepend this attribute
                            result = format!("{}.{}", inner_attr.attr, result);
                            current = &*inner_attr.value;
                        }
                        _ => {
                            // Can't handle this expression type, just return the attribute
                            return attr.attr.to_string();
                        }
                    }
                }

                result
            }
            _ => {
                // Can't handle this expression type
                "Unknown".to_string()
            }
        }
    }

    /// Check if a decorator list contains @replace_me
    fn has_replace_me_decorator(decorators: &[Decorator]) -> bool {
        decorators.iter().any(|dec| match &dec.expression {
            Expr::Name(name) => name.id.as_str() == "replace_me",
            Expr::Call(call) => {
                matches!(&*call.func, Expr::Name(name) if name.id.as_str() == "replace_me")
            }
            _ => false,
        })
    }

    /// Extract the 'since' version from @replace_me decorator
    fn extract_since_version(&self, decorators: &[Decorator]) -> Option<String> {
        self.extract_decorator_version_arg(decorators, "since")
    }

    fn extract_remove_in_version(&self, decorators: &[Decorator]) -> Option<String> {
        self.extract_decorator_version_arg(decorators, "remove_in")
    }

    fn extract_message(decorators: &[Decorator]) -> Option<String> {
        Self::extract_decorator_string_arg(decorators, "message")
    }

    fn extract_decorator_version_arg(
        &self,
        decorators: &[Decorator],
        arg_name: &str,
    ) -> Option<String> {
        for dec in decorators {
            if let Expr::Call(call) = &dec.expression {
                if matches!(&*call.func, Expr::Name(name) if name.id.as_str() == "replace_me") {
                    for keyword in &call.arguments.keywords {
                        if let Some(arg) = &keyword.arg {
                            if arg.as_str() == arg_name {
                                match &keyword.value {
                                    // String literal: "1.2.3"
                                    Expr::StringLiteral(lit) => {
                                        return Some(lit.value.to_string());
                                    }
                                    // Tuple literal: (1, 2, 3) or (1, 2, "final")
                                    Expr::Tuple(tuple) => {
                                        let parts: Vec<String> = tuple
                                            .elts
                                            .iter()
                                            .filter_map(|elt| {
                                                match elt {
                                                    Expr::NumberLiteral(num) => {
                                                        // Extract the number from the source text
                                                        let range = num.range();
                                                        self.source
                                                            .get(
                                                                range.start().to_usize()
                                                                    ..range.end().to_usize(),
                                                            )
                                                            .map(|s| s.to_string())
                                                    }
                                                    Expr::StringLiteral(lit) => {
                                                        Some(lit.value.to_string())
                                                    }
                                                    _ => None,
                                                }
                                            })
                                            .collect();
                                        if !parts.is_empty() {
                                            return Some(parts.join("."));
                                        }
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }
                }
            }
        }
        None
    }

    fn extract_decorator_string_arg(decorators: &[Decorator], arg_name: &str) -> Option<String> {
        for dec in decorators {
            if let Expr::Call(call) = &dec.expression {
                if matches!(&*call.func, Expr::Name(name) if name.id.as_str() == "replace_me") {
                    for keyword in &call.arguments.keywords {
                        if let Some(arg) = &keyword.arg {
                            if arg.as_str() == arg_name {
                                if let Expr::StringLiteral(lit) = &keyword.value {
                                    return Some(lit.value.to_string());
                                }
                            }
                        }
                    }
                }
            }
        }
        None
    }

    /// Extract parameters from a function
    fn extract_parameters(&self, func: &StmtFunctionDef) -> Vec<ParameterInfo> {
        let mut params = Vec::new();

        // Regular parameters
        for param in &func.parameters.args {
            let default_value = param.default.as_ref().map(|default| {
                // Extract the source code of the default value
                let range = default.range();
                self.source
                    .get(range.start().to_usize()..range.end().to_usize())
                    .unwrap_or("")
                    .to_string()
            });

            let mut param_info = ParameterInfo::new(&param.parameter.name);
            param_info.has_default = param.default.is_some();
            param_info.default_value = default_value;
            params.push(param_info);
        }

        // *args
        if let Some(vararg) = &func.parameters.vararg {
            params.push(ParameterInfo::vararg(&vararg.name));
        }

        // Keyword-only parameters
        for param in &func.parameters.kwonlyargs {
            let default_value = param.default.as_ref().map(|default| {
                // Extract the source code of the default value
                let range = default.range();
                self.source
                    .get(range.start().to_usize()..range.end().to_usize())
                    .unwrap_or("")
                    .to_string()
            });

            let mut param_info = ParameterInfo::new(&param.parameter.name);
            param_info.has_default = param.default.is_some();
            param_info.default_value = default_value;
            param_info.is_kwonly = true;
            params.push(param_info);
        }

        // **kwargs
        if let Some(kwarg) = &func.parameters.kwarg {
            params.push(ParameterInfo::kwarg(&kwarg.name));
        }

        params
    }

    /// Extract replacement expression from function body
    fn extract_replacement_from_function(
        &self,
        func: &StmtFunctionDef,
    ) -> Result<(String, Expr), ReplacementExtractionError> {
        // Skip docstring and pass statements
        let body_stmts: Vec<&Stmt> = func
            .body
            .iter()
            .skip_while(|stmt| {
                matches!(stmt, Stmt::Expr(expr_stmt) if matches!(&*expr_stmt.value,
                    Expr::StringLiteral(_) | Expr::FString(_)))
            })
            .filter(|stmt| !matches!(stmt, Stmt::Pass(_)))
            .collect();

        if body_stmts.is_empty() {
            // Empty body (possibly with just pass/docstring) is valid - it means remove the function completely
            // Return empty string and a dummy expression (won't be used)
            return Ok((
                "".to_string(),
                Expr::StringLiteral(ruff_python_ast::ExprStringLiteral {
                    value: ruff_python_ast::StringLiteralValue::single(
                        ruff_python_ast::StringLiteral {
                            value: "".into(),
                            flags: ruff_python_ast::StringLiteralFlags::default(),
                            range: ruff_text_size::TextRange::default(),
                        },
                    ),
                    range: ruff_text_size::TextRange::default(),
                }),
            ));
        }

        if body_stmts.len() > 1 {
            return Err(ReplacementExtractionError::new(
                func.name.to_string(),
                ReplacementFailureReason::MultipleStatements,
                "Function body contains multiple statements".to_string(),
            ));
        }

        // Extract return expression
        match body_stmts[0] {
            Stmt::Return(ret_stmt) => {
                if let Some(value) = &ret_stmt.value {
                    // Get function parameters for placeholder conversion
                    let param_names: HashSet<String> = self
                        .extract_parameters(func)
                        .into_iter()
                        .filter(|p| !p.is_vararg && !p.is_kwarg)
                        .map(|p| p.name)
                        .collect();

                    // Convert the AST expression to string with placeholders
                    let replacement_expr =
                        self.expr_to_string_with_placeholders(value, &param_names);

                    tracing::debug!("Extracted replacement expression: {}", replacement_expr);

                    // Also return the AST so we can store it
                    Ok((replacement_expr, (**value).clone()))
                } else {
                    Err(ReplacementExtractionError::new(
                        func.name.to_string(),
                        ReplacementFailureReason::NoReturnStatement,
                        "Return statement has no value".to_string(),
                    ))
                }
            }
            _ => Err(ReplacementExtractionError::new(
                func.name.to_string(),
                ReplacementFailureReason::NoReturnStatement,
                "Function body does not contain a return statement".to_string(),
            )),
        }
    }

    /// Get all builtin names from Python
    fn get_all_builtins() -> HashSet<String> {
        use pyo3::prelude::*;

        Python::with_gil(|py| {
            let mut builtin_names = HashSet::new();

            // Get the builtins module
            if let Ok(builtins) = py.import("builtins") {
                // Get all attributes of the builtins module
                if let Ok(dir_result) = builtins.dir() {
                    // Iterate through the dir() result
                    for item in dir_result.iter() {
                        if let Ok(name_str) = item.extract::<String>() {
                            builtin_names.insert(name_str);
                        }
                    }
                }
            }

            builtin_names
        })
    }

    /// Check if a name is a Python builtin
    fn is_builtin(&self, name: &str) -> bool {
        self.builtins.contains(name)
    }

    /// Get the builtins set
    pub fn builtins(&self) -> &HashSet<String> {
        &self.builtins
    }

    fn expr_to_string_with_placeholders(
        &self,
        expr: &Expr,
        param_names: &HashSet<String>,
    ) -> String {
        match expr {
            Expr::Name(name) => {
                let name_str = name.id.to_string();
                if param_names.contains(&name_str) {
                    format!("{{{}}}", name_str)
                } else {
                    name_str
                }
            }
            Expr::Call(call) => {
                // Handle function calls
                let func_str = match &*call.func {
                    // For simple function names, qualify them if needed
                    Expr::Name(name) => {
                        let name_str = name.id.to_string();
                        if param_names.contains(&name_str) {
                            format!("{{{}}}", name_str)
                        } else if self.is_builtin(&name_str) {
                            // Don't qualify builtins
                            name_str
                        } else if !name_str.contains('.') {
                            // Qualify unqualified function names with module name
                            format!("{}.{}", self.module_name, name_str)
                        } else {
                            name_str
                        }
                    }
                    // For attribute access (e.g., self.method or module.func), preserve as-is
                    _ => self.expr_to_string_with_placeholders(&call.func, param_names),
                };
                let mut args = Vec::new();

                // Handle positional arguments
                for arg in &call.arguments.args {
                    args.push(self.expr_to_string_with_placeholders(arg, param_names));
                }

                // Handle keyword arguments
                for keyword in &call.arguments.keywords {
                    if let Some(arg_name) = &keyword.arg {
                        // For keyword arguments, we don't replace the keyword name, only the value
                        let value_str =
                            self.expr_to_string_with_placeholders(&keyword.value, param_names);
                        args.push(format!("{}={}", arg_name, value_str));
                    } else {
                        // **kwargs expansion
                        args.push(format!(
                            "**{}",
                            self.expr_to_string_with_placeholders(&keyword.value, param_names)
                        ));
                    }
                }

                // Check if this is a multi-line call by looking at the original formatting
                let call_range = call.range();
                let original_text =
                    &self.source[call_range.start().to_usize()..call_range.end().to_usize()];

                if original_text.contains('\n') && args.len() > 1 {
                    // Multi-line formatting - preserve the style
                    format!(
                        "{}(\n            {}\n        )",
                        func_str,
                        args.join(",\n            ")
                    )
                } else {
                    // Single line
                    format!("{}({})", func_str, args.join(", "))
                }
            }
            Expr::Attribute(attr) => {
                let value_str = self.expr_to_string_with_placeholders(&attr.value, param_names);
                format!("{}.{}", value_str, attr.attr)
            }
            Expr::Starred(starred) => {
                // Handle *args
                format!(
                    "*{}",
                    self.expr_to_string_with_placeholders(&starred.value, param_names)
                )
            }
            Expr::BinOp(binop) => {
                // Handle binary operations like x * 2, y + 1
                let left = self.expr_to_string_with_placeholders(&binop.left, param_names);
                let right = self.expr_to_string_with_placeholders(&binop.right, param_names);

                // Get the operator string
                let op_str = binop.op.as_str();

                format!("{} {} {}", left, op_str, right)
            }
            Expr::Await(await_expr) => {
                // For await expressions, we extract the inner expression
                // The await will be added back by the migration if needed
                self.expr_to_string_with_placeholders(&await_expr.value, param_names)
            }
            _ => {
                // For other expression types, use the original source text
                let range = expr.range();
                self.source[range.start().to_usize()..range.end().to_usize()].to_string()
            }
        }
    }

    /// Visit a function definition
    fn visit_function(&mut self, func: &StmtFunctionDef) {
        if !Self::has_replace_me_decorator(&func.decorator_list) {
            return;
        }

        let full_path = self.build_full_path(&func.name);
        let parameters = self.extract_parameters(func);
        let since = self.extract_since_version(&func.decorator_list);
        let remove_in = self.extract_remove_in_version(&func.decorator_list);
        let message = Self::extract_message(&func.decorator_list);

        // Determine construct type
        let construct_type = if self.class_stack.is_empty() {
            ConstructType::Function
        } else {
            // Check decorators for special methods
            let decorator_names: Vec<&str> = func
                .decorator_list
                .iter()
                .filter_map(|dec| {
                    if let Expr::Name(name) = &dec.expression {
                        Some(name.id.as_str())
                    } else {
                        None
                    }
                })
                .collect();

            if decorator_names.contains(&"property") {
                ConstructType::Property
            } else if decorator_names.contains(&"classmethod") {
                ConstructType::ClassMethod
            } else if decorator_names.contains(&"staticmethod") {
                ConstructType::StaticMethod
            } else {
                ConstructType::Function
            }
        };

        // Try to extract replacement
        match self.extract_replacement_from_function(func) {
            Ok((replacement_expr, ast)) => {
                let mut replace_info =
                    ReplaceInfo::new(&full_path, &replacement_expr, construct_type);
                replace_info.replacement_ast = Some(Box::new(ast));
                replace_info.parameters = parameters;
                replace_info.since = since;
                replace_info.remove_in = remove_in;
                replace_info.message = message;
                self.replacements.insert(full_path, replace_info);
            }
            Err(e) => {
                let unreplaceable = UnreplaceableNode::new(
                    full_path.clone(),
                    e.reason(),
                    e.to_string(),
                    construct_type,
                );
                self.unreplaceable.insert(full_path, unreplaceable);
            }
        }
    }

    /// Visit a class definition
    fn visit_class(&mut self, class_def: &StmtClassDef) {
        let class_name = class_def.name.to_string();
        let full_class_name = self.build_full_path(&class_name);

        // Record base classes
        let mut bases = Vec::new();
        for base in class_def.bases() {
            match base {
                Expr::Name(name) => {
                    // Simple name like BaseRepo
                    // If it's a simple name and likely defined in the same module,
                    // we'll store the fully qualified name
                    let base_name = name.id.to_string();
                    // Check if this is likely a class from the same module
                    // by seeing if we have it in our current class definitions
                    let qualified_name = format!("{}.{}", self.module_name, base_name);
                    bases.push(qualified_name);
                }
                Expr::Attribute(_attr) => {
                    // Qualified name like module.BaseRepo
                    // We need to build the full qualified name from the attribute expression
                    let qualified_name = self.build_qualified_name_from_expr(base);
                    bases.push(qualified_name);
                }
                _ => {
                    // Other base class expressions not handled yet
                }
            }
        }

        if !bases.is_empty() {
            tracing::debug!("Class {} inherits from: {:?}", full_class_name, bases);
            self.inheritance_map.insert(full_class_name.clone(), bases);
        }

        // Check if class itself has @replace_me
        if Self::has_replace_me_decorator(&class_def.decorator_list) {
            // Try to extract replacement from __init__
            if let Some(init_replacement) = self.extract_class_replacement(class_def) {
                let mut replace_info = ReplaceInfo::new(
                    &full_class_name,
                    &init_replacement,
                    ConstructType::Class,
                );

                // Extract __init__ parameters
                for stmt in &class_def.body {
                    if let Stmt::FunctionDef(func) = stmt {
                        if func.name.as_str() == "__init__" {
                            replace_info.parameters = self
                                .extract_parameters(func)
                                .into_iter()
                                .filter(|p| p.name != "self")
                                .collect();
                            break;
                        }
                    }
                }

                self.replacements
                    .insert(full_class_name.clone(), replace_info);
            } else {
                // Class has @replace_me but no clear replacement pattern
                let unreplaceable = UnreplaceableNode::new(
                    full_class_name.clone(),
                    ReplacementFailureReason::NoInitMethod,
                    "Class has @replace_me decorator but no __init__ method with clear replacement pattern".to_string(),
                    ConstructType::Class,
                );
                self.unreplaceable
                    .insert(full_class_name.clone(), unreplaceable);
            }
        }

        // Visit class body
        self.class_stack.push(class_name);
        for stmt in &class_def.body {
            self.visit_stmt(stmt);
        }
        self.class_stack.pop();
    }

    /// Extract replacement from class __init__ method
    fn extract_class_replacement(&self, class_def: &StmtClassDef) -> Option<String> {
        // Look for __init__ method
        for stmt in &class_def.body {
            if let Stmt::FunctionDef(func) = stmt {
                if func.name.as_str() == "__init__" {
                    // Look for self.attr = SomeClass(...) pattern
                    for init_stmt in &func.body {
                        if let Stmt::Assign(assign) = init_stmt {
                            if assign.targets.len() == 1 {
                                if let Expr::Attribute(attr) = &assign.targets[0] {
                                    if let Expr::Name(name) = &*attr.value {
                                        if name.id.as_str() == "self" {
                                            // Found self.attr = expr
                                            let range = assign.value.range();
                                            let mut replacement_expr = self.source
                                                [range.start().to_usize()..range.end().to_usize()]
                                                .to_string();

                                            // Convert parameter names to placeholders (like function replacements)
                                            let params = self.extract_parameters(func);
                                            for param in params {
                                                if param.name != "self" {
                                                    let pattern = if param.is_vararg {
                                                        // Match *args
                                                        format!(
                                                            r"\*{}\b",
                                                            regex::escape(&param.name)
                                                        )
                                                    } else if param.is_kwarg {
                                                        // Match **kwargs
                                                        format!(
                                                            r"\*\*{}\b",
                                                            regex::escape(&param.name)
                                                        )
                                                    } else {
                                                        // Match regular parameter
                                                        format!(
                                                            r"\b{}\b",
                                                            regex::escape(&param.name)
                                                        )
                                                    };

                                                    let placeholder = if param.is_vararg {
                                                        format!("*{{{}}}", param.name)
                                                    } else if param.is_kwarg {
                                                        format!("**{{{}}}", param.name)
                                                    } else {
                                                        format!("{{{}}}", param.name)
                                                    };

                                                    replacement_expr = regex::Regex::new(&pattern)
                                                        .unwrap()
                                                        .replace_all(
                                                            &replacement_expr,
                                                            placeholder.as_str(),
                                                        )
                                                        .to_string();
                                                }
                                            }

                                            return Some(replacement_expr);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        None
    }

    fn visit_ann_assign(&mut self, ann_assign: &ruff_python_ast::StmtAnnAssign) {
        // Handle annotated assignments like DEFAULT_TIMEOUT: int = replace_me(30)
        if let Some(value) = &ann_assign.value {
            if let Expr::Name(name) = ann_assign.target.as_ref() {
                // Check if the assignment value is a replace_me call
                if let Expr::Call(call) = value.as_ref() {
                    if matches!(&*call.func, Expr::Name(func_name) if func_name.id.as_str() == "replace_me")
                    {
                        // Extract the replacement value
                        if let Some(arg) = call.arguments.args.first() {
                            let range = arg.range();
                            let replacement_expr = self.source
                                [range.start().to_usize()..range.end().to_usize()]
                                .to_string();

                            let full_name = if self.class_stack.is_empty() {
                                format!("{}.{}", self.module_name, name.id)
                            } else {
                                format!(
                                    "{}.{}.{}",
                                    self.module_name,
                                    self.class_stack.join("."),
                                    name.id
                                )
                            };

                            // Extract version information from keyword arguments
                            let since = self.extract_since_version(&[]);
                            let remove_in = self.extract_remove_in_version(&[]);
                            let message = Self::extract_message(&[]);

                            // Parse the replacement expression to get its AST
                            let replacement_ast = if let Ok(parsed) =
                                ruff_python_parser::parse_expression(&replacement_expr)
                            {
                                Some(Box::new(parsed.into_expr()))
                            } else {
                                None
                            };

                            let construct_type = if self.class_stack.is_empty() {
                                ConstructType::ModuleAttribute
                            } else {
                                ConstructType::ClassAttribute
                            };

                            let replace_info = ReplaceInfo {
                                old_name: full_name.clone(),
                                replacement_expr,
                                replacement_ast,
                                construct_type,
                                parameters: vec![], // Module attributes don't have parameters
                                return_type: None,
                                since,
                                remove_in,
                                message,
                            };

                            self.replacements.insert(full_name, replace_info);
                        }
                    }
                }
            }
        }
    }

    fn visit_assign(&mut self, assign: &ruff_python_ast::StmtAssign) {
        // Handle module-level assignments like OLD_CONSTANT = replace_me(42)
        if assign.targets.len() == 1 {
            if let Expr::Name(name) = &assign.targets[0] {
                // Check if the assignment value is a replace_me call
                if let Expr::Call(call) = assign.value.as_ref() {
                    if matches!(&*call.func, Expr::Name(func_name) if func_name.id.as_str() == "replace_me")
                    {
                        // Extract the replacement value
                        if let Some(arg) = call.arguments.args.first() {
                            let range = arg.range();
                            let replacement_expr = self.source
                                [range.start().to_usize()..range.end().to_usize()]
                                .to_string();

                            let full_name = if self.class_stack.is_empty() {
                                format!("{}.{}", self.module_name, name.id)
                            } else {
                                format!(
                                    "{}.{}.{}",
                                    self.module_name,
                                    self.class_stack.join("."),
                                    name.id
                                )
                            };

                            // Extract version information from keyword arguments
                            let since = self.extract_since_version(&[]);
                            let remove_in = self.extract_remove_in_version(&[]);
                            let message = Self::extract_message(&[]);

                            // Parse the replacement expression to get its AST
                            let replacement_ast = if let Ok(parsed) =
                                ruff_python_parser::parse_expression(&replacement_expr)
                            {
                                Some(Box::new(parsed.into_expr()))
                            } else {
                                None
                            };

                            let construct_type = if self.class_stack.is_empty() {
                                ConstructType::ModuleAttribute
                            } else {
                                ConstructType::ClassAttribute
                            };

                            let replace_info = ReplaceInfo {
                                old_name: full_name.clone(),
                                replacement_expr,
                                replacement_ast,
                                construct_type,
                                parameters: vec![], // Module/class attributes don't have parameters
                                return_type: None,
                                since,
                                remove_in,
                                message,
                            };

                            self.replacements.insert(full_name, replace_info);
                        }
                    }
                }
            }
        }
    }
}

impl Visitor<'_> for RuffDeprecatedFunctionCollector {
    fn visit_stmt(&mut self, stmt: &Stmt) {
        match stmt {
            Stmt::FunctionDef(func) => self.visit_function(func),
            Stmt::ClassDef(class) => self.visit_class(class),
            Stmt::Import(import) => {
                // Record imports
                for alias in &import.names {
                    self.imports.push(ImportInfo::new(
                        alias.name.to_string(),
                        vec![(
                            alias.name.to_string(),
                            alias.asname.as_ref().map(|n| n.to_string()),
                        )],
                    ));
                }
            }
            Stmt::ImportFrom(import) => {
                let names: Vec<(String, Option<String>)> = import
                    .names
                    .iter()
                    .map(|alias| {
                        (
                            alias.name.to_string(),
                            alias.asname.as_ref().map(|n| n.to_string()),
                        )
                    })
                    .collect();

                // Handle both absolute and relative imports
                let module_name = if let Some(module) = &import.module {
                    // Add dots for relative imports
                    let dots = ".".repeat(import.level as usize);
                    format!("{}{}", dots, module)
                } else {
                    // Pure relative import like "from . import x"
                    ".".repeat(import.level as usize)
                };

                self.imports.push(ImportInfo::new(module_name, names));
            }
            Stmt::Assign(assign) => {
                // Handle module-level assignments with replace_me calls
                self.visit_assign(assign);
                visitor::walk_stmt(self, stmt);
            }
            Stmt::AnnAssign(ann_assign) => {
                // Handle annotated assignments like DEFAULT_TIMEOUT: int = replace_me(30)
                self.visit_ann_assign(ann_assign);
                visitor::walk_stmt(self, stmt);
            }
            _ => visitor::walk_stmt(self, stmt),
        }
    }
}

impl ReplacementExtractionError {
    fn reason(&self) -> ReplacementFailureReason {
        match self {
            Self::ExtractionFailed { reason, .. } => reason.clone(),
        }
    }
}