proguard 5.10.3

Basic proguard mapping file handling for Rust
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
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::fmt::{Error as FmtError, Write};
use std::iter::FusedIterator;

/// Maximum number of frames emitted by span expansion for a single mapping entry.
///
/// R8 uses `0:65535` as the catch-all range for methods with a single unique position:
/// <https://r8.googlesource.com/r8/+/refs/heads/main/doc/retrace.md#catch-all-range-for-methods-with-a-single-unique-position>
///
/// No real method would span more lines than this, so ranges exceeding this cap
/// are treated as malformed and fall through to single-line handling.
const MAX_SPAN_EXPANSION: usize = 65_535;

use crate::builder::{
    Member, MethodReceiver, ParsedProguardMapping, RewriteAction, RewriteCondition, RewriteRule,
};
use crate::java;
use crate::mapping::ProguardMapping;
use crate::stacktrace::{self, StackFrame, StackTrace, Throwable};
use crate::utils::{class_name_to_descriptor, extract_class_name, synthesize_source_file};

/// A deobfuscated method signature.
pub struct DeobfuscatedSignature {
    parameters: Vec<String>,
    return_type: String,
}

impl DeobfuscatedSignature {
    pub(crate) fn new(signature: (Vec<String>, String)) -> DeobfuscatedSignature {
        DeobfuscatedSignature {
            parameters: signature.0,
            return_type: signature.1,
        }
    }

    /// Returns the java return type of the method signature
    pub fn return_type(&self) -> &str {
        self.return_type.as_str()
    }

    /// Returns the list of paramater types of the method signature
    pub fn parameters_types(&self) -> impl Iterator<Item = &str> {
        self.parameters.iter().map(|s| s.as_ref())
    }

    /// formats types (param_type list, return_type) into a human-readable signature
    pub fn format_signature(&self) -> String {
        let mut signature = format!("({})", self.parameters.join(", "));
        if !self.return_type().is_empty() && self.return_type() != "void" {
            signature.push_str(": ");
            signature.push_str(self.return_type());
        }

        signature
    }
}

impl fmt::Display for DeobfuscatedSignature {
    // This trait requires `fmt` with this exact signature.
    fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.format_signature())
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct MemberMapping<'s> {
    startline: Option<usize>,
    endline: Option<usize>,
    original_class: Option<&'s str>,
    original_file: Option<&'s str>,
    original: &'s str,
    original_startline: Option<usize>,
    original_endline: Option<usize>,
    is_synthesized: bool,
    is_outline: bool,
    outline_callsite_positions: Option<HashMap<usize, usize>>,
    rewrite_rules: Vec<RewriteRule<'s>>,
    /// The source file of the outer class, used for synthesizing file names when
    /// the inlined method's class doesn't have its own sourceFile metadata.
    outer_source_file: Option<&'s str>,
}

#[derive(Clone, Debug, Default)]
struct ClassMembers<'s> {
    all_mappings: Vec<MemberMapping<'s>>,
    // method_params -> Vec[MemberMapping]
    mappings_by_params: HashMap<&'s str, Vec<MemberMapping<'s>>>,
}

#[derive(Clone, Debug, Default)]
struct ClassMapping<'s> {
    original: &'s str,
    members: HashMap<&'s str, ClassMembers<'s>>,
    #[expect(
        unused,
        reason = "Class-level synthesized is propagated to members in resolve_mapping; \
                  kept here for potential future class-level queries."
    )]
    is_synthesized: bool,
}

#[derive(Default)]
struct CollectedFrames<'s> {
    frames: Vec<StackFrame<'s>>,
    rewrite_rules: Vec<&'s RewriteRule<'s>>,
}

type MemberIter<'m> = std::slice::Iter<'m, MemberMapping<'m>>;

/// An Iterator over remapped StackFrames.
#[derive(Clone, Debug, Default)]
pub struct RemappedFrameIter<'m> {
    inner: Option<(StackFrame<'m>, MemberIter<'m>)>,
    has_line_info: bool,
}

impl<'m> RemappedFrameIter<'m> {
    fn empty() -> Self {
        Self {
            inner: None,
            has_line_info: false,
        }
    }
    fn members(frame: StackFrame<'m>, members: MemberIter<'m>, has_line_info: bool) -> Self {
        Self {
            inner: Some((frame, members)),
            has_line_info,
        }
    }
}

impl<'m> Iterator for RemappedFrameIter<'m> {
    type Item = StackFrame<'m>;
    fn next(&mut self) -> Option<Self::Item> {
        let (frame, ref mut members) = self.inner.as_mut()?;
        if frame.parameters.is_none() {
            iterate_with_lines(frame, members, self.has_line_info)
        } else {
            iterate_without_lines(frame, members)
        }
    }
}

fn map_member_with_lines<'a>(
    frame: &StackFrame<'a>,
    member: &MemberMapping<'a>,
) -> Option<StackFrame<'a>> {
    let frame_line = frame.line.unwrap_or(0);
    if member.endline.unwrap_or(0) > 0
        && (frame_line < member.startline.unwrap_or(0) || frame_line > member.endline.unwrap_or(0))
    {
        return None;
    }

    // parents of inlined frames don't have an `endline`, and
    // the top inlined frame need to be correctly offset.
    let line = if member.original_endline.is_none()
        || member.original_endline == member.original_startline
    {
        member.original_startline.unwrap_or(0)
    } else {
        member.original_startline.unwrap_or(0) + frame_line - member.startline.unwrap_or(0)
    };

    let class = member.original_class.unwrap_or(frame.class);

    let file: Option<Cow<'a, str>> = if let Some(file_name) = member.original_file {
        if file_name == "R8$$SyntheticClass" {
            // Synthesize from class name for synthetic classes
            extract_class_name(class).map(Cow::Borrowed)
        } else {
            Some(Cow::Borrowed(file_name))
        }
    } else {
        // Synthesize from class name (input filename is not reliable)
        synthesize_source_file(class, member.outer_source_file).map(Cow::Owned)
    };

    Some(StackFrame {
        class,
        method: member.original,
        file,
        line: Some(line),
        parameters: frame.parameters,
        method_synthesized: member.is_synthesized,
    })
}

