Skip to content

Commit

Permalink
fix: raise an error when the asname of import statment is defined mul…
Browse files Browse the repository at this point in the history
…ti-times (#727)

* fix: raise an error when the asname of import statment is defined multi-times

* fix: make fmt

* fix: move test cases to resolver

* fix: fix CR comments
  • Loading branch information
zong-zhe authored Sep 22, 2023
1 parent 92a4d8b commit 44d81f4
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 0 deletions.
14 changes: 14 additions & 0 deletions kclvm/sema/src/resolver/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,20 @@ impl<'ctx> Resolver<'ctx> {
{
match self.ctx.import_names.get_mut(&self.ctx.filename) {
Some(mapping) => {
// 'import sub as s' and 'import sub.sub as s' will raise this error.
// 'import sub' and 'import sub' will not raise this error.
// 'import sub as s' and 'import sub as s' will not raise this error.
if let Some(path) = mapping.get(&import_stmt.name) {
if path != &import_stmt.path {
self.handler.add_compile_error(
&format!(
"the name '{}' is defined multiple times, '{}' must be defined only once",
import_stmt.name, import_stmt.name
),
stmt.get_span_pos(),
);
}
}
mapping.insert(
import_stmt.name.to_string(),
import_stmt.path.to_string(),
Expand Down
5 changes: 5 additions & 0 deletions kclvm/sema/src/resolver/test_fail_data/redefine_import/main.k
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import sub as s

import sub.sub as s

main = s.sub_sub
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sub = "sub"
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sub_sub = "sub_sub"
24 changes: 24 additions & 0 deletions kclvm/sema/src/resolver/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,30 @@ fn test_resolve_program_fail() {
}
}

#[test]
fn test_resolve_program_redefine() {
let sess = Arc::new(ParseSession::default());
let mut program = load_program(
sess.clone(),
&["./src/resolver/test_fail_data/redefine_import/main.k"],
None,
)
.unwrap();

let scope = resolve_program(&mut program);
assert_eq!(scope.handler.diagnostics.len(), 2);
let diag = &scope.handler.diagnostics[0];
assert_eq!(
diag.code,
Some(DiagnosticId::Error(ErrorKind::CompileError))
);
assert_eq!(diag.messages.len(), 1);
assert_eq!(
diag.messages[0].message,
"the name 's' is defined multiple times, 's' must be defined only once"
);
}

#[test]
fn test_resolve_program_mismatch_type_fail() {
let mut program = parse_program("./src/resolver/test_fail_data/config_expr.k").unwrap();
Expand Down

0 comments on commit 44d81f4

Please sign in to comment.