neo-decompiler 0.8.1

Neo N3 NEF decompiler: parse, disassemble, lift bytecode to high-level pseudocode and C# skeletons, with a CLI, JSON reports, and optional WebAssembly bindings.
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
//! Rewrite `if` / `else if` equality chains into `switch` statements.
//!
//! This pass is intentionally conservative: it only rewrites chains that
//! compare the same scrutinee expression against literal case values.
//!
//! Two patterns are recognized:
//! - `if/else if` chains (minimum 2 cases)
//! - Consecutive standalone `if` blocks comparing the same variable (minimum 3 cases)

use super::super::HighLevelEmitter;
use super::util::{extract_any_if_condition, is_else_if_open, is_else_open, is_if_open};

impl HighLevelEmitter {
    /// Rewrite eligible `if` / `else if` chains into `switch` blocks.
    pub(crate) fn rewrite_switch_statements(statements: &mut Vec<String>) {
        let mut index = 0usize;
        while index < statements.len() {
            if let Some((replacement, end)) = try_build_guarded_goto_switch(statements, index) {
                statements.splice(index..=end, replacement);
                index += 1;
                continue;
            }
            if let Some((replacement, end)) = try_build_switch(statements, index) {
                statements.splice(index..=end, replacement);
                index += 1;
                continue;
            }
            index += 1;
        }
    }
}

const MIN_GUARDED_GOTO_CASES: usize = 2;

fn try_build_guarded_goto_switch(
    statements: &[String],
    start: usize,
) -> Option<(Vec<String>, usize)> {
    let mut current_header = start;
    let mut labeled_cases: Vec<(String, String)> = Vec::new();
    let mut scrutinee: Option<String> = None;

    loop {
        let header_line = statements.get(current_header)?.trim();
        if let Some((condition, label)) = parse_inline_if_goto(header_line) {
            let resolved =
                resolve_condition_expression(statements, current_header, condition.as_str())?;
            let (next_scrutinee, case_token) = parse_case_sides(resolved.as_str())?;
            let case_value = resolve_case_value(statements, current_header, case_token)?;
            if !is_literal(case_value.as_str()) {
                return None;
            }
            if let Some(existing) = &scrutinee {
                if existing != &next_scrutinee {
                    return None;
                }
            } else {
                scrutinee = Some(next_scrutinee);
            }
            labeled_cases.push((case_value, label));

            let next_header =
                find_next_guarded_header_after_case_prelude(statements, current_header + 1)?;
            current_header = next_header;
            continue;
        }
        break;
    }

    let header_line = statements.get(current_header)?.trim();
    if !is_if_open(header_line) {
        return None;
    }
    let condition = extract_any_if_condition(header_line)?;
    let resolved = resolve_condition_expression(statements, current_header, condition)?;
    let (next_scrutinee, case_token) = parse_case_sides(resolved.as_str())?;
    let final_case_value = resolve_case_value(statements, current_header, case_token)?;
    if !is_literal(final_case_value.as_str()) {
        return None;
    }
    if let Some(existing) = &scrutinee {
        if existing != &next_scrutinee {
            return None;
        }
    } else {
        scrutinee = Some(next_scrutinee);
    }

    let final_if_end = HighLevelEmitter::find_block_end(statements, current_header)?;
    let (default_label, label_blocks_start) =
        parse_guarded_switch_body_header(statements, current_header + 1, final_if_end)?;
    let label_bodies = collect_label_bodies(statements, label_blocks_start, final_if_end)?;

    let mut cases: Vec<(String, Vec<String>)> = Vec::new();
    for (case_value, label) in &labeled_cases {
        let body = label_bodies.get(label)?;
        if body.is_empty() {
            return None;
        }
        cases.push((case_value.clone(), body.clone()));
    }

    let (final_case_body, default_body, rewrite_end) = if let Some((else_header, else_end)) =
        find_else_block_after(statements, final_if_end + 1)
    {
        if let Some(default_label_index) = find_label_in_range(
            statements,
            else_header + 1,
            else_end,
            default_label.as_str(),
        ) {
            let final_case_body = statements
                .get(else_header + 1..default_label_index)
                .unwrap_or_default()
                .to_vec();
            if final_case_body.is_empty() {
                return None;
            }
            let default_body = statements
                .get(default_label_index + 1..else_end)
                .unwrap_or_default()
                .to_vec();
            if default_body.is_empty() {
                return None;
            }
            (final_case_body, default_body, else_end)
        } else {
            let final_case_body = statements
                .get(else_header + 1..else_end)
                .unwrap_or_default()
                .to_vec();
            if final_case_body.is_empty() {
                return None;
            }
            let default_label_index =
                find_label_after(statements, else_end + 1, default_label.as_str())?;
            let default_end = find_label_body_end(statements, default_label_index + 1);
            if default_end < default_label_index + 1 {
                return None;
            }
            let default_body = statements
                .get(default_label_index + 1..=default_end)
                .unwrap_or_default()
                .to_vec();
            if default_body.is_empty() {
                return None;
            }
            (final_case_body, default_body, default_end)
        }
    } else {
        let default_label_index =
            find_label_after(statements, final_if_end + 1, default_label.as_str())?;
        let final_case_body = statements
            .get(final_if_end + 1..default_label_index)
            .unwrap_or_default()
            .to_vec();
        if final_case_body.is_empty() {
            return None;
        }
        let default_end = find_label_body_end(statements, default_label_index + 1);
        if default_end < default_label_index + 1 {
            return None;
        }
        let default_body = statements
            .get(default_label_index + 1..=default_end)
            .unwrap_or_default()
            .to_vec();
        if default_body.is_empty() {
            return None;
        }
        (final_case_body, default_body, default_end)
    };

    cases.push((final_case_value, final_case_body));

    if cases.len() < MIN_GUARDED_GOTO_CASES {
        return None;
    }

    let mut seen = std::collections::BTreeSet::new();
    if !cases.iter().all(|(value, _)| seen.insert(value.clone())) {
        return None;
    }

    let mut output = Vec::new();
    output.push(format!("switch {} {{", scrutinee?));
    for (value, body) in &cases {
        output.push(format!("case {value} {{"));
        output.extend(body.iter().cloned());
        output.push("}".into());
    }
    output.push("default {".into());
    output.extend(default_body);
    output.push("}".into());
    output.push("}".into());

    Some((output, rewrite_end))
}

