diff --git a/kclvm/sema/src/resolver/import.rs b/kclvm/sema/src/resolver/import.rs index 1927d64b4..fe4d59432 100644 --- a/kclvm/sema/src/resolver/import.rs +++ b/kclvm/sema/src/resolver/import.rs @@ -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(), diff --git a/kclvm/sema/src/resolver/test_fail_data/redefine_import/main.k b/kclvm/sema/src/resolver/test_fail_data/redefine_import/main.k new file mode 100644 index 000000000..2534d9819 --- /dev/null +++ b/kclvm/sema/src/resolver/test_fail_data/redefine_import/main.k @@ -0,0 +1,5 @@ +import sub as s + +import sub.sub as s + +main = s.sub_sub \ No newline at end of file diff --git a/kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/main.k b/kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/main.k new file mode 100644 index 000000000..fd778d797 --- /dev/null +++ b/kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/main.k @@ -0,0 +1 @@ +sub = "sub" \ No newline at end of file diff --git a/kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/sub/main.k b/kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/sub/main.k new file mode 100644 index 000000000..7f92e0de0 --- /dev/null +++ b/kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/sub/main.k @@ -0,0 +1 @@ +sub_sub = "sub_sub" \ No newline at end of file diff --git a/kclvm/sema/src/resolver/tests.rs b/kclvm/sema/src/resolver/tests.rs index 0bf7678ec..a79c4bee2 100644 --- a/kclvm/sema/src/resolver/tests.rs +++ b/kclvm/sema/src/resolver/tests.rs @@ -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();