Repository Public License
1import Foundation2import Testing3@testable import FlowEngine45@Suite struct FlowParserTests {6 @Test func parsesTheResearchBriefIntoATypedTree() throws {7 let program = try validated(briefSource)8 let tree = program.program9 #expect(tree.name == "Research brief" && tree.version == 1 && tree.spaceName == "Research")10 #expect(tree.parameters.map(\.name) == ["topic"] && tree.parameters[0].typeName == "text")11 #expect(tree.domains.map(\.domain) == ["wikipedia.org", "arxiv.org"])12 #expect(tree.limits.map(\.kind) == [.steps, .duration, .timeout] && tree.limits.map(\.value) == [40, 300, 30])13 #expect(tree.headerComments.count == 2)14 #expect(tree.body.statements.count == 5)15 guard case .action(let open) = tree.body.statements[0].kind else { Issue.record("expected an action"); return }16 #expect(open.name == "open" && open.binding == "wiki" && open.arguments.count == 1 && open.arguments[0].label == nil)17 guard case .string(let literal) = open.arguments[0].value else { Issue.record("expected a string"); return }18 #expect(literal.parts.count == 2)19 guard case .interpolation(let path, let range) = literal.parts[1] else { Issue.record("expected interpolation"); return }20 #expect(path == ["topic"])21 #expect(range.start.line == 11 && range.start.column == 41)22 guard case .action(let extract) = tree.body.statements[1].kind else { Issue.record("expected an action"); return }23 #expect(extract.name == "extract article" && extract.arguments[0].label == "from" && extract.binding == "overview")24 guard case .forEach(let loop) = tree.body.statements[3].kind else { Issue.record("expected a loop"); return }25 #expect(loop.variable == "link" && loop.limit == 5 && loop.parallelWidth == 3 && loop.body.statements.count == 4)26 #expect(tree.body.statements[3].comments == ["Only links that stay on the allowed domains are followed."])27 guard case .conditional(let branch) = tree.body.statements[4].kind else { Issue.record("expected an if"); return }28 guard case .binary(.greater, .call("count", _, _), .number(0, _), _) = branch.condition else { Issue.record("expected count(…) > 0"); return }29 guard case .action(let export) = branch.thenBlock.statements[1].kind else { Issue.record("expected export"); return }30 #expect(export.arguments.map(\.label) == [nil, "as", "to"] && export.binding == nil)31 #expect(program.limits == FlowLimits(maximumSteps: 40, maximumDurationSeconds: 300, stepTimeoutSeconds: 30))32 #expect(program.capabilities == [.navigate, .read, .ai, .writeFile])33 #expect(program.collections == ["sources": .list(.article)])34 // open + extract + 5 × (open, extract, close) + summarize + export35 #expect(program.worstCaseSteps == 19)36 }3738 @Test func sourceRangesUseUTF16OffsetsAndOneBasedLinesAndColumns() {39 let source = "flow \"Émoji 🚀\" version 1\nlet x = nope\n"40 let compilation = FlowCompiler.compile(source)41 let diagnostic = compilation.errors.first { $0.code == "undefined-name" }42 #expect(diagnostic?.range.start.line == 2)43 #expect(diagnostic?.range.start.column == 9)44 let utf16 = Array(source.utf16)45 if let range = diagnostic?.range.utf16Range {46 #expect(String(decoding: utf16[range], as: UTF16.self) == "nope")47 }48 #expect(compilation.program.nameRange.utf16Range == 5..<15)49 }5051 @Test func statementsMayShareALineWithSemicolonsAndElseMayStartALine() throws {52 let program = try validated("""53 flow "x" version 154 allow domains "example.org"55 open "https://example.org/a" as p; extract article from p as a; collect a into items56 if count(items) > 5 { notify "many" }57 else if count(items) > 0 { notify "some" }58 else { notify "none" }59 """)60 #expect(program.program.body.statements.count == 4)61 guard case .conditional(let first) = program.program.body.statements[3].kind,62 case .conditional(let second)? = first.elseBlock?.statements.first?.kind else { Issue.record("expected else if"); return }63 #expect(second.elseBlock?.statements.count == 1)64 }6566 @Test func stringEscapesAndInterpolation() throws {67 let program = try validated(#"""68 flow "x" version 169 param who: text70 let a = "say \"hi\" to {who}\n\ttab \{literal\} back\\slash"71 """#)72 guard case .let_(let statement) = program.program.body.statements[0].kind, case .string(let literal) = statement.value else {73 Issue.record("expected let"); return74 }75 #expect(literal.parts.count == 3)76 #expect(literal.parts[0] == .text("say \"hi\" to "))77 #expect(literal.parts[2] == .text("\n\ttab {literal} back\\slash"))78 }7980 @Test(arguments: [81 ("", "expected-keyword"),82 ("flow version 1", "expected-text"),83 ("flow \"\" version 1", "empty-name"),84 ("flow \"x\"", "expected-keyword"),85 ("flow \"x\" version one", "expected-integer"),86 ("flow \"x\" version 1 extra", "unexpected-token"),87 ("flow \"{x}\" version 1", "interpolation-not-allowed"),88 ("flow \"x\" version 1\nlet = 3", "expected-name"),89 ("flow \"x\" version 1\nlet a 3", "expected-symbol"),90 ("flow \"x\" version 1\nlet a = ", "expected-value"),91 ("flow \"x\" version 1\nlet a = \"open", "unterminated-string"),92 ("flow \"x\" version 1\nlet a = \"bad \\q\"", "invalid-escape"),93 ("flow \"x\" version 1\nlet a = \"{1bad}\"", "invalid-interpolation"),94 ("flow \"x\" version 1\nlet a = \"stray } brace\"", "invalid-interpolation"),95 ("flow \"x\" version 1\nlet a = 5parsecs", "invalid-unit"),96 ("flow \"x\" version 1\nlet a = 1234567890123456789012", "invalid-number"),97 ("flow \"x\" version 1\nlet a = 3 $ 4", "unexpected-character"),98 ("flow \"x\" version 1\nlet a = (1 == 1", "expected-symbol"),99 ("flow \"x\" version 1\nlet a = [1, 2", "expected-symbol"),100 ("flow \"x\" version 1\nlet a = count(1", "expected-symbol"),101 ("flow \"x\" version 1\nlet a = 1 = 1", "unexpected-token"),102 ("flow \"x\" version 1\nfrobnicate \"x\"", "unknown-action"),103 ("flow \"x\" version 1\nfor x in [1] { notify \"a\" }", "unbounded-loop"),104 ("flow \"x\" version 1\nparallel { notify \"a\" }", "unbounded-parallel"),105 ("flow \"x\" version 1\nif true { notify \"a\"", "unclosed-block"),106 ("flow \"x\" version 1\n}", "unexpected-token"),107 ("flow \"x\" version 1\nelse { }", "unexpected-token"),108 ("flow \"x\" version 1\nnotify \"a\" notify \"b\"", "unexpected-argument"),109 ("flow \"x\" version 1\nparam a text", "expected-symbol"),110 ("flow \"x\" version 1\nallow \"example.org\"", "expected-keyword"),111 ("flow \"x\" version 1\nlimit bananas 3", "unknown-limit"),112 ("flow \"x\" version 1\nlimit steps 3s", "invalid-limit"),113 ("flow \"x\" version 1\nlimit duration 30", "invalid-limit"),114 ("flow \"x\" version 1\ncollect 1 items", "expected-keyword"),115 ("flow \"x\" version 1\nspace \"s\" { }\nnotify \"after\"", "unexpected-token"),116 ("flow \"x\" version 1\nopen \"https://example.org\" as", "expected-name"),117 ] as [(String, String)])118 func syntaxErrorsAreReportedWithACodeAPositionAndAHint(source: String, code: String) {119 let compilation = FlowCompiler.compile(source)120 let match = compilation.errors.first { $0.code == code }121 #expect(match != nil, "expected \(code), got \(compilation.errors.map(\.code)) for: \(source)")122 #expect(compilation.validated == nil)123 for diagnostic in compilation.diagnostics {124 #expect(diagnostic.range.start.line >= 1 && diagnostic.range.start.column >= 1)125 #expect(diagnostic.range.start.offset <= source.utf16.count && diagnostic.range.end.offset <= source.utf16.count)126 #expect(!diagnostic.message.isEmpty)127 #expect(diagnostic.hint?.isEmpty == false, "no hint for \(diagnostic.code)")128 }129 }130131 @Test func unknownActionSuggestsTheClosestName() {132 let typo = FlowCompiler.compile("flow \"x\" version 1\nsumarize \"x\"").errors.first133 #expect(typo?.hint == "Did you mean “summarize”?")134 let partial = FlowCompiler.compile("flow \"x\" version 1\nextract everything from p").errors.first135 #expect(partial?.code == "unknown-action")136 #expect(partial?.hint?.contains("extract article") == true)137 }138139 @Test func aParseErrorDoesNotHideLaterStatements() {140 let compilation = FlowCompiler.compile("""141 flow "x" version 1142 let a = (143 let b = nope144 notify 12145 """)146 #expect(Set(compilation.errors.map(\.code)).isSuperset(of: ["expected-value", "undefined-name", "type-mismatch"]))147 #expect(compilation.program.body.statements.count == 3)148 }149}150151@Suite struct FlowFuzzTests {152 /// Every public entry point must survive any text.153 func exercise(_ source: String) {154 let compilation = FlowCompiler.compile(source)155 for diagnostic in compilation.diagnostics {156 #expect(diagnostic.range.start.offset >= 0 && diagnostic.range.end.offset <= source.utf16.count)157 }158 let tokens = FlowHighlighter.highlight(source)159 var cursor = 0160 for token in tokens {161 #expect(token.range.lowerBound >= cursor && token.range.upperBound <= source.utf16.count && !token.range.isEmpty)162 cursor = token.range.upperBound163 }164 if let formatted = FlowFormatter.format(source: source) {165 #expect(FlowFormatter.format(source: formatted) == formatted, "formatter not idempotent for: \(source.prefix(200))")166 }167 let length = source.utf16.count168 for offset in [0, length / 3, length / 2, length] { _ = FlowCompletion.complete(source, utf16Offset: offset) }169 if let program = compilation.validated { _ = FlowRunner.plan(program, grant: []) }170 }171172 @Test func everyPrefixOfEveryExampleIsHandled() {173 for example in FlowEngine.examples {174 let scalars = Array(example.source.unicodeScalars)175 for end in 0...scalars.count {176 var text = String.UnicodeScalarView()177 text.append(contentsOf: scalars[0..<end])178 exercise(String(text))179 }180 }181 }182183 @Test(arguments: [1, 2, 3, 4] as [UInt64])184 func randomTokenSoup(seed: UInt64) {185 var generator = SeededGenerator(seed: seed)186 let pieces = ["flow", "version", "param", "allow", "domains", "limit", "steps", "duration", "space", "let", "for", "in",187 "parallel", "if", "else", "collect", "into", "as", "and", "or", "not", "true", "false", "open", "extract",188 "article", "from", "summarize", "with", "citations", "export", "markdown", "to", "downloads", "wait", "x", "y",189 "items", "count", "allowed", "url", "{", "}", "(", ")", "[", "]", ",", ":", ";", ".", "=", "==", "!=", "<", ">=",190 "\"", "\"text\"", "\"https://example.org/{x}\"", "\"{", "}\"", "\\", "#", "# note", "1", "42", "3.5", "30s", "5m", "200ms",191 "9x", "\n", "\n", "\n", " ", "\t", "é", "🚀", "\u{0}", "\u{FEFF}", "\r\n", "$", "@", "'"]192 for _ in 0..<300 {193 let count = Int.random(in: 0..<60, using: &generator)194 var source = Bool.random(using: &generator) ? "flow \"f\" version 1\nallow domains \"example.org\"\n" : ""195 for _ in 0..<count {196 source += pieces.randomElement(using: &generator)!197 if Bool.random(using: &generator) { source += " " }198 }199 exercise(source)200 }201 }202203 @Test(arguments: [11, 12] as [UInt64])204 func randomScalarsAndMutatedExamples(seed: UInt64) {205 var generator = SeededGenerator(seed: seed)206 for _ in 0..<150 {207 var scalars = String.UnicodeScalarView()208 for _ in 0..<Int.random(in: 0..<200, using: &generator) {209 let value = UInt32.random(in: 0..<0x3000, using: &generator)210 if let scalar = Unicode.Scalar(value) { scalars.append(scalar) }211 }212 exercise(String(scalars))213 }214 // Flip, delete and duplicate characters of a valid workflow.215 for _ in 0..<200 {216 var characters = Array(FlowEngine.examples.randomElement(using: &generator)!.source)217 for _ in 0..<Int.random(in: 1...6, using: &generator) where !characters.isEmpty {218 let index = Int.random(in: 0..<characters.count, using: &generator)219 switch Int.random(in: 0..<3, using: &generator) {220 case 0: characters.remove(at: index)221 case 1: characters.insert(characters[index], at: index)222 default: characters[index] = "\"{}()[];:,.=<>#\\\n x1".randomElement(using: &generator)!223 }224 }225 exercise(String(characters))226 }227 }228229 @Test func pathologicalNestingAndSizeDoNotOverflowTheStack() {230 let header = "flow \"deep\" version 1\n"231 let cases = [232 header + "let a = " + String(repeating: "(", count: 50_000),233 header + "let a = " + String(repeating: "[", count: 50_000),234 header + "let a = " + String(repeating: "not ", count: 50_000) + "true",235 header + "let a = " + String(repeating: "count(", count: 20_000),236 header + String(repeating: "if true { ", count: 20_000),237 header + String(repeating: "if true { } else ", count: 5_000) + "{ }",238 header + String(repeating: "for x in y limit 1 { ", count: 5_000),239 header + "let a = x" + String(repeating: ".y", count: 50_000),240 header + "let a = \"" + String(repeating: "{", count: 50_000),241 header + String(repeating: "}", count: 50_000),242 String(repeating: "\"", count: 50_001),243 ]244 for source in cases {245 let compilation = FlowCompiler.compile(source)246 #expect(!compilation.errors.isEmpty)247 #expect(compilation.validated == nil)248 }249 #expect(codes(header + "let a = " + String(repeating: "(", count: 100) + "1" + String(repeating: ")", count: 100)).contains("nesting-too-deep"))250 let tooManyBlocks = header + String(repeating: "if true { ", count: 9) + String(repeating: "}", count: 9)251 #expect(codes(tooManyBlocks).contains("nesting-too-deep"))252 #expect(codes(header + String(repeating: "let a = 1\n", count: 2_100)).contains("too-many-statements"))253 #expect(codes(header + String(repeating: "# padding padding padding\n", count: 12_000)) == ["source-too-large"])254 }255}256