1
0
mirror of https://github.com/Luzifer/cloudkeys-go.git synced 2024-09-20 08:02:57 +00:00
cloudkeys-go/vendor/github.com/flosch/pongo2/variable.go

683 lines
17 KiB
Go
Raw Normal View History

2015-07-30 15:43:22 +00:00
package pongo2
import (
"fmt"
"reflect"
"strconv"
"strings"
2017-12-28 01:56:23 +00:00
"github.com/juju/errors"
2015-07-30 15:43:22 +00:00
)
const (
varTypeInt = iota
varTypeIdent
)
2017-12-28 01:56:23 +00:00
var (
typeOfValuePtr = reflect.TypeOf(new(Value))
typeOfExecCtxPtr = reflect.TypeOf(new(ExecutionContext))
)
2015-07-30 15:43:22 +00:00
type variablePart struct {
typ int
s string
i int
2017-12-28 01:56:23 +00:00
isFunctionCall bool
callingArgs []functionCallArgument // needed for a function call, represents all argument nodes (INode supports nested function calls)
2015-07-30 15:43:22 +00:00
}
type functionCallArgument interface {
Evaluate(*ExecutionContext) (*Value, *Error)
}
// TODO: Add location tokens
type stringResolver struct {
2017-12-28 01:56:23 +00:00
locationToken *Token
val string
2015-07-30 15:43:22 +00:00
}
type intResolver struct {
2017-12-28 01:56:23 +00:00
locationToken *Token
val int
2015-07-30 15:43:22 +00:00
}
type floatResolver struct {
2017-12-28 01:56:23 +00:00
locationToken *Token
val float64
2015-07-30 15:43:22 +00:00
}
type boolResolver struct {
2017-12-28 01:56:23 +00:00
locationToken *Token
val bool
2015-07-30 15:43:22 +00:00
}
type variableResolver struct {
2017-12-28 01:56:23 +00:00
locationToken *Token
2015-07-30 15:43:22 +00:00
parts []*variablePart
}
type nodeFilteredVariable struct {
2017-12-28 01:56:23 +00:00
locationToken *Token
2015-07-30 15:43:22 +00:00
resolver IEvaluator
filterChain []*filterCall
}
type nodeVariable struct {
2017-12-28 01:56:23 +00:00
locationToken *Token
expr IEvaluator
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
type executionCtxEval struct{}
func (v *nodeFilteredVariable) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
value, err := v.Evaluate(ctx)
2015-07-30 15:43:22 +00:00
if err != nil {
return err
}
2017-12-28 01:56:23 +00:00
writer.WriteString(value.String())
2015-07-30 15:43:22 +00:00
return nil
}
2017-12-28 01:56:23 +00:00
func (vr *variableResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
value, err := vr.Evaluate(ctx)
2015-07-30 15:43:22 +00:00
if err != nil {
return err
}
2017-12-28 01:56:23 +00:00
writer.WriteString(value.String())
2015-07-30 15:43:22 +00:00
return nil
}
2017-12-28 01:56:23 +00:00
func (s *stringResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
value, err := s.Evaluate(ctx)
2015-07-30 15:43:22 +00:00
if err != nil {
return err
}
2017-12-28 01:56:23 +00:00
writer.WriteString(value.String())
2015-07-30 15:43:22 +00:00
return nil
}
2017-12-28 01:56:23 +00:00
func (i *intResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
value, err := i.Evaluate(ctx)
2015-07-30 15:43:22 +00:00
if err != nil {
return err
}
2017-12-28 01:56:23 +00:00
writer.WriteString(value.String())
2015-07-30 15:43:22 +00:00
return nil
}
2017-12-28 01:56:23 +00:00
func (f *floatResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
value, err := f.Evaluate(ctx)
2015-07-30 15:43:22 +00:00
if err != nil {
return err
}
2017-12-28 01:56:23 +00:00
writer.WriteString(value.String())
2015-07-30 15:43:22 +00:00
return nil
}
2017-12-28 01:56:23 +00:00
func (b *boolResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
value, err := b.Evaluate(ctx)
2015-07-30 15:43:22 +00:00
if err != nil {
return err
}
2017-12-28 01:56:23 +00:00
writer.WriteString(value.String())
2015-07-30 15:43:22 +00:00
return nil
}
func (v *nodeFilteredVariable) GetPositionToken() *Token {
2017-12-28 01:56:23 +00:00
return v.locationToken
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
func (vr *variableResolver) GetPositionToken() *Token {
return vr.locationToken
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
func (s *stringResolver) GetPositionToken() *Token {
return s.locationToken
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
func (i *intResolver) GetPositionToken() *Token {
return i.locationToken
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
func (f *floatResolver) GetPositionToken() *Token {
return f.locationToken
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
func (b *boolResolver) GetPositionToken() *Token {
return b.locationToken
2015-07-30 15:43:22 +00:00
}
func (s *stringResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
return AsValue(s.val), nil
}
func (i *intResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
return AsValue(i.val), nil
}
func (f *floatResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
return AsValue(f.val), nil
}
func (b *boolResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
return AsValue(b.val), nil
}
func (s *stringResolver) FilterApplied(name string) bool {
return false
}
func (i *intResolver) FilterApplied(name string) bool {
return false
}
func (f *floatResolver) FilterApplied(name string) bool {
return false
}
func (b *boolResolver) FilterApplied(name string) bool {
return false
}
func (nv *nodeVariable) FilterApplied(name string) bool {
return nv.expr.FilterApplied(name)
}
2017-12-28 01:56:23 +00:00
func (nv *nodeVariable) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
2015-07-30 15:43:22 +00:00
value, err := nv.expr.Evaluate(ctx)
if err != nil {
return err
}
if !nv.expr.FilterApplied("safe") && !value.safe && value.IsString() && ctx.Autoescape {
// apply escape filter
value, err = filters["escape"](value, nil)
if err != nil {
return err
}
}
2017-12-28 01:56:23 +00:00
writer.WriteString(value.String())
2015-07-30 15:43:22 +00:00
return nil
}
2017-12-28 01:56:23 +00:00
func (executionCtxEval) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
return AsValue(ctx), nil
}
2015-07-30 15:43:22 +00:00
func (vr *variableResolver) FilterApplied(name string) bool {
return false
}
func (vr *variableResolver) String() string {
parts := make([]string, 0, len(vr.parts))
for _, p := range vr.parts {
switch p.typ {
case varTypeInt:
parts = append(parts, strconv.Itoa(p.i))
case varTypeIdent:
parts = append(parts, p.s)
default:
panic("unimplemented")
}
}
return strings.Join(parts, ".")
}
func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
var current reflect.Value
2017-12-28 01:56:23 +00:00
var isSafe bool
2015-07-30 15:43:22 +00:00
for idx, part := range vr.parts {
if idx == 0 {
// We're looking up the first part of the variable.
// First we're having a look in our private
// context (e. g. information provided by tags, like the forloop)
2017-12-28 01:56:23 +00:00
val, inPrivate := ctx.Private[vr.parts[0].s]
if !inPrivate {
2015-07-30 15:43:22 +00:00
// Nothing found? Then have a final lookup in the public context
val = ctx.Public[vr.parts[0].s]
}
current = reflect.ValueOf(val) // Get the initial value
} else {
// Next parts, resolve it from current
// Before resolving the pointer, let's see if we have a method to call
// Problem with resolving the pointer is we're changing the receiver
2017-12-28 01:56:23 +00:00
isFunc := false
2015-07-30 15:43:22 +00:00
if part.typ == varTypeIdent {
2017-12-28 01:56:23 +00:00
funcValue := current.MethodByName(part.s)
if funcValue.IsValid() {
current = funcValue
isFunc = true
2015-07-30 15:43:22 +00:00
}
}
2017-12-28 01:56:23 +00:00
if !isFunc {
2015-07-30 15:43:22 +00:00
// If current a pointer, resolve it
if current.Kind() == reflect.Ptr {
current = current.Elem()
if !current.IsValid() {
// Value is not valid (anymore)
return AsValue(nil), nil
}
}
// Look up which part must be called now
switch part.typ {
case varTypeInt:
// Calling an index is only possible for:
// * slices/arrays/strings
switch current.Kind() {
case reflect.String, reflect.Array, reflect.Slice:
2017-12-28 01:56:23 +00:00
if part.i >= 0 && current.Len() > part.i {
current = current.Index(part.i)
} else {
// In Django, exceeding the length of a list is just empty.
return AsValue(nil), nil
}
2015-07-30 15:43:22 +00:00
default:
2017-12-28 01:56:23 +00:00
return nil, errors.Errorf("Can't access an index on type %s (variable %s)",
2015-07-30 15:43:22 +00:00
current.Kind().String(), vr.String())
}
case varTypeIdent:
// debugging:
// fmt.Printf("now = %s (kind: %s)\n", part.s, current.Kind().String())
// Calling a field or key
switch current.Kind() {
case reflect.Struct:
current = current.FieldByName(part.s)
case reflect.Map:
current = current.MapIndex(reflect.ValueOf(part.s))
default:
2017-12-28 01:56:23 +00:00
return nil, errors.Errorf("Can't access a field by name on type %s (variable %s)",
2015-07-30 15:43:22 +00:00
current.Kind().String(), vr.String())
}
default:
panic("unimplemented")
}
}
}
if !current.IsValid() {
// Value is not valid (anymore)
return AsValue(nil), nil
}
// If current is a reflect.ValueOf(pongo2.Value), then unpack it
// Happens in function calls (as a return value) or by injecting
// into the execution context (e.g. in a for-loop)
2017-12-28 01:56:23 +00:00
if current.Type() == typeOfValuePtr {
tmpValue := current.Interface().(*Value)
current = tmpValue.val
isSafe = tmpValue.safe
2015-07-30 15:43:22 +00:00
}
// Check whether this is an interface and resolve it where required
if current.Kind() == reflect.Interface {
current = reflect.ValueOf(current.Interface())
}
// Check if the part is a function call
2017-12-28 01:56:23 +00:00
if part.isFunctionCall || current.Kind() == reflect.Func {
2015-07-30 15:43:22 +00:00
// Check for callable
if current.Kind() != reflect.Func {
2017-12-28 01:56:23 +00:00
return nil, errors.Errorf("'%s' is not a function (it is %s)", vr.String(), current.Kind().String())
2015-07-30 15:43:22 +00:00
}
// Check for correct function syntax and types
// func(*Value, ...) *Value
t := current.Type()
2017-12-28 01:56:23 +00:00
currArgs := part.callingArgs
// If an implicit ExecCtx is needed
if t.NumIn() > 0 && t.In(0) == typeOfExecCtxPtr {
currArgs = append([]functionCallArgument{executionCtxEval{}}, currArgs...)
}
2015-07-30 15:43:22 +00:00
// Input arguments
2017-12-28 01:56:23 +00:00
if len(currArgs) != t.NumIn() && !(len(currArgs) >= t.NumIn()-1 && t.IsVariadic()) {
2015-07-30 15:43:22 +00:00
return nil,
2017-12-28 01:56:23 +00:00
errors.Errorf("Function input argument count (%d) of '%s' must be equal to the calling argument count (%d).",
t.NumIn(), vr.String(), len(currArgs))
2015-07-30 15:43:22 +00:00
}
// Output arguments
if t.NumOut() != 1 {
2017-12-28 01:56:23 +00:00
return nil, errors.Errorf("'%s' must have exactly 1 output argument", vr.String())
2015-07-30 15:43:22 +00:00
}
// Evaluate all parameters
2017-12-28 01:56:23 +00:00
var parameters []reflect.Value
2015-07-30 15:43:22 +00:00
2017-12-28 01:56:23 +00:00
numArgs := t.NumIn()
isVariadic := t.IsVariadic()
var fnArg reflect.Type
2015-07-30 15:43:22 +00:00
2017-12-28 01:56:23 +00:00
for idx, arg := range currArgs {
2015-07-30 15:43:22 +00:00
pv, err := arg.Evaluate(ctx)
if err != nil {
return nil, err
}
2017-12-28 01:56:23 +00:00
if isVariadic {
2015-07-30 15:43:22 +00:00
if idx >= t.NumIn()-1 {
2017-12-28 01:56:23 +00:00
fnArg = t.In(numArgs - 1).Elem()
2015-07-30 15:43:22 +00:00
} else {
2017-12-28 01:56:23 +00:00
fnArg = t.In(idx)
2015-07-30 15:43:22 +00:00
}
} else {
2017-12-28 01:56:23 +00:00
fnArg = t.In(idx)
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
if fnArg != typeOfValuePtr {
2015-07-30 15:43:22 +00:00
// Function's argument is not a *pongo2.Value, then we have to check whether input argument is of the same type as the function's argument
2017-12-28 01:56:23 +00:00
if !isVariadic {
if fnArg != reflect.TypeOf(pv.Interface()) && fnArg.Kind() != reflect.Interface {
return nil, errors.Errorf("Function input argument %d of '%s' must be of type %s or *pongo2.Value (not %T).",
idx, vr.String(), fnArg.String(), pv.Interface())
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
// Function's argument has another type, using the interface-value
parameters = append(parameters, reflect.ValueOf(pv.Interface()))
2015-07-30 15:43:22 +00:00
} else {
2017-12-28 01:56:23 +00:00
if fnArg != reflect.TypeOf(pv.Interface()) && fnArg.Kind() != reflect.Interface {
return nil, errors.Errorf("Function variadic input argument of '%s' must be of type %s or *pongo2.Value (not %T).",
vr.String(), fnArg.String(), pv.Interface())
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
// Function's argument has another type, using the interface-value
parameters = append(parameters, reflect.ValueOf(pv.Interface()))
2015-07-30 15:43:22 +00:00
}
} else {
// Function's argument is a *pongo2.Value
parameters = append(parameters, reflect.ValueOf(pv))
}
}
2017-12-28 01:56:23 +00:00
// Check if any of the values are invalid
for _, p := range parameters {
if p.Kind() == reflect.Invalid {
return nil, errors.Errorf("Calling a function using an invalid parameter")
}
}
2015-07-30 15:43:22 +00:00
// Call it and get first return parameter back
rv := current.Call(parameters)[0]
2017-12-28 01:56:23 +00:00
if rv.Type() != typeOfValuePtr {
2015-07-30 15:43:22 +00:00
current = reflect.ValueOf(rv.Interface())
} else {
// Return the function call value
current = rv.Interface().(*Value).val
2017-12-28 01:56:23 +00:00
isSafe = rv.Interface().(*Value).safe
2015-07-30 15:43:22 +00:00
}
}
2017-12-28 01:56:23 +00:00
if !current.IsValid() {
// Value is not valid (e. g. NIL value)
return AsValue(nil), nil
}
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
return &Value{val: current, safe: isSafe}, nil
2015-07-30 15:43:22 +00:00
}
func (vr *variableResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
value, err := vr.resolve(ctx)
if err != nil {
2017-12-28 01:56:23 +00:00
return AsValue(nil), ctx.Error(err.Error(), vr.locationToken)
2015-07-30 15:43:22 +00:00
}
return value, nil
}
func (v *nodeFilteredVariable) FilterApplied(name string) bool {
for _, filter := range v.filterChain {
if filter.name == name {
return true
}
}
return false
}
func (v *nodeFilteredVariable) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
value, err := v.resolver.Evaluate(ctx)
if err != nil {
return nil, err
}
for _, filter := range v.filterChain {
value, err = filter.Execute(value, ctx)
if err != nil {
return nil, err
}
}
return value, nil
}
// IDENT | IDENT.(IDENT|NUMBER)...
func (p *Parser) parseVariableOrLiteral() (IEvaluator, *Error) {
t := p.Current()
if t == nil {
2017-12-28 01:56:23 +00:00
return nil, p.Error("Unexpected EOF, expected a number, string, keyword or identifier.", p.lastToken)
2015-07-30 15:43:22 +00:00
}
// Is first part a number or a string, there's nothing to resolve (because there's only to return the value then)
switch t.Typ {
case TokenNumber:
p.Consume()
// One exception to the rule that we don't have float64 literals is at the beginning
// of an expression (or a variable name). Since we know we started with an integer
// which can't obviously be a variable name, we can check whether the first number
// is followed by dot (and then a number again). If so we're converting it to a float64.
if p.Match(TokenSymbol, ".") != nil {
// float64
t2 := p.MatchType(TokenNumber)
if t2 == nil {
return nil, p.Error("Expected a number after the '.'.", nil)
}
f, err := strconv.ParseFloat(fmt.Sprintf("%s.%s", t.Val, t2.Val), 64)
if err != nil {
return nil, p.Error(err.Error(), t)
}
fr := &floatResolver{
2017-12-28 01:56:23 +00:00
locationToken: t,
val: f,
2015-07-30 15:43:22 +00:00
}
return fr, nil
}
2017-12-28 01:56:23 +00:00
i, err := strconv.Atoi(t.Val)
if err != nil {
return nil, p.Error(err.Error(), t)
}
nr := &intResolver{
locationToken: t,
val: i,
}
return nr, nil
2015-07-30 15:43:22 +00:00
case TokenString:
p.Consume()
sr := &stringResolver{
2017-12-28 01:56:23 +00:00
locationToken: t,
val: t.Val,
2015-07-30 15:43:22 +00:00
}
return sr, nil
case TokenKeyword:
p.Consume()
switch t.Val {
case "true":
br := &boolResolver{
2017-12-28 01:56:23 +00:00
locationToken: t,
val: true,
2015-07-30 15:43:22 +00:00
}
return br, nil
case "false":
br := &boolResolver{
2017-12-28 01:56:23 +00:00
locationToken: t,
val: false,
2015-07-30 15:43:22 +00:00
}
return br, nil
default:
return nil, p.Error("This keyword is not allowed here.", nil)
}
}
resolver := &variableResolver{
2017-12-28 01:56:23 +00:00
locationToken: t,
2015-07-30 15:43:22 +00:00
}
// First part of a variable MUST be an identifier
if t.Typ != TokenIdentifier {
return nil, p.Error("Expected either a number, string, keyword or identifier.", t)
}
resolver.parts = append(resolver.parts, &variablePart{
typ: varTypeIdent,
s: t.Val,
})
p.Consume() // we consumed the first identifier of the variable name
variableLoop:
for p.Remaining() > 0 {
t = p.Current()
if p.Match(TokenSymbol, ".") != nil {
// Next variable part (can be either NUMBER or IDENT)
t2 := p.Current()
if t2 != nil {
switch t2.Typ {
case TokenIdentifier:
resolver.parts = append(resolver.parts, &variablePart{
typ: varTypeIdent,
s: t2.Val,
})
p.Consume() // consume: IDENT
continue variableLoop
case TokenNumber:
i, err := strconv.Atoi(t2.Val)
if err != nil {
return nil, p.Error(err.Error(), t2)
}
resolver.parts = append(resolver.parts, &variablePart{
typ: varTypeInt,
i: i,
})
p.Consume() // consume: NUMBER
continue variableLoop
default:
return nil, p.Error("This token is not allowed within a variable name.", t2)
}
} else {
// EOF
return nil, p.Error("Unexpected EOF, expected either IDENTIFIER or NUMBER after DOT.",
2017-12-28 01:56:23 +00:00
p.lastToken)
2015-07-30 15:43:22 +00:00
}
} else if p.Match(TokenSymbol, "(") != nil {
// Function call
// FunctionName '(' Comma-separated list of expressions ')'
part := resolver.parts[len(resolver.parts)-1]
2017-12-28 01:56:23 +00:00
part.isFunctionCall = true
2015-07-30 15:43:22 +00:00
argumentLoop:
for {
if p.Remaining() == 0 {
2017-12-28 01:56:23 +00:00
return nil, p.Error("Unexpected EOF, expected function call argument list.", p.lastToken)
2015-07-30 15:43:22 +00:00
}
if p.Peek(TokenSymbol, ")") == nil {
// No closing bracket, so we're parsing an expression
2017-12-28 01:56:23 +00:00
exprArg, err := p.ParseExpression()
2015-07-30 15:43:22 +00:00
if err != nil {
return nil, err
}
2017-12-28 01:56:23 +00:00
part.callingArgs = append(part.callingArgs, exprArg)
2015-07-30 15:43:22 +00:00
if p.Match(TokenSymbol, ")") != nil {
// If there's a closing bracket after an expression, we will stop parsing the arguments
break argumentLoop
} else {
// If there's NO closing bracket, there MUST be an comma
if p.Match(TokenSymbol, ",") == nil {
return nil, p.Error("Missing comma or closing bracket after argument.", nil)
}
}
} else {
// We got a closing bracket, so stop parsing arguments
p.Consume()
break argumentLoop
}
}
// We're done parsing the function call, next variable part
continue variableLoop
}
// No dot or function call? Then we're done with the variable parsing
break
}
return resolver, nil
}
func (p *Parser) parseVariableOrLiteralWithFilter() (*nodeFilteredVariable, *Error) {
v := &nodeFilteredVariable{
2017-12-28 01:56:23 +00:00
locationToken: p.Current(),
2015-07-30 15:43:22 +00:00
}
// Parse the variable name
resolver, err := p.parseVariableOrLiteral()
if err != nil {
return nil, err
}
v.resolver = resolver
// Parse all the filters
filterLoop:
for p.Match(TokenSymbol, "|") != nil {
// Parse one single filter
filter, err := p.parseFilter()
if err != nil {
return nil, err
}
// Check sandbox filter restriction
2017-12-28 01:56:23 +00:00
if _, isBanned := p.template.set.bannedFilters[filter.name]; isBanned {
2015-07-30 15:43:22 +00:00
return nil, p.Error(fmt.Sprintf("Usage of filter '%s' is not allowed (sandbox restriction active).", filter.name), nil)
}
v.filterChain = append(v.filterChain, filter)
continue filterLoop
}
return v, nil
}
func (p *Parser) parseVariableElement() (INode, *Error) {
node := &nodeVariable{
2017-12-28 01:56:23 +00:00
locationToken: p.Current(),
2015-07-30 15:43:22 +00:00
}
p.Consume() // consume '{{'
expr, err := p.ParseExpression()
if err != nil {
return nil, err
}
node.expr = expr
if p.Match(TokenSymbol, "}}") == nil {
return nil, p.Error("'}}' expected", nil)
}
return node, nil
}