phpantom_lsp 0.7.0

Fast PHP language server with deep type intelligence. Generics, Laravel, PHPStan annotations. Ready in an instant.
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
//! **Inline Variable** code action (`refactor.inline`).
//!
//! When the cursor is on a simple variable assignment like
//! `$name = $user->getName();`, this action replaces every read of
//! `$name` in the enclosing scope with the RHS expression and removes
//! the assignment statement.
//!
//! ### Safety checks
//!
//! 1. **Single assignment.** The variable must be assigned exactly once
//!    in the enclosing scope.  If reassigned, the action is not offered.
//! 2. **Pure expression.** If the RHS has side effects (function/method
//!    calls, `new`) and there are multiple reads, the action is not
//!    offered.  A single read is always safe.
//! 3. **Parenthesisation.** When substituting the RHS into a larger
//!    expression, binary/ternary/assignment expressions are wrapped in
//!    parentheses to preserve precedence.

use std::collections::HashMap;

use mago_span::HasSpan;
use mago_syntax::ast::class_like::member::ClassLikeMember;
use mago_syntax::ast::class_like::method::MethodBody;
use mago_syntax::ast::*;
use tower_lsp::lsp_types::*;

use crate::Backend;
use crate::code_actions::{CodeActionData, make_code_action_data};
use crate::parser::with_parsed_program;
use crate::scope_collector::{AccessKind, ScopeMap, collect_function_scope, collect_scope};
use crate::util::{offset_to_position, position_to_byte_offset};

// ─── AST helpers ────────────────────────────────────────────────────────────

/// Information about an assignment statement found at the cursor.
struct AssignmentInfo {
    /// The variable name including `$` prefix (e.g. `"$name"`).
    var_name: String,
    /// Byte offset of the `$` in the variable on the LHS.
    var_offset: u32,
    /// Byte range of the RHS expression `[start, end)`.
    rhs_start: usize,
    rhs_end: usize,
    /// Byte range of the entire statement (including semicolon) for deletion.
    stmt_start: usize,
    stmt_end: usize,
    /// Whether the RHS expression needs parentheses when substituted into
    /// a larger expression.
    needs_parens: bool,
    /// Whether the RHS has side effects (calls, `new`).
    has_side_effects: bool,
}

/// Walk the AST to find a simple assignment statement at the cursor offset.
///
/// Returns `None` if the cursor is not on a simple `$var = expr;` statement.
fn find_assignment_at_cursor(
    statements: &[Statement<'_>],
    cursor: u32,
    content: &str,
) -> Option<AssignmentInfo> {
    for stmt in statements {
        if let Some(info) = find_assignment_in_statement(stmt, cursor, content) {
            return Some(info);
        }
    }
    None
}

fn find_assignment_in_statement(
    stmt: &Statement<'_>,
    cursor: u32,
    content: &str,
) -> Option<AssignmentInfo> {
    let stmt_span = stmt.span();
    if cursor < stmt_span.start.offset || cursor > stmt_span.end.offset {
        return None;
    }

    match stmt {
        Statement::Expression(expr_stmt) => {
            if let Expression::Assignment(assignment) = expr_stmt.expression {
                // Only simple assignments (not compound like `+=`).
                if !assignment.operator.is_assign() {
                    return None;
                }
                // LHS must be a simple direct variable (not `$this->foo`, not `$$var`).
                let var = match assignment.lhs {
                    Expression::Variable(Variable::Direct(dv)) => dv,
                    _ => return None,
                };

                let var_name = var.name.to_string();
                // Skip `$this`.
                if var_name == "$this" {
                    return None;
                }

                let var_offset = var.span().start.offset;

                let rhs_span = assignment.rhs.span();
                let rhs_start = rhs_span.start.offset as usize;
                let rhs_end = rhs_span.end.offset as usize;

                let stmt_start = stmt_span.start.offset as usize;
                let stmt_end = stmt_span.end.offset as usize;

                let needs_parens = expression_needs_parens(assignment.rhs);
                let has_side_effects = expression_has_side_effects(assignment.rhs);

                // Verify cursor is actually on this statement.
                if (cursor as usize) < stmt_start || (cursor as usize) > stmt_end {
                    return None;
                }

                // Sanity check: RHS text must be extractable.
                if rhs_end > content.len() || rhs_start > rhs_end {
                    return None;
                }

                return Some(AssignmentInfo {
                    var_name,
                    var_offset,
                    rhs_start,
                    rhs_end,
                    stmt_start,
                    stmt_end,
                    needs_parens,
                    has_side_effects,
                });
            }
            None
        }
        // Recurse into function/method bodies, blocks, if/else, loops, etc.
        Statement::Function(func) => {
            let body_span = func.body.span();
            if cursor >= body_span.start.offset && cursor <= body_span.end.offset {
                for s in func.body.statements.iter() {
                    if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                        return Some(info);
                    }
                }
            }
            None
        }
        Statement::Class(class) => {
            let span = class.span();
            if cursor >= span.start.offset && cursor <= span.end.offset {
                for member in class.members.iter() {
                    if let ClassLikeMember::Method(method) = member
                        && let MethodBody::Concrete(block) = &method.body
                    {
                        let block_span = block.span();
                        if cursor >= block_span.start.offset && cursor <= block_span.end.offset {
                            for s in block.statements.iter() {
                                if let Some(info) = find_assignment_in_statement(s, cursor, content)
                                {
                                    return Some(info);
                                }
                            }
                        }
                    }
                }
            }
            None
        }
        Statement::Trait(tr) => {
            let span = tr.span();
            if cursor >= span.start.offset && cursor <= span.end.offset {
                for member in tr.members.iter() {
                    if let ClassLikeMember::Method(method) = member
                        && let MethodBody::Concrete(block) = &method.body
                    {
                        let block_span = block.span();
                        if cursor >= block_span.start.offset && cursor <= block_span.end.offset {
                            for s in block.statements.iter() {
                                if let Some(info) = find_assignment_in_statement(s, cursor, content)
                                {
                                    return Some(info);
                                }
                            }
                        }
                    }
                }
            }
            None
        }
        Statement::Enum(en) => {
            let span = en.span();
            if cursor >= span.start.offset && cursor <= span.end.offset {
                for member in en.members.iter() {
                    if let ClassLikeMember::Method(method) = member
                        && let MethodBody::Concrete(block) = &method.body
                    {
                        let block_span = block.span();
                        if cursor >= block_span.start.offset && cursor <= block_span.end.offset {
                            for s in block.statements.iter() {
                                if let Some(info) = find_assignment_in_statement(s, cursor, content)
                                {
                                    return Some(info);
                                }
                            }
                        }
                    }
                }
            }
            None
        }
        Statement::Interface(_) => None,
        Statement::Block(block) => {
            for s in block.statements.iter() {
                if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                    return Some(info);
                }
            }
            None
        }
        Statement::If(if_stmt) => find_assignment_in_if_body(if_stmt, cursor, content),
        Statement::While(w) => match &w.body {
            WhileBody::Statement(s) => find_assignment_in_statement(s, cursor, content),
            WhileBody::ColonDelimited(body) => {
                for s in body.statements.iter() {
                    if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                        return Some(info);
                    }
                }
                None
            }
        },
        Statement::DoWhile(dw) => find_assignment_in_statement(dw.statement, cursor, content),
        Statement::For(f) => match &f.body {
            ForBody::Statement(s) => find_assignment_in_statement(s, cursor, content),
            ForBody::ColonDelimited(body) => {
                for s in body.statements.iter() {
                    if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                        return Some(info);
                    }
                }
                None
            }
        },
        Statement::Foreach(fe) => match &fe.body {
            ForeachBody::Statement(s) => find_assignment_in_statement(s, cursor, content),
            ForeachBody::ColonDelimited(body) => {
                for s in body.statements.iter() {
                    if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                        return Some(info);
                    }
                }
                None
            }
        },
        Statement::Switch(sw) => {
            for case in sw.body.cases().iter() {
                let stmts = match case {
                    SwitchCase::Expression(c) => &c.statements,
                    SwitchCase::Default(c) => &c.statements,
                };
                for s in stmts.iter() {
                    if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                        return Some(info);
                    }
                }
            }
            None
        }
        Statement::Try(t) => {
            for s in t.block.statements.iter() {
                if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                    return Some(info);
                }
            }
            for catch in t.catch_clauses.iter() {
                for s in catch.block.statements.iter() {
                    if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                        return Some(info);
                    }
                }
            }
            if let Some(ref finally) = t.finally_clause {
                for s in finally.block.statements.iter() {
                    if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                        return Some(info);
                    }
                }
            }
            None
        }
        Statement::Namespace(ns) => {
            for s in ns.statements().iter() {
                if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                    return Some(info);
                }
            }
            None
        }
        _ => None,
    }
}

fn find_assignment_in_if_body(
    if_stmt: &If<'_>,
    cursor: u32,
    content: &str,
) -> Option<AssignmentInfo> {
    match &if_stmt.body {
        IfBody::Statement(body) => {
            if let Some(info) = find_assignment_in_statement(body.statement, cursor, content) {
                return Some(info);
            }
            for clause in body.else_if_clauses.iter() {
                if let Some(info) = find_assignment_in_statement(clause.statement, cursor, content)
                {
                    return Some(info);
                }
            }
            if let Some(ref else_clause) = body.else_clause
                && let Some(info) =
                    find_assignment_in_statement(else_clause.statement, cursor, content)
            {
                return Some(info);
            }
            None
        }
        IfBody::ColonDelimited(body) => {
            for s in body.statements.iter() {
                if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                    return Some(info);
                }
            }
            for clause in body.else_if_clauses.iter() {
                for s in clause.statements.iter() {
                    if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                        return Some(info);
                    }
                }
            }
            if let Some(ref else_clause) = body.else_clause {
                for s in else_clause.statements.iter() {
                    if let Some(info) = find_assignment_in_statement(s, cursor, content) {
                        return Some(info);
                    }
                }
            }
            None
        }
    }
}

/// Check whether an expression needs parentheses when substituted into a
/// surrounding expression context.
///
/// Binary, ternary, and assignment expressions need wrapping to preserve
/// precedence.  Everything else (literals, variables, calls, property
/// accesses, array accesses) is fine without parens.
fn expression_needs_parens(expr: &Expression<'_>) -> bool {
    matches!(
        expr,
        Expression::Binary(_) | Expression::Conditional(_) | Expression::Assignment(_)
    )
}

