From 4d6ba76b2e534804b116f9eab9634a4847b5a561 Mon Sep 17 00:00:00 2001 From: Laurence Tratt Date: Tue, 9 Jun 2020 17:36:04 +0100 Subject: [PATCH] Don't allow the user to define the same field name in a class more than once. --- lang_tests/instance_fields_overlap2.som | 12 ++++++++++++ src/lib/compiler/ast_to_instrs.rs | 16 +++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 lang_tests/instance_fields_overlap2.som diff --git a/lang_tests/instance_fields_overlap2.som b/lang_tests/instance_fields_overlap2.som new file mode 100644 index 00000000..2a9419ee --- /dev/null +++ b/lang_tests/instance_fields_overlap2.som @@ -0,0 +1,12 @@ +" +VM: + status: error + stderr: + ...instance_fields_overlap2.som', line 11, column 9: + | a a | + Field 'a' has already been defined in this class. +" + +instance_field_overlap2 = ( + | a a | +) diff --git a/src/lib/compiler/ast_to_instrs.rs b/src/lib/compiler/ast_to_instrs.rs index 504bbece..be6929c2 100644 --- a/src/lib/compiler/ast_to_instrs.rs +++ b/src/lib/compiler/ast_to_instrs.rs @@ -168,7 +168,21 @@ impl<'a, 'input> Compiler<'a, 'input> { }; for var in ast_inst_vars { let vars_len = inst_vars.len(); - inst_vars.insert(lexer.span_str(*var).to_owned(), vars_len); + let n = lexer.span_str(*var).to_owned(); + match inst_vars.entry(n) { + hash_map::Entry::Occupied(_) => { + return Err(vec![( + *var, + format!( + "Field '{}' has already been defined in this class.", + self.lexer.span_str(*var) + ), + )]) + } + hash_map::Entry::Vacant(e) => { + e.insert(vars_len); + } + } } self.vars_stack.push(inst_vars);