Skip to content

Union safety rules: single initializer, unsafe non-last-written reads (§16.4) #542

Closed

Description

@ehartford

Summary

Enforce union safety rules from §16.4: construction must initialize exactly one field, and reading a union field other than the last written field requires unsafe. Layout exists; semantic state and diagnostics are the missing piece.

Spec

§16.4 says unions have the size of their largest field and all fields share offset 0 (docs/with-specification.md:8511). Reading a field that was not last written requires unsafe, writing any field is safe, and construction requires exactly one field initializer (docs/with-specification.md:8512).

Current state

The parser supports union type declarations (src/Parser.w:1339). Sema field access treats TY_STRUCT and generic structs uniformly and simply returns struct_field_type (src/SemaCheck.w:5522). Sema.check_struct_literal checks field expressions and default/missing fields only for TypeDeclKind.Struct; it does not reject multi-field union literals (src/SemaCheck.w:5884). Layout/codegen already model union storage: field offsets are 0 in layout (src/TypeLayout.w:101), union size is max field size rounded to max alignment (src/TypeLayout.w:178), and codegen stores union aggregate initializers at offset 0 (src/CodegenDispatch.w:3060). The gap is semantic validation and last-written tracking.

Implementation plan

  1. Add Sema.type_is_union(tid) / Sema.type_decl_sub_kind_for_type(tid) helper using type_layout_struct_sub_kind so Sema can distinguish unions from ordinary structs.
  2. In Sema.check_struct_literal, if the named type is a union, require field_count == 1 and reject positional/missing/default semantics with union literal requires exactly one named field initializer.
  3. Track definite last-written union fields for local union variables in Sema. Minimum v1: a union literal Value { i: 1 } initializes last-written field i; assignment to v.i = ... updates it; field reads of a different field require unsafe.
  4. If control flow makes the last-written field unknown, require unsafe for reads unless the read field is definitely last written on all incoming paths. Start conservative: unknown means unsafe required.
  5. Add the unsafe check in Sema.check_field_access for union field reads. Field writes remain safe; make sure place checking can distinguish read vs assignment target. If that distinction is awkward, add a field-read validation pass over expressions and skip assignment LHS.
  6. Do not change union layout/codegen unless tests reveal layout bugs.

Test plan

Add test/compile_errors/err_union_literal_two_fields.w for Value { i: 1, f: 1.0 }. Add err_union_read_not_last_written_requires_unsafe.w. Add behavior tests for reading the initialized field safely, writing a new field safely then reading that field safely, and reading a different field inside unsafe. Add a conservative control-flow test where different branches write different union fields and a later read requires unsafe.

Acceptance criteria

  • Union literals with zero, positional, or multiple initializers fail.
  • Safe reads of the definitely last-written field compile.
  • Safe reads of other/unknown union fields fail and unsafe reads compile.
  • Union writes remain safe.
  • Existing C union import/layout tests continue to pass.
  • with build && with build :fixpoint && with build :test pass.

Dependencies

Overlaps #500 for union layout/import coverage.

Traceability

From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 16.4.1.10, 16.4.1.8.

Activity

  1. ehartford commented on Jun 16, 2026

    @ehartford
    ContributorAuthor

    Implemented in 7eebe9a. Union literals must initialize exactly one named field (zero/positional/multiple are errors). Local union variables track their last-written field (set by a union literal initializer or a direct field assignment); reading a different field — or any field after control flow makes the last-written unknown — requires unsafe, while writing any field stays safe. Tracking is per-function-body, deterministic, and only applies to literal-initialized/assigned locals, so raw/uninitialized union access (e.g. the embedded regex class_bits_storage) is never flagged. Tests: spec_ss16_4_union_safety, err_union_literal_two_fields, err_union_read_not_last_written_requires_unsafe, err_union_cf_read_requires_unsafe. build + fixpoint + compile-error/spec/behavior suites pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions