Commit Graph

31 Commits

Author SHA1 Message Date
agra
56f6ae3681 ffi 1.33: uikit.sx final sweep — Phase 1D for uikit.sx complete
Six remaining dispatch clusters migrated in one pass:
- `uikit_setup_renderbuffer`: `renderbufferStorage:fromDrawable:` (BOOL).
- `uikit_present_renderbuffer`: `presentRenderbuffer:` (BOOL, every frame).
- `uikit_gl_view_tick`: `targetTimestamp` and `duration` reads (f64,
  every frame — three call sites total across the keyboard-anim path
  and the frame-closure path).
- `uikit_compute_layer_pixel_size`: `bounds` (CGRect HFA).
- `uikit_touch_location`: `locationInView:` (CGPoint HFA — first
  standalone `#objc_call(CGPoint)` exercise, structurally identical to
  the 2×f64 NSPoint already verified by ffi-objc-call-05).
- `uikit_first_touch`: `anyObject` (*void).

Net -15 lines. uikit.sx is now 839 lines — Phase 1D started at 937,
so this is -98 cumulative across the migration. Zero `xx objc_msgSend`
typed casts left in the file.

iOS-sim chess regression smoke: launched chess, tapped a black pawn
through the Simulator window, watched the move (d7→d5) play, then a
second tap played d5→d4. The render loop, touch handlers, layout
math, and the BOOL-returning EAGL presentation calls are all on the
exercised path, so this is the strongest runtime verification any
Phase 1D commit has had so far.

22 `sel_registerName` calls remain in the file, all legitimate:
- `class_addMethod` IMP registrations (runtime class build-out).
- SEL-as-arg to dispatch selectors that take a SEL value
  (`addObserver:selector:name:object:`,
  `displayLinkWithTarget:selector:`). A future `#objc_selector("foo")`
  literal would replace these, but it's not part of Phase 1.
2026-05-19 21:06:53 +03:00
agra
e1d300c661 ffi 1.32: uikit_keyboard_will_change_frame via #objc_call
The keyboard notification callback. First standalone exercises of
`#objc_call(CGRect)` (HFA — structurally equivalent to UIEdgeInsets,
already verified by 1.25 and ffi-objc-call-07) and `#objc_call(u64)`
(LLVM-equivalent to s64; ffi-objc-call-04 already locks in the i64
return path).

Migrates:
- `userInfo` (*void)
- `objectForKey:` with NSString arg (*void)
- `CGRectValue` (CGRect HFA)
- `doubleValue` (f64)
- `unsignedLongValue` (u64)
- `screen` (*void)
- `bounds` (CGRect HFA)

Net -14 lines. uikit.sx now 854 lines (-83 cumulative across Phase 1D).

iOS-sim chess regression smoke: launch is clean; the callback is
registered through cluster 1.30's notification-center wiring and the
function lowers without IR-verifier complaints. The callback body
itself isn't exercised at runtime by chess startup (the game doesn't
open the soft keyboard) — runtime verification of this specific
function is transitive via the other clusters that exercise the same
call shapes.
2026-05-19 21:00:46 +03:00
agra
b3558c3274 ffi 1.31: uikit_scene_will_connect_ios via #objc_call
The biggest Phase 1D cluster: the iOS scene-lifecycle entry that runs
at every launch. UIWindow alloc/init, UIViewController alloc/init, GL
view alloc/init/install, root-view-controller wiring, layer access +
setOpaque:, EAGL drawable-properties dictionary build,
screen/nativeScale DPI scaling, makeKeyAndVisible, UITextField subview
install, CADisplayLink construct + addToRunLoop. Every return shape
this file uses (void, *void, f64) and every arg shape (BOOL via `xx
0`/`xx 1`, multi-arg selectors `displayLinkWithTarget:selector:` and
`setObject:forKey:`) is exercised by this single launch.

Net -44 lines on this commit (104 → 60). Also drops a stale
`EAGLContext := objc_getClass(...)` decl that wasn't referenced inside
this function — EAGL context creation lives in uikit_create_gl_context
(already migrated in 1.29). uikit.sx is now 868 lines (-69 cumulative
across Phase 1D).

iOS-sim chess regression smoke: app launches cleanly, board renders
with status-bar clearance, sharp DPI scaling, compositor working,
display-link tick driving frames. Every part of the migrated function
is on the launch path and all of it succeeds.
2026-05-19 20:57:09 +03:00
agra
ee53348ce0 ffi 1.28 follow-up: keyboard BOOL returns use #objc_call(bool)
Apple documents `-becomeFirstResponder` and `-resignFirstResponder` as
returning `BOOL`. The pre-`#objc_call` cast pattern in this file used
`u8` because BOOL is ABI-equivalent to a 1-byte unsigned integer on
both i386 (signed char) and arm64 (`bool`). The initial 1.28
migration carried that `u8` typing forward without question; switching
to `bool` matches the documented API and aligns with the BOOL→bool
mapping called out in PLAN-FFI.md Phase 3.

First standalone exercise of `#objc_call(bool)`. The lowering is
identical to `#objc_call(u8)` at the ABI layer (single byte in `w0`
on AAPCS64), but the source-level type is now meaningful.
2026-05-19 19:39:56 +03:00
agra
65643fb0ed ffi 1.28-1.30: batch uikit migrations
Three Phase 1D clusters in one commit (user opted for less iOS-sim
verification between each).

1.28 — `show_keyboard` / `hide_keyboard` use `#objc_call(u8)` against
`becomeFirstResponder` / `resignFirstResponder`. Compile-only; chess
startup doesn't reach the keyboard path, so the runtime side of this
cluster is a verification gap to backfill at the end of Phase 1D.

