From 4f263c1be5c3cb87658fc6bba6917c9f0cbdfc1c Mon Sep 17 00:00:00 2001 From: Dustin Mierau <55453+mierau@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:23:17 +0000 Subject: [PATCH] Add foreach else, strict mode, dictionary loops, text indexing and comments. - An else inside foreach runs when there's nothing to loop over. - RenderFeatures.strict logs keys the context doesn't have, with the tag's line, from a separate pass so normal renders pay nothing. - foreach over a dictionary gets each entry as key and value, in key order. - text[0], text[FIRST] and text[LAST] give characters. - {%# ... %} is a comment. --- README.md | 26 ++- .../DMTemplates.docc/TemplateSyntax.md | 18 +- Sources/DMTemplates/Functions.swift | 6 + .../Parsing/ExpressionParser.swift | 2 +- .../Parsing/ExpressionSyntax.swift | 4 +- .../DMTemplates/Parsing/TemplateParser.swift | 76 ++++++-- .../Rendering/ExpressionCode.swift | 126 +++++++++++++- Sources/DMTemplates/Rendering/Program.swift | 87 ++++++++-- .../Rendering/ValueOperations.swift | 36 +++- Tests/DMTemplatesTests/TemplateTests.swift | 163 ++++++++++++++++++ 10 files changed, 502 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 373d3b4..29e559d 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ Every value tag then escapes `&`, `<`, `>`, `"` and `'`. A value tag ending in ` ## Expressions Value tags, conditions and loops all take expressions, written in a syntax modeled on NSPredicate's: -* Key paths: `person.name`, `people[0]`, `person["first name"]`, `people[FIRST]`, `people[LAST]`, `people[SIZE]`. A key path through an array collects the key from every element, so `files.name` is an array of names. +* Key paths: `person.name`, `people[0]`, `person["first name"]`, `people[FIRST]`, `people[LAST]`, `people[SIZE]`. A key path through an array collects the key from every element, so `files.name` is an array of names. Indexing text gives a character, so `name[0]` is the first letter. * Collection operators: `@count`, `@sum`, `@avg`, `@min` and `@max`, as in `people.@avg.age`. * Arithmetic: `+ - * / %`. `+` also joins text, as in `"Hi " + person.name`, whenever either side is text that isn't a number. * Comparisons: `== = != <> < <= > >=`, `BETWEEN`, `IN`, `CONTAINS`, `BEGINSWITH`, `ENDSWITH`, `LIKE` and `MATCHES`, with `[c]`, `[d]` or `[cd]` to ignore case or diacritics. @@ -97,6 +97,20 @@ Inside a loop, the current index is available as the loop variable's name follow Contact {% contactIndex + 1 %}: {% contact.firstName %} {% endforeach %} +An **else** inside a loop runs when there's nothing to loop over: + + {% foreach contact in person.contacts %} + {% contact.firstName %} + {% else %} + No contacts yet. + {% endforeach %} + +A loop over a dictionary gets each entry as `key` and `value`, in key order: + + {% foreach price in prices %} + {% price.key %}: {% price.value | currency %} + {% endforeach %} + ## Functions Functions transform a value before it's shown. Pass a value through them with a pipe, or call them the way you'd call a method in Swift. These all mean the same thing: @@ -170,6 +184,16 @@ To help debug a template, a **log** tag writes an expression's value to `Templat {% log(person.firstName) %} +A misspelled key renders as nothing. To find typos like that, render with the `.strict` feature, which reports every key a tag asks for that the context doesn't have, with its line, to `TemplateOptions.log`. A key that's there with a `nil` value isn't reported. + + template.render(context, features: [.log, .strict]) + // line 3: no value for 'naem' in person.naem + +## Comments +A tag starting with `#` is a comment and renders nothing. + + {%# Shown on the account page. %} + ## Custom expressions Expressions are compiled through the `ExpressionCompiler` protocol, and `TemplateOptions.expressionCompiler` can replace the built-in `NativeExpressionCompiler` with your own. diff --git a/Sources/DMTemplates/DMTemplates.docc/TemplateSyntax.md b/Sources/DMTemplates/DMTemplates.docc/TemplateSyntax.md index 0280d65..04680cf 100644 --- a/Sources/DMTemplates/DMTemplates.docc/TemplateSyntax.md +++ b/Sources/DMTemplates/DMTemplates.docc/TemplateSyntax.md @@ -38,11 +38,21 @@ A `foreach` loop runs over an array from a key path, an expression or an inline {% foreach(name in {"Dustin", "Mary Ann", "Ollie"}) %}{% name %} {% end %} ``` +An `else` inside a loop runs when there's nothing to loop over. A loop over a dictionary gets each entry as `key` and `value`, in key order. + +``` +{% foreach price in prices %} + {% price.key %}: {% price.value | currency %} +{% else %} + No prices yet. +{% endforeach %} +``` + ## Expressions Value tags, conditions and loops take expressions, written in a syntax modeled on NSPredicate's: -- Key paths: `person.name`, `people[0]`, `person["first name"]`, `people[FIRST]`, `people[LAST]`, `people[SIZE]`. A key path through an array collects the key from every element, so `files.name` is an array of names. +- Key paths: `person.name`, `people[0]`, `person["first name"]`, `people[FIRST]`, `people[LAST]`, `people[SIZE]`. A key path through an array collects the key from every element, so `files.name` is an array of names. Indexing text gives a character, so `name[0]` is the first letter. - Collection operators: `@count`, `@sum`, `@avg`, `@min` and `@max`, as in `people.@avg.age`. - Arithmetic: `+ - * / %`. `+` also joins text, as in `"Hi " + person.name`, whenever either side is text that isn't a number. - Comparisons: `== = != <> < <= > >=`, `BETWEEN`, `IN`, `CONTAINS`, `BEGINSWITH`, `ENDSWITH`, `LIKE` and `MATCHES`, with `[c]`, `[d]` or `[cd]` to ignore case or diacritics. @@ -60,6 +70,12 @@ A `log` tag writes an expression's value to ``TemplateOptions/log`` and renders {% log(person.firstName) %} ``` +A misspelled key renders as nothing. Rendering with ``RenderFeatures/strict`` reports every key a tag asks for that the context doesn't have, with its line, to ``TemplateOptions/log``. + +## Comments + +A tag starting with `#`, such as `{%# Shown on the account page. %}`, is a comment and renders nothing. + ## Delimiters ``TemplateOptions/beginDelimiter`` and ``TemplateOptions/endDelimiter`` change `{%` and `%}`. diff --git a/Sources/DMTemplates/Functions.swift b/Sources/DMTemplates/Functions.swift index 031c94f..a031ec7 100644 --- a/Sources/DMTemplates/Functions.swift +++ b/Sources/DMTemplates/Functions.swift @@ -305,6 +305,12 @@ public struct RenderFeatures: OptionSet, Sendable { /// Sends `log(...)` tags to `TemplateOptions.log`. When off, they're skipped. public static let log = RenderFeatures(rawValue: 1 << 1) + /// Reports key paths that name a key the context doesn't have, such as a + /// misspelled `{% person.naem %}`, to `TemplateOptions.log` with the line + /// of the tag. A key that's there with a null value isn't reported. Meant + /// for catching typos while developing. + public static let strict = RenderFeatures(rawValue: 1 << 2) + /// Logging on. public static let `default`: RenderFeatures = [.log] } diff --git a/Sources/DMTemplates/Parsing/ExpressionParser.swift b/Sources/DMTemplates/Parsing/ExpressionParser.swift index 75a1119..0d1d2f3 100644 --- a/Sources/DMTemplates/Parsing/ExpressionParser.swift +++ b/Sources/DMTemplates/Parsing/ExpressionParser.swift @@ -509,7 +509,7 @@ struct ExpressionParser { break } if let slot = locals.lastIndex(of: name) { - return .local(slot) + return .local(slot, name: name) } return .path(.root, [.key(name)]) diff --git a/Sources/DMTemplates/Parsing/ExpressionSyntax.swift b/Sources/DMTemplates/Parsing/ExpressionSyntax.swift index c105e8f..585e7ef 100644 --- a/Sources/DMTemplates/Parsing/ExpressionSyntax.swift +++ b/Sources/DMTemplates/Parsing/ExpressionSyntax.swift @@ -8,8 +8,8 @@ indirect enum Expr: Sendable { case literal(TemplateValue) /// The context being rendered (`self`). case root - /// A loop variable, by slot. - case local(Int) + /// A loop variable, by slot. The name is for messages. + case local(Int, name: String) /// An array literal. case list([Expr]) /// A value followed by keys, subscripts and collection operators. diff --git a/Sources/DMTemplates/Parsing/TemplateParser.swift b/Sources/DMTemplates/Parsing/TemplateParser.swift index e9260bc..fc21427 100644 --- a/Sources/DMTemplates/Parsing/TemplateParser.swift +++ b/Sources/DMTemplates/Parsing/TemplateParser.swift @@ -14,7 +14,8 @@ enum Node { case text(String) case value(TagExpression) case conditional([Branch], otherwise: [Node]?) - case loop(slot: Int, sequence: TagExpression, body: [Node]) + /// `otherwise` runs when the sequence is empty. + case loop(slot: Int, sequence: TagExpression, body: [Node], otherwise: [Node]?) case log(TagExpression) } @@ -24,11 +25,17 @@ struct Branch { let body: [Node] } -/// A tag's compiled expression: a syntax tree from the built-in language, or -/// whatever a custom `ExpressionCompiler` returned. -enum TagExpression { - case native(Expr) - case custom(any CompiledExpression) +/// A tag's compiled expression, and the line its tag is on. +struct TagExpression { + /// A syntax tree from the built-in language, or whatever a custom + /// `ExpressionCompiler` returned. + enum Kind { + case native(Expr) + case custom(any CompiledExpression) + } + + let kind: Kind + let line: Int } /// Splits a template into text and tags and builds the node tree. @@ -39,7 +46,7 @@ struct TemplateParser { private let source: SourceText private let beginDelimiter: [UInt8] private let endDelimiter: [UInt8] - private let compileExpression: (_ source: String, _ locals: [String]) throws -> TagExpression + private let compileExpression: (_ source: String, _ locals: [String]) throws -> TagExpression.Kind // The parser deliberately holds no existentials (such as // `TemplateOptions.expressionCompiler`): they make the struct address-only, @@ -52,6 +59,11 @@ struct TemplateParser { private var locals: [String] = [] private var localCount = 0 + /// The line `lineOffset` is on. Tags are read in order, so finding a tag's + /// line only counts the newlines since the last one. + private var line = 1 + private var lineOffset = 0 + private struct Block { enum Kind { case root @@ -69,6 +81,8 @@ struct TemplateParser { /// Conditionals: the condition of the branch being read, or nil once /// past `else`. var condition: TagExpression? + /// Loops: the loop's body, once past `else`. + var loopBody: [Node]? } private enum Tag { @@ -81,6 +95,7 @@ struct TemplateParser { case endForEach case end case log(Range) + case comment } static func parse(_ source: String, options: TemplateOptions) throws -> ParsedTemplate { @@ -183,7 +198,12 @@ struct TemplateParser { try continueConditional(at: offset, tag: "elseif", nextCondition: compiled) case .else: - try continueConditional(at: offset, tag: "else", nextCondition: nil) + if case .loop = blocks[blocks.count - 1].kind { + try startLoopElse(at: offset) + } + else { + try continueConditional(at: offset, tag: "else", nextCondition: nil) + } case .endIf: try closeConditional(at: offset, tag: "endif") @@ -204,6 +224,9 @@ struct TemplateParser { case .log(let expression): append(.log(try compile(expression))) + + case .comment: + break } return true @@ -214,6 +237,7 @@ struct TemplateParser { /// Identifies a tag by its keyword, ignoring case. Tags that take a /// statement in parentheses, like `if( this )`, come back with it. private func classify(_ content: Range) throws -> Tag { + if source.bytes[content.lowerBound] == UInt8(ascii: "#") { return .comment } if let statement = try call("if", in: content, bare: true) { return .if(statement) } if let statement = try call("elseif", in: content, bare: true) { return .elseIf(statement) } if let statement = try elseIf(in: content) { return .elseIf(statement) } @@ -347,21 +371,37 @@ struct TemplateParser { blocks.append(Block(kind: .loop(slot: slot, sequence: sequence), offset: offset)) } + /// `else` in a loop: what follows runs when there's nothing to loop over. + private mutating func startLoopElse(at offset: Int) throws { + guard blocks[blocks.count - 1].loopBody == nil else { + throw error("else after else", at: offset) + } + blocks[blocks.count - 1].loopBody = blocks[blocks.count - 1].nodes + blocks[blocks.count - 1].nodes = [] + // The loop's variables have no value here. + locals.removeLast(2) + } + private mutating func closeLoop(at offset: Int, tag: String) throws { guard case .loop(let slot, let sequence) = blocks[blocks.count - 1].kind else { throw error("\(tag) without a matching foreach", at: offset) } let block = blocks.removeLast() - locals.removeLast(2) - append(.loop(slot: slot, sequence: sequence, body: block.nodes)) + if let body = block.loopBody { + append(.loop(slot: slot, sequence: sequence, body: body, otherwise: block.nodes)) + } + else { + locals.removeLast(2) + append(.loop(slot: slot, sequence: sequence, body: block.nodes, otherwise: nil)) + } } // MARK: Expressions - private func compile(_ range: Range) throws -> TagExpression { + private mutating func compile(_ range: Range) throws -> TagExpression { let expression = source.text(range) do { - return try compileExpression(expression, locals) + return TagExpression(kind: try compileExpression(expression, locals), line: line(at: range.lowerBound)) } catch let problem as ExpressionError { throw error("\(problem.message) in '\(expression)'", at: range.lowerBound + problem.offset) @@ -371,6 +411,18 @@ struct TemplateParser { } } + private mutating func line(at offset: Int) -> Int { + if offset < lineOffset { + line = 1 + lineOffset = 0 + } + for index in lineOffset.. TemplateError { let (line, column) = source.location(of: offset) return TemplateError(message: message, line: line, column: column) diff --git a/Sources/DMTemplates/Rendering/ExpressionCode.swift b/Sources/DMTemplates/Rendering/ExpressionCode.swift index 4d5f907..e7967f6 100644 --- a/Sources/DMTemplates/Rendering/ExpressionCode.swift +++ b/Sources/DMTemplates/Rendering/ExpressionCode.swift @@ -20,7 +20,8 @@ final class ExpressionCode: @unchecked Sendable { enum Operation { case literal(value: Int32) case root - case local(slot: Int32) + /// A loop variable. `name` is in `strings`, for messages. + case local(slot: Int32, name: Int32) /// An array literal; elements are operations listed in `operands`. case list(Span) case path(base: Int32, steps: Span) @@ -97,8 +98,8 @@ extension ExpressionCode { return append(.literal(value: Self.append(value, to: &values))) case .root: return append(.root) - case .local(let slot): - return append(.local(slot: Int32(slot))) + case .local(let slot, let name): + return append(.local(slot: Int32(slot), name: Self.append(name, to: &strings))) case .list(let elements): return append(.list(addOperands(elements))) case .path(let base, let pathSteps): @@ -189,7 +190,7 @@ struct Interpreter { case .root: return scope.root - case .local(let slot): + case .local(let slot, _): return scope.locals[Int(slot)] case .list(let elements): @@ -256,4 +257,121 @@ struct Interpreter { } return value } + + // MARK: Strict mode + + /// Adds the keys the expression's paths ask for but the context doesn't + /// have to `missing`, for `RenderFeatures.strict`. It's a separate pass + /// over the expression, so that rendering without strict mode pays + /// nothing for it. Like `evaluate`, it skips the right side of `and` and + /// `or` when the left side decides. + func findMissingKeys(_ index: Int32, in scope: ExpressionScope, into missing: MissingKeys) { + func find(_ index: Int32) { + findMissingKeys(index, in: scope, into: missing) + } + switch operations[Int(index)] { + case .literal, .root, .local: + break + case .list(let elements): + elements.range.forEach { find(operands[$0]) } + case .path(let base, let pathSteps): + find(base) + findMissingKey(evaluate(base, in: scope), pathSteps.range, in: scope, base: base, start: pathSteps.range.lowerBound, into: missing) + case .negate(let operand), .not(let operand), .match(_, _, let operand): + find(operand) + case .and(let lhs, let rhs): + find(lhs) + if evaluate(lhs, in: scope).isTruthy { find(rhs) } + case .or(let lhs, let rhs): + find(lhs) + if !evaluate(lhs, in: scope).isTruthy { find(rhs) } + case .arithmetic(_, let lhs, let rhs), .comparison(_, _, let lhs, let rhs): + find(lhs) + find(rhs) + case .function(_, let span): + span.range.forEach { find(operands[$0]) } + } + } + + /// Walks a path like `walk`, adding the first key it can't find to + /// `missing`. `base` and `start` are where the whole path begins, for + /// naming it. + private func findMissingKey(_ value: TemplateValue, _ range: Range, in scope: ExpressionScope, base: Int32, start: Int, into missing: MissingKeys) { + var value = value + for index in range { + switch steps[index] { + case .key(let string): + let key = strings[Int(string)] + guard value.hasMember(key) else { + return missing.add(key: key, path: describe(base, start...index, in: scope)) + } + value = value.member(key) + case .index(let operation): + findMissingKeys(operation, in: scope, into: missing) + let position = evaluate(operation, in: scope) + if case .dictionary(let items) = value, items[position.renderedString] == nil { + return missing.add(key: position.renderedString, path: describe(base, start...index, in: scope)) + } + value = value.element(at: position) + case .first: + value = value.firstElement + case .last: + value = value.lastElement + case .size, .aggregate(.count): + value = value.elementCount + case .aggregate: + guard case .array(let items) = value else { + return + } + for item in items { + findMissingKey(item, (index + 1).., in scope: ExpressionScope) -> String { + var text: String + switch operations[Int(base)] { + case .root: text = "" + case .local(_, let name): text = strings[Int(name)] + default: text = "(…)" + } + for index in range { + switch steps[index] { + case .key(let string): + text += text.isEmpty ? strings[Int(string)] : "." + strings[Int(string)] + case .index(let operation): + let position = evaluate(operation, in: scope) + if case .string(let key) = position { + text += "[\"\(key)\"]" + } + else { + text += "[\(position.renderedString)]" + } + case .first: text += "[FIRST]" + case .last: text += "[LAST]" + case .size: text += "[SIZE]" + case .aggregate(let op): text += (text.isEmpty ? "@" : ".@") + op.rawValue + } + } + return text + } +} + +/// Keys a key path asked for that weren't there, collected while one render +/// evaluates an expression. Only that render uses it. +final class MissingKeys { + private(set) var messages: [String] = [] + + func add(key: String, path: String) { + messages.append(path == key ? "no value for '\(key)'" : "no value for '\(key)' in \(path)") + } + + func removeAll() { + messages.removeAll(keepingCapacity: true) + } } diff --git a/Sources/DMTemplates/Rendering/Program.swift b/Sources/DMTemplates/Rendering/Program.swift index bf1499e..4f0dd75 100644 --- a/Sources/DMTemplates/Rendering/Program.swift +++ b/Sources/DMTemplates/Rendering/Program.swift @@ -18,8 +18,8 @@ final class Program: @unchecked Sendable { /// Continues if the expression is truthy, otherwise jumps to `otherwise`. case branch(ExpressionRef, otherwise: Int32) case jump(Int32) - /// Starts looping over the expression's elements, or jumps to `exit` - /// when there are none. + /// Starts looping over the expression's elements, or a dictionary's + /// entries, or jumps to `exit` when there are none. case loop(ExpressionRef, slot: Int32, exit: Int32) /// Moves to the loop's next element and jumps back to `body`, or falls /// through when done. @@ -36,6 +36,8 @@ final class Program: @unchecked Sendable { } private let instructions: UnsafeMutableBufferPointer + /// The template line of each instruction's tag, for messages. + private let lines: UnsafeMutableBufferPointer private let text: UnsafeMutableBufferPointer private let custom: UnsafeMutableBufferPointer private let code: ExpressionCode @@ -47,6 +49,7 @@ final class Program: @unchecked Sendable { var builder = Builder(options: options) builder.add(template.nodes) self.instructions = .copying(builder.instructions) + self.lines = .copying(builder.lines) self.text = .copying(builder.text) self.custom = .copying(builder.custom) self.code = ExpressionCode(builder.code) @@ -57,6 +60,7 @@ final class Program: @unchecked Sendable { deinit { instructions.release() + lines.release() text.release() custom.release() } @@ -74,17 +78,26 @@ final class Program: @unchecked Sendable { func run(_ context: TemplateValue, features: RenderFeatures, into output: inout [UInt8], flushingAt limit: Int = .max, _ flush: (inout [UInt8]) -> Void = { _ in }) { let interpreter = code.interpreter var scope = ExpressionScope(root: context, features: features, localCount: localCount) + let missingKeys = features.contains(.strict) ? MissingKeys() : nil var loops: [Loop] = [] output.reserveCapacity(min(text.count * 3 / 2, limit)) + var pc = 0 + var reported: Set = [] + func evaluate(_ expression: ExpressionRef) -> TemplateValue { switch expression { - case .native(let operation): return interpreter.evaluate(operation, in: scope) - case .custom(let index): return custom[Int(index)].evaluate(in: scope) + case .native(let operation): + if let missingKeys { + interpreter.findMissingKeys(operation, in: scope, into: missingKeys) + report(missingKeys, line: lines[pc], &reported) + } + return interpreter.evaluate(operation, in: scope) + case .custom(let index): + return custom[Int(index)].evaluate(in: scope) } } - var pc = 0 while pc < instructions.count { switch instructions[pc] { case .text(let span): @@ -104,7 +117,17 @@ final class Program: @unchecked Sendable { pc = Int(target) case .loop(let sequence, let slot, let exit): - guard case .array(let items) = evaluate(sequence), !items.isEmpty else { + let items: [TemplateValue] + switch evaluate(sequence) { + case .array(let elements): + items = elements + case .dictionary(let entries): + // Each entry as `key` and `value`, in key order. + items = entries.sorted { $0.key < $1.key }.map { .dictionary(["key": .string($0.key), "value": $0.value]) } + default: + items = [] + } + guard !items.isEmpty else { pc = Int(exit) break } @@ -137,6 +160,19 @@ final class Program: @unchecked Sendable { } } + /// Logs the keys an expression found missing, each once per tag rather + /// than once per time around a loop. + private func report(_ missing: MissingKeys, line: Int32, _ reported: inout Set) { + guard !missing.messages.isEmpty else { return } + for message in missing.messages { + let message = "line \(line): \(message)" + if reported.insert(message).inserted { + log(message) + } + } + missing.removeAll() + } + /// Writes a value tag's value, escaped as the options ask. private func write(_ value: TemplateValue, raw: Bool, to output: inout [UInt8]) { // Strings and whole numbers, the most common values, skip @@ -173,6 +209,7 @@ final class Program: @unchecked Sendable { private struct Builder { let options: TemplateOptions var instructions: [Instruction] = [] + var lines: [Int32] = [] var text: [UInt8] = [] var custom: [any CompiledExpression] = [] var code = ExpressionCode.Builder() @@ -184,6 +221,11 @@ final class Program: @unchecked Sendable { /// The index the next instruction will get. private var next: Int32 { Int32(instructions.count) } + private mutating func emit(_ instruction: Instruction, line: Int = 0) { + instructions.append(instruction) + lines.append(Int32(clamping: line)) + } + mutating func add(_ nodes: [Node]) { for node in nodes { add(node) @@ -193,11 +235,11 @@ final class Program: @unchecked Sendable { private mutating func add(_ node: Node) { switch node { case .text(let string): - instructions.append(.text(Span(start: text.count, count: string.utf8.count))) + emit(.text(Span(start: text.count, count: string.utf8.count))) text.append(contentsOf: string.utf8) case .value(let expression): - instructions.append(.value(add(expression), raw: Self.isRaw(expression))) + emit(.value(add(expression), raw: Self.isRaw(expression)), line: expression.line) case .conditional(let branches, let otherwise): // Each branch tests its condition and skips to the next branch when @@ -207,11 +249,11 @@ final class Program: @unchecked Sendable { for (number, branch) in branches.enumerated() { let condition = add(branch.condition) let test = instructions.count - instructions.append(.branch(condition, otherwise: -1)) + emit(.branch(condition, otherwise: -1), line: branch.condition.line) add(branch.body) if otherwise != nil || number < branches.count - 1 { exits.append(instructions.count) - instructions.append(.jump(-1)) + emit(.jump(-1)) } instructions[test] = .branch(condition, otherwise: next) } @@ -222,30 +264,41 @@ final class Program: @unchecked Sendable { instructions[exit] = .jump(next) } - case .loop(let slot, let sequence, let body): + case .loop(let slot, let sequence, let body, let otherwise): + // With an else, an empty sequence exits to it, and a finished loop + // jumps past it. let expression = add(sequence) let start = instructions.count - instructions.append(.loop(expression, slot: Int32(slot), exit: -1)) + emit(.loop(expression, slot: Int32(slot), exit: -1), line: sequence.line) add(body) - instructions.append(.next(slot: Int32(slot), body: Int32(start + 1))) - instructions[start] = .loop(expression, slot: Int32(slot), exit: next) + emit(.next(slot: Int32(slot), body: Int32(start + 1))) + if let otherwise { + let skip = instructions.count + emit(.jump(-1)) + instructions[start] = .loop(expression, slot: Int32(slot), exit: next) + add(otherwise) + instructions[skip] = .jump(next) + } + else { + instructions[start] = .loop(expression, slot: Int32(slot), exit: next) + } case .log(let expression): - instructions.append(.log(add(expression))) + emit(.log(add(expression)), line: expression.line) } } /// Whether a value tag ends by calling `raw` or `escape`, so its /// output isn't escaped (again). private static func isRaw(_ expression: TagExpression) -> Bool { - if case .native(.function(_, let name, _, _)) = expression { + if case .native(.function(_, let name, _, _)) = expression.kind { return name == "raw" || name == "escape" } return false } private mutating func add(_ expression: TagExpression) -> ExpressionRef { - switch expression { + switch expression.kind { case .native(let syntax): return .native(code.add(syntax)) case .custom(let compiled): diff --git a/Sources/DMTemplates/Rendering/ValueOperations.swift b/Sources/DMTemplates/Rendering/ValueOperations.swift index 6b3923d..a6ff83d 100644 --- a/Sources/DMTemplates/Rendering/ValueOperations.swift +++ b/Sources/DMTemplates/Rendering/ValueOperations.swift @@ -24,7 +24,20 @@ extension TemplateValue { } } - /// `value[index]`: an array element by position, or a dictionary value by key. + /// Whether `member(key)` finds something: the dictionary has the key, or + /// every element of the array does. Null has every key, so a path that + /// already came up empty isn't reported twice. + func hasMember(_ key: String) -> Bool { + switch self { + case .null: return true + case .dictionary(let items): return items[key] != nil + case .array(let items): return items.allSatisfy { $0.hasMember(key) } + default: return false + } + } + + /// `value[index]`: an array element or a text's character by position, or + /// a dictionary value by key. func element(at index: TemplateValue) -> TemplateValue { switch (self, index) { case (.array(let items), _): @@ -32,7 +45,14 @@ extension TemplateValue { return .null } return items[i] - case (.dictionary, _), (.string, _): + case (.string(let text), _): + guard case .int(let i)? = index.number, i >= 0, + let position = text.index(text.startIndex, offsetBy: i, limitedBy: text.endIndex), + position < text.endIndex else { + return .null + } + return .string(String(text[position])) + case (.dictionary, _): return member(index.renderedString) default: return .null @@ -40,11 +60,19 @@ extension TemplateValue { } var firstElement: TemplateValue { - if case .array(let items) = self, let first = items.first { first } else { .null } + switch self { + case .array(let items): items.first ?? .null + case .string(let text): text.first.map { .string(String($0)) } ?? .null + default: .null + } } var lastElement: TemplateValue { - if case .array(let items) = self, let last = items.last { last } else { .null } + switch self { + case .array(let items): items.last ?? .null + case .string(let text): text.last.map { .string(String($0)) } ?? .null + default: .null + } } /// `@count`: the number of elements, entries or characters. diff --git a/Tests/DMTemplatesTests/TemplateTests.swift b/Tests/DMTemplatesTests/TemplateTests.swift index ff9a099..350dfb6 100644 --- a/Tests/DMTemplatesTests/TemplateTests.swift +++ b/Tests/DMTemplatesTests/TemplateTests.swift @@ -1112,3 +1112,166 @@ private func render(_ source: String, _ context: TemplateValue = nil, options: T #expect(page == "Hi Dustin!") } } + +@Suite struct LoopElseTests { + let source = "{% foreach item in items %}{% item %},{% else %}none{% endforeach %}!" + + @Test func elseRunsOnlyWhenEmpty() throws { + #expect(try render(source, ["items": [1, 2]]) == "1,2,!") + #expect(try render(source, ["items": []]) == "none!") + #expect(try render(source) == "none!") + #expect(try render(source, ["items": "text"]) == "none!") + } + + @Test func elseOnItsOwnLine() throws { + let source = "{% foreach(n in list) %}\n- {% n %}\n{% else %}\nNothing yet.\n{% end %}\ndone" + #expect(try render(source, ["list": [1, 2]]) == "- 1\n- 2\ndone") + #expect(try render(source, ["list": []]) == "Nothing yet.\ndone") + } + + @Test func loopVariablesAreOutOfScopeInElse() throws { + let source = "{% foreach(item in items) %}{% item %}{% else %}[{% item %}]{% endforeach %}" + #expect(try render(source, ["items": [], "item": "root"]) == "[root]") + } + + @Test func conditionalsInsideLoopKeepTheirElse() throws { + let source = "{% foreach(n in list) %}{% if n > 1 %}big{% else %}small{% endif %} {% else %}empty{% endforeach %}" + #expect(try render(source, ["list": [1, 2]]) == "small big ") + #expect(try render(source, ["list": []]) == "empty") + } + + @Test func nestedLoopsWithElse() throws { + let source = "{% foreach(g in groups) %}{% g.name %}:{% foreach(i in g.items) %}{% i %}{% else %}-{% endforeach %};{% else %}no groups{% endforeach %}" + let context: TemplateValue = ["groups": [["name": "a", "items": [1, 2]], ["name": "b", "items": []]]] + #expect(try render(source, context) == "a:12;b:-;") + #expect(try render(source, ["groups": []]) == "no groups") + } + + @Test func secondElseIsAnError() throws { + #expect(throws: TemplateError.self) { + try Template("{% foreach(i in x) %}{% else %}{% else %}{% endforeach %}") + } + #expect(throws: TemplateError.self) { + try Template("{% foreach(i in x) %}{% elseif y %}{% endforeach %}") + } + } +} + +@Suite struct DictionaryLoopTests { + @Test func loopsOverEntriesInKeyOrder() throws { + let source = "{% foreach(entry in prices) %}{% entry.key %}={% entry.value %} {% endforeach %}" + #expect(try render(source, ["prices": ["pear": 3, "apple": 1, "fig": 2]]) == "apple=1 fig=2 pear=3 ") + } + + @Test func entriesHaveAnIndex() throws { + let source = "{% foreach(entry in d) %}{% entryIndex %}:{% entry.key %} {% endforeach %}" + #expect(try render(source, ["d": ["b": 1, "a": 2]]) == "0:a 1:b ") + } + + @Test func emptyDictionaryRunsElse() throws { + #expect(try render("{% foreach(e in d) %}x{% else %}empty{% endforeach %}", ["d": .dictionary([:])]) == "empty") + } +} + +@Suite struct TextIndexTests { + let context: TemplateValue = ["name": "Düstin 🙂"] + + @Test func indexesCharacters() throws { + #expect(try render("{% name[0] %}{% name[1] %}{% name[7] %}", context) == "Dü🙂") + #expect(try render("{% name[FIRST] %}{% name[LAST] %}", context) == "D🙂") + #expect(try render("{% name.@count %}", context) == "8") + } + + @Test func outOfRangeIsNull() throws { + #expect(try render("[{% name[8] %}][{% name[-1] %}][{% name['x'] %}]", context) == "[][][]") + #expect(try render("[{% empty[0] %}][{% empty[FIRST] %}]", ["empty": ""]) == "[][]") + } +} + +@Suite struct CommentTests { + @Test func commentsRenderNothing() throws { + #expect(try render("a{%# a note %}b") == "ab") + #expect(try render("a{%#%}b") == "ab") + #expect(try render("a{% # spaced out %}b") == "ab") + } + + @Test func commentsOnTheirOwnLineLeaveNoBlankLine() throws { + #expect(try render("a\n{%# note %}\nb") == "a\nb") + } + + @Test func commentsCanHoldAnything() throws { + #expect(try render("{%# {% if( unbalanced \"quotes %}ok") == "ok") + } + + @Test func commentsFollowCustomDelimiters() throws { + var options = TemplateOptions() + options.beginDelimiter = "<<" + options.endDelimiter = ">>" + #expect(try render("a<<# note >>b", options: options) == "ab") + } +} + +@Suite struct StrictTests { + private func strict(_ source: String, _ context: TemplateValue) throws -> (output: String, messages: [String]) { + let collector = LogTests.Collector() + var options = TemplateOptions() + options.log = { collector.append($0) } + let output = try Template(source, options: options).render(context, features: [.log, .strict]) + return (output, collector.messages) + } + + let context: TemplateValue = [ + "person": ["name": "Dustin", "nickname": nil], + "people": [["name": "a"], ["name": "b", "age": 3]], + "title": "Hi", + ] + + @Test func reportsMissingKeysWithTheirLine() throws { + let result = try strict("{% title %}\n{% naem %}\n{% person.naem %}", context) + #expect(result.output == "Hi\n\n") + #expect(result.messages == ["line 2: no value for 'naem'", "line 3: no value for 'naem' in person.naem"]) + } + + @Test func keysWithNullValuesAreFine() throws { + #expect(try strict("{% person.nickname %}{% person.name %}", context).messages.isEmpty) + } + + @Test func reportsOnlyTheFirstMissingStep() throws { + #expect(try strict("{% person.address.city %}", context).messages == ["line 1: no value for 'address' in person.address"]) + } + + @Test func reportsInConditionsLoopsAndSubscripts() throws { + let source = "{% if person.isAdmin %}x{% endif %}\n{% foreach(p in people) %}{% p.age %}{% endforeach %}\n{% person[\"nick\"] %}{% people.age %}" + #expect(try strict(source, context).messages == [ + "line 1: no value for 'isAdmin' in person.isAdmin", + "line 2: no value for 'age' in p.age", + "line 3: no value for 'nick' in person[\"nick\"]", + "line 3: no value for 'age' in people.age", + ]) + } + + @Test func skipsWhatAndAndOrSkip() throws { + #expect(try strict("{% if person.isAdmin and person.level > 2 %}x{% endif %}", context).messages == ["line 1: no value for 'isAdmin' in person.isAdmin"]) + #expect(try strict("{% title or person.backup %}", context).messages.isEmpty) + } + + @Test func reportsInsideAggregatesAndFunctions() throws { + #expect(try strict("{% people.@sum.agee %}{% person.nmae | uppercase %}", context).messages == [ + "line 1: no value for 'agee' in people.@sum.agee", + "line 1: no value for 'nmae' in person.nmae", + ]) + } + + @Test func reportsEachTagOnce() throws { + let source = "{% foreach(p in people) %}{% p.nope %}{% endforeach %}" + #expect(try strict(source, context).messages == ["line 1: no value for 'nope' in p.nope"]) + } + + @Test func offByDefault() throws { + let collector = LogTests.Collector() + var options = TemplateOptions() + options.log = { collector.append($0) } + #expect(try Template("{% naem %}", options: options).render(context) == "") + #expect(collector.messages.isEmpty) + } +}