fn try_build_switch(statements: &[String], start: usize) -> Option<(Vec<String>, usize)> {
    let header = statements.get(start)?.trim();
    if !is_if_open(header) {
        return None;
    }

    let mut cases: Vec<(String, Vec<String>)> = Vec::new();
    let mut default_body: Option<Vec<String>> = None;
    let mut overall_end = start;
    let mut has_else_link = false;

    let mut current_header = start;
    let mut scrutinee: Option<String> = None;

    loop {
        let header_line = statements.get(current_header)?.trim();
        let condition = extract_any_if_condition(header_line)?;
        let resolved = resolve_condition_expression(statements, current_header, condition)?;
        let (next_scrutinee, case_token) = parse_case_sides(resolved.as_str())?;

        let case_value = resolve_case_value(statements, current_header, case_token)?;
        if !is_literal(case_value.as_str()) {
            return None;
        }

        if let Some(existing) = &scrutinee {
            if existing != &next_scrutinee {
                return None;
            }
        } else {
            scrutinee = Some(next_scrutinee);
        }

        let (body, if_end) = extract_block_body(statements, current_header)?;
        overall_end = overall_end.max(if_end);
        cases.push((case_value, body));

        let (trivia, next_header) = collect_trivia(statements, if_end + 1);
        if next_header >= statements.len() {
            break;
        }

        let next_line = statements[next_header].trim();
        if is_else_if_open(next_line) {
            has_else_link = true;
            if let Some((_, last_body)) = cases.last_mut() {
                last_body.extend(trivia);
            }
            current_header = next_header;
            continue;
        }

        if is_else_open(next_line) {
            has_else_link = true;
            let else_end = HighLevelEmitter::find_block_end(statements, next_header)?;
            overall_end = overall_end.max(else_end);

            // Try to flatten an `else { <if-chain> }` into an `else if`.
            if let Some(inner_start) = find_first_if_in_range(statements, next_header + 1, else_end)
            {
                let inner_chain_end = end_of_if_chain(statements, inner_start)?;
                if inner_chain_end < else_end {
                    let (inner_trivia, after_inner) =
                        collect_trivia(statements, inner_chain_end + 1);
                    let only_trivia_left = after_inner == else_end;
                    if only_trivia_left {
                        if let Some((_, last_body)) = cases.last_mut() {
                            last_body.extend(trivia);
                            last_body.extend(inner_trivia);
                        }
                        current_header = inner_start;
                        overall_end = overall_end.max(else_end);
                        continue;
                    }
                }
            }

            if let Some((_, last_body)) = cases.last_mut() {
                last_body.extend(trivia);
            }

            default_body = Some(
                statements
                    .get(next_header + 1..else_end)
                    .unwrap_or_default()
                    .to_vec(),
            );
            break;
        }

        // Consecutive standalone `if` comparing the same scrutinee.
        if let Some(next_if_header) = find_next_if_after_case_prelude(statements, if_end + 1) {
            let next_if_line = statements[next_if_header].trim();
            if let Some(cond) = extract_any_if_condition(next_if_line) {
                if let Some(resolved) =
                    resolve_condition_expression(statements, next_if_header, cond)
                {
                    if let Some((peek_scrutinee, _)) = parse_case_sides(resolved.as_str()) {
                        if scrutinee.as_deref() == Some(peek_scrutinee.as_str()) {
                            current_header = next_if_header;
                            continue;
                        }
                    }
                }
            }
        }

        break;
    }

    let scrutinee = scrutinee?;

    // Require at least 2 cases for `if/else if` chains (unambiguous pattern)
    // and at least 3 for consecutive standalone `if` blocks (conservative).
    let min_cases = if has_else_link { 2 } else { 3 };
    if cases.len() < min_cases {
        return None;
    }

    // Ensure case values are unique for readability.
    {
        let mut seen = std::collections::BTreeSet::new();
        if !cases.iter().all(|(value, _)| seen.insert(value.clone())) {
            return None;
        }
    }

    // Consecutive standalone `if` blocks (no `else` links) are only
    // equivalent to a `switch` when at most one case can run. The original
    // bytecode executes each `if x == k { ... }` in sequence, so if a case
    // body reassigns the scrutinee a later comparison can also fire — a
    // common state-machine step pattern. A `switch` would assert exactly one
    // case runs, changing program semantics. Require every case body to be
    // provably exclusive (ends in a terminator, or never reassigns the
    // scrutinee) before rewriting; otherwise leave the if-chain intact.
    if !has_else_link
        && !cases
            .iter()
            .all(|(_, body)| case_body_is_switch_safe(body, &scrutinee))
    {
        return None;
    }

    let mut output = Vec::new();
    output.push(format!("switch {scrutinee} {{"));
    for (value, body) in &cases {
        output.push(format!("case {value} {{"));
        output.extend(body.iter().cloned());
        output.push("}".into());
    }
    if let Some(body) = default_body {
        output.push("default {".into());
        output.extend(body);
        output.push("}".into());
    }
    output.push("}".into());

    Some((output, overall_end))
}

