Skip to content

Commit 5b9e1a4

Browse files
committed
better error when assigning invalid left hand side, fixes #36
1 parent 021d487 commit 5b9e1a4

File tree

1 file changed

+36
-10
lines changed

1 file changed

+36
-10
lines changed

moonscript/parse.lua

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -166,10 +166,15 @@ end
166166

167167
-- makes sure the last item in a chain is an index
168168
local _assignable = { index = true, dot = true, slice = true }
169+
170+
local function is_assignable(node)
171+
local t = ntype(node)
172+
return t == "self" or t == "value" or
173+
t == "chain" and _assignable[ntype(node[#node])]
174+
end
175+
169176
local function check_assignable(str, pos, value)
170-
if ntype(value) == "chain" and _assignable[ntype(value[#value])]
171-
or type(value) == "string"
172-
then
177+
if is_assignable(value) then
173178
return true, value
174179
end
175180
return false
@@ -181,6 +186,13 @@ local function format_assign(lhs_exps, assign)
181186
return flatten_explist(lhs_exps)
182187
end
183188

189+
for _, assign_exp in ipairs(lhs_exps) do
190+
if not is_assignable(assign_exp) then
191+
print(util.dump(assign_exp))
192+
error {assign_exp, "left hand expression is not assignable"}
193+
end
194+
end
195+
184196
local t = ntype(assign)
185197
if t == "assign" then
186198
return {"assign", lhs_exps, unpack(assign, 2)}
@@ -276,7 +288,7 @@ local function self_assign(name)
276288
return {{"key_literal", name}, name}
277289
end
278290

279-
local err_msg = "Failed to parse:\n [%d] >> %s (%d)"
291+
local err_msg = "Failed to parse:%s\n [%d] >> %s"
280292

281293
local build_grammar = wrap_env(function()
282294
local _indent = Stack(0) -- current indent
@@ -559,16 +571,30 @@ local build_grammar = wrap_env(function()
559571
end
560572

561573
local tree
562-
local args = {...}
563-
local pass, err = assert(pcall(function()
564-
tree = self._g:match(str, unpack(args))
565-
end))
574+
local pass, err = pcall(function(...)
575+
tree = self._g:match(str, ...)
576+
end, ...)
577+
578+
-- regular error, let it bubble up
579+
if type(err) == "string" then
580+
error(err)
581+
end
566582

567583
if not tree then
568-
local line_no = pos_to_line(last_pos)
584+
local pos = last_pos
585+
local msg
586+
587+
if err then
588+
local node
589+
node, msg = unpack(err)
590+
msg = msg and " " .. msg
591+
pos = node[-1]
592+
end
593+
594+
local line_no = pos_to_line(pos)
569595
local line_str = get_line(line_no) or ""
570596

571-
return nil, err_msg:format(line_no, trim(line_str), _indent:top())
597+
return nil, err_msg:format(msg or "", line_no, trim(line_str))
572598
end
573599
return tree
574600
end

0 commit comments

Comments
 (0)