/// Check whether an expression has side effects.
///
/// Expressions with side effects:
/// - Function calls, method calls, static method calls
/// - `new` (instantiation)
/// - `clone`
/// - Language constructs: `include`, `require`, `eval`, `print`, `exit`, `die`
/// - Yield expressions
/// - Assignment expressions
///
/// Pure expressions:
/// - Variables, literals, constants
/// - Property/array access
/// - Binary/unary operations (on pure operands)
/// - Ternary/null-coalescing
/// - String interpolation
/// - `isset`, `empty`
fn expression_has_side_effects(expr: &Expression<'_>) -> bool {
    match expr {
        // Calls — always side-effectful.
        Expression::Call(_) => true,
        // Instantiation — side-effectful.
        Expression::Instantiation(_) => true,
        // Clone — side-effectful (calls __clone).
        Expression::Clone(_) => true,
        // Yield — side-effectful.
        Expression::Yield(_) => true,
        // Throw — side-effectful.
        Expression::Throw(_) => true,
        // Assignment in the RHS is side-effectful.
        Expression::Assignment(a) => {
            // The assignment itself is a side effect, plus check the RHS.
            let _ = a;
            true
        }
        // Language constructs with side effects.
        Expression::Construct(construct) => matches!(
            construct,
            Construct::Eval(_)
                | Construct::Include(_)
                | Construct::IncludeOnce(_)
                | Construct::Require(_)
                | Construct::RequireOnce(_)
                | Construct::Print(_)
                | Construct::Exit(_)
                | Construct::Die(_)
        ),
        // Unary postfix (++/--) is side-effectful.
        Expression::UnaryPostfix(_) => true,
        // Unary prefix: check if it's ++ or -- (side-effectful) or
        // a pure operator like `-`, `!`, `~`.
        Expression::UnaryPrefix(u) => {
            // The increment/decrement operators in prefix position
            // are side-effectful.  We check for `++` and `--`.
            let op_span = u.operator.span();
            let op_len = (op_span.end.offset - op_span.start.offset) as usize;
            // `++` and `--` are 2 chars; `!`, `~`, `-`, `+` are 1 char.
            if op_len >= 2 {
                true
            } else {
                expression_has_side_effects(u.operand)
            }
        }
        // Recursive checks for compound pure expressions.
        Expression::Binary(b) => {
            expression_has_side_effects(b.lhs) || expression_has_side_effects(b.rhs)
        }
        Expression::Conditional(c) => {
            expression_has_side_effects(c.condition)
                || c.then.is_some_and(|t| expression_has_side_effects(t))
                || expression_has_side_effects(c.r#else)
        }
        Expression::Parenthesized(p) => expression_has_side_effects(p.expression),
        Expression::Array(arr) => arr.elements.iter().any(|el| match el {
            ArrayElement::KeyValue(kv) => {
                expression_has_side_effects(kv.key) || expression_has_side_effects(kv.value)
            }
            ArrayElement::Value(v) => expression_has_side_effects(v.value),
            ArrayElement::Variadic(s) => expression_has_side_effects(s.value),
            ArrayElement::Missing(_) => false,
        }),
        Expression::LegacyArray(arr) => arr.elements.iter().any(|el| match el {
            ArrayElement::KeyValue(kv) => {
                expression_has_side_effects(kv.key) || expression_has_side_effects(kv.value)
            }
            ArrayElement::Value(v) => expression_has_side_effects(v.value),
            ArrayElement::Variadic(s) => expression_has_side_effects(s.value),
            ArrayElement::Missing(_) => false,
        }),
        Expression::CompositeString(cs) => cs.parts().iter().any(|part| match part {
            StringPart::Expression(e) => expression_has_side_effects(e),
            StringPart::BracedExpression(b) => expression_has_side_effects(b.expression),
            StringPart::Literal(_) => false,
        }),
        Expression::ArrayAccess(a) => {
            expression_has_side_effects(a.array) || expression_has_side_effects(a.index)
        }
        // Pipe operator — the callable is invoked, so side-effectful.
        Expression::Pipe(_) => true,
        // Match expressions — arms may contain side effects.
        Expression::Match(m) => {
            expression_has_side_effects(m.expression)
                || m.arms.iter().any(|arm| match arm {
                    MatchArm::Expression(ea) => {
                        ea.conditions.iter().any(|c| expression_has_side_effects(c))
                            || expression_has_side_effects(ea.expression)
                    }
                    MatchArm::Default(da) => expression_has_side_effects(da.expression),
                })
        }
        // Anonymous class — side-effectful (creates a class).
        Expression::AnonymousClass(_) => true,
        // Closures and arrow functions are pure values (they don't
        // execute until called).
        Expression::Closure(_) | Expression::ArrowFunction(_) => false,
        // Everything else: variables, literals, property access,
        // static property access, class constant access, identifiers,
        // magic constants, self/static/parent, etc.
        _ => false,
    }
}

// ─── Scope map building ─────────────────────────────────────────────────────

/// Build a `ScopeMap` for the file by walking the AST, identical to the
/// approach used in extract_variable.
fn build_scope_map(content: &str, offset: u32) -> ScopeMap {
    with_parsed_program(content, "inline_variable", |program, _content| {
        // Try to find the enclosing function or method.
        for stmt in program.statements.iter() {
            if let Some(map) = try_build_scope_from_statement(stmt, offset) {
                return map;
            }
        }

        // Fallback: top-level scope.
        let body_end = content.len() as u32;
        collect_scope(program.statements.as_slice(), 0, body_end)
    })
}

fn try_build_scope_from_statement(stmt: &Statement<'_>, offset: u32) -> Option<ScopeMap> {
    match stmt {
        Statement::Function(func) => {
            let body_start = func.body.left_brace.start.offset;
            let body_end = func.body.right_brace.end.offset;
            if offset >= body_start && offset <= body_end {
                return Some(collect_function_scope(
                    &func.parameter_list,
                    func.body.statements.as_slice(),
                    body_start,
                    body_end,
                ));
            }
            None
        }
        Statement::Class(class) => {
            for member in class.members.iter() {
                if let ClassLikeMember::Method(method) = member
                    && let MethodBody::Concrete(block) = &method.body
                {
                    let body_start = block.left_brace.start.offset;
                    let body_end = block.right_brace.end.offset;
                    if offset >= body_start && offset <= body_end {
                        return Some(collect_function_scope(
                            &method.parameter_list,
                            block.statements.as_slice(),
                            body_start,
                            body_end,
                        ));
                    }
                }
            }
            None
        }
        Statement::Trait(tr) => {
            for member in tr.members.iter() {
                if let ClassLikeMember::Method(method) = member
                    && let MethodBody::Concrete(block) = &method.body
                {
                    let body_start = block.left_brace.start.offset;
                    let body_end = block.right_brace.end.offset;
                    if offset >= body_start && offset <= body_end {
                        return Some(collect_function_scope(
                            &method.parameter_list,
                            block.statements.as_slice(),
                            body_start,
                            body_end,
                        ));
                    }
                }
            }
            None
        }
        Statement::Enum(en) => {
            for member in en.members.iter() {
                if let ClassLikeMember::Method(method) = member
                    && let MethodBody::Concrete(block) = &method.body
                {
                    let body_start = block.left_brace.start.offset;
                    let body_end = block.right_brace.end.offset;
                    if offset >= body_start && offset <= body_end {
                        return Some(collect_function_scope(
                            &method.parameter_list,
                            block.statements.as_slice(),
                            body_start,
                            body_end,
                        ));
                    }
                }
            }
            None
        }
        Statement::Namespace(ns) => {
            for inner_stmt in ns.statements().iter() {
                if let Some(map) = try_build_scope_from_statement(inner_stmt, offset) {
                    return Some(map);
                }
            }
            None
        }
        _ => None,
    }
}

// ─── Line deletion helpers ──────────────────────────────────────────────────

/// Compute the byte range for deleting an entire statement line.
///
/// Extends the statement span to include leading whitespace and the
/// trailing newline (if present), so that removing the statement doesn't
/// leave a blank line.
/// Check whether inlining the given assignment is safe, based on scope
/// analysis.
///
/// A simple assignment `$var = expr;` completely overwrites the variable,
/// so earlier writes and read-writes (e.g. `$arr[] = …` building up an
/// array) are irrelevant to the inline.  Only occurrences **after** the
/// assignment matter:
///
/// - There must be at least one read after the assignment.
/// - There must be no writes or read-writes after the assignment (which
///   would mean the variable is reassigned or mutated later).
/// - When the RHS has side effects, there must be at most one read.
fn is_inline_safe(info: &AssignmentInfo, content: &str, cursor_offset: u32) -> bool {
    let scope_map = build_scope_map(content, cursor_offset);
    let occurrences = scope_map.all_occurrences(&info.var_name, info.var_offset);

    if occurrences.is_empty() {
        return false;
    }

    // Only consider occurrences after the assignment statement.
    // The RHS may read the variable (e.g. `$x = foo($x)`), but that
    // read consumes the *old* value and is part of the statement being
    // deleted, so it must not count as a post-assignment read.
    let after_stmt = occurrences
        .iter()
        .filter(|(offset, _)| (*offset as usize) >= info.stmt_end);

    let read_count = after_stmt
        .clone()
        .filter(|(_, kind)| matches!(kind, AccessKind::Read))
        .count();
    let write_count = after_stmt
        .clone()
        .filter(|(_, kind)| matches!(kind, AccessKind::Write))
        .count();
    let read_write_count = after_stmt
        .filter(|(_, kind)| matches!(kind, AccessKind::ReadWrite))
        .count();

    if read_count == 0 || write_count > 0 || read_write_count > 0 {
        return false;
    }

    if info.has_side_effects && read_count > 1 {
        return false;
    }

    true
}

fn deletion_range(content: &str, stmt_start: usize, stmt_end: usize) -> (usize, usize) {
    // Extend backward to the start of the line (include leading whitespace).
    let line_start = content[..stmt_start]
        .rfind('\n')
        .map(|pos| pos + 1)
        .unwrap_or(0);

    // Check that everything between line_start and stmt_start is whitespace.
    let prefix = &content[line_start..stmt_start];
    let del_start = if prefix.chars().all(|c| c == ' ' || c == '\t') {
        line_start
    } else {
        stmt_start
    };

    // Extend forward past the trailing newline.
    let del_end = if stmt_end < content.len() && content.as_bytes()[stmt_end] == b'\n' {
        stmt_end + 1
    } else if stmt_end + 1 < content.len()
        && content.as_bytes()[stmt_end] == b'\r'
        && content.as_bytes()[stmt_end + 1] == b'\n'
    {
        stmt_end + 2
    } else {
        stmt_end
    };

    (del_start, del_end)
}

// ─── Code action ────────────────────────────────────────────────────────────

impl Backend {
    /// Collect "Inline Variable" code actions.
    ///
    /// This action is offered when the cursor is on a simple variable
    /// assignment statement (`$var = expr;`).  It replaces every read of
    /// the variable with the RHS expression and deletes the assignment.
    ///
    /// Phase 1 only parses the AST to verify the cursor is on an
    /// assignment.  The expensive scope analysis and safety checks are
    /// deferred to [`resolve_inline_variable`] (Phase 2).
    pub(crate) fn collect_inline_variable_actions(
        &self,
        uri: &str,
        content: &str,
        params: &CodeActionParams,
        out: &mut Vec<CodeActionOrCommand>,
    ) {
        let cursor_offset = position_to_byte_offset(content, params.range.start) as u32;

        // ── 1. Find the assignment at the cursor ────────────────────
        // If the cursor is not on a simple `$var = expr;` assignment,
        // no action is offered.
        let info = with_parsed_program(content, "inline_variable", |program, content| {
            find_assignment_at_cursor(program.statements.as_slice(), cursor_offset, content)
        });

        let info = match info {
            Some(i) => i,
            None => return,
        };

        // ── 2. Scope analysis and safety checks ─────────────────────
        // Run the same checks that Phase 2 uses so the action is only
        // offered when it can actually be applied.  The parse is cached
        // by `with_parsed_program`, so there is no extra parse cost.
        if !is_inline_safe(&info, content, cursor_offset) {
            return;
        }

        out.push(CodeActionOrCommand::CodeAction(CodeAction {
            title: format!("Inline variable {}", info.var_name),
            kind: Some(CodeActionKind::REFACTOR_INLINE),
            diagnostics: None,
            edit: None,
            command: None,
            is_preferred: Some(false),
            disabled: None,
            data: Some(make_code_action_data(
                "refactor.inlineVariable",
                uri,
                &params.range,
                serde_json::json!({}),
            )),
        }));
    }

    /// Resolve a deferred "Inline Variable" code action.
    ///
    /// Re-runs the full analysis using the cursor range from `data` to
    /// find the assignment, build the scope, locate all usages, and
    /// construct the workspace edit with deletion + replacements.
    ///
    /// The safety checks are also performed in Phase 1 (so the action
    /// is not offered when unsafe), but they are repeated here because
    /// the file content may have changed between phases.
    pub(crate) fn resolve_inline_variable(
        &self,
        data: &CodeActionData,
        content: &str,
    ) -> Option<WorkspaceEdit> {
        let cursor_offset = position_to_byte_offset(content, data.range.start) as u32;

        // ── 1. Find the assignment at the cursor ────────────────────
        let info = with_parsed_program(content, "inline_variable", |program, content| {
            find_assignment_at_cursor(program.statements.as_slice(), cursor_offset, content)
        })?;

        // ── 2. Build scope map and check safety ─────────────────────
        let scope_map = build_scope_map(content, cursor_offset);
        let occurrences = scope_map.all_occurrences(&info.var_name, info.var_offset);

        if occurrences.is_empty() {
            return None;
        }

        // Only consider occurrences after the assignment statement.
        let after_stmt = occurrences
            .iter()
            .filter(|(offset, _)| (*offset as usize) >= info.stmt_end);

        let read_count = after_stmt
            .clone()
            .filter(|(_, kind)| matches!(kind, AccessKind::Read))
            .count();
        let write_count = after_stmt
            .clone()
            .filter(|(_, kind)| matches!(kind, AccessKind::Write))
            .count();
        let read_write_count = after_stmt
            .filter(|(_, kind)| matches!(kind, AccessKind::ReadWrite))
            .count();

        if read_count == 0 || write_count > 0 || read_write_count > 0 {
            return None;
        }

        if info.has_side_effects && read_count > 1 {
            return None;
        }

        // ── 3. Extract the RHS text ─────────────────────────────────
        let rhs_text = &content[info.rhs_start..info.rhs_end];

        // ── 4. Build the workspace edit ─────────────────────────────
        let doc_uri: Url = match data.uri.parse() {
            Ok(u) => u,
            Err(_) => return None,
        };

        let mut edits: Vec<TextEdit> = Vec::new();

        // 4a. Delete the assignment statement line.
        let (del_start, del_end) = deletion_range(content, info.stmt_start, info.stmt_end);
        let del_start_pos = offset_to_position(content, del_start);
        let del_end_pos = offset_to_position(content, del_end);
        edits.push(TextEdit {
            range: Range {
                start: del_start_pos,
                end: del_end_pos,
            },
            new_text: String::new(),
        });

        // 4b. Replace each read occurrence with the RHS text.
        let replacement = if info.needs_parens {
            format!("({})", rhs_text)
        } else {
            rhs_text.to_string()
        };

        for (offset, kind) in &occurrences {
            if !matches!(kind, AccessKind::Read) {
                continue;
            }
            // Only replace reads after the assignment statement.
            // Reads within the RHS (e.g. `$badges` in
            // `$badges = self::computeBadges($model, $badges)`)
            // must not be touched.
            if (*offset as usize) < info.stmt_end {
                continue;
            }
            let start = *offset as usize;
            let end = start + info.var_name.len();

            // Verify the text at this offset matches the variable name.
            if end > content.len() || content[start..end] != info.var_name {
                continue;
            }

            let start_pos = offset_to_position(content, start);
            let end_pos = offset_to_position(content, end);
            edits.push(TextEdit {
                range: Range {
                    start: start_pos,
                    end: end_pos,
                },
                new_text: replacement.clone(),
            });
        }

        // Sort edits by position (document order) for determinism.
        edits.sort_by(|a, b| {
            a.range
                .start
                .line
                .cmp(&b.range.start.line)
                .then(a.range.start.character.cmp(&b.range.start.character))
        });

        let mut changes = HashMap::new();
        changes.insert(doc_uri, edits);

        Some(WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        })
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    /// Helper: given PHP source with a cursor marker `/*|*/`, run the
    /// inline variable action and return the resulting edits (if offered).
    fn run_inline(php: &str) -> Option<Vec<TextEdit>> {
        let marker = "/*|*/";
        let marker_pos = php.find(marker)?;
        let content = php.replace(marker, "");

        let uri = "file:///test.php";
        let cursor_offset = marker_pos;
        let position = offset_to_position(&content, cursor_offset);
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: Url::parse(uri).unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let backend = Backend::new_test();
        // Store file content so resolve_code_action can retrieve it.
        backend
            .open_files
            .write()
            .insert(uri.to_string(), std::sync::Arc::new(content.clone()));

        let mut actions = Vec::new();
        backend.collect_inline_variable_actions(uri, &content, &params, &mut actions);

        if actions.is_empty() {
            return None;
        }

        let action = match &actions[0] {
            CodeActionOrCommand::CodeAction(a) => a.clone(),
            _ => return None,
        };

        // Phase 1 should have data but no edit.
        assert!(action.edit.is_none(), "Phase 1 should not compute edits");
        assert!(action.data.is_some(), "Phase 1 should attach resolve data");

        // Phase 2: resolve the action to get the workspace edit.
        let (resolved, _) = backend.resolve_code_action(action);
        let edit = resolved.edit.as_ref()?;
        let changes = edit.changes.as_ref()?;
        let parsed_uri = Url::parse(uri).unwrap();
        let edits = changes.get(&parsed_uri)?;
        Some(edits.clone())
    }

    /// Apply TextEdits to content (edits are assumed to be non-overlapping
    /// and will be applied from bottom to top to preserve positions).
    fn apply_edits(content: &str, edits: &[TextEdit]) -> String {
        let mut result = content.to_string();
        // Sort edits in reverse document order so earlier edits don't
        // shift positions of later ones.
        let mut sorted: Vec<&TextEdit> = edits.iter().collect();
        sorted.sort_by(|a, b| {
            b.range
                .start
                .line
                .cmp(&a.range.start.line)
                .then(b.range.start.character.cmp(&a.range.start.character))
        });
        for edit in sorted {
            let start = position_to_byte_offset(&result, edit.range.start);
            let end = position_to_byte_offset(&result, edit.range.end);
            result.replace_range(start..end, &edit.new_text);
        }
        result
    }

    // ── Basic inline ────────────────────────────────────────────────

    #[test]
    fn inline_simple_variable() {
        let php = r#"<?php
function foo() {
    /*|*/$name = $user->getName();
    echo $name;
}
"#;
        let content_without_marker = php.replace("/*|*/", "");
        let edits = run_inline(php).expect("action should be offered");
        let result = apply_edits(&content_without_marker, &edits);
        assert!(!result.contains("$name = "), "assignment should be removed");
        assert!(
            result.contains("echo $user->getName();"),
            "read should be replaced with RHS: got:\n{}",
            result
        );
    }

    #[test]
    fn inline_variable_multiple_reads() {
        let php = r#"<?php
function foo($user) {
    /*|*/$name = $user->email;
    echo $name;
    return $name;
}
"#;
        let content_without_marker = php.replace("/*|*/", "");
        let edits = run_inline(php).expect("action should be offered");
        let result = apply_edits(&content_without_marker, &edits);
        assert!(!result.contains("$name = "), "assignment should be removed");
        assert!(
            result.contains("echo $user->email;"),
            "first read should be replaced: got:\n{}",
            result
        );
        assert!(
            result.contains("return $user->email;"),
            "second read should be replaced: got:\n{}",
            result
        );
    }

    // ── Safety: reject multiple writes ──────────────────────────────

    #[test]
    fn reject_multiple_writes() {
        let php = r#"<?php
function foo() {
    /*|*/$name = 'hello';
    $name = 'world';
    echo $name;
}
"#;
        assert!(
            run_inline(php).is_none(),
            "should reject: variable is reassigned"
        );
    }

    // ── Safety: reject side-effectful RHS with multiple reads ───────

    #[test]
    fn reject_side_effects_multiple_reads() {
        let php = r#"<?php
function foo() {
    /*|*/$val = getResult();
    echo $val;
    return $val;
}
"#;
        assert!(
            run_inline(php).is_none(),
            "should reject: side-effectful RHS with multiple reads"
        );
    }

    #[test]
    fn allow_side_effects_single_read() {
        let php = r#"<?php
function foo() {
    /*|*/$val = getResult();
    echo $val;
}
"#;
        assert!(
            run_inline(php).is_some(),
            "should allow: side-effectful RHS with single read"
        );
    }

    // ── Parenthesisation ────────────────────────────────────────────

    #[test]
    fn adds_parens_for_binary_expression() {
        let php = r#"<?php
function foo($a, $b) {
    /*|*/$sum = $a + $b;
    echo $sum;
}
"#;
        let content_without_marker = php.replace("/*|*/", "");
        let edits = run_inline(php).expect("action should be offered");
        let result = apply_edits(&content_without_marker, &edits);
        assert!(
            result.contains("echo ($a + $b);"),
            "binary expression should be wrapped in parens: got:\n{}",
            result
        );
    }

    #[test]
    fn no_parens_for_simple_expression() {
        let php = r#"<?php
function foo($user) {
    /*|*/$name = $user->name;
    echo $name;
}
"#;
        let content_without_marker = php.replace("/*|*/", "");
        let edits = run_inline(php).expect("action should be offered");
        let result = apply_edits(&content_without_marker, &edits);
        assert!(
            result.contains("echo $user->name;"),
            "property access should NOT be wrapped in parens: got:\n{}",
            result
        );
    }

    // ── Compound assignment → reject ────────────────────────────────

    #[test]
    fn reject_compound_assignment() {
        // The cursor is on a compound assignment (`.=`), which is not a
        // simple `$var = expr` assignment — should not be offered.
        let php = r#"<?php
function foo() {
    $name = 'hello';
    /*|*/$name .= ' world';
    echo $name;
}
"#;
        assert!(
            run_inline(php).is_none(),
            "should reject: compound assignment is not a simple assignment"
        );
    }

    // ── Method body ─────────────────────────────────────────────────

    #[test]
    fn inline_in_method_body() {
        let php = r#"<?php
class Foo {
    public function bar() {
        /*|*/$x = 42;
        return $x;
    }
}
"#;
        let content_without_marker = php.replace("/*|*/", "");
        let edits = run_inline(php).expect("action should be offered");
        let result = apply_edits(&content_without_marker, &edits);
        assert!(
            result.contains("return 42;"),
            "read should be replaced: got:\n{}",
            result
        );
        assert!(
            !result.contains("$x = 42"),
            "assignment should be deleted: got:\n{}",
            result
        );
    }

    // ── Ternary expression needs parens ─────────────────────────────

    #[test]
    fn adds_parens_for_ternary() {
        let php = r#"<?php
function foo($a) {
    /*|*/$val = $a ? 'yes' : 'no';
    echo $val;
}
"#;
        let content_without_marker = php.replace("/*|*/", "");
        let edits = run_inline(php).expect("action should be offered");
        let result = apply_edits(&content_without_marker, &edits);
        assert!(
            result.contains("echo ($a ? 'yes' : 'no');"),
            "ternary should be wrapped in parens: got:\n{}",
            result
        );
    }

    // ── Code action kind ────────────────────────────────────────────

    #[test]
    fn code_action_kind_is_refactor_inline() {
        let php = r#"<?php
function foo() {
    /*|*/$x = 1;
    echo $x;
}
"#;
        let content = php.replace("/*|*/", "");
        let marker_pos = php.find("/*|*/").unwrap();
        let position = offset_to_position(&content, marker_pos);
        let uri = "file:///test.php";
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: Url::parse(uri).unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let backend = Backend::new_test();
        let mut actions = Vec::new();
        backend.collect_inline_variable_actions(uri, &content, &params, &mut actions);

        assert!(!actions.is_empty(), "action should be offered");
        match &actions[0] {
            CodeActionOrCommand::CodeAction(a) => {
                assert_eq!(a.kind, Some(CodeActionKind::REFACTOR_INLINE));
                // Phase 1: no edit, has data.
                assert!(a.edit.is_none(), "Phase 1 should not compute edits");
                assert!(a.data.is_some(), "Phase 1 should attach resolve data");
            }
            _ => panic!("expected CodeAction"),
        }
    }

    // ── Title format ────────────────────────────────────────────────

    #[test]
    fn title_includes_variable_name() {
        let php = r#"<?php
function foo() {
    /*|*/$myVar = 1;
    echo $myVar;
}
"#;
        let content = php.replace("/*|*/", "");
        let marker_pos = php.find("/*|*/").unwrap();
        let position = offset_to_position(&content, marker_pos);
        let uri = "file:///test.php";
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: Url::parse(uri).unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let backend = Backend::new_test();
        let mut actions = Vec::new();
        backend.collect_inline_variable_actions(uri, &content, &params, &mut actions);

        assert!(!actions.is_empty());
        match &actions[0] {
            CodeActionOrCommand::CodeAction(a) => {
                assert_eq!(a.title, "Inline variable $myVar");
            }
            _ => panic!("expected CodeAction"),
        }
    }

    // ── No reads → no action ────────────────────────────────────────

    #[test]
    fn reject_no_reads() {
        let php = r#"<?php
function foo() {
    /*|*/$x = 1;
}
"#;
        assert!(
            run_inline(php).is_none(),
            "should reject: variable has no reads"
        );
    }

    // ── ReadWrite (e.g. $x++) → reject ──────────────────────────────

    #[test]
    fn reject_read_write_usage() {
        let php = r#"<?php
function foo() {
    /*|*/$x = 0;
    $x++;
}
"#;
        assert!(
            run_inline(php).is_none(),
            "should reject: variable has read-write access ($x++)"
        );
    }

    // ── String literal RHS ──────────────────────────────────────────

    #[test]
    fn inline_string_literal() {
        let php = r#"<?php
function foo() {
    /*|*/$msg = 'hello world';
    echo $msg;
}
"#;
        let content_without_marker = php.replace("/*|*/", "");
        let edits = run_inline(php).expect("action should be offered");
        let result = apply_edits(&content_without_marker, &edits);
        assert!(
            result.contains("echo 'hello world';"),
            "string literal should be inlined: got:\n{}",
            result
        );
    }

    // ── Pure expression helpers ─────────────────────────────────────

    #[test]
    fn side_effect_detection_literals_are_pure() {
        // This is implicitly tested via inline_string_literal and
        // inline_variable_multiple_reads, but we also verify the helper
        // accepts property access with multiple reads.
        let php = r#"<?php
function foo($obj) {
    /*|*/$x = $obj->name;
    echo $x;
    return $x;
}
"#;
        assert!(
            run_inline(php).is_some(),
            "pure property access should be inlinable with multiple reads"
        );
    }

    // ── Deletion range helper ───────────────────────────────────────

    #[test]
    fn deletion_range_includes_indentation_and_newline() {
        let content = "    $x = 1;\n    echo $x;\n";
        let (start, end) = deletion_range(content, 4, 15); // "$x = 1;" is at 4..15
        // Should include leading spaces and trailing newline.
        assert_eq!(start, 0, "should start at line beginning");
        // stmt_end is 15 which is ';', the newline is at index 15 (assuming
        // the ";" is at index 14).  Let's check precisely:
        // "    $x = 1;\n" — the `;` is at index 10, `\n` at 11
        // Actually let's just verify the range covers the full line.
        assert!(end > 10, "should extend past the semicolon");
    }

    // ── Inline in namespace ─────────────────────────────────────────

    #[test]
    fn inline_in_namespaced_function() {
        let php = r#"<?php
namespace App;

function bar() {
    /*|*/$val = 123;
    return $val;
}
"#;
        let content_without_marker = php.replace("/*|*/", "");
        let edits = run_inline(php).expect("action should be offered");
        let result = apply_edits(&content_without_marker, &edits);
        assert!(
            result.contains("return 123;"),
            "should inline in namespaced function: got:\n{}",
            result
        );
    }

    // ── new expression is side-effectful ────────────────────────────

    #[test]
    fn reject_new_with_multiple_reads() {
        let php = r#"<?php
function foo() {
    /*|*/$obj = new stdClass();
    echo $obj;
    return $obj;
}
"#;
        assert!(
            run_inline(php).is_none(),
            "should reject: `new` is side-effectful with multiple reads"
        );
    }

    #[test]
    fn allow_new_with_single_read() {
        let php = r#"<?php
function foo() {
    /*|*/$obj = new stdClass();
    return $obj;
}
"#;
        assert!(
            run_inline(php).is_some(),
            "should allow: `new` with single read"
        );
    }

    // ── String interpolation ────────────────────────────────────────

    #[test]
    fn inline_with_string_interpolation() {
        let php = r#"<?php
class OrderProcessor {
    public function processOrder(Order $order): string {
        /*|*/$total = $order->getTotal();
        return "total {$total}";
    }
}
"#;
        assert!(
            run_inline(php).is_some(),
            "should offer inline for variable read inside string interpolation"
        );
    }

    // ── Reassigned variable after earlier writes/read-writes ────────

    #[test]
    fn inline_reassigned_variable_after_array_appends() {
        // The variable has earlier writes ($badges = []) and read-writes
        // ($badges[] = ...), but the cursor is on a later reassignment
        // that overwrites the variable.  After that reassignment there is
        // only a single read (return $badges), so the inline is safe:
        // `return self::computeBadges($model, $badges);`
        let php = r#"<?php
class BadgeHelper {
    public static function getBadges($model, $lang): array {
        $badges = [];

        if ($model->isDerma()) {
            $badges[] = new BadgeViewModel('derma');
        }

        if ($model->isProHairCare()) {
            $badges[] = new BadgeViewModel('pro-hair');
        }

        /*|*/$badges = self::computeBadges($model, $badges);

        return $badges;
    }
}
"#;
        let content_without_marker = php.replace("/*|*/", "");
        let edits = run_inline(php).expect("action should be offered for reassigned variable");
        let result = apply_edits(&content_without_marker, &edits);
        assert!(
            !result.contains("$badges = self::computeBadges"),
            "assignment should be removed:\n{}",
            result
        );
        assert!(
            result.contains("return self::computeBadges($model, $badges);"),
            "return should inline the RHS:\n{}",
            result
        );
    }

    #[test]
    fn reject_reassigned_variable_with_later_mutation() {
        // After the reassignment there is a read-write ($badges[] = ...),
        // so inlining is NOT safe.
        let php = r#"<?php
function getBadges($model) {
    $badges = [];
    /*|*/$badges = self::computeBadges($model, $badges);
    $badges[] = new BadgeViewModel('extra');
    return $badges;
}
"#;
        assert!(
            run_inline(php).is_none(),
            "should reject: variable has read-write access after the assignment"
        );
    }

    #[test]
    fn reject_reassigned_variable_with_later_overwrite() {
        // After the reassignment there is another write, so inlining
        // would lose that overwrite.
        let php = r#"<?php
function getBadges($model) {
    $badges = [];
    /*|*/$badges = self::computeBadges($model, $badges);
    $badges = array_unique($badges);
    return $badges;
}
"#;
        assert!(
            run_inline(php).is_none(),
            "should reject: variable has another write after the assignment"
        );
    }
}