Skip to content

lib: hide non-pub struct fields across libraries - #215

Merged
dslsdzc merged 1 commit into
developfrom
lib-hidden-fields
Oct 26, 2026
Merged

dslsdzc merged 1 commit into
developfrom
lib-hidden-fields

Conversation

@dslsdzc

@dslsdzc dslsdzc commented Oct 26, 2026

Copy link
Copy Markdown
Owner

问题

非 pub 结构体的类型名和方法已经跨库隐藏,但字段没有:

// src/stdlib fixture
struct HiddenBox:
    x: int

fn makeHiddenBox() -> HiddenBox, pub:
    return HiddenBox { x = 42 }
// user
import fixture
fn main() -> int:
    h := makeHiddenBox()
    return h.x          // 之前 rc=0:隐藏类型的布局泄漏

h.x = 5 同样可写。原因:EXPR_FIELD 解析到 struct 后直接返回字段类型,没有检查结构体类型符号的可见性。

修法

  • EXPR_FIELD 在命名 struct 分支用 find_gsym(struct_ni) 取当前库可见的类型符号;不可见时报 N03 Undefined field 并返回错误类型。
  • 不检查 g_cur_lib < 0 的声明期解析;同库访问、pub struct、@core -> @std 均不变。
  • 字段读写都走 infer_expr(target),所以读和写一起收口。

判据

test_pub_visibility 的跨库 fixture 增加:

  • HiddenBox + pub fn makeHiddenBox() -> HiddenBox:h.x 读 → N03,h.x = 5 写 → N03;
  • ShownBox, pub + pub fn makeShownBox() -> ShownBox:s.y 可读,运行返回预期值。

边界

  • 非 pub 类型整体不可见,字段随之不可见。
  • pub 类型的字段当前整体公开;逐字段 pub 标签尚未实现,这是需要裁决的语言设计项(默认公开 vs 默认私有 + 逐字段导出)。文档已按现状写明。

selfhost-tests / bootstrap-tests / check 全绿;canary 5/5 不变。

A hidden struct can still flow through a pub function return value. Field
access did not consult the struct type visibility, so h.x was readable and
writable outside the owning library even though the type name and its methods
were hidden.

EXPR_FIELD now resolves the struct type symbol with find_gsym under the current
library and reports N03 Undefined field when the type is not visible. Same
library, pub structs and @core -> @std reads are unchanged.

Tests extend the cross-library fixture with hidden/shown structs and pub
factory functions: hidden field read/write -> N03, pub field read -> runs.
Docs state that fields currently follow the struct type visibility; per-field
pub is still an open language decision.

selfhost/bootstrap/check green; canary 5/5 unchanged.
@dslsdzc
dslsdzc merged commit eb926f8 into develop Oct 26, 2026
4 checks passed
@dslsdzc
dslsdzc deleted the lib-hidden-fields branch October 26, 2026 23:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant