...
Run Format

Source file src/text/template/parse/parse.go

Documentation: text/template/parse

     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  }
   206  
   207  // startParse initializes the parser, using the lexer.
   208  func (t *Tree) startParse(funcs []map[string]interface{}, lex *lexer, treeSet map[string]*Tree) {
   209  	t.Root = nil
   210  	t.lex = lex
   211  	t.vars = []string{"$"}
   212  	t.funcs = funcs
   213  	t.treeSet = treeSet
   214  }
   215  
   216  // stopParse terminates parsing.
   217  func (t *Tree) stopParse() {
   218  	t.lex = nil
   219  	t.vars = nil
   220  	t.funcs = nil
   221  	t.treeSet = nil
   222  }
   223  
   224  // Parse parses the template definition string to construct a representation of
   225  // the template for execution. If either action delimiter string is empty, the
   226  // default ("{{" or "}}") is used. Embedded template definitions are added to
   227  // the treeSet map.
   228  func (t *Tree) Parse(text, leftDelim, rightDelim string, treeSet map[string]*Tree, funcs ...map[string]interface{}) (tree *Tree, err error) {
   229  	defer t.recover(&err)
   230  	t.ParseName = t.Name
   231  	t.startParse(funcs, lex(t.Name, text, leftDelim, rightDelim), treeSet)
   232  	t.text = text
   233  	t.parse()
   234  	t.add()
   235  	t.stopParse()
   236  	return t, nil
   237  }
   238  
   239  // add adds tree to t.treeSet.
   240  func (t *Tree) add() {
   241  	tree := t.treeSet[t.Name]
   242  	if tree == nil || IsEmptyTree(tree.Root) {
   243  		t.treeSet[t.Name] = t
   244  		return
   245  	}
   246  	if !IsEmptyTree(t.Root) {
   247  		t.errorf("template: multiple definition of template %q", t.Name)
   248  	}
   249  }
   250  
   251  // IsEmptyTree reports whether this tree (node) is empty of everything but space.
   252  func IsEmptyTree(n Node) bool {
   253  	switch n := n.(type) {
   254  	case nil:
   255  		return true
   256  	case *ActionNode:
   257  	case *IfNode:
   258  	case *ListNode:
   259  		for _, node := range n.Nodes {
   260  			if !IsEmptyTree(node) {
   261  				return false
   262  			}
   263  		}
   264  		return true
   265  	case *RangeNode:
   266  	case *TemplateNode:
   267  	case *TextNode:
   268  		return len(bytes.TrimSpace(n.Text)) == 0
   269  	case *WithNode:
   270  	default:
   271  		panic("unknown node: " + n.String())
   272  	}
   273  	return false
   274  }
   275  
   276  // parse is the top-level parser for a template, essentially the same
   277  // as itemList except it also parses {{define}} actions.
   278  // It runs to EOF.
   279  func (t *Tree) parse() {
   280  	t.Root = t.newList(t.peek().pos)
   281  	for t.peek().typ != itemEOF {
   282  		if t.peek().typ == itemLeftDelim {
   283  			delim := t.next()
   284  			if t.nextNonSpace().typ == itemDefine {
   285  				newT := New("definition") // name will be updated once we know it.
   286  				newT.text = t.text
   287  				newT.ParseName = t.ParseName
   288  				newT.startParse(t.funcs, t.lex, t.treeSet)
   289  				newT.parseDefinition()
   290  				continue
   291  			}
   292  			t.backup2(delim)
   293  		}
   294  		switch n := t.textOrAction(); n.Type() {
   295  		case nodeEnd, nodeElse:
   296  			t.errorf("unexpected %s", n)
   297  		default:
   298  			t.Root.append(n)
   299  		}
   300  	}
   301  }
   302  
   303  // parseDefinition parses a {{define}} ...  {{end}} template definition and
   304  // installs the definition in t.treeSet. The "define" keyword has already
   305  // been scanned.
   306  func (t *Tree) parseDefinition() {
   307  	const context = "define clause"
   308  	name := t.expectOneOf(itemString, itemRawString, context)
   309  	var err error
   310  	t.Name, err = strconv.Unquote(name.val)
   311  	if err != nil {
   312  		t.error(err)
   313  	}
   314  	t.expect(itemRightDelim, context)
   315  	var end Node
   316  	t.Root, end = t.itemList()
   317  	if end.Type() != nodeEnd {
   318  		t.errorf("unexpected %s in %s", end, context)
   319  	}
   320  	t.add()
   321  	t.stopParse()
   322  }
   323  
   324  // itemList:
   325  //	textOrAction*
   326  // Terminates at {{end}} or {{else}}, returned separately.
   327  func (t *Tree) itemList() (list *ListNode, next Node) {
   328  	list = t.newList(t.peekNonSpace().pos)
   329  	for t.peekNonSpace().typ != itemEOF {
   330  		n := t.textOrAction()
   331  		switch n.Type() {
   332  		case nodeEnd, nodeElse:
   333  			return list, n
   334  		}
   335  		list.append(n)
   336  	}
   337  	t.errorf("unexpected EOF")
   338  	return
   339  }
   340  
   341  // textOrAction:
   342  //	text | action
   343  func (t *Tree) textOrAction() Node {
   344  	switch token := t.nextNonSpace(); token.typ {
   345  	case itemText:
   346  		return t.newText(token.pos, token.val)
   347  	case itemLeftDelim:
   348  		return t.action()
   349  	default:
   350  		t.unexpected(token, "input")
   351  	}
   352  	return nil
   353  }
   354  
   355  // Action:
   356  //	control
   357  //	command ("|" command)*
   358  // Left delim is past. Now get actions.
   359  // First word could be a keyword such as range.
   360  func (t *Tree) action() (n Node) {
   361  	switch token := t.nextNonSpace(); token.typ {
   362  	case itemBlock:
   363  		return t.blockControl()
   364  	case itemElse:
   365  		return t.elseControl()
   366  	case itemEnd:
   367  		return t.endControl()
   368  	case itemIf:
   369  		return t.ifControl()
   370  	case itemRange:
   371  		return t.rangeControl()
   372  	case itemTemplate:
   373  		return t.templateControl()
   374  	case itemWith:
   375  		return t.withControl()
   376  	}
   377  	t.backup()
   378  	token := t.peek()
   379  	// Do not pop variables; they persist until "end".
   380  	return t.newAction(token.pos, token.line, t.pipeline("command"))
   381  }
   382  
   383  // Pipeline:
   384  //	declarations? command ('|' command)*
   385  func (t *Tree) pipeline(context string) (pipe *PipeNode) {
   386  	decl := false
   387  	var vars []*VariableNode
   388  	token := t.peekNonSpace()
   389  	pos := token.pos
   390  	// Are there declarations or assignments?
   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  			next := t.peekNonSpace()
   400  			switch {
   401  			case next.typ == itemAssign, next.typ == itemDeclare,
   402  				next.typ == itemChar && next.val == ",":
   403  				t.nextNonSpace()
   404  				variable := t.newVariable(v.pos, v.val)
   405  				vars = append(vars, variable)
   406  				t.vars = append(t.vars, v.val)
   407  				if next.typ == itemDeclare {
   408  					decl = true
   409  				}
   410  				if next.typ == itemChar && next.val == "," {
   411  					if context == "range" && len(vars) < 2 {
   412  						continue
   413  					}
   414  					t.errorf("too many declarations in %s", context)
   415  				}
   416  			case tokenAfterVariable.typ == itemSpace:
   417  				t.backup3(v, tokenAfterVariable)
   418  			default:
   419  				t.backup2(v)
   420  			}
   421  		}
   422  		break
   423  	}
   424  	pipe = t.newPipeline(pos, token.line, vars)
   425  	pipe.IsAssign = !decl
   426  	for {
   427  		switch token := t.nextNonSpace(); token.typ {
   428  		case itemRightDelim, itemRightParen:
   429  			// At this point, the pipeline is complete
   430  			t.checkPipeline(pipe, context)
   431  			if token.typ == itemRightParen {
   432  				t.backup()
   433  			}
   434  			return
   435  		case itemBool, itemCharConstant, itemComplex, itemDot, itemField, itemIdentifier,
   436  			itemNumber, itemNil, itemRawString, itemString, itemVariable, itemLeftParen:
   437  			t.backup()
   438  			pipe.append(t.command())
   439  		default:
   440  			t.unexpected(token, context)
   441  		}
   442  	}
   443  }
   444  
   445  func (t *Tree) checkPipeline(pipe *PipeNode, context string) {
   446  	// Reject empty pipelines
   447  	if len(pipe.Cmds) == 0 {
   448  		t.errorf("missing value for %s", context)
   449  	}
   450  	// Only the first command of a pipeline can start with a non executable operand
   451  	for i, c := range pipe.Cmds[1:] {
   452  		switch c.Args[0].Type() {
   453  		case NodeBool, NodeDot, NodeNil, NodeNumber, NodeString:
   454  			// With A|B|C, pipeline stage 2 is B
   455  			t.errorf("non executable command in pipeline stage %d", i+2)
   456  		}
   457  	}
   458  }
   459  
   460  func (t *Tree) parseControl(allowElseIf bool, context string) (pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) {
   461  	defer t.popVars(len(t.vars))
   462  	pipe = t.pipeline(context)
   463  	var next Node
   464  	list, next = t.itemList()
   465  	switch next.Type() {
   466  	case nodeEnd: //done
   467  	case nodeElse:
   468  		if allowElseIf {
   469  			// Special case for "else if". If the "else" is followed immediately by an "if",
   470  			// the elseControl will have left the "if" token pending. Treat
   471  			//	{{if a}}_{{else if b}}_{{end}}
   472  			// as
   473  			//	{{if a}}_{{else}}{{if b}}_{{end}}{{end}}.
   474  			// To do this, parse the if as usual and stop at it {{end}}; the subsequent{{end}}
   475  			// is assumed. This technique works even for long if-else-if chains.
   476  			// TODO: Should we allow else-if in with and range?
   477  			if t.peek().typ == itemIf {
   478  				t.next() // Consume the "if" token.
   479  				elseList = t.newList(next.Position())
   480  				elseList.append(t.ifControl())
   481  				// Do not consume the next item - only one {{end}} required.
   482  				break
   483  			}
   484  		}
   485  		elseList, next = t.itemList()
   486  		if next.Type() != nodeEnd {
   487  			t.errorf("expected end; found %s", next)
   488  		}
   489  	}
   490  	return pipe.Position(), pipe.Line, pipe, list, elseList
   491  }
   492  
   493  // If:
   494  //	{{if pipeline}} itemList {{end}}
   495  //	{{if pipeline}} itemList {{else}} itemList {{end}}
   496  // If keyword is past.
   497  func (t *Tree) ifControl() Node {
   498  	return t.newIf(t.parseControl(true, "if"))
   499  }
   500  
   501  // Range:
   502  //	{{range pipeline}} itemList {{end}}
   503  //	{{range pipeline}} itemList {{else}} itemList {{end}}
   504  // Range keyword is past.
   505  func (t *Tree) rangeControl() Node {
   506  	return t.newRange(t.parseControl(false, "range"))
   507  }
   508  
   509  // With:
   510  //	{{with pipeline}} itemList {{end}}
   511  //	{{with pipeline}} itemList {{else}} itemList {{end}}
   512  // If keyword is past.
   513  func (t *Tree) withControl() Node {
   514  	return t.newWith(t.parseControl(false, "with"))
   515  }
   516  
   517  // End:
   518  //	{{end}}
   519  // End keyword is past.
   520  func (t *Tree) endControl() Node {
   521  	return t.newEnd(t.expect(itemRightDelim, "end").pos)
   522  }
   523  
   524  // Else:
   525  //	{{else}}
   526  // Else keyword is past.
   527  func (t *Tree) elseControl() Node {
   528  	// Special case for "else if".
   529  	peek := t.peekNonSpace()
   530  	if peek.typ == itemIf {
   531  		// We see "{{else if ... " but in effect rewrite it to {{else}}{{if ... ".
   532  		return t.newElse(peek.pos, peek.line)
   533  	}
   534  	token := t.expect(itemRightDelim, "else")
   535  	return t.newElse(token.pos, token.line)
   536  }
   537  
   538  // Block:
   539  //	{{block stringValue pipeline}}
   540  // Block keyword is past.
   541  // The name must be something that can evaluate to a string.
   542  // The pipeline is mandatory.
   543  func (t *Tree) blockControl() Node {
   544  	const context = "block clause"
   545  
   546  	token := t.nextNonSpace()
   547  	name := t.parseTemplateName(token, context)
   548  	pipe := t.pipeline(context)
   549  
   550  	block := New(name) // name will be updated once we know it.
   551  	block.text = t.text
   552  	block.ParseName = t.ParseName
   553  	block.startParse(t.funcs, t.lex, t.treeSet)
   554  	var end Node
   555  	block.Root, end = block.itemList()
   556  	if end.Type() != nodeEnd {
   557  		t.errorf("unexpected %s in %s", end, context)
   558  	}
   559  	block.add()
   560  	block.stopParse()
   561  
   562  	return t.newTemplate(token.pos, token.line, name, pipe)
   563  }
   564  
   565  // Template:
   566  //	{{template stringValue pipeline}}
   567  // Template keyword is past. The name must be something that can evaluate
   568  // to a string.
   569  func (t *Tree) templateControl() Node {
   570  	const context = "template clause"
   571  	token := t.nextNonSpace()
   572  	name := t.parseTemplateName(token, context)
   573  	var pipe *PipeNode
   574  	if t.nextNonSpace().typ != itemRightDelim {
   575  		t.backup()
   576  		// Do not pop variables; they persist until "end".
   577  		pipe = t.pipeline(context)
   578  	}
   579  	return t.newTemplate(token.pos, token.line, name, pipe)
   580  }
   581  
   582  func (t *Tree) parseTemplateName(token item, context string) (name string) {
   583  	switch token.typ {
   584  	case itemString, itemRawString:
   585  		s, err := strconv.Unquote(token.val)
   586  		if err != nil {
   587  			t.error(err)
   588  		}
   589  		name = s
   590  	default:
   591  		t.unexpected(token, context)
   592  	}
   593  	return
   594  }
   595  
   596  // command:
   597  //	operand (space operand)*
   598  // space-separated arguments up to a pipeline character or right delimiter.
   599  // we consume the pipe character but leave the right delim to terminate the action.
   600  func (t *Tree) command() *CommandNode {
   601  	cmd := t.newCommand(t.peekNonSpace().pos)
   602  	for {
   603  		t.peekNonSpace() // skip leading spaces.
   604  		operand := t.operand()
   605  		if operand != nil {
   606  			cmd.append(operand)
   607  		}
   608  		switch token := t.next(); token.typ {
   609  		case itemSpace:
   610  			continue
   611  		case itemError:
   612  			t.errorf("%s", token.val)
   613  		case itemRightDelim, itemRightParen:
   614  			t.backup()
   615  		case itemPipe:
   616  		default:
   617  			t.errorf("unexpected %s in operand", token)
   618  		}
   619  		break
   620  	}
   621  	if len(cmd.Args) == 0 {
   622  		t.errorf("empty command")
   623  	}
   624  	return cmd
   625  }
   626  
   627  // operand:
   628  //	term .Field*
   629  // An operand is a space-separated component of a command,
   630  // a term possibly followed by field accesses.
   631  // A nil return means the next item is not an operand.
   632  func (t *Tree) operand() Node {
   633  	node := t.term()
   634  	if node == nil {
   635  		return nil
   636  	}
   637  	if t.peek().typ == itemField {
   638  		chain := t.newChain(t.peek().pos, node)
   639  		for t.peek().typ == itemField {
   640  			chain.Add(t.next().val)
   641  		}
   642  		// Compatibility with original API: If the term is of type NodeField
   643  		// or NodeVariable, just put more fields on the original.
   644  		// Otherwise, keep the Chain node.
   645  		// Obvious parsing errors involving literal values are detected here.
   646  		// More complex error cases will have to be handled at execution time.
   647  		switch node.Type() {
   648  		case NodeField:
   649  			node = t.newField(chain.Position(), chain.String())
   650  		case NodeVariable:
   651  			node = t.newVariable(chain.Position(), chain.String())
   652  		case NodeBool, NodeString, NodeNumber, NodeNil, NodeDot:
   653  			t.errorf("unexpected . after term %q", node.String())
   654  		default:
   655  			node = chain
   656  		}
   657  	}
   658  	return node
   659  }
   660  
   661  // term:
   662  //	literal (number, string, nil, boolean)
   663  //	function (identifier)
   664  //	.
   665  //	.Field
   666  //	$
   667  //	'(' pipeline ')'
   668  // A term is a simple "expression".
   669  // A nil return means the next item is not a term.
   670  func (t *Tree) term() Node {
   671  	switch token := t.nextNonSpace(); token.typ {
   672  	case itemError:
   673  		t.errorf("%s", token.val)
   674  	case itemIdentifier:
   675  		if !t.hasFunction(token.val) {
   676  			t.errorf("function %q not defined", token.val)
   677  		}
   678  		return NewIdentifier(token.val).SetTree(t).SetPos(token.pos)
   679  	case itemDot:
   680  		return t.newDot(token.pos)
   681  	case itemNil:
   682  		return t.newNil(token.pos)
   683  	case itemVariable:
   684  		return t.useVar(token.pos, token.val)
   685  	case itemField:
   686  		return t.newField(token.pos, token.val)
   687  	case itemBool:
   688  		return t.newBool(token.pos, token.val == "true")
   689  	case itemCharConstant, itemComplex, itemNumber:
   690  		number, err := t.newNumber(token.pos, token.val, token.typ)
   691  		if err != nil {
   692  			t.error(err)
   693  		}
   694  		return number
   695  	case itemLeftParen:
   696  		pipe := t.pipeline("parenthesized pipeline")
   697  		if token := t.next(); token.typ != itemRightParen {
   698  			t.errorf("unclosed right paren: unexpected %s", token)
   699  		}
   700  		return pipe
   701  	case itemString, itemRawString:
   702  		s, err := strconv.Unquote(token.val)
   703  		if err != nil {
   704  			t.error(err)
   705  		}
   706  		return t.newString(token.pos, token.val, s)
   707  	}
   708  	t.backup()
   709  	return nil
   710  }
   711  
   712  // hasFunction reports if a function name exists in the Tree's maps.
   713  func (t *Tree) hasFunction(name string) bool {
   714  	for _, funcMap := range t.funcs {
   715  		if funcMap == nil {
   716  			continue
   717  		}
   718  		if funcMap[name] != nil {
   719  			return true
   720  		}
   721  	}
   722  	return false
   723  }
   724  
   725  // popVars trims the variable list to the specified length
   726  func (t *Tree) popVars(n int) {
   727  	t.vars = t.vars[:n]
   728  }
   729  
   730  // useVar returns a node for a variable reference. It errors if the
   731  // variable is not defined.
   732  func (t *Tree) useVar(pos Pos, name string) Node {
   733  	v := t.newVariable(pos, name)
   734  	for _, varName := range t.vars {
   735  		if varName == v.Ident[0] {
   736  			return v
   737  		}
   738  	}
   739  	t.errorf("undefined variable %q", v.Ident[0])
   740  	return nil
   741  }
   742  

View as plain text