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
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
use std::collections::HashSet;

use crate::manifest::ManifestParameter;

pub(super) use super::super::helpers::make_unique_identifier;
use super::super::helpers::sanitize_identifier;

#[derive(Clone)]
pub(super) struct CSharpParameter {
    pub(super) name: String,
    pub(super) ty: String,
}

pub(super) fn collect_csharp_parameters(parameters: &[ManifestParameter]) -> Vec<CSharpParameter> {
    let mut used_names = HashSet::new();
    parameters
        .iter()
        .map(|param| CSharpParameter {
            name: make_unique_identifier(sanitize_csharp_identifier(&param.name), &mut used_names),
            ty: format_manifest_type_csharp(&param.kind, false),
        })
        .collect()
}

pub(super) fn format_csharp_parameters(params: &[CSharpParameter]) -> String {
    params
        .iter()
        .map(|param| format!("{} {}", param.ty, param.name))
        .collect::<Vec<_>>()
        .join(", ")
}

pub(super) fn format_manifest_type_csharp(kind: &str, for_return: bool) -> String {
    match kind.to_ascii_lowercase().as_str() {
        // `void` is only legal in return position. In a parameter / event-arg
        // position it would render the illegal `void` / `Action<void>`
        // (C# error CS1547), so fall through to the `object` default there.
        "void" if for_return => "void".into(),
        "boolean" | "bool" => "bool".into(),
        "integer" | "int" => "BigInteger".into(),
        "string" => "string".into(),
        "hash160" => "UInt160".into(),
        "hash256" => "UInt256".into(),
        "publickey" => "ECPoint".into(),
        "bytearray" | "bytes" => "ByteString".into(),
        "signature" => "ByteString".into(),
        "array" => "object[]".into(),
        "map" => "object".into(),
        "interopinterface" => "object".into(),
        "any" => "object".into(),
        _ => "object".into(),
    }
}

pub(super) fn format_method_signature(name: &str, parameters: &str, return_type: &str) -> String {
    if parameters.is_empty() {
        format!("public static {return_type} {name}()")
    } else {
        format!("public static {return_type} {name}({parameters})")
    }
}

pub(in crate::decompiler) fn csharpize_statement(line: &str) -> String {
    let trimmed = line.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    if trimmed.starts_with("//") {
        return trimmed.to_string();
    }
    if let Some(stripped) = trimmed.strip_prefix("let ") {
        // Run the body through `csharpize_expression` so helper
        // calls inside the initialiser also get rewritten — e.g.
        // `let t0 = min(x, y);` must become
        // `var t0 = BigInteger.Min(x, y);`. Without this, the
        // `let` branch was early-returning before the expression
        // rewrites ran (same bug class as the if/while/etc.
        // control-flow branches earlier).
        return format!("var {}", csharpize_expression(stripped));
    }
    if trimmed == "loop {" {
        return "while (true) {".to_string();
    }
    if let Some(condition) = trimmed
        .strip_prefix("if ")
        .and_then(|rest| rest.strip_suffix(" {"))
    {
        return format!("if ({}) {{", csharpize_expression(condition.trim()));
    }
    if let Some(condition) = trimmed
        .strip_prefix("else if ")
        .and_then(|rest| rest.strip_suffix(" {"))
    {
        return format!("else if ({}) {{", csharpize_expression(condition.trim()));
    }
    if let Some(condition) = trimmed
        .strip_prefix("} else if ")
        .and_then(|rest| rest.strip_suffix(" {"))
    {
        return format!("}} else if ({}) {{", csharpize_expression(condition.trim()));
    }
    if let Some(condition) = trimmed
        .strip_prefix("while ")
        .and_then(|rest| rest.strip_suffix(" {"))
    {
        return format!("while ({}) {{", csharpize_expression(condition.trim()));
    }
    if trimmed.starts_with("for (") && trimmed.ends_with(" {") {
        let inner = &trimmed[4..trimmed.len() - 2];
        let inner = inner.strip_prefix('(').unwrap_or(inner);
        let inner = inner.strip_suffix(')').unwrap_or(inner);
        let converted = inner.replacen("let ", "var ", 1);
        return format!("for ({}) {{", csharpize_expression(&converted));
    }
    if let Some(scrutinee) = trimmed
        .strip_prefix("switch ")
        .and_then(|rest| rest.strip_suffix(" {"))
    {
        return format!("switch ({}) {{", csharpize_expression(scrutinee.trim()));
    }
    if let Some(value) = trimmed
        .strip_prefix("case ")
        .and_then(|rest| rest.strip_suffix(" {"))
    {
        return format!("case {}: {{", value.trim());
    }
    if trimmed == "default {" {
        return "default: {".to_string();
    }
    if let Some(target) = trimmed.strip_prefix("leave ") {
        return format!("goto {target}");
    }
    // The high-level emitter renders NEO's `THROW` opcode as
    // `throw(value);` — NEO can throw any stack value (int, string,
    // byte[], etc.). `System.Exception`'s constructor takes a
    // `string`, so non-string operands need to be coerced. We
    // detect string-literal operands (already valid) and wrap
    // everything else in `$"{value}"` interpolation, which calls
    // ToString implicitly and always produces a `string`. The
    // operand itself is run through `csharpize_expression` so
    // helper-call rewrites inside (e.g. `throw(BigInteger.Pow(a, b))`)
    // also apply.
    if let Some(rest) = trimmed
        .strip_prefix("throw(")
        .and_then(|r| r.strip_suffix(");"))
    {
        let operand = csharpize_expression(rest);
        return format!(
            "throw new Exception({});",
            wrap_exception_operand_for_csharp(&operand)
        );
    }
    // NEO `ABORT` / `ABORTMSG` are uncatchable VM aborts. C# has no
    // direct equivalent, but `throw new Exception(...)` (uncaught)
    // terminates execution the same way and reads naturally for a
    // post-decompile reader. Bare `abort()` becomes `throw new
    // Exception();`; `abort(msg)` applies the same coercion as
    // `throw(...)`.
    if trimmed == "abort();" {
        return "throw new Exception();".to_string();
    }
    if let Some(rest) = trimmed
        .strip_prefix("abort(")
        .and_then(|r| r.strip_suffix(");"))
    {
        let operand = csharpize_expression(rest);
        return format!(
            "throw new Exception({});",
            wrap_exception_operand_for_csharp(&operand)
        );
    }
    // NEO's `ASSERT` / `ASSERTMSG` are runtime checks: throw if the
    // condition is false. C# has no `assert(...)` keyword/function in
    // scope, so a `assert(cond);` line wouldn't compile. The closest
    // universal form is `if (!(cond)) throw new Exception();` (and
    // `throw new Exception(msg);` when a message is supplied) — works
    // without any helper imports. Both the condition and the message
    // run through `csharpize_expression` so helper rewrites apply.
    if let Some(args) = trimmed
        .strip_prefix("assert(")
        .and_then(|r| r.strip_suffix(");"))
    {
        if let Some((cond, message)) = split_top_level_comma(args) {
            // Same `Exception(string)` coercion rule as throw/abort:
            // string-typed messages pass through, non-string get
            // wrapped in `$"{...}"` interpolation.
            let message_expr = csharpize_expression(message.trim());
            return format!(
                "if (!({})) throw new Exception({});",
                csharpize_expression(cond.trim()),
                wrap_exception_operand_for_csharp(&message_expr)
            );
        }
        return format!(
            "if (!({})) throw new Exception();",
            csharpize_expression(args.trim())
        );
    }
    csharpize_expression(trimmed)
}

