-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathextract.rs
More file actions
1304 lines (1193 loc) · 48.5 KB
/
Copy pathextract.rs
File metadata and controls
1304 lines (1193 loc) · 48.5 KB
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
//! Extract WhatsApp protobuf specs from a bundle. Per-module `Visit` passes
//! capture owned descriptors; a final resolution pass wires cross-module type
//! references and `$`-nesting into a [`ProtoFile`].
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use oxc_allocator::Allocator;
use oxc_ast::ast::{
ArrayExpression, AssignmentExpression, BinaryExpression, BinaryOperator, Expression,
ObjectExpression, ObjectPropertyKind, UnaryOperator, VariableDeclarator,
};
use oxc_ast_visit::{Visit, walk};
use wa_ir::{
ProtoEntity, ProtoEnum, ProtoEnumValue, ProtoField, ProtoFile, ProtoMember, ProtoMessage,
ProtoOneOf,
};
use wa_oxc::{
arg_expr, as_call, as_identifier, as_int, as_string_lit, assignment_target_name,
property_key_name,
};
use wa_transform::ModuleDefinition;
// ─── Wire vocabulary ──────────────────────────────────────────────────────────
/// One spec type is split across two declarations; this rejoins it pre-parse.
const SPLIT_DECL_FROM: &str = "LimitSharing$Trigger";
const SPLIT_DECL_TO: &str = "LimitSharing$TriggerType";
/// Identifier suffix that marks a message/enum spec export (`FooSpec`).
const SPEC_SUFFIX: &str = "Spec";
/// Nested-name separator inside spec identifiers (`Message$ContextInfo`).
const NESTING_SEP: char = '$';
/// Exported member props that are NOT message/enum identifiers.
const PROP_INTERNAL_SPEC: &str = "internalSpec";
const PROP_INTERNAL_DEFAULTS: &str = "internalDefaults";
const PROP_NAME: &str = "name";
/// Constraint keys inside an `internalSpec` object are `__`-prefixed.
const CONSTRAINT_PREFIX: &str = "__";
const KEY_ONEOFS: &str = "__oneofs__";
/// Special module providing enum construction; never a real cross-reference type.
const INTERNAL_ENUM_MODULE: &str = "$InternalEnum";
/// Member-array type/flag namespaces: `X.TYPES.UINT32`, `X.FLAGS.REPEATED`.
const NS_TYPES: &str = "TYPES";
const NS_FLAGS: &str = "FLAGS";
/// Field type keywords (lowercased `TYPES.*`).
const TYPE_MESSAGE: &str = "message";
const TYPE_ENUM: &str = "enum";
const TYPE_MAP: &str = "map";
/// `elements[1]` property name signalling an enum field.
const ENUM_TYPE_PROP: &str = "ENUM";
/// Suffix on enum spec names used to disambiguate enum cross-refs.
const TYPE_SUFFIX: &str = "Type";
const FLAG_PACKED: &str = "packed";
const FLAG_OPTIONAL: &str = "optional";
const FLAG_REPEATED: &str = "repeated";
// ─── Name helpers ─────────────────────────────────────────────────────────────
/// `FooSpec` → `Foo` (borrowing when there is no suffix to strip).
fn rename(name: &str) -> &str {
name.strip_suffix(SPEC_SUFFIX).unwrap_or(name)
}
/// `A$B$C` → `C`.
fn unnest(name: &str) -> &str {
name.rsplit(NESTING_SEP).next().unwrap_or(name)
}
/// `A$B$C` → `A$B` (the parent path).
fn get_nesting(name: &str) -> &str {
match name.rfind(NESTING_SEP) {
Some(i) => &name[..i],
None => "",
}
}
// ─── Intermediate model ───────────────────────────────────────────────────────
/// Deferred type reference, resolved after all modules are scanned.
enum TypeDesc {
Scalar(String),
Map(Box<TypeDesc>, Box<TypeDesc>),
/// `elements[2]` was an identifier → look up this module's idents by alias.
IdentAlias(String),
/// `elements[2]` was a member expression → cross-module / nested reference.
MemberRef {
elem1_is_enum: bool,
obj: Option<String>,
prop: String,
},
Unresolved,
}
struct FieldDesc {
name: String,
id: i64,
ty: TypeDesc,
flags: Vec<String>,
}
enum MemberDesc {
Field(FieldDesc),
OneOf {
name: String,
fields: Vec<FieldDesc>,
},
}
#[derive(Default)]
struct Ident {
name: String,
alias: Option<String>,
enum_values: Option<Vec<ProtoEnumValue>>,
members: Option<Vec<MemberDesc>>,
/// field name → proto2 default token, from `X.internalDefaults = {...}`.
defaults: HashMap<String, String>,
}
#[derive(Default)]
struct ModuleInfo {
cross_refs: Vec<(String, String)>, // (alias, module)
identifiers: HashMap<String, Ident>,
/// `(target_alias, members)` captured from `X.internalSpec = {...}`.
specs: Vec<(String, Vec<MemberDesc>)>,
/// `(target_alias, field→default)` captured from `X.internalDefaults = {...}`.
defaults: Vec<(String, HashMap<String, String>)>,
enum_aliases: HashMap<String, Vec<ProtoEnumValue>>,
alias_matches: Vec<(String, String)>, // (renamed key, alias)
ident_order: Vec<String>,
}
#[derive(Default)]
struct Indent {
indentation: String,
members: BTreeSet<String>,
}
// ─── Public entry ─────────────────────────────────────────────────────────────
/// Extract a [`ProtoFile`] from a bundle's source.
pub fn extract_proto(bundle_source: &str, wa_version: &str) -> ProtoFile {
let module_defs = wa_transform::extract_module_definitions(bundle_source);
extract_proto_from_modules(bundle_source, &module_defs, wa_version)
}
/// Extract a [`ProtoFile`] from an already-split module index (shares one
/// whole-bundle parse with the other extractors; only proto module slices are
/// re-parsed here).
pub fn extract_proto_from_modules(
source: &str,
module_defs: &[ModuleDefinition],
wa_version: &str,
) -> ProtoFile {
let mut modules: HashMap<String, ModuleInfo> = HashMap::new();
let mut indent_map: HashMap<String, Indent> = HashMap::new();
for def in module_defs {
let slice = &source[def.start..def.end];
if !slice.contains(PROP_INTERNAL_SPEC) {
continue;
}
// One spec type is split across two declarations; rejoin it before
// parsing. The split only ever occurs inside a proto module, so patching
// the slice is equivalent to the old whole-bundle replace, without the
// ~71MB clone.
let patched: Cow<str> = if slice.contains(SPLIT_DECL_FROM) {
Cow::Owned(slice.replace(SPLIT_DECL_FROM, SPLIT_DECL_TO))
} else {
Cow::Borrowed(slice)
};
let alloc = Allocator::default();
let ret = wa_oxc::parse_cjs(&alloc, &patched);
let mut info = ModuleInfo::default();
let mut cross = CrossRefCollector { refs: Vec::new() };
cross.visit_program(&ret.program);
info.cross_refs = cross.refs;
let mut idents = IdentCollector { names: Vec::new() };
idents.visit_program(&ret.program);
info.ident_order = idents.names;
let mut enums = EnumAliasCollector {
aliases: HashMap::new(),
};
enums.visit_program(&ret.program);
info.enum_aliases = enums.aliases;
let mut am = AliasMatchCollector {
matches: Vec::new(),
};
am.visit_program(&ret.program);
info.alias_matches = am.matches;
let mut contents = ContentsCollector { specs: Vec::new() };
contents.visit_program(&ret.program);
info.specs = contents.specs;
let mut defaults = DefaultsCollector {
defaults: Vec::new(),
};
defaults.visit_program(&ret.program);
info.defaults = defaults.defaults;
modules.insert(def.name.clone(), info);
}
// Build blank identifiers (reversed: first declaration wins) + nesting map.
for info in modules.values_mut() {
for key in info.ident_order.iter().rev() {
let indentation = get_nesting(key).to_string();
indent_map.entry(key.clone()).or_default().indentation = indentation.clone();
if !indentation.is_empty() {
indent_map
.entry(indentation.clone())
.or_default()
.members
.insert(key.clone());
}
info.identifiers
.entry(key.clone())
.or_insert_with(|| Ident {
name: key.clone(),
..Default::default()
});
}
}
// Match aliases → identifiers, attach enum values.
for info in modules.values_mut() {
let aliases = std::mem::take(&mut info.alias_matches);
let enum_aliases = std::mem::take(&mut info.enum_aliases);
for (key, alias) in aliases {
if let Some(ident) = info.identifiers.get_mut(&key) {
ident.alias = Some(alias.clone());
ident.enum_values = enum_aliases.get(&alias).cloned();
}
}
}
// Attach message members to their target identifier (by alias).
for info in modules.values_mut() {
let specs = std::mem::take(&mut info.specs);
for (target_alias, members) in specs {
if let Some(key) = info
.identifiers
.iter()
.find(|(_, v)| v.alias.as_deref() == Some(target_alias.as_str()))
.map(|(k, _)| k.clone())
{
info.identifiers.get_mut(&key).unwrap().members = Some(members);
}
}
}
// Attach proto2 field defaults to their target identifier (same alias match).
for info in modules.values_mut() {
let defaults = std::mem::take(&mut info.defaults);
for (target_alias, map) in defaults {
if let Some(key) = info
.identifiers
.iter()
.find(|(_, v)| v.alias.as_deref() == Some(target_alias.as_str()))
.map(|(k, _)| k.clone())
{
info.identifiers.get_mut(&key).unwrap().defaults = map;
}
}
}
// Resolve into the proto entity tree.
let mut entities: Vec<ProtoEntity> = Vec::new();
for info in modules.values() {
for ident in info.identifiers.values() {
let is_top_level = indent_map
.get(&ident.name)
.map(|i| i.indentation.is_empty())
.unwrap_or(true);
if is_top_level
&& let Some(entity) = build_entity(ident, &ident.name, info, &modules, &indent_map)
{
entities.push(entity);
}
}
}
ProtoFile {
wa_version: wa_version.to_string(),
entities: make_protoc_valid(entities),
}
}
// ─── protoc-validity post-processing ──────────────────────────────────────────
/// Reconcile the resolved tree with `protoc`'s C++ enum scoping.
///
/// WhatsApp's runtime is protobuf.js, which scopes enum values *per enum*, so the
/// bundle happily declares two top-level enums sharing a value name (e.g.
/// `ADVEncryptionType` and `HostedState` both with `E2EE`/`HOSTED`). `protoc`
/// instead treats enum values as siblings of the enum's *container*, so two such
/// top-level enums collide at package scope. The bundle also re-exports common
/// types from several modules (a legacy `WAFingerprint.pb` + a
/// `WAWebProtobufsFingerprintV3.pb` variant, …), surfacing the same type twice.
/// Neither survives `protoc`. This pass:
/// 1. drops duplicate top-level entities (keeps one), and
/// 2. relocates a colliding top-level enum *into* the message that references
/// it, scoping its values out of the package namespace.
fn make_protoc_valid(entities: Vec<ProtoEntity>) -> Vec<ProtoEntity> {
relocate_colliding_enums(dedup_top_level(entities))
}
/// Keep one entity per top-level name. Duplicates are byte-identical in practice
/// (the same spec exported by two modules); sorting by `(name, debug)` makes the
/// survivor deterministic even if two same-named entities ever diverged, since the
/// source `modules` map iterates in a nondeterministic order.
fn dedup_top_level(mut entities: Vec<ProtoEntity>) -> Vec<ProtoEntity> {
entities.sort_by(|a, b| {
a.name()
.cmp(b.name())
.then_with(|| format!("{a:?}").cmp(&format!("{b:?}")))
});
let mut out: Vec<ProtoEntity> = Vec::with_capacity(entities.len());
for e in entities {
if out.last().map(ProtoEntity::name) != Some(e.name()) {
out.push(e);
}
}
out
}
/// Move any top-level enum whose value names clash with another top-level enum's
/// under the message that references it. In each clash component the most-
/// referenced enum stays at package scope (it is the hardest to re-home cleanly);
/// the rest are nested into a referencing message, which scopes their values away.
fn relocate_colliding_enums(mut entities: Vec<ProtoEntity>) -> Vec<ProtoEntity> {
// value name -> top-level enums declaring it.
let mut owners: HashMap<String, BTreeSet<String>> = HashMap::new();
for e in &entities {
if let ProtoEntity::Enum(en) = e {
for v in &en.values {
owners
.entry(v.name.clone())
.or_default()
.insert(en.name.clone());
}
}
}
// Adjacency among enums that share at least one value name.
let mut adj: HashMap<String, BTreeSet<String>> = HashMap::new();
for set in owners.values().filter(|s| s.len() > 1) {
for a in set {
for b in set.iter().filter(|b| *b != a) {
adj.entry(a.clone()).or_default().insert(b.clone());
}
}
}
if adj.is_empty() {
return entities;
}
let refs = referencers(&entities);
let ref_count = |name: &str| refs.get(name).map(BTreeSet::len).unwrap_or(0);
// Walk clash components; pick a keeper, schedule the rest for relocation.
let mut visited: BTreeSet<String> = BTreeSet::new();
let mut decisions: Vec<(String, String)> = Vec::new(); // (enum, host message)
let mut prefix_only: Vec<String> = Vec::new(); // colliding but no referencer
for start in adj.keys().cloned().collect::<BTreeSet<String>>() {
if visited.contains(&start) {
continue;
}
let mut comp: BTreeSet<String> = BTreeSet::new();
let mut stack = vec![start];
while let Some(n) = stack.pop() {
if !visited.insert(n.clone()) {
continue;
}
comp.insert(n.clone());
for m in adj.get(&n).into_iter().flatten() {
if !visited.contains(m) {
stack.push(m.clone());
}
}
}
// Keeper: most referencers; tie broken by smallest name (deterministic).
let keeper = comp
.iter()
.max_by(|a, b| ref_count(a).cmp(&ref_count(b)).then_with(|| b.cmp(a)))
.cloned()
.expect("component is non-empty");
for en in comp.iter().filter(|e| **e != keeper) {
match refs.get(en).and_then(|hosts| hosts.iter().next()) {
Some(host) => decisions.push((en.clone(), host.clone())),
None => prefix_only.push(en.clone()),
}
}
}
let relocated: BTreeSet<String> = decisions.iter().map(|(e, _)| e.clone()).collect();
// Pull the relocated enums out of the top level.
let mut taken: HashMap<String, ProtoEntity> = HashMap::new();
entities.retain(|e| {
if matches!(e, ProtoEntity::Enum(_)) && relocated.contains(e.name()) {
taken.insert(e.name().to_string(), e.clone());
false
} else {
true
}
});
// Defensive fallback for an unreferenced colliding enum (cannot be nested):
// prefix its values so they no longer clash at package scope. Does not occur
// in current bundles, but keeps the output protoc-valid unconditionally.
for e in &mut entities {
if let ProtoEntity::Enum(en) = e
&& prefix_only.contains(&en.name)
{
let prefix = en.name.clone();
for v in &mut en.values {
v.name = format!("{prefix}_{}", v.name);
}
}
}
// An enum referenced by *several* top-level messages can still be relocated,
// but references from outside its new home must then be fully qualified.
let qualified: HashMap<String, String> = decisions
.iter()
.filter(|(en, _)| ref_count(en) > 1)
.map(|(en, host)| (en.clone(), format!("{host}.{en}")))
.collect();
if !qualified.is_empty() {
for e in &mut entities {
if let ProtoEntity::Message(m) = e {
rewrite_refs(m, &qualified);
}
}
}
// Nest each relocated enum under its host (host-grouped, sorted by name).
let mut by_host: BTreeMap<String, Vec<ProtoEntity>> = BTreeMap::new();
for (en, host) in &decisions {
if let Some(ent) = taken.remove(en) {
by_host.entry(host.clone()).or_default().push(ent);
}
}
for e in &mut entities {
if let ProtoEntity::Message(m) = e
&& let Some(mut adds) = by_host.remove(&m.name)
{
adds.sort_by(|a, b| a.name().cmp(b.name()));
m.nested.extend(adds);
}
}
// A host should always be found above; re-home any leftover at top level
// rather than silently dropping it.
for adds in by_host.into_values() {
entities.extend(adds);
}
entities
}
/// Map each top-level message to the type names referenced anywhere in its
/// subtree (fields, `oneof` fields, and nested messages).
fn referencers(entities: &[ProtoEntity]) -> HashMap<String, BTreeSet<String>> {
let mut map: HashMap<String, BTreeSet<String>> = HashMap::new();
for e in entities {
if let ProtoEntity::Message(m) = e {
let mut refs = BTreeSet::new();
collect_refs(m, &mut refs);
for r in refs {
map.entry(r).or_default().insert(m.name.clone());
}
}
}
map
}
fn collect_refs(m: &ProtoMessage, out: &mut BTreeSet<String>) {
for mem in &m.members {
match mem {
ProtoMember::Field(f) => {
for b in type_ref_bases(&f.type_name) {
out.insert(b.to_string());
}
}
ProtoMember::OneOf(o) => {
for f in &o.fields {
for b in type_ref_bases(&f.type_name) {
out.insert(b.to_string());
}
}
}
}
}
for n in &m.nested {
if let ProtoEntity::Message(nm) = n {
collect_refs(nm, out);
}
}
}
/// Base (unqualified) type name(s) of a printed field type: the trailing segment
/// of a dotted path, or both sides of a `map<K, V>`.
fn type_ref_bases(type_name: &str) -> Vec<&str> {
/// Trailing segment of a dotted path (`A.B.C` → `C`), trimmed.
fn base(t: &str) -> &str {
let t = t.trim();
t.rsplit('.').next().unwrap_or(t)
}
match type_name
.strip_prefix("map<")
.and_then(|s| s.strip_suffix('>'))
{
Some(inner) => inner.split(',').map(base).collect(),
None => vec![base(type_name)],
}
}
/// Rewrite field types referencing a relocated enum to their qualified form.
fn rewrite_refs(m: &mut ProtoMessage, map: &HashMap<String, String>) {
for mem in &mut m.members {
match mem {
ProtoMember::Field(f) => rewrite_type(&mut f.type_name, map),
ProtoMember::OneOf(o) => {
for f in &mut o.fields {
rewrite_type(&mut f.type_name, map);
}
}
}
}
for n in &mut m.nested {
if let ProtoEntity::Message(nm) = n {
rewrite_refs(nm, map);
}
}
}
fn rewrite_type(type_name: &mut String, map: &HashMap<String, String>) {
if let Some(repl) = map.get(type_name.as_str()) {
*type_name = repl.clone();
return;
}
if let Some(inner) = type_name
.strip_prefix("map<")
.and_then(|s| s.strip_suffix('>'))
{
let parts: Vec<String> = inner
.split(',')
.map(|p| {
let t = p.trim();
map.get(t).cloned().unwrap_or_else(|| t.to_string())
})
.collect();
*type_name = format!("map<{}>", parts.join(", "));
}
}
// ─── Resolution ───────────────────────────────────────────────────────────────
fn build_entity(
ident: &Ident,
display_name: &str,
info: &ModuleInfo,
modules: &HashMap<String, ModuleInfo>,
indent_map: &HashMap<String, Indent>,
) -> Option<ProtoEntity> {
if let Some(members) = &ident.members {
// A message. Resolve members, then attach nested children (sorted).
let proto_members = members
.iter()
.map(|m| resolve_member(m, &ident.name, &ident.defaults, info, modules, indent_map))
.collect();
let mut nested = Vec::new();
if let Some(indent) = indent_map.get(&ident.name) {
for child_key in &indent.members {
if let Some(child) = info.identifiers.get(child_key) {
let child_display = child_key
.strip_prefix(&format!("{}$", ident.name))
.unwrap_or(unnest(child_key));
if let Some(e) = build_entity(child, child_display, info, modules, indent_map) {
nested.push(e);
}
}
}
}
Some(ProtoEntity::Message(ProtoMessage {
name: display_name.to_string(),
members: proto_members,
nested,
}))
} else {
ident.enum_values.as_ref().map(|values| {
ProtoEntity::Enum(ProtoEnum {
name: display_name.to_string(),
values: values.clone(),
})
})
}
}
fn resolve_member(
m: &MemberDesc,
parent_name: &str,
defaults: &HashMap<String, String>,
info: &ModuleInfo,
modules: &HashMap<String, ModuleInfo>,
indent_map: &HashMap<String, Indent>,
) -> ProtoMember {
match m {
MemberDesc::OneOf { name, fields } => {
// oneof fields carry no auto-`optional` and no parent context, so
// nested types are always fully qualified. proto2 forbids defaults on
// oneof fields, so pass an empty map (also enforced by `message_member`).
let fields = fields
.iter()
.map(|f| build_field(f, None, false, &HashMap::new(), info, modules, indent_map))
.collect();
ProtoMember::OneOf(ProtoOneOf {
name: name.clone(),
fields,
})
}
MemberDesc::Field(f) => ProtoMember::Field(build_field(
f,
Some(parent_name),
true,
defaults,
info,
modules,
indent_map,
)),
}
}
fn build_field(
f: &FieldDesc,
parent_name: Option<&str>,
message_member: bool,
defaults: &HashMap<String, String>,
info: &ModuleInfo,
modules: &HashMap<String, ModuleInfo>,
indent_map: &HashMap<String, Indent>,
) -> ProtoField {
let resolved_type = resolve_type(&f.ty, info, modules);
let type_name = qualify_type(&resolved_type, parent_name, indent_map);
let mut flags = f.flags.clone();
// `packed` is a wire encoding hint, not a label: lift it out wherever it sits
// and keep the remaining flags (e.g. `repeated`) in order — truncating from
// `packed` would drop `repeated` if it ever appeared after it.
let packed = flags.iter().any(|fl| fl == FLAG_PACKED);
flags.retain(|fl| fl != FLAG_PACKED);
if message_member && flags.is_empty() && !type_name.contains(TYPE_MAP) {
flags.push(FLAG_OPTIONAL.to_string());
}
// A proto2 default applies only to a singular message field — never a oneof
// member (`message_member` is false there) nor a `repeated` field (protoc rejects
// that). All of WA's `internalDefaults` target singular optional fields.
let default = (message_member && !flags.iter().any(|fl| fl == FLAG_REPEATED))
.then(|| defaults.get(&f.name).cloned())
.flatten();
ProtoField {
name: f.name.clone(),
id: f.id,
type_name,
flags,
packed,
default,
}
}
fn resolve_type(ty: &TypeDesc, info: &ModuleInfo, modules: &HashMap<String, ModuleInfo>) -> String {
match ty {
TypeDesc::Scalar(s) => s.clone(),
TypeDesc::Map(k, v) => format!(
"map<{}, {}>",
resolve_type(k, info, modules),
resolve_type(v, info, modules)
),
TypeDesc::IdentAlias(alias) => info
.identifiers
.values()
.find(|v| v.alias.as_deref() == Some(alias.as_str()))
.map(|v| v.name.clone())
.unwrap_or_else(|| alias.clone()),
TypeDesc::MemberRef {
elem1_is_enum,
obj,
prop,
} => {
if (*elem1_is_enum && prop.contains(TYPE_SUFFIX)) || prop.contains(SPEC_SUFFIX) {
rename(prop).to_string()
} else {
// Cross-module reference: match the cross-ref by exact alias.
let key = rename(prop);
let cross = info
.cross_refs
.iter()
.find(|(alias, _)| Some(alias.as_str()) == obj.as_deref());
if let Some((_, module)) = cross
&& module != INTERNAL_ENUM_MODULE
&& modules
.get(module)
.is_some_and(|m| m.identifiers.contains_key(key))
{
return key.to_string();
}
key.to_string()
}
}
TypeDesc::Unresolved => "/*unresolved*/".to_string(),
}
}
/// Apply `$`-nesting: unnest the type name and, if it lives under a different
/// parent than the current message, qualify it with a dotted path.
fn qualify_type(
type_name: &str,
parent_name: Option<&str>,
indent_map: &HashMap<String, Indent>,
) -> String {
let base = unnest(type_name).to_string();
if let Some(indent) = indent_map.get(type_name)
&& !indent.indentation.is_empty()
&& Some(indent.indentation.as_str()) != parent_name
{
return format!("{}.{}", indent.indentation.replace(NESTING_SEP, "."), base);
}
base
}
// ─── Collectors ───────────────────────────────────────────────────────────────
struct CrossRefCollector {
refs: Vec<(String, String)>,
}
impl<'a> Visit<'a> for CrossRefCollector {
fn visit_assignment_expression(&mut self, n: &AssignmentExpression<'a>) {
if let Some(call) = as_call(&n.right)
&& call.arguments.len() == 1
&& let Some(arg0) = arg_expr(&call.arguments[0])
&& !matches!(arg0, Expression::ObjectExpression(_))
&& let (Some(alias), Some(module)) =
(assignment_target_name(&n.left), as_string_lit(arg0))
{
self.refs.push((alias.to_string(), module.to_string()));
}
walk::walk_assignment_expression(self, n);
}
}
struct IdentCollector {
names: Vec<String>,
}
impl<'a> Visit<'a> for IdentCollector {
fn visit_assignment_expression(&mut self, n: &AssignmentExpression<'a>) {
if let Some(prop) = n
.left
.as_member_expression()
.and_then(|m| m.static_property_name())
&& prop != PROP_INTERNAL_SPEC
&& prop != PROP_INTERNAL_DEFAULTS
&& prop != PROP_NAME
{
self.names.push(rename(prop).to_string());
}
walk::walk_assignment_expression(self, n);
}
}
struct EnumAliasCollector {
aliases: HashMap<String, Vec<ProtoEnumValue>>,
}
impl EnumAliasCollector {
/// Enum defined as `X = someCall({A:0, B:1})` (e.g. `$InternalEnum(...)`).
fn record_call(&mut self, name_alias: &str, init: &Expression) {
if let Some(call) = as_call(init)
&& let Some(Expression::ObjectExpression(obj)) =
call.arguments.first().and_then(arg_expr)
{
let values = enum_values_from_obj(obj);
if !values.is_empty() {
self.aliases.insert(name_alias.to_string(), values);
}
}
}
/// Enum defined as a direct literal `var X = {A:0, B:1}`.
fn record_object_literal(&mut self, name_alias: &str, init: &Expression) {
if let Expression::ObjectExpression(obj) = init {
let values = enum_values_from_obj(obj);
if !values.is_empty() {
self.aliases.insert(name_alias.to_string(), values);
}
}
}
}
impl<'a> Visit<'a> for EnumAliasCollector {
fn visit_variable_declarator(&mut self, d: &VariableDeclarator<'a>) {
if let (Some(name), Some(init)) = (d.id.get_identifier_name(), d.init.as_ref()) {
self.record_call(name.as_str(), init);
self.record_object_literal(name.as_str(), init);
}
walk::walk_variable_declarator(self, d);
}
fn visit_assignment_expression(&mut self, n: &AssignmentExpression<'a>) {
if let Some(name) = assignment_target_name(&n.left) {
self.record_call(name, &n.right);
}
walk::walk_assignment_expression(self, n);
}
}
fn enum_values_from_obj(obj: &ObjectExpression) -> Vec<ProtoEnumValue> {
let mut out = Vec::new();
for prop in &obj.properties {
let ObjectPropertyKind::ObjectProperty(p) = prop else {
continue;
};
// Keep forward `IDENT: int` members; skip non-forward entries (e.g.
// protobuf.js's bidirectional reverse map `0: "NAME"`) rather than
// discarding the whole enum. Aliases only become enums when matched to an
// enum declaration later, so a stray non-enum object stays harmless.
if let (Some(name), Some(id)) = (property_key_name(&p.key), as_int(&p.value)) {
out.push(ProtoEnumValue {
name: name.to_string(),
id,
});
}
}
out
}
struct AliasMatchCollector {
matches: Vec<(String, String)>,
}
impl<'a> Visit<'a> for AliasMatchCollector {
fn visit_assignment_expression(&mut self, n: &AssignmentExpression<'a>) {
if let Some(prop) = n
.left
.as_member_expression()
.and_then(|m| m.static_property_name())
&& let Some(right) = as_identifier(&n.right)
{
self.matches
.push((rename(prop).to_string(), right.to_string()));
}
walk::walk_assignment_expression(self, n);
}
}
struct ContentsCollector {
specs: Vec<(String, Vec<MemberDesc>)>,
}
impl<'a> Visit<'a> for ContentsCollector {
fn visit_assignment_expression(&mut self, n: &AssignmentExpression<'a>) {
if let Some(member) = n.left.as_member_expression()
&& member.static_property_name() == Some(PROP_INTERNAL_SPEC)
&& let (Some(obj_name), Expression::ObjectExpression(obj)) =
(as_identifier(member.object()), &n.right)
{
self.specs
.push((obj_name.to_string(), parse_internal_spec(obj)));
}
walk::walk_assignment_expression(self, n);
}
}
/// Captures `X.internalDefaults = { field: <defaultExpr>, … }` — the proto2
/// per-field defaults, keyed (like `internalSpec`) by the message's alias `X`.
struct DefaultsCollector {
defaults: Vec<(String, HashMap<String, String>)>,
}
impl<'a> Visit<'a> for DefaultsCollector {
fn visit_assignment_expression(&mut self, n: &AssignmentExpression<'a>) {
if let Some(member) = n.left.as_member_expression()
&& member.static_property_name() == Some(PROP_INTERNAL_DEFAULTS)
&& let (Some(obj_name), Expression::ObjectExpression(obj)) =
(as_identifier(member.object()), &n.right)
{
self.defaults
.push((obj_name.to_string(), parse_defaults(obj)));
}
walk::walk_assignment_expression(self, n);
}
}
/// Parse an `internalDefaults` object into `field → proto2 default token`, dropping
/// any value whose expression shape isn't a recognized default (see [`resolve_default`]).
fn parse_defaults(obj: &ObjectExpression) -> HashMap<String, String> {
let mut out = HashMap::new();
for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(p) = prop
&& let Some(key) = property_key_name(&p.key)
&& let Some(value) = resolve_default(&p.value)
{
out.insert(key.to_string(), value);
}
}
out
}
/// Resolve a single `internalDefaults` value to its proto2 default token. WA declares
/// these as an enum-variant member (`s.E2EE` / `c.Foo.E2EE` → the variant name), a
/// numeric literal (`1`), a negated number (`-1`), or a boolean written `!1`/`!0`.
/// Returns `None` for anything else (which then emits no default, never a wrong one).
fn resolve_default(expr: &Expression) -> Option<String> {
// An enum default references a variant: the bare last property name is the token.
if let Some(member) = expr.as_member_expression() {
return member.static_property_name().map(str::to_string);
}
match expr {
Expression::NumericLiteral(n) => Some(format_number(n.value)),
Expression::BooleanLiteral(b) => Some(b.value.to_string()),
Expression::StringLiteral(s) => Some(s.value.to_string()),
Expression::UnaryExpression(u) => {
let Expression::NumericLiteral(n) = &u.argument else {
return None;
};
match u.operator {
// `!1` → false, `!0` → true (JS truthiness of the numeric operand).
UnaryOperator::LogicalNot => Some((n.value == 0.0).to_string()),
UnaryOperator::UnaryNegation => Some(format!("-{}", format_number(n.value))),
_ => None,
}
}
_ => None,
}
}
/// Render a numeric default without a spurious `.0` (WA's numeric defaults are integers).
fn format_number(v: f64) -> String {
if v.fract() == 0.0 && v.abs() < 9.007_199_254_740_992e15 {
(v as i64).to_string()
} else {
v.to_string()
}
}
// ─── internalSpec parsing ─────────────────────────────────────────────────────
fn parse_internal_spec(obj: &ObjectExpression) -> Vec<MemberDesc> {
let mut fields: Vec<FieldDesc> = Vec::new();
let mut oneofs: Vec<(String, Vec<String>)> = Vec::new();
for prop in &obj.properties {
let ObjectPropertyKind::ObjectProperty(p) = prop else {
continue;
};
let Some(key) = property_key_name(&p.key) else {
continue;
};
if key.starts_with(CONSTRAINT_PREFIX) {
if key == KEY_ONEOFS
&& let Expression::ObjectExpression(o) = &p.value
{
for op in &o.properties {
if let ObjectPropertyKind::ObjectProperty(oneof) = op
&& let (Some(oname), Expression::ArrayExpression(arr)) =
(property_key_name(&oneof.key), &oneof.value)
{
let names = arr
.elements
.iter()
.filter_map(|e| e.as_expression().and_then(as_string_lit))
.map(str::to_string)
.collect();
oneofs.push((oname.to_string(), names));
}
}
}
continue;
}
if let Expression::ArrayExpression(arr) = &p.value
&& let Some(field) = parse_field(key, arr)
{
fields.push(field);
}
}
// Splice oneof members out of the flat field list into their groups, then emit
// the remaining fields (original order) followed by the oneof groups. A