-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathComponentWatParser.swift
More file actions
1416 lines (1262 loc) · 67 KB
/
Copy pathComponentWatParser.swift
File metadata and controls
1416 lines (1262 loc) · 67 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
#if ComponentModel
import ComponentModel
import WasmParserCore
import WasmTypes
public struct ComponentWatParser: ~Copyable {
let features: WasmFeatureSet
/// Stack of components currently being parsed (supports nested components)
private var componentStack: [ComponentDef] = []
struct Field {
enum Kind {
case component(Int)
}
}
init(features: WasmFeatureSet) {
self.features = features
// Initialize stack with empty root component
self.componentStack.append(ComponentDef())
}
private var currentComponent: ComponentDef {
_read {
yield self.componentStack[componentStack.count - 1]
}
_modify {
yield &self.componentStack[componentStack.count - 1]
}
}
/// Returns the parsed root component after all fields have been processed
consuming func parse(_ parser: inout Parser) throws(WatParserError) -> ComponentDef {
try parser.expect(.leftParen)
try parser.expectKeyword("component")
let id = try parser.takeId()
componentStack.append(ComponentDef(id: id))
try parseComponentFields(&parser)
try parser.expect(.rightParen)
return componentStack.removeLast()
}
/// Parses a component body when `(component $id?` has already been consumed.
/// Expects the parser to be positioned at the first field or closing `)`.
/// Consumes the closing `)` and returns the parsed ComponentDef.
consuming func parseComponentBody(_ parser: inout Parser, id: Name?) throws(WatParserError) -> ComponentDef {
componentStack.append(ComponentDef(id: id))
try parseComponentFields(&parser)
try parser.expect(.rightParen)
return componentStack.removeLast()
}
/// Parses component fields until a closing `)` is encountered.
/// Assumes the parser is positioned after `(component $id?`.
private mutating func parseComponentFields(_ parser: inout Parser) throws(WatParserError) {
while try parser.take(.leftParen) {
let keyword = try parser.expectKeyword()
let location = parser.lexer.location()
switch keyword {
case "core":
try parseCoreDef(&parser)
case "type":
try parseComponentTypeDef(&parser)
case "func":
try parseComponentFunc(&parser)
case "component":
let nestedId = try parser.takeId()
componentStack.append(ComponentDef(id: nestedId))
try parseComponentFields(&parser) // Recursive call for nested components
let nested = componentStack.removeLast()
_ = try currentComponent.componentsMap.add(nested)
currentComponent.fields.append(.init(location: location, kind: .component(nested)))
case "import":
try parseComponentImport(&parser, location: location)
case "export":
try parseComponentExport(&parser, location: location)
case "instance":
try parseComponentInstance(&parser, location: location)
case "alias":
try parseComponentAlias(&parser, location: location)
default:
throw WatParserError(
"Unknown component definition keyword \(keyword)",
location: location
)
}
try parser.expect(.rightParen)
}
}
/// Parse a core definition (module, instance, type, or func via canon lower) and add it to the current component
private mutating func parseCoreDef(_ parser: inout Parser) throws(WatParserError) {
let coreKeyword = try parser.expectKeyword()
let location = parser.lexer.location()
switch coreKeyword {
case "module":
let moduleDef = try self.parseModuleDef(&parser)
_ = try self.currentComponent.coreModulesMap.add(moduleDef)
self.currentComponent.fields.append(
.init(location: location, kind: .coreModule(moduleDef))
)
case "instance":
let instanceDef = try self.parseCoreInstanceDef(&parser)
_ = try self.currentComponent.coreInstancesMap.add(instanceDef)
self.currentComponent.fields.append(
.init(location: location, kind: .coreInstance(instanceDef))
)
case "type":
let coreTypeDef = try self.parseCoreTypeDef(&parser)
_ = try self.currentComponent.coreTypesMap.add(coreTypeDef)
self.currentComponent.fields.append(
.init(location: location, kind: .coreType(coreTypeDef))
)
case "func":
// (core func $id (canon lower (func $instance "export")))
let coreFuncId = try parser.takeId()
try parser.expect(.leftParen)
try parser.expectKeyword("canon")
try parser.expectKeyword("lower")
// Parse component function reference: (func $instance "export") or (func $index)
let componentFuncRef = try parseComponentFunctionIndex(&parser)
// Parse canon options
var options = [CanonDef.Option]()
while try parser.take(.leftParen) {
options.append(try parseCanonOpt(&parser))
try parser.expect(.rightParen)
}
try parser.expect(.rightParen) // Close the (canon lower ...) block
// Track core function in the core functions index space
let coreFuncIndex = try self.currentComponent.coreFunctionsMap.add(
CoreFuncDef(id: coreFuncId)
)
self.currentComponent.fields.append(
.init(
location: location,
kind: .canon(
.init(
kind: .lower(componentFuncRef),
functionIndex: FuncIndex(instance: .index(0, location), exportName: ""), // Placeholder for lower
options: options
))
)
)
_ = coreFuncIndex // Will be used for resolving references
default:
throw WatParserError(
"Unknown core definition keyword \(coreKeyword)",
location: location
)
}
}
/// Parse a component import definition
/// Syntax: (import "name" (instance $id? (export "name" (func ...))...))
private mutating func parseComponentImport(_ parser: inout Parser, location: Location) throws(WatParserError) {
let importName = try parser.expectString()
try parser.expect(.leftParen)
let descKeyword = try parser.expectKeyword()
switch descKeyword {
case "instance":
let instanceId = try parser.takeId()
// Parse the instance type constraint
let instanceTypeDef = try parseInstanceTypeDeclarations(&parser)
try parser.expect(.rightParen)
// Add the instance type to componentTypes
let typeDef = ComponentTypeDef(id: nil, kind: .instance(instanceTypeDef))
let typeIndex = try currentComponent.componentTypes.add(typeDef)
// Add the instance to componentInstancesMap
let instanceIndex = try currentComponent.componentInstancesMap.add(
ComponentInstanceDef(id: instanceId, componentRef: nil, arguments: [])
)
// Add import field with reference to the type
currentComponent.fields.append(
.init(
location: location,
kind: .componentImport(
ImportDef(
importModuleName: "", // Not used for component imports
importName: importName,
descriptor: .instance(.index(UInt32(typeIndex), location))
))
)
)
_ = instanceIndex // silence unused warning
case "func":
// Handle function imports
let funcId = try parser.takeId()
#warning("Skipping the type constraint as unimplemented")
var depth = 1
while depth > 0 {
if try parser.take(.leftParen) {
depth += 1
} else if try parser.take(.rightParen) {
depth -= 1
} else {
try parser.consume()
}
}
// Add function to componentFunctions
let funcIndex = try currentComponent.componentFunctions.add(
ComponentFuncDef(id: funcId, paramNames: [], type: ComponentTypeIndex(rawValue: 0))
)
currentComponent.fields.append(
.init(
location: location,
kind: .componentImport(
ImportDef(
importModuleName: "",
importName: importName,
descriptor: .function(ComponentFuncIndex(funcIndex))
))
)
)
default:
throw WatParserError("Unsupported import descriptor '\(descKeyword)'", location: parser.lexer.location())
}
}
/// Parse a component export definition
/// Syntax: (export "name" (func $ref)) or (export "name" (func $instance "exportname"))
private mutating func parseComponentExport(_ parser: inout Parser, location: Location) throws(WatParserError) {
let exportName = try parser.expectString()
try parser.expect(.leftParen)
let descKeyword = try parser.expectKeyword()
let descriptor: ExternDesc
switch descKeyword {
case "func":
// Check if it's (func $idx) or (func $instance "name")
let firstArg = try parser.expectIndexOrId()
if let exportedName = try parser.takeString() {
// It's (func $instance "name") - function from an instance export
descriptor = .functionFromInstance(firstArg, exportedName)
} else {
// It's (func $idx) - direct function index
let funcIndex = try currentComponent.componentFunctions.resolveIndex(use: firstArg)
descriptor = .function(ComponentFuncIndex(funcIndex))
}
try parser.expect(.rightParen)
case "instance":
// (instance $ref)
let instanceRef = try parser.expectIndexOrId()
descriptor = .instance(instanceRef)
try parser.expect(.rightParen)
case "type":
// (type $ref)
let typeRef = try parser.expectIndexOrId()
descriptor = .type(typeRef)
try parser.expect(.rightParen)
default:
throw WatParserError("Unsupported export descriptor '\(descKeyword)'", location: parser.lexer.location())
}
currentComponent.fields.append(
.init(
location: location,
kind: .componentExport(
ExportDef(
exportName: exportName,
descriptor: descriptor
))
)
)
}
/// Parse a component-level alias definition
/// Syntax: (alias core export $instance "name" (core <sort> $bindingId))
private mutating func parseComponentAlias(_ parser: inout Parser, location: Location) throws(WatParserError) {
// Parse: core export $instance "name"
try parser.expectKeyword("core")
try parser.expectKeyword("export")
let instanceIndex = try parser.expectIndexOrId()
let exportName = try parser.expectString()
// Parse: (core <sort> $bindingId)
try parser.expect(.leftParen)
try parser.expectKeyword("core")
let sortKeyword = try parser.expectKeyword()
guard let sort = CoreDefSort(rawValue: sortKeyword) else {
throw WatParserError("Unknown core alias sort '\(sortKeyword)'", location: parser.lexer.location())
}
let bindingId = try parser.takeId()
try parser.expect(.rightParen) // Close (core <sort> ...)
let alias = ComponentAlias(
sort: .core(sort),
target: .export(isCore: true, instanceIndex: instanceIndex, exportName: exportName),
bindingId: bindingId
)
// Add to appropriate index space based on sort
switch sort {
case .func:
let funcDef = CoreFuncDef(id: bindingId)
_ = try currentComponent.coreFunctionsMap.add(funcDef)
case .memory:
let memDef = CoreMemoryAliasDef(id: bindingId)
_ = try currentComponent.coreMemoriesMap.add(memDef)
case .table, .global, .type, .module, .instance:
// TODO: Add support for table and global aliases
#warning("Not all core alias sorts supported yet")
break
}
currentComponent.fields.append(
.init(location: location, kind: .alias(alias))
)
}
/// Parse a component instance definition
/// Syntax: (instance $id (instantiate $component (with "name" (instance $ref))...))
private mutating func parseComponentInstance(_ parser: inout Parser, location: Location) throws(WatParserError) {
let instanceId = try parser.takeId()
try parser.expect(.leftParen)
try parser.expectKeyword("instantiate")
let componentRef = try parser.expectIndexOrId()
var arguments = [ComponentInstanceArgument]()
while try parser.takeParenBlockStart("with") {
let argName = try parser.expectString()
try parser.expect(.leftParen)
let argKind = try parser.expectKeyword()
let argValue: ComponentInstanceArgument.Kind
switch argKind {
case "instance":
let instanceRef = try parser.expectIndexOrId()
argValue = .instance(instanceRef)
default:
throw WatParserError("Unsupported component instance argument kind '\(argKind)'", location: parser.lexer.location())
}
try parser.expect(.rightParen) // Close (instance ...)
try parser.expect(.rightParen) // Close (with ...)
arguments.append(ComponentInstanceArgument(name: argName, kind: argValue))
}
try parser.expect(.rightParen) // Close (instantiate ...)
let instanceDef = ComponentInstanceDef(id: instanceId, componentRef: componentRef, arguments: arguments)
_ = try currentComponent.componentInstancesMap.add(instanceDef)
currentComponent.fields.append(
.init(location: location, kind: .instance(instanceDef))
)
}
/// Parse a component type definition (func, instance, component, or primitive) with optional inline exports
private mutating func parseComponentTypeDef(_ parser: inout Parser) throws(WatParserError) {
let typeLocation = parser.lexer.location()
let typeId = try parser.takeId()
// Parse inline exports (zero or more)
var inlineExports: [(location: Location, name: String)] = []
while try parser.takeParenBlockStart("export") {
let exportLocation = parser.lexer.location()
let exportName = try parser.expectString()
inlineExports.append((location: exportLocation, name: exportName))
try parser.expect(.rightParen)
}
let kind: ComponentTypeDef.Kind
if try parser.take(.leftParen) {
// Parenthesized type constructor
let typeKeyword = try parser.expectKeyword()
switch typeKeyword {
case "func":
let params = try parseFuncParams(&parser)
var resultType: ComponentValueType?
if try parser.takeParenBlockStart("result") {
resultType = try parseComponentValueType(&parser)
try parser.expect(.rightParen)
}
kind = .function(ComponentFuncType(params: params, result: resultType))
try parser.expect(.rightParen)
case "instance":
let instanceTypeDef = try parseInstanceTypeDeclarations(&parser)
kind = .instance(instanceTypeDef)
try parser.expect(.rightParen)
case "component":
let componentTypeDef = try parseComponentTypeDeclarations(&parser)
kind = .component(componentTypeDef)
try parser.expect(.rightParen)
case "record":
var fields: [ComponentRecordField] = []
while try parser.takeParenBlockStart("field") {
let fieldName = try parser.expectString()
let fieldType = try parseComponentValueType(&parser)
let fieldTypeIndex: ComponentTypeIndex
if case .indexed(let idx) = fieldType {
fieldTypeIndex = idx
} else {
let idx = try addAnonymousComponentType(fieldType)
fieldTypeIndex = ComponentTypeIndex(rawValue: idx)
}
fields.append(ComponentRecordField(name: fieldName, type: fieldTypeIndex))
try parser.expect(.rightParen)
}
let recordType = ComponentValueType.record(fields)
kind = .value(recordType)
try parser.expect(.rightParen)
case "variant":
var cases: [ComponentCaseField] = []
while try parser.takeParenBlockStart("case") {
_ = try parser.takeId() // optional case id like $x
let caseName = try parser.expectString()
var caseType: ComponentTypeIndex? = nil
if try !parser.take(.rightParen) {
let valueType = try parseComponentValueType(&parser)
if case .indexed(let idx) = valueType {
caseType = idx
} else {
let idx = try addAnonymousComponentType(valueType)
caseType = ComponentTypeIndex(rawValue: idx)
}
try parser.expect(.rightParen)
}
cases.append(ComponentCaseField(name: caseName, type: caseType))
}
let variantType = ComponentValueType.variant(cases)
kind = .value(variantType)
try parser.expect(.rightParen)
case "flags":
var flagNames: [String] = []
while let flagName = try parser.takeString() {
flagNames.append(flagName)
}
let flagsType = ComponentValueType.flags(flagNames)
kind = .value(flagsType)
try parser.expect(.rightParen)
case "enum":
var enumCases: [String] = []
while let caseName = try parser.takeString() {
enumCases.append(caseName)
}
let enumType = ComponentValueType.enum(enumCases)
kind = .value(enumType)
try parser.expect(.rightParen)
case "list":
let elementType = try parseComponentValueType(&parser)
let elementIndex: ComponentTypeIndex
if case .indexed(let idx) = elementType {
elementIndex = idx
} else {
let elemIdx = try addAnonymousComponentType(elementType)
elementIndex = ComponentTypeIndex(rawValue: elemIdx)
}
let listType = ComponentValueType.list(elementIndex)
kind = .value(listType)
try parser.expect(.rightParen)
case "tuple":
var typeIndices: [ComponentTypeIndex] = []
while try !parser.take(.rightParen) {
let valueType = try parseComponentValueType(&parser)
if case .indexed(let idx) = valueType {
typeIndices.append(idx)
} else {
let elemIdx = try addAnonymousComponentType(valueType)
typeIndices.append(ComponentTypeIndex(rawValue: elemIdx))
}
}
let tupleType = ComponentValueType.tuple(typeIndices)
kind = .value(tupleType)
case "option":
let someType = try parseComponentValueType(&parser)
let elementIndex: ComponentTypeIndex
if case .indexed(let idx) = someType {
elementIndex = idx
} else {
let elemIdx = try addAnonymousComponentType(someType)
elementIndex = ComponentTypeIndex(rawValue: elemIdx)
}
let optionType = ComponentValueType.option(elementIndex)
kind = .value(optionType)
try parser.expect(.rightParen)
case "result":
var okType: ComponentTypeIndex?
var errorType: ComponentTypeIndex?
// Result can be: (result), (result TYPE), (result (ok TYPE)), (result (error TYPE)),
// (result TYPE (error TYPE)), (result (ok TYPE) (error TYPE))
if try !parser.take(.rightParen) {
// Check for (error ...) first (error-only result)
if try parser.takeParenBlockStart("error") {
let valueType = try parseComponentValueType(&parser)
if case .indexed(let idx) = valueType {
errorType = idx
} else {
errorType = ComponentTypeIndex(rawValue: try addAnonymousComponentType(valueType))
}
try parser.expect(.rightParen)
try parser.expect(.rightParen)
} else if try parser.takeParenBlockStart("ok") {
// Explicit (ok TYPE)
let valueType = try parseComponentValueType(&parser)
if case .indexed(let idx) = valueType {
okType = idx
} else {
okType = ComponentTypeIndex(rawValue: try addAnonymousComponentType(valueType))
}
try parser.expect(.rightParen)
// Check for optional (error TYPE)
if try parser.takeParenBlockStart("error") {
let errType = try parseComponentValueType(&parser)
if case .indexed(let idx) = errType {
errorType = idx
} else {
errorType = ComponentTypeIndex(rawValue: try addAnonymousComponentType(errType))
}
try parser.expect(.rightParen)
}
try parser.expect(.rightParen)
} else {
// Shorthand: TYPE is the ok type
let valueType = try parseComponentValueType(&parser)
if case .indexed(let idx) = valueType {
okType = idx
} else {
okType = ComponentTypeIndex(rawValue: try addAnonymousComponentType(valueType))
}
// Check for optional (error TYPE)
if try parser.takeParenBlockStart("error") {
let errType = try parseComponentValueType(&parser)
if case .indexed(let idx) = errType {
errorType = idx
} else {
errorType = ComponentTypeIndex(rawValue: try addAnonymousComponentType(errType))
}
try parser.expect(.rightParen)
}
try parser.expect(.rightParen)
}
}
let resultType = ComponentValueType.result(ok: okType, error: errorType)
kind = .value(resultType)
default:
throw WatParserError(
"Unsupported type definition keyword \(typeKeyword)",
location: parser.lexer.location()
)
}
} else {
// Shorthand: primitive value type keyword directly (e.g., `bool`, `u8`, etc.)
let primitiveType = try parseComponentValueType(&parser)
kind = .value(primitiveType)
}
let typeDef = ComponentTypeDef(id: typeId, kind: kind)
let typeIndex = try self.currentComponent.componentTypes.add(typeDef)
self.currentComponent.typesMap[kind] = typeIndex
// Add the type definition to fields
self.currentComponent.fields.append(
.init(
location: typeLocation,
kind: .componentType(typeDef, typeIndex: typeIndex)
)
)
// Generate exports for inline export annotations (after the type)
for inlineExport in inlineExports {
self.currentComponent.fields.append(
.init(
location: inlineExport.location,
kind: .componentExport(
ExportDef(
exportName: inlineExport.name,
descriptor: .type(.index(UInt32(typeIndex), typeLocation))
))
)
)
}
}
private mutating func parseModuleDef(_ parser: inout Parser) throws(WatParserError) -> ModuleDef {
let moduleID = try parser.takeId()
let wat = try parseWAT(&parser, features: features)
return .init(id: moduleID, wat: wat)
}
private mutating func parseModuleInstanceArguments(_ parser: inout Parser) throws(WatParserError) -> CoreInstanceDef.Argument {
try parser.expectKeyword("with")
let importName = try parser.expectString()
try parser.expect(.leftParen)
let result: CoreInstanceDef.Argument.Kind
if try parser.takeKeyword("instance") {
// Check if it's a reference to an existing instance or inline exports
if try parser.peek(.leftParen) != nil {
// Inline exports: (instance (export "name" (func $ref))...)
var exports: [CoreInstanceDef.Argument.Kind.Export] = []
while try parser.takeParenBlockStart("export") {
let exportName = try parser.expectString()
try parser.expect(.leftParen)
let sort = try parseCoreDefSort(&parser)
let indexOrId = try parser.expectIndexOrId()
// Resolve the index from the appropriate index space
let resolvedIndex: UInt32
switch sort {
case .func:
resolvedIndex = try UInt32(self.currentComponent.coreFunctionsMap.resolveIndex(use: indexOrId))
case .memory:
// For memory, we'd need to resolve through core memory index space
throw WatParserError("Inline export of memory not yet supported", location: parser.lexer.location())
default:
throw WatParserError("Inline export of \(sort) not yet supported", location: parser.lexer.location())
}
try parser.expect(.rightParen) // Close (func/memory/etc.)
try parser.expect(.rightParen) // Close (export ...)
exports.append(.init(name: exportName, sort: sort, index: resolvedIndex))
}
result = .exports(exports)
} else {
// Reference to existing instance: (instance $ref)
let instanceID = try parser.expectIndexOrId()
result = .instance(instanceID)
}
} else {
throw WatParserError("Expected 'instance' keyword after '('", location: parser.lexer.location())
}
try parser.expect(.rightParen)
return .init(importName: importName, kind: result)
}
private mutating func parseCoreDefSort(_ parser: inout Parser) throws(WatParserError) -> CoreDefSort {
let rawKeyword = try parser.expectKeyword()
guard let keyword = CoreDefSort(rawValue: rawKeyword) else {
throw WatParserError(
"Unexpected core declaration sort `\(rawKeyword)",
location: parser.lexer.location()
)
}
return keyword
}
private mutating func parseComponentDefSort(_ parser: inout Parser) throws(WatParserError) -> ComponentDefSort {
let rawKeyword = try parser.expectKeyword()
switch rawKeyword {
case "core":
return .core(try parseCoreDefSort(&parser))
case "func": return .func
case "value": return .value
case "type": return .type
case "component": return .component
case "instance": return .instance
default:
throw WatParserError(
"Unexpected component declaration sort `\(rawKeyword)",
location: parser.lexer.location()
)
}
}
private mutating func parseCoreInstanceDef(_ parser: inout Parser) throws(WatParserError) -> CoreInstanceDef {
let instanceId = try parser.takeId()
try parser.expect(.leftParen)
try parser.expectKeyword("instantiate")
let instantiatedModuleId = try parser.expectIndexOrId()
var instantiateArguments = [CoreInstanceDef.Argument]()
while try parser.take(.leftParen) {
instantiateArguments.append(try self.parseModuleInstanceArguments(&parser))
try parser.expect(.rightParen)
}
try parser.expect(.rightParen)
return CoreInstanceDef(
id: instanceId,
moduleId: instantiatedModuleId,
arguments: instantiateArguments
)
}
private mutating func parseCoreTypeDef(_ parser: inout Parser) throws(WatParserError) -> CoreTypeDef {
let typeId = try parser.takeId()
try parser.expect(.leftParen)
let keyword = try parser.expectKeyword()
let kind: CoreTypeDef.Kind
switch keyword {
case "func":
let (parameters, parameterNames) = try parser.parseParamList(mayHaveName: true) { parser throws(WatParserError) in
try Self.parseCoreValueType(&parser)
}
let results = try parser.parseResultList { parser throws(WatParserError) in
try Self.parseCoreValueType(&parser)
}
let funcType = WatParser.FunctionType(
signature: WasmTypes.FunctionType(parameters: parameters, results: results),
parameterNames: parameterNames
)
kind = .function(funcType)
case "module":
var declarations: [CoreModuleDecl] = []
while try parser.take(.leftParen) {
let declKeyword = try parser.expectKeyword()
switch declKeyword {
case "alias":
try parser.expectKeyword("outer")
let componentIndex = try parser.expectIndexOrId()
let typeIndex = try parser.expectIndexOrId()
try parser.expect(.leftParen)
let sortKeyword = try parser.expectKeyword()
let bindingId = try parser.takeId()
try parser.expect(.rightParen)
guard let aliasSort = CoreDefSort(rawValue: sortKeyword) else {
throw WatParserError("Unknown alias sort '\(sortKeyword)'", location: parser.lexer.location())
}
// Resolve outer alias immediately using component stack
let (resolvedIndex, outerCount) = try resolveOuterReference(componentId: componentIndex, typeIndex: typeIndex, sort: aliasSort)
declarations.append(
.alias(
CoreModuleAlias(
sort: aliasSort,
target: .outer(componentId: componentIndex, index: typeIndex, resolvedIndex: resolvedIndex, outerCount: outerCount),
bindingId: bindingId
)))
case "import":
let moduleName = try parser.expectString()
let importName = try parser.expectString()
try parser.expect(.leftParen)
let descKeyword = try parser.expectKeyword()
let descriptor: CoreImportDesc
switch descKeyword {
case "func":
try parser.expect(.leftParen)
try parser.expectKeyword("type")
let typeIndex = try parser.expectIndexOrId()
try parser.expect(.rightParen)
descriptor = .func(typeIndex: typeIndex)
default:
throw WatParserError("Unsupported import descriptor '\(descKeyword)'", location: parser.lexer.location())
}
try parser.expect(.rightParen)
declarations.append(
.import(
CoreModuleImport(
moduleName: moduleName,
name: importName,
descriptor: descriptor
)))
default:
throw WatParserError("Unknown module declaration '\(declKeyword)'", location: parser.lexer.location())
}
try parser.expect(.rightParen)
}
var moduleTypeDef = CoreModuleTypeDef(declarations: declarations)
// Build local type bindings from aliases
for (index, decl) in declarations.enumerated() {
if case .alias(let alias) = decl,
alias.sort == .type,
let bindingId = alias.bindingId
{
if moduleTypeDef.localTypeBindings[bindingId.value] != nil {
throw WatParserError("Duplicate type binding \(bindingId.value)", location: bindingId.location)
}
moduleTypeDef.localTypeBindings[bindingId.value] = index
}
}
kind = .module(moduleTypeDef)
default:
throw WatParserError("Unknown core type keyword \(keyword)", location: parser.lexer.location())
}
try parser.expect(.rightParen)
return CoreTypeDef(id: typeId, kind: kind)
}
private static func parseCoreValueType(_ parser: inout Parser) throws(WatParserError) -> WasmTypes.ValueType {
var tempParser = WatParser(parser: parser)
let unresolvedType = try tempParser.valueType()
parser = tempParser.parser
// Core types must be simple value types (i32, i64, f32, f64), not type references.
// Resolve immediately using a throwing resolver since these types don't reference other definitions.
return try unresolvedType.resolve { (use: Parser.IndexOrId) throws(WatParserError) in
throw WatParserError("Core value types cannot reference other types", location: use.location)
}
}
/// Resolve an outer alias reference to a component's type
/// Returns a tuple of (resolvedTypeIndex, outerCount) where outerCount is the distance to the target component
private mutating func resolveOuterReference(componentId: Parser.IndexOrId, typeIndex: Parser.IndexOrId, sort: CoreDefSort) throws(WatParserError) -> (resolvedIndex: Int, outerCount: Int) {
// Find the target component in the component stack
// For now, we assume componentId refers to a parent component by name
// TODO: Support numeric outer counts (e.g., outer 0, outer 1)
guard case .id(let targetName, _) = componentId else {
throw WatParserError("Numeric outer counts not yet supported", location: componentId.location)
}
// Search component stack from top down (most recent first)
// Include the current component (it can reference itself from within a module type)
let currentDepth = componentStack.count - 1
for i in (0...currentDepth).reversed() {
let component = componentStack[i]
if let compId = component.id, compId.value == targetName.value {
// Found the target component - resolve the type in its namespace
// Outer count is from the module type's perspective:
// - 1 level to get from module type to containing component
// - (currentDepth - i) levels from containing component to target
let outerCount = (currentDepth - i) + 1
switch sort {
case .type:
let resolvedIndex = try component.coreTypesMap.resolveIndex(use: typeIndex)
return (resolvedIndex, outerCount)
case .func, .table, .memory, .global, .module, .instance:
throw WatParserError("Outer alias sort '\(sort.rawValue)' not yet supported", location: componentId.location)
}
}
}
throw WatParserError("Component '\(targetName.value)' not found in outer scope", location: componentId.location)
}
/// Parse instance type declarations (type decls and exports)
private mutating func parseInstanceTypeDeclarations(_ parser: inout Parser) throws(WatParserError) -> InstanceTypeDef {
var typeDecls: [InstanceTypeDef.TypeDecl] = []
var exports: [InstanceTypeDef.ExportDecl] = []
while try parser.take(.leftParen) {
let declKeyword = try parser.expectKeyword()
switch declKeyword {
case "type":
let typeId = try parser.takeId()
let valueType = try parseComponentValueType(&parser)
typeDecls.append(InstanceTypeDef.TypeDecl(id: typeId, valueType: valueType))
case "export":
let exportName = try parser.expectString()
#warning("Skipping the type constraint as unimplemented")
var depth = 1
while depth > 0 {
if try parser.take(.leftParen) {
depth += 1
} else if try parser.take(.rightParen) {
depth -= 1
} else {
try parser.consume()
}
}
exports.append(InstanceTypeDef.ExportDecl(name: exportName))
continue // Skip the outer expect(.rightParen) since we already consumed it
default:
throw WatParserError("Unknown instance type declaration '\(declKeyword)'", location: parser.lexer.location())
}
try parser.expect(.rightParen)
}
return InstanceTypeDef(typeDecls: typeDecls, exports: exports)
}
/// Parse component type declarations (type decls, imports, and exports)
private mutating func parseComponentTypeDeclarations(_ parser: inout Parser) throws(WatParserError) -> ComponentInnerTypeDef {
var typeDecls: [ComponentInnerTypeDef.TypeDecl] = []
var imports: [ComponentInnerTypeDef.ImportDecl] = []
var exports: [ComponentInnerTypeDef.ExportDecl] = []
while try parser.take(.leftParen) {
let declKeyword = try parser.expectKeyword()
switch declKeyword {
case "type":
let typeId = try parser.takeId()
let valueType = try parseComponentValueType(&parser)
typeDecls.append(ComponentInnerTypeDef.TypeDecl(id: typeId, valueType: valueType))
case "import":
let importName = try parser.expectString()
#warning("Skipping the type constraint as unimplemented")
var depth = 1
while depth > 0 {
if try parser.take(.leftParen) {
depth += 1
} else if try parser.take(.rightParen) {
depth -= 1
} else {
try parser.consume()
}
}
imports.append(ComponentInnerTypeDef.ImportDecl(name: importName))
continue
case "export":
let exportName = try parser.expectString()
#warning("Skipping the type constraint as unimplemented")
var depth = 1
while depth > 0 {
if try parser.take(.leftParen) {
depth += 1
} else if try parser.take(.rightParen) {
depth -= 1
} else {
try parser.consume()
}
}
exports.append(ComponentInnerTypeDef.ExportDecl(name: exportName))
continue
default:
throw WatParserError("Unknown component type declaration '\(declKeyword)'", location: parser.lexer.location())
}
try parser.expect(.rightParen)
}
return ComponentInnerTypeDef(typeDecls: typeDecls, imports: imports, exports: exports)
}
private mutating func parseComponentValueType(_ parser: inout Parser) throws(WatParserError) -> ComponentValueType {
// First check for type reference (identifier like $A1)
if let typeRef = try parser.takeId() {
// Resolve the type reference to an index
let typeIndex = try currentComponent.componentTypes.resolveIndex(
use: .id(typeRef, typeRef.location)
)
return .indexed(ComponentTypeIndex(rawValue: typeIndex))
}
let primitiveTypeKeyword = try parser.peekKeyword()
if let primitiveTypeKeyword {
let primitiveType: ComponentValueType
switch primitiveTypeKeyword {
case "bool": primitiveType = .bool
case "u8": primitiveType = .u8
case "u16": primitiveType = .u16
case "u32": primitiveType = .u32
case "u64": primitiveType = .u64
case "s8": primitiveType = .s8
case "s16": primitiveType = .s16
case "s32": primitiveType = .s32
case "s64": primitiveType = .s64
case "float32", "f32": primitiveType = .float32
case "float64", "f64": primitiveType = .float64
case "char": primitiveType = .char
case "string": primitiveType = .string
case "error-context": primitiveType = .errorContext
default:
throw WatParserError(
"Unexpected primitive component type keyword `\(primitiveTypeKeyword)`",
location: parser.lexer.location()
)
}
try parser.consume()