Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:

Expand Down Expand Up @@ -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.

Expand Down
18 changes: 17 additions & 1 deletion Sources/DMTemplates/DMTemplates.docc/TemplateSyntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 `%}`.
6 changes: 6 additions & 0 deletions Sources/DMTemplates/Functions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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]
}
2 changes: 1 addition & 1 deletion Sources/DMTemplates/Parsing/ExpressionParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)])

Expand Down
4 changes: 2 additions & 2 deletions Sources/DMTemplates/Parsing/ExpressionSyntax.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
76 changes: 64 additions & 12 deletions Sources/DMTemplates/Parsing/TemplateParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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.
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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 {
Expand All @@ -81,6 +95,7 @@ struct TemplateParser {
case endForEach
case end
case log(Range<Int>)
case comment
}

static func parse(_ source: String, options: TemplateOptions) throws -> ParsedTemplate {
Expand Down Expand Up @@ -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")
Expand All @@ -204,6 +224,9 @@ struct TemplateParser {

case .log(let expression):
append(.log(try compile(expression)))

case .comment:
break
}

return true
Expand All @@ -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<Int>) 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) }
Expand Down Expand Up @@ -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<Int>) throws -> TagExpression {
private mutating func compile(_ range: Range<Int>) 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)
Expand All @@ -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..<offset where source.bytes[index] == UInt8(ascii: "\n") {
line += 1
}
lineOffset = offset
return line
}

private func error(_ message: String, at offset: Int) -> TemplateError {
let (line, column) = source.location(of: offset)
return TemplateError(message: message, line: line, column: column)
Expand Down
Loading
Loading