1.29 — `uikit_create_gl_context` migrates `alloc` / `initWithAPI:` /
`setCurrentContext:` and folds in the same `mainScreen.nativeScale`
read shape already migrated in 1.27. EAGL context creation runs on
launch, so this cluster IS runtime-exercised.

1.30 — `uikit_subscribe_keyboard_notifications` migrates the
`defaultCenter` + `addObserver:selector:name:object:` pair. First
standalone exercise of a 4-keyword selector through `#objc_call`.
Notification-center wiring runs at launch, so runtime-exercised.

Net -23 lines across the file.

iOS-sim chess regression smoke: app launches cleanly into a fresh
board state. Status-bar clearance, sharp rendering, and asset loading
all good — confirming clusters 1.25–1.27 still work alongside the new
ones.
2026-05-19 19:37:43 +03:00
agra
4844f57968 ffi 1.27: uikit_read_screen_scale via #objc_call
Third Phase 1D cluster. `UIScreen.mainScreen.nativeScale` chain reads
through `#objc_call(*void)` + `#objc_call(f64)`. First standalone
`#objc_call(f64)` exercise — `f64` returns had only been covered
indirectly by the 4×f64 UIEdgeInsets HFA path. Net -4 lines.

iOS-sim chess regression smoke: sharp text rendering + accurate touch
hit-testing both confirm `plat.dpi_scale` is being populated correctly
through the new path.
2026-05-19 19:33:52 +03:00
agra
3518d0ee26 ffi 1.26: uikit_chdir_to_bundle via #objc_call
Second Phase 1D cluster. NSBundle.mainBundle.resourcePath chain now
dispatches through `#objc_call(*void)` instead of a shared `msg_o`
typed cast — covers both class-method (`+mainBundle`) and
instance-method (`-resourcePath`) shapes through one intrinsic. Net
-3 lines.

iOS-sim chess regression smoke: app launches with all piece assets
rendered, which is the visible signal that `chdir` to the bundle's
resource path still succeeds.
2026-05-19 19:30:59 +03:00
agra
bcbf2ace22 ffi 1.25: uikit safeAreaInsets via #objc_call
First Phase 1D migration cluster. `uikit_refresh_safe_insets` reads
`safeAreaInsets` through `#objc_call(UIEdgeInsets)` instead of the
hand-typed `objc_msgSend` cast + `sel_registerName` triple, and a dead
`sel_safe_insets` selector decl in `uikit_scene_will_connect_ios` goes
away with it. Net -3 lines.

iOS-sim chess regression smoke: SxChess launches, board renders with
correct status-bar clearance — `safe_top` is populated correctly,
which is the actual ABI under test (32 B HFA returned in v0..v3).
2026-05-19 19:29:03 +03:00
agra
c08a749043 ffi 0.7: #import c { #include / #source } via stdlib-path resolution
94/94 regression tests pass (+ffi-07-c-import-block).

Companion C helper lives only at
`library/vendors/sx_ffi_resolve_test/`. Critically NOT in
`sx/vendors/` (the sx repo root) and NOT in the importing
example's directory — so the `vendors/...` paths in this
example are findable solely via the stdlib search branch
(`<exe>/../../library`, `<exe>/../library`, `<exe>/library`).

That branch is the one the JNI insets bridge needs to reach
`library/vendors/sx_android_jni/sx_android_jni.c` without
forcing chess (or any consumer) to vendor an identically-named
copy. The test pins the resolution end-to-end:
  - #include  resolves; clang parses the .h; c_import.zig
    synthesizes #foreign fn decls for `sx_ffi_resolve_test_add` /
    `_mul`.
  - #source   resolves; the .c is compiled into the build's
    object list.
  - sx calls the synthesized decls and prints results.
2026-05-19 11:51:34 +03:00
agra
4849cfb904 android: dpi_scale, scissor, JNI safe-insets, touch input
Four Android UX wins landing together; all verified end-to-end on a
Pixel 7 Pro (board fills width, info-panel text renders, status bar
inset honored, tap-to-select + tap-to-move plays 1. e4).

- AndroidPlatform.init reads density via AConfiguration_getDensity
  (app->config at offset 32) and sets dpi_scale = density / 160. The
  hardcoded 1.0 had been making every logical unit equal one physical
  pixel; ChessBoardView's 520-default size_that_fits fallback then
  rendered at ~half the framebuffer width on the device, and glyphs
  rasterized at literal 11-13 physical pixels were essentially invisible
  on a 2340-tall display.
- gles3.sx set_scissor un-stubbed; with dpi_scale right the renderer
  feeds in valid pixel bounds and the Y-flip math lands inside the
  framebuffer.