fn extract_block_body(statements: &[String], header_index: usize) -> Option<(Vec<String>, usize)> {
    let end = HighLevelEmitter::find_block_end(statements, header_index)?;
    let body = statements
        .get(header_index + 1..end)
        .unwrap_or_default()
        .to_vec();
    Some((body, end))
}

fn collect_trivia(statements: &[String], mut index: usize) -> (Vec<String>, usize) {
    let mut trivia = Vec::new();
    while index < statements.len() {
        let trimmed = statements[index].trim();
        if trimmed.is_empty() || trimmed.starts_with("//") {
            trivia.push(statements[index].clone());
            index += 1;
            continue;
        }
        break;
    }
    (trivia, index)
}

fn resolve_condition_expression(
    statements: &[String],
    header_index: usize,
    condition: &str,
) -> Option<String> {
    if condition.contains("==") {
        return Some(condition.trim().to_string());
    }
    let condition = condition.trim();
    let condition = condition
        .strip_prefix('!')
        .map(str::trim)
        .unwrap_or(condition);
    let prev = HighLevelEmitter::previous_code_line(statements, header_index)?;
    let assign = HighLevelEmitter::parse_assignment(statements[prev].as_str())?;
    (assign.lhs == condition).then_some(assign.rhs)
}

fn parse_case_sides(condition: &str) -> Option<(String, &str)> {
    let (left, right) = split_equals(condition)?;
    let left = left.trim();
    let right = right.trim();

    if is_literal(left) && !is_literal(right) {
        return Some((right.to_string(), left));
    }
    if !is_literal(left) && is_literal(right) {
        return Some((left.to_string(), right));
    }

    // Common compiler shape: `loc0 == t1` where `t1` is a pushed literal.
    if is_temp(left) && !is_temp(right) {
        return Some((right.to_string(), left));
    }
    if is_temp(right) && !is_temp(left) {
        return Some((left.to_string(), right));
    }

    None
}

