fix operator detect

This commit is contained in:
Roy Cao 2019-12-04 20:06:43 +08:00
parent a82ff332b4
commit 9b539c94da
3 changed files with 103 additions and 3 deletions

View File

@ -12,8 +12,24 @@ public struct Function {
public let parameters: [String]
}
extension Function: CustomStringConvertible {
public var description: String {
parameters.reduce("\(name)(") { $0 + "\($1):" } + ")"
extension Function {
private var isOperator: Bool {
Validation.isOperator(name)
}
}
extension Function: CustomStringConvertible {
/// operator function naming rules are different from ordinary function, for example:
/// func ==> (lhs: String, rhs: Int) -> Bool {
/// return lhs == String(rhs)
/// }
/// name is ==>(_:_:)
public var description: String {
if isOperator {
return parameters.map { _ in "_" }.reduce("\(name)(") { $0 + "\($1):" } + ")"
} else {
return parameters.reduce("\(name)(") { $0 + "\($1):" } + ")"
}
}
}

View File

@ -0,0 +1,71 @@
import Foundation
private func ~= (regex: Regex, string: String) -> Bool {
return regex.matches(string, options: [.anchored])
}
struct Regex {
private let regex: NSRegularExpression
init(regex: NSRegularExpression) {
self.regex = regex
}
init(_ pattern: String, options: NSRegularExpression.Options = []) {
do {
regex = try NSRegularExpression(pattern: pattern, options: options)
} catch {
preconditionFailure("Invalid regex: \(error)")
}
}
func matches(_ string: String, options: NSRegularExpression.MatchingOptions = []) -> Bool {
return regex.matchesWhole(string, options: options)
}
}
extension Regex: ExpressibleByStringLiteral {
typealias StringLiteralType = String
init(stringLiteral value: StringLiteralType) {
self = Regex(value)
}
init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
}
extension Regex: Hashable, Equatable {
func hash(into hasher: inout Hasher) {
hasher.combine(regex)
}
static func == (lhs: Regex, rhs: Regex) -> Bool {
return lhs.regex == rhs.regex
}
}
private extension NSRegularExpression {
func matchesWhole(_ string: String, options: NSRegularExpression.MatchingOptions = []) -> Bool {
var isMatch = false
let length = (string as NSString).length
enumerateMatches(in: string, options: options, range: NSRange(location: 0, length: length)) { result, _, stop in
guard let match = result else { return }
if match.range.location == 0 && match.range.length == length {
isMatch = true
stop.pointee = true
}
}
return isMatch
}
}

View File

@ -0,0 +1,13 @@
import Foundation
class Validation {
private enum RegexTypes: Regex {
// TODO: This is not the most correct regex, optimized after
case notOperator = "^[a-zA-Z]"
}
static func isOperator(_ str: String) -> Bool {
return !RegexTypes.notOperator.rawValue.matches(str)
}
}