/// Coerce a `throw(...)` / `abort(...)` operand into something
/// `new Exception(string)` accepts. NEO bytecode can THROW any
/// stack value; `System.Exception`'s only constructor that takes a
/// payload is `Exception(string)`, so non-string operands need to
/// be coerced. The detection is:
///
/// - Self-contained `"…"` string literal → already valid; pass
///   through verbatim.
/// - Contains a `"` somewhere → likely a string concatenation
///   (`"err" + code`, `prefix + "..." + suffix`, etc.). The result
///   is a `string`; pass through.
/// - Otherwise (numeric literals, identifiers without `"`, helper
///   calls returning non-string) → wrap in C# interpolation
///   `$"{value}"`, which calls `ToString()` implicitly and always
///   produces a `string`.
///
/// The "any `"` triggers pass-through" heuristic occasionally
/// false-positives (e.g. `BigInteger.Parse("123") + 1` would slip
/// through and produce `Exception(BigInteger)` — uncompilable). In
/// practice the lift produces `"…"` only inside genuine string
/// constructions, so the heuristic stays cleaner than a full type
/// inference and the user can still hand-edit the rare miss.
fn wrap_exception_operand_for_csharp(operand: &str) -> String {
    let trimmed = operand.trim();
    if operand_appears_string_typed(trimmed) {
        operand.to_string()
    } else {
        format!("$\"{{{trimmed}}}\"")
    }
}

/// Return `true` when `text` plausibly evaluates to a `string`
/// without further coercion — either a single string literal or
/// any expression containing one (most commonly a string-concat).
fn operand_appears_string_typed(text: &str) -> bool {
    text.contains('"')
}

/// Apply the C# expression-level rewrites (cat → `+`, NEO helper
/// calls → `BigInteger.X` / `Helper.X` / pattern forms) to a fragment
/// that's already known to be a single expression — for instance the
/// condition of an `if`/`while`, or the scrutinee of a `switch`.
///
/// `csharpize_statement`'s control-flow branches dispatch to this so
/// the rewrites apply uniformly whether the helper appears in a
/// statement position or inside a control header.
fn csharpize_expression(text: &str) -> String {
    rewrite_numeric_helpers(&rewrite_cat_operator(text))
}

