Repository navigation
Std hygiene: fix Optional/Result unwrap UB, align READMEs with reality - #6
Conversation
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]>
| - `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`) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.agsoOptional.unwrap(),Result.unwrap(), andResult.get_error()emit an error tostderrand terminate with SIGABRT when called on the wrong variant. - Updated
tests/optional_test.agto stop asserting UB-driven behavior and document why aborting paths aren’t tested in-process. - Updated
README.mdandexamples/README.mdto 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.
| /// Terminates the process with SIGABRT, like C `abort()`. | ||
| void __optional_abort() { | ||
| raise(6); // 6 = SIGABRT | ||
| } |
| - `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`) |
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]>
Std hygiene: fix Optional/Result unwrap UB, align READMEs with reality
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, andResult.get_error()on an ok value previously executedreturn self.thing;/return self.value;/return self.error;unconditionally, returning uninitialized memory.fprintf(stderr, ...)) and terminate with SIGABRT, following thestd/map.agabort-with-dummy-return pattern.unwrap_or,is_some/is_none,success/failedare untouched.__optional_abort()helper overraise(6 /* SIGABRT */)rather than avoid 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 declareabort(). Declaring it here would have broken every program importingstd.optionalalongsidestd.memorstd.map. (Verified empirically; see notes below.)tests/optional_test.ag
ok_result.get_error() == 0, which relied on the old UB (uninitialized memory happening to be zero).README.md
docs/entry now reflects its actual contents (docs/runtime-migration.md).examples/README.md
const_inference.ag,calculator.ag,macros.ag,comptime.ag,math.ag).ownership.ag,defer_cleanup.ag,associated_fn_values.ag,regression_demo.ag.Verification
cargo build -p agcclean;cargo test -p agc: 220 passed, 0 failed.tests/optional_test.ag: 37/37, exit 0.sys_exit(42)test — identical on unmodified main).std.mem+std.optionalandstd.map+std.optionalcompile and run.Notes for maintainers (pre-existing issues found, not fixed here)
import std.mem;+import std.map;in one program already fails on main withambiguous overload for 'abort'(both declare the extern). A typeck-level dedupe of identical extern declarations would fix this class of breakage.#[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), yieldingunknown function. It only works for.agmmodule imports. Also, attributes are rejected insideextern "C" { ... }blocks (parse error), only on standalone declarations.docs/runtime-migration.mdis 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, andResult.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 viaraise(6)). The PR also correctsexamples/README.md(removes five phantom entries, adds four real ones) and commitsdocs/runtime-migration.md, which the README now correctly references.std/optional.agadds a guarded check before each field access and a dedicated abort helper that usesraiseinstead ofabort()to avoid the type-checker ambiguity caused by multiple stdlib modules each declaring their ownabortextern.tests/optional_test.agremoves theget_error()call that relied on the UB returning zero and documents why the abort paths cannot be exercised in-process.docs/runtime-migration.mdis added (196 lines): full wave-based plan for rewritingsilver_runtimein 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
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%%{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:#fffReviews (4): Last reviewed commit: "Merge origin/main into std-hygiene-optio..." | Re-trigger Greptile