From d2fdbaf67e93d69072921680af4bfe9e91cc1def Mon Sep 17 00:00:00 2001 From: shove Date: Tue, 12 Dec 2023 17:28:03 +0800 Subject: [PATCH] parser: fix an error message when initializing a struct from another module(fix #20141) (#20158) --- vlib/v/parser/parser.v | 19 +++++++++++++++++++ .../struct_init_from_another_mod_err.out | 6 ++++++ .../tests/struct_init_from_another_mod_err.vv | 7 +++++++ 3 files changed, 32 insertions(+) create mode 100644 vlib/v/parser/tests/struct_init_from_another_mod_err.out create mode 100644 vlib/v/parser/tests/struct_init_from_another_mod_err.vv diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index 393cae437..e7cd5360e 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -2926,7 +2926,26 @@ fn (mut p Parser) name_expr() ast.Expr { return node } else if is_option && p.tok.kind == .lsbr { return p.array_init(is_option) + } else if !known_var && language == .v && p.peek_tok.kind == .dot && !p.pref.is_fmt { + peek_tok2 := p.peek_token(2) + peek_tok3 := p.peek_token(3) + mod = p.tok.lit + mut n := -1 + for p.peek_token(n).kind == .dot && p.peek_token(n - 1).kind == .name { + mod = p.peek_token(n - 1).lit + '.' + mod + n -= 2 + } + if peek_tok2.kind == .name && peek_tok2.lit.len > 0 && peek_tok2.lit[0].is_capital() + && peek_tok3.kind == .lcbr + && (mod.len > p.tok.lit.len || !p.known_import(p.tok.lit)) { + mut msg := 'unknown module `${mod}`' + if mod.len > p.tok.lit.len && p.known_import(p.tok.lit) { + msg += '; did you mean `${p.tok.lit}`?' + } + p.error_with_pos(msg, p.tok.pos()) + } } + ident := p.ident(language) node = ident p.add_defer_var(ident) diff --git a/vlib/v/parser/tests/struct_init_from_another_mod_err.out b/vlib/v/parser/tests/struct_init_from_another_mod_err.out new file mode 100644 index 000000000..f771961f6 --- /dev/null +++ b/vlib/v/parser/tests/struct_init_from_another_mod_err.out @@ -0,0 +1,6 @@ +vlib/v/parser/tests/struct_init_from_another_mod_err.vv:6:27: error: unknown module `rand.config`; did you mean `config`? + 4 | fn main() { + 5 | mut a := [0, 1, 2] + 6 | rand.shuffle(mut a, rand.config.ShuffleConfigStruct{})! + | ~~~~~~ + 7 | } diff --git a/vlib/v/parser/tests/struct_init_from_another_mod_err.vv b/vlib/v/parser/tests/struct_init_from_another_mod_err.vv new file mode 100644 index 000000000..d836b513c --- /dev/null +++ b/vlib/v/parser/tests/struct_init_from_another_mod_err.vv @@ -0,0 +1,7 @@ +import rand +import rand.config + +fn main() { + mut a := [0, 1, 2] + rand.shuffle(mut a, rand.config.ShuffleConfigStruct{})! +} -- 2.39.5