/// Rewrite NEO arithmetic / buffer helper calls into compilable C# forms.
///
/// The high-level lift emits these NEO opcodes as bare function calls
/// (`abs(x)`, `min(a, b)`, `pow(a, b)`, `left(s, n)`, etc.). C# has
/// no top-level `abs`/`min`/`pow`/`left` etc. in scope, so leaving
/// them as-is produces output that doesn't compile against the
/// standard NEO SmartContract Framework. We rewrite to two
/// canonical forms:
///
/// - `System.Numerics.BigInteger` static methods (`BigInteger.Abs`,
///   `BigInteger.Min`, `BigInteger.Max`, `BigInteger.Pow`,
///   `BigInteger.ModPow`) — pure .NET, in scope via the
///   `using System.Numerics;` preamble.
/// - `Neo.SmartContract.Framework.Helper` static methods
///   (`Helper.Sign`, `Helper.Sqrt`, `Helper.ModMul`, `Helper.Within`,
///   `Helper.Left`, `Helper.Right`, `Helper.Substr`) — for ones with
///   no `BigInteger` equivalent.
///
/// Some of these accept `int` parameters at specific positions
/// (`BigInteger.Pow`'s exponent; `Left`/`Right`'s `n`; `Substr`'s
/// `start` + `length`). The lift uses `BigInteger` everywhere, so
/// we wrap those args in `(int)(...)` to keep the call
/// type-correct.
///
/// The rewrite is identifier-boundary aware (so `pow(x)` matches
/// but `mypow(x)` does not) and string-aware (so a literal
/// containing `abs(...)` is preserved verbatim).
fn rewrite_numeric_helpers(line: &str) -> String {
    let bytes = line.as_bytes();
    let mut out = String::with_capacity(line.len());
    let mut i = 0;
    let mut in_string: Option<u8> = None;
    while i < bytes.len() {
        let b = bytes[i];
        // Copy any non-ASCII (multibyte UTF-8) character verbatim. A helper
        // pattern can only begin with ASCII, and slicing `&line[i..]` at a
        // multibyte continuation byte would panic (not a char boundary), so
        // advance one whole character at a time here. The `is_char_boundary`
        // guard keeps this panic-free even if an earlier match advanced `i`
        // into the middle of a character.
        if !b.is_ascii() {
            if line.is_char_boundary(i) {
                let ch = line[i..].chars().next().unwrap_or('\u{FFFD}');
                out.push(ch);
                i += ch.len_utf8();
            } else {
                i += 1;
            }
            continue;
        }
        if let Some(quote) = in_string {
            out.push(b as char);
            if b == b'\\' && i + 1 < bytes.len() {
                // Skip the escaped character (so an escaped quote does not end
                // the string), copying it whole in case it is multibyte.
                let esc = line[i + 1..].chars().next().unwrap_or('\u{FFFD}');
                out.push(esc);
                i += 1 + esc.len_utf8();
                continue;
            }
            if b == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }
        if b == b'"' || b == b'\'' {
            in_string = Some(b);
            out.push(b as char);
            i += 1;
            continue;
        }
        let prev_is_ident_continuation = i > 0 && {
            let p = bytes[i - 1];
            p.is_ascii_alphanumeric() || p == b'_'
        };
        if !prev_is_ident_continuation {
            if let Some(rendered) = match_unary_pattern(&line[i..]) {
                out.push_str(&rendered.body);
                i += rendered.consumed;
                continue;
            }
            if let Some((replacement, consumed)) = match_collection_constructor(&line[i..]) {
                out.push_str(replacement);
                i += consumed;
                continue;
            }
            if let Some((rendered, consumed)) = match_map_literal(&line[i..]) {
                out.push_str(&rendered);
                i += consumed;
                continue;
            }
            if let Some((rendered, consumed)) = match_big_byte_literal(&line[i..]) {
                out.push_str(&rendered);
                i += consumed;
                continue;
            }
            if let Some((rendered, consumed)) = match_big_integer_literal(&line[i..]) {
                out.push_str(&rendered);
                i += consumed;
                continue;
            }
            if let Some(rule) = match_numeric_helper(&bytes[i..]) {
                if !rule.int_cast_args.is_empty() {
                    if let Some(rendered) = format_helper_with_casts(&line[i..], &rule) {
                        out.push_str(&rendered.body);
                        i += rendered.consumed;
                        continue;
                    }
                }
                out.push_str(rule.replacement);
                out.push('(');
                i += rule.needle_len;
                continue;
            }
        }
        out.push(b as char);
        i += 1;
    }
    out
}

