@@ -170,6 +170,7 @@ func parseWAT(_ parser: inout Parser, features: WasmFeatureSet) throws -> Wat {
170170
171171 var exportDecls : [ WatParser . ExportDecl ] = [ ]
172172
173+ var hasNonImport = false
173174 func visitDecl( decl: WatParser . ModuleField ) throws {
174175 let location = decl. location
175176
@@ -188,10 +189,23 @@ func parseWAT(_ parser: inout Parser, features: WasmFeatureSet) throws -> Wat {
188189 }
189190 }
190191
192+ // Verify that imports precede all non-import module fields
193+ func checkImportOrder( _ importNames: WatParser . ImportNames ? ) throws {
194+ if importNames != nil {
195+ if hasNonImport {
196+ throw WatParserError ( " Imports must precede all non-import module fields " , location: location)
197+ }
198+ } else {
199+ hasNonImport = true
200+ }
201+ }
202+
203+
191204 switch decl. kind {
192205 case let . type( decl) :
193206 try typesMap. add ( decl)
194207 case let . function( decl) :
208+ try checkImportOrder ( decl. importNames)
195209 let index = try functionsMap. add ( decl)
196210 addExports ( decl. exports, index: index, kind: . function)
197211 switch decl. kind {
@@ -203,6 +217,7 @@ func parseWAT(_ parser: inout Parser, features: WasmFeatureSet) throws -> Wat {
203217 }
204218 }
205219 case let . table( decl) :
220+ try checkImportOrder ( decl. importNames)
206221 let index = try tablesMap. add ( decl)
207222 addExports ( decl. exports, index: index, kind: . table)
208223 if var inlineElement = decl. inlineElement {
@@ -215,6 +230,7 @@ func parseWAT(_ parser: inout Parser, features: WasmFeatureSet) throws -> Wat {
215230 addImport ( importNames) { . table( decl. type) }
216231 }
217232 case let . memory( decl) :
233+ try checkImportOrder ( decl. importNames)
218234 let index = try memoriesMap. add ( decl)
219235 if var inlineData = decl. inlineData {
220236 // Associate the memory with the inline data
@@ -227,6 +243,7 @@ func parseWAT(_ parser: inout Parser, features: WasmFeatureSet) throws -> Wat {
227243 addImport ( importNames) { . memory( decl. type) }
228244 }
229245 case let . global( decl) :
246+ try checkImportOrder ( decl. importNames)
230247 let index = try globalsMap. add ( decl)
231248 addExports ( decl. exports, index: index, kind: . global)
232249 switch decl. kind {
0 commit comments