/// Builds a remapped frame from a no-line (base) mapping entry.
///
/// `output_line` is the line number to use in the output frame, already computed
/// by the caller based on group context (presence of `startline`, entry count, etc.).
fn map_member_without_lines<'a>(
    frame: &StackFrame<'a>,
    member: &MemberMapping<'a>,
    output_line: Option<usize>,
) -> StackFrame<'a> {
    let class = member.original_class.unwrap_or(frame.class);
    // Synthesize from class name (input filename is not reliable)
    let file = synthesize_source_file(class, member.outer_source_file).map(Cow::Owned);
    StackFrame {
        class,
        method: member.original,
        file,
        line: output_line,
        parameters: frame.parameters,
        method_synthesized: member.is_synthesized,
    }
}

fn remap_class_only<'a>(frame: &StackFrame<'a>, reference_file: Option<&str>) -> StackFrame<'a> {
    let file = synthesize_source_file(frame.class, reference_file).map(Cow::Owned);
    StackFrame {
        class: frame.class,
        method: frame.method,
        file,
        line: Some(frame.line.unwrap_or(0)),
        parameters: frame.parameters,
        method_synthesized: false,
    }
}

fn apply_rewrite_rules<'s>(collected: &mut CollectedFrames<'s>, thrown_descriptor: Option<&str>) {
    if collected.frames.is_empty() {
        return;
    }
    for rule in &collected.rewrite_rules {
        let matches = rule.conditions.iter().all(|condition| match condition {
            RewriteCondition::Throws(descriptor) => Some(*descriptor) == thrown_descriptor,
            RewriteCondition::Unknown(_) => false,
        });

        if !matches {
            continue;
        }

        for action in &rule.actions {
            match action {
                RewriteAction::RemoveInnerFrames(count) => {
                    if *count >= collected.frames.len() {
                        collected.frames.clear();
                    } else {
                        collected.frames.drain(0..*count);
                    }
                }
                RewriteAction::Unknown(_) => {}
            }
        }
        if collected.frames.is_empty() {
            break;
        }
    }
}

fn iterate_with_lines<'a>(
    frame: &mut StackFrame<'a>,
    members: &mut core::slice::Iter<'_, MemberMapping<'a>>,
    has_line_info: bool,
) -> Option<StackFrame<'a>> {
    let frame_line = frame.line.unwrap_or(0);
    for member in members {
        // If this method has line mappings, skip base (no-line) entries when we have a concrete line.
        if has_line_info && frame_line > 0 && member.endline.unwrap_or(0) == 0 {
            continue;
        }
        // If the mapping entry has no line range, determine output line.
        if member.endline.unwrap_or(0) == 0 {
            let output_line = if member.original_startline.is_none() {
                // Bare method mapping: pass through frame line.
                frame.line
            } else if member.original_startline.unwrap_or(0) > 0 {
                member.original_startline
            } else {
                None
            };
            return Some(map_member_without_lines(frame, member, output_line));
        }
        if let Some(mapped) = map_member_with_lines(frame, member) {
            return Some(mapped);
        }
    }
    None
}

fn iterate_without_lines<'a>(
    frame: &mut StackFrame<'a>,
    members: &mut core::slice::Iter<'_, MemberMapping<'a>>,
) -> Option<StackFrame<'a>> {
    members.next().map(|member| {
        let output_line = if member.original_startline.unwrap_or(0) > 0 {
            member.original_startline
        } else {
            None
        };
        map_member_without_lines(frame, member, output_line)
    })
}

impl FusedIterator for RemappedFrameIter<'_> {}

/// Resolves frames for the no-line (frame_line==0) case.
///
/// When the input frame has no line number, base entries (endline==0) are preferred
/// over line-mapped entries. Base entries are split into two groups by whether
/// `startline` is present (0:0 entries) or absent (no-range entries), and each
/// group's output lines are computed based on whether the group contains range
/// mappings, single-line mappings, or bare methods.
fn resolve_no_line_frames<'s>(
    frame: &StackFrame<'s>,
    mapping_entries: &'s [MemberMapping<'s>],
    base_entries: &[&'s MemberMapping<'s>],
    collected: &mut CollectedFrames<'s>,
) {
    if !base_entries.is_empty() {
        resolve_base_entries(frame, base_entries, collected);
        return;
    }

    // No base entries — check if the first range group forms an inline group
    // (multiple entries sharing the same startline/endline). If so, resolve
    // that group with proper output lines. Otherwise, fall back to emitting
    // a single frame with line 0 (ambiguous non-inline case).
    //
    // This matches retrace's `allRangesForLine(0, true)` which picks the first
    // range containing line 0 and returns all entries in that range group.
    // Whether this is intentional retrace behavior or accidental is debatable,
    // but we match it because users compare our output against retrace-based tools.
    let Some(first) = mapping_entries.first() else {
        return;
    };

    let first_start = first.startline;
    let first_end = first.endline;
    let first_group: Vec<_> = mapping_entries
        .iter()
        .take_while(|m| m.startline == first_start && m.endline == first_end)
        .collect();

    if first_group.len() > 1 {
        // Inline group: multiple entries share the same range.
        // Resolve each with its proper original line.
        for member in &first_group {
            let line = member.original_startline.filter(|&v| v > 0).or(Some(0));
            collected
                .frames
                .push(map_member_without_lines(frame, member, line));
            collected.rewrite_rules.extend(member.rewrite_rules.iter());
        }
    } else {
        // Ambiguous: each entry has a different range. Collapse to one
        // frame with line 0, matching retrace behavior.
        let unambiguous = mapping_entries.iter().all(|m| m.original == first.original);
        if unambiguous {
            collected
                .frames
                .push(map_member_without_lines(frame, first, Some(0)));
            collected.rewrite_rules.extend(first.rewrite_rules.iter());
        } else {
            for member in mapping_entries {
                collected
                    .frames
                    .push(map_member_without_lines(frame, member, Some(0)));
                collected.rewrite_rules.extend(member.rewrite_rules.iter());
            }
        }
    }
}

