├── .gitignore ├── 01 └── TryRegex │ ├── .swiftpm │ └── xcode │ │ └── package.xcworkspace │ │ └── contents.xcworkspacedata │ ├── Package.swift │ ├── Sources │ ├── RegexParser │ │ └── Regex │ │ │ ├── AST │ │ │ ├── AST.swift │ │ │ ├── Atom.swift │ │ │ ├── Group.swift │ │ │ └── Quantification.swift │ │ │ └── Parse │ │ │ ├── LexicalAnalysis.swift │ │ │ ├── Parse.swift │ │ │ └── Source.swift │ └── StringProcessing │ │ ├── ByteCodeGen.swift │ │ ├── Compiler.swift │ │ ├── Engine │ │ ├── Backtracking.swift │ │ ├── InstPayload.swift │ │ ├── Instruction.swift │ │ ├── MEBuilder.swift │ │ ├── MEBuiltins.swift │ │ ├── MEProgram.swift │ │ ├── Processor.swift │ │ └── Registers.swift │ │ ├── Executor.swift │ │ └── Regex │ │ ├── ASTConversion.swift │ │ ├── Core.swift │ │ ├── DSLTree.swift │ │ └── Match.swift │ └── Tests │ └── RegexTests │ ├── MatchTests.swift │ └── PerformanceTests.swift ├── 02 └── TryRegex │ ├── .swiftpm │ └── xcode │ │ └── package.xcworkspace │ │ └── contents.xcworkspacedata │ ├── Package.swift │ ├── Sources │ ├── RegexParser │ │ └── Regex │ │ │ ├── AST │ │ │ ├── AST.swift │ │ │ ├── Atom.swift │ │ │ ├── Group.swift │ │ │ └── Quantification.swift │ │ │ └── Parse │ │ │ ├── LexicalAnalysis.swift │ │ │ ├── Parse.swift │ │ │ └── Source.swift │ └── StringProcessing │ │ ├── ByteCodeGen.swift │ │ ├── Compiler.swift │ │ ├── Engine │ │ ├── Backtracking.swift │ │ ├── InstPayload.swift │ │ ├── Instruction.swift │ │ ├── MEBuilder.swift │ │ ├── MEBuiltins.swift │ │ ├── MEProgram.swift │ │ ├── Processor.swift │ │ └── Registers.swift │ │ ├── Executor.swift │ │ └── Regex │ │ ├── ASTConversion.swift │ │ ├── Core.swift │ │ ├── DSLTree.swift │ │ └── Match.swift │ └── Tests │ └── RegexTests │ ├── MatchTests.swift │ └── PerformanceTests.swift ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ### Generated by gibo (https://github.com/simonwhitaker/gibo) 2 | ### https://raw.github.com/github/gitignore/76e40b7cecb059211e360822247bf0b6e585d1eb/Global/macOS.gitignore 3 | 4 | # General 5 | .DS_Store 6 | .AppleDouble 7 | .LSOverride 8 | 9 | # Icon must end with two \r 10 | Icon 11 | 12 | # Thumbnails 13 | ._* 14 | 15 | # Files that might appear in the root of a volume 16 | .DocumentRevisions-V100 17 | .fseventsd 18 | .Spotlight-V100 19 | .TemporaryItems 20 | .Trashes 21 | .VolumeIcon.icns 22 | .com.apple.timemachine.donotpresent 23 | 24 | # Directories potentially created on remote AFP share 25 | .AppleDB 26 | .AppleDesktop 27 | Network Trash Folder 28 | Temporary Items 29 | .apdisk 30 | ### Generated by gibo (https://github.com/simonwhitaker/gibo) 31 | ### https://raw.github.com/github/gitignore/76e40b7cecb059211e360822247bf0b6e585d1eb/Swift.gitignore 32 | 33 | # Xcode 34 | # 35 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 36 | 37 | ## User settings 38 | xcuserdata/ 39 | 40 | ## Obj-C/Swift specific 41 | *.hmap 42 | 43 | ## App packaging 44 | *.ipa 45 | *.dSYM.zip 46 | *.dSYM 47 | 48 | ## Playgrounds 49 | timeline.xctimeline 50 | playground.xcworkspace 51 | 52 | # Swift Package Manager 53 | # 54 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 55 | # Packages/ 56 | # Package.pins 57 | # Package.resolved 58 | # *.xcodeproj 59 | # 60 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 61 | # hence it is not needed unless you have added a package configuration file to your project 62 | # .swiftpm 63 | 64 | .build/ 65 | 66 | # CocoaPods 67 | # 68 | # We recommend against adding the Pods directory to your .gitignore. However 69 | # you should judge for yourself, the pros and cons are mentioned at: 70 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 71 | # 72 | # Pods/ 73 | # 74 | # Add this line if you want to avoid checking in source code from the Xcode workspace 75 | # *.xcworkspace 76 | 77 | # Carthage 78 | # 79 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 80 | # Carthage/Checkouts 81 | 82 | Carthage/Build/ 83 | 84 | # fastlane 85 | # 86 | # It is recommended to not store the screenshots in the git repo. 87 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 88 | # For more information about the recommended setup visit: 89 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 90 | 91 | fastlane/report.xml 92 | fastlane/Preview.html 93 | fastlane/screenshots/**/*.png 94 | fastlane/test_output 95 | -------------------------------------------------------------------------------- /01/TryRegex/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /01/TryRegex/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.5 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "TryRegex", 8 | products: [ 9 | .library( 10 | name: "StringProcessing", 11 | targets: ["StringProcessing"] 12 | ), 13 | .library( 14 | name: "RegexParser", 15 | targets: ["RegexParser"] 16 | ), 17 | ], 18 | targets: [ 19 | .target( 20 | name: "RegexParser", 21 | dependencies: [] 22 | ), 23 | .target( 24 | name: "StringProcessing", 25 | dependencies: [ 26 | "RegexParser", 27 | ] 28 | ), 29 | .testTarget( 30 | name: "RegexTests", 31 | dependencies: [ 32 | "StringProcessing", 33 | ] 34 | ), 35 | ] 36 | ) 37 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/RegexParser/Regex/AST/AST.swift: -------------------------------------------------------------------------------- 1 | public struct AST { 2 | public var root: AST.Node 3 | 4 | public init(_ root: AST.Node) { 5 | self.root = root 6 | } 7 | } 8 | 9 | extension AST { 10 | public indirect enum Node { 11 | case alternation(Alternation) 12 | case concatenation(Concatenation) 13 | case group(Group) 14 | case quantification(Quantification) 15 | case atom(Atom) 16 | case empty(Empty) 17 | } 18 | } 19 | 20 | extension AST { 21 | public struct Alternation { 22 | public let children: [AST.Node] 23 | 24 | public init(_ mems: [AST.Node]) { 25 | self.children = mems 26 | } 27 | } 28 | 29 | public struct Concatenation { 30 | public let children: [AST.Node] 31 | 32 | public init(_ mems: [AST.Node]) { 33 | self.children = mems 34 | } 35 | } 36 | 37 | public struct Empty {} 38 | } 39 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/RegexParser/Regex/AST/Atom.swift: -------------------------------------------------------------------------------- 1 | extension AST { 2 | public struct Atom { 3 | public let kind: Kind 4 | 5 | public init(_ k: Kind) { 6 | self.kind = k 7 | } 8 | 9 | public enum Kind { 10 | case char(Character) 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/RegexParser/Regex/AST/Group.swift: -------------------------------------------------------------------------------- 1 | extension AST { 2 | public struct Group { 3 | public let kind: Kind 4 | public let child: AST.Node 5 | 6 | public init(_ kind: Kind, _ child: AST.Node) { 7 | self.kind = kind 8 | self.child = child 9 | } 10 | 11 | public enum Kind { 12 | case capture 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/RegexParser/Regex/AST/Quantification.swift: -------------------------------------------------------------------------------- 1 | extension AST { 2 | public struct Quantification { 3 | public let amount: Amount 4 | public let child: AST.Node 5 | 6 | public init(_ amount: Amount, _ child: AST.Node) { 7 | self.amount = amount 8 | self.child = child 9 | } 10 | 11 | public enum Amount: Hashable { 12 | case zeroOrMore // * 13 | } 14 | } 15 | } 16 | 17 | extension AST.Quantification.Amount { 18 | public var bounds: (atLeast: Int?, atMost: Int?) { 19 | switch self { 20 | case .zeroOrMore: return (0, nil) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/RegexParser/Regex/Parse/LexicalAnalysis.swift: -------------------------------------------------------------------------------- 1 | extension Parser { 2 | typealias Char = Source.Char 3 | } 4 | 5 | extension Parser { 6 | mutating func tryEating( 7 | _ body: (inout Self) -> T? 8 | ) -> T? { 9 | guard let result = body(&self) else { 10 | return nil 11 | } 12 | return result 13 | } 14 | } 15 | 16 | extension Parser { 17 | typealias Quant = AST.Quantification 18 | 19 | @discardableResult 20 | mutating func expect(_ c: Character) -> Bool { 21 | guard tryEat(c) else { 22 | return false 23 | } 24 | return true 25 | } 26 | 27 | func peek() -> Char? { src.peek() } 28 | 29 | mutating func advance(_ n: Int = 1) { 30 | guard src.tryAdvance(n) else { 31 | fatalError("Advancing beyond end!") 32 | } 33 | } 34 | 35 | mutating func tryEat() -> Char? { 36 | guard let char = peek() else { return nil } 37 | advance() 38 | return char 39 | } 40 | 41 | mutating func tryEat(_ c: Char) -> Bool { 42 | guard peek() == c else { return false } 43 | advance() 44 | return true 45 | } 46 | } 47 | 48 | extension Parser { 49 | mutating func lexQuantifier() -> Quant.Amount? { 50 | tryEating { p in 51 | let amt: Quant.Amount? = { 52 | if p.tryEat("*") { return .zeroOrMore } 53 | return nil 54 | }() 55 | guard let amt = amt else { return nil } 56 | 57 | return amt 58 | } 59 | } 60 | 61 | mutating func lexGroupStart() -> AST.Group.Kind? { 62 | tryEating { p in 63 | guard p.tryEat("(") else { return nil } 64 | return .capture 65 | } 66 | } 67 | 68 | mutating func lexAtom() -> AST.Atom? { 69 | if src.isEmpty { return nil } 70 | if (peek() == ")" || peek() == "|") { return nil } 71 | 72 | guard let char = tryEat() else { 73 | fatalError("Unexpected end of input") 74 | } 75 | 76 | return AST.Atom(.char(char)) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/RegexParser/Regex/Parse/Parse.swift: -------------------------------------------------------------------------------- 1 | struct Parser { 2 | var src: Source 3 | 4 | init(_ src: Source) { 5 | self.src = src 6 | } 7 | } 8 | 9 | extension Parser { 10 | mutating func parse() -> AST { 11 | let ast = parseNode() 12 | 13 | if !src.isEmpty { 14 | if tryEat(")") { 15 | fatalError("closing ')' does not balance any groups openings") 16 | } else { 17 | fatalError("Unhandled termination condition") 18 | } 19 | } 20 | 21 | return .init(ast) 22 | } 23 | 24 | mutating func parseNode() -> AST.Node { 25 | if src.isEmpty { 26 | return .empty(.init()) 27 | } 28 | 29 | var result = [parseConcatenation()] 30 | while true { 31 | guard tryEat("|") else { break } 32 | result.append(parseConcatenation()) 33 | } 34 | 35 | if result.count == 1 { 36 | return result[0] 37 | } 38 | 39 | return .alternation(.init(result)) 40 | } 41 | 42 | mutating func parseConcatenation() -> AST.Node { 43 | var result = [AST.Node]() 44 | 45 | while true { 46 | if src.isEmpty { 47 | break 48 | } 49 | if peek() == "|" || peek() == ")" { 50 | break 51 | } 52 | 53 | if let operand = parseQuantifierOperand() { 54 | if let amt = lexQuantifier() { 55 | result.append( 56 | .quantification(.init(amt, operand)) 57 | ) 58 | } else { 59 | result.append(operand) 60 | } 61 | continue 62 | } 63 | 64 | fatalError("Should have parsed at least an atom") 65 | break 66 | } 67 | guard !result.isEmpty else { 68 | return .empty(.init()) 69 | } 70 | if result.count == 1 { 71 | return result[0] 72 | } 73 | 74 | return .concatenation(.init(result)) 75 | } 76 | 77 | mutating func parseGroupBody( 78 | _ kind: AST.Group.Kind 79 | ) -> AST.Group { 80 | let child = parseNode() 81 | expect(")") 82 | return .init(kind, child) 83 | } 84 | 85 | mutating func parseQuantifierOperand() -> AST.Node? { 86 | if let kind = lexGroupStart() { 87 | return .group(parseGroupBody(kind)) 88 | } 89 | 90 | if let atom = lexAtom() { 91 | return .atom(atom) 92 | } 93 | 94 | return nil 95 | } 96 | } 97 | 98 | public func parse(_ regex: S) -> AST where S.SubSequence == Substring { 99 | let source = Source(String(regex)) 100 | var parser = Parser(source) 101 | return parser.parse() 102 | } 103 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/RegexParser/Regex/Parse/Source.swift: -------------------------------------------------------------------------------- 1 | public struct Source { 2 | var input: Input 3 | var bounds: Range 4 | 5 | init(_ str: Input) { 6 | self.input = str 7 | self.bounds = str.startIndex.. Char? { _slice.first } 22 | 23 | @discardableResult 24 | mutating func tryAdvance(_ n: Int = 1) -> Bool { 25 | guard n > 0, let newLower = _slice.index( 26 | bounds.lowerBound, offsetBy: n, limitedBy: bounds.upperBound 27 | ) 28 | else { 29 | return false 30 | } 31 | self.bounds = newLower.. MEProgram { 11 | try emitNode(root) 12 | builder.buildAccept() 13 | 14 | return try builder.assemble() 15 | } 16 | } 17 | 18 | fileprivate extension Compiler.ByteCodeGen { 19 | mutating func emitAtom(_ a: DSLTree.Atom) throws { 20 | switch a { 21 | case let .char(c): 22 | emitCharacter(c) 23 | } 24 | } 25 | 26 | mutating func emitCharacter(_ c: Character) { 27 | builder.buildMatch(c) 28 | } 29 | 30 | mutating func emitAlternationGen( 31 | _ elements: C, 32 | withBacktracking: Bool, 33 | _ body: (inout Compiler.ByteCodeGen, C.Element) throws -> Void 34 | ) rethrows { 35 | let done = builder.makeAddress() 36 | for element in elements.dropLast() { 37 | let next = builder.makeAddress() 38 | builder.buildSave(next) 39 | try body(&self, element) 40 | builder.buildBranch(to: done) 41 | builder.label(next) 42 | } 43 | try body(&self, elements.last!) 44 | builder.label(done) 45 | } 46 | 47 | mutating func emitAlternation( 48 | _ children: [DSLTree.Node] 49 | ) throws { 50 | try emitAlternationGen(children, withBacktracking: true) { 51 | try $0.emitNode($1) 52 | } 53 | } 54 | 55 | mutating func emitConcatenationComponent( 56 | _ node: DSLTree.Node 57 | ) throws { 58 | try emitNode(node) 59 | } 60 | 61 | mutating func emitQuantification( 62 | _ amount: AST.Quantification.Amount, 63 | _ child: DSLTree.Node 64 | ) throws { 65 | let (low, _) = amount.bounds 66 | guard let low = low else { 67 | fatalError("Must have a lower bound") 68 | } 69 | 70 | let minTrips = low 71 | 72 | let minTripsControl = builder.makeAddress() 73 | let loopBody = builder.makeAddress() 74 | let exitPolicy = builder.makeAddress() 75 | let exit = builder.makeAddress() 76 | 77 | builder.label(minTripsControl) 78 | switch minTrips { 79 | case 0: builder.buildBranch(to: exitPolicy) 80 | default: break 81 | } 82 | 83 | builder.label(loopBody) 84 | try emitNode(child) 85 | 86 | builder.label(exitPolicy) 87 | 88 | builder.buildSplit(to: loopBody, saving: exit) 89 | builder.label(exit) 90 | } 91 | 92 | mutating func emitConcatenation(_ children: [DSLTree.Node]) throws { 93 | for child in children { 94 | try emitConcatenationComponent(child) 95 | } 96 | } 97 | 98 | mutating func emitNode(_ node: DSLTree.Node) throws { 99 | switch node { 100 | case let .orderedChoice(children): 101 | try emitAlternation(children) 102 | 103 | case let .concatenation(children): 104 | try emitConcatenation(children) 105 | 106 | case .capture(let child): 107 | try emitNode(child) 108 | 109 | case let .quantification(amt, child): 110 | try emitQuantification(amt.ast, child) 111 | 112 | case let .atom(a): 113 | try emitAtom(a) 114 | 115 | case .empty: 116 | return 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Compiler.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | class Compiler { 4 | let tree: DSLTree 5 | 6 | init(ast: AST) { 7 | self.tree = ast.dslTree 8 | } 9 | 10 | init(tree: DSLTree) { 11 | self.tree = tree 12 | } 13 | 14 | __consuming func emit() throws -> MEProgram { 15 | var codegen = ByteCodeGen() 16 | return try codegen.emitRoot(tree.root) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Engine/Backtracking.swift: -------------------------------------------------------------------------------- 1 | extension Processor { 2 | struct SavePoint { 3 | var pc: InstructionAddress 4 | var pos: Position? 5 | 6 | var destructure: ( 7 | pc: InstructionAddress, 8 | pos: Position? 9 | ) { 10 | return (pc, pos) 11 | } 12 | } 13 | 14 | func makeSavePoint( 15 | resumingAt pc: InstructionAddress 16 | ) -> SavePoint { 17 | SavePoint( 18 | pc: pc, 19 | pos: currentPosition 20 | ) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Engine/InstPayload.swift: -------------------------------------------------------------------------------- 1 | extension Instruction { 2 | enum Payload { 3 | case none 4 | case int(Int) 5 | case element(Character) 6 | case addr(InstructionAddress) 7 | case pairedImmediateInt(UInt64, Int) 8 | case pairedAddrInt(InstructionAddress, Int) 9 | case pairedAddrAddr(InstructionAddress, InstructionAddress) 10 | } 11 | } 12 | 13 | extension Instruction.Payload { 14 | init(int: Int) { 15 | self = .int(int) 16 | } 17 | var int: Int { 18 | guard case .int(let value) = self else { 19 | fatalError("Payload is not an operand.") 20 | } 21 | return value 22 | } 23 | 24 | init(element: Character) { 25 | self = .element(element) 26 | } 27 | var elementPayload: Character { 28 | guard case .element(let element) = self else { 29 | fatalError("Payload is not an operand.") 30 | } 31 | return element 32 | } 33 | 34 | init(addr: InstructionAddress) { 35 | self = .addr(addr) 36 | } 37 | var addr: InstructionAddress { 38 | guard case .addr(let addr) = self else { 39 | fatalError("Payload is not an address.") 40 | } 41 | return addr 42 | } 43 | 44 | init(immediate: UInt64, int: IntRegister) { 45 | self = .pairedImmediateInt(immediate, int) 46 | } 47 | var pairedImmediateInt: (UInt64, IntRegister) { 48 | guard case .pairedImmediateInt(let i, let r) = self else { 49 | fatalError("Payload is not an address pair.") 50 | } 51 | return (i, r) 52 | } 53 | 54 | init(addr: InstructionAddress, int: Int) { 55 | self = .pairedAddrInt(addr, int) 56 | } 57 | var pairedAddrInt: (InstructionAddress, Int) { 58 | guard case .pairedAddrInt(let addr, let i) = self else { 59 | fatalError("Payload is not an address pair.") 60 | } 61 | return (addr, i) 62 | } 63 | 64 | init(addr: InstructionAddress, addr2: InstructionAddress) { 65 | self = .pairedAddrAddr(addr, addr2) 66 | } 67 | var pairedAddrAddr: (InstructionAddress, InstructionAddress) { 68 | guard case .pairedAddrAddr(let a1, let a2) = self else { 69 | fatalError("Payload is not an address pair.") 70 | } 71 | return (a1, a2) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Engine/Instruction.swift: -------------------------------------------------------------------------------- 1 | struct Instruction { 2 | let opcode: Instruction.OpCode 3 | let payload: Instruction.Payload 4 | 5 | init(_ opcode: Instruction.OpCode) { 6 | self.init(opcode, .none) 7 | } 8 | 9 | init(_ opcode: Instruction.OpCode, _ payload: Instruction.Payload) { 10 | self.opcode = opcode 11 | self.payload = payload 12 | } 13 | } 14 | 15 | extension Instruction { 16 | enum OpCode: UInt64 { 17 | case invalid = 0 18 | 19 | case branch 20 | 21 | case match 22 | 23 | case save 24 | 25 | case splitSaving 26 | 27 | case accept 28 | } 29 | } 30 | 31 | extension Instruction { 32 | var destructure: (opcode: OpCode, payload: Payload) { 33 | get { (opcode, payload) } 34 | set { self = Self(opcode, payload) } 35 | } 36 | } 37 | 38 | enum State { 39 | case inProgress 40 | case fail 41 | case accept 42 | } 43 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Engine/MEBuilder.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser // For errors 2 | 3 | typealias InstructionAddress = Int 4 | 5 | extension MEProgram { 6 | struct Builder { 7 | var instructions: [Instruction] = [] 8 | 9 | var elements = Array() 10 | 11 | var addressTokens: [InstructionAddress?] = [] 12 | var addressFixups: [(InstructionAddress, AddressFixup)] = [] 13 | 14 | var nextIntRegister = IntRegister(0) 15 | } 16 | } 17 | 18 | extension MEProgram.Builder { 19 | struct AddressFixup { 20 | var first: AddressToken 21 | var second: AddressToken? = nil 22 | 23 | init(_ a: AddressToken) { self.first = a } 24 | init(_ a: AddressToken, _ b: AddressToken) { 25 | self.first = a 26 | self.second = b 27 | } 28 | } 29 | } 30 | 31 | extension MEProgram.Builder { 32 | mutating func buildBranch(to t: AddressToken) { 33 | instructions.append(.init(.branch)) 34 | fixup(to: t) 35 | } 36 | 37 | mutating func buildSave(_ t: AddressToken) { 38 | instructions.append(.init(.save)) 39 | fixup(to: t) 40 | } 41 | 42 | mutating func buildSplit( 43 | to: AddressToken, saving: AddressToken 44 | ) { 45 | instructions.append(.init(.splitSaving)) 46 | fixup(to: (to, saving)) 47 | } 48 | 49 | mutating func buildMatch(_ e: Character) { 50 | instructions.append(.init(.match, .init(element: e))) 51 | } 52 | 53 | mutating func buildAccept() { 54 | instructions.append(.init(.accept)) 55 | } 56 | 57 | mutating func assemble() throws -> MEProgram { 58 | var instructions = instructions 59 | for (instAddr, tok) in addressFixups { 60 | let inst = instructions[instAddr] 61 | let addr = addressTokens[tok.first]! 62 | let payload: Instruction.Payload 63 | 64 | switch inst.opcode { 65 | case .branch, .save: 66 | payload = .init(addr: addr) 67 | case .splitSaving: 68 | guard let fix2 = tok.second else { 69 | fatalError() 70 | } 71 | let saving = addressTokens[fix2]! 72 | payload = .init(addr: addr, addr2: saving) 73 | default: 74 | fatalError() 75 | } 76 | 77 | instructions[instAddr] = .init(inst.opcode, payload) 78 | } 79 | 80 | let regs = Processor.Registers( 81 | numInts: nextIntRegister 82 | ) 83 | 84 | let program = MEProgram( 85 | instructions: instructions, 86 | registers: regs 87 | ) 88 | return program 89 | } 90 | } 91 | 92 | extension MEProgram.Builder { 93 | enum _AddressToken {} 94 | typealias AddressToken = Int 95 | 96 | mutating func makeAddress() -> AddressToken { 97 | defer { addressTokens.append(nil) } 98 | return AddressToken(addressTokens.count) 99 | } 100 | 101 | mutating func label(_ t: AddressToken) { 102 | addressTokens[t] = InstructionAddress(instructions.count) 103 | } 104 | 105 | mutating func fixup(to t: AddressToken) { 106 | assert(!instructions.isEmpty) 107 | addressFixups.append( 108 | (InstructionAddress(instructions.endIndex - 1), .init(t))) 109 | } 110 | 111 | mutating func fixup(to ts: (AddressToken, AddressToken)) { 112 | assert(!instructions.isEmpty) 113 | addressFixups.append(( 114 | InstructionAddress(instructions.endIndex - 1), 115 | .init(ts.0, ts.1))) 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Engine/MEBuiltins.swift: -------------------------------------------------------------------------------- 1 | extension String { 2 | func characterAndEnd( 3 | at pos: String.Index, limitedBy end: String.Index 4 | ) -> (Character, String.Index)? { 5 | guard pos < end else { return nil } 6 | let next = index(after: pos) 7 | if next <= end { 8 | return (self[pos], next) 9 | } 10 | 11 | let substr = self[pos.. 17 | let instructions: [Instruction] 18 | 19 | var searchBounds: Range 20 | var currentPosition: Position 21 | var controller: Controller 22 | var registers: Registers 23 | var savePoints: [SavePoint] = [] 24 | var state: State = .inProgress 25 | } 26 | 27 | extension Processor { 28 | typealias Position = Input.Index 29 | 30 | var start: Position { searchBounds.lowerBound } 31 | var end: Position { searchBounds.upperBound } 32 | } 33 | 34 | extension Processor { 35 | init( 36 | program: MEProgram, 37 | input: Input, 38 | subjectBounds: Range, 39 | searchBounds: Range 40 | ) { 41 | self.controller = Controller(pc: 0) 42 | self.instructions = program.instructions 43 | self.input = input 44 | self.subjectBounds = subjectBounds 45 | self.searchBounds = searchBounds 46 | 47 | self.currentPosition = searchBounds.lowerBound 48 | 49 | self.registers = program.registers 50 | } 51 | 52 | mutating func reset( 53 | currentPosition: Position, 54 | searchBounds: Range 55 | ) { 56 | self.currentPosition = currentPosition 57 | self.searchBounds = searchBounds 58 | 59 | self.controller = Controller(pc: 0) 60 | 61 | if !self.savePoints.isEmpty { 62 | self.savePoints.removeAll(keepingCapacity: true) 63 | } 64 | 65 | self.state = .inProgress 66 | } 67 | } 68 | 69 | extension Processor { 70 | func fetch() -> (Instruction.OpCode, Instruction.Payload) { 71 | instructions[controller.pc].destructure 72 | } 73 | 74 | mutating func match(_ e: Element) -> Bool { 75 | guard let next = input.match( 76 | e, 77 | at: currentPosition, 78 | limitedBy: end 79 | ) else { 80 | signalFailure() 81 | return false 82 | } 83 | 84 | currentPosition = next 85 | return true 86 | } 87 | 88 | mutating func signalFailure(preservingCaptures: Bool = false) { 89 | guard !savePoints.isEmpty else { 90 | state = .fail 91 | return 92 | } 93 | 94 | let (pc, pos) = savePoints.removeLast().destructure 95 | 96 | controller.pc = pc 97 | currentPosition = pos ?? currentPosition 98 | } 99 | 100 | mutating func tryAccept() { 101 | state = .accept 102 | } 103 | 104 | mutating func cycle() { 105 | let (opcode, payload) = fetch() 106 | switch opcode { 107 | case .invalid: 108 | fatalError("Invalid program") 109 | 110 | case .branch: 111 | controller.pc = payload.addr 112 | 113 | case .save: 114 | let resumeAddr = payload.addr 115 | let sp = makeSavePoint(resumingAt: resumeAddr) 116 | savePoints.append(sp) 117 | controller.step() 118 | 119 | case .splitSaving: 120 | let (nextPC, resumeAddr) = payload.pairedAddrAddr 121 | let sp = makeSavePoint(resumingAt: resumeAddr) 122 | savePoints.append(sp) 123 | controller.pc = nextPC 124 | 125 | case .accept: 126 | tryAccept() 127 | 128 | case .match: 129 | let element = payload.elementPayload 130 | if match(element) { 131 | controller.step() 132 | } 133 | } 134 | } 135 | } 136 | 137 | extension String { 138 | func match( 139 | _ char: Character, 140 | at pos: Index, 141 | limitedBy end: String.Index 142 | ) -> Index? { 143 | guard let (stringChar, next) = characterAndEnd(at: pos, limitedBy: end) else { return nil } 144 | guard stringChar == char else { return nil } 145 | 146 | return next 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Engine/Registers.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | typealias IntRegister = Int 4 | 5 | extension Processor { 6 | struct Registers { 7 | var isDirty = false 8 | var ints: [Int] 9 | 10 | init( 11 | isDirty: Bool = false, 12 | numInts: Int 13 | ) { 14 | self.isDirty = isDirty 15 | self.ints = Array(repeating: 0, count: numInts) 16 | } 17 | } 18 | } 19 | 20 | extension Processor.Registers { 21 | typealias Input = String 22 | 23 | subscript(_ i: IntRegister) -> Int { 24 | get { ints[i] } 25 | set { 26 | isDirty = true 27 | ints[i] = newValue 28 | } 29 | } 30 | } 31 | 32 | extension Processor.Registers { 33 | mutating func reset() { 34 | guard isDirty else { 35 | return 36 | } 37 | self.ints._setAll(to: 0) 38 | } 39 | } 40 | 41 | extension MutableCollection { 42 | mutating func _setAll(to e: Element) { 43 | for idx in self.indices { 44 | self[idx] = e 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Executor.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | enum Executor { 4 | static func firstMatch( 5 | _ program: MEProgram, 6 | _ input: String, 7 | subjectBounds: Range, 8 | searchBounds: Range 9 | ) throws -> Regex.Match? { 10 | var cpu = Processor( 11 | program: program, 12 | input: input, 13 | subjectBounds: subjectBounds, 14 | searchBounds: searchBounds 15 | ) 16 | return try Executor._firstMatch( 17 | program, 18 | using: &cpu 19 | ) 20 | } 21 | 22 | static func _firstMatch( 23 | _ program: MEProgram, 24 | using cpu: inout Processor 25 | ) throws -> Regex.Match? { 26 | var low = cpu.searchBounds.lowerBound 27 | let high = cpu.searchBounds.upperBound 28 | while true { 29 | if let m = try Executor._run(program, &cpu) { 30 | return m 31 | } 32 | 33 | if low == high { 34 | return nil 35 | } 36 | 37 | cpu.input.unicodeScalars.formIndex(after: &low) 38 | 39 | guard low <= high else { 40 | return nil 41 | } 42 | 43 | cpu.reset(currentPosition: low, searchBounds: cpu.searchBounds) 44 | } 45 | } 46 | } 47 | 48 | extension Executor { 49 | static func _run( 50 | _ program: MEProgram, 51 | _ input: String, 52 | subjectBounds: Range, 53 | searchBounds: Range 54 | ) throws -> Regex.Match? { 55 | var cpu = Processor( 56 | program: program, 57 | input: input, 58 | subjectBounds: subjectBounds, 59 | searchBounds: searchBounds 60 | ) 61 | return try _run(program, &cpu) 62 | } 63 | 64 | static func _run( 65 | _ program: MEProgram, 66 | _ cpu: inout Processor 67 | ) throws -> Regex.Match? { 68 | let startPosition = cpu.currentPosition 69 | guard let endIdx = try cpu.run() else { 70 | return nil 71 | } 72 | 73 | let range = startPosition.. Input.Index? { 80 | if self.state == .fail { 81 | return nil 82 | } 83 | 84 | while true { 85 | switch self.state { 86 | case .accept: 87 | return self.currentPosition 88 | case .fail: 89 | return nil 90 | case .inProgress: 91 | self.cycle() 92 | } 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Regex/ASTConversion.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | extension AST { 4 | var dslTree: DSLTree { 5 | return DSLTree(root.dslTreeNode) 6 | } 7 | } 8 | 9 | extension AST.Node { 10 | var dslTreeNode: DSLTree.Node { 11 | func convert() throws -> DSLTree.Node { 12 | switch self { 13 | case let .alternation(v): 14 | let children = v.children.map(\.dslTreeNode) 15 | return .orderedChoice(children) 16 | 17 | case let .concatenation(v): 18 | return .concatenation(v.children.map(\.dslTreeNode)) 19 | 20 | case let .group(v): 21 | let child = v.child.dslTreeNode 22 | switch v.kind { 23 | case .capture: 24 | return .capture(child) 25 | } 26 | case let .quantification(v): 27 | let child = v.child.dslTreeNode 28 | return .quantification( 29 | .init(ast: v.amount), child) 30 | 31 | case let .atom(v): 32 | switch v.kind { 33 | default: 34 | return .atom(v.dslTreeAtom) 35 | } 36 | 37 | case .empty(_): 38 | return .empty 39 | } 40 | } 41 | 42 | let converted = try! convert() 43 | return converted 44 | } 45 | } 46 | 47 | extension AST.Atom { 48 | var dslTreeAtom: DSLTree.Atom { 49 | switch self.kind { 50 | case let .char(c): return .char(c) 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Regex/Core.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | public struct Regex { 4 | let program: Program 5 | 6 | init(ast: AST) { 7 | self.program = Program(ast: ast) 8 | } 9 | init(ast: AST.Node) { 10 | self.program = Program( 11 | ast: .init(ast) 12 | ) 13 | } 14 | 15 | @usableFromInline 16 | init(_regexString pattern: String) { 17 | self.init(ast: parse(pattern)) 18 | } 19 | } 20 | 21 | extension Regex { 22 | internal final class Program { 23 | let tree: DSLTree 24 | 25 | var loweredProgram: MEProgram { 26 | let compiledProgram = try! Compiler(tree: tree).emit() 27 | return compiledProgram 28 | } 29 | 30 | init(ast: AST) { 31 | self.tree = ast.dslTree 32 | } 33 | 34 | init(tree: DSLTree) { 35 | self.tree = tree 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Regex/DSLTree.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | public struct DSLTree { 4 | var root: Node 5 | 6 | init(_ r: Node) { 7 | self.root = r 8 | } 9 | } 10 | 11 | extension DSLTree { 12 | indirect enum Node { 13 | case orderedChoice([Node]) 14 | 15 | case concatenation([Node]) 16 | 17 | case capture(Node) 18 | 19 | case quantification( 20 | _AST.QuantificationAmount, 21 | Node 22 | ) 23 | 24 | case atom(Atom) 25 | 26 | case empty 27 | } 28 | } 29 | 30 | extension DSLTree { 31 | public enum Atom { 32 | case char(Character) 33 | } 34 | } 35 | 36 | extension DSLTree { 37 | public enum _AST { 38 | public struct QuantificationAmount { 39 | internal var ast: AST.Quantification.Amount 40 | 41 | public static var zeroOrMore: Self { 42 | .init(ast: .zeroOrMore) 43 | } 44 | } 45 | 46 | public struct ASTNode { 47 | internal var ast: AST.Node 48 | } 49 | 50 | public struct Atom { 51 | internal var ast: AST.Atom 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /01/TryRegex/Sources/StringProcessing/Regex/Match.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | extension Regex { 4 | public struct Match { 5 | public let range: Range 6 | } 7 | } 8 | 9 | extension Regex { 10 | public func firstMatch(in string: String) throws -> Regex.Match? { 11 | let bounds = string.startIndex..(_regexString: pattern) 14 | let result = try regex.firstMatch(in: input) 15 | 16 | let match = try #require(result) 17 | 18 | #expect(match.range == range) 19 | #expect(input[match.range] == "a") 20 | } 21 | 22 | @Test func testMatch02() throws { 23 | let pattern = "a" 24 | let input = "ccab" 25 | 26 | let start = input.index(input.startIndex, offsetBy: 2) 27 | let end = input.index(input.startIndex, offsetBy: 3) 28 | let range = start..(_regexString: pattern) 31 | let result = try regex.firstMatch(in: input) 32 | 33 | let match = try #require(result) 34 | 35 | #expect(match.range == range) 36 | #expect(input[match.range] == "a") 37 | } 38 | 39 | @Test func testMatch03() throws { 40 | let pattern = "ab" 41 | let input = "ccab" 42 | 43 | let start = input.index(input.startIndex, offsetBy: 2) 44 | let end = input.index(input.startIndex, offsetBy: 4) 45 | let range = start..(_regexString: pattern) 48 | let result = try regex.firstMatch(in: input) 49 | 50 | let match = try #require(result) 51 | 52 | #expect(match.range == range) 53 | #expect(input[match.range] == "ab") 54 | } 55 | 56 | @Test func testMatch04() throws { 57 | let pattern = "e|a" 58 | let input = "ccab" 59 | 60 | let start = input.index(input.startIndex, offsetBy: 2) 61 | let end = input.index(input.startIndex, offsetBy: 3) 62 | let range = start..(_regexString: pattern) 65 | let result = try regex.firstMatch(in: input) 66 | 67 | let match = try #require(result) 68 | 69 | #expect(match.range == range) 70 | #expect(input[match.range] == "a") 71 | } 72 | 73 | @Test func testMatch05() throws { 74 | let pattern = "a*" 75 | let input = "ccaab" 76 | 77 | let start = input.index(input.startIndex, offsetBy: 0) 78 | let end = input.index(input.startIndex, offsetBy: 0) 79 | let range = start..(_regexString: pattern) 82 | let result = try regex.firstMatch(in: input) 83 | 84 | let match = try #require(result) 85 | 86 | #expect(match.range == range) 87 | #expect(input[match.range] == "") 88 | } 89 | 90 | @Test func testMatch06() throws { 91 | let pattern = "aa*" 92 | let input = "ccaaab" 93 | 94 | let start = input.index(input.startIndex, offsetBy: 2) 95 | let end = input.index(input.startIndex, offsetBy: 5) 96 | let range = start..(_regexString: pattern) 99 | let result = try regex.firstMatch(in: input) 100 | 101 | let match = try #require(result) 102 | 103 | #expect(match.range == range) 104 | #expect(input[match.range] == "aaa") 105 | } 106 | 107 | @Test func testMatch07() throws { 108 | let pattern = "(|a)" 109 | let input = "ccaab" 110 | 111 | let start = input.index(input.startIndex, offsetBy: 0) 112 | let end = input.index(input.startIndex, offsetBy: 0) 113 | let range = start..(_regexString: pattern) 116 | let result = try regex.firstMatch(in: input) 117 | 118 | let match = try #require(result) 119 | 120 | #expect(match.range == range) 121 | #expect(input[match.range] == "") 122 | } 123 | 124 | @Test func testMatch08() throws { 125 | let pattern = "(ab)" 126 | let input = "ccaab" 127 | 128 | let start = input.index(input.startIndex, offsetBy: 3) 129 | let end = input.index(input.startIndex, offsetBy: 5) 130 | let range = start..(_regexString: pattern) 133 | let result = try regex.firstMatch(in: input) 134 | 135 | let match = try #require(result) 136 | 137 | #expect(match.range == range) 138 | #expect(input[match.range] == "ab") 139 | } 140 | 141 | @Test func testMatch09() throws { 142 | let pattern = "(ab)" 143 | let input = "ccaabe" 144 | 145 | let start = input.index(input.startIndex, offsetBy: 3) 146 | let end = input.index(input.startIndex, offsetBy: 5) 147 | let range = start..(_regexString: pattern) 150 | let result = try regex.firstMatch(in: input) 151 | 152 | let match = try #require(result) 153 | 154 | #expect(match.range == range) 155 | #expect(input[match.range] == "ab") 156 | } 157 | 158 | @Test func testMatch10() throws { 159 | let pattern = "(ab)|(bc)" 160 | let input = "ccabce" 161 | 162 | let start = input.index(input.startIndex, offsetBy: 2) 163 | let end = input.index(input.startIndex, offsetBy: 4) 164 | let range = start..(_regexString: pattern) 167 | let result = try regex.firstMatch(in: input) 168 | 169 | let match = try #require(result) 170 | 171 | #expect(match.range == range) 172 | #expect(input[match.range] == "ab") 173 | } 174 | 175 | @Test func testMatch11() throws { 176 | let pattern = "(ab)|(bc)" 177 | let input = "ccebce" 178 | 179 | let start = input.index(input.startIndex, offsetBy: 3) 180 | let end = input.index(input.startIndex, offsetBy: 5) 181 | let range = start..(_regexString: pattern) 184 | let result = try regex.firstMatch(in: input) 185 | 186 | let match = try #require(result) 187 | 188 | #expect(match.range == range) 189 | #expect(input[match.range] == "bc") 190 | } 191 | 192 | @Test func testMatch12() throws { 193 | let pattern = "Bob|Robert" 194 | let input = "Robert" 195 | 196 | let start = input.index(input.startIndex, offsetBy: 0) 197 | let end = input.index(input.startIndex, offsetBy: 6) 198 | let range = start..(_regexString: pattern) 201 | let result = try regex.firstMatch(in: input) 202 | 203 | let match = try #require(result) 204 | 205 | #expect(match.range == range) 206 | #expect(input[match.range] == "Robert") 207 | } 208 | 209 | @Test func testMatch13() throws { 210 | let pattern = "Bob|Robert" 211 | let input = "Bob" 212 | 213 | let start = input.index(input.startIndex, offsetBy: 0) 214 | let end = input.index(input.startIndex, offsetBy: 3) 215 | let range = start..(_regexString: pattern) 218 | let result = try regex.firstMatch(in: input) 219 | 220 | let match = try #require(result) 221 | 222 | #expect(match.range == range) 223 | #expect(input[match.range] == "Bob") 224 | } 225 | 226 | @Test func testMatch14() throws { 227 | let pattern = "gr(a|e)y" 228 | let input = "grey" 229 | 230 | let start = input.index(input.startIndex, offsetBy: 0) 231 | let end = input.index(input.startIndex, offsetBy: 4) 232 | let range = start..(_regexString: pattern) 235 | let result = try regex.firstMatch(in: input) 236 | 237 | let match = try #require(result) 238 | 239 | #expect(match.range == range) 240 | #expect(input[match.range] == "grey") 241 | } 242 | 243 | @Test func testMatch16() throws { 244 | let pattern = "cat" 245 | let input = "The dragging belly indicates your cat is too fat" 246 | 247 | let start = input.index(input.startIndex, offsetBy: 23) 248 | let end = input.index(input.startIndex, offsetBy: 26) 249 | let range = start..(_regexString: pattern) 252 | let result = try regex.firstMatch(in: input) 253 | 254 | let match = try #require(result) 255 | 256 | #expect(match.range == range) 257 | #expect(input[match.range] == "cat") 258 | } 259 | 260 | @Test func testMatch17() throws { 261 | let pattern = "fat|cat|belly|your" 262 | let input = "The dragging belly indicates your cat is too fat" 263 | 264 | let start = input.index(input.startIndex, offsetBy: 13) 265 | let end = input.index(input.startIndex, offsetBy: 18) 266 | let range = start..(_regexString: pattern) 269 | let result = try regex.firstMatch(in: input) 270 | 271 | let match = try #require(result) 272 | 273 | #expect(match.range == range) 274 | #expect(input[match.range] == "belly") 275 | } 276 | 277 | @Test func testMatch18() throws { 278 | let pattern = "a(|b)c" 279 | let inputs = ["abc", "ac"] 280 | 281 | for input in inputs { 282 | let range = input.startIndex..(_regexString: pattern) 285 | let result = try regex.firstMatch(in: input) 286 | 287 | let match = try #require(result) 288 | 289 | #expect(match.range == range) 290 | #expect(input[match.range] == input) 291 | } 292 | } 293 | 294 | @Test func testMatch19() throws { 295 | let pattern = "a(|b)c" 296 | let input = "abc" 297 | 298 | let start = input.index(input.startIndex, offsetBy: 0) 299 | let end = input.index(input.startIndex, offsetBy: 3) 300 | let range = start..(_regexString: pattern) 303 | let result = try regex.firstMatch(in: input) 304 | 305 | let match = try #require(result) 306 | 307 | #expect(match.range == range) 308 | #expect(input[match.range] == "abc") 309 | } 310 | 311 | @Test func testMatch20() throws { 312 | let pattern = "a*" 313 | let input = "aaaaa" 314 | 315 | let start = input.index(input.startIndex, offsetBy: 0) 316 | let end = input.index(input.startIndex, offsetBy: 5) 317 | let range = start..(_regexString: pattern) 320 | let result = try regex.firstMatch(in: input) 321 | 322 | let match = try #require(result) 323 | 324 | #expect(match.range == range) 325 | #expect(input[match.range] == "aaaaa") 326 | } 327 | 328 | @Test func testMatch21() throws { 329 | let pattern = "a+" 330 | let input = "ccaa+b" 331 | 332 | let start = input.index(input.startIndex, offsetBy: 3) 333 | let end = input.index(input.startIndex, offsetBy: 5) 334 | let range = start..(_regexString: pattern) 337 | let result = try regex.firstMatch(in: input) 338 | 339 | let match = try #require(result) 340 | 341 | #expect(match.range == range) 342 | #expect(input[match.range] == "a+") 343 | } 344 | 345 | @Test func testMatch22() throws { 346 | let pattern = "a?" 347 | let input = "cca?ab" 348 | 349 | let start = input.index(input.startIndex, offsetBy: 2) 350 | let end = input.index(input.startIndex, offsetBy: 4) 351 | let range = start..(_regexString: pattern) 354 | let result = try regex.firstMatch(in: input) 355 | 356 | let match = try #require(result) 357 | 358 | #expect(match.range == range) 359 | #expect(input[match.range] == "a?") 360 | } 361 | 362 | @Test func testMatch23() throws { 363 | let pattern = "a(a)*" 364 | let input = "ccaaab" 365 | 366 | let start = input.index(input.startIndex, offsetBy: 2) 367 | let end = input.index(input.startIndex, offsetBy: 5) 368 | let range = start..(_regexString: pattern) 371 | let result = try regex.firstMatch(in: input) 372 | 373 | let match = try #require(result) 374 | 375 | #expect(match.range == range) 376 | #expect(input[match.range] == "aaa") 377 | } 378 | 379 | @Test func testNotMatch01() throws { 380 | let pattern = "a" 381 | let input = "bb" 382 | 383 | let regex = Regex(_regexString: pattern) 384 | let match = try regex.firstMatch(in: input) 385 | 386 | #expect(match == nil) 387 | } 388 | 389 | @Test func testNotMatch02() throws { 390 | let pattern = "ab?c" 391 | let input = "abbc" 392 | 393 | let regex = Regex(_regexString: pattern) 394 | let match = try regex.firstMatch(in: input) 395 | 396 | #expect(match == nil) 397 | } 398 | -------------------------------------------------------------------------------- /01/TryRegex/Tests/RegexTests/PerformanceTests.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Testing 3 | 4 | @Suite("Performance tests", .serialized) 5 | struct PerformanceTests { 6 | @Suite("Swift Regex performance tests") 7 | struct SwiftRegexPerformanceTests { 8 | @Test("Factor out required components from the front of alternation") 9 | func alternation() async throws { 10 | let text = """ 11 | The theory that the mathematician proposed about the threshold of the universe was both innovative and controversial. 12 | """ 13 | 14 | let pattern1 = #/this|that|the/# 15 | let pattern2 = #/th(is|at|e)/# 16 | 17 | let iterations = 10_000 18 | 19 | measureTime(label: "Pattern1 (this|that|the)") { 20 | for _ in 0..{ 36 | let v: T 37 | } 38 | <<<<<<< HEAD 39 | func f(a: A>>>>>>>>>>>>>>>>>>>>>){ 40 | ======= 41 | func f(a: A){ 42 | >>>>>>> develop 43 | print(a) 44 | } 45 | """ 46 | 47 | // Swift Regex(Swift 5.7 以降)でパターンを定義 48 | let pattern1 = #/>* develop/# 49 | let pattern2 = #/>>>>>>> develop/# 50 | 51 | // 何回マッチ処理を実行するか 52 | let iterations = 10_000 53 | 54 | measureTime(label: "Pattern1 >* develop") { 55 | for _ in 0..>>>>>> develop") { 61 | for _ in 0..{ 103 | let v: T 104 | } 105 | <<<<<<< HEAD 106 | func f(a: A>>>>>>>>>>>>>>>>>>>>>){ 107 | ======= 108 | func f(a: A){ 109 | >>>>>>> develop 110 | print(a) 111 | } 112 | """ 113 | 114 | let pattern1 = ">* develop" 115 | let pattern2 = ">>>>>>> develop" 116 | 117 | let regex1 = try NSRegularExpression(pattern: pattern1) 118 | let regex2 = try NSRegularExpression(pattern: pattern2) 119 | 120 | let iterations = 10_000 121 | 122 | measureTime(label: "Pattern1 >* develop") { 123 | for _ in 0..>>>>>> develop") { 130 | for _ in 0.. Void) { 140 | let start = CFAbsoluteTimeGetCurrent() 141 | block() 142 | let end = CFAbsoluteTimeGetCurrent() 143 | let diff = end - start 144 | print("\(label) took \(diff) seconds.") 145 | } 146 | -------------------------------------------------------------------------------- /02/TryRegex/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /02/TryRegex/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.5 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "TryRegex", 8 | products: [ 9 | .library( 10 | name: "StringProcessing", 11 | targets: ["StringProcessing"] 12 | ), 13 | .library( 14 | name: "RegexParser", 15 | targets: ["RegexParser"] 16 | ), 17 | ], 18 | targets: [ 19 | .target( 20 | name: "RegexParser", 21 | dependencies: [] 22 | ), 23 | .target( 24 | name: "StringProcessing", 25 | dependencies: [ 26 | "RegexParser", 27 | ] 28 | ), 29 | .testTarget( 30 | name: "RegexTests", 31 | dependencies: [ 32 | "StringProcessing", 33 | ] 34 | ), 35 | ] 36 | ) 37 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/RegexParser/Regex/AST/AST.swift: -------------------------------------------------------------------------------- 1 | public struct AST { 2 | public var root: AST.Node 3 | 4 | public init(_ root: AST.Node) { 5 | self.root = root 6 | } 7 | } 8 | 9 | extension AST { 10 | public indirect enum Node { 11 | case alternation(Alternation) 12 | case concatenation(Concatenation) 13 | case group(Group) 14 | case quantification(Quantification) 15 | case atom(Atom) 16 | case empty(Empty) 17 | } 18 | } 19 | 20 | extension AST { 21 | public struct Alternation { 22 | public let children: [AST.Node] 23 | 24 | public init(_ mems: [AST.Node]) { 25 | self.children = mems 26 | } 27 | } 28 | 29 | public struct Concatenation { 30 | public let children: [AST.Node] 31 | 32 | public init(_ mems: [AST.Node]) { 33 | self.children = mems 34 | } 35 | } 36 | 37 | public struct Empty {} 38 | } 39 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/RegexParser/Regex/AST/Atom.swift: -------------------------------------------------------------------------------- 1 | extension AST { 2 | public struct Atom { 3 | public let kind: Kind 4 | 5 | public init(_ k: Kind) { 6 | self.kind = k 7 | } 8 | 9 | public enum Kind { 10 | case char(Character) 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/RegexParser/Regex/AST/Group.swift: -------------------------------------------------------------------------------- 1 | extension AST { 2 | public struct Group { 3 | public let kind: Kind 4 | public let child: AST.Node 5 | 6 | public init(_ kind: Kind, _ child: AST.Node) { 7 | self.kind = kind 8 | self.child = child 9 | } 10 | 11 | public enum Kind { 12 | case capture 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/RegexParser/Regex/AST/Quantification.swift: -------------------------------------------------------------------------------- 1 | extension AST { 2 | public struct Quantification { 3 | public let amount: Amount 4 | public let child: AST.Node 5 | 6 | public init(_ amount: Amount, _ child: AST.Node) { 7 | self.amount = amount 8 | self.child = child 9 | } 10 | 11 | public enum Amount: Hashable { 12 | case zeroOrMore // * 13 | case oneOrMore // + 14 | case zeroOrOne // ? 15 | } 16 | } 17 | } 18 | 19 | extension AST.Quantification.Amount { 20 | public var bounds: (atLeast: Int?, atMost: Int?) { 21 | switch self { 22 | case .zeroOrMore: return (0, nil) 23 | case .oneOrMore: return (1, nil) 24 | case .zeroOrOne: return (0, 1) 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/RegexParser/Regex/Parse/LexicalAnalysis.swift: -------------------------------------------------------------------------------- 1 | extension Parser { 2 | typealias Char = Source.Char 3 | } 4 | 5 | extension Parser { 6 | mutating func tryEating( 7 | _ body: (inout Self) -> T? 8 | ) -> T? { 9 | guard let result = body(&self) else { 10 | return nil 11 | } 12 | return result 13 | } 14 | } 15 | 16 | extension Parser { 17 | typealias Quant = AST.Quantification 18 | 19 | @discardableResult 20 | mutating func expect(_ c: Character) -> Bool { 21 | guard tryEat(c) else { 22 | return false 23 | } 24 | return true 25 | } 26 | 27 | func peek() -> Char? { src.peek() } 28 | 29 | mutating func advance(_ n: Int = 1) { 30 | guard src.tryAdvance(n) else { 31 | fatalError("Advancing beyond end!") 32 | } 33 | } 34 | 35 | mutating func tryEat() -> Char? { 36 | guard let char = peek() else { return nil } 37 | advance() 38 | return char 39 | } 40 | 41 | mutating func tryEat(_ c: Char) -> Bool { 42 | guard peek() == c else { return false } 43 | advance() 44 | return true 45 | } 46 | } 47 | 48 | extension Parser { 49 | mutating func lexQuantifier() -> Quant.Amount? { 50 | tryEating { p in 51 | let amt: Quant.Amount? = { 52 | if p.tryEat("*") { return .zeroOrMore } 53 | if p.tryEat("+") { return .oneOrMore } 54 | if p.tryEat("?") { return .zeroOrOne } 55 | 56 | return nil 57 | }() 58 | guard let amt = amt else { return nil } 59 | 60 | return amt 61 | } 62 | } 63 | 64 | mutating func lexGroupStart() -> AST.Group.Kind? { 65 | tryEating { p in 66 | guard p.tryEat("(") else { return nil } 67 | return .capture 68 | } 69 | } 70 | 71 | mutating func lexAtom() -> AST.Atom? { 72 | if src.isEmpty { return nil } 73 | if (peek() == ")" || peek() == "|") { return nil } 74 | 75 | guard let char = tryEat() else { 76 | fatalError("Unexpected end of input") 77 | } 78 | 79 | return AST.Atom(.char(char)) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/RegexParser/Regex/Parse/Parse.swift: -------------------------------------------------------------------------------- 1 | struct Parser { 2 | var src: Source 3 | 4 | init(_ src: Source) { 5 | self.src = src 6 | } 7 | } 8 | 9 | extension Parser { 10 | mutating func parse() -> AST { 11 | let ast = parseNode() 12 | 13 | if !src.isEmpty { 14 | if tryEat(")") { 15 | fatalError("closing ')' does not balance any groups openings") 16 | } else { 17 | fatalError("Unhandled termination condition") 18 | } 19 | } 20 | 21 | return .init(ast) 22 | } 23 | 24 | mutating func parseNode() -> AST.Node { 25 | if src.isEmpty { 26 | return .empty(.init()) 27 | } 28 | 29 | var result = [parseConcatenation()] 30 | while true { 31 | guard tryEat("|") else { break } 32 | result.append(parseConcatenation()) 33 | } 34 | 35 | if result.count == 1 { 36 | return result[0] 37 | } 38 | 39 | return .alternation(.init(result)) 40 | } 41 | 42 | mutating func parseConcatenation() -> AST.Node { 43 | var result = [AST.Node]() 44 | 45 | while true { 46 | if src.isEmpty { 47 | break 48 | } 49 | if peek() == "|" || peek() == ")" { 50 | break 51 | } 52 | 53 | if let operand = parseQuantifierOperand() { 54 | if let amt = lexQuantifier() { 55 | result.append( 56 | .quantification(.init(amt, operand)) 57 | ) 58 | } else { 59 | result.append(operand) 60 | } 61 | continue 62 | } 63 | 64 | fatalError("Should have parsed at least an atom") 65 | break 66 | } 67 | guard !result.isEmpty else { 68 | return .empty(.init()) 69 | } 70 | if result.count == 1 { 71 | return result[0] 72 | } 73 | 74 | return .concatenation(.init(result)) 75 | } 76 | 77 | mutating func parseGroupBody( 78 | _ kind: AST.Group.Kind 79 | ) -> AST.Group { 80 | let child = parseNode() 81 | expect(")") 82 | return .init(kind, child) 83 | } 84 | 85 | mutating func parseQuantifierOperand() -> AST.Node? { 86 | if let kind = lexGroupStart() { 87 | return .group(parseGroupBody(kind)) 88 | } 89 | 90 | if let atom = lexAtom() { 91 | return .atom(atom) 92 | } 93 | 94 | return nil 95 | } 96 | } 97 | 98 | public func parse(_ regex: S) -> AST where S.SubSequence == Substring { 99 | let source = Source(String(regex)) 100 | var parser = Parser(source) 101 | return parser.parse() 102 | } 103 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/RegexParser/Regex/Parse/Source.swift: -------------------------------------------------------------------------------- 1 | public struct Source { 2 | var input: Input 3 | var bounds: Range 4 | 5 | init(_ str: Input) { 6 | self.input = str 7 | self.bounds = str.startIndex.. Char? { _slice.first } 22 | 23 | @discardableResult 24 | mutating func tryAdvance(_ n: Int = 1) -> Bool { 25 | guard n > 0, let newLower = _slice.index( 26 | bounds.lowerBound, offsetBy: n, limitedBy: bounds.upperBound 27 | ) 28 | else { 29 | return false 30 | } 31 | self.bounds = newLower.. MEProgram { 11 | try emitNode(root) 12 | builder.buildAccept() 13 | 14 | return try builder.assemble() 15 | } 16 | } 17 | 18 | fileprivate extension Compiler.ByteCodeGen { 19 | mutating func emitAtom(_ a: DSLTree.Atom) throws { 20 | switch a { 21 | case let .char(c): 22 | emitCharacter(c) 23 | } 24 | } 25 | 26 | mutating func emitCharacter(_ c: Character) { 27 | builder.buildMatch(c) 28 | } 29 | 30 | mutating func emitAlternationGen( 31 | _ elements: C, 32 | withBacktracking: Bool, 33 | _ body: (inout Compiler.ByteCodeGen, C.Element) throws -> Void 34 | ) rethrows { 35 | let done = builder.makeAddress() 36 | for element in elements.dropLast() { 37 | let next = builder.makeAddress() 38 | builder.buildSave(next) 39 | try body(&self, element) 40 | builder.buildBranch(to: done) 41 | builder.label(next) 42 | } 43 | try body(&self, elements.last!) 44 | builder.label(done) 45 | } 46 | 47 | mutating func emitAlternation( 48 | _ children: [DSLTree.Node] 49 | ) throws { 50 | try emitAlternationGen(children, withBacktracking: true) { 51 | try $0.emitNode($1) 52 | } 53 | } 54 | 55 | mutating func emitConcatenationComponent( 56 | _ node: DSLTree.Node 57 | ) throws { 58 | try emitNode(node) 59 | } 60 | 61 | mutating func emitQuantification( 62 | _ amount: AST.Quantification.Amount, 63 | _ child: DSLTree.Node 64 | ) throws { 65 | let (low, high) = amount.bounds 66 | guard let low = low else { 67 | fatalError("Must have a lower bound") 68 | } 69 | 70 | let maxExtraTrips: Int? 71 | if let h = high { 72 | maxExtraTrips = h - low 73 | } else { 74 | maxExtraTrips = nil 75 | } 76 | let minTrips = low 77 | 78 | let minTripsControl = builder.makeAddress() 79 | let loopBody = builder.makeAddress() 80 | let exitPolicy = builder.makeAddress() 81 | let exit = builder.makeAddress() 82 | 83 | let maxExtraTripsReg: IntRegister? 84 | if (maxExtraTrips ?? 0) > 0 { 85 | maxExtraTripsReg = builder.makeIntRegister( 86 | initialValue: maxExtraTrips! 87 | ) 88 | } else { 89 | maxExtraTripsReg = nil 90 | } 91 | 92 | builder.label(minTripsControl) 93 | switch minTrips { 94 | case 0: builder.buildBranch(to: exitPolicy) 95 | default: break 96 | } 97 | 98 | builder.label(loopBody) 99 | try emitNode(child) 100 | 101 | builder.label(exitPolicy) 102 | 103 | switch maxExtraTrips { 104 | case nil: 105 | break 106 | case 0: 107 | builder.buildBranch(to: exit) 108 | default: 109 | builder.buildCondBranch(to: exit, ifZeroElseDecrement: maxExtraTripsReg!) 110 | } 111 | 112 | builder.buildSplit(to: loopBody, saving: exit) 113 | builder.label(exit) 114 | } 115 | 116 | mutating func emitConcatenation(_ children: [DSLTree.Node]) throws { 117 | for child in children { 118 | try emitConcatenationComponent(child) 119 | } 120 | } 121 | 122 | mutating func emitNode(_ node: DSLTree.Node) throws { 123 | switch node { 124 | case let .orderedChoice(children): 125 | try emitAlternation(children) 126 | 127 | case let .concatenation(children): 128 | try emitConcatenation(children) 129 | 130 | case .capture(let child): 131 | try emitNode(child) 132 | 133 | case let .quantification(amt, child): 134 | try emitQuantification(amt.ast, child) 135 | 136 | case let .atom(a): 137 | try emitAtom(a) 138 | 139 | case .empty: 140 | return 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Compiler.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | class Compiler { 4 | let tree: DSLTree 5 | 6 | init(ast: AST) { 7 | self.tree = ast.dslTree 8 | } 9 | 10 | init(tree: DSLTree) { 11 | self.tree = tree 12 | } 13 | 14 | __consuming func emit() throws -> MEProgram { 15 | var codegen = ByteCodeGen() 16 | return try codegen.emitRoot(tree.root) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Engine/Backtracking.swift: -------------------------------------------------------------------------------- 1 | extension Processor { 2 | struct SavePoint { 3 | var pc: InstructionAddress 4 | var pos: Position? 5 | 6 | var destructure: ( 7 | pc: InstructionAddress, 8 | pos: Position? 9 | ) { 10 | return (pc, pos) 11 | } 12 | } 13 | 14 | func makeSavePoint( 15 | resumingAt pc: InstructionAddress 16 | ) -> SavePoint { 17 | SavePoint( 18 | pc: pc, 19 | pos: currentPosition 20 | ) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Engine/InstPayload.swift: -------------------------------------------------------------------------------- 1 | extension Instruction { 2 | enum Payload { 3 | case none 4 | case int(Int) 5 | case element(Character) 6 | case addr(InstructionAddress) 7 | case pairedImmediateInt(UInt64, Int) 8 | case pairedAddrInt(InstructionAddress, Int) 9 | case pairedAddrAddr(InstructionAddress, InstructionAddress) 10 | } 11 | } 12 | 13 | extension Instruction.Payload { 14 | init(int: Int) { 15 | self = .int(int) 16 | } 17 | var int: Int { 18 | guard case .int(let value) = self else { 19 | fatalError("Payload is not an operand.") 20 | } 21 | return value 22 | } 23 | 24 | init(element: Character) { 25 | self = .element(element) 26 | } 27 | var elementPayload: Character { 28 | guard case .element(let element) = self else { 29 | fatalError("Payload is not an operand.") 30 | } 31 | return element 32 | } 33 | 34 | init(addr: InstructionAddress) { 35 | self = .addr(addr) 36 | } 37 | var addr: InstructionAddress { 38 | guard case .addr(let addr) = self else { 39 | fatalError("Payload is not an address.") 40 | } 41 | return addr 42 | } 43 | 44 | init(immediate: UInt64, int: IntRegister) { 45 | self = .pairedImmediateInt(immediate, int) 46 | } 47 | var pairedImmediateInt: (UInt64, IntRegister) { 48 | guard case .pairedImmediateInt(let i, let r) = self else { 49 | fatalError("Payload is not an address pair.") 50 | } 51 | return (i, r) 52 | } 53 | 54 | init(addr: InstructionAddress, int: Int) { 55 | self = .pairedAddrInt(addr, int) 56 | } 57 | var pairedAddrInt: (InstructionAddress, Int) { 58 | guard case .pairedAddrInt(let addr, let i) = self else { 59 | fatalError("Payload is not an address pair.") 60 | } 61 | return (addr, i) 62 | } 63 | 64 | init(addr: InstructionAddress, addr2: InstructionAddress) { 65 | self = .pairedAddrAddr(addr, addr2) 66 | } 67 | var pairedAddrAddr: (InstructionAddress, InstructionAddress) { 68 | guard case .pairedAddrAddr(let a1, let a2) = self else { 69 | fatalError("Payload is not an address pair.") 70 | } 71 | return (a1, a2) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Engine/Instruction.swift: -------------------------------------------------------------------------------- 1 | struct Instruction { 2 | let opcode: Instruction.OpCode 3 | let payload: Instruction.Payload 4 | 5 | init(_ opcode: Instruction.OpCode) { 6 | self.init(opcode, .none) 7 | } 8 | 9 | init(_ opcode: Instruction.OpCode, _ payload: Instruction.Payload) { 10 | self.opcode = opcode 11 | self.payload = payload 12 | } 13 | } 14 | 15 | extension Instruction { 16 | enum OpCode: UInt64 { 17 | case invalid = 0 18 | 19 | case moveImmediate 20 | 21 | case branch 22 | 23 | case condBranchZeroElseDecrement 24 | 25 | case match 26 | 27 | case save 28 | 29 | case splitSaving 30 | 31 | case accept 32 | } 33 | } 34 | 35 | extension Instruction { 36 | var destructure: (opcode: OpCode, payload: Payload) { 37 | get { (opcode, payload) } 38 | set { self = Self(opcode, payload) } 39 | } 40 | } 41 | 42 | enum State { 43 | case inProgress 44 | case fail 45 | case accept 46 | } 47 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Engine/MEBuilder.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser // For errors 2 | 3 | typealias InstructionAddress = Int 4 | 5 | extension MEProgram { 6 | struct Builder { 7 | var instructions: [Instruction] = [] 8 | 9 | var elements = Array() 10 | 11 | var addressTokens: [InstructionAddress?] = [] 12 | var addressFixups: [(InstructionAddress, AddressFixup)] = [] 13 | 14 | var nextIntRegister = IntRegister(0) 15 | } 16 | } 17 | 18 | extension MEProgram.Builder { 19 | struct AddressFixup { 20 | var first: AddressToken 21 | var second: AddressToken? = nil 22 | 23 | init(_ a: AddressToken) { self.first = a } 24 | init(_ a: AddressToken, _ b: AddressToken) { 25 | self.first = a 26 | self.second = b 27 | } 28 | } 29 | } 30 | 31 | extension MEProgram.Builder { 32 | mutating func buildMoveImmediate( 33 | _ value: Int, into: IntRegister 34 | ) { 35 | let uint = UInt64(truncatingIfNeeded: value) 36 | instructions.append( 37 | .init(.moveImmediate, .init(immediate: uint, int: into)) 38 | ) 39 | } 40 | 41 | mutating func buildBranch(to t: AddressToken) { 42 | instructions.append(.init(.branch)) 43 | fixup(to: t) 44 | } 45 | 46 | mutating func buildCondBranch( 47 | to t: AddressToken, ifZeroElseDecrement i: Int 48 | ) { 49 | instructions.append(.init(.condBranchZeroElseDecrement, .init(int: i))) 50 | fixup(to: t) 51 | } 52 | 53 | mutating func buildSave(_ t: AddressToken) { 54 | instructions.append(.init(.save)) 55 | fixup(to: t) 56 | } 57 | 58 | mutating func buildSplit( 59 | to: AddressToken, saving: AddressToken 60 | ) { 61 | instructions.append(.init(.splitSaving)) 62 | fixup(to: (to, saving)) 63 | } 64 | 65 | mutating func buildMatch(_ e: Character) { 66 | instructions.append(.init(.match, .init(element: e))) 67 | } 68 | 69 | mutating func buildAccept() { 70 | instructions.append(.init(.accept)) 71 | } 72 | 73 | mutating func assemble() throws -> MEProgram { 74 | var instructions = instructions 75 | for (instAddr, tok) in addressFixups { 76 | let inst = instructions[instAddr] 77 | let addr = addressTokens[tok.first]! 78 | let payload: Instruction.Payload 79 | 80 | switch inst.opcode { 81 | case .condBranchZeroElseDecrement: 82 | payload = .init(addr: addr, int: inst.payload.int) 83 | case .branch, .save: 84 | payload = .init(addr: addr) 85 | case .splitSaving: 86 | guard let fix2 = tok.second else { 87 | fatalError() 88 | } 89 | let saving = addressTokens[fix2]! 90 | payload = .init(addr: addr, addr2: saving) 91 | default: 92 | fatalError() 93 | } 94 | 95 | instructions[instAddr] = .init(inst.opcode, payload) 96 | } 97 | 98 | let regs = Processor.Registers( 99 | numInts: nextIntRegister 100 | ) 101 | 102 | let program = MEProgram( 103 | instructions: instructions, 104 | registers: regs 105 | ) 106 | return program 107 | } 108 | } 109 | 110 | extension MEProgram.Builder { 111 | enum _AddressToken {} 112 | typealias AddressToken = Int 113 | 114 | mutating func makeAddress() -> AddressToken { 115 | defer { addressTokens.append(nil) } 116 | return AddressToken(addressTokens.count) 117 | } 118 | 119 | mutating func label(_ t: AddressToken) { 120 | addressTokens[t] = InstructionAddress(instructions.count) 121 | } 122 | 123 | mutating func fixup(to t: AddressToken) { 124 | assert(!instructions.isEmpty) 125 | addressFixups.append( 126 | (InstructionAddress(instructions.endIndex - 1), .init(t))) 127 | } 128 | 129 | mutating func fixup(to ts: (AddressToken, AddressToken)) { 130 | assert(!instructions.isEmpty) 131 | addressFixups.append(( 132 | InstructionAddress(instructions.endIndex - 1), 133 | .init(ts.0, ts.1))) 134 | } 135 | } 136 | 137 | extension MEProgram.Builder { 138 | mutating func makeIntRegister() -> IntRegister { 139 | defer { nextIntRegister += 1 } 140 | return nextIntRegister 141 | } 142 | 143 | mutating func makeIntRegister( 144 | initialValue: Int 145 | ) -> IntRegister { 146 | let r = makeIntRegister() 147 | self.buildMoveImmediate(initialValue, into: r) 148 | return r 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Engine/MEBuiltins.swift: -------------------------------------------------------------------------------- 1 | extension String { 2 | func characterAndEnd( 3 | at pos: String.Index, limitedBy end: String.Index 4 | ) -> (Character, String.Index)? { 5 | guard pos < end else { return nil } 6 | let next = index(after: pos) 7 | if next <= end { 8 | return (self[pos], next) 9 | } 10 | 11 | let substr = self[pos.. 17 | let instructions: [Instruction] 18 | 19 | var searchBounds: Range 20 | var currentPosition: Position 21 | var controller: Controller 22 | var registers: Registers 23 | var savePoints: [SavePoint] = [] 24 | var state: State = .inProgress 25 | } 26 | 27 | extension Processor { 28 | typealias Position = Input.Index 29 | 30 | var start: Position { searchBounds.lowerBound } 31 | var end: Position { searchBounds.upperBound } 32 | } 33 | 34 | extension Processor { 35 | init( 36 | program: MEProgram, 37 | input: Input, 38 | subjectBounds: Range, 39 | searchBounds: Range 40 | ) { 41 | self.controller = Controller(pc: 0) 42 | self.instructions = program.instructions 43 | self.input = input 44 | self.subjectBounds = subjectBounds 45 | self.searchBounds = searchBounds 46 | 47 | self.currentPosition = searchBounds.lowerBound 48 | 49 | self.registers = program.registers 50 | } 51 | 52 | mutating func reset( 53 | currentPosition: Position, 54 | searchBounds: Range 55 | ) { 56 | self.currentPosition = currentPosition 57 | self.searchBounds = searchBounds 58 | 59 | self.controller = Controller(pc: 0) 60 | 61 | if !self.savePoints.isEmpty { 62 | self.savePoints.removeAll(keepingCapacity: true) 63 | } 64 | 65 | self.state = .inProgress 66 | } 67 | } 68 | 69 | extension Processor { 70 | func fetch() -> (Instruction.OpCode, Instruction.Payload) { 71 | instructions[controller.pc].destructure 72 | } 73 | 74 | mutating func match(_ e: Element) -> Bool { 75 | guard let next = input.match( 76 | e, 77 | at: currentPosition, 78 | limitedBy: end 79 | ) else { 80 | signalFailure() 81 | return false 82 | } 83 | 84 | currentPosition = next 85 | return true 86 | } 87 | 88 | mutating func signalFailure(preservingCaptures: Bool = false) { 89 | guard !savePoints.isEmpty else { 90 | state = .fail 91 | return 92 | } 93 | 94 | let (pc, pos) = savePoints.removeLast().destructure 95 | 96 | controller.pc = pc 97 | currentPosition = pos ?? currentPosition 98 | } 99 | 100 | mutating func tryAccept() { 101 | state = .accept 102 | } 103 | 104 | mutating func cycle() { 105 | let (opcode, payload) = fetch() 106 | switch opcode { 107 | case .invalid: 108 | fatalError("Invalid program") 109 | 110 | case .moveImmediate: 111 | let (imm, reg) = payload.pairedImmediateInt 112 | let int = Int(truncatingIfNeeded: imm) 113 | 114 | registers[reg] = int 115 | controller.step() 116 | 117 | case .branch: 118 | controller.pc = payload.addr 119 | 120 | case .condBranchZeroElseDecrement: 121 | let (addr, int) = payload.pairedAddrInt 122 | if registers[int] == 0 { 123 | controller.pc = addr 124 | } else { 125 | registers[int] -= 1 126 | controller.step() 127 | } 128 | 129 | case .save: 130 | let resumeAddr = payload.addr 131 | let sp = makeSavePoint(resumingAt: resumeAddr) 132 | savePoints.append(sp) 133 | controller.step() 134 | 135 | case .splitSaving: 136 | let (nextPC, resumeAddr) = payload.pairedAddrAddr 137 | let sp = makeSavePoint(resumingAt: resumeAddr) 138 | savePoints.append(sp) 139 | controller.pc = nextPC 140 | 141 | case .accept: 142 | tryAccept() 143 | 144 | case .match: 145 | let element = payload.elementPayload 146 | if match(element) { 147 | controller.step() 148 | } 149 | } 150 | } 151 | } 152 | 153 | extension String { 154 | func match( 155 | _ char: Character, 156 | at pos: Index, 157 | limitedBy end: String.Index 158 | ) -> Index? { 159 | guard let (stringChar, next) = characterAndEnd(at: pos, limitedBy: end) else { return nil } 160 | guard stringChar == char else { return nil } 161 | 162 | return next 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Engine/Registers.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | typealias IntRegister = Int 4 | 5 | extension Processor { 6 | struct Registers { 7 | var isDirty = false 8 | var ints: [Int] 9 | 10 | init( 11 | isDirty: Bool = false, 12 | numInts: Int 13 | ) { 14 | self.isDirty = isDirty 15 | self.ints = Array(repeating: 0, count: numInts) 16 | } 17 | } 18 | } 19 | 20 | extension Processor.Registers { 21 | typealias Input = String 22 | 23 | subscript(_ i: IntRegister) -> Int { 24 | get { ints[i] } 25 | set { 26 | isDirty = true 27 | ints[i] = newValue 28 | } 29 | } 30 | } 31 | 32 | extension Processor.Registers { 33 | mutating func reset() { 34 | guard isDirty else { 35 | return 36 | } 37 | self.ints._setAll(to: 0) 38 | } 39 | } 40 | 41 | extension MutableCollection { 42 | mutating func _setAll(to e: Element) { 43 | for idx in self.indices { 44 | self[idx] = e 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Executor.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | enum Executor { 4 | static func firstMatch( 5 | _ program: MEProgram, 6 | _ input: String, 7 | subjectBounds: Range, 8 | searchBounds: Range 9 | ) throws -> Regex.Match? { 10 | var cpu = Processor( 11 | program: program, 12 | input: input, 13 | subjectBounds: subjectBounds, 14 | searchBounds: searchBounds 15 | ) 16 | return try Executor._firstMatch( 17 | program, 18 | using: &cpu 19 | ) 20 | } 21 | 22 | static func _firstMatch( 23 | _ program: MEProgram, 24 | using cpu: inout Processor 25 | ) throws -> Regex.Match? { 26 | var low = cpu.searchBounds.lowerBound 27 | let high = cpu.searchBounds.upperBound 28 | while true { 29 | if let m = try Executor._run(program, &cpu) { 30 | return m 31 | } 32 | 33 | if low == high { 34 | return nil 35 | } 36 | 37 | cpu.input.unicodeScalars.formIndex(after: &low) 38 | 39 | guard low <= high else { 40 | return nil 41 | } 42 | 43 | cpu.reset(currentPosition: low, searchBounds: cpu.searchBounds) 44 | } 45 | } 46 | } 47 | 48 | extension Executor { 49 | static func _run( 50 | _ program: MEProgram, 51 | _ input: String, 52 | subjectBounds: Range, 53 | searchBounds: Range 54 | ) throws -> Regex.Match? { 55 | var cpu = Processor( 56 | program: program, 57 | input: input, 58 | subjectBounds: subjectBounds, 59 | searchBounds: searchBounds 60 | ) 61 | return try _run(program, &cpu) 62 | } 63 | 64 | static func _run( 65 | _ program: MEProgram, 66 | _ cpu: inout Processor 67 | ) throws -> Regex.Match? { 68 | let startPosition = cpu.currentPosition 69 | guard let endIdx = try cpu.run() else { 70 | return nil 71 | } 72 | 73 | let range = startPosition.. Input.Index? { 80 | if self.state == .fail { 81 | return nil 82 | } 83 | 84 | while true { 85 | switch self.state { 86 | case .accept: 87 | return self.currentPosition 88 | case .fail: 89 | return nil 90 | case .inProgress: 91 | self.cycle() 92 | } 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Regex/ASTConversion.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | extension AST { 4 | var dslTree: DSLTree { 5 | return DSLTree(root.dslTreeNode) 6 | } 7 | } 8 | 9 | extension AST.Node { 10 | var dslTreeNode: DSLTree.Node { 11 | func convert() throws -> DSLTree.Node { 12 | switch self { 13 | case let .alternation(v): 14 | let children = v.children.map(\.dslTreeNode) 15 | return .orderedChoice(children) 16 | 17 | case let .concatenation(v): 18 | return .concatenation(v.children.map(\.dslTreeNode)) 19 | 20 | case let .group(v): 21 | let child = v.child.dslTreeNode 22 | switch v.kind { 23 | case .capture: 24 | return .capture(child) 25 | } 26 | case let .quantification(v): 27 | let child = v.child.dslTreeNode 28 | return .quantification( 29 | .init(ast: v.amount), child) 30 | 31 | case let .atom(v): 32 | switch v.kind { 33 | default: 34 | return .atom(v.dslTreeAtom) 35 | } 36 | 37 | case .empty(_): 38 | return .empty 39 | } 40 | } 41 | 42 | let converted = try! convert() 43 | return converted 44 | } 45 | } 46 | 47 | extension AST.Atom { 48 | var dslTreeAtom: DSLTree.Atom { 49 | switch self.kind { 50 | case let .char(c): return .char(c) 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Regex/Core.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | public struct Regex { 4 | let program: Program 5 | 6 | init(ast: AST) { 7 | self.program = Program(ast: ast) 8 | } 9 | init(ast: AST.Node) { 10 | self.program = Program( 11 | ast: .init(ast) 12 | ) 13 | } 14 | 15 | @usableFromInline 16 | init(_regexString pattern: String) { 17 | self.init(ast: parse(pattern)) 18 | } 19 | } 20 | 21 | extension Regex { 22 | internal final class Program { 23 | let tree: DSLTree 24 | 25 | var loweredProgram: MEProgram { 26 | let compiledProgram = try! Compiler(tree: tree).emit() 27 | return compiledProgram 28 | } 29 | 30 | init(ast: AST) { 31 | self.tree = ast.dslTree 32 | } 33 | 34 | init(tree: DSLTree) { 35 | self.tree = tree 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Regex/DSLTree.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | public struct DSLTree { 4 | var root: Node 5 | 6 | init(_ r: Node) { 7 | self.root = r 8 | } 9 | } 10 | 11 | extension DSLTree { 12 | indirect enum Node { 13 | case orderedChoice([Node]) 14 | 15 | case concatenation([Node]) 16 | 17 | case capture(Node) 18 | 19 | case quantification( 20 | _AST.QuantificationAmount, 21 | Node 22 | ) 23 | 24 | case atom(Atom) 25 | 26 | case empty 27 | } 28 | } 29 | 30 | extension DSLTree { 31 | public enum Atom { 32 | case char(Character) 33 | } 34 | } 35 | 36 | extension DSLTree { 37 | public enum _AST { 38 | public struct QuantificationAmount { 39 | internal var ast: AST.Quantification.Amount 40 | 41 | public static var zeroOrMore: Self { 42 | .init(ast: .zeroOrMore) 43 | } 44 | public static var oneOrMore: Self { 45 | .init(ast: .oneOrMore) 46 | } 47 | public static var zeroOrOne: Self { 48 | .init(ast: .zeroOrOne) 49 | } 50 | } 51 | 52 | public struct ASTNode { 53 | internal var ast: AST.Node 54 | } 55 | 56 | public struct Atom { 57 | internal var ast: AST.Atom 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /02/TryRegex/Sources/StringProcessing/Regex/Match.swift: -------------------------------------------------------------------------------- 1 | internal import RegexParser 2 | 3 | extension Regex { 4 | public struct Match { 5 | public let range: Range 6 | } 7 | } 8 | 9 | extension Regex { 10 | public func firstMatch(in string: String) throws -> Regex.Match? { 11 | let bounds = string.startIndex..(_regexString: pattern) 14 | let result = try regex.firstMatch(in: input) 15 | 16 | let match = try #require(result) 17 | 18 | #expect(match.range == range) 19 | #expect(input[match.range] == "a") 20 | } 21 | 22 | @Test func testMatch02() throws { 23 | let pattern = "a" 24 | let input = "ccab" 25 | 26 | let start = input.index(input.startIndex, offsetBy: 2) 27 | let end = input.index(input.startIndex, offsetBy: 3) 28 | let range = start..(_regexString: pattern) 31 | let result = try regex.firstMatch(in: input) 32 | 33 | let match = try #require(result) 34 | 35 | #expect(match.range == range) 36 | #expect(input[match.range] == "a") 37 | } 38 | 39 | @Test func testMatch03() throws { 40 | let pattern = "ab" 41 | let input = "ccab" 42 | 43 | let start = input.index(input.startIndex, offsetBy: 2) 44 | let end = input.index(input.startIndex, offsetBy: 4) 45 | let range = start..(_regexString: pattern) 48 | let result = try regex.firstMatch(in: input) 49 | 50 | let match = try #require(result) 51 | 52 | #expect(match.range == range) 53 | #expect(input[match.range] == "ab") 54 | } 55 | 56 | @Test func testMatch04() throws { 57 | let pattern = "e|a" 58 | let input = "ccab" 59 | 60 | let start = input.index(input.startIndex, offsetBy: 2) 61 | let end = input.index(input.startIndex, offsetBy: 3) 62 | let range = start..(_regexString: pattern) 65 | let result = try regex.firstMatch(in: input) 66 | 67 | let match = try #require(result) 68 | 69 | #expect(match.range == range) 70 | #expect(input[match.range] == "a") 71 | } 72 | 73 | @Test func testMatch05() throws { 74 | let pattern = "a*" 75 | let input = "ccaab" 76 | 77 | let start = input.index(input.startIndex, offsetBy: 0) 78 | let end = input.index(input.startIndex, offsetBy: 0) 79 | let range = start..(_regexString: pattern) 82 | let result = try regex.firstMatch(in: input) 83 | 84 | let match = try #require(result) 85 | 86 | #expect(match.range == range) 87 | #expect(input[match.range] == "") 88 | } 89 | 90 | @Test func testMatch06() throws { 91 | let pattern = "a+" 92 | let input = "ccaaab" 93 | 94 | let start = input.index(input.startIndex, offsetBy: 2) 95 | let end = input.index(input.startIndex, offsetBy: 5) 96 | let range = start..(_regexString: pattern) 99 | let result = try regex.firstMatch(in: input) 100 | 101 | let match = try #require(result) 102 | 103 | #expect(match.range == range) 104 | #expect(input[match.range] == "aaa") 105 | } 106 | 107 | @Test func testMatch07() throws { 108 | let pattern = "a?" 109 | let input = "ccaab" 110 | 111 | let start = input.index(input.startIndex, offsetBy: 0) 112 | let end = input.index(input.startIndex, offsetBy: 0) 113 | let range = start..(_regexString: pattern) 116 | let result = try regex.firstMatch(in: input) 117 | 118 | let match = try #require(result) 119 | 120 | #expect(match.range == range) 121 | #expect(input[match.range] == "") 122 | } 123 | 124 | @Test func testMatch08() throws { 125 | let pattern = "(ab)" 126 | let input = "ccaab" 127 | 128 | let start = input.index(input.startIndex, offsetBy: 3) 129 | let end = input.index(input.startIndex, offsetBy: 5) 130 | let range = start..(_regexString: pattern) 133 | let result = try regex.firstMatch(in: input) 134 | 135 | let match = try #require(result) 136 | 137 | #expect(match.range == range) 138 | #expect(input[match.range] == "ab") 139 | } 140 | 141 | @Test func testMatch09() throws { 142 | let pattern = "(ab)" 143 | let input = "ccaabe" 144 | 145 | let start = input.index(input.startIndex, offsetBy: 3) 146 | let end = input.index(input.startIndex, offsetBy: 5) 147 | let range = start..(_regexString: pattern) 150 | let result = try regex.firstMatch(in: input) 151 | 152 | let match = try #require(result) 153 | 154 | #expect(match.range == range) 155 | #expect(input[match.range] == "ab") 156 | } 157 | 158 | @Test func testMatch10() throws { 159 | let pattern = "(ab)|(bc)" 160 | let input = "ccabce" 161 | 162 | let start = input.index(input.startIndex, offsetBy: 2) 163 | let end = input.index(input.startIndex, offsetBy: 4) 164 | let range = start..(_regexString: pattern) 167 | let result = try regex.firstMatch(in: input) 168 | 169 | let match = try #require(result) 170 | 171 | #expect(match.range == range) 172 | #expect(input[match.range] == "ab") 173 | } 174 | 175 | @Test func testMatch11() throws { 176 | let pattern = "(ab)|(bc)" 177 | let input = "ccebce" 178 | 179 | let start = input.index(input.startIndex, offsetBy: 3) 180 | let end = input.index(input.startIndex, offsetBy: 5) 181 | let range = start..(_regexString: pattern) 184 | let result = try regex.firstMatch(in: input) 185 | 186 | let match = try #require(result) 187 | 188 | #expect(match.range == range) 189 | #expect(input[match.range] == "bc") 190 | } 191 | 192 | @Test func testMatch12() throws { 193 | let pattern = "Bob|Robert" 194 | let input = "Robert" 195 | 196 | let start = input.index(input.startIndex, offsetBy: 0) 197 | let end = input.index(input.startIndex, offsetBy: 6) 198 | let range = start..(_regexString: pattern) 201 | let result = try regex.firstMatch(in: input) 202 | 203 | let match = try #require(result) 204 | 205 | #expect(match.range == range) 206 | #expect(input[match.range] == "Robert") 207 | } 208 | 209 | @Test func testMatch13() throws { 210 | let pattern = "Bob|Robert" 211 | let input = "Bob" 212 | 213 | let start = input.index(input.startIndex, offsetBy: 0) 214 | let end = input.index(input.startIndex, offsetBy: 3) 215 | let range = start..(_regexString: pattern) 218 | let result = try regex.firstMatch(in: input) 219 | 220 | let match = try #require(result) 221 | 222 | #expect(match.range == range) 223 | #expect(input[match.range] == "Bob") 224 | } 225 | 226 | @Test func testMatch14() throws { 227 | let pattern = "gr(a|e)y" 228 | let input = "grey" 229 | 230 | let start = input.index(input.startIndex, offsetBy: 0) 231 | let end = input.index(input.startIndex, offsetBy: 4) 232 | let range = start..(_regexString: pattern) 235 | let result = try regex.firstMatch(in: input) 236 | 237 | let match = try #require(result) 238 | 239 | #expect(match.range == range) 240 | #expect(input[match.range] == "grey") 241 | } 242 | 243 | @Test func testMatch15() throws { 244 | let pattern = "July? (fourth|4(th)?)" 245 | let inputs = ["July 4th", "Jul 4", "Jul fourth"] 246 | 247 | for input in inputs { 248 | let range = input.startIndex..(_regexString: pattern) 251 | let result = try regex.firstMatch(in: input) 252 | 253 | let match = try #require(result) 254 | 255 | #expect(match.range == range) 256 | #expect(input[match.range] == input) 257 | } 258 | } 259 | 260 | @Test func testMatch16() throws { 261 | let pattern = "cat" 262 | let input = "The dragging belly indicates your cat is too fat" 263 | 264 | let start = input.index(input.startIndex, offsetBy: 23) 265 | let end = input.index(input.startIndex, offsetBy: 26) 266 | let range = start..(_regexString: pattern) 269 | let result = try regex.firstMatch(in: input) 270 | 271 | let match = try #require(result) 272 | 273 | #expect(match.range == range) 274 | #expect(input[match.range] == "cat") 275 | } 276 | 277 | @Test func testMatch17() throws { 278 | let pattern = "fat|cat|belly|your" 279 | let input = "The dragging belly indicates your cat is too fat" 280 | 281 | let start = input.index(input.startIndex, offsetBy: 13) 282 | let end = input.index(input.startIndex, offsetBy: 18) 283 | let range = start..(_regexString: pattern) 286 | let result = try regex.firstMatch(in: input) 287 | 288 | let match = try #require(result) 289 | 290 | #expect(match.range == range) 291 | #expect(input[match.range] == "belly") 292 | } 293 | 294 | @Test func testMatch18() throws { 295 | let pattern = "ab?c" 296 | let inputs = ["abc", "ac"] 297 | 298 | for input in inputs { 299 | let range = input.startIndex..(_regexString: pattern) 302 | let result = try regex.firstMatch(in: input) 303 | 304 | let match = try #require(result) 305 | 306 | #expect(match.range == range) 307 | #expect(input[match.range] == input) 308 | } 309 | } 310 | 311 | @Test func testMatch19() throws { 312 | let pattern = "ab?c" 313 | let input = "abc" 314 | 315 | let start = input.index(input.startIndex, offsetBy: 0) 316 | let end = input.index(input.startIndex, offsetBy: 3) 317 | let range = start..(_regexString: pattern) 320 | let result = try regex.firstMatch(in: input) 321 | 322 | let match = try #require(result) 323 | 324 | #expect(match.range == range) 325 | #expect(input[match.range] == "abc") 326 | } 327 | 328 | @Test func testMatch20() throws { 329 | let pattern = "a*" 330 | let input = "aaaaa" 331 | 332 | let start = input.index(input.startIndex, offsetBy: 0) 333 | let end = input.index(input.startIndex, offsetBy: 5) 334 | let range = start..(_regexString: pattern) 337 | let result = try regex.firstMatch(in: input) 338 | 339 | let match = try #require(result) 340 | 341 | #expect(match.range == range) 342 | #expect(input[match.range] == "aaaaa") 343 | } 344 | 345 | @Test func testMatch21() throws { 346 | let regex = Regex(_regexString: "((0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9))-((0(1|2|3|4|5|6|7|8|9))|(1(0|1|2)))-((0(1|2|3|4|5|6|7|8|9))|(1(0|1|2|3|4|5|6|7|8|9))|(2(0|1|2|3|4|5|6|7|8|9))|(3(0|1)))") 347 | let input = "New release date: 2025-04-12" 348 | if let match = try regex.firstMatch(in: input) { 349 | print(input[match.range]) // 2025-04-12 350 | } 351 | } 352 | 353 | @Test func testNotMatch01() throws { 354 | let pattern = "a" 355 | let input = "bb" 356 | 357 | let regex = Regex(_regexString: pattern) 358 | let match = try regex.firstMatch(in: input) 359 | 360 | #expect(match == nil) 361 | } 362 | 363 | @Test func testNotMatch02() throws { 364 | let pattern = "ab?c" 365 | let input = "abbc" 366 | 367 | let regex = Regex(_regexString: pattern) 368 | let match = try regex.firstMatch(in: input) 369 | 370 | #expect(match == nil) 371 | } 372 | -------------------------------------------------------------------------------- /02/TryRegex/Tests/RegexTests/PerformanceTests.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Testing 3 | 4 | @Suite("Performance tests", .serialized) 5 | struct PerformanceTests { 6 | @Suite("Swift Regex performance tests") 7 | struct SwiftRegexPerformanceTests { 8 | @Test("Factor out required components from the front of alternation") 9 | func alternation() async throws { 10 | let text = """ 11 | The theory that the mathematician proposed about the threshold of the universe was both innovative and controversial. 12 | """ 13 | 14 | let pattern1 = #/this|that|the/# 15 | let pattern2 = #/th(is|at|e)/# 16 | 17 | let iterations = 10_000 18 | 19 | measureTime(label: "Pattern1 (this|that|the)") { 20 | for _ in 0..{ 36 | let v: T 37 | } 38 | <<<<<<< HEAD 39 | func f(a: A>>>>>>>>>>>>>>>>>>>>>){ 40 | ======= 41 | func f(a: A){ 42 | >>>>>>> develop 43 | print(a) 44 | } 45 | """ 46 | 47 | // Swift Regex(Swift 5.7 以降)でパターンを定義 48 | let pattern1 = #/>* develop/# 49 | let pattern2 = #/>>>>>>> develop/# 50 | 51 | // 何回マッチ処理を実行するか 52 | let iterations = 10_000 53 | 54 | measureTime(label: "Pattern1 >* develop") { 55 | for _ in 0..>>>>>> develop") { 61 | for _ in 0..{ 103 | let v: T 104 | } 105 | <<<<<<< HEAD 106 | func f(a: A>>>>>>>>>>>>>>>>>>>>>){ 107 | ======= 108 | func f(a: A){ 109 | >>>>>>> develop 110 | print(a) 111 | } 112 | """ 113 | 114 | let pattern1 = ">* develop" 115 | let pattern2 = ">>>>>>> develop" 116 | 117 | let regex1 = try NSRegularExpression(pattern: pattern1) 118 | let regex2 = try NSRegularExpression(pattern: pattern2) 119 | 120 | let iterations = 10_000 121 | 122 | measureTime(label: "Pattern1 >* develop") { 123 | for _ in 0..>>>>>> develop") { 130 | for _ in 0.. Void) { 140 | let start = CFAbsoluteTimeGetCurrent() 141 | block() 142 | let end = CFAbsoluteTimeGetCurrent() 143 | let diff = end - start 144 | print("\(label) took \(diff) seconds.") 145 | } 146 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TryRegex 2 | 3 | Build your Swift Regex - How to implement regular expressions in Swift 4 | 5 | ## Overview 6 | 7 | This repository contains sample code from my talk at try! Swift 2025. You can learn how regular expressions work by building your own tiny regular expression engine with limited specifications. 8 | 9 | The talk is titled "Build your own regex engine" and was presented at try! Swift 2025 in Tokyo, Japan. The slides are available on iCloud. 10 | [You can read the slides here](https://www.icloud.com/keynote/05cS1btc22VKpxnUiYTI7w0pQ#Build_your_own_regex_engine). 11 | 12 | The code is written in Swift and is designed to be simple and easy to understand. The goal is to help you learn how regular expressions work under the hood. 13 | 14 | ## Three Fondamental Operations of Regex 15 | 16 | These three operations are the foundation of regular expressions. By combining these operations, you can create complex patterns to match strings. 17 | 18 | - Concatenation: This operation allows you to match a sequence of characters in a specific order. For example, the regex `abc` matches the string "abc". 19 | - Alternation: This operation allows you to match one of several possible patterns. For example, the regex `a|b` matches either "a" or "b". 20 | - Repetition: This operation allows you to match a pattern zero or more times. For example, the regex `a*` matches the string "aaa", "aa", "a", or "" (an empty string). 21 | 22 | All other syntax of regex can be implemented using these three operations. For example, the regex `a?` can be implemented as `a*|ε`, where ε is the empty string. The regex `a+` can be implemented as `aa*`, where `a*` matches zero or more occurrences of "a". The regex `[a-z]` can be implemented as `a|b|c|...|z`, where each letter is separated by the alternation operator `|`. 23 | 24 | ## How to Use 25 | 26 | ```swift 27 | let regex = Regex(_regexString: "a|b|c") 28 | let input = "a" 29 | 30 | if let result = regex.firstMatch(in: input) { 31 | print("Matched! \(result)") 32 | } else { 33 | print("Not matched.") 34 | } 35 | ``` 36 | 37 | This code creates a regex object with the pattern "abc" and checks if the string "abc" matches the regex. If it does, it prints "Matched!", otherwise it prints "Not matched.". 38 | 39 | ## Specifications 40 | 41 | This repository contains two projects. The project in the [01 directory](https://github.com/kishikawakatsumi/TryRegex/tree/main/01/TryRegex) is a regular expression engine that implements the following minimal specifications. 42 | 43 | ### 01. Minimal Implementation 44 | 45 | The first implementation is a minimal regex engine that supports the following features: 46 | 47 | - Concatenation 48 | - Alternation `|` 49 | - Repetition `*` 50 | - Grouping `()` 51 | 52 | ### 02. Optional and Plus 53 | 54 | The second implementation is an extension of the first one, adding support for optional and plus operators. The following features are added: 55 | 56 | The project in the [02 directory](https://github.com/kishikawakatsumi/TryRegex/tree/main/02/TryRegex) is a regular expression engine that implements the following additional specifications. 57 | 58 | - Optional `?` 59 | - One or more `+` 60 | --------------------------------------------------------------------------------