fn resolve_case_value(statements: &[String], header_index: usize, token: &str) -> Option<String> {
    if is_literal(token) {
        return Some(token.trim().to_string());
    }
    if !is_temp(token) {
        return None;
    }

    let mut cursor = header_index;
    while let Some(prev) = HighLevelEmitter::previous_code_line(statements, cursor) {
        cursor = prev;
        let Some(assign) = HighLevelEmitter::parse_assignment(statements[prev].as_str()) else {
            continue;
        };
        if assign.lhs != token {
            continue;
        }
        let rhs = assign.rhs.trim().to_string();
        return is_literal(rhs.as_str()).then_some(rhs);
    }
    None
}

fn split_equals(condition: &str) -> Option<(&str, &str)> {
    let pos = condition.find("==")?;
    let (left, rest) = condition.split_at(pos);
    let right = rest.strip_prefix("==")?;
    Some((left, right))
}

fn is_literal(value: &str) -> bool {
    let value = value.trim();
    if value.is_empty() {
        return false;
    }
    if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
        return true;
    }
    if value.starts_with('\'') && value.ends_with('\'') && value.len() >= 3 {
        return true;
    }
    if matches!(value, "true" | "false" | "null") {
        return true;
    }
    if value.starts_with("0x") && value.len() > 2 {
        return value[2..].chars().all(|ch| ch.is_ascii_hexdigit());
    }
    value.parse::<i64>().is_ok()
}

fn is_temp(value: &str) -> bool {
    // A temp identifier is `t` followed by at least one digit (`t0`, `t12`),
    // matching the JS port's `^t\d+$`. The non-empty digit requirement avoids
    // treating a bare `t` as a temp.
    let value = value.trim();
    value.len() > 1 && value.starts_with('t') && value[1..].bytes().all(|b| b.is_ascii_digit())
}

fn find_first_if_in_range(statements: &[String], start: usize, end: usize) -> Option<usize> {
    let mut index = start;
    while index < end {
        let trimmed = statements[index].trim();
        if trimmed.is_empty() || trimmed.starts_with("//") {
            index += 1;
            continue;
        }
        if is_if_open(trimmed) {
            return Some(index);
        }
        index += 1;
    }
    None
}

fn find_next_if_after_case_prelude(statements: &[String], start: usize) -> Option<usize> {
    let mut index = start;
    while index < statements.len() {
        let trimmed = statements[index].trim();
        if trimmed.is_empty() || trimmed.starts_with("//") {
            index += 1;
            continue;
        }
        if is_if_open(trimmed) {
            return Some(index);
        }
        // Only skip a genuine case-value temp definition: a `tN = …` whose temp
        // feeds the upcoming case comparison (so it is referenced by the next
        // code statement). Anything else must block the fold so it is not
        // spliced away and silently dropped — a real local assignment
        // (`loc5 = effect();`) AND a temp that captures a side-effecting call
        // and discards it (`let t7 = Foo(arg);`, not consumed by the next case).
        if let Some(assign) = HighLevelEmitter::parse_assignment(statements[index].as_str()) {
            if is_temp(&assign.lhs) && temp_consumed_by_next_code(statements, index, &assign.lhs) {
                index += 1;
                continue;
            }
        }
        return None;
    }
    None
}

/// A case-value temp prelude (`tN = <value>;`) feeds the upcoming comparison, so
/// `tN` is referenced by the next code statement (e.g. `tN = loc0 == tM;` or
/// `if tN { … }`). A temp that captures a side-effecting call and is discarded
/// is not referenced; treat it as a real statement so the switch fold is blocked
/// and it is preserved.
fn temp_consumed_by_next_code(statements: &[String], index: usize, temp: &str) -> bool {
    statements
        .iter()
        .skip(index + 1)
        .find(|stmt| {
            let trimmed = stmt.trim();
            !trimmed.is_empty() && !trimmed.starts_with("//")
        })
        .is_some_and(|stmt| HighLevelEmitter::contains_identifier(stmt, temp))
}

