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