From 9f43170708f8cfe510b88d6748de597638dd4157 Mon Sep 17 00:00:00 2001 From: Marc Vertes Date: Tue, 25 Oct 2022 18:16:10 +0200 Subject: [PATCH] interp: error instead of panic when assigning to a constant Add early detection of assigning to a constant during compiling instead of panicking at runtime. --- interp/cfg.go | 4 ++++ interp/interp_eval_test.go | 1 + 2 files changed, 5 insertions(+) diff --git a/interp/cfg.go b/interp/cfg.go index 27809cdb6..388a26a71 100644 --- a/interp/cfg.go +++ b/interp/cfg.go @@ -579,6 +579,10 @@ func (interp *Interpreter) cfg(root *node, sc *scope, importPath, pkgName string var sym *symbol var level int + if dest.rval.IsValid() && isConstType(dest.typ) { + err = n.cfgErrorf("cannot assign to %s (%s constant)", dest.rval, dest.typ.str) + break + } if isBlank(src) { err = n.cfgErrorf("cannot use _ as value") break diff --git a/interp/interp_eval_test.go b/interp/interp_eval_test.go index 89d963813..0c2d3b9aa 100644 --- a/interp/interp_eval_test.go +++ b/interp/interp_eval_test.go @@ -135,6 +135,7 @@ func TestEvalAssign(t *testing.T) { {src: "j := interface{}(int(1)); j.(_)", err: "1:54: cannot use _ as value"}, {src: "ff := func() (a, b, c int) {return 1, 2, 3}; x, y, x := ff()", err: "1:73: x repeated on left side of :="}, {src: "xx := 1; xx, _ := 2, 3", err: "1:37: no new variables on left side of :="}, + {src: "1 = 2", err: "1:28: cannot assign to 1 (untyped int constant)"}, }) }