fn find_next_guarded_header_after_case_prelude(
    statements: &[String],
    start: usize,
) -> Option<usize> {
    let mut index = start;
    while index < statements.len() {
        let trimmed = statements[index].trim();
        if trimmed.is_empty() || trimmed.starts_with("//") {
            index += 1;
            continue;
        }
        if parse_inline_if_goto(trimmed).is_some() || is_if_open(trimmed) {
            return Some(index);
        }
        // See find_next_if_after_case_prelude: only skip a case-value temp that
        // feeds the upcoming comparison; a real inter-case assignment or a temp
        // capturing a discarded side-effecting call must block the fold so it is
        // not silently dropped.
        if let Some(assign) = HighLevelEmitter::parse_assignment(statements[index].as_str()) {
            if is_temp(&assign.lhs) && temp_consumed_by_next_code(statements, index, &assign.lhs) {
                index += 1;
                continue;
            }
        }
        return None;
    }
    None
}

/// A standalone-`if` case body is safe to fold into a `switch` only when it
/// cannot fall through into a later case's comparison: either it ends in a
/// terminator (so control never reaches the next `if`), or it never
/// reassigns the scrutinee (so a later `scrutinee == k` can't newly match).
fn case_body_is_switch_safe(body: &[String], scrutinee: &str) -> bool {
    if body_ends_with_terminator(body) {
        return true;
    }
    !body.iter().any(|line| statement_reassigns(line, scrutinee))
}

fn body_ends_with_terminator(body: &[String]) -> bool {
    for line in body.iter().rev() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with("//") || trimmed == "{" || trimmed == "}" {
            continue;
        }
        return is_terminator_statement(trimmed);
    }
    false
}

fn is_terminator_statement(line: &str) -> bool {
    let trimmed = line.trim();
    trimmed == "return;"
        || trimmed.starts_with("return ")
        || trimmed.starts_with("throw")
        || trimmed.starts_with("abort")
        || trimmed.starts_with("goto ")
        || trimmed == "break;"
        || trimmed == "continue;"
}

fn statement_reassigns(line: &str, scrutinee: &str) -> bool {
    HighLevelEmitter::parse_assignment(line).is_some_and(|assignment| assignment.lhs == scrutinee)
}

fn parse_inline_if_goto(line: &str) -> Option<(String, String)> {
    let line = line.trim();
    let rest = line.strip_prefix("if ")?;
    let (condition, suffix) = rest.split_once(" { goto ")?;
    let label = suffix.strip_suffix("; }")?.trim();
    if label.is_empty() {
        return None;
    }
    Some((condition.trim().to_string(), label.to_string()))
}

fn parse_plain_goto_label(line: &str) -> Option<String> {
    let line = line.trim();
    let label = line.strip_prefix("goto ")?.strip_suffix(';')?.trim();
    if label.is_empty() {
        return None;
    }
    Some(label.to_string())
}

fn parse_label_line(line: &str) -> Option<String> {
    let line = line.trim();
    let label = line.strip_suffix(':')?.trim();
    if !label.starts_with("label_") {
        return None;
    }
    Some(label.to_string())
}

fn parse_guarded_switch_body_header(
    statements: &[String],
    start: usize,
    end: usize,
) -> Option<(String, usize)> {
    let (_, first_code) = collect_trivia(statements, start);
    if first_code >= end {
        return None;
    }
    let default_label = parse_plain_goto_label(statements[first_code].as_str())?;
    let (_, body_start) = collect_trivia(statements, first_code + 1);
    if body_start >= end {
        return None;
    }
    parse_label_line(statements[body_start].as_str())?;
    Some((default_label, body_start))
}

fn collect_label_bodies(
    statements: &[String],
    start: usize,
    end: usize,
) -> Option<std::collections::BTreeMap<String, Vec<String>>> {
    let mut bodies: std::collections::BTreeMap<String, Vec<String>> =
        std::collections::BTreeMap::new();
    let mut current_label: Option<String> = None;
    let mut index = start;

    while index < end {
        let trimmed = statements[index].trim();
        if let Some(label) = parse_label_line(trimmed) {
            if bodies.contains_key(&label) {
                return None;
            }
            current_label = Some(label.clone());
            bodies.insert(label, Vec::new());
            index += 1;
            continue;
        }

        let Some(label) = current_label.as_ref() else {
            if trimmed.is_empty() || trimmed.starts_with("//") {
                index += 1;
                continue;
            }
            return None;
        };
        bodies
            .entry(label.clone())
            .or_default()
            .push(statements[index].clone());
        index += 1;
    }

    Some(bodies)
}