- New library/vendors/sx_android_jni/sx_android_jni.c walks
  activity -> window -> decorView -> rootWindowInsets via JNI and
  publishes the system-bar insets. safe_insets() lazy-queries the
  first call after EGL is up (decor view isn't attached at bootstrap).
- sx_android_install_input_handler sets app->onInputEvent; sx-side
  sx_android_input_event translates AMotionEvent DOWN/MOVE/UP/CANCEL
  into existing mouse_down/mouse_moved/mouse_up Events so the chess
  board's tap-to-select + ScrollView drag path Just Works. Coordinates
  divided by dpi_scale so layout-side hit tests match. poll_events
  drains its slice after returning (mirrors the SDL pattern).
- src/imports.zig now routes #import c { #source / #include } paths
  through the same chain as #import (importing dir -> CWD -> stdlib
  search paths). Lets library-owned C helpers like the JNI bridge
  live in sx/library/vendors/ without forcing consumers to vendor a
  copy. Existing CWD-relative consumer layouts (chess's vendors/...)
  still resolve first, so no regression.

86/86 regression tests pass.
2026-05-19 11:09:41 +03:00
agra
b5bf789b7b android: AAssetManager bootstrap + APK asset bundling + scissor TODO
platform/android.sx: `sx_android_bootstrap(app)` now also reads the
ANativeActivity's `assetManager` (offset 64) and `internalDataPath`
(offset 32) into module globals so consumers can route file I/O
through the APK's bundled `assets/` tree.

target.zig (`createApk`): also zips the project's `./assets/`
directory into the APK alongside `lib/<arch>/`. Resolves relative
to the user's CWD at invoke time — matches the convention chess
uses (assets/ next to main.sx).

gles3.sx: scissor is currently a no-op on Android. The renderer's
ScrollView clip_push path feeds bounds that land outside the
framebuffer (clipping everything off-screen). With scissor disabled
the chess board + pieces render correctly. TODO recorded in the
file to fix the bounds path properly.
2026-05-19 10:09:30 +03:00
agra
5c41e9c180 gpu: Gles3Gpu — GLES3 implementation of the GPU protocol
Mirror of metal.sx, talks to GLES3 via opengl.sx's runtime-loaded
fn-pointer variables. EGL bootstrap is owned by AndroidPlatform; this
module just calls `load_gl(@eglGetProcAddress)` once during `init` to
populate the pointers, then drives raw draw/state from there.

The renderer's vertex layout (12 floats: pos2/uv2/color4/params4 = 48
bytes, attribute locations 0-3) is hardcoded in a single shared VAO
the Gles3Gpu owns — `set_vertex_buffer` rebinds the active VBO against
it. `set_vertex_constants(slot=1, data, 64)` is treated as the 4x4
projection matrix; `set_texture(slot=0, ...)` binds texture unit 0 and
sets `uniform sampler2D uTex` — both match renderer.sx's shader
contract.

A subtle gotcha caught + recorded in the file header: declaring the
same GL name as a `#foreign` function while opengl.sx also declares it
as an fn-pointer global silently lets the global win, and calling
through the uninitialized variable jumps to PC=0. Solution: don't
re-declare; use opengl.sx's pointers and `load_gl` them.

renderer.sx: the GPU-protocol shader-source branch now passes
(UI_VERT_SRC_ES, UI_FRAG_SRC_ES) on Android (separate vert+frag) vs.
the combined MSL library on iOS. Both gated with `inline if OS == X`.
2026-05-19 09:32:09 +03:00
agra
561ad03a7c android: Platform-owned entry bridge + .android OS enum variant
User writes BOTH `main` and a 3-line `android_main(app)` trampoline.
The library provides `sx_android_bootstrap(app)` (stashes the NDK app
pointer into a platform-owned global) and `AndroidPlatform` impl of
the Platform protocol. The library NEVER references `main` — the OS-
shape entry symbol lives in user code where the other entry symbols
already live. iOS / SDL3 keep their existing shape; only Android adds
the trampoline.

Cross-cutting bits this commit ships:

  library/modules/compiler.sx
    Add `android` variant to `OperatingSystem`.

  src/ir/lower.zig
    - injectComptimeConstants: map TargetConfig.isAndroid() → .android.
    - New Pass 4 `checkRequiredEntryPoints`: emit a clean diagnostic
      when `--target android` is requested but `android_main` isn't
      defined, instead of letting the user crash on a dlopen-time
      missing-symbol error.

  library/modules/platform/android.sx
    AndroidPlatform impl of the Platform protocol — EGL bringup on
    `APP_CMD_INIT_WINDOW`, ALooper(0) polling, dispatches the user's
    frame closure each ~16 ms tick. `sx_android_bootstrap(app)` is the
    only function exposed for the entry trampoline.

  examples/99-android-egl-clear.sx
    Rewritten to use the new pattern: minimum `main` + `android_main`
    pair, AndroidPlatform-driven render loop. Doubles as the usage
    reference users hand off to the compiler diagnostic.

Verified on Pixel 7 Pro: purple clear-color frame, periodic
`rendered 60 frames` logcat lines. iOS-sim chess + 86/86 regression
tests pass.
2026-05-19 00:23:33 +03:00
agra
f41a121a29 gpu: destroy_shader/buffer/texture on the GPU protocol (issue-0029)
Three new method signatures on the GPU protocol. Metal backend sends
`release` to the MTLTexture/Buffer/RenderPipelineState and nulls the
slot in its backing List so the handle becomes inert; handles are not
re-used. glyph_cache.grow() now destroys the old atlas before
allocating its replacement, eliminating the per-grow leak the file's
comment had been flagging since Session 62.
2026-05-18 23:09:32 +03:00
agra
79419b99bd issue-0028: ?Protocol = null sentinel-shaped optional protocols
Protocol structs registered via registerProtocolDecl carry a new
is_protocol flag; the ?T paths in sizeOf/typeSizeBytes/toLLVMType
recognise it and lay out ?Protocol as the protocol struct itself
(ctx == null IS the "none" state), matching how ?Closure / ?*T are
sentinel-shaped — no extra storage.

Method dispatch on ?Protocol auto-unwraps in lowerCall's field-access
path; the unwrap is structurally a no-op so we just rebind obj_ty to
the payload type. resolveCallParamTypes extended for optional-protocol
receivers so enum-literal args (gpu.create_texture(.r8, ...)) get the
right target_type and don't silently collapse to tag=0 : s32 — same
issue-0031-class bug closed in Session 66, one type-system layer
deeper.

Library: UIRenderer / UIPipeline / GlyphCache migrated from the verbose
gpu: GPU = ---; has_gpu: bool pattern to gpu: ?GPU = null. set_gpu no
longer maintains a parallel bool flag.

Bundled: dock.sx threads delta_time as a struct field rather than via
a global pointer (cleanup unrelated to issue-0028, committed alongside).

