Skip to content

Std hygiene: fix Optional/Result unwrap UB, align READMEs with reality - #6

Merged
CierCier merged 4 commits into
mainfrom
std-hygiene-optional-unwrap
Jul 20, 2026
Merged

CierCier merged 4 commits into
mainfrom
std-hygiene-optional-unwrap

Conversation

@CierCier

@CierCier CierCier commented Jul 20, 2026 •

Copy link
Copy Markdown
Owner

Wave 1, unit 7 of the runtime migration (docs/runtime-migration.md §2).

What changed

std/optional.ag — fix uninitialized-memory UB

  • Optional.unwrap() on a none value, Result.unwrap() on an err value, and Result.get_error() on an ok value previously executed return self.thing; / return self.value; / return self.error; unconditionally, returning uninitialized memory.
  • All three now print a clear message to stderr (fprintf(stderr, ...)) and terminate with SIGABRT, following the std/map.ag abort-with-dummy-return pattern.
  • Struct layouts and public signatures are unchanged; only failure behavior changed. unwrap_or, is_some/is_none, success/failed are untouched.
  • The abort is a private __optional_abort() helper over raise(6 /* SIGABRT */) rather than a void abort(); extern. Reason: the type checker reports calls as ambiguous when more than one identical extern declaration is visible, and vec/map/string/slice each already declare abort(). Declaring it here would have broken every program importing std.optional alongside std.mem or std.map. (Verified empirically; see notes below.)

tests/optional_test.ag

  • Removed the assertion ok_result.get_error() == 0, which relied on the old UB (uninitialized memory happening to be zero).
  • Documented that the aborting paths cannot be asserted in-process (no child-process spawning; suite must exit 0). All non-aborting paths remain covered: Some/None, ok/err, unwrap, unwrap_or, is_some/is_none, success/failed, get_error on err. 37/37 pass.

README.md

  • docs/ entry now reflects its actual contents (docs/runtime-migration.md).

examples/README.md

  • Removed five phantom entries (const_inference.ag, calculator.ag, macros.ag, comptime.ag, math.ag).
  • Added the four files that exist but were unlisted, with descriptions verified against the sources: ownership.ag, defer_cleanup.ag, associated_fn_values.ag, regression_demo.ag.

Verification

  • cargo build -p agc clean; cargo test -p agc: 220 passed, 0 failed.
  • tests/optional_test.ag: 37/37, exit 0.
  • Regression sweep: vec_test, map_test, str_key_map_test, memory_pentest all exit 0; syscall_test exits 42 by design (sys_exit(42) test — identical on unmodified main).
  • Abort paths manually verified with throwaway programs: all three terminate with SIGABRT (exit 134) and the message goes to stderr only.
  • Co-import checks: std.mem+std.optional and std.map+std.optional compile and run.

Notes for maintainers (pre-existing issues found, not fixed here)

  1. import std.mem; + import std.map; in one program already fails on main with ambiguous overload for 'abort' (both declare the extern). A typeck-level dedupe of identical extern declarations would fix this class of breakage.
  2. #[link_name] on a local extern declaration is effectively broken for direct calls: codegen registers the LLVM function under the link name but call sites resolve by the Silver name (agc/src/codegen/llvm_ir.rs ~4836), yielding unknown function. It only works for .agm module imports. Also, attributes are rejected inside extern "C" { ... } blocks (parse error), only on standalone declarations.
  3. docs/runtime-migration.md is currently untracked in the repo — README now references it, so it should be committed by the coordinator (intentionally left out of this PR to avoid cross-worker conflicts).

🤖 Generated with Claude Code

Greptile Summary

Fixes three uninitialized-memory bugs in std/optional.ag: Optional.unwrap() on a none value, Result.unwrap() on an err value, and Result.get_error() on an ok value previously returned whichever uninitialized struct field happened to sit in memory. All three paths now print a diagnostic to stderr and call __optional_abort() (which delivers SIGABRT via raise(6)). The PR also corrects examples/README.md (removes five phantom entries, adds four real ones) and commits docs/runtime-migration.md, which the README now correctly references.

  • std/optional.ag adds a guarded check before each field access and a dedicated abort helper that uses raise instead of abort() to avoid the type-checker ambiguity caused by multiple stdlib modules each declaring their own abort extern.
  • tests/optional_test.ag removes the get_error() call that relied on the UB returning zero and documents why the abort paths cannot be exercised in-process.
  • docs/runtime-migration.md is added (196 lines): full wave-based plan for rewriting silver_runtime in Silver, with work-unit descriptions, language gap analysis, and a per-worker verification recipe.

Confidence Score: 5/5

Safe to merge. The abort-on-misuse fix is correct, the established dummy-return pattern is followed, and the test suite removal of the UB-reliant assertion is accurate.

The changes are narrowly scoped: guard checks before field access in three methods, a single helper that delegates to raise(SIGABRT), a test that removes a UB-dependent assertion, and documentation/README corrections. The logic is straightforward, empirically verified per the PR, and the only open item (the raise extern carrying the same latent ambiguity risk as abort) is a future maintenance concern rather than a current defect.

std/optional.ag — the raise extern declaration should be kept in mind if the planned syscall layer (wave 1, unit 1) introduces its own raise declaration.

Important Files Changed

