github.com/FenixAra/go@v0.0.0-20170127160404-96ea0918e670/src/text/template/parse/parse.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package parse builds parse trees for templates as defined by text/template 6 // and html/template. Clients should use those packages to construct templates 7 // rather than this one, which provides shared internal data structures not 8 // intended for general use. 9 package parse 10 11 import ( 12 "bytes" 13 "fmt" 14 "runtime" 15 "strconv" 16 "strings" 17 ) 18 19 // Tree is the representation of a single parsed template. 20 type Tree struct { 21 Name string // name of the template represented by the tree. 22 ParseName string // name of the top-level template during parsing, for error messages. 23 Root *ListNode // top-level root of the tree. 24 text string // text parsed to create the template (or its parent) 25 // Parsing only; cleared after parse. 26 funcs []map[string]interface{} 27 lex *lexer 28 token [3]item // three-token lookahead for parser. 29 peekCount int 30 vars []string // variables defined at the moment. 31 treeSet map[string]*Tree 32 } 33 34 // Copy returns a copy of the Tree. Any parsing state is discarded. 35 func (t *Tree) Copy() *Tree { 36 if t == nil { 37 return nil 38 } 39 return &Tree{ 40 Name: t.Name, 41 ParseName: t.ParseName, 42 Root: t.Root.CopyList(), 43 text: t.text, 44 } 45 } 46 47 // Parse returns a map from template name to parse.Tree, created by parsing the 48 // templates described in the argument string. The top-level template will be 49 // given the specified name. If an error is encountered, parsing stops and an 50 // empty map is returned with the error. 51 func Parse(name, text, leftDelim, rightDelim string, funcs ...map[string]interface{}) (map[string]*Tree, error) { 52 treeSet := make(map[string]*Tree) 53 t := New(name) 54 t.text = text 55 _, err := t.Parse(text, leftDelim, rightDelim, treeSet, funcs...) 56 return treeSet, err 57 } 58 59 // next returns the next token. 60 func (t *Tree) next() item { 61 if t.peekCount > 0 { 62 t.peekCount-- 63 } else { 64 t.token[0] = t.lex.nextItem() 65 } 66 return t.token[t.peekCount] 67 } 68 69 // backup backs the input stream up one token. 70 func (t *Tree) backup() { 71 t.peekCount++ 72 } 73 74 // backup2 backs the input stream up two tokens. 75 // The zeroth token is already there. 76 func (t *Tree) backup2(t1 item) { 77 t.token[1] = t1 78 t.peekCount = 2 79 } 80 81 // backup3 backs the input stream up three tokens 82 // The zeroth token is already there. 83 func (t *Tree) backup3(t2, t1 item) { // Reverse order: we're pushing back. 84 t.token[1] = t1 85 t.token[2] = t2 86 t.peekCount = 3 87 } 88 89 // peek returns but does not consume the next token. 90 func (t *Tree) peek() item { 91 if t.peekCount > 0 { 92 return t.token[t.peekCount-1] 93 } 94 t.peekCount = 1 95 t.token[0] = t.lex.nextItem() 96 return t.token[0] 97 } 98 99 // nextNonSpace returns the next non-space token. 100 func (t *Tree) nextNonSpace() (token item) { 101 for { 102 token = t.next() 103 if token.typ != itemSpace { 104 break 105 } 106 } 107 return token 108 } 109 110 // peekNonSpace returns but does not consume the next non-space token. 111 func (t *Tree) peekNonSpace() (token item) { 112 for { 113 token = t.next() 114 if token.typ != itemSpace { 115 break 116 } 117 } 118 t.backup() 119 return token 120 } 121 122 // Parsing. 123 124 // New allocates a new parse tree with the given name. 125 func New(name string, funcs ...map[string]interface{}) *Tree { 126 return &Tree{ 127 Name: name, 128 funcs: funcs, 129 } 130 } 131 132 // ErrorContext returns a textual representation of the location of the node in the input text. 133 // The receiver is only used when the node does not have a pointer to the tree inside, 134 // which can occur in old code. 135 func (t *Tree) ErrorContext(n Node) (location, context string) { 136 pos := int(n.Position()) 137 tree := n.tree() 138 if tree == nil { 139 tree = t 140 } 141 text := tree.text[:pos] 142 byteNum := strings.LastIndex(text, "\n") 143 if byteNum == -1 { 144 byteNum = pos // On first line. 145 } else { 146 byteNum++ // After the newline. 147 byteNum = pos - byteNum 148 } 149 lineNum := 1 + strings.Count(text, "\n") 150 context = n.String() 151 if len(context) > 20 { 152 context = fmt.Sprintf("%.20s...", context) 153 } 154 return fmt.Sprintf("%s:%d:%d", tree.ParseName, lineNum, byteNum), context 155 } 156 157 // errorf formats the error and terminates processing. 158 func (t *Tree) errorf(format string, args ...interface{}) { 159 t.Root = nil 160 format = fmt.Sprintf("template: %s:%d: %s", t.ParseName, t.token[0].line, format) 161 panic(fmt.Errorf(format, args...)) 162 } 163 164 // error terminates processing. 165 func (t *Tree) error(err error) { 166 t.errorf("%s", err) 167 } 168 169 // expect consumes the next token and guarantees it has the required type. 170 func (t *Tree) expect(expected itemType, context string) item { 171 token := t.nextNonSpace() 172 if token.typ != expected { 173 t.unexpected(token, context) 174 } 175 return token 176 } 177 178 // expectOneOf consumes the next token and guarantees it has one of the required types. 179 func (t *Tree) expectOneOf(expected1, expected2 itemType, context string) item { 180 token := t.nextNonSpace() 181 if token.typ != expected1 && token.typ != expected2 { 182 t.unexpected(token, context) 183 } 184 return token 185 } 186 187 // unexpected complains about the token and terminates processing. 188 func (t *Tree) unexpected(token item, context string) { 189 t.errorf("unexpected %s in %s", token, context) 190 } 191 192 // recover is the handler that turns panics into returns from the top level of Parse. 193 func (t *Tree) recover(errp *error) { 194 e := recover() 195 if e != nil { 196 if _, ok := e.(runtime.Error); ok { 197 panic(e) 198 } 199 if t != nil { 200 t.lex.drain() 201 t.stopParse() 202 } 203 *errp = e.(error) 204 } 205 return 206 } 207 208 // startParse initializes the parser, using the lexer. 209 func (t *Tree) startParse(funcs []map[string]interface{}, lex *lexer, treeSet map[string]*Tree) { 210 t.Root = nil 211 t.lex = lex 212 t.vars = []string{"$"} 213 t.funcs = funcs 214 t.treeSet = treeSet 215 } 216 217 // stopParse terminates parsing. 218 func (t *Tree) stopParse() { 219 t.lex = nil 220 t.vars = nil 221 t.funcs = nil 222 t.treeSet = nil 223 } 224 225 // Parse parses the template definition string to construct a representation of 226 // the template for execution. If either action delimiter string is empty, the 227 // default ("{{" or "}}") is used. Embedded template definitions are added to 228 // the treeSet map. 229 func (t *Tree) Parse(text, leftDelim, rightDelim string, treeSet map[string]*Tree, funcs ...map[string]interface{}) (tree *Tree, err error) { 230 defer t.recover(&err) 231 t.ParseName = t.Name 232 t.startParse(funcs, lex(t.Name, text, leftDelim, rightDelim), treeSet) 233 t.text = text 234 t.parse() 235 t.add() 236 t.stopParse() 237 return t, nil 238 } 239 240 // add adds tree to t.treeSet. 241 func (t *Tree) add() { 242 tree := t.treeSet[t.Name] 243 if tree == nil || IsEmptyTree(tree.Root) { 244 t.treeSet[t.Name] = t 245 return 246 } 247 if !IsEmptyTree(t.Root) { 248 t.errorf("template: multiple definition of template %q", t.Name) 249 } 250 } 251 252 // IsEmptyTree reports whether this tree (node) is empty of everything but space. 253 func IsEmptyTree(n Node) bool { 254 switch n := n.(type) { 255 case nil: 256 return true 257 case *ActionNode: 258 case *IfNode: 259 case *ListNode: 260 for _, node := range n.Nodes { 261 if !IsEmptyTree(node) { 262 return false 263 } 264 } 265 return true 266 case *RangeNode: 267 case *TemplateNode: 268 case *TextNode: 269 return len(bytes.TrimSpace(n.Text)) == 0 270 case *WithNode: 271 default: 272 panic("unknown node: " + n.String()) 273 } 274 return false 275 } 276 277 // parse is the top-level parser for a template, essentially the same 278 // as itemList except it also parses {{define}} actions. 279 // It runs to EOF. 280 func (t *Tree) parse() { 281 t.Root = t.newList(t.peek().pos) 282 for t.peek().typ != itemEOF { 283 if t.peek().typ == itemLeftDelim { 284 delim := t.next() 285 if t.nextNonSpace().typ == itemDefine { 286 newT := New("definition") // name will be updated once we know it. 287 newT.text = t.text 288 newT.ParseName = t.ParseName 289 newT.startParse(t.funcs, t.lex, t.treeSet) 290 newT.parseDefinition() 291 continue 292 } 293 t.backup2(delim) 294 } 295 switch n := t.textOrAction(); n.Type() { 296 case nodeEnd, nodeElse: 297 t.errorf("unexpected %s", n) 298 default: 299 t.Root.append(n) 300 } 301 } 302 } 303 304 // parseDefinition parses a {{define}} ... {{end}} template definition and 305 // installs the definition in t.treeSet. The "define" keyword has already 306 // been scanned. 307 func (t *Tree) parseDefinition() { 308 const context = "define clause" 309 name := t.expectOneOf(itemString, itemRawString, context) 310 var err error 311 t.Name, err = strconv.Unquote(name.val) 312 if err != nil { 313 t.error(err) 314 } 315 t.expect(itemRightDelim, context) 316 var end Node 317 t.Root, end = t.itemList() 318 if end.Type() != nodeEnd { 319 t.errorf("unexpected %s in %s", end, context) 320 } 321 t.add() 322 t.stopParse() 323 } 324 325 // itemList: 326 // textOrAction* 327 // Terminates at {{end}} or {{else}}, returned separately. 328 func (t *Tree) itemList() (list *ListNode, next Node) { 329 list = t.newList(t.peekNonSpace().pos) 330 for t.peekNonSpace().typ != itemEOF { 331 n := t.textOrAction() 332 switch n.Type() { 333 case nodeEnd, nodeElse: 334 return list, n 335 } 336 list.append(n) 337 } 338 t.errorf("unexpected EOF") 339 return 340 } 341 342 // textOrAction: 343 // text | action 344 func (t *Tree) textOrAction() Node { 345 switch token := t.nextNonSpace(); token.typ { 346 case itemText: 347 return t.newText(token.pos, token.val) 348 case itemLeftDelim: 349 return t.action() 350 default: 351 t.unexpected(token, "input") 352 } 353 return nil 354 } 355 356 // Action: 357 // control 358 // command ("|" command)* 359 // Left delim is past. Now get actions. 360 // First word could be a keyword such as range. 361 func (t *Tree) action() (n Node) { 362 switch token := t.nextNonSpace(); token.typ { 363 case itemBlock: 364 return t.blockControl() 365 case itemElse: 366 return t.elseControl() 367 case itemEnd: 368 return t.endControl() 369 case itemIf: 370 return t.ifControl() 371 case itemRange: 372 return t.rangeControl() 373 case itemTemplate: 374 return t.templateControl() 375 case itemWith: 376 return t.withControl() 377 } 378 t.backup() 379 token := t.peek() 380 // Do not pop variables; they persist until "end". 381 return t.newAction(token.pos, token.line, t.pipeline("command")) 382 } 383 384 // Pipeline: 385 // declarations? command ('|' command)* 386 func (t *Tree) pipeline(context string) (pipe *PipeNode) { 387 var decl []*VariableNode 388 token := t.peekNonSpace() 389 pos := token.pos 390 // Are there declarations? 391 for { 392 if v := t.peekNonSpace(); v.typ == itemVariable { 393 t.next() 394 // Since space is a token, we need 3-token look-ahead here in the worst case: 395 // in "$x foo" we need to read "foo" (as opposed to ":=") to know that $x is an 396 // argument variable rather than a declaration. So remember the token 397 // adjacent to the variable so we can push it back if necessary. 398 tokenAfterVariable := t.peek() 399 if next := t.peekNonSpace(); next.typ == itemColonEquals || (next.typ == itemChar && next.val == ",") { 400 t.nextNonSpace() 401 variable := t.newVariable(v.pos, v.val) 402 decl = append(decl, variable) 403 t.vars = append(t.vars, v.val) 404 if next.typ == itemChar && next.val == "," { 405 if context == "range" && len(decl) < 2 { 406 continue 407 } 408 t.errorf("too many declarations in %s", context) 409 } 410 } else if tokenAfterVariable.typ == itemSpace { 411 t.backup3(v, tokenAfterVariable) 412 } else { 413 t.backup2(v) 414 } 415 } 416 break 417 } 418 pipe = t.newPipeline(pos, token.line, decl) 419 for { 420 switch token := t.nextNonSpace(); token.typ { 421 case itemRightDelim, itemRightParen: 422 // At this point, the pipeline is complete 423 t.checkPipeline(pipe, context) 424 if token.typ == itemRightParen { 425 t.backup() 426 } 427 return 428 case itemBool, itemCharConstant, itemComplex, itemDot, itemField, itemIdentifier, 429 itemNumber, itemNil, itemRawString, itemString, itemVariable, itemLeftParen: 430 t.backup() 431 pipe.append(t.command()) 432 default: 433 t.unexpected(token, context) 434 } 435 } 436 } 437 438 func (t *Tree) checkPipeline(pipe *PipeNode, context string) { 439 // Reject empty pipelines 440 if len(pipe.Cmds) == 0 { 441 t.errorf("missing value for %s", context) 442 } 443 // Only the first command of a pipeline can start with a non executable operand 444 for i, c := range pipe.Cmds[1:] { 445 switch c.Args[0].Type() { 446 case NodeBool, NodeDot, NodeNil, NodeNumber, NodeString: 447 // With A|B|C, pipeline stage 2 is B 448 t.errorf("non executable command in pipeline stage %d", i+2) 449 } 450 } 451 } 452 453 func (t *Tree) parseControl(allowElseIf bool, context string) (pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) { 454 defer t.popVars(len(t.vars)) 455 pipe = t.pipeline(context) 456 var next Node 457 list, next = t.itemList() 458 switch next.Type() { 459 case nodeEnd: //done 460 case nodeElse: 461 if allowElseIf { 462 // Special case for "else if". If the "else" is followed immediately by an "if", 463 // the elseControl will have left the "if" token pending. Treat 464 // {{if a}}_{{else if b}}_{{end}} 465 // as 466 // {{if a}}_{{else}}{{if b}}_{{end}}{{end}}. 467 // To do this, parse the if as usual and stop at it {{end}}; the subsequent{{end}} 468 // is assumed. This technique works even for long if-else-if chains. 469 // TODO: Should we allow else-if in with and range? 470 if t.peek().typ == itemIf { 471 t.next() // Consume the "if" token. 472 elseList = t.newList(next.Position()) 473 elseList.append(t.ifControl()) 474 // Do not consume the next item - only one {{end}} required. 475 break 476 } 477 } 478 elseList, next = t.itemList() 479 if next.Type() != nodeEnd { 480 t.errorf("expected end; found %s", next) 481 } 482 } 483 return pipe.Position(), pipe.Line, pipe, list, elseList 484 } 485 486 // If: 487 // {{if pipeline}} itemList {{end}} 488 // {{if pipeline}} itemList {{else}} itemList {{end}} 489 // If keyword is past. 490 func (t *Tree) ifControl() Node { 491 return t.newIf(t.parseControl(true, "if")) 492 } 493 494 // Range: 495 // {{range pipeline}} itemList {{end}} 496 // {{range pipeline}} itemList {{else}} itemList {{end}} 497 // Range keyword is past. 498 func (t *Tree) rangeControl() Node { 499 return t.newRange(t.parseControl(false, "range")) 500 } 501 502 // With: 503 // {{with pipeline}} itemList {{end}} 504 // {{with pipeline}} itemList {{else}} itemList {{end}} 505 // If keyword is past. 506 func (t *Tree) withControl() Node { 507 return t.newWith(t.parseControl(false, "with")) 508 } 509 510 // End: 511 // {{end}} 512 // End keyword is past. 513 func (t *Tree) endControl() Node { 514 return t.newEnd(t.expect(itemRightDelim, "end").pos) 515 } 516 517 // Else: 518 // {{else}} 519 // Else keyword is past. 520 func (t *Tree) elseControl() Node { 521 // Special case for "else if". 522 peek := t.peekNonSpace() 523 if peek.typ == itemIf { 524 // We see "{{else if ... " but in effect rewrite it to {{else}}{{if ... ". 525 return t.newElse(peek.pos, peek.line) 526 } 527 token := t.expect(itemRightDelim, "else") 528 return t.newElse(token.pos, token.line) 529 } 530 531 // Block: 532 // {{block stringValue pipeline}} 533 // Block keyword is past. 534 // The name must be something that can evaluate to a string. 535 // The pipeline is mandatory. 536 func (t *Tree) blockControl() Node { 537 const context = "block clause" 538 539 token := t.nextNonSpace() 540 name := t.parseTemplateName(token, context) 541 pipe := t.pipeline(context) 542 543 block := New(name) // name will be updated once we know it. 544 block.text = t.text 545 block.ParseName = t.ParseName 546 block.startParse(t.funcs, t.lex, t.treeSet) 547 var end Node 548 block.Root, end = block.itemList() 549 if end.Type() != nodeEnd { 550 t.errorf("unexpected %s in %s", end, context) 551 } 552 block.add() 553 block.stopParse() 554 555 return t.newTemplate(token.pos, token.line, name, pipe) 556 } 557 558 // Template: 559 // {{template stringValue pipeline}} 560 // Template keyword is past. The name must be something that can evaluate 561 // to a string. 562 func (t *Tree) templateControl() Node { 563 const context = "template clause" 564 token := t.nextNonSpace() 565 name := t.parseTemplateName(token, context) 566 var pipe *PipeNode 567 if t.nextNonSpace().typ != itemRightDelim { 568 t.backup() 569 // Do not pop variables; they persist until "end". 570 pipe = t.pipeline(context) 571 } 572 return t.newTemplate(token.pos, token.line, name, pipe) 573 } 574 575 func (t *Tree) parseTemplateName(token item, context string) (name string) { 576 switch token.typ { 577 case itemString, itemRawString: 578 s, err := strconv.Unquote(token.val) 579 if err != nil { 580 t.error(err) 581 } 582 name = s 583 default: 584 t.unexpected(token, context) 585 } 586 return 587 } 588 589 // command: 590 // operand (space operand)* 591 // space-separated arguments up to a pipeline character or right delimiter. 592 // we consume the pipe character but leave the right delim to terminate the action. 593 func (t *Tree) command() *CommandNode { 594 cmd := t.newCommand(t.peekNonSpace().pos) 595 for { 596 t.peekNonSpace() // skip leading spaces. 597 operand := t.operand() 598 if operand != nil { 599 cmd.append(operand) 600 } 601 switch token := t.next(); token.typ { 602 case itemSpace: 603 continue 604 case itemError: 605 t.errorf("%s", token.val) 606 case itemRightDelim, itemRightParen: 607 t.backup() 608 case itemPipe: 609 default: 610 t.errorf("unexpected %s in operand", token) 611 } 612 break 613 } 614 if len(cmd.Args) == 0 { 615 t.errorf("empty command") 616 } 617 return cmd 618 } 619 620 // operand: 621 // term .Field* 622 // An operand is a space-separated component of a command, 623 // a term possibly followed by field accesses. 624 // A nil return means the next item is not an operand. 625 func (t *Tree) operand() Node { 626 node := t.term() 627 if node == nil { 628 return nil 629 } 630 if t.peek().typ == itemField { 631 chain := t.newChain(t.peek().pos, node) 632 for t.peek().typ == itemField { 633 chain.Add(t.next().val) 634 } 635 // Compatibility with original API: If the term is of type NodeField 636 // or NodeVariable, just put more fields on the original. 637 // Otherwise, keep the Chain node. 638 // Obvious parsing errors involving literal values are detected here. 639 // More complex error cases will have to be handled at execution time. 640 switch node.Type() { 641 case NodeField: 642 node = t.newField(chain.Position(), chain.String()) 643 case NodeVariable: 644 node = t.newVariable(chain.Position(), chain.String()) 645 case NodeBool, NodeString, NodeNumber, NodeNil, NodeDot: 646 t.errorf("unexpected . after term %q", node.String()) 647 default: 648 node = chain 649 } 650 } 651 return node 652 } 653 654 // term: 655 // literal (number, string, nil, boolean) 656 // function (identifier) 657 // . 658 // .Field 659 // $ 660 // '(' pipeline ')' 661 // A term is a simple "expression". 662 // A nil return means the next item is not a term. 663 func (t *Tree) term() Node { 664 switch token := t.nextNonSpace(); token.typ { 665 case itemError: 666 t.errorf("%s", token.val) 667 case itemIdentifier: 668 if !t.hasFunction(token.val) { 669 t.errorf("function %q not defined", token.val) 670 } 671 return NewIdentifier(token.val).SetTree(t).SetPos(token.pos) 672 case itemDot: 673 return t.newDot(token.pos) 674 case itemNil: 675 return t.newNil(token.pos) 676 case itemVariable: 677 return t.useVar(token.pos, token.val) 678 case itemField: 679 return t.newField(token.pos, token.val) 680 case itemBool: 681 return t.newBool(token.pos, token.val == "true") 682 case itemCharConstant, itemComplex, itemNumber: 683 number, err := t.newNumber(token.pos, token.val, token.typ) 684 if err != nil { 685 t.error(err) 686 } 687 return number 688 case itemLeftParen: 689 pipe := t.pipeline("parenthesized pipeline") 690 if token := t.next(); token.typ != itemRightParen { 691 t.errorf("unclosed right paren: unexpected %s", token) 692 } 693 return pipe 694 case itemString, itemRawString: 695 s, err := strconv.Unquote(token.val) 696 if err != nil { 697 t.error(err) 698 } 699 return t.newString(token.pos, token.val, s) 700 } 701 t.backup() 702 return nil 703 } 704 705 // hasFunction reports if a function name exists in the Tree's maps. 706 func (t *Tree) hasFunction(name string) bool { 707 for _, funcMap := range t.funcs { 708 if funcMap == nil { 709 continue 710 } 711 if funcMap[name] != nil { 712 return true 713 } 714 } 715 return false 716 } 717 718 // popVars trims the variable list to the specified length 719 func (t *Tree) popVars(n int) { 720 t.vars = t.vars[:n] 721 } 722 723 // useVar returns a node for a variable reference. It errors if the 724 // variable is not defined. 725 func (t *Tree) useVar(pos Pos, name string) Node { 726 v := t.newVariable(pos, name) 727 for _, varName := range t.vars { 728 if varName == v.Ident[0] { 729 return v 730 } 731 } 732 t.errorf("undefined variable %q", v.Ident[0]) 733 return nil 734 }