File: PEGTests.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (308 lines) | stat: -rw-r--r-- 8,526 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
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//

import XCTest
@testable import Prototypes
import _RegexParser

// Make examples more sane. Need builder
typealias Pattern = PEG<Character>.Pattern

class PEGTests: XCTestCase {
}

class PEGStringTests: XCTestCase {
  typealias Pattern = PEG<Character>.Pattern

  let doPrint = false
  func show<S: CustomStringConvertible>(_ s: S) {
    if doPrint { print(s) }
  }

  func testComments() {
    /// Match C-style comments 
    ///
    ///     CComment -> '/*' (!'*/' <any>)* '*/'
    ///
    let notEnd = Pattern(.difference(.any, "*/"))
    let cComment = Pattern(
      "/*",
      .many(notEnd),
      "*/")
    show(cComment)
    let cProgram = PEG.Program(
      start: "CComment",
      environment: ["CComment": cComment])

    /// Match Swift style comments
    ///
    ///     SwiftComment -> '/*' SwiftBody '*/'
    ///     SwiftBody -> (SwiftComment | (!'*/' <any>))*
    ///
    let swiftComment = Pattern(
      "/*", .variable("SwiftBody"), "*/")
    let swiftBody = Pattern(
      .many(.orderedChoice(.variable("SwiftComment"), notEnd)))
    let swiftProgram = PEG.Program(
      start: "SwiftComment",
      environment: ["SwiftComment": swiftComment, "SwiftBody": swiftBody])
    
    // Test convention: special characters denote end of C, Swift, or both
    // comment styles.
    let tests: Array<String> = [
      "abc",
      "/**/🔚 xyz",
      "/* abc */🔚 xyz",
      "/* abc * / def */🔚 xyz",
      "/* abc /* def */🐚 def*/🕊 xyz",
    ]
    func expect(
      _ test: String, cEnd: String.Index?, swiftEnd: String.Index?
    ) {
      if let idx = test.firstIndex(of: "🔚") {
        XCTAssertEqual(idx, cEnd)
        XCTAssertEqual(idx, swiftEnd)
        return
      }
      XCTAssertEqual(test.firstIndex(of: "🐚"), cEnd)
      XCTAssertEqual(test.firstIndex(of: "🕊"), swiftEnd)
    }

    // Test PEG interpreter
    for test in tests {
      expect(
        test,
        cEnd: cProgram.consume(test),
        swiftEnd: swiftProgram.consume(test))
    }

    // Compile down to the PEG core and run that
    let cCode = PEG.VM<String>.compile(cProgram)
    let swiftCode = PEG.VM<String>.compile(swiftProgram)
    show(cCode)
    show(swiftCode)
    let cVM = PEG.VM.load(cCode)
    let swiftVM = PEG.VM.load(swiftCode)
    show(cVM)
    show(swiftVM)

    for test in tests {
      expect(
        test,
        cEnd: cVM.consume(test),
        swiftEnd: swiftVM.consume(test))
    }

    // Transpile to the matching engine and run that
    let cTranspiled = cVM.transpile()
    let swiftTranspiled = swiftVM.transpile()
    show(cTranspiled)
    show(swiftTranspiled)

    let cME = Engine<String>(cTranspiled)
    let swiftME = Engine<String>(swiftTranspiled)

    for test in tests {
      expect(
        test,
        cEnd: cME.consume(test),
        swiftEnd: swiftME.consume(test))
    }
  }

  // TODO: Simple parse examples
  /*

   `a + (b - c) * d` -> .product(.sum(a, .minus(b, c)), d)

   */

