Skip to content

Commit

Permalink
fix: add full type string for function type (#771)
Browse files Browse the repository at this point in the history
* fix: add full type string for function type

Signed-off-by: zongz <[email protected]>

* fix: change the location of test case

Signed-off-by: zongz <[email protected]>

---------

Signed-off-by: zongz <[email protected]>
  • Loading branch information
zong-zhe committed Oct 16, 2023
1 parent 3ad1f27 commit 83cc443
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
6 changes: 6 additions & 0 deletions kclvm/sema/src/resolver/test_fail_data/lambda_ty_error.k
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
_func = lambda x: int, y: int -> int {
x - y
} # Ok
_func = lambda x: int, y: int -> str {
str(x + y)
} # Error: expect function (int, int) -> str, got function (int, int) -> int
20 changes: 20 additions & 0 deletions kclvm/sema/src/resolver/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -549,3 +549,23 @@ fn test_resolve_assignment_in_lambda() {
let images_scope_obj = lambda_scope.borrow().elems.get("images").unwrap().clone();
assert_eq!(images_scope_obj.borrow().ty.ty_str(), "[str]");
}

#[test]
fn test_resolve_lambda_assignment_diagnostic() {
let sess = Arc::new(ParseSession::default());
let mut program = load_program(
sess.clone(),
&["./src/resolver/test_fail_data/lambda_ty_error.k"],
None,
)
.unwrap();
let scope = resolve_program(&mut program);
assert_eq!(scope.handler.diagnostics.len(), 1);
let diag = &scope.handler.diagnostics[0];
assert_eq!(diag.code, Some(DiagnosticId::Error(ErrorKind::TypeError)));
assert_eq!(diag.messages.len(), 1);
assert_eq!(
diag.messages[0].message,
"expected function (int, int) -> int, got function (int, int) -> str"
);
}
16 changes: 15 additions & 1 deletion kclvm/sema/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl Type {
.join("|"),
TypeKind::Schema(schema_ty) => schema_ty.name.to_string(),
TypeKind::NumberMultiplier(number_multiplier) => number_multiplier.ty_str(),
TypeKind::Function(_) => FUNCTION_TYPE_STR.to_string(),
TypeKind::Function(func_ty) => func_ty.ty_str(),
TypeKind::Void => VOID_TYPE_STR.to_string(),
TypeKind::Module(module_ty) => format!("{} '{}'", MODULE_TYPE_STR, module_ty.pkgpath),
TypeKind::Named(name) => name.to_string(),
Expand Down Expand Up @@ -387,6 +387,20 @@ pub struct FunctionType {
pub kw_only_index: Option<usize>,
}

impl FunctionType {
pub fn ty_str(&self) -> String {
format!(
"function ({}) -> {}",
self.params
.iter()
.map(|param| param.ty.ty_str())
.collect::<Vec<String>>()
.join(", "),
self.return_ty.ty_str()
)
}
}

impl FunctionType {
#[inline]
pub fn variadic_func() -> Self {
Expand Down

0 comments on commit 83cc443

Please sign in to comment.