fn find_label_after(statements: &[String], start: usize, label: &str) -> Option<usize> {
    let needle = format!("{label}:");
    let mut index = start;
    while index < statements.len() {
        if statements[index].trim() == needle {
            return Some(index);
        }
        index += 1;
    }
    None
}

fn find_label_in_range(
    statements: &[String],
    start: usize,
    end: usize,
    label: &str,
) -> Option<usize> {
    let needle = format!("{label}:");
    let mut index = start;
    while index < end {
        if statements[index].trim() == needle {
            return Some(index);
        }
        index += 1;
    }
    None
}

fn find_else_block_after(statements: &[String], start: usize) -> Option<(usize, usize)> {
    let (_, header) = collect_trivia(statements, start);
    if header >= statements.len() || !is_else_open(statements[header].trim()) {
        return None;
    }
    let end = HighLevelEmitter::find_block_end(statements, header)?;
    Some((header, end))
}

fn find_label_body_end(statements: &[String], start: usize) -> usize {
    let mut index = start;
    while index < statements.len() {
        if index > start && parse_label_line(statements[index].as_str()).is_some() {
            break;
        }
        index += 1;
    }
    index.saturating_sub(1)
}

fn end_of_if_chain(statements: &[String], start: usize) -> Option<usize> {
    let if_end = HighLevelEmitter::find_block_end(statements, start)?;
    let (_, next) = collect_trivia(statements, if_end + 1);
    if next < statements.len() && is_else_open(statements[next].trim()) {
        return HighLevelEmitter::find_block_end(statements, next);
    }
    Some(if_end)
}

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

    #[test]
    fn switch_fold_preserves_non_temp_inter_case_statement() {
        // Regression: a real (non-temp) assignment between consecutive
        // standalone-if cases must block the switch fold so it is not silently
        // spliced away and dropped from the output.
        let mut statements = vec![
            "if loc0 == 0 {".to_string(),
            "    do0();".to_string(),
            "}".to_string(),
            "loc5 = side_effect();".to_string(),
            "if loc0 == 1 {".to_string(),
            "    do1();".to_string(),
            "}".to_string(),
            "if loc0 == 2 {".to_string(),
            "    do2();".to_string(),
            "}".to_string(),
        ];
        HighLevelEmitter::rewrite_switch_statements(&mut statements);
        assert!(
            statements
                .iter()
                .any(|s| s.trim() == "loc5 = side_effect();"),
            "non-temp inter-case statement must survive: {statements:?}"
        );
    }

    #[test]
    fn switch_fold_preserves_side_effecting_temp_between_cases() {
        // Regression (adversarial): a temp capturing a discarded side-effecting
        // call between cases is NOT a case-value definition and must block the
        // fold so the call is not silently dropped.
        let mut statements = vec![
            "if loc0 == 0 {".to_string(),
            "    do0();".to_string(),
            "    return;".to_string(),
            "}".to_string(),
            "let t7 = Foo(arg);".to_string(),
            "if loc0 == 1 {".to_string(),
            "    do1();".to_string(),
            "    return;".to_string(),
            "}".to_string(),
            "if loc0 == 2 {".to_string(),
            "    do2();".to_string(),
            "    return;".to_string(),
            "}".to_string(),
        ];
        HighLevelEmitter::rewrite_switch_statements(&mut statements);
        assert!(
            statements.iter().any(|s| s.trim() == "let t7 = Foo(arg);"),
            "side-effecting temp must survive: {statements:?}"
        );
    }

    #[test]
    fn switch_fold_still_applies_to_consecutive_cases() {
        // Without an inter-case statement, three consecutive standalone-if cases
        // must still fold into a switch (the legitimate target pattern).
        let mut statements = vec![
            "if loc0 == 0 {".to_string(),
            "    do0();".to_string(),
            "}".to_string(),
            "if loc0 == 1 {".to_string(),
            "    do1();".to_string(),
            "}".to_string(),
            "if loc0 == 2 {".to_string(),
            "    do2();".to_string(),
            "}".to_string(),
        ];
        HighLevelEmitter::rewrite_switch_statements(&mut statements);
        assert!(
            statements.iter().any(|s| s.trim().starts_with("switch ")),
            "consecutive standalone-if cases should still fold to a switch: {statements:?}"
        );
    }
}