Repository Public License
1// FlowEngine — source positions, diagnostics and the lexer of the Flow language (docs/FLOW_LANGUAGE.md).2import Foundation34/// A place in the source. `offset` counts UTF-16 code units (what `NSRange` and text views use); `line` and5/// `column` are 1-based, the column counting UTF-16 units from the start of the line.6public struct FlowPosition: Hashable, Sendable, Codable, Comparable {7 public var offset: Int8 public var line: Int9 public var column: Int1011 public init(offset: Int, line: Int, column: Int) { self.offset = offset; self.line = line; self.column = column }12 public static let start = FlowPosition(offset: 0, line: 1, column: 1)13 public static func < (lhs: FlowPosition, rhs: FlowPosition) -> Bool { lhs.offset < rhs.offset }14}1516public struct FlowRange: Hashable, Sendable, Codable {17 public var start: FlowPosition18 public var end: FlowPosition1920 public init(start: FlowPosition, end: FlowPosition) { self.start = start; self.end = end }21 public init(at position: FlowPosition) { start = position; end = position }2223 /// Half-open range of UTF-16 offsets, directly usable as an `NSRange`.24 public var utf16Range: Range<Int> { start.offset..<max(start.offset, end.offset) }25 public func contains(offset: Int) -> Bool { offset >= start.offset && offset <= end.offset }26 public func union(_ other: FlowRange) -> FlowRange {27 FlowRange(start: min(start, other.start), end: max(end, other.end))28 }29}3031public struct FlowDiagnostic: Hashable, Sendable, Codable, CustomStringConvertible {32 public enum Severity: String, Sendable, Codable { case error, warning }3334 public var severity: Severity35 /// Stable machine-readable identifier (`undefined-name`, `unbounded-loop`…), listed in docs/FLOW_LANGUAGE.md.36 public var code: String37 public var message: String38 public var range: FlowRange39 /// How to fix it, when the engine can tell.40 public var hint: String?4142 public init(_ severity: Severity, _ code: String, _ message: String, at range: FlowRange, hint: String? = nil) {43 self.severity = severity; self.code = code; self.message = message; self.range = range; self.hint = hint44 }4546 public var description: String {47 "\(range.start.line):\(range.start.column): \(severity.rawValue): \(message) [\(code)]" + (hint.map { " — \($0)" } ?? "")48 }49}5051/// One piece of a string literal: literal text or an interpolated name path (`{article.title}`).52public enum FlowStringPart: Hashable, Sendable {53 case text(String)54 case interpolation(path: [String], range: FlowRange)55}5657public enum FlowTokenKind: Hashable, Sendable {58 case identifier(String)59 case string([FlowStringPart])60 case number(Double)61 /// A number with a unit (`ms`, `s`, `m`), in seconds.62 case duration(Double)63 case symbol(String)64 case newline65 case comment(String)66 case invalid67 case end68}6970public struct FlowToken: Hashable, Sendable {71 public var kind: FlowTokenKind72 public var range: FlowRange7374 var identifier: String? { if case .identifier(let name) = kind { return name } else { return nil } }75 func isSymbol(_ text: String) -> Bool { kind == .symbol(text) }76 func isWord(_ text: String) -> Bool { kind == .identifier(text) }77 var isTerminator: Bool {78 switch kind {79 case .newline, .end: return true80 case .symbol(let text): return text == ";" || text == "}"81 default: return false82 }83 }84}8586public enum FlowKeywords {87 /// Words with a fixed meaning; none of them can name a parameter, a variable or a collection.88 public static let reserved: Set<String> = [89 "flow", "version", "param", "allow", "domains", "limit", "steps", "duration", "timeout", "space",90 "let", "for", "in", "parallel", "if", "else", "collect", "into", "as", "and", "or", "not", "true", "false",91 ]92 public static let typeNames = ["text", "number", "bool", "url"]93}9495/// Turns source text into tokens. Never fails: anything it cannot read becomes an `.invalid` token plus a96/// diagnostic, and lexing continues.97struct FlowLexer {98 private let scalars: [Unicode.Scalar]99 private var index = 0100 private var position = FlowPosition.start101 private(set) var diagnostics: [FlowDiagnostic] = []102 private(set) var tokens: [FlowToken] = []103104 static let maximumNumberLength = 18105106 init(_ source: String) { scalars = Array(source.unicodeScalars) }107108 static func tokenize(_ source: String) -> (tokens: [FlowToken], diagnostics: [FlowDiagnostic]) {109 var lexer = FlowLexer(source)110 lexer.run()111 return (lexer.tokens, lexer.diagnostics)112 }113114 private var current: Unicode.Scalar? { index < scalars.count ? scalars[index] : nil }115 private func peek(_ distance: Int = 1) -> Unicode.Scalar? {116 index + distance < scalars.count ? scalars[index + distance] : nil117 }118119 private mutating func advance() {120 guard let scalar = current else { return }121 index += 1122 position.offset += scalar.utf16.count123 if scalar == "\n" {124 position.line += 1125 position.column = 1126 } else {127 position.column += scalar.utf16.count128 }129 }130131 private static func isIdentifierStart(_ scalar: Unicode.Scalar) -> Bool {132 scalar == "_" || scalar.properties.isAlphabetic133 }134135 private static func isIdentifierPart(_ scalar: Unicode.Scalar) -> Bool {136 isIdentifierStart(scalar) || isDigit(scalar)137 }138139 private static func isDigit(_ scalar: Unicode.Scalar) -> Bool { scalar.value >= 48 && scalar.value <= 57 }140141 private mutating func emit(_ kind: FlowTokenKind, from start: FlowPosition) {142 tokens.append(FlowToken(kind: kind, range: FlowRange(start: start, end: position)))143 }144145 private mutating func report(_ code: String, _ message: String, from start: FlowPosition, hint: String? = nil) {146 diagnostics.append(FlowDiagnostic(.error, code, message, at: FlowRange(start: start, end: position), hint: hint))147 }148149 mutating func run() {150 while let scalar = current {151 let start = position152 if scalar == "\n" {153 advance()154 emit(.newline, from: start)155 } else if scalar == "\r" || scalar == " " || scalar == "\t" || scalar.properties.isWhitespace {156 advance()157 } else if scalar == "#" {158 var text = ""159 advance()160 while let next = current, next != "\n" { text.unicodeScalars.append(next); advance() }161 emit(.comment(text.trimmingCharacters(in: .whitespaces)), from: start)162 } else if scalar == "\"" {163 lexString()164 } else if Self.isDigit(scalar) {165 lexNumber()166 } else if Self.isIdentifierStart(scalar) {167 var name = ""168 while let next = current, Self.isIdentifierPart(next) { name.unicodeScalars.append(next); advance() }169 emit(.identifier(name), from: start)170 } else {171 lexSymbol(scalar)172 }173 }174 tokens.append(FlowToken(kind: .end, range: FlowRange(at: position)))175 }176177 private mutating func lexSymbol(_ scalar: Unicode.Scalar) {178 let start = position179 let two = peek().map { String(scalar) + String($0) }180 if let two, ["==", "!=", "<=", ">="].contains(two) {181 advance(); advance()182 emit(.symbol(two), from: start)183 } else if "{}()[],:;.=<>".unicodeScalars.contains(scalar) {184 advance()185 emit(.symbol(String(scalar)), from: start)186 } else {187 advance()188 report("unexpected-character", "Unexpected character “\(scalar)”.", from: start,189 hint: "Remove it. Text goes between double quotes; comments start with #.")190 emit(.invalid, from: start)191 }192 }193194 private mutating func lexNumber() {195 let start = position196 var text = ""197 while let next = current, Self.isDigit(next) { text.unicodeScalars.append(next); advance() }198 if current == ".", let after = peek(), Self.isDigit(after) {199 text.append(".")200 advance()201 while let next = current, Self.isDigit(next) { text.unicodeScalars.append(next); advance() }202 }203 var unit = ""204 while let next = current, Self.isIdentifierPart(next) { unit.unicodeScalars.append(next); advance() }205 guard text.count <= Self.maximumNumberLength, let value = Double(text), value.isFinite else {206 report("invalid-number", "This number is too long.", from: start, hint: "Use at most \(Self.maximumNumberLength) digits.")207 emit(.invalid, from: start)208 return209 }210 switch unit {211 case "": emit(.number(value), from: start)212 case "ms": emit(.duration(value / 1_000), from: start)213 case "s": emit(.duration(value), from: start)214 case "m": emit(.duration(value * 60), from: start)215 default:216 report("invalid-unit", "Unknown unit “\(unit)”.", from: start, hint: "Durations use ms, s or m, as in 500ms, 30s, 5m.")217 emit(.invalid, from: start)218 }219 }220221 private mutating func lexString() {222 let start = position223 advance() // opening quote224 var parts: [FlowStringPart] = []225 var text = ""226 var closed = false227 func flush(_ parts: inout [FlowStringPart], _ text: inout String) {228 if !text.isEmpty { parts.append(.text(text)); text = "" }229 }230 loop: while let scalar = current {231 switch scalar {232 case "\"":233 advance()234 closed = true235 break loop236 case "\n":237 break loop238 case "\\":239 let escapeStart = position240 advance()241 guard let escaped = current, escaped != "\n" else { break loop }242 advance()243 switch escaped {244 case "n": text.append("\n")245 case "t": text.append("\t")246 case "\"", "\\", "{", "}": text.unicodeScalars.append(escaped)247 default:248 report("invalid-escape", "Unknown escape “\\\(escaped)”.", from: escapeStart,249 hint: "Valid escapes: \\\" \\\\ \\n \\t \\{ \\}.")250 }251 case "{":252 let braceStart = position253 advance()254 var path: [String] = []255 var name = ""256 var valid = true257 var terminated = false258 while let next = current, next != "\n", next != "\"" {259 advance()260 if next == "}" { terminated = true; break }261 if next == "." {262 if name.isEmpty { valid = false }263 path.append(name); name = ""264 } else if Self.isIdentifierPart(next), !(name.isEmpty && Self.isDigit(next)) {265 name.unicodeScalars.append(next)266 } else {267 valid = false268 }269 }270 path.append(name)271 if !terminated || !valid || path.contains("") {272 report("invalid-interpolation", "This {…} is not a name.", from: braceStart,273 hint: "Write {name} or {name.field}; write \\{ for a literal brace.")274 } else {275 flush(&parts, &text)276 parts.append(.interpolation(path: path, range: FlowRange(start: braceStart, end: position)))277 }278 case "}":279 let braceStart = position280 advance()281 report("invalid-interpolation", "Unmatched “}” in text.", from: braceStart, hint: "Write \\} for a literal brace.")282 default:283 text.unicodeScalars.append(scalar)284 advance()285 }286 }287 flush(&parts, &text)288 if !closed {289 report("unterminated-string", "This text is not closed.", from: start, hint: "Add a closing double quote on the same line.")290 }291 emit(.string(parts), from: start)292 }293}294