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 all 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
141 changes: 107 additions & 34 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,140 @@ struct VariadicsGenerator: ParsableCommand {
}
}
}

struct QuantifierParameters {
var disfavored: String
var genericParams: 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.disfavored = arity == 0 ? "@_disfavoredOverload\n" : ""
self.genericParams = {
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)" }
let capturesJoined = captures.joined(separator: ", ")
self.whereClause = arity == 0 ? "" :
"where Component.Match == (W, \(capturesJoined))"
self.quantifiedCaptures = {
switch kind {
case .zeroOrOne, .zeroOrMore:
return captures.map { "\($0)?" }.joined(separator: ", ")
case .oneOrMore:
return capturesJoined
}
}()
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)" }
let capturesJoined = captures.joined(separator: ", ")
let whereClause: String = arity == 0 ? "" :
"where Component.Match == (W, \(capturesJoined))"
let quantifiedCaptures: String = {
switch kind {
case .zeroOrOne, .zeroOrMore:
return captures.map { "\($0)?" }.joined(separator: ", ")
case .oneOrMore:
return capturesJoined
}
}()
let matchType = arity == 0 ? baseMatchTypeName : "(\(baseMatchTypeName), \(quantifiedCaptures))"
let params = QuantifierParameters(kind: kind, arity: arity)
output("""
\(arity == 0 ? "@_disfavoredOverload" : "")
public func \(kind.rawValue)<\(genericParams)>(
\(params.disfavored)\
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)>(
\(params.disfavored)\
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)>(
\(params.disfavored)\
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)
// `repeat(..<5)` has the same generic semantics as zeroOrMore
let params = QuantifierParameters(kind: .zeroOrMore, arity: arity)
// TODO: Could `repeat(count:)` have the same generic semantics as oneOrMore?
// We would need to prohibit `repeat(count: 0)`; can only happen at runtime

output("""
\(params.disfavored)\
public func repeating<\(params.genericParams)>(
_ component: Component,
count: Int
) -> \(regexTypeName)<\(params.matchType)> \(params.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))
}

\(params.disfavored)\
public func repeating<\(params.genericParams)>(
count: Int,
@RegexBuilder _ component: () -> Component
) -> \(regexTypeName)<\(params.matchType)> \(params.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))
}

\(params.disfavored)\
public func repeating<\(params.genericParams), R: RangeExpression>(
_ component: Component,
_ expression: R,
_ behavior: QuantificationBehavior = .eagerly
) -> \(regexTypeName)<\(params.matchType)> \(params.repeatingWhereClause) {
.init(node: .repeating(expression.relative(to: 0..<Int.max), behavior, component.regex.root))
}

\(params.disfavored)\
public func repeating<\(params.genericParams), R: RangeExpression>(
_ expression: R,
_ behavior: QuantificationBehavior = .eagerly,
@RegexBuilder _ component: () -> Component
) -> \(regexTypeName)<\(params.matchType)> \(params.repeatingWhereClause) {
.init(node: .repeating(expression.relative(to: 0..<Int.max), behavior, component().regex.root))
}

""")
}

func emitAlternation(leftArity: Int, rightArity: Int) {
let leftGenParams: String = {
Expand Down
30 changes: 30 additions & 0 deletions Sources/_StringProcessing/RegexDSL/DSLTree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -307,3 +307,33 @@ extension DSLTree.Node {
return .alternation([self, newNode])
}
}

extension DSLTree.Node {
/// Generates a DSLTree node for a repeated range of the given DSLTree node.
/// Individual public API functions are in the generated Variadics.swift file.
static func 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)
}
}
}
Loading