SPB Git

Repository Public License

FlowParser.swift 33.7 KB 718 lines swift

1// FlowEngine — recursive-descent parser: tokens → FlowProgram, with error recovery.2import Foundation34/// Parses a workflow. Total: any input produces a (possibly partial) tree and a list of diagnostics, never a5/// crash. Nesting is bounded so hostile input cannot exhaust the stack.6struct FlowParser {7    static let maximumBlockDepth = 88    static let maximumExpressionDepth = 329    static let maximumChainLength = 3210    static let maximumSourceUTF8Bytes = 256 * 102411    static let maximumStatements = 2_0001213    private let tokens: [FlowToken]14    private let registry: FlowActionRegistry15    private var index = 016    private var blockDepth = 017    private var expressionDepth = 018    private var statementCount = 019    private(set) var diagnostics: [FlowDiagnostic]20    private var reported = Set<String>()21    private var reachedDiagnosticLimit = false22    static let maximumDiagnostics = 2002324    struct Output {25        var program: FlowProgram26        var diagnostics: [FlowDiagnostic]27        var tokens: [FlowToken]28    }2930    static func parse(_ source: String, registry: FlowActionRegistry) -> Output {31        guard source.utf8.count <= maximumSourceUTF8Bytes else {32            let range = FlowRange(at: .start)33            let program = FlowProgram(name: "", nameRange: range, version: 0, headerComments: [], parameters: [], domains: [],34                                      domainComments: [], limits: [], limitComments: [], spaceName: nil, bodyComments: [],35                                      body: FlowBlock(statements: [], trailingComments: [], range: range))36            let diagnostic = FlowDiagnostic(.error, "source-too-large", "This workflow is larger than \(maximumSourceUTF8Bytes / 1024) KB.",37                                            at: range, hint: "Split it into several workflows.")38            return Output(program: program, diagnostics: [diagnostic], tokens: [])39        }40        let lexed = FlowLexer.tokenize(source)41        var parser = FlowParser(tokens: lexed.tokens, registry: registry, diagnostics: Array(lexed.diagnostics.prefix(maximumDiagnostics)))42        let program = parser.parseProgram()43        return Output(program: program, diagnostics: parser.diagnostics.sorted { $0.range.start < $1.range.start }, tokens: lexed.tokens)44    }4546    private init(tokens: [FlowToken], registry: FlowActionRegistry, diagnostics: [FlowDiagnostic]) {47        self.tokens = tokens; self.registry = registry; self.diagnostics = diagnostics48    }4950    // MARK: Token access5152    private var current: FlowToken { tokens[min(index, tokens.count - 1)] }53    private func peek(_ distance: Int = 1) -> FlowToken { tokens[min(index + distance, tokens.count - 1)] }54    private var atEnd: Bool { current.kind == .end }55    private var previousEnd: FlowPosition { index > 0 ? tokens[min(index, tokens.count) - 1].range.end : .start }5657    private mutating func advance() { if index < tokens.count - 1 { index += 1 } }5859    private mutating func error(_ code: String, _ message: String, at range: FlowRange, hint: String? = nil) {60        // One diagnostic per position is enough (recovery can revisit a token), and a hostile input must not61        // be able to produce an unbounded list.62        guard reported.insert("\(range.start.offset):\(code)").inserted else { return }63        guard diagnostics.count < Self.maximumDiagnostics else {64            if !reachedDiagnosticLimit {65                reachedDiagnosticLimit = true66                diagnostics.append(FlowDiagnostic(.error, "too-many-errors", "Too many errors; the rest are not listed.", at: range,67                                                  hint: "Fix the first errors, the others often disappear."))68            }69            return70        }71        diagnostics.append(FlowDiagnostic(.error, code, message, at: range, hint: hint))72    }7374    /// Skips newlines, `;` and comments; returns the comments.75    private mutating func skipTrivia() -> [String] {76        var comments: [String] = []77        while true {78            switch current.kind {79            case .newline: advance()80            case .symbol(";"): advance()81            case .comment(let text): comments.append(text); advance()82            default: return comments83            }84        }85    }8687    private mutating func skipCommentsOnLine() {88        while case .comment = current.kind { advance() }89    }9091    /// Recovery: drop the rest of the statement.92    private mutating func skipToStatementEnd() {93        var depth = 094        while !atEnd {95            if current.isSymbol("{") { depth += 1 }96            if current.isSymbol("}") { if depth == 0 { return }; depth -= 1 }97            if depth == 0, current.kind == .newline || current.isSymbol(";") { return }98            advance()99        }100    }101102    private mutating func expectWord(_ word: String, hint: String) -> Bool {103        if current.isWord(word) { advance(); return true }104        error("expected-keyword", "Expected “\(word)”.", at: current.range, hint: hint)105        return false106    }107108    private mutating func expectSymbol(_ symbol: String, hint: String) -> Bool {109        if current.isSymbol(symbol) { advance(); return true }110        error("expected-symbol", "Expected “\(symbol)”.", at: current.range, hint: hint)111        return false112    }113114    private mutating func plainString(_ what: String, hint: String) -> (String, FlowRange)? {115        if case .string(let parts) = current.kind {116            let token = current117            advance()118            let literal = FlowStringLiteral(parts: parts, range: token.range)119            guard let text = literal.plainText else {120                error("interpolation-not-allowed", "\(what) cannot contain {…}.", at: token.range, hint: "Write the text literally.")121                return ("", token.range)122            }123            return (text, token.range)124        }125        error("expected-text", "Expected \(what.lowercased()) between double quotes.", at: current.range, hint: hint)126        return nil127    }128129    private mutating func integer(_ what: String, hint: String) -> (Int, FlowRange)? {130        if case .number(let value) = current.kind {131            let range = current.range132            advance()133            guard value == value.rounded(), value >= 0, value <= 1_000_000_000 else {134                error("expected-integer", "\(what) must be a whole number.", at: range, hint: hint)135                return nil136            }137            return (Int(value), range)138        }139        error("expected-integer", "Expected a whole number for \(what.lowercased()).", at: current.range, hint: hint)140        return nil141    }142143    // MARK: Program144145    private mutating func parseProgram() -> FlowProgram {146        let headerComments = skipTrivia()147        var name = "", nameRange = FlowRange(at: current.range.start), version = 0148        if expectWord("flow", hint: "A workflow starts with: flow \"Name\" version 1") {149            if let (text, range) = plainString("The workflow name", hint: "Example: flow \"Morning news\" version 1") {150                name = text; nameRange = range151                if text.trimmingCharacters(in: .whitespaces).isEmpty {152                    error("empty-name", "The workflow needs a name.", at: range, hint: "Put a name between the quotes.")153                }154            }155            if expectWord("version", hint: "Add: version 1"),156               let (number, _) = integer("The version", hint: "The language version is 1.") {157                version = number158            }159            if !current.isTerminator, !isComment(current) {160                error("unexpected-token", "Unexpected text after the header.", at: current.range, hint: "Start a new line.")161                skipToStatementEnd()162            }163        } else {164            skipToStatementEnd()165        }166167        var parameters: [FlowParameterDeclaration] = []168        var domains: [FlowDomainLiteral] = [], domainComments: [String] = []169        var limits: [FlowLimitDeclaration] = [], limitComments: [String] = []170        var comments = skipTrivia()171        declarations: while !atEnd {172            guard let word = current.identifier else { break }173            switch word {174            case "param":175                if let parameter = parseParameter(comments: comments) { parameters.append(parameter) }176            case "allow":177                domainComments += comments178                domains += parseDomains()179            case "limit":180                // `limit` also appears inside `for … limit`, never at the start of a statement.181                limitComments += comments182                limits += parseLimits()183            default:184                break declarations185            }186            if !current.isTerminator, !isComment(current) {187                error("unexpected-token", "Unexpected text at the end of this line.", at: current.range, hint: "Start a new line.")188                skipToStatementEnd()189            }190            comments = skipTrivia()191        }192193        var spaceName: String?194        var body: FlowBlock195        if current.isWord("space") {196            advance()197            if let (text, range) = plainString("The space name", hint: "Example: space \"Research\" { … }") {198                spaceName = text199                if text.trimmingCharacters(in: .whitespaces).isEmpty {200                    error("empty-name", "The space needs a name.", at: range, hint: "Put a name between the quotes.")201                }202            }203            body = parseBlock()204            let trailing = skipTrivia()205            body.trailingComments += trailing206            if !atEnd {207                error("unexpected-token", "Nothing can follow the space block.", at: current.range,208                      hint: "Move these lines inside the braces of the space.")209            }210        } else {211            body = parseStatements(until: nil, leading: [])212            // Comments read while looking for declarations belong to the first statement.213            if !comments.isEmpty {214                if body.statements.isEmpty { body.trailingComments = comments + body.trailingComments }215                else { body.statements[0].comments = comments + body.statements[0].comments }216            }217            comments = []218        }219        return FlowProgram(name: name, nameRange: nameRange, version: version, headerComments: headerComments,220                           parameters: parameters, domains: domains, domainComments: domainComments, limits: limits,221                           limitComments: limitComments, spaceName: spaceName, bodyComments: comments, body: body)222    }223224    private func isComment(_ token: FlowToken) -> Bool { if case .comment = token.kind { return true } else { return false } }225226    private mutating func parseParameter(comments: [String]) -> FlowParameterDeclaration? {227        let start = current.range.start228        advance()   // param229        guard let name = current.identifier else {230            error("expected-name", "Expected a parameter name.", at: current.range, hint: "Example: param topic: text")231            skipToStatementEnd()232            return nil233        }234        let nameRange = current.range235        advance()236        guard expectSymbol(":", hint: "Example: param \(name): text") else { skipToStatementEnd(); return nil }237        guard let typeName = current.identifier else {238            error("expected-type", "Expected a type.", at: current.range, hint: "Parameter types: text, number, bool, url.")239            skipToStatementEnd()240            return nil241        }242        let typeRange = current.range243        advance()244        var defaultValue: FlowExpression?245        if current.isSymbol("=") {246            advance()247            defaultValue = parseExpression()248        }249        return FlowParameterDeclaration(name: name, nameRange: nameRange, typeName: typeName, typeRange: typeRange,250                                        defaultValue: defaultValue, comments: comments,251                                        range: FlowRange(start: start, end: previousEnd))252    }253254    private mutating func parseDomains() -> [FlowDomainLiteral] {255        advance()   // allow256        guard expectWord("domains", hint: "Example: allow domains \"wikipedia.org\", \"arxiv.org\"") else {257            skipToStatementEnd()258            return []259        }260        var result: [FlowDomainLiteral] = []261        repeat {262            if current.isSymbol(",") { advance() }263            guard let (text, range) = plainString("A domain", hint: "Example: allow domains \"wikipedia.org\"") else {264                skipToStatementEnd()265                return result266            }267            result.append(FlowDomainLiteral(domain: text, range: range))268        } while current.isSymbol(",")269        return result270    }271272    private mutating func parseLimits() -> [FlowLimitDeclaration] {273        advance()   // limit274        var result: [FlowLimitDeclaration] = []275        repeat {276            if current.isSymbol(",") { advance() }277            let start = current.range.start278            guard let word = current.identifier, let kind = FlowLimitDeclaration.Kind(rawValue: word) else {279                error("unknown-limit", "Expected steps, duration or timeout.", at: current.range,280                      hint: "Example: limit steps 40, duration 300s, timeout 20s")281                skipToStatementEnd()282                return result283            }284            advance()285            switch (kind, current.kind) {286            case (.steps, .number(let value)) where value == value.rounded():287                advance()288                result.append(FlowLimitDeclaration(kind: kind, value: value, range: FlowRange(start: start, end: previousEnd)))289            case (.duration, .duration(let seconds)), (.timeout, .duration(let seconds)):290                advance()291                result.append(FlowLimitDeclaration(kind: kind, value: seconds, range: FlowRange(start: start, end: previousEnd)))292            default:293                error("invalid-limit", kind == .steps ? "“steps” takes a whole number." : "“\(kind.rawValue)” takes a duration.",294                      at: current.range, hint: kind == .steps ? "Example: limit steps 40" : "Example: limit \(kind.rawValue) 30s")295                skipToStatementEnd()296                return result297            }298        } while current.isSymbol(",")299        return result300    }301302    // MARK: Statements303304    private mutating func parseBlock() -> FlowBlock {305        let start = current.range.start306        guard current.isSymbol("{") else {307            error("expected-block", "Expected “{”.", at: current.range, hint: "Statements of a block go between { and }.")308            return FlowBlock(statements: [], trailingComments: [], range: FlowRange(at: start))309        }310        advance()311        blockDepth += 1312        defer { blockDepth -= 1 }313        if blockDepth > Self.maximumBlockDepth {314            error("nesting-too-deep", "Blocks are nested more than \(Self.maximumBlockDepth) levels deep.", at: FlowRange(at: start),315                  hint: "Flatten the workflow.")316            // Skip the over-deep block without descending.317            var depth = 1318            while !atEnd, depth > 0 {319                if current.isSymbol("{") { depth += 1 }320                if current.isSymbol("}") { depth -= 1 }321                advance()322            }323            return FlowBlock(statements: [], trailingComments: [], range: FlowRange(start: start, end: previousEnd))324        }325        var block = parseStatements(until: "}", leading: [])326        if current.isSymbol("}") {327            advance()328        } else {329            error("unclosed-block", "This block is not closed.", at: FlowRange(at: start), hint: "Add a closing }.")330        }331        block.range = FlowRange(start: start, end: previousEnd)332        return block333    }334335    private mutating func parseStatements(until closer: String?, leading: [String]) -> FlowBlock {336        let start = current.range.start337        var statements: [FlowStatement] = []338        var comments = leading + skipTrivia()339        while !atEnd {340            if let closer, current.isSymbol(closer) { break }341            if current.isSymbol("}") {342                error("unexpected-token", "Unmatched “}”.", at: current.range, hint: "Remove it.")343                advance()344                comments += skipTrivia()345                continue346            }347            let before = index348            statementCount += 1349            if statementCount > Self.maximumStatements {350                error("too-many-statements", "A workflow holds at most \(Self.maximumStatements) statements.", at: current.range,351                      hint: "Split it into several workflows.")352                while !atEnd { advance() }353                break354            }355            if let kind = parseStatement() {356                statements.append(FlowStatement(kind: kind, comments: comments))357                comments = []358            }359            skipCommentsOnLine()360            if !current.isTerminator {361                error("unexpected-token", "Unexpected text at the end of this statement.", at: current.range,362                      hint: "Put each statement on its own line, or separate statements with “;”.")363                skipToStatementEnd()364            }365            if index == before { advance() }   // always make progress366            comments += skipTrivia()367        }368        return FlowBlock(statements: statements, trailingComments: comments, range: FlowRange(start: start, end: previousEnd))369    }370371    private mutating func parseStatement() -> FlowStatementKind? {372        let start = current.range.start373        guard let word = current.identifier else {374            error("expected-statement", "Expected a statement.", at: current.range,375                  hint: "A statement starts with an action (open, extract…), let, for, parallel, if or collect.")376            skipToStatementEnd()377            return nil378        }379        switch word {380        case "let":381            advance()382            guard let name = current.identifier else {383                error("expected-name", "Expected a name after “let”.", at: current.range, hint: "Example: let query = \"swift\"")384                skipToStatementEnd()385                return nil386            }387            let nameRange = current.range388            advance()389            guard expectSymbol("=", hint: "Example: let \(name) = \"value\"") else { skipToStatementEnd(); return nil }390            let value = parseExpression()391            return .let_(FlowLetStatement(name: name, nameRange: nameRange, value: value, range: FlowRange(start: start, end: previousEnd)))392        case "for":393            advance()394            guard let variable = current.identifier else {395                error("expected-name", "Expected a name after “for”.", at: current.range, hint: "Example: for link in links limit 5 { … }")396                skipToStatementEnd()397                return nil398            }399            let variableRange = current.range400            advance()401            guard expectWord("in", hint: "Example: for \(variable) in links limit 5 { … }") else { skipToStatementEnd(); return nil }402            let sequence = parseExpression()403            var limit: Int?, limitRange: FlowRange?, width: Int?404            if current.isWord("limit") {405                advance()406                if let (value, range) = integer("The loop limit", hint: "Example: limit 5") { limit = value; limitRange = range }407            } else {408                error("unbounded-loop", "A loop needs a limit.", at: FlowRange(start: start, end: previousEnd),409                      hint: "Add “limit N” before the block, for example: for \(variable) in … limit 10 { … }")410            }411            if current.isWord("parallel") {412                advance()413                if let (value, _) = integer("The parallel width", hint: "Example: parallel 3") { width = value }414            }415            let body = parseBlock()416            return .forEach(FlowForStatement(variable: variable, variableRange: variableRange, sequence: sequence, limit: limit,417                                             limitRange: limitRange, parallelWidth: width, body: body,418                                             range: FlowRange(start: start, end: previousEnd)))419        case "parallel":420            advance()421            var width: Int?, widthRange: FlowRange?422            if current.isWord("limit") {423                advance()424                if let (value, range) = integer("The parallel limit", hint: "Example: parallel limit 3 { … }") { width = value; widthRange = range }425            } else {426                error("unbounded-parallel", "“parallel” needs a limit.", at: FlowRange(start: start, end: previousEnd),427                      hint: "Write: parallel limit 3 { … }")428            }429            let body = parseBlock()430            return .parallel(FlowParallelStatement(width: width, widthRange: widthRange, body: body,431                                                   range: FlowRange(start: start, end: previousEnd)))432        case "if":433            return parseIf()434        case "collect":435            advance()436            let value = parseExpression()437            guard expectWord("into", hint: "Example: collect item into sources") else { skipToStatementEnd(); return nil }438            guard let target = current.identifier else {439                error("expected-name", "Expected a collection name after “into”.", at: current.range, hint: "Example: collect item into sources")440                skipToStatementEnd()441                return nil442            }443            let targetRange = current.range444            advance()445            return .collect(FlowCollectStatement(value: value, target: target, targetRange: targetRange,446                                                 range: FlowRange(start: start, end: previousEnd)))447        case "else":448            error("unexpected-token", "“else” without “if”.", at: current.range, hint: "Put else right after the closing } of an if block.")449            skipToStatementEnd()450            return nil451        default:452            return parseAction()453        }454    }455456    private mutating func parseIf() -> FlowStatementKind {457        let start = current.range.start458        advance()   // if459        let condition = parseExpression()460        let thenBlock = parseBlock()461        var elseBlock: FlowBlock?462        // `else` may sit on the line after the closing brace.463        var lookahead = index464        while tokens[min(lookahead, tokens.count - 1)].kind == .newline, lookahead < tokens.count - 1 { lookahead += 1 }465        if tokens[min(lookahead, tokens.count - 1)].isWord("else") {466            index = lookahead467            advance()468            if current.isWord("if") {469                blockDepth += 1470                defer { blockDepth -= 1 }471                let nestedStart = current.range.start472                if blockDepth > Self.maximumBlockDepth {473                    error("nesting-too-deep", "Too many chained “else if”.", at: current.range, hint: "Flatten the workflow.")474                    skipToStatementEnd()475                } else {476                    let nested = parseIf()477                    let range = FlowRange(start: nestedStart, end: previousEnd)478                    elseBlock = FlowBlock(statements: [FlowStatement(kind: nested, comments: [])], trailingComments: [], range: range)479                }480            } else {481                elseBlock = parseBlock()482            }483        }484        return .conditional(FlowIfStatement(condition: condition, thenBlock: thenBlock, elseBlock: elseBlock,485                                            range: FlowRange(start: start, end: previousEnd)))486    }487488    private mutating func parseAction() -> FlowStatementKind? {489        let start = current.range.start490        guard let first = current.identifier else { return nil }491        var name = first492        var nameRange = current.range493        if let second = peek().identifier, registry.definition(named: "\(first) \(second)") != nil {494            name = "\(first) \(second)"495            nameRange = nameRange.union(peek().range)496            advance()497        }498        advance()499        guard let definition = registry.definition(named: name) else {500            let candidates = registry.names + ["let", "for", "parallel", "if", "collect"]501            let suggestion = FlowText.closest(to: name, in: candidates)502            let partial = registry.firstWords.contains(first)503                ? registry.names.filter { $0.hasPrefix(first + " ") }.joined(separator: ", ") : ""504            error("unknown-action", "Unknown action “\(name)”.", at: nameRange,505                  hint: !partial.isEmpty ? "Did you mean: \(partial)?" : suggestion.map { "Did you mean “\($0)”?" }506                    ?? "Actions: \(registry.names.joined(separator: ", ")).")507            skipToStatementEnd()508            return .action(FlowActionStatement(name: name, nameRange: nameRange, arguments: [], binding: nil, bindingRange: nil,509                                               range: FlowRange(start: start, end: previousEnd)))510        }511        var arguments: [FlowArgument] = []512        var binding: String?, bindingRange: FlowRange?513        let labels = Set(definition.labels)514        func startsValue(_ token: FlowToken) -> Bool {515            switch token.kind {516            case .identifier, .string, .number, .duration: return true517            case .symbol(let text): return text == "(" || text == "["518            default: return false519            }520        }521        while !current.isTerminator, !isComment(current) {522            if let word = current.identifier, word == "as", !definition.usesAsLabel {523                advance()524                if let target = current.identifier {525                    binding = target526                    bindingRange = current.range527                    advance()528                } else {529                    error("expected-name", "Expected a name after “as”.", at: current.range, hint: "Example: \(name) … as result")530                }531                break532            }533            if let word = current.identifier, labels.contains(word), startsValue(peek()) {534                let labelRange = current.range535                advance()536                arguments.append(FlowArgument(label: word, labelRange: labelRange, value: parseExpression()))537            } else if arguments.isEmpty, startsValue(current) {538                arguments.append(FlowArgument(label: nil, labelRange: nil, value: parseExpression()))539            } else {540                let expected = definition.labels.isEmpty ? "" : " Expected one of: \(definition.labels.joined(separator: ", "))."541                error("unexpected-argument", "“\(name)” cannot take this here.\(expected)", at: current.range,542                      hint: "Usage: \(definition.signature)")543                skipToStatementEnd()544                break545            }546        }547        return .action(FlowActionStatement(name: name, nameRange: nameRange, arguments: arguments, binding: binding,548                                           bindingRange: bindingRange, range: FlowRange(start: start, end: previousEnd)))549    }550551    // MARK: Expressions552553    private mutating func parseExpression() -> FlowExpression {554        expressionDepth += 1555        defer { expressionDepth -= 1 }556        if expressionDepth > Self.maximumExpressionDepth {557            let range = current.range558            error("nesting-too-deep", "This expression is nested too deeply.", at: range, hint: "Split it with “let”.")559            skipToStatementEnd()560            return .invalid(range)561        }562        return parseOr()563    }564565    private mutating func parseOr() -> FlowExpression {566        var left = parseAnd()567        var operands = 1568        while current.isWord("or") {569            advance()570            let right = parseAnd()571            left = .binary(.or, left, right, left.range.union(right.range))572            operands += 1573            if operands > Self.maximumChainLength { return chainTooLong(left) }574        }575        return left576    }577578    private mutating func parseAnd() -> FlowExpression {579        var left = parseNot()580        var operands = 1581        while current.isWord("and") {582            advance()583            let right = parseNot()584            left = .binary(.and, left, right, left.range.union(right.range))585            operands += 1586            if operands > Self.maximumChainLength { return chainTooLong(left) }587        }588        return left589    }590591    /// Chains build left-deep trees; an unbounded chain would make every later tree walk recurse without limit.592    private mutating func chainTooLong(_ expression: FlowExpression) -> FlowExpression {593        error("nesting-too-deep", "This expression chains more than \(Self.maximumChainLength) parts.", at: FlowRange(at: current.range.start),594              hint: "Split it with “let”.")595        skipToStatementEnd()596        return .invalid(expression.range)597    }598599    private mutating func parseNot() -> FlowExpression {600        if current.isWord("not") {601            let start = current.range602            advance()603            expressionDepth += 1604            defer { expressionDepth -= 1 }605            if expressionDepth > Self.maximumExpressionDepth {606                error("nesting-too-deep", "This expression is nested too deeply.", at: start, hint: "Split it with “let”.")607                skipToStatementEnd()608                return .invalid(start)609            }610            let operand = parseNot()611            return .not(operand, start.union(operand.range))612        }613        return parseComparison()614    }615616    private mutating func parseComparison() -> FlowExpression {617        let left = parsePrimary()618        if case .symbol(let text) = current.kind, let op = FlowBinaryOperator(rawValue: text), op != .and, op != .or {619            advance()620            let right = parsePrimary()621            return .binary(op, left, right, left.range.union(right.range))622        }623        if current.isSymbol("=") {624            error("unexpected-token", "“=” is not a comparison.", at: current.range, hint: "Use “==” to compare.")625            advance()626            _ = parsePrimary()627        }628        return left629    }630631    private mutating func parsePrimary() -> FlowExpression {632        let token = current633        var expression: FlowExpression634        switch token.kind {635        case .string(let parts):636            advance()637            expression = .string(FlowStringLiteral(parts: parts, range: token.range))638        case .number(let value):639            advance()640            expression = .number(value, token.range)641        case .duration(let seconds):642            advance()643            expression = .duration(seconds, token.range)644        case .identifier("true"):645            advance()646            expression = .bool(true, token.range)647        case .identifier("false"):648            advance()649            expression = .bool(false, token.range)650        case .identifier(let name):651            advance()652            if current.isSymbol("("), current.range.start == token.range.end {653                advance()654                var arguments: [FlowExpression] = []655                while !current.isSymbol(")"), !current.isTerminator {656                    arguments.append(parseExpression())657                    if current.isSymbol(",") { advance() } else { break }658                }659                if !expectSymbol(")", hint: "Close the parenthesis of \(name)(…).") { skipToStatementEnd() }660                expression = .call(name, arguments, FlowRange(start: token.range.start, end: previousEnd))661            } else {662                expression = .identifier(name, token.range)663            }664        case .symbol("("):665            advance()666            expression = parseExpression()667            if !expectSymbol(")", hint: "Close the parenthesis.") { skipToStatementEnd() }668        case .symbol("["):669            advance()670            var items: [FlowExpression] = []671            while !current.isSymbol("]"), !current.isTerminator {672                items.append(parseExpression())673                if current.isSymbol(",") { advance() } else { break }674            }675            if !expectSymbol("]", hint: "Close the list with ].") { skipToStatementEnd() }676            expression = .list(items, FlowRange(start: token.range.start, end: previousEnd))677        default:678            error("expected-value", "Expected a value.", at: token.range,679                  hint: "A value is text in quotes, a number, a name, a list [a, b] or a function call such as count(items).")680            // Do not consume a terminator: the statement loop needs it.681            if !token.isTerminator { advance() }682            return .invalid(token.range)683        }684        var depth = 0685        while current.isSymbol("."), let member = peek().identifier {686            let end = peek().range.end687            advance(); advance()688            expression = .member(expression, member, FlowRange(start: expression.range.start, end: end))689            depth += 1690            if depth > Self.maximumChainLength { return chainTooLong(expression) }691        }692        return expression693    }694}695696enum FlowText {697    /// The candidate closest to `word` by edit distance, if it is close enough to be a plausible typo.698    static func closest(to word: String, in candidates: some Sequence<String>) -> String? {699        let target = Array(word.lowercased().unicodeScalars.prefix(40))700        var best: (name: String, distance: Int)?701        for candidate in candidates {702            let other = Array(candidate.lowercased().unicodeScalars.prefix(40))703            var previous = Array(0...other.count)704            for (i, a) in target.enumerated() {705                var row = [i + 1] + Array(repeating: 0, count: other.count)706                for (j, b) in other.enumerated() {707                    row[j + 1] = Swift.min(previous[j] + (a == b ? 0 : 1), previous[j + 1] + 1, row[j] + 1)708                }709                previous = row710            }711            let distance = previous[other.count]712            if distance < (best?.distance ?? Int.max), candidate != word { best = (candidate, distance) }713        }714        guard let best, best.distance <= max(1, target.count / 3) else { return nil }715        return best.name716    }717}718
Files main
Menu

Theme