-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathLeafSerializer.swift
More file actions
194 lines (165 loc) · 7.18 KB
/
LeafSerializer.swift
File metadata and controls
194 lines (165 loc) · 7.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import NIOCore
struct LeafSerializer {
// MARK: - Internal Only
init(
ast: [Syntax],
tags: [String: any LeafTag] = defaultTags,
userInfo: [AnyHashable: Any] = [:],
ignoreUnfoundImports: Bool
) {
self.ast = ast
self.offset = 0
self.buffer = ByteBufferAllocator().buffer(capacity: 0)
self.tags = tags
self.userInfo = userInfo
self.ignoreUnfoundImports = ignoreUnfoundImports
}
mutating func serialize(
context data: [String: LeafData]
) throws -> ByteBuffer {
self.offset = 0
while let next = self.peek() {
self.pop()
try self.serialize(next, context: data)
}
return self.buffer
}
// MARK: - Private Only
private let ast: [Syntax]
private var offset: Int
private var buffer: ByteBuffer
private let tags: [String: any LeafTag]
private let userInfo: [AnyHashable: Any]
private let ignoreUnfoundImports: Bool
private mutating func serialize(_ syntax: Syntax, context data: [String: LeafData]) throws {
switch syntax {
case .raw(var byteBuffer): self.buffer.writeBuffer(&byteBuffer)
case .custom(let custom): try self.serialize(custom, context: data)
case .conditional(let c): try self.serialize(c, context: data)
case .loop(let loop): try self.serialize(loop, context: data)
case .with(let with): try self.serialize(with, context: data)
case .expression(let exp): try self.serialize(expression: exp, context: data)
case .import:
if (self.ignoreUnfoundImports) {
break
} else {
fallthrough
}
case .extend, .export:
throw LeafError(.unknownError("\(syntax) should have been resolved BEFORE serialization"))
}
}
private mutating func serialize(expression: [ParameterDeclaration], context data: [String: LeafData]) throws {
let resolved = try self.resolve(parameters: [.expression(expression)], context: data)
guard resolved.count == 1, let leafData = resolved.first else {
throw LeafError(.unknownError("expressions should resolve to single value"))
}
try? leafData.htmlEscaped().serialize(buffer: &self.buffer)
}
private mutating func serialize(body: [Syntax], context data: [String: LeafData]) throws {
try body.forEach { try self.serialize($0, context: data) }
}
private mutating func serialize(_ conditional: Syntax.Conditional, context data: [String: LeafData]) throws {
evaluate:
for block in conditional.chain {
let evaluated = try self.resolveAtomic(block.condition.expression(), context: data)
guard (evaluated.bool ?? false) || (!evaluated.isNil && evaluated.celf != .bool) else {
continue
}
try self.serialize(body: block.body, context: data)
break evaluate
}
}
private mutating func serialize(_ tag: Syntax.CustomTagDeclaration, context data: [String: LeafData]) throws {
let sub = try LeafContext(
parameters: self.resolve(parameters: tag.params, context: data),
data: data,
body: tag.body,
userInfo: self.userInfo
)
guard let foundTag = self.tags[tag.name] else {
try? LeafData("#\(tag.name)").serialize(buffer: &self.buffer)
return
}
let leafData: LeafData
if foundTag is any UnsafeUnescapedLeafTag {
leafData = try foundTag.render(sub)
} else {
leafData = try foundTag.render(sub).htmlEscaped()
}
try? leafData.serialize(buffer: &self.buffer)
}
private mutating func serialize(_ with: Syntax.With, context data: [String: LeafData]) throws {
let resolved = try self.resolve(parameters: [.expression(with.context)], context: data)
guard resolved.count == 1,
let dict = resolved[0].dictionary
else {
throw LeafError(.unknownError("expressions should resolve to a single dictionary value"))
}
try? self.serialize(body: with.body, context: dict)
}
private mutating func serialize(_ loop: Syntax.Loop, context data: [String: LeafData]) throws {
let finalData: [String: LeafData]
let pathComponents = loop.array.split(separator: ".")
if pathComponents.count > 1 {
finalData = try pathComponents[0..<(pathComponents.count - 1)].enumerated()
.reduce(data) { (innerData, pathContext) -> [String: LeafData] in
let key = String(pathContext.element)
guard let nextData = innerData[key]?.dictionary else {
let currentPath = pathComponents[0...pathContext.offset].joined(separator: ".")
throw LeafError(.unknownError("expected dictionary at key: \(currentPath)"))
}
return nextData
}
} else {
finalData = data
}
guard let array = finalData[String(pathComponents.last!)]?.array else {
throw LeafError(.unknownError("expected array at key: \(loop.array)"))
}
for (idx, item) in array.enumerated() {
var innerContext = data
innerContext["isFirst"] = .bool(idx == array.startIndex)
innerContext["isLast"] = .bool(idx == array.index(before: array.endIndex))
innerContext[loop.index] = .int(idx)
innerContext[loop.item] = item
var serializer = LeafSerializer(
ast: loop.body,
tags: self.tags,
userInfo: self.userInfo,
ignoreUnfoundImports: self.ignoreUnfoundImports
)
var loopBody = try serializer.serialize(context: innerContext)
self.buffer.writeBuffer(&loopBody)
}
}
private func resolve(parameters: [ParameterDeclaration], context data: [String: LeafData]) throws -> [LeafData] {
let resolver = ParameterResolver(
params: parameters,
data: data,
tags: self.tags,
userInfo: self.userInfo
)
return try resolver.resolve().map { $0.result }
}
// Directive resolver for a [ParameterDeclaration] where only one parameter is allowed that must resolve to a single value
private func resolveAtomic(_ parameters: [ParameterDeclaration], context data: [String: LeafData]) throws -> LeafData {
guard parameters.count == 1 else {
if parameters.isEmpty {
throw LeafError(.unknownError("Parameter statement can't be empty"))
} else {
throw LeafError(.unknownError("Parameter statement must hold a single value"))
}
}
return try self.resolve(parameters: parameters, context: data).first ?? .trueNil
}
private func peek() -> Syntax? {
guard self.offset < self.ast.count else {
return nil
}
return self.ast[self.offset]
}
private mutating func pop() {
self.offset += 1
}
}