From 54dbb2a1cdc696218bc8387e2055325e7118c774 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 12 Oct 2024 21:14:08 -0300 Subject: [PATCH] fix --- vlib/v/checker/str.v | 2 +- vlib/v/comptime/comptimeinfo.v | 3 +++ .../generics/generic_lambda_inference_test.v | 21 +++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/generics/generic_lambda_inference_test.v diff --git a/vlib/v/checker/str.v b/vlib/v/checker/str.v index 186fbe3145d6c5..aaa2b5615faa7f 100644 --- a/vlib/v/checker/str.v +++ b/vlib/v/checker/str.v @@ -75,7 +75,7 @@ fn (mut c Checker) string_inter_lit(mut node ast.StringInterLiteral) ast.Type { if fmt == `_` { // set default representation for type if none has been given fmt = c.get_default_fmt(ftyp, typ) if fmt == `_` { - if typ != ast.void_type { + if typ != ast.void_type && !(c.inside_lambda && typ.has_flag(.generic)) { c.error('no known default format for type `${c.table.get_type_name(ftyp)}`', node.fmt_poss[i]) } diff --git a/vlib/v/comptime/comptimeinfo.v b/vlib/v/comptime/comptimeinfo.v index 2db852f1991b89..9a029bbb433fd6 100644 --- a/vlib/v/comptime/comptimeinfo.v +++ b/vlib/v/comptime/comptimeinfo.v @@ -287,6 +287,9 @@ fn (mut ct ComptimeInfo) comptime_get_kind_var(var ast.Ident) ?ast.ComptimeForKi pub fn (mut ct ComptimeInfo) unwrap_generic_expr(expr ast.Expr, default_typ ast.Type) ast.Type { match expr { + ast.StringLiteral, ast.StringInterLiteral { + return ast.string_type + } ast.ParExpr { return ct.unwrap_generic_expr(expr.expr, default_typ) } diff --git a/vlib/v/tests/generics/generic_lambda_inference_test.v b/vlib/v/tests/generics/generic_lambda_inference_test.v new file mode 100644 index 00000000000000..4026839f23e4d7 --- /dev/null +++ b/vlib/v/tests/generics/generic_lambda_inference_test.v @@ -0,0 +1,21 @@ +const result = ['0: a', '1: b', '2: c', '3: d'] + +fn mapi[T, U](arr []T, callback fn (int, T) U) []U { + mut mapped := []U{} + for i, el in arr { + mapped << callback(i, el) + } + return mapped +} + +fn test_main() { + arr := [`a`, `b`, `c`, `d`] + arr_1 := mapi(arr, |i, e| '${i}: ${e}') + assert arr_1 == result + arr_2 := mapi[rune, string](arr, |i, e| '${i}: ${e}') + assert arr_2 == result + arr_3 := mapi(arr, fn (i int, e rune) string { + return '${i}: ${e}' + }) + assert arr_3 == result +}