Filename Overview
std/optional.ag Core fix: adds checked guard + abort on bad variant access for Optional.unwrap, Result.unwrap, Result.get_error; introduces __optional_abort() via raise(6) to sidestep the abort() ambiguity issue; raise extern has the same latent ambiguity risk
bootstrap/include/silver/std/optional.ag Mirror of std/optional.ag with identical changes; both files are kept in sync
tests/optional_test.ag Removes UB-reliant assertion (get_error on ok returning 0); adds accurate limitation comment about untestable abort paths; non-aborting coverage is intact
examples/README.md Removes five phantom entries and adds four files that actually exist with descriptions verified against sources
docs/runtime-migration.md New file: comprehensive runtime migration plan with 12 work units across 3 waves; resolves the untracked-file concern mentioned in the README change
README.md docs/ entry updated to reference runtime-migration.md, which is now committed in this PR

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[unwrap / get_error called] --> B{Check variant flag\nself.present / self.ok}
    B -- correct variant --> C[return field value]
    B -- wrong variant --> D[fprintf to stderr\nerror message]
    D --> E[__optional_abort]
    E --> F[raise 6 / SIGABRT]
    F --> G[Process terminates\nexit 134]
    E --> H[while true — unreachable\nkeeps compiler happy]
    C --> I[Caller receives value]
    style G fill:#f66,color:#fff
    style H fill:#aaa,color:#fff
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A[unwrap / get_error called] --> B{Check variant flag\nself.present / self.ok}
    B -- correct variant --> C[return field value]
    B -- wrong variant --> D[fprintf to stderr\nerror message]
    D --> E[__optional_abort]
    E --> F[raise 6 / SIGABRT]
    F --> G[Process terminates\nexit 134]
    E --> H[while true — unreachable\nkeeps compiler happy]
    C --> I[Caller receives value]
    style G fill:#f66,color:#fff
    style H fill:#aaa,color:#fff
Loading

Reviews (4): Last reviewed commit: "Merge origin/main into std-hygiene-optio..." | Re-trigger Greptile

std/optional.ag previously returned uninitialized memory from
Optional.unwrap() on a none value, Result.unwrap() on an err value,
and Result.get_error() on an ok value. These now print a clear
message to stderr and terminate the process with SIGABRT. Struct
layouts and public signatures are unchanged.

The abort is implemented via raise(SIGABRT) in a private helper
instead of declaring the abort() extern, because the type checker
reports calls as ambiguous when multiple identical extern
declarations are visible (vec/map/string/slice already declare
abort()), which would have broken std.optional + std.mem/std.map
co-imports.

Also:
- tests/optional_test.ag: drop the assertion that relied on
  get_error() returning uninitialized (zero) memory on an ok result;
  document that aborting paths cannot be asserted in-process.
- README.md: make the docs/ entry reflect its actual contents
  (docs/runtime-migration.md).
- examples/README.md: remove five listed files that do not exist
  (const_inference, calculator, macros, comptime, math) and add the
  four that were missing (ownership, defer_cleanup,
  associated_fn_values, regression_demo).

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings July 20, 2026 15:14
Comment thread README.md
- `examples/` - sample Silver programs
- `tests/` - project test inputs and supporting material
- `docs/` - design notes and related documentation
- `docs/` - project documentation, currently the runtime migration plan (`docs/runtime-migration.md`)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 README references a file that does not exist in the repository

The updated line names docs/runtime-migration.md as the current content of docs/, but that file is untracked and the docs/ directory is entirely absent from the repository. Anyone who reads the README and looks for the file will find nothing. The PR description acknowledges this and defers the commit to a coordinator, but once this PR is merged the README will be inaccurate until that follow-up lands. Consider keeping the docs entry generic (e.g., the original wording) until the file is actually committed, or opening a tracking issue to ensure it is not forgotten.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves standard-library hygiene by making Optional/Result fail-fast instead of returning uninitialized memory on invalid unwrap/error extraction, and updates READMEs to reflect the actual repository/example contents.

Changes:

  • Updated std/optional.ag so Optional.unwrap(), Result.unwrap(), and Result.get_error() emit an error to stderr and terminate with SIGABRT when called on the wrong variant.
  • Updated tests/optional_test.ag to stop asserting UB-driven behavior and document why aborting paths aren’t tested in-process.
  • Updated README.md and examples/README.md to align documentation with the repo’s actual file set.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
std/optional.ag Adds stderr diagnostics + abort behavior to prevent uninitialized-memory returns on invalid unwrap/get_error.
tests/optional_test.ag Removes assertion that depended on UB; clarifies test limitation around process-aborting paths.
README.md Adjusts repository layout docs (currently references an untracked/nonexistent docs path).
examples/README.md Removes phantom example entries and documents the example files that actually exist.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread std/optional.ag
Comment on lines +21 to +24
/// Terminates the process with SIGABRT, like C `abort()`.
void __optional_abort() {
raise(6); // 6 = SIGABRT
}
Comment thread README.md
- `examples/` - sample Silver programs
- `tests/` - project test inputs and supporting material
- `docs/` - design notes and related documentation
- `docs/` - project documentation, currently the runtime migration plan (`docs/runtime-migration.md`)
CierCier and others added 3 commits July 20, 2026 21:38
The std-hygiene PR updated README to name this file; commit the plan so
the reference is not a dead link after merge.

Co-Authored-By: Claude Fable 5 <[email protected]>
@CierCier
CierCier merged commit 154f06a into main Jul 20, 2026
1 check passed
@CierCier
CierCier deleted the std-hygiene-optional-unwrap branch July 21, 2026 10:16
CierCier added a commit that referenced this pull request Aug 1, 2026
Std hygiene: fix Optional/Result unwrap UB, align READMEs with reality
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.

2 participants