checker: improve virtual C consts

This commit is contained in:
Alexander Medvednikov 2025-07-19 19:27:59 +03:00
parent 4dc9167b60
commit d87b8c2627
5 changed files with 18 additions and 6 deletions

View File

@ -34,6 +34,8 @@ mut:
sin_zero [8]char
}
const C.AF_INET u8
pub struct C.sockaddr_un {
mut:
sun_len u8

View File

@ -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

View File

@ -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)

View File

@ -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())
}

View File

@ -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
}