File: URLTemplate_Expression.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (254 lines) | stat: -rw-r--r-- 8,806 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if canImport(CollectionsInternal)
internal import CollectionsInternal
#elseif canImport(OrderedCollections)
internal import OrderedCollections
#elseif canImport(_FoundationCollections)
internal import _FoundationCollections
#endif

extension URL.Template {
    struct Expression: Sendable, Hashable {
        var `operator`: Operator?
        var elements: [Element]

        struct Element: Sendable, Hashable {
            var name: URL.Template.VariableName
            var maximumLength: Int?
            var explode: Bool
        }

        enum Operator: String, Sendable, Hashable {
            /// `+`   Reserved character strings;
            case reserved = "+"
            /// `#`   Fragment identifiers prefixed by "#";
            case fragment = "#"
            /// `.`   Name labels or extensions prefixed by ".";
            case nameLabel = "."
            /// `/`   Path segments prefixed by "/";
            case pathSegment = "/"
            /// `;`   Path parameter name or name=value pairs prefixed by ";";
            case pathParameter = ";"
            /// `?`   Query component beginning with "?" and consisting of
            /// name=value pairs separated by "&"; and,
            case queryComponent = "?"
            /// `&`   Continuation of query-style &name=value pairs within
            /// a literal query component.
            case continuation = "&"
        }
    }
}

extension URL.Template {
    fileprivate struct InvalidExpression: Swift.Error {
        var text: String
    }
}

extension Substring {
    fileprivate mutating func popPrefixMatch<Output>(_ regex: Regex<Output>) throws -> Regex<Output>.Match? {
        guard
            let match = try regex.prefixMatch(in: self)
        else { return nil }
        self = self[match.range.upperBound..<self.endIndex]
        return match
    }
}

extension URL.Template.Expression: CustomStringConvertible {
    var description: String {
        "\(`operator`?.rawValue ?? "")" + elements.map { "\($0)" }.joined(separator: ",")
    }
}

extension URL.Template.Expression.Element: CustomStringConvertible {
    var description: String {
        "\(name)\(maximumLength.map { ":\($0)" } ?? "")\(explode ? "*" : "")"
    }
}

extension URL.Template.Expression {
    init(_ input: String) throws {
        var remainder = input[...]
        guard let opString = try remainder.popPrefixMatch(URL.Template.Global.shared.operatorRegex) else {
            throw URL.Template.InvalidExpression(text: input)
        }

        let op = try opString.1.map {
            guard let o = Operator(rawValue: String($0)) else {
                throw URL.Template.InvalidExpression(text: input)
            }
            return o
        }
        var elements: [Element] = []

        func popElement() throws {
            guard let match = try remainder.popPrefixMatch(URL.Template.Global.shared.elementRegex) else {
                throw URL.Template.InvalidExpression(text: input)
            }

            let name: Substring = match.output.1
            let maximumLength: Int?
            let explode: Bool
            if let max = match.output.3 {
                guard
                    let m = Int(max)
                else { throw URL.Template.InvalidExpression(text: "Invalid maximum length '\(input[match.range])'") }
                maximumLength = m
                explode = false
            } else if match.output.2 != nil {
                maximumLength = nil
                explode = true
            } else {
                maximumLength = nil
                explode = false
            }
            elements.append(Element(
                name: URL.Template.VariableName(name),
                maximumLength: maximumLength,
                explode: explode
            ))
        }

        try popElement()

        while !remainder.isEmpty {
            guard try remainder.popPrefixMatch(URL.Template.Global.shared.separatorRegex) != nil else {
                throw URL.Template.InvalidExpression(text: input)
            }

            try popElement()
        }

        self.init(
            operator: op,
            elements: elements
        )
    }
}

extension URL.Template {
    // Making the type unchecked Sendable is fine, Regex is safe in this context, as it only contains
    // other Sendable types. For details, see https://forums.swift.org/t/should-regex-be-sendable/69529/7
    internal final class Global: @unchecked Sendable {

        static let shared: Global = .init()

        let operatorRegex: Regex<(Substring, Substring?)>
        let separatorRegex: Regex<(Substring)>
        let elementRegex: Regex<(Substring, Substring, Substring?, Substring?)>
        let uriTemplateRegex: Regex<(Substring, Substring)>

        private init() {
            self.operatorRegex = try! Regex(#"([\+#.\/;\?&])?"#)
            .asciiOnlyWordCharacters()
            .asciiOnlyDigits()
            .asciiOnlyCharacterClasses()
            self.separatorRegex = try! Regex(#","#)
            .asciiOnlyWordCharacters()
            .asciiOnlyDigits()
            .asciiOnlyCharacterClasses()
            self.elementRegex = try! Regex(#"([a-zA-Z][a-zA-Z0-9_]*)(:([0-9]*)|\*)?"#)
            .asciiOnlyWordCharacters()
            .asciiOnlyDigits()
            .asciiOnlyCharacterClasses()
            self.uriTemplateRegex = try! Regex(#"{([^}]+)}"#)
        }
    }
}

// .------------------------------------------------------------------.
// |          NUL     +      .       /       ;      ?      &      #   |
// |------------------------------------------------------------------|
// | first |  ""     ""     "."     "/"     ";"    "?"    "&"    "#"  |
// | sep   |  ","    ","    "."     "/"     ";"    "&"    "&"    ","  |
// | named | false  false  false   false   true   true   true   false |
// | ifemp |  ""     ""     ""      ""      ""     "="    "="    ""   |
// | allow |   U     U+R     U       U       U      U      U     U+R  |
// `------------------------------------------------------------------'

extension URL.Template.Expression.Operator? {
    var firstPrefix: Character? {
        switch self {
        case nil: return nil
        case .reserved?: return nil
        case .nameLabel?: return "."
        case .pathSegment?: return "/"
        case .pathParameter?: return ";"
        case .queryComponent?: return "?"
        case .continuation?: return "&"
        case .fragment?: return "#"
        }
    }

    var separator: Character {
        switch self {
        case nil: return ","
        case .reserved?: return ","
        case .nameLabel?: return "."
        case .pathSegment?: return "/"
        case .pathParameter?: return ";"
        case .queryComponent?: return "&"
        case .continuation?: return "&"
        case .fragment?: return ","
        }
    }

    var isNamed: Bool {
        switch self {
        case nil: return false
        case .reserved?: return false
        case .nameLabel?: return false
        case .pathSegment?: return false
        case .pathParameter?: return true
        case .queryComponent?: return true
        case .continuation?: return true
        case .fragment?: return false
        }
    }

    var replacementForEmpty: Character? {
        switch self {
        case nil: return nil
        case .reserved?: return nil
        case .nameLabel?: return nil
        case .pathSegment?: return nil
        case .pathParameter?: return nil
        case .queryComponent?: return "="
        case .continuation?: return "="
        case .fragment?: return nil
        }
    }

    var allowedCharacters: URL.Template.Expression.Operator.AllowedCharacters {
        switch self {
        case nil: return .unreserved
        case .reserved?: return .unreservedReserved
        case .nameLabel?: return .unreserved
        case .pathSegment?: return .unreserved
        case .pathParameter?: return .unreserved
        case .queryComponent?: return .unreserved
        case .continuation?: return .unreserved
        case .fragment?: return .unreservedReserved
        }
    }
}

extension URL.Template.Expression.Operator {
    enum AllowedCharacters {
        case unreserved
        // The union of (unreserved / reserved / pct-encoded)
        case unreservedReserved
    }
}