Skip to content

Commit

Permalink
Merge pull request #193 from Mido-sys/fix_panic_unassignabile_array
Browse files Browse the repository at this point in the history
Fix Panic when the underlying data type of the array differs from value
  • Loading branch information
paganotoni authored Feb 6, 2025
2 parents e1f0290 + 331eaa5 commit d62fe8a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
11 changes: 10 additions & 1 deletion compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,16 @@ func (c *compiler) evalUpdateIndex(left, index, value interface{}) error {
if rv.Len()-1 < i {
err = fmt.Errorf("array index out of bounds, got index %d, while array size is %v", i, rv.Len())
} else {
rv.Index(i).Set(reflect.ValueOf(value))
elemType := reflect.TypeOf(left).Elem()
if elemType.Kind() != reflect.Interface {
t := reflect.ValueOf(value).Type()
if elemType != t {
err = fmt.Errorf("cannot use '%v' (untyped %s constant) as %s value in assignment", value, t, elemType)
}
}
if err == nil {
rv.Index(i).Set(reflect.ValueOf(value))
}
}
} else {
err = fmt.Errorf("can't access Slice/Array with a non int Index (%v)", index)
Expand Down
29 changes: 29 additions & 0 deletions variables_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,35 @@ func Test_Render_Let_Array(t *testing.T) {
}
}

func Test_Render_Let_ArrayAsssign_Unassignable(t *testing.T) {
r := require.New(t)
ctx := plush.NewContext()

type tt struct {
P string
}

ctx.Set("myArray", []tt{tt{P: "t"}})
input := `<p><% let a = myArray %></p><% a[0] = "HELLO WORLD" %>`
_, err := plush.Render(input, ctx)
r.Error(err)
r.Contains(err.Error(), "cannot use 'HELLO WORLD' (untyped string constant) as plush_test.tt value in assignment")
}

func Test_Render_Let_ArrayAsssign_AssignableToArrayInterface(t *testing.T) {
r := require.New(t)
ctx := plush.NewContext()

type tt struct {
P string
}

ctx.Set("myArray", []interface{}{tt{P: "t"}, tt{P: "g"}})
input := `<p><% let a = myArray %></p><% a[0] = "HELLO WORLD" %>`
_, err := plush.Render(input, ctx)
r.NoError(err)
}

type Category1 struct {
Products []Product1
}
Expand Down

0 comments on commit d62fe8a

Please sign in to comment.