-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.rs
More file actions
427 lines (380 loc) · 14.3 KB
/
parser.rs
File metadata and controls
427 lines (380 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
mod support;
use std::fs;
use std::path::{Path, PathBuf};
use insta::assert_snapshot;
use notplusplus::diag::DiagEngine;
use notplusplus::parse::{
AssignOp, BinaryOp, Expr, ExprStmt, FunctionDef, Program, Stmt, TopLevelDecl, Type, parse,
render_ast,
};
use notplusplus::source::SourceManager;
#[test]
fn parser_goldens_match() {
let fixture_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/parser");
let mut fixtures = fixture_paths(&fixture_dir);
assert!(
!fixtures.is_empty(),
"expected parser fixtures in {}",
fixture_dir.display()
);
fixtures.sort();
for fixture in fixtures {
let name = fixture
.file_stem()
.and_then(|stem| stem.to_str())
.expect("fixture names should be valid UTF-8");
let source = fs::read_to_string(&fixture)
.unwrap_or_else(|err| panic!("failed to read fixture {}: {err}", fixture.display()));
let mut sm = SourceManager::new();
let file = sm.add_file(
fixture
.file_name()
.and_then(|file_name| file_name.to_str())
.expect("fixture file names should be valid UTF-8")
.to_owned(),
source,
);
let mut diags = DiagEngine::new();
let program = parse(&sm, file, &mut diags);
let rendered = render_snapshot(&sm, &program, &diags);
assert_snapshot!(name, rendered);
}
}
#[test]
fn parser_renders_ast_dump_for_cli_output() {
let program = parse_source(
"dump_ast.cpp",
"int main() {\n int value = 1;\n return value;\n}\n",
);
assert_snapshot!("parser_render_ast_dump", render_ast(&program));
}
#[test]
fn parser_builds_expected_operator_associativity() {
let program = parse_source(
"associativity.cpp",
"int main() {\n a = b = c;\n x - y - z;\n p || q && r;\n return 0;\n}\n",
);
let [TopLevelDecl::FunctionDef(FunctionDef { body, .. })] = &program.decls[..] else {
panic!("expected a single function definition");
};
let [
Stmt::Expr(assign_stmt),
Stmt::Expr(sub_stmt),
Stmt::Expr(logic_stmt),
Stmt::Return(_),
] = &body.stmts[..]
else {
panic!("expected three expression statements followed by return");
};
match assign_stmt
.expr
.as_ref()
.expect("assignment statement should have an expression")
{
Expr::Assign(assign) => {
assert_eq!(assign.op, AssignOp::Assign);
assert!(matches!(assign.lhs.as_ref(), Expr::Name(name) if name.name == "a"));
match assign.rhs.as_ref() {
Expr::Assign(inner) => {
assert_eq!(inner.op, AssignOp::Assign);
assert!(matches!(inner.lhs.as_ref(), Expr::Name(name) if name.name == "b"));
assert!(matches!(inner.rhs.as_ref(), Expr::Name(name) if name.name == "c"));
}
other => panic!("expected right-associative nested assignment, got {other:?}"),
}
}
other => panic!("expected assignment expression, got {other:?}"),
}
match sub_stmt
.expr
.as_ref()
.expect("subtraction statement should have an expression")
{
Expr::Binary(binary) => {
assert_eq!(binary.op, BinaryOp::Sub);
match binary.lhs.as_ref() {
Expr::Binary(lhs) => {
assert_eq!(lhs.op, BinaryOp::Sub);
assert!(matches!(lhs.lhs.as_ref(), Expr::Name(name) if name.name == "x"));
assert!(matches!(lhs.rhs.as_ref(), Expr::Name(name) if name.name == "y"));
}
other => panic!("expected left-associative subtraction lhs, got {other:?}"),
}
assert!(matches!(binary.rhs.as_ref(), Expr::Name(name) if name.name == "z"));
}
other => panic!("expected subtraction expression, got {other:?}"),
}
match logic_stmt
.expr
.as_ref()
.expect("logical statement should have an expression")
{
Expr::Binary(binary) => {
assert_eq!(binary.op, BinaryOp::LogicalOr);
assert!(matches!(binary.lhs.as_ref(), Expr::Name(name) if name.name == "p"));
match binary.rhs.as_ref() {
Expr::Binary(rhs) => {
assert_eq!(rhs.op, BinaryOp::LogicalAnd);
assert!(matches!(rhs.lhs.as_ref(), Expr::Name(name) if name.name == "q"));
assert!(matches!(rhs.rhs.as_ref(), Expr::Name(name) if name.name == "r"));
}
other => panic!("expected && on the rhs of ||, got {other:?}"),
}
}
other => panic!("expected logical-or expression, got {other:?}"),
}
}
#[test]
fn parser_accepts_compound_assignments_and_loop_control() {
let program = parse_source(
"loop_control.cpp",
"int main() {\n while (true) break;\n for (;;)\n continue;\n x += 1;\n y -= 2;\n z *= 3;\n q /= 4;\n r %= 5;\n return 0;\n}\n",
);
let [TopLevelDecl::FunctionDef(FunctionDef { body, .. })] = &program.decls[..] else {
panic!("expected a single function definition");
};
let [
Stmt::While(while_stmt),
Stmt::For(for_stmt),
Stmt::Expr(add_assign),
Stmt::Expr(sub_assign),
Stmt::Expr(mul_assign),
Stmt::Expr(div_assign),
Stmt::Expr(rem_assign),
Stmt::Return(_),
] = &body.stmts[..]
else {
panic!("expected loop-control and compound-assignment statements");
};
assert!(matches!(while_stmt.body.as_ref(), Stmt::Break(_)));
assert!(matches!(for_stmt.body.as_ref(), Stmt::Continue(_)));
assert_expr_assign_op(add_assign, AssignOp::AddAssign);
assert_expr_assign_op(sub_assign, AssignOp::SubAssign);
assert_expr_assign_op(mul_assign, AssignOp::MulAssign);
assert_expr_assign_op(div_assign, AssignOp::DivAssign);
assert_expr_assign_op(rem_assign, AssignOp::RemAssign);
}
#[test]
fn parser_accepts_array_declarations_and_subscripts() {
let program = parse_source(
"arrays.cpp",
"int main() {\n int a[3];\n bool seen[2];\n a[0] = 1;\n seen[1] = false;\n return a[0];\n}\n",
);
let [TopLevelDecl::FunctionDef(FunctionDef { body, .. })] = &program.decls[..] else {
panic!("expected a single function definition");
};
let [
Stmt::Decl(int_array),
Stmt::Decl(bool_array),
Stmt::Expr(write_int),
Stmt::Expr(write_bool),
Stmt::Return(ret),
] = &body.stmts[..]
else {
panic!("expected array declarations, element writes, and a return");
};
assert_eq!(int_array.ty, Type::Int);
assert_eq!(int_array.array_len, Some(3));
assert_eq!(bool_array.ty, Type::Bool);
assert_eq!(bool_array.array_len, Some(2));
match write_int.expr.as_ref() {
Some(Expr::Assign(assign)) => {
assert_eq!(assign.op, AssignOp::Assign);
match assign.lhs.as_ref() {
Expr::Subscript(subscript) => {
assert!(matches!(
subscript.base.as_ref(),
Expr::Name(name) if name.name == "a"
));
assert!(matches!(
subscript.index.as_ref(),
Expr::IntLiteral(lit) if lit.value == 0
));
}
other => panic!("expected int array subscript assignment lhs, got {other:?}"),
}
}
other => panic!("expected int array assignment expression, got {other:?}"),
}
match write_bool.expr.as_ref() {
Some(Expr::Assign(assign)) => match assign.lhs.as_ref() {
Expr::Subscript(subscript) => {
assert!(matches!(
subscript.base.as_ref(),
Expr::Name(name) if name.name == "seen"
));
assert!(matches!(
subscript.index.as_ref(),
Expr::IntLiteral(lit) if lit.value == 1
));
}
other => panic!("expected bool array subscript assignment lhs, got {other:?}"),
},
other => panic!("expected bool array assignment expression, got {other:?}"),
}
match ret.expr.as_ref() {
Some(Expr::Subscript(subscript)) => {
assert!(matches!(
subscript.base.as_ref(),
Expr::Name(name) if name.name == "a"
));
assert!(matches!(
subscript.index.as_ref(),
Expr::IntLiteral(lit) if lit.value == 0
));
}
other => panic!("expected array subscript return expression, got {other:?}"),
}
}
#[test]
fn parser_accepts_parenthesized_array_element_assignments() {
let program = parse_source(
"paren_array_assign.cpp",
"int main() {\n int a[1];\n (a[0]) = 1;\n (a[0]) += 2;\n return a[0];\n}\n",
);
let [TopLevelDecl::FunctionDef(FunctionDef { body, .. })] = &program.decls[..] else {
panic!("expected a single function definition");
};
let [
Stmt::Decl(_),
Stmt::Expr(assign),
Stmt::Expr(add_assign),
Stmt::Return(_),
] = &body.stmts[..]
else {
panic!("expected declaration, two assignments, and return");
};
match assign.expr.as_ref() {
Some(Expr::Assign(assign)) => {
assert_eq!(assign.op, AssignOp::Assign);
assert!(matches!(assign.lhs.as_ref(), Expr::Paren(_)));
}
other => panic!("expected parenthesized assignment, got {other:?}"),
}
match add_assign.expr.as_ref() {
Some(Expr::Assign(assign)) => {
assert_eq!(assign.op, AssignOp::AddAssign);
assert!(matches!(assign.lhs.as_ref(), Expr::Paren(_)));
}
other => panic!("expected parenthesized compound assignment, got {other:?}"),
}
}
#[test]
fn parser_rejects_invalid_array_declarators() {
let (_, rendered) = parse_source_with_diags(
"invalid_arrays.cpp",
"int main() {\n int zero[0];\n int neg[-1];\n int dyn[n];\n int init[2] = 1;\n}\n",
);
assert!(
rendered.contains("array size must be a positive integer literal"),
"expected positive-size diagnostic, got:\n{rendered}"
);
assert!(
rendered.contains("initialized arrays are unsupported"),
"expected initialized-array diagnostic, got:\n{rendered}"
);
}
#[test]
fn parser_reports_out_of_range_integer_literals_without_panicking() {
let (program, rendered) =
parse_source_with_diags("overflow.cpp", "int main() {\n return 2147483648;\n}\n");
assert_eq!(
program.decls.len(),
1,
"the surrounding function should still parse"
);
assert!(
rendered.contains("error[NPP2004]: integer literal is out of range for 'int'"),
"expected range diagnostic, got:\n{rendered}"
);
}
#[test]
fn parser_preserves_spans_for_empty_statement_bodies() {
let mut sm = SourceManager::new();
sm.add_file(
"first.cpp".to_owned(),
"int ignored() { return 0; }\n".to_owned(),
);
let file = sm.add_file(
"second.cpp".to_owned(),
"int main() {\n if (true) ;\n while (false) ;\n for (;;)\n ;\n return 0;\n}\n"
.to_owned(),
);
let mut diags = DiagEngine::new();
let program = parse(&sm, file, &mut diags);
assert!(
!diags.has_errors(),
"expected parser success, got:\n{}",
support::normalize_newlines(&diags.render_to_string(&sm))
);
let [TopLevelDecl::FunctionDef(FunctionDef { body, .. })] = &program.decls[..] else {
panic!("expected a single function definition");
};
let [
Stmt::If(if_stmt),
Stmt::While(while_stmt),
Stmt::For(for_stmt),
Stmt::Return(_),
] = &body.stmts[..]
else {
panic!("expected empty-body control-flow statements");
};
assert_stmt_in_file(if_stmt.then_branch.as_ref(), file);
assert_stmt_in_file(while_stmt.body.as_ref(), file);
assert_stmt_in_file(for_stmt.body.as_ref(), file);
assert!(if_stmt.span.end > if_stmt.span.start);
assert!(while_stmt.span.end > while_stmt.span.start);
assert!(for_stmt.span.end > for_stmt.span.start);
}
fn fixture_paths(dir: &Path) -> Vec<PathBuf> {
fs::read_dir(dir)
.unwrap_or_else(|err| panic!("failed to read fixture directory {}: {err}", dir.display()))
.map(|entry| {
entry
.expect("fixture directory entries should be readable")
.path()
})
.filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("cpp"))
.collect()
}
fn parse_source(name: &str, source: &str) -> Program {
let (program, rendered) = parse_source_with_diags(name, source);
assert!(
!rendered.contains("error["),
"expected parser success, got:\n{rendered}"
);
program
}
fn parse_source_with_diags(name: &str, source: &str) -> (Program, String) {
let mut sm = SourceManager::new();
let file = sm.add_file(name.to_owned(), source.to_owned());
let mut diags = DiagEngine::new();
let program = parse(&sm, file, &mut diags);
let rendered = support::normalize_newlines(&diags.render_to_string(&sm));
(program, rendered)
}
fn render_snapshot(sm: &SourceManager, program: &Program, diags: &DiagEngine) -> String {
let mut out = render_ast(program);
out.push_str("diagnostics:\n");
if diags.diagnostics().is_empty() {
out.push_str("<none>\n");
} else {
out.push_str(&support::normalize_newlines(&diags.render_to_string(sm)));
}
out
}
fn assert_expr_assign_op(stmt: &ExprStmt, expected: AssignOp) {
match stmt.expr.as_ref() {
Some(Expr::Assign(assign)) => assert_eq!(assign.op, expected),
other => panic!("expected assignment expression, got {other:?}"),
}
}
fn assert_stmt_in_file(stmt: &Stmt, file: notplusplus::source::FileId) {
match stmt {
Stmt::Expr(expr_stmt) => {
assert_eq!(expr_stmt.span.file, file);
assert!(expr_stmt.span.end >= expr_stmt.span.start);
}
other => panic!("expected empty expression statement, got {other:?}"),
}
}