generated from ianlewis/repo-template
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtemplate_example_test.go
More file actions
584 lines (495 loc) · 14.5 KB
/
template_example_test.go
File metadata and controls
584 lines (495 loc) · 14.5 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// Copyright 2023 Google LLC
// Copyright 2025 Ian Lewis
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lexparse_test
import (
"context"
"errors"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"unicode"
"github.com/ianlewis/lexparse"
)
const (
lexTypeText lexparse.TokenType = iota
lexTypeBlockStart
lexTypeBlockEnd
lexTypeVarStart
lexTypeVarEnd
lexTypeIdentifier
)
const (
tokenBlockStart = "{%"
tokenBlockEnd = "%}"
tokenVarStart = "{{"
tokenVarEnd = "}}"
tokenIf = "if"
tokenElse = "else"
tokenEndif = "endif"
)
var (
errRune = errors.New("unexpected rune")
errIdentifier = errors.New("unexpected identifier")
)
// Identifier regexp.
var (
idenRegexp = regexp.MustCompile(`[a-zA-Z]+[a-zA-Z0-9]*`)
symbolRegexp = regexp.MustCompile(`[{}%]+`)
)
type tmplNodeType int
const (
// nodeTypeSeq is a node whose children are various text, if, var nodes in
// order.
nodeTypeSeq tmplNodeType = iota
// nodeTypeText is a leaf node comprised of text.
nodeTypeText
// nodeTypeBranch is a binary node whose first child is the 'if' sequence
// node and second is the 'else' sequence node.
nodeTypeBranch
// nodeTypeVar nodes are variable leaf nodes.
nodeTypeVar
)
type tmplNode struct {
typ tmplNodeType
// Fields below are populated based on node type.
varName string
text string
}
func (n *tmplNode) String() string {
switch n.typ {
case nodeTypeSeq:
return "[]"
case nodeTypeText:
return fmt.Sprintf("%q", n.text)
case nodeTypeBranch:
return "if/else"
case nodeTypeVar:
return fmt.Sprintf("{{%s}}", n.varName)
default:
return "<Unknown>"
}
}
func lexTokenErr(err error, t *lexparse.Token) error {
return fmt.Errorf("%w: %s", err, t)
}
// lexText tokenizes normal text.
//
//nolint:ireturn // returning interface is required to satisfy lexparse.LexState.
func lexText(ctx *lexparse.CustomLexerContext) (lexparse.LexState, error) {
for {
p := string(ctx.PeekN(2))
if p == tokenBlockStart || p == tokenVarStart {
if ctx.Width() > 0 {
ctx.Emit(lexTypeText)
}
return lexparse.LexStateFn(lexCode), nil
}
// Advance the input.
if !ctx.Advance() {
// End of input. Emit the text up to this point.
if ctx.Width() > 0 {
ctx.Emit(lexTypeText)
}
return nil, io.EOF
}
}
}
// lexCode tokenizes template code.
//
//nolint:ireturn // returning interface is required to satisfy lexparse.LexState.
func lexCode(ctx *lexparse.CustomLexerContext) (lexparse.LexState, error) {
// Consume whitespace and discard it.
// TODO(#94): use backtracking
for unicode.IsSpace(ctx.Peek()) {
if !ctx.Discard() {
// End of input
return nil, io.EOF
}
}
rn := ctx.Peek()
switch {
case idenRegexp.MatchString(string(rn)):
return lexparse.LexStateFn(lexIden), nil
case symbolRegexp.MatchString(string(rn)):
return lexparse.LexStateFn(lexSymbol), nil
default:
return nil, fmt.Errorf("%w: %q; line: %d, column: %d", errRune,
rn, ctx.Pos().Line, ctx.Pos().Column)
}
}
// lexIden tokenizes identifiers (e.g. variable names).
//
//nolint:ireturn // returning interface is required to satisfy lexparse.LexState.
func lexIden(ctx *lexparse.CustomLexerContext) (lexparse.LexState, error) {
for {
if rn := ctx.Peek(); !idenRegexp.MatchString(string(rn)) {
ctx.Emit(lexTypeIdentifier)
return lexparse.LexStateFn(lexCode), nil
}
if !ctx.Advance() {
return nil, io.EOF
}
}
}
// lexSymbol tokenizes template symbols (e.g. {%, {{, }}, %}).
//
//nolint:ireturn // returning interface is required to satisfy lexparse.LexState.
func lexSymbol(ctx *lexparse.CustomLexerContext) (lexparse.LexState, error) {
for {
switch ctx.Token() {
case tokenVarStart:
ctx.Emit(lexTypeVarStart)
return lexparse.LexStateFn(lexCode), nil
case tokenVarEnd:
ctx.Emit(lexTypeVarEnd)
return lexparse.LexStateFn(lexText), nil
case tokenBlockStart:
ctx.Emit(lexTypeBlockStart)
return lexparse.LexStateFn(lexCode), nil
case tokenBlockEnd:
ctx.Emit(lexTypeBlockEnd)
return lexparse.LexStateFn(lexText), nil
default:
if rn := ctx.Peek(); !symbolRegexp.MatchString(string(rn)) {
return nil, fmt.Errorf("symbol: %w: %q; line: %d, column: %d",
errRune, rn, ctx.Pos().Line, ctx.Pos().Column)
}
}
if !ctx.Advance() {
return nil, io.EOF
}
}
}
// parseRoot updates the root node to be a sequence block.
func parseRoot(ctx *lexparse.ParserContext[*tmplNode]) error {
ctx.Replace(&tmplNode{
typ: nodeTypeSeq,
})
ctx.PushState(lexparse.ParseStateFn(parseSeq))
return nil
}
// parseSeq delegates to another parse function based on token type.
func parseSeq(ctx *lexparse.ParserContext[*tmplNode]) error {
token := ctx.Peek()
switch token.Type {
case lexTypeText:
ctx.PushState(lexparse.ParseStateFn(parseText))
case lexTypeVarStart:
ctx.PushState(lexparse.ParseStateFn(parseVarStart))
case lexTypeBlockStart:
ctx.PushState(lexparse.ParseStateFn(parseBlockStart))
default:
}
return nil
}
// parseText handles normal text.
func parseText(ctx *lexparse.ParserContext[*tmplNode]) error {
token := ctx.Next()
// Emit a text node.
ctx.Node(&tmplNode{
typ: nodeTypeText,
text: token.Value,
})
// Return to handling a sequence.
ctx.PushState(lexparse.ParseStateFn(parseSeq))
return nil
}
// parseVarStart handles var start (e.g. '{{').
func parseVarStart(ctx *lexparse.ParserContext[*tmplNode]) error {
// Consume the var start token.
_ = ctx.Next()
ctx.PushState(
lexparse.ParseStateFn(parseVar),
lexparse.ParseStateFn(parseVarEnd),
)
return nil
}
// parseVar handles replacement variables (e.g. the 'var' in {{ var }}).
func parseVar(ctx *lexparse.ParserContext[*tmplNode]) error {
switch token := ctx.Next(); token.Type {
case lexTypeIdentifier:
// Validate the variable name.
if !idenRegexp.MatchString(token.Value) {
return lexTokenErr(fmt.Errorf("%w: invalid variable name", errIdentifier), token)
}
// Add a variable node.
_ = ctx.Node(&tmplNode{
typ: nodeTypeVar,
varName: token.Value,
})
return nil
case lexparse.TokenTypeEOF:
return fmt.Errorf("%w: parsing variable name", io.ErrUnexpectedEOF)
default:
return lexTokenErr(errIdentifier, token)
}
}
// parseVarEnd handles var end (e.g. '}}').
func parseVarEnd(ctx *lexparse.ParserContext[*tmplNode]) error {
switch token := ctx.Next(); token.Type {
case lexTypeVarEnd:
// Go back to parsing template init state.
ctx.PushState(lexparse.ParseStateFn(parseSeq))
return nil
case lexparse.TokenTypeEOF:
return fmt.Errorf("%w: unclosed variable, expected %q", io.ErrUnexpectedEOF, tokenVarEnd)
default:
return fmt.Errorf("%w: expected %q", lexTokenErr(errIdentifier, token), tokenVarEnd)
}
}
// parseBranch handles the start if conditional block.
func parseBranch(ctx *lexparse.ParserContext[*tmplNode]) error {
switch token := ctx.Next(); token.Type {
case lexTypeIdentifier:
if token.Value != tokenIf {
return fmt.Errorf("%w: expected %q", errIdentifier, tokenIf)
}
// Add a branch node.
_ = ctx.Push(&tmplNode{
typ: nodeTypeBranch,
})
ctx.PushState(
// Parse the conditional expression. Currently only a simple
// variable is supported.
lexparse.ParseStateFn(parseVar),
// Parse the '%}'
lexparse.ParseStateFn(parseBlockEnd),
// Parse the if block.
lexparse.ParseStateFn(parseIf),
// Parse an 'else' (or 'endif')
lexparse.ParseStateFn(parseElse),
)
return nil
case lexparse.TokenTypeEOF:
return fmt.Errorf("%w: expected %q", io.ErrUnexpectedEOF, tokenIf)
default:
return lexTokenErr(errIdentifier, token)
}
}
// parseIf handles the if body.
func parseIf(ctx *lexparse.ParserContext[*tmplNode]) error {
// Add an if body sequence node.
_ = ctx.Push(&tmplNode{
typ: nodeTypeSeq,
})
ctx.PushState(lexparse.ParseStateFn(parseSeq))
return nil
}
// parseElse handles an else (or endif) block.
func parseElse(ctx *lexparse.ParserContext[*tmplNode]) error {
token := ctx.Peek()
switch token.Type {
case lexTypeIdentifier:
// Validate we are at a sequence node.
if cur := ctx.Pos(); cur.Value.typ != nodeTypeSeq {
return lexTokenErr(errIdentifier, token)
}
case lexparse.TokenTypeEOF:
return fmt.Errorf("%w: unclosed if block, looking for %q or %q", io.ErrUnexpectedEOF, tokenElse, tokenEndif)
default:
return lexTokenErr(errIdentifier, token)
}
switch token.Value {
case tokenElse:
// Consume the token.
_ = ctx.Next()
// Climb the tree back to the conditional.
ctx.Climb()
// Validate that we are in a conditional and there isn't already an else branch.
if cur := ctx.Pos(); cur.Value.typ != nodeTypeBranch || len(cur.Children) != 2 {
return lexTokenErr(errIdentifier, token)
}
// Add an else sequence node to the conditional.
_ = ctx.Push(&tmplNode{
typ: nodeTypeSeq,
})
ctx.PushState(
// Parse the '%}'
lexparse.ParseStateFn(parseBlockEnd),
// parse the else sequence block.
lexparse.ParseStateFn(parseSeq),
// parse the endif.
lexparse.ParseStateFn(parseEndif),
)
case tokenEndif:
ctx.PushState(lexparse.ParseStateFn(parseEndif))
default:
return lexTokenErr(fmt.Errorf("%w: looking for %q or %q", errIdentifier, tokenElse, tokenEndif), token)
}
return nil
}
// parseEndif handles either an endif block.
func parseEndif(ctx *lexparse.ParserContext[*tmplNode]) error {
switch token := ctx.Next(); token.Type {
case lexTypeIdentifier:
if token.Value != tokenEndif {
return lexTokenErr(fmt.Errorf("%w: looking for %q", errIdentifier, tokenEndif), token)
}
// Climb out of the sequence node.
ctx.Climb()
// Climb out of the branch node.
ctx.Climb()
ctx.PushState(
// parse the '%}'
lexparse.ParseStateFn(parseBlockEnd),
// Go back to parsing a sequence.
lexparse.ParseStateFn(parseSeq),
)
return nil
case lexparse.TokenTypeEOF:
return fmt.Errorf("%w: looking for %q", io.ErrUnexpectedEOF, tokenEndif)
default:
return lexTokenErr(errIdentifier, token)
}
}
// parseBlockStart handles the start of a template block '{%'.
func parseBlockStart(ctx *lexparse.ParserContext[*tmplNode]) error {
// Validate the block start token.
switch token := ctx.Next(); token.Type {
case lexTypeBlockStart:
// OK
case lexparse.TokenTypeEOF:
return fmt.Errorf("%w: expected %q", io.ErrUnexpectedEOF, tokenBlockStart)
default:
return lexTokenErr(errIdentifier, token)
}
// Validate the command token.
token := ctx.Peek()
switch token.Type {
case lexTypeIdentifier:
// OK
case lexparse.TokenTypeEOF:
return fmt.Errorf("%w: expected %q", io.ErrUnexpectedEOF, tokenBlockStart)
default:
return fmt.Errorf("%w: expected %q, %q, or %q",
lexTokenErr(errIdentifier, token), tokenIf, tokenElse, tokenEndif)
}
// Handle the block command.
switch token.Value {
case tokenIf:
ctx.PushState(lexparse.ParseStateFn(parseBranch))
case tokenElse, tokenEndif:
// NOTE: parseElse, parseEndif should already be on the stack.
default:
return lexTokenErr(
fmt.Errorf("%w: expected %q, %q, or %q", errIdentifier, tokenIf, tokenElse, tokenEndif), token)
}
return nil
}
// parseBlockEnd handles the end of a template block '%}'.
func parseBlockEnd(ctx *lexparse.ParserContext[*tmplNode]) error {
switch token := ctx.Next(); token.Type {
case lexTypeBlockEnd:
return nil
case lexparse.TokenTypeEOF:
return fmt.Errorf("%w: expected %q", io.ErrUnexpectedEOF, tokenBlockEnd)
default:
return lexTokenErr(fmt.Errorf("%w: expected %q", errIdentifier, tokenBlockEnd), token)
}
}
// Execute renders the template with the given data.
func Execute(root *lexparse.Node[*tmplNode], data map[string]string) (string, error) {
var b strings.Builder
// Support basic boolean values.
if _, ok := data["true"]; !ok {
data["true"] = "true"
}
if _, ok := data["false"]; !ok {
data["false"] = "false"
}
if err := execNode(root, data, &b); err != nil {
return "", err
}
return b.String(), nil
}
func execNode(root *lexparse.Node[*tmplNode], data map[string]string, bldr *strings.Builder) error {
for _, node := range root.Children {
switch node.Value.typ {
case nodeTypeText:
// Write raw text to the output.
bldr.WriteString(node.Value.text)
case nodeTypeVar:
// Replace templated variables with given data.
bldr.WriteString(data[node.Value.varName])
case nodeTypeBranch:
// condition sanity check
if len(node.Children) < 2 {
panic(fmt.Sprintf("invalid branch: %#v", node))
}
// Get the condition.
cond := node.Children[0]
// Condition sanity check
if cond.Value.typ != nodeTypeVar {
panic(fmt.Sprintf("invalid branch condition: %#v", cond))
}
v, err := strconv.ParseBool(data[node.Value.varName])
if (err == nil && v) || (err != nil && data[node.Value.varName] != "") {
if err := execNode(node.Children[0], data, bldr); err != nil {
return err
}
} else {
if err := execNode(node.Children[1], data, bldr); err != nil {
return err
}
}
case nodeTypeSeq:
if err := execNode(node, data, bldr); err != nil {
return err
}
}
}
return nil
}
// Example_templateEngine implements a simple text templating language. The
// language replaces variables identified with double brackets
// (e.g. `{{ var }}`) with data values for those variables.
//
// LexParse is used to lex and parse the template into a parse tree. This tree
// can be passed with a data map to the Execute function to interpret the
// template and retrieve a final result.
//
// This example includes some best practices for error handling, such as
// including line and column numbers in error messages.
func Example_templateEngine() {
r := strings.NewReader(`Hello, {% if subject %}{{ subject }}{% else %}World{% endif %}!`)
tree, err := lexparse.LexParse(
context.Background(),
lexparse.NewCustomLexer(r, lexparse.LexStateFn(lexText)),
lexparse.ParseStateFn(parseRoot),
)
if err != nil {
panic(err)
}
fmt.Println(tree)
txt, err := Execute(tree, map[string]string{"subject": "世界"})
if err != nil {
panic(err)
}
fmt.Print(txt)
// Output:
// [] (0:0)
// ├── "Hello, " (1:1)
// ├── if/else (1:11)
// │ ├── {{subject}} (1:14)
// │ ├── [] (1:22)
// │ │ └── {{subject}} (1:27)
// │ └── [] (1:40)
// │ └── "World" (1:47)
// └── "!" (1:63)
//
// Hello, 世界!
}