/// Resolves output lines for base (endline==0) entries when the frame has no line number.
///
/// Entries are split by whether `startline` is present:
/// - **0:0 entries** (`startline.is_some()`): if any entry has a range
///   (`original_endline != original_startline`), all emit `Some(0)`;
///   otherwise each emits its `original_startline`.
/// - **No-range entries** (`startline.is_none()`): a single entry emits
///   its `original_startline` if > 0, otherwise `Some(0)`; multiple entries
///   with the same name collapse to one frame with `Some(0)`; different names
///   each emit `Some(0)` in original order.
fn resolve_base_entries<'s>(
    frame: &StackFrame<'s>,
    base_entries: &[&'s MemberMapping<'s>],
    collected: &mut CollectedFrames<'s>,
) {
    // Pre-compute aggregates in a single pass.
    // Whether any 0:0 entry has a multi-line original range (original_endline != original_startline).
    let mut any_zero_zero_has_range = false;
    // Number of no-range (startline.is_none()) entries.
    let mut no_range_count = 0usize;
    // Original name of the first no-range entry, used to detect ambiguity.
    let mut first_no_range_name: Option<&str> = None;
    // Whether all no-range entries map to the same original method name.
    let mut all_no_range_same_name = true;
    let mut all_no_range_have_line_mapping = true;
    for member in base_entries {
        if member.startline.is_some() {
            if member.original_endline.is_some()
                && member.original_endline != member.original_startline
            {
                any_zero_zero_has_range = true;
            }
        } else {
            no_range_count += 1;
            if member.original_startline.is_none() {
                all_no_range_have_line_mapping = false;
            }
            match first_no_range_name {
                None => first_no_range_name = Some(member.original),
                Some(first) if member.original != first => all_no_range_same_name = false,
                _ => {}
            }
        }
    }

    // Whether a no-range entry has already been emitted (used to collapse duplicates).
    let mut no_range_emitted = false;
    for member in base_entries {
        if member.startline.is_some() {
            let line = if any_zero_zero_has_range {
                Some(0)
            } else if member.original_startline.unwrap_or(0) > 0 {
                member.original_startline
            } else {
                None
            };
            collected
                .frames
                .push(map_member_without_lines(frame, member, line));
            collected.rewrite_rules.extend(member.rewrite_rules.iter());
        } else if all_no_range_same_name {
            if !no_range_emitted {
                no_range_emitted = true;
                let line = if no_range_count == 1 {
                    member.original_startline.or(Some(0))
                } else {
                    Some(0)
                };
                collected
                    .frames
                    .push(map_member_without_lines(frame, member, line));
                collected.rewrite_rules.extend(member.rewrite_rules.iter());
            }
        } else {
            collected
                .frames
                .push(map_member_without_lines(frame, member, Some(0)));
            collected.rewrite_rules.extend(member.rewrite_rules.iter());
        }
    }

    // Sort no-range frames by original method name when all have line mappings;
    // bare method entries preserve original mapping file order.
    if !all_no_range_same_name && all_no_range_have_line_mapping {
        collected.frames.sort_by_key(|f| f.method);
    }
}

/// A Proguard Remapper.
///
/// This can remap class names, stack frames one at a time, or the complete
/// raw stacktrace.
#[derive(Clone, Debug)]
pub struct ProguardMapper<'s> {
    classes: HashMap<&'s str, ClassMapping<'s>>,
}

impl<'s> From<&'s str> for ProguardMapper<'s> {
    fn from(s: &'s str) -> Self {
        let mapping = ProguardMapping::new(s.as_ref());
        Self::new(mapping)
    }
}

impl<'s> From<(&'s str, bool)> for ProguardMapper<'s> {
    fn from(t: (&'s str, bool)) -> Self {
        let mapping = ProguardMapping::new(t.0.as_ref());
        Self::new_with_param_mapping(mapping, t.1)
    }
}

impl<'s> ProguardMapper<'s> {
    /// Create a new ProguardMapper.
    pub fn new(mapping: ProguardMapping<'s>) -> Self {
        Self::create_proguard_mapper(mapping, false)
    }

    /// Create a new ProguardMapper with the extra mappings_by_params.
    /// This is useful when we want to deobfuscate frames with missing
    /// line information
    pub fn new_with_param_mapping(
        mapping: ProguardMapping<'s>,
        initialize_param_mapping: bool,
    ) -> Self {
        Self::create_proguard_mapper(mapping, initialize_param_mapping)
    }

    fn create_proguard_mapper(
        mapping: ProguardMapping<'s>,
        initialize_param_mapping: bool,
    ) -> Self {
        let parsed = ParsedProguardMapping::parse(mapping, initialize_param_mapping);

        // Initialize class mappings with obfuscated -> original name data. The mappings will be filled in afterwards.
        let mut class_mappings: HashMap<&str, ClassMapping<'s>> = parsed
            .class_names
            .iter()
            .map(|(obfuscated, original)| {
                let is_synthesized = parsed
                    .class_infos
                    .get(original)
                    .map(|ci| ci.is_synthesized)
                    .unwrap_or_default();
                (
                    obfuscated.as_str(),
                    ClassMapping {
                        original: original.as_str(),
                        is_synthesized,
                        ..Default::default()
                    },
                )
            })
            .collect();

        for ((obfuscated_class, obfuscated_method), members) in &parsed.members {
            let class_mapping = class_mappings.entry(obfuscated_class.as_str()).or_default();

            // Get the outer class's sourceFile for use in synthesizing file names
            let outer_source_file = parsed
                .class_names
                .get(obfuscated_class)
                .and_then(|original| parsed.class_infos.get(original))
                .and_then(|ci| ci.source_file);

            let method_mappings = class_mapping
                .members
                .entry(obfuscated_method.as_str())
                .or_default();

            for member in members.all.iter() {
                method_mappings.all_mappings.push(Self::resolve_mapping(
                    &parsed,
                    member,
                    outer_source_file,
                ));
            }

            for (args, param_members) in members.by_params.iter() {
                let param_mappings = method_mappings.mappings_by_params.entry(args).or_default();

                for member in param_members.iter() {
                    param_mappings.push(Self::resolve_mapping(&parsed, member, outer_source_file));
                }
            }
        }

        Self {
            classes: class_mappings,
        }
    }

