Skip to content

Commit f7c2a29

Browse files
committed
Fix parser crashes, assignment chains, deep nesting, comma edge cases, mixed tabs in brackets (#1) [merged from test repo]
1 parent 31b7626 commit f7c2a29

9 files changed

Lines changed: 176 additions & 9 deletions

File tree

‎shell_lite/compiler.cpp‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,46 @@ class ProperCompiler : public Visitor {
164164
}
165165

166166
// write value to local slot, upvalue, self prop or global
167+
bool assign_declares_local(const std::string &name) {
168+
if (resolve_local(state, name) != -1)
169+
return false;
170+
if (resolve_upvalue(state, name) != -1)
171+
return false;
172+
if (compiling_method && resolve_local(state, "self") != -1)
173+
return false;
174+
return state->enclosing != nullptr && state->scope_depth > 0;
175+
}
176+
177+
void compile_assign_expr(Assign *node) {
178+
std::vector<std::string> targets;
179+
Node *v = node;
180+
while (Assign *a = dynamic_cast<Assign *>(v)) {
181+
if (!a->value) {
182+
throw CompileError("Compilation aborted",
183+
{source_file, current_line, current_col});
184+
}
185+
targets.emplace_back(a->name);
186+
v = a->value;
187+
}
188+
v->accept(this);
189+
std::vector<std::string> setters, declarers;
190+
for (auto &t : targets)
191+
(assign_declares_local(t) ? declarers : setters).push_back(t);
192+
size_t remaining = targets.size();
193+
for (auto &t : setters) {
194+
if (remaining > 1)
195+
emit_byte(OP_DUP);
196+
emit_assignment(t);
197+
--remaining;
198+
}
199+
for (auto &t : declarers) {
200+
if (remaining > 1)
201+
emit_byte(OP_DUP);
202+
emit_assignment(t);
203+
--remaining;
204+
}
205+
}
206+
167207
void emit_assignment(const std::string &name) {
168208
int arg = resolve_local(state, name);
169209
if (arg != -1) {
@@ -408,8 +448,7 @@ class ProperCompiler : public Visitor {
408448
throw CompileError("Compilation aborted",
409449
{source_file, current_line, current_col});
410450
}
411-
node->value->accept(this);
412-
emit_assignment(std::string(node->name));
451+
compile_assign_expr(node);
413452
}
414453

415454
void visit(TypedAssign *n) override {

‎shell_lite/gbp_core_logic.cpp‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,35 @@ bool is_anchor_line(std::string_view source, size_t line_start) {
3030
return true;
3131
}
3232

33+
static void check_mixed_tabs_continuations(std::string_view raw_block, int start_line,
34+
std::string_view source,
35+
std::vector<SyntaxError> &diagnostics) {
36+
int cont_line = start_line;
37+
size_t search = 0;
38+
while (search < raw_block.size()) {
39+
size_t nl = raw_block.find('\n', search);
40+
if (nl == std::string_view::npos)
41+
break;
42+
++cont_line;
43+
size_t i = nl + 1;
44+
bool c_has_tab = false, c_has_space = false;
45+
while (i < raw_block.size() && (raw_block[i] == ' ' || raw_block[i] == '\t')) {
46+
if (raw_block[i] == '\t')
47+
c_has_tab = true;
48+
else
49+
c_has_space = true;
50+
++i;
51+
}
52+
bool has_content = i < raw_block.size() && raw_block[i] != '\n' && raw_block[i] != '\r';
53+
if (c_has_tab && c_has_space && has_content) {
54+
std::string sl = extract_source_line(source, cont_line);
55+
diagnostics.push_back(SyntaxError("IndentationError: mixed tabs and spaces in indentation",
56+
SourceLocation{"", cont_line, 1, sl, "use either tabs or spaces consistently"}));
57+
}
58+
search = nl + 1;
59+
}
60+
}
61+
3362
TopographyResult phase1_topography_scan(std::string_view source) {
3463
TopographyResult result;
3564
result.nodes.reserve(source.size() / 40);
@@ -148,6 +177,7 @@ TopographyResult phase1_topography_scan(std::string_view source) {
148177
result.diagnostics.push_back(SyntaxError("IndentationError: mixed tabs and spaces in indentation",
149178
SourceLocation{"", start_line, 1, sl, "use either tabs or spaces consistently"}));
150179
}
180+
check_mixed_tabs_continuations(raw_block, start_line, source, result.diagnostics);
151181
result.nodes.push_back({start_line, indent, -1, raw_block, {}, {}, false});
152182
}
153183

@@ -325,6 +355,7 @@ static ChunkScanResult scan_chunk(std::string_view source, size_t chunk_start, s
325355
result.diagnostics.push_back(SyntaxError("IndentationError: mixed tabs and spaces in indentation",
326356
SourceLocation{"", current_start_line, 1, sl, "use either tabs or spaces consistently"}));
327357
}
358+
check_mixed_tabs_continuations(raw_block, current_start_line, source, result.diagnostics);
328359
if (!result.has_anchor && indent == 0 && is_anchor_line(source, node_start)) {
329360
result.has_anchor = true;
330361
result.first_anchor_line = current_start_line;

‎shell_lite/parser.hpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ class Parser {
6262
Parser &parent_;
6363
size_t pos_ = 0;
6464
bool is_complex_ = false;
65+
int expr_depth_ = 0;
6566

6667
Node *parse_assignment();
6768
Node *parse_logical_or();

‎shell_lite/parser/parser_core.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,7 @@ Node *Parser::bind_node(int index) {
249249
Node *val = parse_expr_recursive(
250250
std::vector<Token>(tokens.begin() + assign_idx + 1, tokens.end()),
251251
flat_nodes_[index].child_indices);
252+
check_assignment_chain(val, true, flat_nodes_[index].line);
252253
Assign *a = arena_.emplace<Assign>(name, val);
253254
set_node_loc(a, index);
254255
return a;
@@ -267,6 +268,7 @@ Node *Parser::bind_node(int index) {
267268
flat_nodes_[index].child_indices);
268269

269270
TokenType op = tokens[assign_idx].type;
271+
check_assignment_chain(val, true, flat_nodes_[index].line);
270272
if (op != TokenType::TOK_ASSIGN) {
271273
std::string_view op_str = get_compound_op_str(op);
272274
val =

‎shell_lite/parser/parser_expressions.cpp‎

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ Parser::SubParser::SubParser(const std::vector<Token> &tokens, Arena &arena,
1010
child_indices_(child_indices) {}
1111

1212
Node *Parser::SubParser::parse_expression() {
13+
struct DepthGuard {
14+
int &depth;
15+
explicit DepthGuard(int &d) : depth(d) { ++depth; }
16+
~DepthGuard() { --depth; }
17+
};
18+
DepthGuard guard(expr_depth_);
19+
if (expr_depth_ > 100)
20+
throw SyntaxError("Syntax error: Expression nested too deeply");
1321
return parse_assignment();
1422
}
1523

@@ -195,11 +203,16 @@ Node *Parser::SubParser::parse_assignment() {
195203
throw SyntaxError(
196204
"Syntax error: Missing right operand for assignment at line " +
197205
std::to_string(op.line));
198-
if (VarAccess *v = dynamic_cast<VarAccess *>(node))
206+
if (VarAccess *v = dynamic_cast<VarAccess *>(node)) {
207+
check_assignment_chain(value, true, op.line);
199208
return arena_.emplace<Assign>(v->name, value);
200-
if (IndexAccess *idx = dynamic_cast<IndexAccess *>(node))
209+
}
210+
if (IndexAccess *idx = dynamic_cast<IndexAccess *>(node)) {
211+
check_assignment_chain(value, false, op.line);
201212
return arena_.emplace<IndexAssign>(idx->obj, idx->index, value);
213+
}
202214
if (PropertyAccess *prop = dynamic_cast<PropertyAccess *>(node)) {
215+
check_assignment_chain(value, false, op.line);
203216
PropertyAssign *pa = arena_.emplace<PropertyAssign>();
204217
pa->instance_name = prop->instance_name;
205218
pa->property_name = prop->property_name;
@@ -467,7 +480,13 @@ Node *Parser::SubParser::parse_call_and_access() {
467480
mc->method_name = pa->property_name;
468481
if (!check(TokenType::TOK_RPAREN)) {
469482
do {
470-
mc->args.push_back(parse_expression());
483+
if (check(TokenType::TOK_RPAREN))
484+
break;
485+
Node *arg = parse_expression();
486+
if (!arg)
487+
throw SyntaxError(
488+
"Syntax error: Expected expression in argument list");
489+
mc->args.push_back(arg);
471490
} while (match(TokenType::TOK_COMMA));
472491
}
473492
consume(TokenType::TOK_RPAREN, "Expected ')'");
@@ -482,13 +501,24 @@ Node *Parser::SubParser::parse_call_and_access() {
482501
}
483502
if (!check(TokenType::TOK_RPAREN)) {
484503
do {
504+
if (check(TokenType::TOK_RPAREN))
505+
break;
485506
if (check(TokenType::TOK_ID) && pos_ + 1 < tokens_.size() &&
486507
tokens_[pos_ + 1].type == TokenType::TOK_ASSIGN) {
487508
std::string_view key = consume(TokenType::TOK_ID, "").value;
488509
consume(TokenType::TOK_ASSIGN, "");
489-
call->kwargs.push_back({key, parse_expression()});
490-
} else
491-
call->args.push_back(parse_expression());
510+
Node *arg = parse_expression();
511+
if (!arg)
512+
throw SyntaxError(
513+
"Syntax error: Expected expression in argument list");
514+
call->kwargs.push_back({key, arg});
515+
} else {
516+
Node *arg = parse_expression();
517+
if (!arg)
518+
throw SyntaxError(
519+
"Syntax error: Expected expression in argument list");
520+
call->args.push_back(arg);
521+
}
492522
} while (match(TokenType::TOK_COMMA));
493523
}
494524
consume(TokenType::TOK_RPAREN, "Expected ')'");
@@ -919,7 +949,10 @@ Node *Parser::SubParser::parse_primary() {
919949
}
920950
if (check(TokenType::TOK_RBRACKET))
921951
break;
922-
list->elements.push_back(parse_expression());
952+
Node *elem = parse_expression();
953+
if (!elem)
954+
throw SyntaxError("Syntax error: Expected expression in list literal");
955+
list->elements.push_back(elem);
923956
} else {
924957
break;
925958
}

‎shell_lite/parser/parser_functions.cpp‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,11 +165,13 @@ Node *Parser::bind_complex_assignment(int index, size_t assign_idx) {
165165
}
166166

167167
if (IndexAccess *idx = dynamic_cast<IndexAccess *>(lhs)) {
168+
check_assignment_chain(rhs, false, flat_nodes_[index].line);
168169
IndexAssign *ia = arena_.emplace<IndexAssign>(idx->obj, idx->index, rhs);
169170
set_node_loc(ia, index);
170171
return ia;
171172
}
172173
if (PropertyAccess *prop = dynamic_cast<PropertyAccess *>(lhs)) {
174+
check_assignment_chain(rhs, false, flat_nodes_[index].line);
173175
PropertyAssign *pa = arena_.emplace<PropertyAssign>();
174176
pa->instance_name = prop->instance_name;
175177
pa->property_name = prop->property_name;
@@ -178,6 +180,7 @@ Node *Parser::bind_complex_assignment(int index, size_t assign_idx) {
178180
return pa;
179181
}
180182
if (VarAccess *v = dynamic_cast<VarAccess *>(lhs)) {
183+
check_assignment_chain(rhs, true, flat_nodes_[index].line);
181184
Assign *a = arena_.emplace<Assign>(v->name, rhs);
182185
set_node_loc(a, index);
183186
return a;

‎shell_lite/parser/parser_internal.hpp‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,14 @@ static inline std::string_view get_compound_op_str(TokenType op) {
2828
: "%";
2929
}
3030

31+
static inline void check_assignment_chain(Node *value, bool outer_is_plain_var,
32+
int line) {
33+
bool v_is_assign = dynamic_cast<Assign *>(value) != nullptr;
34+
bool v_is_complex = dynamic_cast<IndexAssign *>(value) != nullptr ||
35+
dynamic_cast<PropertyAssign *>(value) != nullptr;
36+
if (v_is_complex || (!outer_is_plain_var && v_is_assign))
37+
throw SyntaxError("Syntax error: Cannot chain mixed assignment targets at line " +
38+
std::to_string(line));
39+
}
40+
3141
} // namespace shell_lite

‎tests/test_errors.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,36 @@ def test_primitive_prop(self):
5353
def test_missing_import(self):
5454
self.assert_error("import NonExistentModule12345", "Module not found:")
5555

56+
def test_double_comma_list(self):
57+
self.assert_error("x = [1,,2]", "Expected expression in list literal")
58+
59+
def test_double_comma_call(self):
60+
self.assert_error("f(1,,2)", "Expected expression in argument list")
61+
62+
def test_deep_parens(self):
63+
code = "say " + "("*600 + "1" + ")"*600
64+
self.assert_error(code, "nested too deeply")
65+
66+
def test_mixed_tabs_bracket_continuation(self):
67+
self.assert_error("x = [\n \t1,\n]", "mixed tabs and spaces")
68+
69+
def test_chained_assign_var_property(self):
70+
code = "class P\n init():\n self.x = 0\np = P()\na = p.x = 1"
71+
self.assert_error(code, "Cannot chain mixed assignment targets")
72+
73+
def test_chained_assign_var_index(self):
74+
self.assert_error("l = [0]\na = l[0] = 1", "Cannot chain mixed assignment targets")
75+
76+
def test_chained_assign_property_var(self):
77+
code = "class P\n init():\n self.x = 0\np = P()\np.x = a = 1"
78+
self.assert_error(code, "Cannot chain mixed assignment targets")
79+
80+
def test_chained_assign_index_var(self):
81+
self.assert_error("l = [0]\nl[0] = a = 1", "Cannot chain mixed assignment targets")
82+
83+
def test_plain_chained_assign_still_works(self):
84+
self.assertEqual(run_shl_code("a = b = 1\nsay a + b").strip(), "2")
85+
5686
def test_error_format(self):
5787
with self.assertRaises(RuntimeError) as ctx:
5888
run_shl_code('throw "Fatal custom error"')

‎tests/test_interpreter.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,24 @@ def test_var_assign(self):
1717
code = "x = 10\nsay x"
1818
self.assertEqual(run_shl_code(code).strip(), "10")
1919

20+
def test_chained_assignment(self):
21+
code = "a = b = c = 1\nsay a\nsay b\nsay c"
22+
self.assertEqual(run_shl_code(code).strip(), "1\n1\n1")
23+
24+
def test_chained_assignment_in_function(self):
25+
code = "to f()\n a = b = 1\n say a\n say b\nf()"
26+
self.assertEqual(run_shl_code(code).strip(), "1\n1")
27+
28+
def test_chained_assignment_mixed_targets(self):
29+
code = "to f()\n a = 0\n a = b = 1\n say a\n say b\nf()"
30+
self.assertEqual(run_shl_code(code).strip(), "1\n1")
31+
code = "to f()\n b = 0\n a = b = 1\n say a\n say b\nf()"
32+
self.assertEqual(run_shl_code(code).strip(), "1\n1")
33+
34+
def test_trailing_comma_call(self):
35+
code = "to f(x)\n say x\nf(1,)"
36+
self.assertEqual(run_shl_code(code).strip(), "1")
37+
2038
def test_bin_ops(self):
2139
code = "x = 5 + 5\nsay x"
2240
self.assertEqual(run_shl_code(code).strip(), "10")

0 commit comments

Comments
 (0)