checker: check mutability in index exprs; parser: set is_mut for args

pull/4606/head
Alexander Medvednikov 2020-04-26 10:25:54 +02:00
parent ee31339dfd
commit a56121c329
2 changed files with 16 additions and 0 deletions

View File

@ -450,6 +450,7 @@ fn (mut c Checker) assign_expr(assign_expr mut ast.AssignExpr) {
if ast.expr_is_blank_ident(assign_expr.left) { if ast.expr_is_blank_ident(assign_expr.left) {
return return
} }
// Make sure the variable is mutable
match assign_expr.left { match assign_expr.left {
ast.Ident { ast.Ident {
scope := c.file.scope.innermost(assign_expr.pos.pos) 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 {} else {}
} }
// Single side check // Single side check

View File

@ -161,6 +161,7 @@ fn (mut p Parser) fn_decl() ast.FnDecl {
p.scope.register(arg.name, ast.Var{ p.scope.register(arg.name, ast.Var{
name: arg.name name: arg.name
typ: arg.typ typ: arg.typ
is_mut: arg.is_mut
}) })
} }
mut end_pos := p.prev_tok.position() mut end_pos := p.prev_tok.position()