    fn resolve_mapping(
        parsed: &ParsedProguardMapping<'s>,
        member: &Member<'s>,
        outer_source_file: Option<&'s str>,
    ) -> MemberMapping<'s> {
        let original_file = parsed
            .class_infos
            .get(&member.method.receiver.name())
            .and_then(|class| class.source_file);

        // Only fill in `original_class` if it is _not_ the current class
        let original_class = match member.method.receiver {
            MethodReceiver::ThisClass(_) => None,
            MethodReceiver::OtherClass(original_class_name) => Some(original_class_name.as_str()),
        };

        let method_info = parsed
            .method_infos
            .get(&member.method)
            .copied()
            .unwrap_or_default();
        // A member is considered synthesized if either its own method info
        // or its owning class is marked synthesized.
        let class_synthesized = parsed
            .class_infos
            .get(&member.method.receiver.name())
            .is_some_and(|ci| ci.is_synthesized);
        let is_synthesized = method_info.is_synthesized || class_synthesized;
        let is_outline = method_info.is_outline;

        let outline_callsite_positions = member.outline_callsite_positions.clone();

        MemberMapping {
            startline: member.startline,
            endline: member.endline,
            original_class,
            original_file,
            original: member.method.name.as_str(),
            original_startline: member.original_startline,
            original_endline: member.original_endline,
            is_synthesized,
            is_outline,
            outline_callsite_positions,
            rewrite_rules: member.rewrite_rules.clone(),
            outer_source_file,
        }
    }

    /// If the previous frame was an outline and carried a position, attempt to
    /// map that outline position to a callsite position for the given method.
    fn map_outline_position(
        &self,
        class: &str,
        method: &str,
        callsite_line: usize,
        pos: usize,
        parameters: Option<&str>,
    ) -> Option<usize> {
        let ms = self.classes.get(class)?.members.get(method)?;
        let candidates: &[_] = if let Some(params) = parameters {
            match ms.mappings_by_params.get(params) {
                Some(v) => &v[..],
                None => &[],
            }
        } else {
            &ms.all_mappings[..]
        };

        // Find the member mapping covering the callsite line, then map the pos.
        candidates
            .iter()
            .filter(|m| {
                m.endline.unwrap_or(0) == 0
                    || (callsite_line >= m.startline.unwrap_or(0)
                        && callsite_line <= m.endline.unwrap_or(0))
            })
            .find_map(|m| {
                m.outline_callsite_positions
                    .as_ref()
                    .and_then(|mm| mm.get(&pos).copied())
            })
    }

    /// Determines if a frame refers to an outline method via the method-level flag.
    /// Outline metadata is consistent across all mappings for a method, so checking
    /// a single mapping entry is sufficient.
    fn is_outline_frame(&self, class: &str, method: &str) -> bool {
        self.classes
            .get(class)
            .and_then(|c| c.members.get(method))
            .and_then(|ms| ms.all_mappings.first())
            .is_some_and(|m| m.is_outline)
    }

    /// Applies any carried outline position to the frame line and returns the adjusted frame.
    fn prepare_frame_for_mapping<'a>(
        &self,
        frame: &StackFrame<'a>,
        carried_outline_pos: &mut Option<usize>,
    ) -> StackFrame<'a> {
        let mut effective = frame.clone();
        if let Some(pos) = carried_outline_pos.take() {
            if let Some(mapped) = self.map_outline_position(
                effective.class,
                effective.method,
                effective.line.unwrap_or(0),
                pos,
                effective.parameters,
            ) {
                effective.line = Some(mapped);
            }
        }

        effective
    }

    /// Remaps an obfuscated Class.
    ///
    /// This works on the fully-qualified name of the class, with its complete
    /// module prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// let mapping = r#"android.arch.core.executor.ArchTaskExecutor -> a.a.a.a.c:"#;
    /// let mapper = proguard::ProguardMapper::from(mapping);
    ///
    /// let mapped = mapper.remap_class("a.a.a.a.c");
    /// assert_eq!(mapped, Some("android.arch.core.executor.ArchTaskExecutor"));
    /// ```
    pub fn remap_class(&'s self, class: &str) -> Option<&'s str> {
        self.classes.get(class).map(|class| class.original)
    }

    fn collect_remapped_frames(&'s self, frame: &StackFrame<'s>) -> CollectedFrames<'s> {
        let mut collected = CollectedFrames::default();
        let Some(class) = self.classes.get(frame.class) else {
            return collected;
        };

        let mut frame = frame.clone();
        frame.class = class.original;

        // If we don't have any member mappings, we can still remap the class name.
        // This is especially important for stack frames where the method is not mapped or the
        // stacktrace does not contain sufficient information to resolve the method.
        let Some(members) = class.members.get(frame.method) else {
            collected
                .frames
                .push(remap_class_only(&frame, frame.file()));
            return collected;
        };

        let mapping_entries: &[MemberMapping<'s>] = if let Some(parameters) = frame.parameters {
            let Some(typed_members) = members.mappings_by_params.get(parameters) else {
                return collected;
            };
            typed_members.as_slice()
        } else {
            members.all_mappings.as_slice()
        };

        if frame.parameters.is_none() {
            let has_line_info = mapping_entries.iter().any(|m| m.endline.unwrap_or(0) > 0);
            let frame_line = frame.line.unwrap_or(0);

            // Base entries are those with endline == 0 (no minified range or 0:0 range).
            let base_entries: Vec<&MemberMapping<'s>> = mapping_entries
                .iter()
                .filter(|m| m.endline.unwrap_or(0) == 0)
                .collect();

            // If the stacktrace has no line number, treat it as unknown and remap without
            // applying line filters. If there are base (no-line) mappings present, prefer those.
            if frame_line == 0 {
                resolve_no_line_frames(&frame, mapping_entries, &base_entries, &mut collected);
                return collected;
            }

            // Frame has a line number > 0.
            for member in mapping_entries {
                if has_line_info && frame_line > 0 && member.endline.unwrap_or(0) == 0 {
                    continue;
                }
                if member.endline.unwrap_or(0) == 0 {
                    // No-range entry with frame_line > 0.
                    if member.original_startline.is_none() {
                        // Bare method mapping (no line info) — pass through frame line.
                        collected
                            .frames
                            .push(map_member_without_lines(&frame, member, frame.line));
                        collected.rewrite_rules.extend(member.rewrite_rules.iter());
                        continue;
                    }
                    // Span expansion: if the original range spans multiple lines,
                    // emit one frame per original line.
                    if let Some(oe) = member.original_endline {
                        let os = member.original_startline.unwrap_or(0);
                        if oe > os && (oe - os) <= MAX_SPAN_EXPANSION {
                            for line in os..=oe {
                                collected.frames.push(map_member_without_lines(
                                    &frame,
                                    member,
                                    Some(line),
                                ));
                            }
                            collected.rewrite_rules.extend(member.rewrite_rules.iter());
                            continue;
                        }
                    }
                    // Single-line: use original_startline if > 0, else None.
                    let output_line = if member.original_startline.unwrap_or(0) > 0 {
                        member.original_startline
                    } else {
                        None
                    };
                    collected
                        .frames
                        .push(map_member_without_lines(&frame, member, output_line));
                    collected.rewrite_rules.extend(member.rewrite_rules.iter());
                } else if let Some(mapped) = map_member_with_lines(&frame, member) {
                    collected.frames.push(mapped);
                    collected.rewrite_rules.extend(member.rewrite_rules.iter());
                }
            }

            // Outside-range fallback: if we had line mappings but nothing matched,
            // remap only the class name, keeping the obfuscated method name and original line.
            if collected.frames.is_empty() && has_line_info {
                collected
                    .frames
                    .push(remap_class_only(&frame, frame.file()));
            }
        } else {
            for member in mapping_entries {
                // For parameter-based lookups, use original_startline if > 0, else None
                let output_line = if member.original_startline.unwrap_or(0) > 0 {
                    member.original_startline
                } else {
                    None
                };
                let mapped = map_member_without_lines(&frame, member, output_line);
                collected.frames.push(mapped);
                collected.rewrite_rules.extend(member.rewrite_rules.iter());
            }
        }

        collected
    }

    /// returns a tuple where the first element is the list of the function
    /// parameters and the second one is the return type
    pub fn deobfuscate_signature(&'s self, signature: &str) -> Option<DeobfuscatedSignature> {
        java::deobfuscate_bytecode_signature(signature, self).map(DeobfuscatedSignature::new)
    }

    /// Remaps an obfuscated Class Method.
    ///
    /// The `class` argument has to be the fully-qualified obfuscated name of the
    /// class, with its complete module prefix.
    ///
    /// If the `method` can be resolved unambiguously, it will be returned
    /// alongside the remapped `class`, otherwise `None` is being returned.
    pub fn remap_method(&'s self, class: &str, method: &str) -> Option<(&'s str, &'s str)> {
        let class = self.classes.get(class)?;
        let mut members = class.members.get(method)?.all_mappings.iter();
        let first = members.next()?;

        // We conservatively check that all the mappings point to the same method,
        // as we don’t have line numbers to disambiguate.
        // We could potentially skip inlined functions here, but lets rather be conservative.
        let all_matching = members.all(|member| member.original == first.original);

        all_matching.then_some((class.original, first.original))
    }

    /// Remaps a single Stackframe.
    ///
    /// Returns zero or more [`StackFrame`]s, based on the information in
    /// the proguard mapping. This can return more than one frame in the case
    /// of inlined functions. In that case, frames are sorted top to bottom.
    pub fn remap_frame(&'s self, frame: &StackFrame<'s>) -> RemappedFrameIter<'s> {
        let Some(class) = self.classes.get(frame.class) else {
            return RemappedFrameIter::empty();
        };

        let Some(members) = class.members.get(frame.method) else {
            return RemappedFrameIter::empty();
        };

        let mut frame = frame.clone();
        frame.class = class.original;

        let mappings = if let Some(parameters) = frame.parameters {
            if let Some(typed_members) = members.mappings_by_params.get(parameters) {
                typed_members.iter()
            } else {
                return RemappedFrameIter::empty();
            }
        } else {
            members.all_mappings.iter()
        };

        let has_line_info = members
            .all_mappings
            .iter()
            .any(|m| m.endline.unwrap_or(0) > 0);
        RemappedFrameIter::members(frame, mappings, has_line_info)
    }

    /// Remaps a throwable which is the first line of a full stacktrace.
    ///
    /// # Example
    ///
    /// ```
    /// use proguard::{ProguardMapper, Throwable};
    ///
    /// let mapping = "com.example.Mapper -> a.b:";
    /// let mapper = ProguardMapper::from(mapping);
    ///
    /// let throwable = Throwable::try_parse(b"a.b: Crash").unwrap();
    /// let mapped = mapper.remap_throwable(&throwable);
    ///
    /// assert_eq!(
    ///     Some(Throwable::with_message("com.example.Mapper", "Crash")),
    ///     mapped
    /// );
    /// ```
    pub fn remap_throwable<'a>(&'a self, throwable: &Throwable<'a>) -> Option<Throwable<'a>> {
        self.remap_class(throwable.class).map(|class| Throwable {
            class,
            message: throwable.message,
        })
    }

    /// Remaps a complete Java StackTrace, similar to [`Self::remap_stacktrace_typed`] but instead works on
    /// strings as input and output.
    pub fn remap_stacktrace(&self, input: &str) -> Result<String, std::fmt::Error> {
        let mut stacktrace = String::new();
        let mut carried_outline_pos: Option<usize> = None;
        let mut current_exception_descriptor: Option<String> = None;
        let mut next_frame_can_rewrite = false;

        for line in input.lines() {
            if let Some(throwable) = stacktrace::parse_throwable(line) {
                let remapped_throwable = self.remap_throwable(&throwable);
                let descriptor_class = remapped_throwable
                    .as_ref()
                    .map(|t| t.class)
                    .unwrap_or(throwable.class);
                current_exception_descriptor = Some(class_name_to_descriptor(descriptor_class));
                next_frame_can_rewrite = true;
                format_throwable(&mut stacktrace, line, remapped_throwable)?;
                continue;
            }

            if let Some(frame) = stacktrace::parse_frame(line) {
                if self.is_outline_frame(frame.class, frame.method) {
                    carried_outline_pos = Some(frame.line.unwrap_or(0));
                    continue;
                }

                let effective_frame =
                    self.prepare_frame_for_mapping(&frame, &mut carried_outline_pos);

                let mut collected = self.collect_remapped_frames(&effective_frame);
                let had_frames = !collected.frames.is_empty();
                if next_frame_can_rewrite {
                    apply_rewrite_rules(&mut collected, current_exception_descriptor.as_deref());
                }

                next_frame_can_rewrite = false;
                current_exception_descriptor = None;

                // If rewrite rules cleared all frames, skip entirely
                if had_frames && collected.frames.is_empty() {
                    continue;
                }

                format_frames(&mut stacktrace, line, collected.frames.into_iter())?;
                continue;
            }

            if let Some(cause) = line
                .strip_prefix("Caused by: ")
                .and_then(stacktrace::parse_throwable)
            {
                let remapped_cause = self.remap_throwable(&cause);
                let descriptor_class = remapped_cause
                    .as_ref()
                    .map(|t| t.class)
                    .unwrap_or(cause.class);
                current_exception_descriptor = Some(class_name_to_descriptor(descriptor_class));
                next_frame_can_rewrite = true;
                format_cause(&mut stacktrace, line, remapped_cause)?;
                continue;
            }

            current_exception_descriptor = None;
            next_frame_can_rewrite = false;
            writeln!(&mut stacktrace, "{line}")?;
        }
        Ok(stacktrace)
    }

    /// Remaps a complete Java StackTrace.
    pub fn remap_stacktrace_typed<'a>(&'a self, trace: &StackTrace<'a>) -> StackTrace<'a> {
        let exception = trace
            .exception
            .as_ref()
            .and_then(|t| self.remap_throwable(t));
        let exception_descriptor = trace.exception.as_ref().map(|original| {
            let class = exception
                .as_ref()
                .map(|t| t.class)
                .unwrap_or(original.class);
            class_name_to_descriptor(class)
        });

        let mut carried_outline_pos: Option<usize> = None;
        let mut frames_out = Vec::with_capacity(trace.frames.len());
        let mut next_frame_can_rewrite = exception_descriptor.is_some();
        for f in trace.frames.iter() {
            if self.is_outline_frame(f.class, f.method) {
                carried_outline_pos = Some(f.line.unwrap_or(0));
                continue;
            }

            let effective = self.prepare_frame_for_mapping(f, &mut carried_outline_pos);
            let mut collected = self.collect_remapped_frames(&effective);
            let had_frames = !collected.frames.is_empty();
            if next_frame_can_rewrite {
                apply_rewrite_rules(&mut collected, exception_descriptor.as_deref());
            }
            next_frame_can_rewrite = false;

            // If rewrite rules cleared all frames, skip entirely
            if had_frames && collected.frames.is_empty() {
                continue;
            }

            if collected.frames.is_empty() {
                frames_out.push(f.clone());
            } else {
                frames_out.append(&mut collected.frames);
            }
        }

        let cause = trace
            .cause
            .as_ref()
            .map(|c| Box::new(self.remap_stacktrace_typed(c)));

        StackTrace {
            exception,
            frames: frames_out,
            cause,
        }
    }
}