Verified: 85/85 regression tests pass; iOS-sim chess + macOS chess
both render correctly post-migration.
2026-05-18 18:32:55 +03:00
agra
f9ecf9d00e iOS lock step keyboard + metal 2026-05-18 17:40:10 +03:00
agra
b43472e6ab ui: text shader uses raw atlas coverage (no SDF smoothstep)
Two small cleanups in the Metal text path on top of the buffer-offset
fix from cc71d95:

- Drop the SDF-style `smoothstep(0.5 ± ew, alpha)` from the text mode
  branch in UI_MSL_SRC. The glyph atlas stores alpha coverage straight
  from stbtt_MakeGlyphBitmap, not signed distance, so the smoothstep
  was thinning anti-aliased strokes by mapping mid-coverage values
  (0.3–0.7) toward 0/1. Use the sampled value directly as alpha.

- Drop the 16-byte alignment pad on `mtl_buf_offset` in `flush()`. Each
  batch's upload_size is already a multiple of UI_VERTEX_BYTES (48), so
  the running offset stays vertex-aligned without the extra rounding.

- After `font.shape_text` + `font.flush` in `render_text`, re-bind
  `font.texture_id`. If the atlas grew during shaping, the GPU texture
  handle changed; without this rebind the next flush samples the old
  (smaller) atlas which doesn't have the newly-rasterized glyphs.

- Use explicit s64-pointer arithmetic in `metal_update_buffer_at_ios`
  so a future regression in `[*]u8` indexing can't quietly miscompile
  the per-flush write offset.

Text at small sizes still renders dim on dark backgrounds — most glyph
pixels sit in 0.1–0.5 coverage and the linear blend doesn't push them
to bright values — tracked separately as the faint-text follow-up.
2026-05-18 10:26:31 +03:00
agra
cc71d9591d ui: per-flush byte-offset on Metal vertex buffer fixes chess board
UIRenderer.flush wrote to mtl_vbuf at byte offset 0 on every flush.
Metal records draw commands but reads the buffer at GPU execution time,
so a frame with multiple flushes ended up rendering whatever the LAST
writer left in the buffer for every draw. Chess UI hit this hard:
each of the 32 pieces in the initial position triggers two bind_texture
flushes (atlas -> pieces -> atlas), so ~64 mid-frame flushes silently
rendered the final info-panel batch over the board and the sprites.

New GPU protocol method update_buffer_at(buf, data, size, byte_offset);
Metal impl writes at offset via [*]u8 arithmetic on [buf contents].
UIRenderer tracks mtl_buf_offset (reset in begin, advanced per flush,
aligned to 16B, wraps on overflow) and draws each batch with
vertex_off = byte_off / UI_VERTEX_BYTES. Metal buffer over-allocated
4x the per-flush max (~3 MB) for headroom. GL path untouched —
glBufferData already orphans the storage.

71/71 regression tests pass. Metal-clear example, macOS GL chess, and
WASM chess all still build.
2026-05-18 09:19:21 +03:00
agra
3622993311 ui: chess UI renders on iOS sim via Metal (scene lifecycle + alias fix)
Four root causes for "chess UI shows white screen" — all fixed:

1. Hybrid legacy-app + scene-API path on iOS 26. Without
   UIApplicationSceneManifest in the Info.plist, iOS 26 booted us in
   [rb-legacy] mode and -[UIApplication connectedScenes] returned an
   empty set. didFinishLaunching's window-setup code bailed at "no scene"
   and the UIWindow never appeared on screen. Fix: emit the manifest in
   buildInfoPlist (src/target.zig) AND split the window/view/layer setup
   from didFinishLaunching into a new SxSceneDelegate's
   scene:willConnectToSession:options: IMP. didFinishLaunching now just
   subscribes the keyboard observer and returns YES.

2. UISceneDelegate formal protocol conformance. iOS 26 checks
   -[cls conformsToProtocol:@protocol(UISceneDelegate)] before
   instantiating the scene delegate; without it the runtime logs
   "SxSceneDelegate does not conform to the UISceneDelegate protocol"
   and silently uses a default delegate that does nothing. Fix:
   look up UISceneDelegate + UIWindowSceneDelegate via objc_getProtocol
   and class_addProtocol BEFORE objc_registerClassPair. The protocol
   metadata is present at link time (unlike UIApplicationDelegate per
   the long-standing legacy note in CHECKPOINT).

3. Protocol method return types via type aliases lowered as void.
   The GPU protocol declares `create_shader(...) -> ShaderHandle` where
   `ShaderHandle :: u32`. The protocol-decl lowering at lower.zig:7547
   passed the return AST node through type_bridge.resolveAstType which
   doesn't know about the type_alias_map. resolveTypeName fell through
   to its "assume named struct" branch and registered ShaderHandle as
   an empty struct ({ }). LLVM IR for the protocol call_indirect then
   read `call {} %fn_ptr(...)` — return value discarded; the
   subsequent abi.coerce load from a zero-init'd alloca yielded 0.
   Symptom: UIRenderer.mtl_shader = 0, set_shader sees state == null,
   the render-encoder fires draw with no pipeline state bound, GPU
   rejects the command buffer with MTLCommandBufferErrorInternal.
   Fix: at the protocol-decl method-type resolution sites in
   lower.zig, check type_alias_map BEFORE falling through to
   type_bridge.resolveAstType for both params and return type. A
   chess-side companion fix in /Users/agra/projects/game/main.sx
   (separate commit) memsets the MetalGPU struct after alloc so the
   List(*void) fields' len/cap/items aren't garbage.

After all four (this commit + memset companion in chess repo):
- 71/71 regression tests pass.
- Chess game now boots, scene-connects, ticks CADisplayLink, renders
  dark-gray clear + UI text + panel dividers every frame on iOS sim.
- Metal-clear example still renders.

