Skip to content

Add repeatMatch functions to DSL #161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 16, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 99 additions & 31 deletions Sources/VariadicsGenerator/VariadicsGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ struct VariadicsGenerator: ParsableCommand {
print("\(kind.rawValue) ", terminator: "", to: &standardError)
emitQuantifier(kind: kind, arity: arity)
}
print("repeating ", terminator: "", to: &standardError)
emitRepeating(arity: arity)
print(to: &standardError)
}

Expand Down Expand Up @@ -307,69 +309,135 @@ struct VariadicsGenerator: ParsableCommand {
}
}
}

struct QuantifierParameters {
var genericParams: String
var captures: String
var capturesTupled: String
var whereClause: String
var quantifiedCaptures: String
var matchType: String

var repeatingWhereClause: String {
whereClause.isEmpty
? "where R.Bound == Int"
: whereClause + ", R.Bound == Int"
}

init(kind: QuantifierKind, arity: Int) {
self.genericParams = {
var result = ""
if arity > 0 {
result += "W"
result += (0..<arity).map { ", C\($0)" }.joined()
result += ", "
}
result += "Component: \(regexProtocolName)"
return result
}()
self.captures = (0..<arity).map { "C\($0)" }.joined(separator: ", ")
self.capturesTupled = arity == 1 ? captures : "(\(captures))"
self.whereClause = arity == 0 ? "" :
"where Component.Match == (W, \(captures))"
self.quantifiedCaptures = kind == .zeroOrOne
? "\(capturesTupled)?"
: "[\(capturesTupled)]"
self.matchType = arity == 0
? baseMatchTypeName
: "(\(baseMatchTypeName), \(quantifiedCaptures))"
}
}