  func testEvenZeroesOnes() {
    // Even zeroes and even ones
    // This is a regular language, simple state machine,
    // but increadibly difficult to express with a
    // regular expression

    /*

     Even -> 0 OddZero | 1 OddOne
     OddZero -> 0 Even | 1 OddBoth
     OddOne -> 0 OddBoth | 1 Even
     OddBoth -> 0 OddOne | 1 OddZero

     */

    let even = Pattern.orderedChoice(
      Pattern("0", .variable("OddZero")),
      Pattern("1", .variable("OddOne")))
    let oddZero = Pattern.orderedChoice(
      Pattern("0", .variable("Even")),
      Pattern("1", .variable("OddBoth")))
    let oddOne = Pattern.orderedChoice(
      Pattern("0", .variable("OddBoth")),
      Pattern("1", .variable("Even")))
    let oddBoth = Pattern.orderedChoice(
      Pattern("0", .variable("OddOne")),
      Pattern("1", .variable("OddZero")))

    /*
     If you wanted to accept zero-length, you can modify the
     grammar:

     Start -> Even | success

     But that's all-or-nothing. Otherwise, you need to adjust
     the calls to "Even" to call start instead

     Similarly, you can match anywhere in the middle with
     something like:

     Start -> Evens | . Start

     But I don't think this is a great user experience, better
     to have APIs drive the right behavior through native Swift
     rather than require the user to modify a different
     matching language

     Note that backtracking is not strictly needed, as 
     alternatives are strictly exclusive. But, naive compilation
     will produce them, so this is an interesting example
     for byte code optimization

     */
    let start = Pattern(.orderedChoice(.variable("_Even"), .success))
    let env: PEG<Character>.Environment = [
      "Even": start,
      "_Even": even,
      "OddZero": oddZero,
      "OddOne": oddOne,
      "OddBoth": oddBoth,
    ]
    show(start)
    let pegProgram = PEG.Program(start: "Even", environment: env)

    let tests: Array<(String, Int)> = [
     // ("x00", 0),
      ("00", 2),
      ("11", 2),
      ("1100", 4),
      ("010100", 6),
      ("10100", 4),
      ("0101tail", 4),
    ]
    func expect(
      _ test: String, expected: Int, actual: String.Index?
    ) {
      guard let idx = actual else {
        XCTAssertEqual(expected, 0)
        return
      }
      XCTAssertEqual(
        expected,
        test.distance(from: test.startIndex, to: idx))
    }

    for (test, count) in tests {
      expect(
        test, expected: count, actual: pegProgram.consume(test))
    }

    // TODO: A more natural way to solve even zeros and even ones is to attach
    // a counter. This might be provided by a generalized pattern matching
    // facility or through custom user hooks like assertions and consumptions

    // Compilation
    let code = PEG.VM<String>.compile(
      PEG.Program(start: "Even", environment: env)
    )

    var vm = PEG.VM.load(code)
    vm.enableTracing = false
    show(vm)
    for (test, count) in tests {
      // TODO: This test doesn't work quite yet
      _ = (test, count)

      expect(test, expected: count, actual: vm.consume(test))
    }

    let engine = Engine<String>(vm.transpile())
    show(engine)
    for (test, count) in tests {
      // TODO: This test doesn't work quite yet
      _ = (test, count, engine)

      expect(test, expected: count, actual: engine.consume(test))
    }


  }

  func testHappensBefore() {
    enum Event: Comparable, Hashable {
      case auth, approve, use, other
    }
    typealias Pattern = PEG<Event>.Pattern

    return // TODO: happens before PEG equivalents
  }

  func testCamelCase() {
    let tests: Array<(String, Array<String>)> = [
      ("AB", ["AB"]),
      ("ABc", ["A", "Bc"]),
      ("ABcdE", ["A", "Bcd", "E"]),
      ("abc", ["abc"]),
      ("abcDEF", ["abc", "DEF"]),
      ("abcDEFgh", ["abc", "DE", "Fgh"]),
    ]
    _ = tests

    return // TODO: camel case examples
  }

  func testCharacterClasses() {
    func testClass(_ p: Pattern, _ c: Character) -> Bool {
      // Compilation
      let code = PEG.VM<String>.compile(PEG.Program(start: "S", environment: ["S": p]))
      var vm = PEG.VM.load(code)
      vm.enableTracing = false
      show(vm)

      let engine = Engine<String>(vm.transpile())
      show(engine)

      let s = String(c)

      let (vmResult, transpileResult) = (vm.consume(s), engine.consume(s))
      XCTAssertEqual(vmResult, transpileResult)
      return vmResult != nil
    }

    let hex = Pattern.charactetSet(\.isHexDigit)
    let newline = Pattern.charactetSet(\.isNewline)
    let letter = Pattern.charactetSet(\.isLetter)
    let ascii = Pattern.charactetSet(\.isASCII)

    let alphaHexadecimal = Pattern.orderedChoice(hex, letter)

    let tests = "7abCz 🧟‍♀️_e\u{301}_é\n.\r\n,"
    for char in tests {
      XCTAssertEqual(char.isHexDigit, testClass(hex, char))
      XCTAssertEqual(char.isNewline, testClass(newline, char))
      XCTAssertEqual(char.isLetter, testClass(letter, char))
      XCTAssertEqual(char.isASCII, testClass(ascii, char))
      XCTAssertEqual(char.isHexDigit || char.isLetter, testClass(alphaHexadecimal, char))
    }
  }


}