/// Wrap a bare decimal integer literal that exceeds C#'s `ulong` range in
/// `BigInteger.Parse("…")`. A literal above `ulong.MaxValue` is C# error CS1021
/// ("integral constant is too large"), which the lift hits for large
/// PUSHINT128/PUSHINT256 operands. `System.Numerics` is already imported by the
/// C# preamble, so `BigInteger.Parse` is in scope.
///
/// The caller guarantees `s` begins at an identifier boundary (so digits inside
/// `t12`/`loc5` are never matched). Only the magnitude is wrapped, so a leading
/// unary `-` stays valid (`-BigInteger.Parse("…")`). Hex (`0x…`) and literals
/// that continue into an identifier or a `.` are left untouched.
fn match_big_integer_literal(s: &str) -> Option<(String, usize)> {
    let bytes = s.as_bytes();
    if bytes.is_empty() || !bytes[0].is_ascii_digit() {
        return None;
    }
    let mut j = 0;
    while j < bytes.len() && bytes[j].is_ascii_digit() {
        j += 1;
    }
    if j < bytes.len() {
        let after = bytes[j];
        // `0x…` hex prefix, an identifier continuation, or a fractional/member
        // `.` means this digit run is not a standalone decimal literal.
        if after == b'x'
            || after == b'X'
            || after.is_ascii_alphabetic()
            || after == b'_'
            || after == b'.'
        {
            return None;
        }
    }
    let digits = &s[..j];
    if !decimal_exceeds_u64(digits) {
        return None;
    }
    Some((format!("BigInteger.Parse(\"{digits}\")"), j))
}

/// Rewrite a non-empty PACKMAP literal `Map(k1: v1, k2: v2)` into a C# map
/// collection initializer `new Map<object, object> { [k1] = v1, [k2] = v2 }`.
///
/// The high-level lift renders PACKMAP as `Map(key: value, …)`, whose `:`
/// separators are not valid inside a C# call (error CS1026). The empty `Map()`
/// form is handled by [`match_collection_constructor`]; a body carrying a
/// `/* N more … */` truncation marker is left untouched (it is an incomplete
/// literal that cannot be rendered faithfully). Keys and values are recursively
/// run through [`csharpize_expression`] so nested helpers/maps are translated.
fn match_map_literal(rest: &str) -> Option<(String, usize)> {
    let inner = rest.strip_prefix("Map(")?;
    let close = matching_paren(inner)?;
    let body = inner[..close].trim();
    if body.is_empty() || body.contains("/*") {
        return None;
    }
    let mut entries = Vec::new();
    for entry in split_top_level_args(body) {
        let (key, value) = split_top_level_colon(entry)?;
        entries.push(format!(
            "[{}] = {}",
            csharpize_expression(key.trim()),
            csharpize_expression(value.trim())
        ));
    }
    let consumed = "Map(".len() + close + 1;
    Some((
        format!("new Map<object, object> {{ {} }}", entries.join(", ")),
        consumed,
    ))
}

/// Index of the `)` that closes an already-opened paren at the start of `s`
/// (i.e. `s` is the text *after* the opening `(`). String- and nesting-aware
/// over `()[]{}`. Returns `None` if unbalanced.
fn matching_paren(s: &str) -> Option<usize> {
    let bytes = s.as_bytes();
    let mut depth = 0i32;
    let mut in_string: Option<u8> = None;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if let Some(quote) = in_string {
            if b == b'\\' && i + 1 < bytes.len() {
                i += 2;
                continue;
            }
            if b == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }
        match b {
            b'"' | b'\'' => in_string = Some(b),
            b')' if depth == 0 => return Some(i),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth -= 1,
            _ => {}
        }
        i += 1;
    }
    None
}

/// Split a single map entry `key: value` at its first top-level `:`
/// (string/nesting aware). Returns `None` when no top-level `:` is present.
fn split_top_level_colon(entry: &str) -> Option<(&str, &str)> {
    let bytes = entry.as_bytes();
    let mut depth = 0i32;
    let mut in_string: Option<u8> = None;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if let Some(quote) = in_string {
            if b == b'\\' && i + 1 < bytes.len() {
                i += 2;
                continue;
            }
            if b == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }
        match b {
            b'"' | b'\'' => in_string = Some(b),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth -= 1,
            b':' if depth == 0 => return Some((&entry[..i], &entry[i + 1..])),
            _ => {}
        }
        i += 1;
    }
    None
}

/// Rewrite an oversized `0x…` hex blob into a C# `new byte[] { … }` literal.
///
/// The high-level lift renders a non-printable PUSHDATA operand as `0x<HEX>`.
/// When that blob is wider than 8 bytes (> 16 hex digits) it cannot be a C#
/// integer literal (above `ulong` → error CS1021). A run that long is also
/// unambiguously a byte blob: every other `0x…` the lift emits — syscall hashes
/// (8 digits), CALLT indices and jump targets (≤ 4 digits) — is shorter, so a
/// length cutoff cannot misfire on them. Short hex is left untouched.
///
/// `new byte[] { … }` compiles wherever a byte array is assignable (an `object`
/// return, an expression operand). A manifest-typed return such as `UInt160`
/// still needs a cast the text rewriter can't infer here, but eliminating the
/// uncompilable integer literal is the correct minimal fix.
fn match_big_byte_literal(s: &str) -> Option<(String, usize)> {
    let bytes = s.as_bytes();
    if bytes.len() < 2 || bytes[0] != b'0' || !(bytes[1] == b'x' || bytes[1] == b'X') {
        return None;
    }
    let mut j = 2;
    while j < bytes.len() && bytes[j].is_ascii_hexdigit() {
        j += 1;
    }
    let hex = &s[2..j];
    // > 16 nibbles (beyond ulong) and whole bytes only.
    if hex.len() <= 16 || hex.len() % 2 != 0 {
        return None;
    }
    // Must be a complete token, not the prefix of a longer identifier.
    if j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') {
        return None;
    }
    let mut rendered = String::from("new byte[] { ");
    for (idx, pair) in hex.as_bytes().chunks_exact(2).enumerate() {
        if idx > 0 {
            rendered.push_str(", ");
        }
        rendered.push_str("0x");
        rendered.push(pair[0] as char);
        rendered.push(pair[1] as char);
    }
    rendered.push_str(" }");
    Some((rendered, j))
}