func emitQuantifier(kind: QuantifierKind, arity: Int) {
assert(arity >= 0)
let genericParams: String = {
var result = ""
if arity > 0 {
result += "W"
result += (0..<arity).map { ", C\($0)" }.joined()
result += ", "
}
result += "Component: \(regexProtocolName)"
return result
}()
let captures = (0..<arity).map { "C\($0)" }.joined(separator: ", ")
let capturesTupled = arity == 1 ? captures : "(\(captures))"
let whereClause: String = arity == 0 ? "" :
"where Component.Match == (W, \(captures))"
let quantifiedCaptures: String = {
switch kind {
case .zeroOrOne:
return "\(capturesTupled)?"
case .zeroOrMore, .oneOrMore:
return "[\(capturesTupled)]"
}
}()
let matchType = arity == 0 ? baseMatchTypeName : "(\(baseMatchTypeName), \(quantifiedCaptures))"
let params = QuantifierParameters(kind: kind, arity: arity)
output("""
\(arity == 0 ? "@_disfavoredOverload" : "")
public func \(kind.rawValue)<\(genericParams)>(
public func \(kind.rawValue)<\(params.genericParams)>(
_ component: Component,
_ behavior: QuantificationBehavior = .eagerly
) -> \(regexTypeName)<\(matchType)> \(whereClause) {
) -> \(regexTypeName)<\(params.matchType)> \(params.whereClause) {
.init(node: .quantification(.\(kind.astQuantifierAmount), behavior.astKind, component.regex.root))
}

\(arity == 0 ? "@_disfavoredOverload" : "")
public func \(kind.rawValue)<\(genericParams)>(
public func \(kind.rawValue)<\(params.genericParams)>(
_ behavior: QuantificationBehavior = .eagerly,
@RegexBuilder _ component: () -> Component
) -> \(regexTypeName)<\(matchType)> \(whereClause) {
) -> \(regexTypeName)<\(params.matchType)> \(params.whereClause) {
.init(node: .quantification(.\(kind.astQuantifierAmount), behavior.astKind, component().regex.root))
}

\(arity == 0 ? "@_disfavoredOverload" : "")
public postfix func \(kind.operatorName)<\(genericParams)>(
public postfix func \(kind.operatorName)<\(params.genericParams)>(
_ component: Component
) -> \(regexTypeName)<\(matchType)> \(whereClause) {
) -> \(regexTypeName)<\(params.matchType)> \(params.whereClause) {
.init(node: .quantification(.\(kind.astQuantifierAmount), .eager, component.regex.root))
}

\(kind == .zeroOrOne ?
"""
extension RegexBuilder {
public static func buildLimitedAvailability<\(genericParams)>(
public static func buildLimitedAvailability<\(params.genericParams)>(
_ component: Component
) -> \(regexTypeName)<\(matchType)> \(whereClause) {
) -> \(regexTypeName)<\(params.matchType)> \(params.whereClause) {
.init(node: .quantification(.\(kind.astQuantifierAmount), .eager, component.regex.root))
}
}
""" : "")

""")
}

func emitRepeating(arity: Int) {
assert(arity >= 0)
// `repeatMatch(..<5)` has the same generic semantics as zeroOrMore
let rangeParams = QuantifierParameters(kind: .zeroOrMore, arity: arity)
// `repeatMatch(count:)` has the same generic semantics as oneOrMore
let exactlyParams = QuantifierParameters(kind: .zeroOrMore, arity: arity)
output("""
\(arity == 0 ? "@_disfavoredOverload" : "")
public func repeatMatch<\(exactlyParams.genericParams)>(
_ component: Component,
count: Int
) -> \(regexTypeName)<\(exactlyParams.matchType)> \(exactlyParams.whereClause) {
assert(count > 0, "Must specify a positive count")
// TODO: Emit a warning about `repeatMatch(count: 0)` or `repeatMatch(count: 1)`
return Regex(node: .quantification(.exactly(.init(faking: count)), .eager, component.regex.root))
}

\(arity == 0 ? "@_disfavoredOverload" : "")
public func repeatMatch<\(exactlyParams.genericParams)>(
count: Int,
@RegexBuilder _ component: () -> Component
) -> \(regexTypeName)<\(exactlyParams.matchType)> \(exactlyParams.whereClause) {
assert(count > 0, "Must specify a positive count")
// TODO: Emit a warning about `repeatMatch(count: 0)` or `repeatMatch(count: 1)`
return Regex(node: .quantification(.exactly(.init(faking: count)), .eager, component().regex.root))
}

\(arity == 0 ? "@_disfavoredOverload" : "")
public func repeatMatch<\(rangeParams.genericParams), R: RangeExpression>(
_ component: Component,
_ expression: R,
_ behavior: QuantificationBehavior = .eagerly
) -> \(regexTypeName)<\(rangeParams.matchType)> \(rangeParams.repeatingWhereClause) {
.init(node:
_repeatingNode(expression.relative(to: 0..<Int.max), behavior, component.regex.root))
}

\(arity == 0 ? "@_disfavoredOverload" : "")
public func repeatMatch<\(rangeParams.genericParams), R: RangeExpression>(
_ expression: R,
_ behavior: QuantificationBehavior = .eagerly,
@RegexBuilder _ component: () -> Component
) -> \(regexTypeName)<\(rangeParams.matchType)> \(rangeParams.repeatingWhereClause) {
.init(node:
_repeatingNode(expression.relative(to: 0..<Int.max), behavior, component().regex.root))
}

""")
}

func emitAlternation(leftArity: Int, rightArity: Int) {
let leftGenParams: String = {
Expand Down
28 changes: 28 additions & 0 deletions Sources/_StringProcessing/RegexDSL/DSL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,34 @@ postfix operator .?
postfix operator .*
postfix operator .+

/// Generates a DSLTree node for a repeated range of the given DSLTree node.
/// Individual public API functions are in the generated Variadics.swift file.
internal func _repeatingNode(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: How about a static method DSLTree.Node.repeating(_:_:_:)

_ range: Range<Int>,
_ behavior: QuantificationBehavior,
_ node: DSLTree.Node
) -> DSLTree.Node {
// TODO: Throw these as errors
assert(range.lowerBound >= 0, "Cannot specify a negative lower bound")
assert(!range.isEmpty, "Cannot specify an empty range")

switch (range.lowerBound, range.upperBound) {
case (0, Int.max): // 0...
return .quantification(.zeroOrMore, behavior.astKind, node)
case (1, Int.max): // 1...
return .quantification(.oneOrMore, behavior.astKind, node)
case _ where range.count == 1: // ..<1 or ...0 or any range with count == 1
// Note: `behavior` is ignored in this case
return .quantification(.exactly(.init(faking: range.lowerBound)), .eager, node)
case (0, _): // 0..<n or 0...n or ..<n or ...n
return .quantification(.upToN(.init(faking: range.upperBound)), behavior.astKind, node)
case (_, Int.max): // n...
return .quantification(.nOrMore(.init(faking: range.lowerBound)), behavior.astKind, node)
default: // any other range
return .quantification(.range(.init(faking: range.lowerBound), .init(faking: range.upperBound)), behavior.astKind, node)
}
}

// MARK: Alternation

// TODO: Variadic generics
Expand Down
Loading