Repository Public License
1// FlowEngine — static validation: names, types, bounds, domains. Only a validated program can run.2import CryptoKit3import Foundation45public enum FlowLanguage {6 /// The only language version this build reads.7 public static let currentVersion = 18}910/// Hard ceilings no workflow can raise. A workflow declares its own limits below these.11public struct FlowCaps: Hashable, Sendable {12 public var maximumLoopIterations = 10013 public var maximumParallelWidth = 814 public var maximumParallelBranches = 1615 public var maximumSteps = 50016 public var maximumDurationSeconds: Double = 3_60017 public var maximumStepTimeoutSeconds: Double = 30018 public var maximumWaitSeconds: Double = 6019 public var maximumDomains = 5020 /// Longest list a workflow value may hold; longer host results are an error.21 public var maximumListLength = 2_00022 /// Longest text a workflow value may hold, in UTF-8 bytes.23 public var maximumTextBytes = 4 * 1024 * 102424 public var defaultSteps = 5025 public var defaultDurationSeconds: Double = 30026 public var defaultStepTimeoutSeconds: Double = 302728 public init() {}29 public static let standard = FlowCaps()30}3132/// The limits of one workflow after validation (declared values or defaults, all within the caps).33public struct FlowLimits: Hashable, Sendable, Codable {34 public var maximumSteps: Int35 public var maximumDurationSeconds: Double36 public var stepTimeoutSeconds: Double37}3839/// The domain allow-list of a workflow. A URL passes when it is http or https, carries no credentials, and its40/// host is one of the domains or a subdomain of one.41public struct FlowDomainPolicy: Hashable, Sendable, Codable {42 public let domains: [String]4344 public init(domains: [String]) { self.domains = domains.map { $0.lowercased() } }4546 /// `nil` when the text is an acceptable domain; otherwise why it is not.47 public static func problem(with domain: String) -> String? {48 let text = domain.lowercased()49 if text == "localhost" { return nil }50 if text.contains("://") || text.contains("/") { return "Write the domain only, without scheme or path." }51 if text.contains("*") { return "Wildcards are not needed: a domain also allows its subdomains." }52 let labels = text.split(separator: ".", omittingEmptySubsequences: false)53 guard labels.count >= 2 else { return "A whole top-level domain cannot be allowed; write a registrable domain such as example.org." }54 for label in labels {55 guard !label.isEmpty, label.utf8.count <= 63, label.first != "-", label.last != "-",56 label.utf8.allSatisfy({ ($0 >= 97 && $0 <= 122) || ($0 >= 48 && $0 <= 57) || $0 == 45 }) else {57 return "A domain is made of letters, digits and hyphens separated by dots (use the punycode form for other scripts)."58 }59 }60 if labels.allSatisfy({ $0.utf8.allSatisfy { $0 >= 48 && $0 <= 57 } }) { return "IP addresses cannot be allowed." }61 if text.utf8.count > 253 { return "This domain is too long." }62 return nil63 }6465 public func allows(host: String) -> Bool {66 var host = host.lowercased()67 if host.hasSuffix(".") { host.removeLast() }68 guard !host.isEmpty else { return false }69 return domains.contains { host == $0 || host.hasSuffix("." + $0) }70 }7172 public func allows(_ url: URL) -> Bool {73 guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https",74 url.user == nil, url.password == nil, let host = url.host else { return false }75 return allows(host: host)76 }77}7879public struct FlowSymbol: Hashable, Sendable {80 public enum Kind: String, Sendable { case parameter, variable, loopVariable, collection }81 public var name: String82 public var type: FlowType83 public var kind: Kind84 public var declaration: FlowRange85 /// UTF-16 offsets between which the name can be used.86 public var visibleFrom: Int87 public var visibleTo: Int88}8990public struct FlowParameterSpec: Hashable, Sendable {91 public var name: String92 public var type: FlowType93 public var defaultValue: FlowValue?94}9596/// A program that passed validation. It can only be produced by `FlowCompiler.compile`, so the interpreter97/// never sees an unchecked tree.98public struct FlowValidatedProgram: Sendable, Hashable {99 public let program: FlowProgram100 public let source: String101 /// SHA-256 of the source, used to refuse resuming a run with a different workflow text.102 public let sourceHash: String103 public let registry: FlowActionRegistry104 public let caps: FlowCaps105 public let limits: FlowLimits106 public let policy: FlowDomainPolicy107 public let parameters: [FlowParameterSpec]108 public let collections: [String: FlowType]109 /// Every capability some action of the workflow needs.110 public let capabilities: Set<FlowCapability>111 /// Upper bound on the number of actions, from the loop limits.112 public let worstCaseSteps: Int113114 public var name: String { program.name }115}116117public struct FlowCompilation: Sendable {118 public var program: FlowProgram119 public var diagnostics: [FlowDiagnostic]120 public var symbols: [FlowSymbol]121 /// Present only when there is no error.122 public var validated: FlowValidatedProgram?123 var tokens: [FlowToken]124125 public var errors: [FlowDiagnostic] { diagnostics.filter { $0.severity == .error } }126 public var warnings: [FlowDiagnostic] { diagnostics.filter { $0.severity == .warning } }127 public var isRunnable: Bool { validated != nil }128}129130public enum FlowCompiler {131 /// Lexes, parses and validates. Total: every input returns a compilation with diagnostics.132 public static func compile(_ source: String, registry: FlowActionRegistry = .standard, caps: FlowCaps = .standard) -> FlowCompilation {133 let parsed = FlowParser.parse(source, registry: registry)134 var diagnostics = parsed.diagnostics135 // First pass only discovers the element types of collections, so a collection can be read before the136 // statement that fills it (inside a loop, for instance).137 var discovery = FlowValidator(registry: registry, caps: caps, knownCollections: [:])138 discovery.validate(parsed.program)139 var validator = FlowValidator(registry: registry, caps: caps, knownCollections: discovery.collections)140 validator.validate(parsed.program)141 diagnostics += validator.diagnostics142 diagnostics.sort { ($0.range.start, $0.code) < ($1.range.start, $1.code) }143 var validated: FlowValidatedProgram?144 if !diagnostics.contains(where: { $0.severity == .error }) {145 let hash = SHA256.hash(data: Data(source.utf8)).map { String(format: "%02x", $0) }.joined()146 validated = FlowValidatedProgram(program: parsed.program, source: source, sourceHash: hash, registry: registry, caps: caps,147 limits: validator.limits, policy: FlowDomainPolicy(domains: validator.domains),148 parameters: validator.parameters, collections: validator.collections,149 capabilities: validator.capabilities, worstCaseSteps: validator.worstCaseSteps)150 }151 return FlowCompilation(program: parsed.program, diagnostics: diagnostics, symbols: validator.symbols, validated: validated,152 tokens: parsed.tokens)153 }154}155156struct FlowValidator {157 let registry: FlowActionRegistry158 let caps: FlowCaps159 private let knownCollections: [String: FlowType]160161 private(set) var diagnostics: [FlowDiagnostic] = []162 private(set) var symbols: [FlowSymbol] = []163 private(set) var collections: [String: FlowType] = [:]164 private(set) var domains: [String] = []165 private(set) var parameters: [FlowParameterSpec] = []166 private(set) var capabilities: Set<FlowCapability> = []167 private(set) var worstCaseSteps = 0168 private(set) var limits: FlowLimits169170 private var scopes: [[String: FlowType]] = [[:]]171 /// Offsets up to which names declared in each open scope are visible. `Int.max` for a scope that runs to172 /// the end of the text (the top level, or a block still being typed), so completion works past the last token.173 private var blockEnds: [Int] = [Int.max]174 private var sourceEnd = 0175 private var policy = FlowDomainPolicy(domains: [])176 private var firstNetworkUse: FlowRange?177 private var bodyRange = FlowRange(at: .start)178179 init(registry: FlowActionRegistry, caps: FlowCaps, knownCollections: [String: FlowType]) {180 self.registry = registry; self.caps = caps; self.knownCollections = knownCollections181 limits = FlowLimits(maximumSteps: caps.defaultSteps, maximumDurationSeconds: caps.defaultDurationSeconds,182 stepTimeoutSeconds: caps.defaultStepTimeoutSeconds)183 }184185 private mutating func error(_ code: String, _ message: String, at range: FlowRange, hint: String? = nil) {186 guard diagnostics.count < FlowParser.maximumDiagnostics else { return }187 diagnostics.append(FlowDiagnostic(.error, code, message, at: range, hint: hint))188 }189190 private mutating func warning(_ code: String, _ message: String, at range: FlowRange, hint: String? = nil) {191 diagnostics.append(FlowDiagnostic(.warning, code, message, at: range, hint: hint))192 }193194 // MARK: Program195196 mutating func validate(_ program: FlowProgram) {197 bodyRange = program.body.range198 sourceEnd = program.body.range.end.offset199 if program.version != FlowLanguage.currentVersion, program.version != 0 || !program.name.isEmpty {200 error("unsupported-version", "Language version \(program.version) is not supported.", at: program.nameRange,201 hint: "This build reads version \(FlowLanguage.currentVersion): write “version \(FlowLanguage.currentVersion)”.")202 }203 validateDomains(program.domains)204 validateLimits(program.limits)205 for parameter in program.parameters { validateParameter(parameter) }206 sourceEnd = program.body.range.end.offset207 worstCaseSteps = validate(program.body.statements, multiplier: 1)208 for (name, type) in collections.sorted(by: { $0.key < $1.key }) {209 symbols.append(FlowSymbol(name: name, type: type, kind: .collection, declaration: program.body.range,210 visibleFrom: program.body.range.start.offset, visibleTo: Int.max))211 }212 if let use = firstNetworkUse, domains.isEmpty {213 error("missing-allow-domains", "This workflow uses the network but allows no domain.", at: use,214 hint: "Add a line near the top: allow domains \"example.org\"")215 }216 if program.body.statements.isEmpty, !program.name.isEmpty {217 warning("empty-flow", "This workflow does nothing.", at: program.nameRange, hint: "Add statements, for example: open \"https://…\" as page")218 }219 if worstCaseSteps > limits.maximumSteps {220 warning("step-budget", "In the worst case this workflow runs \(worstCaseSteps) steps but its limit is \(limits.maximumSteps); it would stop when the limit is reached.",221 at: program.nameRange, hint: "Lower the loop limits or raise “limit steps” (at most \(caps.maximumSteps)).")222 }223 }224225 private mutating func validateDomains(_ literals: [FlowDomainLiteral]) {226 var seen = Set<String>()227 for literal in literals {228 let domain = literal.domain.lowercased()229 if let problem = FlowDomainPolicy.problem(with: domain) {230 error("invalid-domain", "“\(literal.domain)” is not a valid domain.", at: literal.range, hint: problem)231 } else if !seen.insert(domain).inserted {232 warning("duplicate-domain", "“\(domain)” is listed twice.", at: literal.range, hint: "Remove the duplicate.")233 } else {234 domains.append(domain)235 }236 }237 if domains.count > caps.maximumDomains, let last = literals.last {238 error("too-many-domains", "A workflow allows at most \(caps.maximumDomains) domains.", at: last.range, hint: "Remove some domains.")239 }240 policy = FlowDomainPolicy(domains: domains)241 }242243 private mutating func validateLimits(_ declarations: [FlowLimitDeclaration]) {244 var seen = Set<FlowLimitDeclaration.Kind>()245 for declaration in declarations {246 guard seen.insert(declaration.kind).inserted else {247 error("duplicate-limit", "“\(declaration.kind.rawValue)” is limited twice.", at: declaration.range, hint: "Keep one value.")248 continue249 }250 switch declaration.kind {251 case .steps:252 if declaration.value < 1 || declaration.value > Double(caps.maximumSteps) {253 error("limit-out-of-range", "“steps” must be between 1 and \(caps.maximumSteps).", at: declaration.range,254 hint: "Write a value such as: limit steps \(caps.defaultSteps)")255 } else { limits.maximumSteps = Int(declaration.value) }256 case .duration:257 if declaration.value <= 0 || declaration.value > caps.maximumDurationSeconds {258 error("limit-out-of-range", "“duration” must be at most \(Int(caps.maximumDurationSeconds))s.", at: declaration.range,259 hint: "Write a value such as: limit duration \(Int(caps.defaultDurationSeconds))s")260 } else { limits.maximumDurationSeconds = declaration.value }261 case .timeout:262 if declaration.value <= 0 || declaration.value > caps.maximumStepTimeoutSeconds {263 error("limit-out-of-range", "“timeout” must be at most \(Int(caps.maximumStepTimeoutSeconds))s.", at: declaration.range,264 hint: "Write a value such as: limit timeout \(Int(caps.defaultStepTimeoutSeconds))s")265 } else { limits.stepTimeoutSeconds = declaration.value }266 }267 }268 }269270 private mutating func validateParameter(_ parameter: FlowParameterDeclaration) {271 let type: FlowType272 switch parameter.typeName {273 case "text": type = .text274 case "number": type = .number275 case "bool": type = .bool276 case "url": type = .url277 default:278 let suggestion = FlowText.closest(to: parameter.typeName, in: FlowKeywords.typeNames)279 error("unknown-type", "Unknown type “\(parameter.typeName)”.", at: parameter.typeRange,280 hint: suggestion.map { "Did you mean “\($0)”?" } ?? "Parameter types: text, number, bool, url.")281 type = .unknown282 }283 var defaultValue: FlowValue?284 if let expression = parameter.defaultValue {285 switch (expression, type) {286 case (.string(let literal), .text) where literal.plainText != nil: defaultValue = .text(literal.plainText ?? "")287 case (.number(let value, _), .number): defaultValue = .number(value)288 case (.bool(let value, _), .bool): defaultValue = .bool(value)289 case (.string(let literal), .url) where literal.plainText != nil:290 checkURLLiteral(literal)291 if let url = URL(string: literal.plainText ?? "") { defaultValue = .url(url) }292 case (_, .unknown): break293 default:294 error("invalid-default", "The default of “\(parameter.name)” must be a literal \(type).", at: expression.range,295 hint: "Defaults are constants: text in quotes without {…}, a number, true or false.")296 }297 }298 if declare(parameter.name, type, .parameter, at: parameter.nameRange) {299 parameters.append(FlowParameterSpec(name: parameter.name, type: type, defaultValue: defaultValue))300 }301 }302303 // MARK: Scopes304305 private func lookup(_ name: String) -> FlowType? {306 for scope in scopes.reversed() { if let type = scope[name] { return type } }307 return collections[name] ?? knownCollections[name]308 }309310 private var visibleNames: [String] { scopes.flatMap(\.keys) + collections.keys + knownCollections.keys }311312 @discardableResult313 private mutating func declare(_ name: String, _ type: FlowType, _ kind: FlowSymbol.Kind, at range: FlowRange) -> Bool {314 if FlowKeywords.reserved.contains(name) {315 error("reserved-name", "“\(name)” is a reserved word.", at: range, hint: "Choose another name.")316 return false317 }318 if lookup(name) != nil {319 error("duplicate-name", "“\(name)” is already defined.", at: range,320 hint: "Names are assigned once; choose another name.")321 return false322 }323 scopes[scopes.count - 1][name] = type324 symbols.append(FlowSymbol(name: name, type: type, kind: kind, declaration: range, visibleFrom: range.end.offset,325 visibleTo: blockEnds.last ?? range.end.offset))326 return true327 }328329 // MARK: Statements330331 /// Validates statements in the current scope and returns their worst-case number of steps.332 private mutating func validate(_ statements: [FlowStatement], multiplier: Int) -> Int {333 var steps = 0334 for statement in statements { steps = min(steps &+ validate(statement, multiplier: multiplier), 1_000_000_000) }335 return steps336 }337338 private mutating func validateBlock(_ block: FlowBlock, multiplier: Int, bindings: [(String, FlowType, FlowSymbol.Kind, FlowRange)] = []) -> Int {339 scopes.append([:])340 blockEnds.append(block.range.end.offset >= sourceEnd ? Int.max : block.range.end.offset)341 defer { scopes.removeLast(); blockEnds.removeLast() }342 for (name, type, kind, range) in bindings {343 if declare(name, type, kind, at: range) {344 // A loop variable is visible in the whole body.345 symbols[symbols.count - 1].visibleFrom = block.range.start.offset346 }347 }348 return validate(block.statements, multiplier: multiplier)349 }350351 private mutating func validate(_ statement: FlowStatement, multiplier: Int) -> Int {352 switch statement.kind {353 case .action(let action):354 return validateAction(action)355 case .let_(let statement):356 let type = typeOf(statement.value)357 if type == .void || type == .option {358 error("type-mismatch", "This has no value to keep.", at: statement.value.range, hint: "Use a value: text, a number, a name…")359 }360 declare(statement.name, type == .void ? .unknown : type, .variable, at: statement.nameRange)361 return 0362 case .forEach(let loop):363 let sequence = typeOf(loop.sequence, expecting: nil)364 var element = FlowType.unknown365 if case .list(let inner) = sequence { element = inner } else if !sequence.containsUnknown {366 error("type-mismatch", "“for” needs a list, not \(sequence).", at: loop.sequence.range,367 hint: "Loop over a list such as article.links or a collection.")368 }369 var limit = 1370 if let declared = loop.limit {371 if declared < 1 || declared > caps.maximumLoopIterations {372 error("loop-limit-out-of-range", "A loop limit must be between 1 and \(caps.maximumLoopIterations).",373 at: loop.limitRange ?? loop.range, hint: "Write for example: limit 10")374 } else { limit = declared }375 }376 if let width = loop.parallelWidth, width < 1 || width > caps.maximumParallelWidth {377 error("parallel-width-out-of-range", "A parallel width must be between 1 and \(caps.maximumParallelWidth).", at: loop.range,378 hint: "Write for example: parallel 3")379 }380 let inner = validateBlock(loop.body, multiplier: multiplier * limit,381 bindings: [(loop.variable, element, .loopVariable, loop.variableRange)])382 return min(inner &* limit, 1_000_000_000)383 case .parallel(let parallel):384 if let width = parallel.width, width < 1 || width > caps.maximumParallelWidth {385 error("parallel-width-out-of-range", "A parallel limit must be between 1 and \(caps.maximumParallelWidth).",386 at: parallel.widthRange ?? parallel.range, hint: "Write for example: parallel limit 3 { … }")387 }388 if parallel.body.statements.count > caps.maximumParallelBranches {389 error("too-many-branches", "A parallel block holds at most \(caps.maximumParallelBranches) statements.", at: parallel.range,390 hint: "Use “for … limit N parallel W” to repeat the same work.")391 }392 // Branches run at the same time: each sees what existed before the block, not its siblings' results.393 var steps = 0394 var produced: [(name: String, type: FlowType)] = []395 let symbolStart = symbols.count396 for branch in parallel.body.statements {397 scopes.append([:])398 steps += validate(branch, multiplier: multiplier)399 produced += scopes.removeLast().map { ($0.key, $0.value) }400 }401 for (name, type) in produced.sorted(by: { $0.name < $1.name }) {402 if lookup(name) != nil {403 let range = symbols[symbolStart...].last { $0.name == name }?.declaration ?? parallel.range404 error("duplicate-name", "“\(name)” is defined by two branches of the same parallel block.", at: range,405 hint: "Give each branch its own result name.")406 } else {407 scopes[scopes.count - 1][name] = type408 }409 }410 return steps411 case .conditional(let conditional):412 let condition = typeOf(conditional.condition)413 if condition != .bool, !condition.containsUnknown {414 error("type-mismatch", "A condition must be true or false, not \(condition).", at: conditional.condition.range,415 hint: "Compare something, for example: count(items) > 0")416 }417 let thenSteps = validateBlock(conditional.thenBlock, multiplier: multiplier)418 let elseSteps = conditional.elseBlock.map { validateBlock($0, multiplier: multiplier) } ?? 0419 return max(thenSteps, elseSteps)420 case .collect(let collect):421 let type = typeOf(collect.value)422 if FlowKeywords.reserved.contains(collect.target) {423 error("reserved-name", "“\(collect.target)” is a reserved word.", at: collect.targetRange, hint: "Choose another name.")424 } else if scopes.contains(where: { $0[collect.target] != nil }) {425 error("duplicate-name", "“\(collect.target)” is a value, not a collection.", at: collect.targetRange,426 hint: "Collect into a name that is not used for anything else.")427 } else if type == .void || type == .option {428 error("type-mismatch", "This has no value to collect.", at: collect.value.range, hint: "Collect a value such as an article or a URL.")429 } else if !type.containsUnknown {430 let existing = collections[collect.target] ?? knownCollections[collect.target]431 if let existing, !existing.containsUnknown, existing != .list(type) {432 error("type-mismatch", "“\(collect.target)” is a \(existing); a \(type) cannot be added to it.", at: collect.value.range,433 hint: "Use one collection per kind of value.")434 } else if collections[collect.target] == nil {435 collections[collect.target] = existing ?? .list(type)436 }437 } else if collections[collect.target] == nil {438 collections[collect.target] = knownCollections[collect.target] ?? .list(.unknown)439 }440 return 0441 }442 }443444 private mutating func validateAction(_ action: FlowActionStatement) -> Int {445 guard let definition = registry.definition(named: action.name) else {446 // Reported by the parser. Keep the binding usable so one error is not followed by many.447 if let binding = action.binding, let range = action.bindingRange { declare(binding, .unknown, .variable, at: range) }448 return 1449 }450 if let capability = definition.capability {451 capabilities.insert(capability)452 if FlowCapability.networked.contains(capability), firstNetworkUse == nil { firstNetworkUse = action.nameRange }453 }454 var seen = Set<String?>()455 for argument in action.arguments {456 guard let parameter = definition.parameter(label: argument.label) else {457 error("unexpected-argument", "“\(action.name)” takes no value directly after its name.", at: argument.value.range,458 hint: "Usage: \(definition.signature)")459 _ = typeOf(argument.value)460 continue461 }462 guard seen.insert(argument.label).inserted else {463 error("duplicate-argument", "“\(argument.label ?? parameter.name)” is given twice.", at: argument.labelRange ?? argument.value.range,464 hint: "Usage: \(definition.signature)")465 continue466 }467 switch parameter.kind {468 case .option(let words):469 if case .identifier(let word, _) = argument.value, words.contains(word) { break }470 error("invalid-option", "Expected \(words.map { "“\($0)”" }.joined(separator: " or ")).", at: argument.value.range,471 hint: "Usage: \(definition.signature)")472 case .value(let types):473 var expecting: FlowType? = types.count == 1 ? types[0] : nil474 if case .string = argument.value, types.contains(.url), !types.contains(.text) { expecting = .url }475 let type = typeOf(argument.value, expecting: expecting)476 if !types.contains(where: { type.isAssignable(to: $0) }) {477 let wanted = types.map(\.description).joined(separator: " or ")478 var hint = "Usage: \(definition.signature)"479 if type == .text, types.contains(.url) { hint = "Convert the text with url(…), or write the address as a literal in quotes." }480 error("type-mismatch", "“\(action.name)” needs \(wanted) here, not \(type).", at: argument.value.range, hint: hint)481 }482 if action.name == FlowBuiltInAction.wait, case .duration(let seconds, let range) = argument.value, seconds > caps.maximumWaitSeconds {483 error("limit-out-of-range", "“wait” pauses at most \(Int(caps.maximumWaitSeconds))s.", at: range, hint: "Use a shorter pause.")484 }485 }486 }487 for parameter in definition.parameters where parameter.isRequired && !seen.contains(parameter.label) {488 error("missing-argument", "“\(action.name)” needs \(parameter.label.map { "“\($0) …”" } ?? "a value after its name").",489 at: action.nameRange, hint: "Usage: \(definition.signature)")490 }491 if let binding = action.binding, let range = action.bindingRange {492 if definition.result == .void {493 error("no-result", "“\(action.name)” produces nothing to name.", at: range, hint: "Remove “as \(binding)”.")494 declare(binding, .unknown, .variable, at: range)495 } else {496 declare(binding, definition.result, .variable, at: range)497 }498 }499 return 1500 }501502 // MARK: Expressions503504 /// Checks that a string literal used as a URL is http(s), has a constant host with no credentials, and that505 /// the host is on the allow-list. Interpolation is allowed only after the host.506 private mutating func checkURLLiteral(_ literal: FlowStringLiteral) {507 var prefix = ""508 var authorityClosed = false509 for part in literal.parts {510 switch part {511 case .text(let text): prefix += text512 case .interpolation(_, let range):513 let afterScheme = prefix.range(of: "://").map { prefix[$0.upperBound...] } ?? Substring("")514 if !afterScheme.contains(where: { "/?#".contains($0) }) {515 error("dynamic-host", "The host of a URL cannot come from a value.", at: range,516 hint: "Write the scheme and host literally; values may appear in the path or query.")517 return518 }519 authorityClosed = true520 }521 if authorityClosed { break }522 }523 let lower = prefix.lowercased()524 guard lower.hasPrefix("https://") || lower.hasPrefix("http://") else {525 error("invalid-url", "A URL must start with https:// or http://.", at: literal.range,526 hint: "Only web addresses are allowed; file:, javascript:, data: and other schemes are refused.")527 return528 }529 let afterScheme = prefix[prefix.range(of: "://")!.upperBound...]530 let authority = afterScheme.prefix { !"/?#".contains($0) }531 guard !authority.isEmpty, !authority.contains("@"), !authority.contains("\\"), !authority.contains(where: \.isWhitespace) else {532 error("invalid-url", "This URL has no valid host.", at: literal.range, hint: "Write for example: \"https://example.org/page\"")533 return534 }535 var host = String(authority)536 if let colon = host.lastIndex(of: ":"), !host.hasPrefix("[") {537 let port = host[host.index(after: colon)...]538 guard !port.isEmpty, port.allSatisfy(\.isNumber) else {539 error("invalid-url", "This URL has an invalid port.", at: literal.range, hint: "Write for example: \"https://example.org:8443/\"")540 return541 }542 host = String(host[..<colon])543 }544 firstNetworkUse = firstNetworkUse ?? literal.range545 if !domains.isEmpty, !policy.allows(host: host) {546 error("domain-not-allowed", "“\(host)” is not in the allowed domains.", at: literal.range,547 hint: "Add it to the list: allow domains \"\(host.lowercased())\"")548 }549 }550551 private mutating func typeOf(_ expression: FlowExpression, expecting: FlowType? = nil) -> FlowType {552 switch expression {553 case .invalid: return .unknown554 case .number: return .number555 case .bool: return .bool556 case .duration: return .duration557 case .string(let literal):558 for part in literal.parts {559 guard case .interpolation(let path, let range) = part else { continue }560 var type = resolve(path[0], at: range)561 for member in path.dropFirst() { type = memberType(of: type, member, at: range) }562 if case .list = type {563 error("type-mismatch", "A list cannot be inserted in text.", at: range, hint: "Use join(list, \", \") in a “let” first.")564 } else if type == .void || type == .option {565 error("type-mismatch", "This has no text form.", at: range, hint: "Insert a text, a number or a URL.")566 }567 }568 if expecting == .url {569 checkURLLiteral(literal)570 return .url571 }572 return .text573 case .identifier(let name, let range):574 return resolve(name, at: range)575 case .member(let base, let member, let range):576 return memberType(of: typeOf(base), member, at: range)577 case .list(let items, _):578 var element: FlowType = .unknown579 if case .list(let expected)? = expecting { element = expected }580 for item in items {581 let type = typeOf(item, expecting: element.containsUnknown ? nil : element)582 if element.containsUnknown { element = type } else if !type.isAssignable(to: element) {583 error("type-mismatch", "This list holds \(element) values; this one is \(type).", at: item.range,584 hint: "All items of a list have the same type.")585 }586 }587 if element == .void || element == .option { return .list(.unknown) }588 return .list(element)589 case .not(let operand, _):590 let type = typeOf(operand)591 if type != .bool, !type.containsUnknown {592 error("type-mismatch", "“not” needs true or false, not \(type).", at: operand.range, hint: "Negate a comparison, for example: not empty(items)")593 }594 return .bool595 case .binary(let op, let left, let right, let range):596 let leftType = typeOf(left)597 let rightType = typeOf(right, expecting: leftType == .url ? .url : nil)598 switch op {599 case .and, .or:600 for (type, operand) in [(leftType, left), (rightType, right)] where type != .bool && !type.containsUnknown {601 error("type-mismatch", "“\(op.rawValue)” needs true or false on both sides, not \(type).", at: operand.range,602 hint: "Combine comparisons, for example: count(a) > 0 and count(b) > 0")603 }604 case .equal, .notEqual:605 let comparable: Set<FlowType> = [.text, .number, .bool, .url, .duration]606 if !leftType.containsUnknown, !rightType.containsUnknown, leftType != rightType || !comparable.contains(leftType) {607 error("type-mismatch", "Cannot compare \(leftType) with \(rightType).", at: range,608 hint: "Compare two values of the same simple type (text, number, bool, url).")609 }610 case .less, .lessOrEqual, .greater, .greaterOrEqual:611 let ordered = (leftType == .number && rightType == .number) || (leftType == .duration && rightType == .duration)612 if !leftType.containsUnknown, !rightType.containsUnknown, !ordered {613 error("type-mismatch", "“\(op.rawValue)” compares numbers, not \(leftType) and \(rightType).", at: range,614 hint: "Use count(…) to compare the size of a list or a text.")615 }616 }617 return .bool618 case .call(let name, let arguments, let range):619 return typeOfCall(name, arguments, range)620 }621 }622623 private mutating func resolve(_ name: String, at range: FlowRange) -> FlowType {624 if let type = lookup(name) { return type }625 let suggestion = FlowText.closest(to: name, in: visibleNames)626 error("undefined-name", "“\(name)” is not defined.", at: range,627 hint: suggestion.map { "Did you mean “\($0)”?" } ?? "Define it first with “let”, “param”, or “… as \(name)”.")628 return .unknown629 }630631 private mutating func memberType(of type: FlowType, _ member: String, at range: FlowRange) -> FlowType {632 if type.containsUnknown { return .unknown }633 if let result = type.members[member] { return result }634 let fields = type.members.keys.sorted()635 error("unknown-member", "A \(type) has no “\(member)”.", at: range,636 hint: fields.isEmpty ? "A \(type) has no fields." : "Fields of \(type): \(fields.joined(separator: ", ")).")637 return .unknown638 }639640 private mutating func typeOfCall(_ name: String, _ arguments: [FlowExpression], _ range: FlowRange) -> FlowType {641 guard FlowFunctions.names.contains(name) else {642 let suggestion = FlowText.closest(to: name, in: FlowFunctions.names)643 error("unknown-function", "Unknown function “\(name)”.", at: range,644 hint: suggestion.map { "Did you mean “\($0)”?" } ?? "Functions: \(FlowFunctions.names.sorted().joined(separator: ", ")). New functions cannot be defined.")645 for argument in arguments { _ = typeOf(argument) }646 return .unknown647 }648 let arity = ["contains": 2, "take": 2, "join": 2][name] ?? 1649 guard arguments.count == arity else {650 let usage = FlowFunctions.all.first { $0.name == name }?.display ?? name651 error("wrong-argument-count", "“\(name)” takes \(arity) argument\(arity == 1 ? "" : "s").", at: range, hint: "Usage: \(usage)")652 for argument in arguments { _ = typeOf(argument) }653 return name == "count" ? .number : .unknown654 }655 func mismatch(_ validator: inout FlowValidator, _ index: Int, _ wanted: String, _ got: FlowType) {656 let usage = FlowFunctions.all.first { $0.name == name }?.display ?? name657 validator.error("type-mismatch", "“\(name)” needs \(wanted) here, not \(got).", at: arguments[index].range, hint: "Usage: \(usage)")658 }659 func isList(_ type: FlowType) -> FlowType? { if case .list(let element) = type { return element } else { return nil } }660 switch name {661 case "count", "empty":662 let type = typeOf(arguments[0])663 if isList(type) == nil, type != .text, !type.containsUnknown { mismatch(&self, 0, "a list or a text", type) }664 return name == "count" ? .number : .bool665 case "contains":666 let container = typeOf(arguments[0])667 if container == .text {668 let needle = typeOf(arguments[1])669 if !needle.isAssignable(to: .text) { mismatch(&self, 1, "text", needle) }670 } else if let element = isList(container) {671 let needle = typeOf(arguments[1], expecting: element)672 if !needle.isAssignable(to: element) { mismatch(&self, 1, "\(element)", needle) }673 } else {674 _ = typeOf(arguments[1])675 if !container.containsUnknown { mismatch(&self, 0, "a list or a text", container) }676 }677 return .bool678 case "first", "unique", "take":679 let type = typeOf(arguments[0])680 if name == "take" {681 let count = typeOf(arguments[1])682 if !count.isAssignable(to: .number) { mismatch(&self, 1, "a number", count) }683 }684 guard let element = isList(type) else {685 if !type.containsUnknown { mismatch(&self, 0, "a list", type) }686 return .unknown687 }688 return name == "first" ? element : .list(element)689 case "allowed":690 let type = typeOf(arguments[0], expecting: .list(.url))691 if !type.isAssignable(to: .list(.url)) { mismatch(&self, 0, "list<url>", type) }692 return .list(.url)693 case "join":694 let list = typeOf(arguments[0]), separator = typeOf(arguments[1])695 if !list.isAssignable(to: .list(.text)) { mismatch(&self, 0, "list<text>", list) }696 if !separator.isAssignable(to: .text) { mismatch(&self, 1, "text", separator) }697 return .text698 case "host":699 var expecting: FlowType?700 if case .string = arguments[0] { expecting = .url }701 let type = typeOf(arguments[0], expecting: expecting)702 if type != .url, type != .page, !type.containsUnknown { mismatch(&self, 0, "a url or a page", type) }703 return .text704 case "url":705 // A literal is checked now; any other text is checked when the workflow runs.706 if case .string = arguments[0] { return typeOf(arguments[0], expecting: .url) }707 let type = typeOf(arguments[0])708 if !type.isAssignable(to: .text), type != .url { mismatch(&self, 0, "text", type) }709 firstNetworkUse = firstNetworkUse ?? range710 return .url711 case "text":712 let type = typeOf(arguments[0])713 if type == .void || type == .option || isList(type) != nil { mismatch(&self, 0, "a single value", type) }714 return .text715 default: // lower, upper, trim716 let type = typeOf(arguments[0])717 if !type.isAssignable(to: .text) { mismatch(&self, 0, "text", type) }718 return .text719 }720 }721}722