Fix nil index handling

This commit is contained in:
Elara 2024-02-11 22:11:17 -08:00
parent d9356a48a5
commit feb0f0db31
2 changed files with 18 additions and 1 deletions

View File

@ -415,7 +415,7 @@ func (t *Template) getIndex(i ast.Index, local map[string]any) (any, error) {
return nil, ast.PosError(i, "%s: cannot get index of nil value", valueToString(i))
}
rindex := reflect.ValueOf(index)
if !rval.IsValid() {
if !rindex.IsValid() {
return nil, ast.PosError(i, "%s: cannot use nil value as an index", valueToString(i))
}

View File

@ -107,6 +107,23 @@ func TestGetIndexNil(t *testing.T) {
}
}
func TestGetIndexNilIndex(t *testing.T) {
testMap := map[string]any{}
tmpl := testTmpl(t)
// test[index]
ast := ast.Index{
Value: ast.Ident{Value: "test", Position: testPos(t)},
Index: ast.Ident{Value: "index", Position: testPos(t)},
Position: testPos(t),
}
_, err := tmpl.getIndex(ast, map[string]any{"test": testMap, "index": nil})
if err == nil {
t.Error("Expected error, got nil")
}
}
func TestGetField(t *testing.T) {
testStruct := struct {
X int