/// Whether a run of decimal digits represents a value greater than
/// `u64::MAX` (18446744073709551615) — i.e. beyond what a C# `ulong` literal
/// can hold. Compared by length then lexically to avoid overflowing any fixed
/// integer width (PUSHINT256 values can be up to 78 digits).
fn decimal_exceeds_u64(digits: &str) -> bool {
    const U64_MAX: &str = "18446744073709551615";
    let trimmed = digits.trim_start_matches('0');
    let significant = if trimmed.is_empty() { "0" } else { trimmed };
    match significant.len().cmp(&U64_MAX.len()) {
        std::cmp::Ordering::Greater => true,
        std::cmp::Ordering::Less => false,
        std::cmp::Ordering::Equal => significant > U64_MAX,
    }
}

struct HelperRule {
    replacement: &'static str,
    needle_len: usize,
    /// 0-based positions within the call's argument list that need
    /// to be wrapped in `(int)(...)` for the C# overload signature
    /// to match. Empty for helpers that take only `BigInteger`/
    /// reference-typed args.
    int_cast_args: &'static [usize],
}

/// Recognise empty NEWMAP / NEWARRAY0 / NEWSTRUCT0 constructor
/// shapes the lift emits and rewrite to compilable C# forms:
///
/// - `Map()` → `new Map<object, object>()` — the Neo
///   `SmartContract.Framework.Services.Map` is generic; without
///   key/value-type info we default to `object`.
/// - `[]` → `new object[0]` — the bare collection literal `[]`
///   has no inferable target type at the lift site, so emit an
///   explicit zero-length `object[]`.
/// - `Struct()` → `new Struct()` — Neo's runtime `Struct` is a
///   reference type; the empty constructor is the simplest
///   compilable form even if the user later fills items in.
///
/// Returns `(replacement, consumed_bytes)` on a match. Only the
/// empty-arg forms (literally `Map()`, `[]`, `Struct()`) are
/// handled here. Non-empty PACK / PACKMAP / PACKSTRUCT shapes
/// (e.g. `Map(k1, v1, k2, v2)`) are deferred — they need
/// collection-initialiser rendering that the lift doesn't supply
/// the structure for yet.
fn match_collection_constructor(rest: &str) -> Option<(&'static str, usize)> {
    const TABLE: &[(&str, &str)] = &[
        ("Map()", "new Map<object, object>()"),
        ("Struct()", "new Struct()"),
        ("[]", "new object[0]"),
    ];
    for (needle, replacement) in TABLE {
        if rest.starts_with(needle) {
            return Some((replacement, needle.len()));
        }
    }
    None
}

/// Recognise lifted unary helpers that don't map cleanly to a
/// `Method(arg)` rewrite — they expand into a small inline
/// expression instead.
///
/// - `is_null(x)` → `(x is null)` (idiomatic C# pattern match;
///   works against any reference-typed argument including the NEO
///   runtime stack types).
/// - `new_buffer(n)` → `new byte[(int)(n)]` — NEWBUFFER lifts to a
///   byte-array constructor in C#.
/// - `new_array(n)` → `new object[(int)(n)]` — NEO arrays are
///   heterogeneous; `object[]` is the safe fallback without
///   element-type info.
fn match_unary_pattern(rest: &str) -> Option<HelperRewrite> {
    if let Some(rendered) = match_simple_unary(rest, "is_null(", |arg| format!("({arg} is null)")) {
        return Some(rendered);
    }
    if let Some(rendered) = match_simple_unary(rest, "new_buffer(", |arg| {
        format!("new byte[{}]", wrap_int_cast_unless_literal(arg))
    }) {
        return Some(rendered);
    }
    if let Some(rendered) = match_simple_unary(rest, "new_array(", |arg| {
        format!("new object[{}]", wrap_int_cast_unless_literal(arg))
    }) {
        return Some(rendered);
    }
    // Collection helpers — lift emits `clear_items(c)`, `keys(m)`,
    // `values(m)`, `reverse_items(arr)`. Rewrite to the standard
    // .NET / Neo Map / List accessor forms. These work for both
    // Neo's `Map<TKey, TValue>` and `List<T>` / arrays via the
    // common collection interfaces.
    if let Some(rendered) = match_simple_unary(rest, "clear_items(", |arg| format!("{arg}.Clear()"))
    {
        return Some(rendered);
    }
    if let Some(rendered) = match_simple_unary(rest, "keys(", |arg| format!("{arg}.Keys")) {
        return Some(rendered);
    }
    if let Some(rendered) = match_simple_unary(rest, "values(", |arg| format!("{arg}.Values")) {
        return Some(rendered);
    }
    if let Some(rendered) =
        match_simple_unary(rest, "reverse_items(", |arg| format!("{arg}.Reverse()"))
    {
        return Some(rendered);
    }
    // Two-argument collection helpers — `remove_item(c, k)` lifts
    // to `c.Remove(k)` (works for both `Map<,>` and `List<>` /
    // collection-interface types). `append(arr, item)` →
    // `arr.Add(item)` matches `List<T>.Add` and Neo's `Array.Add`.
    // `has_key(c, k)` → `c.ContainsKey(k)` matches `IDictionary`.
    for (needle, method) in METHOD_CALL_TABLE {
        if let Some(rendered) = match_method_call(rest, needle, method) {
            return Some(rendered);
        }
    }
    // Typed CONVERT and ISTYPE rewrites — the high-level lift emits
    // `convert_to_T(x)` / `is_type_T(x)` for each NEO stack-item
    // type. Map the safe subset (bool / integer / bytestring /
    // buffer) onto C# casts (`(T)(x)`) and pattern matches
    // (`(x is T)`). The other types (any, pointer, array, struct,
    // map, interopinterface) need more context — left as-is so the
    // user sees an obvious "fix this manually" identifier.
    for (needle, csharp_type) in CONVERT_TYPED_TABLE {
        if let Some(rendered) =
            match_simple_unary(rest, needle, |arg| format!("({csharp_type})({arg})"))
        {
            return Some(rendered);
        }
    }
    for (needle, csharp_type) in IS_TYPE_TYPED_TABLE {
        if let Some(rendered) =
            match_simple_unary(rest, needle, |arg| format!("({arg} is {csharp_type})"))
        {
            return Some(rendered);
        }
    }
    None
}

