1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2021-2023 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 Swift project authors
*/
/// The argument text provided to a directive, which can be parsed
/// into various kinds of arguments.
///
/// For example, take the following directive:
///
/// ```markdown
/// @Dir(x: 1,
/// y: 2)
/// ```
///
/// The following line segments would be provided as ``DirectiveArgumentText``,
/// parsed as one logical string:
///
/// ```
/// x: 1,
/// ```
/// ```
/// y: 2
/// ```
public struct DirectiveArgumentText: Equatable {
/// Errors parsing name-value arguments from argument text segments.
public enum ParseError: Equatable {
/// A duplicate argument was given.
case duplicateArgument(name: String, firstLocation: SourceLocation, duplicateLocation: SourceLocation)
/// A character was expected but not found at a source location.
case missingExpectedCharacter(Character, location: SourceLocation)
/// Unexpected character at a source location.
case unexpectedCharacter(Character, location: SourceLocation)
}
/// A segment of a line of argument text.
public struct LineSegment: Equatable {
/// The original untrimmed text of the line, from which arguments can be parsed.
public var untrimmedText: String
@available(*, deprecated, renamed: "untrimmedText.startIndex")
public var lineStartIndex: String.Index {
get { untrimmedText.startIndex }
set { }
}
/// The index from which parsing should start.
public var parseIndex: String.Index
/// The range from which a segment was extracted from a line
/// of source, or `nil` if it was provided by other means.
public var range: SourceRange?
/// The segment's text starting from ``parseIndex``.
public var trimmedText: Substring {
return untrimmedText[parseIndex...]
}
/// Create an argument line segment.
/// - Parameters:
/// - untrimmedText: the segment's untrimmed text from which arguments can be parsed.
/// - parseIndex: The index from which parsing should start.
/// - range: The range from which a segment was extracted from a line
/// of source, or `nil` if the argument text was provided by other means.
init(untrimmedText: String, parseIndex: String.Index? = nil, range: SourceRange? = nil) {
self.untrimmedText = untrimmedText
self.parseIndex = parseIndex ?? untrimmedText.startIndex
self.range = range
}
/// Parse a quoted literal.
///
/// ```
/// quoted-literal -> " unquoted-literal "
/// ```
func parseQuotedLiteral(from line: inout TrimmedLine,
parseErrors: inout [ParseError]) -> TrimmedLine.Lex? {
precondition(line.text.starts(with: "\""))
_ = line.take(1)
guard let contents = line.lex(until: {
switch $0 {
case "\"":
return .stop
default:
return .continue
}
}, allowEscape: true, allowEmpty: true) else {
return nil
}
_ = parseCharacter("\"", from: &line,
required: true,
allowEscape: true,
diagnoseIfNotFound: true,
parseErrors: &parseErrors)
return contents
}
/// Parse an unquoted literal.
///
/// ```
/// unquoted-literal -> [^, :){]
/// ```
func parseUnquotedLiteral(from line: inout TrimmedLine) -> TrimmedLine.Lex? {
let result = line.lex(until: {
switch $0 {
case ",", " ", ":", ")", "{":
return .stop
default:
return .continue
}
}, allowEscape: true)
return result
}
/// Parse a literal.
///
/// ```
/// literal -> quoted-literal
/// | unquoted-literal
/// ```
func parseLiteral(from line: inout TrimmedLine, parseErrors: inout [ParseError]) -> TrimmedLine.Lex? {
line.lexWhitespace()
if line.text.starts(with: "\"") {
return parseQuotedLiteral(from: &line, parseErrors: &parseErrors)
} else {
return parseUnquotedLiteral(from: &line)
}
}
/// Attempt to parse a single character.
///
/// - Parameters:
/// - character: the expected character to parse
/// - line: the trimmed line from which to parse
/// - required: whether the character is required
/// - allowEscape: whether to allow the character to be escaped
/// - diagnoseIfNotFound: if `true` and the character was both required and not found, emit a diagnostic
/// - parseErrors: an array to update with any errors encountered while parsing
/// - Returns: `true` if the character was found.
func parseCharacter(_ character: Character,
from line: inout TrimmedLine,
required: Bool,
allowEscape: Bool,
diagnoseIfNotFound: Bool,
parseErrors: inout [ParseError]) -> Bool {
guard line.lex(character, allowEscape: allowEscape) != nil || !required else {
if diagnoseIfNotFound,
let expectedLocation = line.location {
parseErrors.append(.missingExpectedCharacter(character, location: expectedLocation))
}
return false
}
return true
}
/// Parse the line segment as name-value argument pairs separated by commas.
///
/// ```
/// arguments -> first-argument name-value-arguments-rest
/// first-argument -> value-only-argument | name-value-argument
/// value-only-argument -> literal
/// name-value-argument -> literal : literal
/// name-value-arguments -> name-value-argument name-value-arguments-rest
/// name-value-arguments-rest -> , name-value-arguments | ε
/// ```
///
/// Note the following aspects of this parsing function.
///
/// - An argument-name pair is only recognized within a single line or line segment;
/// that is, an argument cannot span multiple lines.
/// - A comma is expected between name-value pairs.
/// - The first argument can be unnamed. An unnamed argument will have an empty ``DirectiveArgument/name`` with no ``DirectiveArgument/nameRange``.
///
/// - Parameter parseErrors: an array to update with any errors encountered while parsing
/// - Returns: an array of successfully parsed ``DirectiveArgument`` values.
public func parseNameValueArguments(parseErrors: inout [ParseError]) -> [DirectiveArgument] {
var arguments = [DirectiveArgument]()
var line = TrimmedLine(untrimmedText[...],
source: range?.lowerBound.source,
lineNumber: range?.lowerBound.line,
parseIndex: parseIndex
)
line.lexWhitespace()
while !line.isEmptyOrAllWhitespace {
let name: TrimmedLine.Lex?
let value: TrimmedLine.Lex
guard let firstLiteral = parseLiteral(from: &line, parseErrors: &parseErrors) else {
while parseCharacter(",", from: &line, required: true, allowEscape: false, diagnoseIfNotFound: false, parseErrors: &parseErrors) {
if let location = line.location {
parseErrors.append(.unexpectedCharacter(",", location: location))
}
}
_ = line.lex(untilCharacter: ",")
continue
}
// The first argument can be without a name.
// An argument without a name must be followed by a "," or be the only argument. Otherwise the argument will be parsed as a named argument.
if arguments.isEmpty && (line.isEmptyOrAllWhitespace || line.text.first == ",") {
name = nil
value = firstLiteral
} else {
_ = parseCharacter(":", from: &line, required: true, allowEscape: false, diagnoseIfNotFound: true, parseErrors: &parseErrors)
guard let secondLiteral = parseLiteral(from: &line, parseErrors: &parseErrors) else {
while parseCharacter(",", from: &line, required: true, allowEscape: false, diagnoseIfNotFound: false, parseErrors: &parseErrors) {
if let location = line.location {
parseErrors.append(.unexpectedCharacter(",", location: location))
}
}
_ = line.lex(untilCharacter: ",")
continue
}
name = firstLiteral
value = secondLiteral
}
let nameRange: SourceRange?
let valueRange: SourceRange?
if let lineLocation = line.location,
let range = name?.range {
nameRange = SourceLocation(line: lineLocation.line, column: range.lowerBound.column, source: range.lowerBound.source)..<SourceLocation(line: lineLocation.line, column: range.upperBound.column, source: range.upperBound.source)
} else {
nameRange = nil
}
if let lineNumber = line.lineNumber,
let range = value.range {
valueRange = SourceLocation(line: lineNumber, column: range.lowerBound.column, source: range.lowerBound.source)..<SourceLocation(line: lineNumber, column: range.upperBound.column, source: range.lowerBound.source)
} else {
valueRange = nil
}
line.lexWhitespace()
let hasTrailingComma = parseCharacter(",",
from: &line,
required: true,
allowEscape: false,
diagnoseIfNotFound: false,
parseErrors: &parseErrors)
let argument = DirectiveArgument(name: String(name?.text ?? ""),
nameRange: nameRange,
value: String(value.text),
valueRange: valueRange,
hasTrailingComma: hasTrailingComma)
arguments.append(argument)
line.lexWhitespace()
}
return arguments
}
}
/// The segments that make up the argument text.
public var segments: [LineSegment]
/// Create a body of argument text as a single, rangeless ``LineSegment``
/// from a string.
public init<S: StringProtocol>(_ string: S) {
let text = String(string)
self.segments = [LineSegment(untrimmedText: text, range: nil)]
}
/// Create a body of argument text from a sequence of ``LineSegment`` elements.
public init<Segments: Sequence>(segments: Segments) where Segments.Element == LineSegment {
self.segments = Array(segments)
}
/// `true` if there are no segments or all segments consist entirely of whitespace.
public var isEmpty: Bool {
return segments.isEmpty || segments.allSatisfy {
$0.untrimmedText.isEmpty || $0.untrimmedText.allSatisfy {
$0 == " " || $0 == "\t"
}
}
}
/// Parse the line segments as name-value argument pairs separated by commas.
///
/// ```
/// arguments -> first-argument name-value-arguments-rest
/// first-argument -> value-only-argument | name-value-argument
/// value-only-argument -> literal
/// name-value-argument -> literal : literal
/// name-value-arguments -> name-value-argument name-value-arguments-rest
/// name-value-arguments-rest -> , name-value-arguments | ε
/// ```
///
/// Note the following aspects of this parsing function.
///
/// - An argument-name pair is only recognized within a single line or line segment;
/// that is, an argument cannot span multiple lines.
/// - A comma is expected between name-value pairs.
/// - The first argument can be unnamed. An unnamed argument will have an empty ``DirectiveArgument/name`` with no ``DirectiveArgument/nameRange``.
///
/// - Parameter parseErrors: an array to collect errors while parsing arguments.
/// - Returns: an array of successfully parsed ``DirectiveArgument`` values.
public func parseNameValueArguments(parseErrors: inout [ParseError]) -> [DirectiveArgument] {
var arguments = [DirectiveArgument]()
for segment in segments {
let segmentArguments = segment.parseNameValueArguments(parseErrors: &parseErrors)
for argument in segmentArguments {
if let originalArgument = arguments.first(where: { $0.name == argument.name }),
let firstLocation = originalArgument.nameRange?.lowerBound,
let duplicateLocation = argument.nameRange?.lowerBound {
parseErrors.append(.duplicateArgument(name: argument.name,
firstLocation: firstLocation,
duplicateLocation: duplicateLocation))
}
arguments.append(argument)
}
}
if arguments.count > 1 {
for argument in arguments.prefix(arguments.count - 1) {
if !argument.hasTrailingComma,
let valueRange = argument.valueRange {
parseErrors.append(.missingExpectedCharacter(",", location: valueRange.upperBound))
}
}
}
return arguments
}
/// Parse the line segments as name-value argument pairs separated by commas.
///
/// ```
/// arguments -> first-argument name-value-arguments-rest
/// first-argument -> value-only-argument | name-value-argument
/// value-only-argument -> literal
/// name-value-argument -> literal : literal
/// name-value-arguments -> name-value-argument name-value-arguments-rest
/// name-value-arguments-rest -> , name-value-arguments | ε
/// ```
///
/// Note the following aspects of this parsing function.
///
/// - An argument-name pair is only recognized within a single line or line segment;
/// that is, an argument cannot span multiple lines.
/// - A comma is expected between name-value pairs.
/// - The first argument can be unnamed. An unnamed argument will have an empty ``DirectiveArgument/name`` with no ``DirectiveArgument/nameRange``.
///
/// - Returns: an array of successfully parsed ``DirectiveArgument`` values.
///
/// This overload discards parse errors.
///
/// - SeeAlso: ``parseNameValueArguments(parseErrors:)``
public func parseNameValueArguments() -> [DirectiveArgument] {
var parseErrors = [ParseError]()
return parseNameValueArguments(parseErrors: &parseErrors)
}
}
/// A directive argument, parsed from the form `name: value` or `name: "value"`.
public struct DirectiveArgument: Equatable {
/// The name of the argument.
public var name: String
/// The range of the argument name if it was parsed from source text.
public var nameRange: SourceRange?
/// The value of the argument.
public var value: String
/// The range of the argument value if it was parsed from source text.
public var valueRange: SourceRange?
/// `true` if the argument value was followed by a comma.
public var hasTrailingComma: Bool
}
|