Skip to content

Commit 43205ce

Browse files
authored
add failing test: compiler should reject duplicate name (#43)
* add failing test: compiler should reject duplicate name * add test of duplicate constant name and duplicate name checks
1 parent f64a5da commit 43205ce

File tree

3 files changed

+43
-4
lines changed

3 files changed

+43
-4
lines changed

crates/lean_compiler/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ pub fn compile_program(program: &str) -> (Bytecode, BTreeMap<usize, String>) {
2424
let intermediate_bytecode = compile_to_intermediate_bytecode(simple_program).unwrap();
2525
// println!("Intermediate Bytecode:\n\n{}", intermediate_bytecode.to_string());
2626
let compiled = compile_to_low_level_bytecode(intermediate_bytecode).unwrap();
27-
// println!("Compiled Program:\n\n{}", compiled.to_string());
27+
println!("Compiled Program:\n\n{}", compiled.to_string());
2828
(compiled, function_locations)
2929
}
3030

crates/lean_compiler/src/parser.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,18 @@ pub fn parse_program(input: &str) -> Result<(Program, BTreeMap<usize, String>),
5151
match pair.as_rule() {
5252
Rule::constant_declaration => {
5353
let (name, value) = parse_constant_declaration(pair, &constants)?;
54-
constants.insert(name, value);
54+
if constants.insert(name.clone(), value).is_some() {
55+
panic!("Multiply defined constant: {name}");
56+
}
5557
}
5658
Rule::function => {
5759
let location = pair.line_col().0;
5860
let function = parse_function(pair, &constants, &mut trash_var_count)?;
59-
function_locations.insert(location, function.name.clone());
60-
functions.insert(function.name.clone(), function);
61+
let name = function.name.clone();
62+
function_locations.insert(location, name.clone());
63+
if functions.insert(name.clone(), function).is_some() {
64+
panic!("Multiply defined function: {name}");
65+
}
6166
}
6267
Rule::EOI => break,
6368
_ => {}

crates/lean_compiler/tests/test_compiler.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,40 @@ use lean_vm::*;
33
use p3_symmetric::Permutation;
44
use utils::{get_poseidon16, get_poseidon24};
55

6+
#[test]
7+
#[should_panic]
8+
fn test_duplicate_function_name() {
9+
let program = r#"
10+
fn a() -> 1 {
11+
return 0;
12+
}
13+
14+
fn a() -> 1 {
15+
return 1;
16+
}
17+
18+
fn main() {
19+
a();
20+
return;
21+
}
22+
"#;
23+
compile_and_run(program, &[], &[], false);
24+
}
25+
26+
#[test]
27+
#[should_panic]
28+
fn test_duplicate_constant_name() {
29+
let program = r#"
30+
const A = 1;
31+
const A = 0;
32+
33+
fn main() {
34+
return;
35+
}
36+
"#;
37+
compile_and_run(program, &[], &[], false);
38+
}
39+
640
#[test]
741
fn test_fibonacci_program() {
842
// a program to check the value of the 30th Fibonacci number (832040)

0 commit comments

Comments
 (0)