pub(crate) fn format_throwable(
    stacktrace: &mut impl Write,
    line: &str,
    throwable: Option<Throwable<'_>>,
) -> Result<(), FmtError> {
    if let Some(throwable) = throwable {
        writeln!(stacktrace, "{throwable}")
    } else {
        writeln!(stacktrace, "{line}")
    }
}

pub(crate) fn format_frames<'s>(
    stacktrace: &mut impl Write,
    line: &str,
    remapped: impl Iterator<Item = StackFrame<'s>>,
) -> Result<(), FmtError> {
    let mut remapped = remapped.peekable();

    if remapped.peek().is_none() {
        return writeln!(stacktrace, "{line}");
    }
    for line in remapped {
        writeln!(stacktrace, "    {line}")?;
    }

    Ok(())
}

pub(crate) fn format_cause(
    stacktrace: &mut impl Write,
    line: &str,
    cause: Option<Throwable<'_>>,
) -> Result<(), FmtError> {
    if let Some(cause) = cause {
        writeln!(stacktrace, "Caused by: {cause}")
    } else {
        writeln!(stacktrace, "{line}")
    }
}

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

    #[test]
    fn stacktrace() {
        let mapping = "\
com.example.MainFragment$EngineFailureException -> com.example.MainFragment$d:
com.example.MainFragment$RocketException -> com.example.MainFragment$e:
com.example.MainFragment$onActivityCreated$4 -> com.example.MainFragment$g:
    1:1:void com.example.MainFragment$Rocket.startEngines():90:90 -> onClick
    1:1:void com.example.MainFragment$Rocket.fly():83 -> onClick
    1:1:void onClick(android.view.View):65 -> onClick
    2:2:void com.example.MainFragment$Rocket.fly():85:85 -> onClick
    2:2:void onClick(android.view.View):65 -> onClick
    ";
        let stacktrace = StackTrace {
            exception: Some(Throwable {
                class: "com.example.MainFragment$e",
                message: Some("Crash!"),
            }),
            frames: vec![
                StackFrame {
                    class: "com.example.MainFragment$g",
                    method: "onClick",
                    line: Some(2),
                    file: Some(Cow::Borrowed("SourceFile")),
                    parameters: None,
                    method_synthesized: false,
                },
                StackFrame {
                    class: "android.view.View",
                    method: "performClick",
                    line: Some(7393),
                    file: Some(Cow::Borrowed("View.java")),
                    parameters: None,
                    method_synthesized: false,
                },
            ],
            cause: Some(Box::new(StackTrace {
                exception: Some(Throwable {
                    class: "com.example.MainFragment$d",
                    message: Some("Engines overheating"),
                }),
                frames: vec![StackFrame {
                    class: "com.example.MainFragment$g",
                    method: "onClick",
                    line: Some(1),
                    file: Some(Cow::Borrowed("SourceFile")),
                    parameters: None,
                    method_synthesized: false,
                }],
                cause: None,
            })),
        };
        let expect = "\
com.example.MainFragment$RocketException: Crash!
    at com.example.MainFragment$Rocket.fly(MainFragment.java:85)
    at com.example.MainFragment$onActivityCreated$4.onClick(MainFragment.java:65)
    at android.view.View.performClick(View.java:7393)
Caused by: com.example.MainFragment$EngineFailureException: Engines overheating
    at com.example.MainFragment$Rocket.startEngines(MainFragment.java:90)
    at com.example.MainFragment$Rocket.fly(MainFragment.java:83)
    at com.example.MainFragment$onActivityCreated$4.onClick(MainFragment.java:65)\n";

        let mapper = ProguardMapper::from(mapping);

        assert_eq!(
            mapper.remap_stacktrace_typed(&stacktrace).to_string(),
            expect
        );
    }

    #[test]
    fn stacktrace_str() {
        let mapping = "\
com.example.MainFragment$EngineFailureException -> com.example.MainFragment$d:
com.example.MainFragment$RocketException -> com.example.MainFragment$e:
com.example.MainFragment$onActivityCreated$4 -> com.example.MainFragment$g:
    1:1:void com.example.MainFragment$Rocket.startEngines():90:90 -> onClick
    1:1:void com.example.MainFragment$Rocket.fly():83 -> onClick
    1:1:void onClick(android.view.View):65 -> onClick
    2:2:void com.example.MainFragment$Rocket.fly():85:85 -> onClick
    2:2:void onClick(android.view.View):65 -> onClick
    ";
        let stacktrace = "\
com.example.MainFragment$e: Crash!
    at com.example.MainFragment$g.onClick(SourceFile:2)
    at android.view.View.performClick(View.java:7393)
Caused by: com.example.MainFragment$d: Engines overheating
    at com.example.MainFragment$g.onClick(SourceFile:1)
    ... 13 more";
        let expect = "\
com.example.MainFragment$RocketException: Crash!
    at com.example.MainFragment$Rocket.fly(MainFragment.java:85)
    at com.example.MainFragment$onActivityCreated$4.onClick(MainFragment.java:65)
    at android.view.View.performClick(View.java:7393)
Caused by: com.example.MainFragment$EngineFailureException: Engines overheating
    at com.example.MainFragment$Rocket.startEngines(MainFragment.java:90)
    at com.example.MainFragment$Rocket.fly(MainFragment.java:83)
    at com.example.MainFragment$onActivityCreated$4.onClick(MainFragment.java:65)
    ... 13 more\n";

        let mapper = ProguardMapper::from(mapping);

        assert_eq!(mapper.remap_stacktrace(stacktrace).unwrap(), expect);
    }

    #[test]
    fn rewrite_frame_remove_inner_frame() {
        let mapping = "\
some.Class -> a:
    4:4:void other.Class.inlinee():23:23 -> a
    4:4:void caller(other.Class):7 -> a
    # {\"id\":\"com.android.tools.r8.rewriteFrame\",\"conditions\":[\"throws(Ljava/lang/NullPointerException;)\"],\"actions\":[\"removeInnerFrames(1)\"]}
";
        let stacktrace = "\
java.lang.NullPointerException: Boom
    at a.a(SourceFile:4)";
        let expect = "\
java.lang.NullPointerException: Boom
    at some.Class.caller(Class.java:7)
";

        let mapper = ProguardMapper::from(mapping);

        assert_eq!(mapper.remap_stacktrace(stacktrace).unwrap(), expect);
    }

    #[test]
    fn rewrite_frame_condition_mismatch() {
        let mapping = "\
some.Class -> a:
    4:4:void other.Class.inlinee():23:23 -> a
    4:4:void caller(other.Class):7 -> a
    # {\"id\":\"com.android.tools.r8.rewriteFrame\",\"conditions\":[\"throws(Ljava/lang/NullPointerException;)\"],\"actions\":[\"removeInnerFrames(1)\"]}
";
        let stacktrace = "\
java.lang.IllegalStateException: Boom
    at a.a(SourceFile:4)";
        let expect = "\
java.lang.IllegalStateException: Boom
    at other.Class.inlinee(Class.java:23)
    at some.Class.caller(Class.java:7)
";

        let mapper = ProguardMapper::from(mapping);

        assert_eq!(mapper.remap_stacktrace(stacktrace).unwrap(), expect);
    }

    #[test]
    fn rewrite_frame_typed_stacktrace() {
        let mapping = "\
some.Class -> a:
    4:4:void other.Class.inlinee():23:23 -> a
    4:4:void caller(other.Class):7 -> a
    # {\"id\":\"com.android.tools.r8.rewriteFrame\",\"conditions\":[\"throws(Ljava/lang/NullPointerException;)\"],\"actions\":[\"removeInnerFrames(1)\"]}
";
        let trace = StackTrace {
            exception: Some(Throwable {
                class: "java.lang.NullPointerException",
                message: Some("Boom"),
            }),
            frames: vec![StackFrame {
                class: "a",
                method: "a",
                line: Some(4),
                file: Some(Cow::Borrowed("SourceFile")),
                parameters: None,
                method_synthesized: false,
            }],
            cause: None,
        };

        let mapper = ProguardMapper::from(mapping);
        let remapped = mapper.remap_stacktrace_typed(&trace);

        assert_eq!(remapped.frames.len(), 1);
        assert_eq!(remapped.frames[0].class, "some.Class");
        assert_eq!(remapped.frames[0].method, "caller");
        assert_eq!(remapped.frames[0].line, Some(7));
    }

    #[test]
    fn rewrite_frame_multiple_rules_or_semantics() {
        let mapping = "\
some.Class -> a:
    4:4:void other.Class.inlinee():23:23 -> call
    4:4:void outer():7 -> call
    # {\"id\":\"com.android.tools.r8.rewriteFrame\",\"conditions\":[\"throws(Ljava/lang/NullPointerException;)\"],\"actions\":[\"removeInnerFrames(1)\"]}
    # {\"id\":\"com.android.tools.r8.rewriteFrame\",\"conditions\":[\"throws(Ljava/lang/IllegalStateException;)\"],\"actions\":[\"removeInnerFrames(1)\"]}
";
        let mapper = ProguardMapper::from(mapping);

        let input_npe = "\
java.lang.NullPointerException: Boom
    at a.call(SourceFile:4)";
        let expected_npe = "\
java.lang.NullPointerException: Boom
    at some.Class.outer(Class.java:7)
";
        assert_eq!(mapper.remap_stacktrace(input_npe).unwrap(), expected_npe);

        let input_ise = "\
java.lang.IllegalStateException: Boom
    at a.call(SourceFile:4)";
        let expected_ise = "\
java.lang.IllegalStateException: Boom
    at some.Class.outer(Class.java:7)
";
        assert_eq!(mapper.remap_stacktrace(input_ise).unwrap(), expected_ise);
    }

    #[test]
    fn remap_frame_without_mapping_remaps_class_best_effort() {
        let mapping = "\
some.Class -> a:
    1:1:void some.Class.existing():10:10 -> a
";
        let mapper = ProguardMapper::from(mapping);

        let input = "\
java.lang.RuntimeException: boom
    at a.missing(SourceFile:42)
";
        let expected = "\
java.lang.RuntimeException: boom
    at some.Class.missing(Class.java:42)
";

        assert_eq!(mapper.remap_stacktrace(input).unwrap(), expected);
    }

    #[test]
    fn rewrite_frame_removes_all_frames_skips_line() {
        // When rewrite rules remove ALL frames, the line should be skipped entirely
        // (not fall back to original obfuscated frame)
        let mapping = "\
some.Class -> a:
    4:4:void inlined():10:10 -> call
    4:4:void outer():20 -> call
    # {\"id\":\"com.android.tools.r8.rewriteFrame\",\"conditions\":[\"throws(Ljava/lang/NullPointerException;)\"],\"actions\":[\"removeInnerFrames(2)\"]}
some.Other -> b:
    5:5:void method():30 -> run
";
        let mapper = ProguardMapper::from(mapping);

        let input = "\
java.lang.NullPointerException: Boom
    at a.call(SourceFile:4)
    at b.run(SourceFile:5)
";

        // The first frame (a.call) should be completely removed by rewrite rules,
        // not replaced with the original "at a.call(SourceFile:4)"
        let expected = "\
java.lang.NullPointerException: Boom
    at some.Other.method(Other.java:30)
";

        let actual = mapper.remap_stacktrace(input).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn rewrite_frame_removes_all_frames_skips_line_typed() {
        // When rewrite rules remove ALL frames, the frame should be skipped entirely
        // (not fall back to original obfuscated frame)
        let mapping = "\
some.Class -> a:
    4:4:void inlined():10:10 -> call
    4:4:void outer():20 -> call
    # {\"id\":\"com.android.tools.r8.rewriteFrame\",\"conditions\":[\"throws(Ljava/lang/NullPointerException;)\"],\"actions\":[\"removeInnerFrames(2)\"]}
some.Other -> b:
    5:5:void method():30 -> run
";
        let mapper = ProguardMapper::from(mapping);

        let trace = StackTrace {
            exception: Some(Throwable {
                class: "java.lang.NullPointerException",
                message: Some("Boom"),
            }),
            frames: vec![
                StackFrame {
                    class: "a",
                    method: "call",
                    line: Some(4),
                    file: Some(Cow::Borrowed("SourceFile")),
                    parameters: None,
                    method_synthesized: false,
                },
                StackFrame {
                    class: "b",
                    method: "run",
                    line: Some(5),
                    file: Some(Cow::Borrowed("SourceFile")),
                    parameters: None,
                    method_synthesized: false,
                },
            ],
            cause: None,
        };

        let remapped = mapper.remap_stacktrace_typed(&trace);

        // The first frame should be completely removed by rewrite rules,
        // leaving only the second frame
        assert_eq!(remapped.frames.len(), 1);
        assert_eq!(remapped.frames[0].class, "some.Other");
        assert_eq!(remapped.frames[0].method, "method");
        assert_eq!(remapped.frames[0].line, Some(30));
    }
}