From a56121c3291c506b4d8d925452ea908f09fb4c0b Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sun, 26 Apr 2020 10:25:54 +0200 Subject: [PATCH] checker: check mutability in index exprs; parser: set is_mut for args --- vlib/v/checker/checker.v | 15 +++++++++++++++ vlib/v/parser/fn.v | 1 + 2 files changed, 16 insertions(+) diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 29deebb057..04c280af37 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -450,6 +450,7 @@ fn (mut c Checker) assign_expr(assign_expr mut ast.AssignExpr) { if ast.expr_is_blank_ident(assign_expr.left) { return } + // Make sure the variable is mutable match assign_expr.left { ast.Ident { scope := c.file.scope.innermost(assign_expr.pos.pos) @@ -460,6 +461,20 @@ fn (mut c Checker) assign_expr(assign_expr mut ast.AssignExpr) { } } } + ast.IndexExpr { + // `m[key] = val` + if it.left is ast.Ident { + ident := it.left as ast.Ident + // TODO copy pasta + scope := c.file.scope.innermost(assign_expr.pos.pos) + if v := scope.find_var(ident.name) { + if !v.is_mut { + c.error('`$ident.name` is immutable, declare it with `mut` to assign to it', + assign_expr.pos) + } + } + } + } else {} } // Single side check diff --git a/vlib/v/parser/fn.v b/vlib/v/parser/fn.v index c465ee4d21..19bbea336a 100644 --- a/vlib/v/parser/fn.v +++ b/vlib/v/parser/fn.v @@ -161,6 +161,7 @@ fn (mut p Parser) fn_decl() ast.FnDecl { p.scope.register(arg.name, ast.Var{ name: arg.name typ: arg.typ + is_mut: arg.is_mut }) } mut end_pos := p.prev_tok.position()