Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/gohugoio/hugo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2019-12-10 21:56:44 +0300
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2019-12-12 12:04:35 +0300
commita03c631c420a03f9d90699abdf9be7e4fca0ff61 (patch)
treefcc245c75aa6cc6dc5be40a614700b6aca26c84f /tpl/internal
parent167c01530bb295c8b8d35921eb27ffa5bee76dfe (diff)
Rework template handling for function and map lookups
This is a big commit, but it deletes lots of code and simplifies a lot. * Resolving the template funcs at execution time means we don't have to create template clones per site * Having a custom map resolver means that we can remove the AST lower case transformation for the special lower case Params map Not only is the above easier to reason about, it's also faster, especially if you have more than one language, as in the benchmark below: ``` name old time/op new time/op delta SiteNew/Deep_content_tree-16 53.7ms ± 0% 48.1ms ± 2% -10.38% (p=0.029 n=4+4) name old alloc/op new alloc/op delta SiteNew/Deep_content_tree-16 41.0MB ± 0% 36.8MB ± 0% -10.26% (p=0.029 n=4+4) name old allocs/op new allocs/op delta SiteNew/Deep_content_tree-16 481k ± 0% 410k ± 0% -14.66% (p=0.029 n=4+4) ``` This should be even better if you also have lots of templates. Closes #6594
Diffstat (limited to 'tpl/internal')
-rw-r--r--tpl/internal/go_templates/texttemplate/exec.go4
-rw-r--r--tpl/internal/go_templates/texttemplate/hugo_exec.go38
-rw-r--r--tpl/internal/go_templates/texttemplate/hugo_template.go158
-rw-r--r--tpl/internal/go_templates/texttemplate/hugo_template_test.go71
4 files changed, 214 insertions, 57 deletions
diff --git a/tpl/internal/go_templates/texttemplate/exec.go b/tpl/internal/go_templates/texttemplate/exec.go
index d47793320..db64edcb2 100644
--- a/tpl/internal/go_templates/texttemplate/exec.go
+++ b/tpl/internal/go_templates/texttemplate/exec.go
@@ -558,7 +558,7 @@ func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ide
return s.evalField(dot, ident[n-1], node, args, final, receiver)
}
-func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
+func (s *state) evalFunctionOld(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
s.at(node)
name := node.Ident
function, ok := findFunction(name, s.tmpl)
@@ -571,7 +571,7 @@ func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd
// evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
// The 'final' argument represents the return value from the preceding
// value of the pipeline, if any.
-func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
+func (s *state) evalFieldOld(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
if !receiver.IsValid() {
if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
s.errorf("nil data; no entry for key %q", fieldName)
diff --git a/tpl/internal/go_templates/texttemplate/hugo_exec.go b/tpl/internal/go_templates/texttemplate/hugo_exec.go
deleted file mode 100644
index cc3aeb2f1..000000000
--- a/tpl/internal/go_templates/texttemplate/hugo_exec.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright 2019 The Hugo Authors. All rights reserved.
-//
-// 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 template
-
-import (
- "io"
-
- "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
-)
-
-/*
-
-This files contains the Hugo related addons. All the other files in this
-package is auto generated.
-
-*/
-
-// 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.
- depth int // the height of the stack of executing templates.
-}
diff --git a/tpl/internal/go_templates/texttemplate/hugo_template.go b/tpl/internal/go_templates/texttemplate/hugo_template.go
index e3252e7aa..c2738ec53 100644
--- a/tpl/internal/go_templates/texttemplate/hugo_template.go
+++ b/tpl/internal/go_templates/texttemplate/hugo_template.go
@@ -27,15 +27,31 @@ package is auto generated.
*/
-// TODO1 name
+// Preparer prepares the template before execution.
type Preparer interface {
Prepare() (*Template, error)
}
-type TemplateExecutor struct {
+// ExecHelper allows some custom eval hooks.
+type ExecHelper interface {
+ GetFunc(name string) (reflect.Value, bool)
+ GetMapValue(receiver, key reflect.Value) (reflect.Value, bool)
}
-func (t *TemplateExecutor) Execute(p Preparer, wr io.Writer, data interface{}) error {
+// Executer executes a given template.
+type Executer interface {
+ Execute(p Preparer, wr io.Writer, data interface{}) error
+}
+
+type executer struct {
+ helper ExecHelper
+}
+
+func NewExecuter(helper ExecHelper) Executer {
+ return &executer{helper: helper}
+}
+
+func (t *executer) Execute(p Preparer, wr io.Writer, data interface{}) error {
tmpl, err := p.Prepare()
if err != nil {
return err
@@ -47,9 +63,10 @@ func (t *TemplateExecutor) Execute(p Preparer, wr io.Writer, data interface{}) e
}
state := &state{
- tmpl: tmpl,
- wr: wr,
- vars: []variable{{"$", value}},
+ helper: t.helper,
+ tmpl: tmpl,
+ wr: wr,
+ vars: []variable{{"$", value}},
}
return tmpl.executeWithState(state, value)
@@ -62,24 +79,131 @@ func (t *Template) Prepare() (*Template, error) {
return t, nil
}
+func (t *Template) executeWithState(state *state, value reflect.Value) (err error) {
+ defer errRecover(&err)
+ if t.Tree == nil || t.Root == nil {
+ state.errorf("%q is an incomplete or empty template", t.Name())
+ }
+ state.walk(value, t.Root)
+ return
+}
+
// Below are modifed structs etc.
// 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.
- depth int // the height of the stack of executing templates.
+ tmpl *Template
+ helper ExecHelper
+ wr io.Writer
+ node parse.Node // current node, for errors
+ vars []variable // push-down stack of variable values.
+ depth int // the height of the stack of executing templates.
}
-func (t *Template) executeWithState(state *state, value reflect.Value) (err error) {
- defer errRecover(&err)
- if t.Tree == nil || t.Root == nil {
- state.errorf("%q is an incomplete or empty template", t.Name())
+func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
+ s.at(node)
+ name := node.Ident
+
+ var function reflect.Value
+ var ok bool
+ if s.helper != nil {
+ function, ok = s.helper.GetFunc(name)
}
- state.walk(value, t.Root)
- return
+
+ if !ok {
+ function, ok = findFunction(name, s.tmpl)
+ }
+
+ if !ok {
+ s.errorf("%q is not a defined function", name)
+ }
+ return s.evalCall(dot, function, cmd, name, args, final)
+}
+
+// evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
+// The 'final' argument represents the return value from the preceding
+// value of the pipeline, if any.
+func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
+ if !receiver.IsValid() {
+ if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
+ s.errorf("nil data; no entry for key %q", fieldName)
+ }
+ return zero
+ }
+ typ := receiver.Type()
+ receiver, isNil := indirect(receiver)
+ if receiver.Kind() == reflect.Interface && isNil {
+ // Calling a method on a nil interface can't work. The
+ // MethodByName method call below would panic.
+ s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
+ return zero
+ }
+
+ // Unless it's an interface, need to get to a value of type *T to guarantee
+ // we see all methods of T and *T.
+ ptr := receiver
+ if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Ptr && ptr.CanAddr() {
+ ptr = ptr.Addr()
+ }
+ if method := ptr.MethodByName(fieldName); method.IsValid() {
+ return s.evalCall(dot, method, node, fieldName, args, final)
+ }
+ hasArgs := len(args) > 1 || final != missingVal
+ // It's not a method; must be a field of a struct or an element of a map.
+ switch receiver.Kind() {
+ case reflect.Struct:
+ tField, ok := receiver.Type().FieldByName(fieldName)
+ if ok {
+ field := receiver.FieldByIndex(tField.Index)
+ if tField.PkgPath != "" { // field is unexported
+ s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
+ }
+ // If it's a function, we must call it.
+ if hasArgs {
+ s.errorf("%s has arguments but cannot be invoked as function", fieldName)
+ }
+ return field
+ }
+ case reflect.Map:
+ // If it's a map, attempt to use the field name as a key.
+ nameVal := reflect.ValueOf(fieldName)
+ if nameVal.Type().AssignableTo(receiver.Type().Key()) {
+ if hasArgs {
+ s.errorf("%s is not a method but has arguments", fieldName)
+ }
+ var result reflect.Value
+ if s.helper != nil {
+ result, _ = s.helper.GetMapValue(receiver, nameVal)
+ } else {
+ result = receiver.MapIndex(nameVal)
+ }
+ if !result.IsValid() {
+ switch s.tmpl.option.missingKey {
+ case mapInvalid:
+ // Just use the invalid value.
+ case mapZeroValue:
+ result = reflect.Zero(receiver.Type().Elem())
+ case mapError:
+ s.errorf("map has no entry for key %q", fieldName)
+ }
+ }
+ return result
+ }
+ case reflect.Ptr:
+ etyp := receiver.Type().Elem()
+ if etyp.Kind() == reflect.Struct {
+ if _, ok := etyp.FieldByName(fieldName); !ok {
+ // If there's no such field, say "can't evaluate"
+ // instead of "nil pointer evaluating".
+ break
+ }
+ }
+ if isNil {
+ s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
+ }
+ }
+ s.errorf("can't evaluate field %s in type %s", fieldName, typ)
+ panic("not reached")
}
diff --git a/tpl/internal/go_templates/texttemplate/hugo_template_test.go b/tpl/internal/go_templates/texttemplate/hugo_template_test.go
new file mode 100644
index 000000000..2424a0a48
--- /dev/null
+++ b/tpl/internal/go_templates/texttemplate/hugo_template_test.go
@@ -0,0 +1,71 @@
+// Copyright 2019 The Hugo Authors. All rights reserved.
+//
+// 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 template
+
+import (
+ "bytes"
+ "reflect"
+ "strings"
+ "testing"
+
+ qt "github.com/frankban/quicktest"
+)
+
+type TestStruct struct {
+ S string
+ M map[string]string
+}
+
+type execHelper struct {
+}
+
+func (e *execHelper) GetFunc(name string) (reflect.Value, bool) {
+ if name == "print" {
+ return zero, false
+ }
+ return reflect.ValueOf(func(s string) string {
+ return "hello " + s
+ }), true
+}
+
+func (e *execHelper) GetMapValue(m, key reflect.Value) (reflect.Value, bool) {
+ key = reflect.ValueOf(strings.ToLower(key.String()))
+ return m.MapIndex(key), true
+}
+
+func TestTemplateExecutor(t *testing.T) {
+ c := qt.New(t)
+
+ templ, err := New("").Parse(`
+{{ print "foo" }}
+{{ printf "hugo" }}
+Map: {{ .M.A }}
+
+`)
+
+ c.Assert(err, qt.IsNil)
+
+ ex := NewExecuter(&execHelper{})
+
+ var b bytes.Buffer
+ data := TestStruct{S: "sv", M: map[string]string{"a": "av"}}
+
+ c.Assert(ex.Execute(templ, &b, data), qt.IsNil)
+ got := b.String()
+
+ c.Assert(got, qt.Contains, "foo")
+ c.Assert(got, qt.Contains, "hello hugo")
+ c.Assert(got, qt.Contains, "Map: av")
+
+}