const METHOD_CALL_TABLE: &[(&str, &str)] = &[
    ("remove_item(", "Remove"),
    ("append(", "Add"),
    ("has_key(", "ContainsKey"),
];

const CONVERT_TYPED_TABLE: &[(&str, &str)] = &[
    ("convert_to_bool(", "bool"),
    ("convert_to_integer(", "BigInteger"),
    ("convert_to_bytestring(", "ByteString"),
    ("convert_to_buffer(", "byte[]"),
];

const IS_TYPE_TYPED_TABLE: &[(&str, &str)] = &[
    ("is_type_bool(", "bool"),
    ("is_type_integer(", "BigInteger"),
    ("is_type_bytestring(", "ByteString"),
    ("is_type_buffer(", "byte[]"),
];

/// Wrap a numeric argument in `(int)(...)` — but skip the cast when
/// the argument is already a literal decimal integer (`3`, `-5`,
/// `100`). Neo's lifted source treats all integers as BigInteger by
/// default, so a defensive `(int)` cast is needed for any expression
/// that could carry BigInteger semantics — but a bare integer
/// literal is unambiguously an `int` to the C# parser, and the
/// redundant cast just adds visual noise (`new object[(int)(3)]`
/// → `new object[3]`).
fn wrap_int_cast_unless_literal(arg: &str) -> String {
    let trimmed = arg.trim();
    let is_decimal_literal = !trimmed.is_empty()
        && trimmed
            .strip_prefix('-')
            .unwrap_or(trimmed)
            .chars()
            .all(|ch| ch.is_ascii_digit());
    if is_decimal_literal {
        trimmed.to_string()
    } else {
        format!("(int)({trimmed})")
    }
}

fn match_simple_unary(
    rest: &str,
    needle: &str,
    render: impl FnOnce(&str) -> String,
) -> Option<HelperRewrite> {
    if !rest.starts_with(needle) {
        return None;
    }
    let after_open = &rest[needle.len()..];
    let close_index = find_matching_close_paren(after_open.as_bytes())?;
    let arg = after_open[..close_index].trim();
    Some(HelperRewrite {
        body: render(arg),
        consumed: needle.len() + close_index + 1,
    })
}

/// Rewrite a lifted helper call of shape `prefix(arg0, arg1, ...)`
/// into a C# method invocation `arg0.method_name(arg1, ...)`. Used
/// for collection helpers like `remove_item(coll, key)` →
/// `coll.Remove(key)` where the first argument is the receiver.
fn match_method_call(rest: &str, needle: &str, method_name: &str) -> Option<HelperRewrite> {
    if !rest.starts_with(needle) {
        return None;
    }
    let after_open = &rest[needle.len()..];
    let close_index = find_matching_close_paren(after_open.as_bytes())?;
    let args = &after_open[..close_index];
    let parts = split_top_level_args(args);
    if parts.is_empty() {
        return None;
    }
    let receiver = parts[0].trim();
    let rest_args = parts[1..]
        .iter()
        .map(|p| p.trim())
        .collect::<Vec<_>>()
        .join(", ");
    Some(HelperRewrite {
        body: format!("{receiver}.{method_name}({rest_args})"),
        consumed: needle.len() + close_index + 1,
    })
}

