File: ParserTests.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (205 lines) | stat: -rw-r--r-- 7,077 bytes parent folder | download
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
import Foundation
import WasmParser
import XCTest

@testable import WAT

class ParserTests: XCTestCase {
    func parseWast(_ source: String, features: WasmFeatureSet = .default) throws -> [WastDirective] {
        var parser = WastParser(source, features: features)
        var directives: [WastDirective] = []
        while let directive = try parser.nextDirective() {
            directives.append(directive)
        }
        return directives
    }

    func parseModule(_ source: String) throws -> ModuleDirective? {
        let directives = try parseWast(source)
        guard case let .module(moduleDirective) = directives.first else {
            XCTFail("Expected module directive")
            return nil
        }
        return moduleDirective
    }

    func parseBinaryModule(_ source: String) throws -> (source: [UInt8], id: String?)? {
        guard let module = try parseModule(source) else { return nil }
        guard case let .binary(content) = module.source else { return nil }
        return (content, module.id)
    }

    func testParseWastBinaryModule() throws {
        try XCTAssertEqual(
            parseBinaryModule(#"(module binary "\00asm\01\00\00\00")"#)?.source,
            [0, 97, 115, 109, 1, 0, 0, 0]
        )
        try XCTAssertEqual(
            parseBinaryModule(
                #"""
                (module binary
                "\00asm" "\01\00\00\00"
                ;; comment between strings
                "foo"
                )
                """#)?.source,
            [0, 97, 115, 109, 1, 0, 0, 0, 102, 111, 111]
        )

        do {
            let m1 = try parseBinaryModule(#"(module $M1 binary "\00asm\01\00\00\00")"#)
            XCTAssertEqual(m1?.id, "$M1")
            XCTAssertEqual(m1?.source, [0, 97, 115, 109, 1, 0, 0, 0])
        }
    }

    func testParseWastModule() throws {
        var parser = WastParser(
            #"""
            (module
              ;; comment here
              (memory 1)

              (func $dummy)

              (func (export "empty")
                (unknown expr)
              )
            )
            """#, features: .default)

        while let directive = try parser.nextDirective() {
            switch directive {
            case .module(let directive):
                guard case .text(_) = directive.source else {
                    XCTFail("Expected text module field")
                    return
                }
            case _:
                XCTFail("Expected only module directive")
            }
        }
    }

    func testParseWastModuleSkip() throws {
        let directives = try parseWast(
            #"""
            (module
              ;; comment here
              (memory 1)

              (func $dummy)

              (func (export "empty")
                (unknown expr)
              )
            )
            (module binary "ok")
            """#)

        XCTAssertEqual(directives.count, 2)
        guard case let .module(directive) = try XCTUnwrap(directives.last),
            case let .binary(content) = directive.source
        else {
            return
        }
        XCTAssertEqual(content, Array("ok".utf8))
    }

    func testSpecForward() throws {
        let source = """
            (module
              (func $even (export "even") (param $n i32) (result i32)
                (if (result i32) (i32.eq (local.get $n) (i32.const 0))
                  (then (i32.const 1))
                  (else (call $odd (i32.sub (local.get $n) (i32.const 1))))
                )
              )

              (func $odd (export "odd") (param $n i32) (result i32)
                (if (result i32) (i32.eq (local.get $n) (i32.const 0))
                  (then (i32.const 0))
                  (else (call $even (i32.sub (local.get $n) (i32.const 1))))
                )
              )
            )

            (assert_return (invoke "even" (i32.const 13)) (i32.const 0))
            (assert_return (invoke "even" (i32.const 20)) (i32.const 1))
            (assert_return (invoke "odd" (i32.const 13)) (i32.const 1))
            (assert_return (invoke "odd" (i32.const 20)) (i32.const 0))
            """
        let wast = try parseWast(source)
        XCTAssertEqual(wast.count, 5)
        guard case let .module(module) = wast.first, case var .text(wat) = module.source else {
            XCTFail("expect a module directive")
            return
        }
        XCTAssertEqual(wat.functionsMap.count, 2)
        let even = wat.functionsMap[0]
        let (evenType, _) = try wat.types.resolve(use: even.typeUse)
        XCTAssertEqual(evenType.signature.parameters, [.i32])
        XCTAssertEqual(evenType.signature.results.first, .i32)
        XCTAssertEqual(evenType.parameterNames.map(\.?.value), ["$n"])
    }

    func testFuncIdBinding() throws {
        let source = """
            (module
              (table $t 10 funcref)
              (func $f)
              (func $g)

              ;; Passive
              (elem funcref)
              (elem funcref (ref.func $f) (item ref.func $f) (item (ref.null func)) (ref.func $g))
              (elem func)
              (elem func $f $f $g $g)

              (elem $p1 funcref)
              (elem $p2 funcref (ref.func $f) (ref.func $f) (ref.null func) (ref.func $g))
              (elem $p3 func)
              (elem $p4 func $f $f $g $g)

              ;; Active
              (elem (table $t) (i32.const 0) funcref)
              (elem (table $t) (i32.const 0) funcref (ref.func $f) (ref.null func))
              (elem (table $t) (i32.const 0) func)
              (elem (table $t) (i32.const 0) func $f $g)
              (elem (table $t) (offset (i32.const 0)) funcref)
              (elem (table $t) (offset (i32.const 0)) func $f $g)
            )
            """
        let wat = try parseWAT(source)
        XCTAssertEqual(wat.tables.count, 1)
        let table = wat.tables[0]
        XCTAssertEqual(table.type, TableType(elementType: .funcRef, limits: Limits(min: 10, max: nil)))
        XCTAssertEqual(wat.elementsMap.count, 14)
    }

    func testParseSpectest() throws {
        // NOTE: We do the same check as a part of the EncoderTests, so it's
        // usually redundant and time-wasting to run this test every time.
        // Keeping it here just for local unit testing purposes.
        try XCTSkipIf(
            ProcessInfo.processInfo.environment["WASMKIT_PARSER_SPECTEST"] != "1"
        )
        var failureCount = 0
        var totalCount = 0
        for filePath in Spectest.wastFiles(include: []) {
            print("Parsing \(filePath.path)...")
            totalCount += 1
            let source = try String(contentsOf: filePath)
            do {
                _ = try parseWast(source, features: Spectest.deriveFeatureSet(wast: filePath))
            } catch {
                failureCount += 1
                XCTFail("Failed to parse \(filePath.path):\(error)")
            }
        }

        if failureCount > 0 {
            XCTFail("Failed to parse \(failureCount) / \(totalCount) files")
        }
    }
}