Chess board + pieces visual contrast and faint-text-color are remaining
visual-polish items, not compiler/platform-setup issues.
2026-05-18 08:42:22 +03:00
agra
63565e41ff abi: pass >16B aggregates by ptr-in-next-reg (Apple ARM64 ABI) + Path B for fn-ptr casts
Three stacked compiler bugs were causing iOS-sim chess to crash inside
[MTLTexture replaceRegion:...]. Fixing them lets every replaceRegion call
site succeed (1×1 RGBA8, 1MB R8 atlas, 440×440 chess pieces).

Path B for callconv(.c) fn-pointer casts:
- FunctionInfo now carries call_conv: CallConv (TypeInfo.CallConv) so
  function-type interning distinguishes sx-CC from C-CC. Inst.zig's
  Function.CallingConvention aliases the same enum.
- Parser accepts an optional `callconv(.c)` suffix on fn-pointer type
  spellings (factored into parseOptionalCallConv() shared with parseFnDecl
  and parseLambda).
- resolveFunctionType passes the parsed CC through functionTypeCC().
- .call_indirect reads fp.call_conv == .c and applies the C-ABI
  alloca+materialize for >16B aggregate args (Path A's behaviour at .call).

Apple ARM64 ABI (drop LLVM byval):
- Side-by-side asm diff vs clang's emission for the equivalent C call site
  showed LLVM's `byval` attribute lowers Apple-arm64 byval on the stack,
  while clang passes the struct via a pointer in the next int register
  (x2 for replaceRegion:). The runtime objc_msgSend dispatch path expects
  clang's convention.
- Dropped the byval attribute from the function-signature emission and
  from both call sites (.call and .call_indirect). The materialize-into-
  alloca + pass-plain-ptr pattern stays — the call site now matches
  clang's `mov x2, sp` exactly.
- Path A's sx-to-sx case continues to work since both ends use plain ptr
  (caller does alloca+store+pass, callee loads from the ptr in prologue).

Protocol dispatch (emitProtocolDispatch):
- Untargeted `null` lowers as const_null with type .void (per
  target_type orelse .void). The "wrap-value-in-alloca-pass-pointer"
  branch alloca'd a void slot, which LLVM's IRBuilder asserts on —
  EXC_BREAKPOINT in getTypeSizeInBits, manifesting as exit 133 / SIGTRAP
  when building the chess game. Fixed by re-emitting as
  constNull(void_ptr) when arg_ty == .void && expected_ty == void_ptr.
- is_pointer_ty only recognized .pointer, so [*]T (many_pointer) was
  alloca-wrapped — the heap pixels pointer from stbi_load was stored
  into a stack slot and the slot's address was passed as the *void arg.
  Fixed by extending the check to `.pointer or .many_pointer`.

metal.sx call sites + lifecycle guards:
- msg_replace (replaceRegion:, MTLRegion = 48B) and the two setScissorRect:
  sites (MTLScissorRect = 32B) now spell their fn-pointer types with
  by-value params + callconv(.c) — the *MTLRegion/@local workaround is
  gone.
- metal_begin_frame_ios bails before nextDrawable when pixel_w/h are 0
  (drawableSize 0×0 makes nextDrawable abort via XPC).
- metal_init_ios only sets drawableSize when dims are positive.
- begin_frame's encoder/cmd_buffer failure paths now clear self.drawable
  so a partial failure doesn't leak a drawable back into the pool.

Examples + tests:
- examples/86-callconv-c-fnptr-large-aggregate.sx — new, covers Path B
  with C-CC fn-ptr cast.
- examples/87-fnptr-cast-large-aggregate.sx — renamed from issue-0025.sx,
  covers Path B with default sx-CC (the negative case).
- examples/85-cc-c-large-aggregate.sx — from Session 60, covers Path A.
- examples/issue-0014.sx, issue-0024.sx, issue-0025.sx — removed
  (resolved earlier this work).

71 regression tests pass, 0 failed. Chess game builds clean for iOS sim
and reaches its frame loop without aborting. Runtime: chess UI still
doesn't render — remaining issue is in the UIKit lifecycle / CAMetalLayer
setup (legacy-app vs scene-API hybrid), not a compiler bug. See
current/CHECKPOINT.md "Next step" for the diagnosis + options.
2026-05-18 00:11:23 +03:00
agra
a1647eab9b metal: pause step 3b pending sx-side fixes (filed 0024-0030)
Step 3b code is wired across UIRenderer + GlyphCache + UIPipeline +
chess game (gpu_mode = .metal on iOS, MetalGPU bound via the GPU
protocol). macOS GL chess, iOS-sim GLES chess, and iOS-sim Metal
triangle (63-metal-clear.sx) all still render.

iOS-sim Metal chess crashes inside replaceRegion uploading the 1MB
font atlas. Bisecting that crash exposed several sx-language issues
where mid-bisect tracers (NSLog inside if/else branch bodies) didn't
produce output, blocking further investigation.

Filing each finding as examples/issue-NNNN.sx rather than working
around piecemeal:

Bugs:
- 0024 NSLog/foreign-call inside if/else body not producing output
- 0025 C-ABI param coercion incomplete for composites >16B
       (combined direct-call abiCoerceParamType TODO + call_indirect
        path that doesn't apply C-ABI coercion at all)
- 0026 replaceRegion 1MB upload crash (likely downstream of 0025)

Features needed for step 4 + cleanup:
- 0027 Obj-C block bridge (^{...}) for animateWithDuration:
- 0028 Optional protocol box (?GPU = null) replaces T = ---; has_T: bool
- 0029 destroy_texture/buffer/shader on GPU protocol
- 0030 extern cross-file globals

Library-side: renderer.sx + glyph_cache.sx + pipeline.sx gain a
`gpu: GPU = ---; has_gpu: bool` field pair + branches that route every
GL touchpoint through the protocol when has_gpu. glyph_cache.init
saves/restores those fields around its memset. pipeline.set_gpu()
propagates to renderer + font. Renderer's MSL shader source added as
UI_MSL_SRC using packed_float2/packed_float4 to keep the 12-float
interleaved vertex layout tight (48 bytes).

metal.sx: dual-phase init (init(null, 0, 0) for eager device+queue,
re-init with the layer once UIKit installs the SxMetalView).
setStorageMode:.shared on every texture descriptor to ensure CPU-
writable atlas pixels on Apple Silicon iOS-sim.

Regression suite: 68 passing, 0 failed. WASM chess build currently
broken under step 3b state (silent compiler crash); documented in
CHECKPOINT.md, likely fallout from one of the filed issues (probably
0028 — the verbose protocol-box pattern). Step 3b resumes after
0024-0030 land.
2026-05-17 21:17:17 +03:00
agra
a938c4f900 metal: GPU protocol + MetalGPU renders MSL triangle on iOS
Phase 8 step 3a of the Metal renderer port:

- New library/modules/gpu/ with types.sx (handles + ClearColor +
  TextureFormat enum), api.sx (GPU :: protocol { ... } covering the
  lifecycle / per-frame / resource / per-draw surface), and metal.sx
  (MetalGPU backend implementing the protocol against CAMetalLayer).
  Resource handles are 1-based indices into backend List(*void) tables.
  MTL aggregates >16 bytes (MTLRegion, MTLScissorRect) pass via *T to
  match arm64 Apple's indirect-by-reference ABI; MTLClearColor + CGSize
  go through the HFA path as direct fn-pointer casts on objc_msgSend.

- UIKitPlatform got a gpu_mode: GpuMode toggle + sibling SxMetalView
  class registration. In metal mode init skips EAGL context, the
  did_finish_launching IMP skips the EAGL drawable-properties dict,
  layoutSubviews reads the layer's bounds * dpi_scale into pixel_w/h
  instead of allocating a GL renderbuffer, and end_frame is a no-op
  (the MetalGPU owns its own present).

- examples/63-metal-clear.sx verifies the pipeline end-to-end on iOS
  sim — compiles a pass-through MSL shader (packed_float2/packed_float4
  to avoid alignment padding), uploads 3 vertices, draws a colored
  triangle on a dark-blue clear.

Compiler fixes (filed-and-fixed in this branch):

- inline if X { return E; } followed by a fall-through final expression
  no longer emits two terminators into the same basic block. Verified
  by examples/83-inline-if-return-fallthrough.sx.

- Top-level type alias Name :: u32; now resolves correctly as the type
  annotation on a global variable (was treated as ptr {}, breaking
  comparisons + initializers). Verified by examples/84-global-type-alias.sx.

Issue->feature promotion:

- 16 historical examples/issue-NNNN.sx repros now confirmed-fixed and
  renamed to focused feature names (67-82). Each gains a
  tests/expected/*.txt + .exit pair so the regression suite covers them.

- 5 stale issue repros deleted (subsumed by broader tests).

Regression suite: 68 passing, 0 failed. macOS chess builds + runs; wasm
chess builds; iOS sim GLES chess still renders the full board; iOS sim
Metal demo renders the triangle.
2026-05-17 19:36:37 +03:00
agra
2ff24e29cc platform: snap keyboard inset (lockstep deferred to Metal renderer)
Walked back the manual-interpolation + CABasicAnimation+presentationLayer
attempts at lockstep keyboard inset. Both leave a visible frame of lag
because the lockstep problem is structural, not implementation-detail:

  - GL renderbuffer content is baked at presentRenderbuffer() time.
  - The CoreAnimation compositor can interpolate the *position* of a
    CALayer per-vsync but cannot reach into our renderbuffer's pixels.
  - The GPU pipeline (CADisplayLink → command build → present →
    compositor → display) is 2-3 frames deep on iOS GLES, so even
    `targetTimestamp`-based prediction is one to two frames short.

The architectural escape that doesn't move the GL view (rejected for
edge cases) is to give CoreAnimation a renderable handle it can sync
on. That means **Metal**:

  - CAMetalLayer + MTLDrawable.presentAtTime(_:) caps the pipeline at
    exactly one frame.
  - With targetTimestamp prediction + curve-accurate keyboard math,
    our drawable lands at the same vsync as UIKit's keyboard.
  - Renderer modernization (Metal/Vulkan/WebGPU per platform) was on
    the roadmap anyway; lockstep is the forcing function.

This commit keeps the keyboard observer + show/hide_keyboard wiring
intact and SNAPS keyboard_height when the observer fires. Behavior:
the chess board doesn't shift during the keyboard animation; it shifts
in one step when the observer fires. Less smooth than the broken
attempt but honest.

Plan for the Metal port (next):

  - library/modules/gpu/{metal,vulkan,webgpu}.sx + a `GPU` protocol
    analogous to Platform.
  - Port modules/ui/renderer.sx shaders from GLSL to MSL.
  - SxGLView becomes SxMetalView; CAEAGLLayer becomes CAMetalLayer.
  - Lockstep falls out of MTLDrawable.presentAtTime(targetTimestamp).
2026-05-17 17:46:17 +03:00
agra
1af8e1ffd5 platform: iOS safe-area insets + keyboard observer
UIKitPlatform now reads `[UIView safeAreaInsets]` (UIEdgeInsets = 32-byte
struct: top, left, bottom, right CGFloats) in begin_frame, and subscribes
to UIKeyboardWillChangeFrameNotification on NSNotificationCenter. The
chess game's build_ui pads its root by `g_safe_insets`, so the Dynamic
Island no longer overlaps the board on iPhone 17 Pro — all 8 ranks and
files are visible.

Struct returns >16 bytes (UIEdgeInsets, CGRect) go through the arm64
x8 indirect-result-pointer convention; expressing the return type on a
typed `objc_msgSend` fn-pointer cast generates the right call sequence.
Same pattern used to unwrap the keyboard's CGRect from NSValue
(UIKeyboardFrameEndUserInfoKey).

show_keyboard / hide_keyboard now drive a hidden UITextField subview as
the firstResponder source. resignFirstResponder dismisses; observer
fires with height=0 → safe_insets bottom collapses.

Deferred (next iteration): wrap the inset update in
[UIView animateWithDuration: animations:^{ ... }] to land in the same
CoreAnimation transaction as the keyboard. sx doesn't have block
syntax yet — we'd need a C shim that takes an fn-ptr and builds the
block. Today the inset snaps while the keyboard slides; the lag is
visible but the rest of the wiring is in place.

examples/66-uikit-platform.sx updated: each tap toggles the keyboard
+ advances the clear color (red→green→blue), so the observer can be
observed firing via the visible keyboard slide.
2026-05-17 17:07:33 +03:00
agra
4e27a7e6c9 platform: UIKitPlatform end-to-end — chess game runs on iOS sim
What works on iOS sim now:
- pure-UIKit boot via UIApplicationMain (no SDL3 on iOS)
- SxGLView (CAEAGLLayer) + EAGLContext(GLES3) + CADisplayLink
- GLES3 shader path in modules/ui/renderer.sx (was wasm-only; now
  wasm-OR-ios)
- UITouch -> ui.Event translation (mouse_down/moved/up) on touchesBegan/
  Moved/Ended/Cancelled. Verified by tapping the chess board: the
  expected pawn highlights and its legal moves show as green dots.
- chdir to NSBundle.mainBundle.resourcePath inside UIKitPlatform.init so
  the game's relative fopen("assets/...") calls resolve.

Required restructuring to fix four problems discovered along the way:

1. GL context + load_gl must happen BEFORE UIApplicationMain so the
   game's pipeline.init (which compiles shaders) doesn't crash on null
   function pointers. Pulled EAGLContext creation + load_gl out of
   didFinishLaunching: into UIKitPlatform.init via uikit_create_gl_context.

2. UIScreen.nativeScale returns CGFloat (=double on 64-bit Apple).
   Reading it through a `(*void, *void) -> f32` msgSend signature
   clobbers the value to 0 — the upper 32 bits of d0 land where the f32
   reads from. Replaced msg_f with msg_d returning f64 (and added
   msg_odbl for setContentScaleFactor: which takes CGFloat).

3. `xx <f64-call-result>` directly assigned to an f32 field through a
   sema path lowers as `sitofp` (integer→float) on the double — LLVM
   verification rejects it. Workaround: hoist into an `f64` local first.

4. The renderer was selecting the GLSL 330 core shader on every non-wasm
   target, including iOS GLES3 where it silently fails to compile and
   no quads render. Added OS == .ios to the GLES branch.

Game changes:
- main.sx: g_plat is now a boxed `Platform` (not concrete *SdlPlatform).
  Backend chosen per-target via `inline if OS == .ios { ... }`. The
  ESC-to-stop handling is OS-guarded (mobile apps don't quit on key
  press, and SDL_Keycode references would force-link SDL on iOS).
- build.sx: iOS no longer adds SDL3; it adds UIKit + OpenGLES +
  QuartzCore instead.
- delta_time and viewport dims are now mirrored to free globals so the
  dock subsystem (`g_dock_delta_time = @g_delta_time`) and build_ui
  layout decisions don't need a pointer through the boxed protocol.

Other:
- Added `stop()` to the Platform protocol (no-op on UIKitPlatform).
- examples/66-uikit-platform.sx updated: taps advance the clear color
  (red → green → blue) — smoke test for the touch IMP wiring.
- shutdown() on UIKitPlatform is a no-op (mobile apps don't tear down).

Outstanding for next session:
- The Dynamic Island notch overlaps the top of the board because we
  haven't read UIView.safeAreaInsets yet (CGRect/UIEdgeInsets struct
  returns require a different msgSend ABI than we currently express).
- Keyboard observer (UIKeyboardWillChangeFrameNotification + animation
  duration) — the load-bearing iOS feature.
- Real-device codesigning workflow for the new build.

Two more sx compiler bugs to file out of this work:
- xx(f64 call result) → f32 emits sitofp (problem #3 above).
- Inline `#import` inside `inline if` fails to parse (we worked around
  by importing both backends unconditionally; the unused-backend's
  Obj-C calls are gated by `inline if OS == .ios`).
2026-05-17 16:52:03 +03:00
agra
858d691181 platform: UIKit backend renders GLES3 via CAEAGLLayer + CADisplayLink
End-to-end on iOS sim: UIKitPlatform boots an SxAppDelegate, installs
an SxGLView (UIView subclass overriding +layerClass to return
CAEAGLLayer) as the root view controller's view, sets the drawable
properties (EAGLColorFormatRGBA8, non-retained backing — looked up by
dlsym so pointer-identity-checked constants match), creates an
EAGLContext (GLES3), and registers a CADisplayLink that invokes the
user's frame closure on every vsync. end_frame presents the
renderbuffer via [EAGLContext presentRenderbuffer:].

The renderbuffer is allocated lazily in -[SxGLView layoutSubviews] once
the layer has its real on-screen bounds — allocating earlier (e.g. in
didFinishLaunching) failed with INCOMPLETE_ATTACHMENT because the
SxGLView's frame was still zero at that point. Setting the SxGLView
as the VC's `view` (via setView:) lets the standard VC layout pipeline
size it to the window without us having to read CGRect struct returns
from objc_msgSend.

EAGL drawableProperties dict keys/values are dlsym'd from OpenGLES —
the framework checks them by pointer identity, so synthesized NSString
literals with the same contents don't work.

examples/66-uikit-platform.sx — runnable smoke test that cycles the
screen color (red → green → blue every 30 frames) so you can confirm
the display-link tick and present pipeline.

modules/opengl.sx gains glGenFramebuffers, glGenRenderbuffers,
glBindFramebuffer, glBindRenderbuffer, glFramebufferRenderbuffer,
glGetRenderbufferParameteriv, glCheckFramebufferStatus — needed for
the iOS GLES FBO-to-renderbuffer setup. They're wired into load_gl
so SDL and the iOS dlsym loader both pick them up.

Compiles cleanly on macOS / WASM / iOS-sim. Non-iOS targets never
reference the unresolved UIKit/QuartzCore/OpenGLES symbols because
every Obj-C touch lives inside `inline if OS == .ios`.

Game's iOS path still goes through SDL3 for now. Touch events + game
wire-up + keyboard observer = next steps.
2026-05-17 15:51:57 +03:00
agra
32da32ca66 platform: SDL3 backend (desktop + WASM) + two bug repros
- library/modules/platform/sdl3.sx: SdlPlatform impl wrapping SDL3 init,
  GL context, event pump, swap. run_frame_loop owns the loop: while loop
  on desktop, emscripten_set_main_loop on WASM. Registers an event-watch
  that re-invokes the frame closure during macOS modal resize-drag so
  content keeps rendering at the new size. safe_insets / keyboard /
  show_keyboard / hide_keyboard are no-ops (these targets have no soft
  keyboard).

Two compiler bug repros uncovered during the refactor:

- examples/issue-0020.sx: global `Foo = .{}` zero-initializes, ignoring
  struct field defaults. Local `Foo = .{}` correctly applies defaults.
  Workaround: set fields explicitly in an init method or heap-allocate
  the value.

- examples/issue-0021.sx: an enclosing function's return type bleeds
  into `xx`'s target type inside an `if-then-else` expression on the
  RHS of a struct-field assignment. The same expression in a `-> void`
  function produces the right value; in a `-> bool` function it
  silently produces 0. Bit the SX Chess game's dpi_scale calc inside
  `SdlPlatform.init` (returns bool), making all text labels render
  invisibly on retina. Workaround: hoist each `xx` cast into its own
  f32 local.

Regression gate: 50/50 examples pass, macOS chess game runs at ~2700fps
(close to the pre-refactor 2900 baseline), WASM build still emits a
working .html/.js/.wasm/.data quad.
2026-05-17 15:26:35 +03:00
agra
327c8af9b7 platform: protocol skeleton (types + api, no backend yet)
First commit of the Phase 8 platform abstraction (see current/PLATFORM_PLAN.md):

- `library/modules/platform/types.sx` — `FrameContext` (viewport_w/h,
  pixel_w/h, dpi_scale, delta_time) and `KeyboardState` (visible, height
  + `zero()`). `EdgeInsets`/`Point`/`Size` and `Event` are reused from
  `modules/ui/types.sx` / `modules/ui/events.sx`.
- `library/modules/platform/api.sx` — `Platform :: protocol { init,
  run_frame_loop, poll_events, begin_frame, end_frame, safe_insets,
  keyboard, show_keyboard, hide_keyboard, shutdown }`. Protocol bodies
  omit `self` (matches the `View`/`Allocator` convention).
- `run_frame_loop` takes `Closure()` so backends own the run loop:
  SDL drives a `while !quit`, UIKit hands it to a `CADisplayLink` tick,
  Emscripten hands it to `emscripten_set_main_loop`.

No backend yet. Regression suite still 50/50; game build still green.
2026-05-17 14:39:08 +03:00
agra
e8bd40f710 ios: framework embedding in .app + -F search paths
- `-F <dir>` CLI flag adds Apple framework search paths (parallel to `-L`).
- `TargetConfig.framework_paths` flows into the iOS link line (`-F<dir>`).
- iOS link adds `-Wl,-rpath,@executable_path/Frameworks` so embedded
  frameworks resolve at runtime.
- `createBundle` now takes the framework list; for each one it locates
  `<name>.framework` in the `-F` paths and `cp -R`s it into
  `<bundle>.app/Frameworks/`.
- `c_import.compileCToObjects` forwards `-target`/`-isysroot` to clang so
  `#c_import` works under cross-compile (was using host clang implicitly).
- iOS SDK is auto-discovered once at startup and shared by both the C
  compile and the link paths.
- `SX_DEBUG_LINK=1` prints the resolved link argv.
- `library/modules/sdl3.sx`: drop `#library "SDL3"` — linking is now
  per-target (build.sx handles `-lSDL3` on macOS, `-framework SDL3` on iOS).
2026-05-17 14:38:58 +03:00
agra
dc8529e3ea ui: port game UI framework into library/modules/ui
20 files (~3,830 lines): view protocol, layout, renderer, glyph cache,
fonts, gestures, animation, scroll, stacks, modifiers, etc.

Internal imports rewritten from "ui/..." to "modules/ui/...".
Consumers now `#import "modules/ui"` from any project; no symlink
hacks needed. Verified by compiling game/main.sx without its local
ui/ — resolves via the Phase 6 stdlib fallback.
2026-05-17 13:54:11 +03:00
agra
c027e1969b stdlib: relocate modules under library/
- examples/modules/ -> library/modules/ (top-level, no more
  symlink hacks in consumer projects)
- compiler discovers stdlib via _NSGetExecutablePath / readlink
  /proc/self/exe; searches dev layout (../../library), install
  layout (../library), and alongside-binary fallback
- SX_STDLIB_PATH env var overrides for tests / dev convenience
- SX_DEBUG_STDLIB env var dumps the discovery results
- build.zig installs library/ alongside the binary
- Compilation gains stdlib_paths field threaded through resolveImports
- 50 tests pass; consumer projects can now build from any cwd
2026-05-17 13:49:25 +03:00