fn match_numeric_helper(bytes: &[u8]) -> Option<HelperRule> {
    const TABLE: &[(&[u8], &str, &[usize])] = &[
        (b"abs(", "BigInteger.Abs", &[]),
        (b"min(", "BigInteger.Min", &[]),
        (b"max(", "BigInteger.Max", &[]),
        (b"pow(", "BigInteger.Pow", &[1]),
        (b"modpow(", "BigInteger.ModPow", &[]),
        (b"sign(", "Helper.Sign", &[]),
        (b"sqrt(", "Helper.Sqrt", &[]),
        (b"modmul(", "Helper.ModMul", &[]),
        (b"within(", "Helper.Within", &[]),
        (b"left(", "Helper.Left", &[1]),
        (b"right(", "Helper.Right", &[1]),
        (b"substr(", "Helper.Substr", &[1, 2]),
    ];
    for (needle, replacement, int_cast_args) in TABLE {
        if bytes.starts_with(needle) {
            return Some(HelperRule {
                replacement,
                needle_len: needle.len(),
                int_cast_args,
            });
        }
    }
    None
}

struct HelperRewrite {
    body: String,
    consumed: usize,
}

fn format_helper_with_casts(rest: &str, rule: &HelperRule) -> Option<HelperRewrite> {
    let after_open = &rest[rule.needle_len..];
    let close_index = find_matching_close_paren(after_open.as_bytes())?;
    let args = &after_open[..close_index];
    let parts = split_top_level_args(args);
    let mut rendered = Vec::with_capacity(parts.len());
    for (index, part) in parts.iter().enumerate() {
        // Normalize each argument through the same expression rewriter the
        // non-cast helpers use, so nested NEO helper calls (abs/min/sqrt/
        // is_null/convert_to_*, ` cat `) become compilable C# rather than being
        // emitted verbatim (e.g. `pow(abs(x), 2)` → `BigInteger.Pow(BigInteger.Abs(x), 2)`).
        let normalized = csharpize_expression(part.trim());
        if rule.int_cast_args.contains(&index) {
            // Same idea as `wrap_int_cast_unless_literal`: defensive
            // `(int)` casts are necessary for variable / expression
            // operands that could carry BigInteger semantics, but
            // bare integer literals are unambiguously `int` to the C#
            // parser, so emit `pow(2, 8)` → `BigInteger.Pow(2, 8)`
            // rather than `BigInteger.Pow(2, (int)(8))`.
            rendered.push(wrap_int_cast_unless_literal(&normalized));
        } else {
            rendered.push(normalized);
        }
    }
    let body = format!("{}({})", rule.replacement, rendered.join(", "));
    Some(HelperRewrite {
        consumed: rule.needle_len + close_index + 1,
        body,
    })
}

/// Split a top-level argument list — like `split_top_level_comma` but
/// returns every comma-separated piece, not just the first split.
fn split_top_level_args(args: &str) -> Vec<&str> {
    let bytes = args.as_bytes();
    let mut parts = Vec::new();
    let mut start = 0usize;
    let mut depth = 0i32;
    let mut in_string: Option<u8> = None;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if let Some(quote) = in_string {
            // Skip the escaped character so an escaped quote (`\"`) inside a
            // string literal does not prematurely terminate the string.
            if b == b'\\' && i + 1 < bytes.len() {
                i += 2;
                continue;
            }
            if b == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }
        match b {
            b'"' | b'\'' => in_string = Some(b),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth -= 1,
            b',' if depth == 0 => {
                parts.push(&args[start..i]);
                start = i + 1;
            }
            _ => {}
        }
        i += 1;
    }
    if !args.is_empty() {
        parts.push(&args[start..]);
    }
    parts
}

