916 lines · 27.8 KB · Go
RawDownload
// Copyright 2011 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file. package template import (	"bytes"	"fmt"	"io"	"reflect"	"runtime"	"sort"	"strings"	"text/template/parse") // state represents the state of an execution. It's not part of the// template so that multiple executions of the same template// can execute in parallel.type state struct {	tmpl *Template	wr   io.Writer	node parse.Node // current node, for errors	vars []variable // push-down stack of variable values.} // variable holds the dynamic value of a variable such as $, $x etc.type variable struct {	name  string	value reflect.Value} // push pushes a new variable on the stack.func (s *state) push(name string, value reflect.Value) {	s.vars = append(s.vars, variable{name, value})} // mark returns the length of the variable stack.func (s *state) mark() int {	return len(s.vars)} // pop pops the variable stack up to the mark.func (s *state) pop(mark int) {	s.vars = s.vars[0:mark]} // setVar overwrites the top-nth variable on the stack. Used by range iterations.func (s *state) setVar(n int, value reflect.Value) {	s.vars[len(s.vars)-n].value = value} // varValue returns the value of the named variable.func (s *state) varValue(name string) reflect.Value {	for i := s.mark() - 1; i >= 0; i-- {		if s.vars[i].name == name {			return s.vars[i].value		}	}	s.errorf("undefined variable: %s", name)	return zero} var zero reflect.Value // at marks the state to be on node n, for error reporting.func (s *state) at(node parse.Node) {	s.node = node} // doublePercent returns the string with %'s replaced by %%, if necessary,// so it can be used safely inside a Printf format string.func doublePercent(str string) string {	if strings.Contains(str, "%") {		str = strings.Replace(str, "%", "%%", -1)	}	return str} // TODO: It would be nice if ExecError was more broken down, but// the way ErrorContext embeds the template name makes the// processing too clumsy. // ExecError is the custom error type returned when Execute has an// error evaluating its template. (If a write error occurs, the actual// error is returned; it will not be of type ExecError.)type ExecError struct {	Name string // Name of template.	Err  error  // Pre-formatted error.} func (e ExecError) Error() string {	return e.Err.Error()} // errorf records an ExecError and terminates processing.func (s *state) errorf(format string, args ...interface{}) {	name := doublePercent(s.tmpl.Name())	if s.node == nil {		format = fmt.Sprintf("template: %s: %s", name, format)	} else {		location, context := s.tmpl.ErrorContext(s.node)		format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)	}	panic(ExecError{		Name: s.tmpl.Name(),		Err:  fmt.Errorf(format, args...),	})} // writeError is the wrapper type used internally when Execute has an// error writing to its output. We strip the wrapper in errRecover.// Note that this is not an implementation of error, so it cannot escape// from the package as an error value.type writeError struct {	Err error // Original error.} func (s *state) writeError(err error) {	panic(writeError{		Err: err,	})} // errRecover is the handler that turns panics into returns from the top// level of Parse.func errRecover(errp *error) {	e := recover()	if e != nil {		switch err := e.(type) {		case runtime.Error:			panic(e)		case writeError:			*errp = err.Err // Strip the wrapper.		case ExecError:			*errp = err // Keep the wrapper.		default:			panic(e)		}	}} // ExecuteTemplate applies the template associated with t that has the given name// to the specified data object and writes the output to wr.// If an error occurs executing the template or writing its output,// execution stops, but partial results may already have been written to// the output writer.// A template may be executed safely in parallel.func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {	var tmpl *Template	if t.common != nil {		tmpl = t.tmpl[name]	}	if tmpl == nil {		return fmt.Errorf("template: no template %q associated with template %q", name, t.name)	}	return tmpl.Execute(wr, data)} // Execute applies a parsed template to the specified data object,// and writes the output to wr.// If an error occurs executing the template or writing its output,// execution stops, but partial results may already have been written to// the output writer.// A template may be executed safely in parallel.func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {	defer errRecover(&err)	value := reflect.ValueOf(data)	state := &state{		tmpl: t,		wr:   wr,		vars: []variable{{"$", value}},	}	if t.Tree == nil || t.Root == nil {		state.errorf("%q is an incomplete or empty template%s", t.Name(), t.DefinedTemplates())	}	state.walk(value, t.Root)	return} // DefinedTemplates returns a string listing the defined templates,// prefixed by the string "; defined templates are: ". If there are none,// it returns the empty string. For generating an error message here// and in html/template.func (t *Template) DefinedTemplates() string {	if t.common == nil {		return ""	}	var b bytes.Buffer	for name, tmpl := range t.tmpl {		if tmpl.Tree == nil || tmpl.Root == nil {			continue		}		if b.Len() > 0 {			b.WriteString(", ")		}		fmt.Fprintf(&b, "%q", name)	}	var s string	if b.Len() > 0 {		s = "; defined templates are: " + b.String()	}	return s} // Walk functions step through the major pieces of the template structure,// generating output as they go.func (s *state) walk(dot reflect.Value, node parse.Node) {	s.at(node)	switch node := node.(type) {	case *parse.ActionNode:		// Do not pop variables so they persist until next end.		// Also, if the action declares variables, don't print the result.		val := s.evalPipeline(dot, node.Pipe)		if len(node.Pipe.Decl) == 0 {			s.printValue(node, val)		}	case *parse.IfNode:		s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)	case *parse.ListNode:		for _, node := range node.Nodes {			s.walk(dot, node)		}	case *parse.RangeNode:		s.walkRange(dot, node)	case *parse.TemplateNode:		s.walkTemplate(dot, node)	case *parse.TextNode:		if _, err := s.wr.Write(node.Text); err != nil {			s.writeError(err)		}	case *parse.WithNode:		s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)	default:		s.errorf("unknown node: %s", node)	}} // walkIfOrWith walks an 'if' or 'with' node. The two control structures// are identical in behavior except that 'with' sets dot.func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {	defer s.pop(s.mark())	val := s.evalPipeline(dot, pipe)	truth, ok := isTrue(val)	if !ok {		s.errorf("if/with can't use %v", val)	}	if truth {		if typ == parse.NodeWith {			s.walk(val, list)		} else {			s.walk(dot, list)		}	} else if elseList != nil {		s.walk(dot, elseList)	}} // IsTrue reports whether the value is 'true', in the sense of not the zero of its type,// and whether the value has a meaningful truth value. This is the definition of// truth used by if and other such actions.func IsTrue(val interface{}) (truth, ok bool) {	return isTrue(reflect.ValueOf(val))} func isTrue(val reflect.Value) (truth, ok bool) {	if !val.IsValid() {		// Something like var x interface{}, never set. It's a form of nil.		return false, true	}	switch val.Kind() {	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:		truth = val.Len() > 0	case reflect.Bool:		truth = val.Bool()	case reflect.Complex64, reflect.Complex128:		truth = val.Complex() != 0	case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:		truth = !val.IsNil()	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:		truth = val.Int() != 0	case reflect.Float32, reflect.Float64:		truth = val.Float() != 0	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:		truth = val.Uint() != 0	case reflect.Struct:		truth = true // Struct values are always true.	default:		return	}	return truth, true} func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {	s.at(r)	defer s.pop(s.mark())	val, _ := indirect(s.evalPipeline(dot, r.Pipe))	// mark top of stack before any variables in the body are pushed.	mark := s.mark()	oneIteration := func(index, elem reflect.Value) {		// Set top var (lexically the second if there are two) to the element.		if len(r.Pipe.Decl) > 0 {			s.setVar(1, elem)		}		// Set next var (lexically the first if there are two) to the index.		if len(r.Pipe.Decl) > 1 {			s.setVar(2, index)		}		s.walk(elem, r.List)		s.pop(mark)	}	switch val.Kind() {	case reflect.Array, reflect.Slice:		if val.Len() == 0 {			break		}		for i := 0; i < val.Len(); i++ {			oneIteration(reflect.ValueOf(i), val.Index(i))		}		return	case reflect.Map:		if val.Len() == 0 {			break		}		for _, key := range sortKeys(val.MapKeys()) {			oneIteration(key, val.MapIndex(key))		}		return	case reflect.Chan:		if val.IsNil() {			break		}		i := 0		for ; ; i++ {			elem, ok := val.Recv()			if !ok {				break			}			oneIteration(reflect.ValueOf(i), elem)		}		if i == 0 {			break		}		return	case reflect.Invalid:		break // An invalid value is likely a nil map, etc. and acts like an empty map.	default:		s.errorf("range can't iterate over %v", val)	}	if r.ElseList != nil {		s.walk(dot, r.ElseList)	}} func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {	s.at(t)	tmpl := s.tmpl.tmpl[t.Name]	if tmpl == nil {		s.errorf("template %q not defined", t.Name)	}	// Variables declared by the pipeline persist.	dot = s.evalPipeline(dot, t.Pipe)	newState := *s	newState.tmpl = tmpl	// No dynamic scoping: template invocations inherit no variables.	newState.vars = []variable{{"$", dot}}	newState.walk(dot, tmpl.Root)} // Eval functions evaluate pipelines, commands, and their elements and extract// values from the data structure by examining fields, calling methods, and so on.// The printing of those values happens only through walk functions. // evalPipeline returns the value acquired by evaluating a pipeline. If the// pipeline has a variable declaration, the variable will be pushed on the// stack. Callers should therefore pop the stack after they are finished// executing commands depending on the pipeline value.func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {	if pipe == nil {		return	}	s.at(pipe)	for _, cmd := range pipe.Cmds {		value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.		// If the object has type interface{}, dig down one level to the thing inside.		if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {			value = reflect.ValueOf(value.Interface()) // lovely!		}	}	for _, variable := range pipe.Decl {		s.push(variable.Ident[0], value)	}	return value} func (s *state) notAFunction(args []parse.Node, final reflect.Value) {	if len(args) > 1 || final.IsValid() {		s.errorf("can't give argument to non-function %s", args[0])	}} func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {	firstWord := cmd.Args[0]	switch n := firstWord.(type) {	case *parse.FieldNode:		return s.evalFieldNode(dot, n, cmd.Args, final)	case *parse.ChainNode:		return s.evalChainNode(dot, n, cmd.Args, final)	case *parse.IdentifierNode:		// Must be a function.		return s.evalFunction(dot, n, cmd, cmd.Args, final)	case *parse.PipeNode:		// Parenthesized pipeline. The arguments are all inside the pipeline; final is ignored.		return s.evalPipeline(dot, n)	case *parse.VariableNode:		return s.evalVariableNode(dot, n, cmd.Args, final)	}	s.at(firstWord)	s.notAFunction(cmd.Args, final)	switch word := firstWord.(type) {	case *parse.BoolNode:		return reflect.ValueOf(word.True)	case *parse.DotNode:		return dot	case *parse.NilNode:		s.errorf("nil is not a command")	case *parse.NumberNode:		return s.idealConstant(word)	case *parse.StringNode:		return reflect.ValueOf(word.Text)	}	s.errorf("can't evaluate command %q", firstWord)	panic("not reached")} // idealConstant is called to return the value of a number in a context where// we don't know the type. In that case, the syntax of the number tells us// its type, and we use Go rules to resolve.  Note there is no such thing as// a uint ideal constant in this situation - the value must be of int type.func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {	// These are ideal constants but we don't know the type	// and we have no context.  (If it was a method argument,	// we'd know what we need.) The syntax guides us to some extent.	s.at(constant)	switch {	case constant.IsComplex:		return reflect.ValueOf(constant.Complex128) // incontrovertible.	case constant.IsFloat && !isHexConstant(constant.Text) && strings.IndexAny(constant.Text, ".eE") >= 0:		return reflect.ValueOf(constant.Float64)	case constant.IsInt:		n := int(constant.Int64)		if int64(n) != constant.Int64 {			s.errorf("%s overflows int", constant.Text)		}		return reflect.ValueOf(n)	case constant.IsUint:		s.errorf("%s overflows int", constant.Text)	}	return zero} func isHexConstant(s string) bool {	return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')} func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {	s.at(field)	return s.evalFieldChain(dot, dot, field, field.Ident, args, final)} func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {	s.at(chain)	if len(chain.Field) == 0 {		s.errorf("internal error: no fields in evalChainNode")	}	if chain.Node.Type() == parse.NodeNil {		s.errorf("indirection through explicit nil in %s", chain)	}	// (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.	pipe := s.evalArg(dot, nil, chain.Node)	return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)} func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {	// $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.	s.at(variable)	value := s.varValue(variable.Ident[0])	if len(variable.Ident) == 1 {		s.notAFunction(args, final)		return value	}	return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)} // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.// dot is the environment in which to evaluate arguments, while// receiver is the value being walked along the chain.func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {	n := len(ident)

Lines 1–500 of 916.