From d87b8c26270c618c30d0d652bc03caed535a1bc5 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sat, 19 Jul 2025 19:27:59 +0300 Subject: [PATCH] checker: improve virtual C consts --- vlib/net/address_darwin.c.v | 2 ++ vlib/v/checker/checker.v | 3 +-- vlib/v/gen/c/consts_and_globals.v | 3 +++ vlib/v/parser/parser.v | 2 +- vlib/v/tests/c_const_u8_test.v | 14 +++++++++++--- 5 files changed, 18 insertions(+), 6 deletions(-) diff --git a/vlib/net/address_darwin.c.v b/vlib/net/address_darwin.c.v index 4246325840..26e889417c 100644 --- a/vlib/net/address_darwin.c.v +++ b/vlib/net/address_darwin.c.v @@ -34,6 +34,8 @@ mut: sin_zero [8]char } +const C.AF_INET u8 + pub struct C.sockaddr_un { mut: sun_len u8 diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index f4dd3adac6..6756be23f2 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -4297,8 +4297,7 @@ fn (mut c Checker) ident(mut node ast.Ident) ast.Type { if node.name == 'C.NULL' { return ast.voidptr_type } - // TODO remove main. to avoid extra concats - if x := c.table.global_scope.find_const('main.' + node.name) { + if x := c.table.global_scope.find_const(node.name) { return x.typ } return ast.int_type diff --git a/vlib/v/gen/c/consts_and_globals.v b/vlib/v/gen/c/consts_and_globals.v index 5df83f2a5e..cf9f0042be 100644 --- a/vlib/v/gen/c/consts_and_globals.v +++ b/vlib/v/gen/c/consts_and_globals.v @@ -309,6 +309,9 @@ fn (mut g Gen) c_const_name(name string) string { } fn (mut g Gen) const_decl_init_later(mod string, name string, expr ast.Expr, typ ast.Type, surround_cbr bool) { + if name.starts_with('C__') { + return + } // Initialize more complex consts in `void _vinit/2{}` // (C doesn't allow init expressions that can't be resolved at compile time). mut styp := g.styp(typ) diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index 579d7afda3..c1edbcdb46 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -2384,7 +2384,7 @@ fn (mut p Parser) const_decl() ast.ConstDecl { p.error_with_pos('const names cannot contain uppercase letters, use snake_case instead', pos) } - full_name := p.prepend_mod(name) + full_name := if is_virtual_c_const { name } else { p.prepend_mod(name) } if p.tok.kind == .comma { p.error_with_pos('const declaration do not support multiple assign yet', p.tok.pos()) } diff --git a/vlib/v/tests/c_const_u8_test.v b/vlib/v/tests/c_const_u8_test.v index 7e9f9ce4d1..15f912a500 100644 --- a/vlib/v/tests/c_const_u8_test.v +++ b/vlib/v/tests/c_const_u8_test.v @@ -1,9 +1,17 @@ -const C.AF_INET u16 +import net -fn x(n u16) bool { +const C.AF_UNIX u16 + +fn x16(n u16) bool { + return true +} + +fn xint(n int) bool { return true } fn test_const() { - assert x(C.AF_INET) == true + assert xint(C.EOF) == true // a random libc const is int by default + + assert x16(C.AF_INET) == true // defined in V's net module }