fn find_matching_close_paren(bytes: &[u8]) -> Option<usize> {
    let mut depth: i32 = 0;
    let mut in_string: Option<u8> = None;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if let Some(quote) = in_string {
            // Skip the escaped character (see split_top_level_args).
            if b == b'\\' && i + 1 < bytes.len() {
                i += 2;
                continue;
            }
            if b == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }
        match b {
            b'"' | b'\'' => in_string = Some(b),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => {
                if depth == 0 {
                    return Some(i);
                }
                depth -= 1;
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// Split a comma-separated argument list at the first top-level comma —
/// i.e. ignore commas inside parens / brackets / strings. Used by the
/// C#-ize pass to peel `assert(cond, message);` into its two pieces.
fn split_top_level_comma(args: &str) -> Option<(&str, &str)> {
    let bytes = args.as_bytes();
    let mut depth = 0i32;
    let mut in_string: Option<u8> = None;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if let Some(quote) = in_string {
            // Skip the escaped character (see split_top_level_args).
            if b == b'\\' && i + 1 < bytes.len() {
                i += 2;
                continue;
            }
            if b == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }
        match b {
            b'"' | b'\'' => in_string = Some(b),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth -= 1,
            b',' if depth == 0 => return Some((&args[..i], &args[i + 1..])),
            _ => {}
        }
        i += 1;
    }
    None
}

/// Translate the high-level `cat` (CAT / string-concat) operator to C#'s
/// `+`. The replacement only fires for ` cat ` tokens that sit outside
/// string literals so contents like `"a cat b"` are preserved verbatim.
fn rewrite_cat_operator(line: &str) -> String {
    if !line.contains(" cat ") {
        return line.to_string();
    }
    let bytes = line.as_bytes();
    let mut out = String::with_capacity(line.len());
    let mut i = 0;
    let mut in_string: Option<u8> = None;
    while i < bytes.len() {
        let b = bytes[i];
        // Copy any non-ASCII (multibyte UTF-8) character verbatim. ` cat ` and
        // the quote/escape markers are all ASCII, so multibyte bytes only ever
        // need pass-through; `b as char` would re-encode them as Latin-1 and
        // corrupt the UTF-8. The is_char_boundary guard keeps this panic-free.
        if !b.is_ascii() {
            if line.is_char_boundary(i) {
                let ch = line[i..].chars().next().unwrap_or('\u{FFFD}');
                out.push(ch);
                i += ch.len_utf8();
            } else {
                i += 1;
            }
            continue;
        }
        if let Some(quote) = in_string {
            out.push(b as char);
            if b == b'\\' && i + 1 < bytes.len() {
                // Copy the escaped character whole in case it is multibyte.
                let esc = line[i + 1..].chars().next().unwrap_or('\u{FFFD}');
                out.push(esc);
                i += 1 + esc.len_utf8();
                continue;
            }
            if b == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }
        if b == b'"' || b == b'\'' {
            in_string = Some(b);
            out.push(b as char);
            i += 1;
            continue;
        }
        if b == b' '
            && i + 4 < bytes.len()
            && &bytes[i..i + 5] == b" cat "
            // Only treat ` cat ` as the operator when both flanks are
            // already part of expression context (something on the
            // left). At i==0 we'd have `cat ` at the start of a line,
            // which is more likely to be an identifier — leave alone.
            && i > 0
        {
            out.push_str(" + ");
            i += 5;
            continue;
        }
        out.push(b as char);
        i += 1;
    }
    out
}

/// Returns true if `line` already terminates control flow such that a trailing
/// `break;` would be unreachable. Used by C# switch-case rendering to skip
/// inserting a redundant `break;` after `return`/`throw`/`goto`/`break`.
pub(in crate::decompiler) fn line_is_csharp_terminator(line: &str) -> bool {
    let trimmed = line.trim();
    trimmed.starts_with("return ")
        || trimmed == "return;"
        || trimmed.starts_with("return;")
        || trimmed.starts_with("throw ")
        || trimmed == "throw;"
        || trimmed.starts_with("goto ")
        || trimmed == "break;"
        || trimmed == "continue;"
}

pub(super) fn sanitize_csharp_identifier(input: &str) -> String {
    let ident = sanitize_identifier(input);
    if is_csharp_keyword(&ident) {
        format!("@{ident}")
    } else {
        ident
    }
}

fn is_csharp_keyword(ident: &str) -> bool {
    matches!(
        ident,
        "abstract"
            | "as"
            | "base"
            | "bool"
            | "break"
            | "byte"
            | "case"
            | "catch"
            | "char"
            | "checked"
            | "class"
            | "const"
            | "continue"
            | "decimal"
            | "default"
            | "delegate"
            | "do"
            | "double"
            | "else"
            | "enum"
            | "event"
            | "explicit"
            | "extern"
            | "false"
            | "finally"
            | "fixed"
            | "float"
            | "for"
            | "foreach"
            | "goto"
            | "if"
            | "implicit"
            | "in"
            | "int"
            | "interface"
            | "internal"
            | "is"
            | "lock"
            | "long"
            | "namespace"
            | "new"
            | "null"
            | "object"
            | "operator"
            | "out"
            | "override"
            | "params"
            | "private"
            | "protected"
            | "public"
            | "readonly"
            | "ref"
            | "return"
            | "sbyte"
            | "sealed"
            | "short"
            | "sizeof"
            | "stackalloc"
            | "static"
            | "string"
            | "struct"
            | "switch"
            | "this"
            | "throw"
            | "true"
            | "try"
            | "typeof"
            | "uint"
            | "ulong"
            | "unchecked"
            | "unsafe"
            | "ushort"
            | "using"
            | "virtual"
            | "void"
            | "volatile"
            | "while"
            | "add"
            | "alias"
            | "ascending"
            | "async"
            | "await"
            | "by"
            | "descending"
            | "dynamic"
            | "equals"
            | "from"
            | "get"
            | "global"
            | "group"
            | "init"
            | "into"
            | "join"
            | "let"
            | "nameof"
            | "on"
            | "orderby"
            | "partial"
            | "remove"
            | "select"
            | "set"
            | "unmanaged"
            | "value"
            | "var"
            | "when"
            | "where"
            | "with"
            | "yield"
    )
}

pub(super) fn escape_csharp_string(value: &str) -> String {
    value
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
}