Skip to content

Eliminate globalMobileApp — return context from main - #2

Closed
jappeace-sloth wants to merge 208 commits into
masterfrom
refactor/eliminate-global-mobileapp
Closed

jappeace-sloth wants to merge 208 commits into
masterfrom
refactor/eliminate-global-mobileapp

Conversation

@jappeace-sloth

Copy link
Copy Markdown
Owner

Summary

  • Remove the global IORef (globalMobileApp, runMobileApp, getMobileApp) and the haskellCreateContext foreign export
  • User's main now returns IO (Ptr AppContext) via startMobileApp, and the C bridge captures the return value using rts_evalIO + rts_getPtr
  • AppContext gains acViewFunction :: IORef (UserState -> IO Widget) so all state lives in the context — no globals on either side
  • Each test creates its own isolated AppContext, eliminating sequentialTestGroup and shared mutation

Changes

  • src/HaskellMobile/Types.hs — Removed globalMobileApp, runMobileApp, getMobileApp, and unsafePerformIO import
  • src/HaskellMobile/AppContext.hs — Added acViewFunction field, changed newAppContext to take MobileApp
  • src/HaskellMobile.hs — Removed haskellCreateContext foreign export, added startMobileApp, rewrote renderView/handleException/errorWidget/fireUserErrorCallback to use AppContext
  • cbits/run_main.c — Changed from rts_evalLazyIO to rts_evalIO + rts_getPtr, returns void*
  • include/HaskellMobile.h — Updated haskellRunMain signature, removed haskellCreateContext
  • cbits/jni_bridge.c — Merged haskellRunMain() + haskellCreateContext() into single g_ctx = haskellRunMain()
  • iOS/watchOS Swift bridges — Same merge
  • nix/lib.nix — Removed 3 haskellCreateContext linker symbols
  • app/Main.hs, app/MobileMain.hs — Updated to use startMobileApp
  • All 5 demo mains — Updated to return IO (Ptr AppContext)
  • test/Test.hs — Restructured: each exception handler test creates its own context, removed sequentialTestGroup, added context-independence tests
  • Readme.md — Updated architecture docs

Test plan

  • cabal build — typechecker passes, no warnings
  • cabal test — all 97 tests pass
  • grep -r 'globalMobileApp\|getMobileApp\|runMobileApp' src/ — no matches
  • grep -r 'haskellCreateContext' src/ cbits/ include/ ios/ watchos/ nix/ — no matches
  • CI passes on GitHub

🤖 Generated with Claude Code

jappeace-sloth and others added 30 commits March 15, 2026 21:43
- Renamed template.cabal to haskell-mobile.cabal with all references updated
- Renamed Template module to HaskellMobile
- Updated default.nix, shell.nix, nix/hpkgs.nix nix references
- Updated Changelog.md for v1.0.0
- Updated LICENSE and Readme.md
- Build and tests pass on GHC 9.10.3

Prompt: clone this repository git@github.com:jappeace/haskell-mobile.git, execute the steps in the readme to satisfy the template, it should be named haskell-mobile

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Satisfy template: rename to haskell-mobile
Move -threaded/-rtsopts/-with-rtsopts from common-options to exe/test
sections, as these flags are invalid for library targets and cause
errors during cross-compilation.

Add haskell.nix (armv7a branch) from input-output-hk via npins,
providing GHC 9.6 cross-compiler for aarch64-android. Create
nix/android.nix with android26 overlay (API level 26), patched
libiconv (HAVE_LANGINFO_CODESET) and libffi (fortify/static),
and projectCross-based cross-compilation.

Add ci.nix entry point for native + android builds, and an android
CI job with IOHK binary cache (cache.iog.io) for pre-built
cross-compiler artifacts.

Prompt: Implement the following plan: Add Android Cross-Compilation to haskell-mobile

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The latest nixpkgs-unstable has LLVM 19 whose compiler-rt is broken
for Android — os_version_check.c requires pthread.h which is unavailable
in the builtins-only sysroot (NixOS/nixpkgs#380604).

Switch to nixpkgs-2305 (LLVM 14) and pin haskell.nix to a known-good
revision (d0c35e75) matching simplex-chat's working configuration.
Also fix the android26 overlay to use localSystem/config instead of
system.

Verified: nix-build nix/android.nix -A lib succeeds locally, producing
aarch64-android-ghc-9.6.3 cross-compiled library.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Complete pipeline from Haskell source to installable Android APK,
all managed by Nix (no Gradle):

- Add `foreign export ccall` for haskellInit and haskellGreet in
  HaskellMobile.hs with CString marshalling
- Add c-sources: cbits/android_stubs.c for bionic libc compatibility
- Create cbits/jni_bridge.c: JNI_OnLoad/OnUnload + greet wrapper
- Create minimal Android project (manifest, layout, MainActivity.java)
- nix/shared-lib.nix: Uses haskell.nix component override with GHC
  `-shared` flag (simplex-chat approach), bakes JNI bridge object into
  single libhaskellmobile.so via -optl linker passthrough
- nix/apk.nix: Raw SDK tools pipeline (aapt2 → javac → d8 → zip →
  zipalign → apksigner) producing debug-signed APK
- Add haskellGreet FFI tests verifying CString round-trip
- ci.nix now includes apk target

Key decisions:
- GHC -shared instead of manual NDK linking (avoids -fPIC issues with
  boot libraries, GHC uses its own PIC shared boot libs)
- Single .so architecture (JNI bridge linked as object via -optl)
- No Gradle (raw SDK tools are simpler and more Nix-friendly)

Prompt: Implement the full Android APK pipeline plan

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add Android aarch64 cross-compilation via haskell.nix
Build Haskell to a single .a using GHC -staticlib on macOS aarch64,
then patch Mach-O platform tags from macOS to iOS using mac2ios
(zw3rk/mobile-core-tools). Same ISA, no cross-compilation needed.

- nix/project.nix: shared haskell.nix project definition (android + ios)
- nix/mac2ios.nix: builds mac2ios C tool from pinned mobile-core-tools
- nix/ios.nix: GHC -staticlib + mac2ios patching → libHaskellMobile.a
- include/HaskellMobile.h: C bridging header for Swift FFI
- ios/: SwiftUI app skeleton with HaskellBridge wrapper
- ci.nix: iOS target guarded by builtins.currentSystem Darwin check
- CI: macOS runner job for nix-build nix/ios.nix

Prompt: Implement the iOS build pipeline plan for haskell-mobile
Tokens: ~45k input, ~8k output

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The armv7a branch is Android-specific and has macOS build issues
(GHC 8.10.7 patching runs out of memory). Use the standard master
branch which works natively on macOS.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
nixpkgs-unstable has a bootstrap incompatibility where ghc943 is
missing from haskell.compiler. nixpkgs-2305 is the stable choice
used by both Android and native builds.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
haskell.nix tried to build GHC 9.6.3 from source on macOS aarch64 CI
runners because the IOG binary cache didn't have it. The 7GB RAM runner
OOMs when patching dll-loader-8.4.2.patch during the source build.

Since the iOS build only needs base (Foreign.C.String) and foreign
export ccall, we don't need haskell.nix's cross-compilation infra.
Replace it with a simple mkDerivation that uses nixpkgs' pre-built GHC
and compiles directly with ghc -staticlib.

Also remove the now-unused haskell.nix-master npins entry.

Prompt: Implement the plan to fix iOS CI build by replacing haskell.nix
with nixpkgs GHC. Rewrite nix/ios.nix, remove haskell.nix-master pin.
Used tokens: ~25k input, ~3k output

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add iOS build pipeline: static lib + mac2ios
Replace haskell.nix project system with direct GHC cross-compilation
via nixpkgs' pkgsCross.aarch64-android-prebuilt. This uses Google's
prebuilt NDK toolchain, avoiding the LLVM 19 compiler-rt issue and
eliminating the slow uncached GHC-from-source build that haskell.nix
required (IOG binary cache lacked the cross-compiler).

Changes:
- Rewrite nix/android.nix: use androidPkgs.haskellPackages.ghc for
  cross-GHC, compile directly with ghc -shared (same pattern as ios.nix)
- Delete nix/shared-lib.nix and nix/project.nix (haskell.nix wrappers)
- Update nix/apk.nix to import android.nix directly
- Update ci.nix: android attribute is now the derivation itself
- Remove IOG cache (cache.iog.io) from android and ios CI jobs
- Remove haskell.nix pin from npins/sources.json

First CI run will still build cross-GHC from source (slow), but
cachix will cache it for subsequent runs.

Prompt: Remove all haskell.nix usage from haskell-mobile
Tokens: input ~115k, output ~12k

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
GHC's cross-linker doesn't pick up buildInputs automatically.
Pass -optl-L flags for androidPkgs.gmp and androidPkgs.libffi
so the linker can find -lgmp (needed by GHC RTS) and -lffi.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The nix job already used CACHIX_AUTH_TOKEN but android/ios still
referenced CACHIX_SIGNING_KEY. Standardize on authToken so all
jobs push built artifacts to the jappie cachix cache.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Remove haskell.nix, use nixpkgs cross-compilation for Android
Android job now also builds the APK and uploads it as a
downloadable artifact. iOS job uploads the static library
and header. Both can be downloaded from the GitHub Actions
artifacts page.

Prompt: upload artifacts for android and ios CI jobs
Tokens: input ~150k, output ~15k

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Skip APK build and artifact uploads on PRs to save CI time.
Artifacts are only produced on pushes to master.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Upload Android APK and iOS library as CI artifacts
Add conditional IPA build pipeline to the iOS CI job:
- Stage nix-built .a/.h into ios/lib and ios/include
- Generate Xcode project via xcodegen from ios/project.yml
- Import signing certificate into temporary keychain
- xcodebuild archive + exportArchive to produce .ipa
- Upload as CI artifact alongside the static library
All IPA steps are gated on APPLE_CERTIFICATE_BASE64 secret + master branch,
so CI still works without Apple credentials (just builds the .a).

Create ios/project.yml XcodeGen spec with correct library/header search
paths and GHC RTS linker flags.

Update .gitignore for generated xcodeproj and staging directories.

Rewrite Readme.md with build instructions for native, Android APK,
iOS static library, and iOS app (local dev with xcodegen), plus CI
overview and signing secrets documentation.

Prompt: Implement the plan for iOS IPA build in CI + Readme update
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add iOS IPA build to CI with XcodeGen
Introduce a LifecycleEvent ADT (Create/Start/Resume/Pause/Stop/Destroy/LowMemory)
with a global IORef-based callback dispatch. Platform bridges forward lifecycle
transitions from Android Activity methods and iOS ScenePhase changes to Haskell
via a single haskellOnLifecycle FFI export.

New module HaskellMobile.Lifecycle with int conversion, callback registration,
and foreign export. Updated JNI bridge (7 lifecycle JNI functions), Java
MainActivity (all lifecycle overrides), Swift bridge (onLifecycle + constants),
SwiftUI app (scenePhase observer), nix build files (force-export symbol), and
test suite (6 new tests covering roundtrip, dispatch, and unknown code handling).

Prompt: Implement lifecycle callbacks for haskell-mobile per the approved plan.
Tokens: ~85k input, ~15k output

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Combine callback-mutating tests into a single test case to avoid
races from tasty's default parallel test execution. The global
IORef callback was being overwritten by concurrent tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace the global `IORef` + `unsafePerformIO` lifecycle callback with
a `MobileContext` record passed through the C FFI as an opaque `StablePtr`.

- Add `MobileContext` record with `onLifecycle` callback field
- Add `newMobileContext`/`freeMobileContext` for StablePtr lifecycle
- Add `defaultMobileContext` (no-op callback) and `haskellCreateContext` FFI export
- Change `haskellOnLifecycle` to take `Ptr ()` context as first argument
- Update JNI bridge: create context in `JNI_OnLoad`, pass to all lifecycle calls
- Update Swift bridge: store context in static var, pass to lifecycle calls
- Update C header with new signatures
- Add `-u,haskellCreateContext` link flags to android.nix and ios.nix
- Split callback tests into independent cases (no more shared global state)
- Remove `setLifecycleCallback`, `IORef`, `unsafePerformIO`

Each platform bridge (and each test) now owns its own context, eliminating
races and making the API pure `IO`.

Prompt: Implement the plan to refactor StablePtr MobileContext (eliminate global IORef)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add cbits/platform_log.c with platform-dispatched logging: Android
logcat (__android_log_print), Apple os_log, or stderr on desktop.

Haskell FFI-imports this as platformLog and builds loggingMobileContext
on top, which logs every lifecycle event. haskellCreateContext now
returns a logging context instead of the silent default, so Android/iOS
apps get lifecycle logging with no bridge changes.

The desktop sample app (app/Main.hs) now demonstrates the Haskell-level
API by firing all 7 lifecycle events through loggingMobileContext.

Updated nix/android.nix (-llog for liblog) and nix/ios.nix to include
the new C source. Added test asserting loggingMobileContext handles all
events without throwing.

Prompt: Implement platform-aware lifecycle logging + sample app
Tokens: ~55k input, ~5k output

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Switch platformLog from String to Text for better ergonomics with
OverloadedStrings. Update the desktop sample app to frame itself as
a lifecycle event listener, mirroring how Android/iOS bridges dispatch
events through haskellOnLifecycle into the Haskell callback.

Prompt: change platformLog to receive a Text instead of a String. Change the demonstration such that we have a haskell program that listens for lifecycle events from android/ios and upon receiving a life cycle event it emits a message to the platformLog saying it received it.
Tokens: ~100k input, ~3k output

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The nix builds compile src/ directly with ghc (not cabal), so
cabal default-extensions aren't applied. The Text string literal
"Lifecycle: " needs the pragma in-source.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Introduce a Backpack signature (HaskellMobile.App) so consumers can
provide their own MobileContext at compile time without modifying
library source. The library is now split into sub-libraries:

- haskell-mobile-lifecycle: types, lifecycle events, platformLog
- haskell-mobile (indefinite): FFI exports, uses appContext from signature
- haskell-mobile-default-app: default appContext = loggingMobileContext
- haskell-mobile-app: instantiates the main library with default-app

For nix mobile builds, -i flags point at src-lifecycle and default-app
so raw GHC resolves the modules without Cabal's Backpack resolver.

Prompt: Implement the following plan: Backpack-based user app hook for MobileContext

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Two issues with the nix mobile builds (android.nix, ios.nix):

1. The .hsig file in src/ was picked up by raw GHC which doesn't
   handle Backpack signatures. Moved it to src-sig/ so only Cabal
   (via hs-source-dirs) sees it.

2. Using -i with nix store paths for src-lifecycle/default-app
   failed because GHC writes _stub.h files next to the source and
   the nix store is read-only. Now we copy the modules into the
   writable build directory instead.

Prompt: repair the nix build, make sure ci.nix builds

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
jappeace and others added 28 commits April 7, 2026 20:30
…handler

Add default exception handler for FFI entry points
…report

Add cross-compilation gaps report
…ender-context

Eliminate global render context
Add UITextField support to the iOS UI bridge, bringing it to parity with
the Android bridge for text input widgets. Previously, UI_NODE_TEXT_INPUT
(type 4) hit the default case and was silently dropped.

Changes:
- ios_create_node: handle UI_NODE_TEXT_INPUT → UITextField
- ios_set_str_prop: handle UI_PROP_TEXT and UI_PROP_HINT on UITextField
- ios_set_num_prop: handle UI_PROP_FONT_SIZE and UI_PROP_INPUT_TYPE on UITextField
- ios_set_handler: handle UI_EVENT_TEXT_CHANGE via UIControlEventEditingChanged
- IOSBridgeHandler: add handleTextChange: dispatching to haskellOnUITextChange
- HaskellMobile.h: declare haskellOnUITextChange
- HaskellBridge.swift: add onUITextChange for Swift API completeness
- test/ios/textinput.sh: assert UITextField creation and handler registration

Closes jappeace#40

Prompt: Implement the iOS TextInput onChange callback plan (issue jappeace#40)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The assert_log helper uses grep -qE (extended regex), so literal
parentheses in createNode(type=4) must be escaped as \( \).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ange

Implement iOS TextInput with onChange callback
Wire UI_PROP_COLOR (text color) and UI_PROP_BG_COLOR (background color)
through the full stack: Haskell WidgetStyle → Render.applyStyle →
C bridge → Android JNI / iOS UIKit / watchOS SwiftUI.

Colors are hex strings (#RGB, #RRGGBB, or #AARRGGBB). Each platform
parses hex inline with its native tooling (strtoul on Android,
NSScanner on iOS, UInt64 radix:16 on watchOS).

- Add PropBgColor to UIBridge.hs, UI_PROP_BG_COLOR to UIBridge.h
- Extend WidgetStyle with wsTextColor and wsBackgroundColor fields
- Extend applyStyle to emit setStrProp calls for color fields
- Android: parse_hex_color + setTextColor/setBackgroundColor via JNI
- iOS: parse_hex_color → UIColor, apply to UILabel/UIButton/UITextField
- watchOS: Color(hex:) extension, .foregroundColor/.background modifiers
- Counter app demo uses red text on green background for integration tests
- 5 new unit tests for color rendering and callback pass-through
- Integration test assertions for setStrProp color/bgColor on all 3 platforms

Prompt: Implement the plan for Colors and Theming (Issue jappeace#38)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace raw Text hex strings with a proper Color data type holding
Word8 channels (red, green, blue, alpha). Provides:
- Color constructor: Color r g b a
- colorFromText: parse "#RGB", "#RRGGBB", "#AARRGGBB" → Maybe Color
- colorToHex: serialize Color → "#AARRGGBB" for the C bridge

WidgetStyle fields wsTextColor and wsBackgroundColor now use Maybe Color
instead of Maybe Text. Render.applyStyle calls colorToHex at the bridge
boundary.

5 new tests: colorFromText parsing (#RGB, #RRGGBB, #AARRGGBB), invalid
input rejection, and colorToHex roundtrip.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add text color and background color support
…plate

Consumer apps previously had to copy-paste ~150 lines of MainActivity.java
and keep it in sync with haskell-mobile. When new JNI features were added
(like the permission bridge), consumers would silently break at runtime with
SIGSEGV from uncleared JNI exceptions.

- Extract all JNI native declarations, lifecycle forwarding, permission
  handling, and UI wiring into HaskellMobileActivity base class
- Simplify MainActivity to a one-line extends
- Change JNI_CLASS default from MainActivity to HaskellMobileActivity
- Hardcode JNI_PACKAGE=me_jappie_haskellmobile for core C files (jni_bridge,
  permission_bridge) since native methods live on the library's own class
- Add ExceptionClear safety nets in permission_bridge_android.c and
  ui_bridge_android.c to prevent SIGSEGV from pending JNI exceptions
- Guard registerTextWatcher usage against null method ID
- Add baseJavaSrc parameter to mkApk for consumer APK builds

Closes jappeace#52

Prompt: Implement the plan to eliminate duplicated MainActivity boilerplate (Issue jappeace#52)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…vity-boilerplate

Extract HaskellMobileActivity base class (fixes jappeace#52)
Instead of re-implementing cabal build + package database generation in
mk-deps.nix, use standard nixpkgs haskellPackages infrastructure to build
cross-compiled Haskell dependencies. A new collect-deps.nix collects the
pre-built .conf and .a files from nixpkgs derivation outputs.

This enables consumers to use standard nixpkgs mechanisms (dontCheck,
doJailBreak, overrideCabal, etc.) via a new `hpkgs` overlay parameter,
replacing the old extraPackages/perPackageFlags interface.

Changes:
- New nix/collect-deps.nix: shared collection logic for both platforms
- cross-deps.nix: rewritten to use nixpkgs haskellPackages + collect-deps
- ios-deps.nix: same approach with native haskellPackages
- resolve-deps.nix: added haskellPkgs param, returns derivations by default
  (returnSources=true for backward compat with mk-deps.nix consumers)
- android.nix, ios.nix, watchos.nix: pass through hpkgs parameter
- mk-deps.nix: kept with deprecation comment for backward compat

Prompt: Replace mk-deps.nix with nixpkgs haskellPackages for cross-compilation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Nothing in haskell-mobile imports mk-deps.nix anymore — cross-deps.nix
and ios-deps.nix both use collect-deps.nix now. Also removes deps-wrapper/
and cabal-config (only used by mk-deps.nix), and the returnSources
backward-compat flag from resolve-deps.nix.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace mk-deps.nix with nixpkgs haskellPackages
cabal2nix merges internal sub-library deps into libraryHaskellDepends
(e.g. vector's benchmarks-O2 → tasty, random), which leaks test
frameworks into propagatedBuildInputs. Their transitive deps (unix,
process via optparse-applicative) cause link failures because boot
packages aren't linked into the .so.

Add a test framework exclusion list to resolve-deps.nix so these
packages are skipped during the transitive walk. Consumers who
genuinely need them can add them via the hpkgs overlay.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…-leakage

Exclude test frameworks from transitive dep collection
Introduces Image as a new widget type with three source variants
(ImageResource, ImageData, ImageFile) and configurable ScaleType
(ScaleFit, ScaleFill, ScaleNone). The full bridge pipeline is
implemented: Haskell Widget ADT → Render.hs → UIBridge FFI →
C dispatcher → platform callbacks.

New types: ScaleType, ImageSource, ImageConfig in Widget.hs.
New FFI: ui_set_image_data for binary data, new string props
(UI_PROP_IMAGE_RESOURCE=4, UI_PROP_IMAGE_FILE=5) and numeric
prop (UI_PROP_SCALE_TYPE=4).

Platform implementations:
- Android: ImageView with BitmapFactory.decodeByteArray/decodeFile,
  resource lookup via getIdentifier, ScaleType enum mapping
- iOS: UIImageView with UIImage imageNamed/imageWithData/
  imageWithContentsOfFile, contentMode mapping
- watchOS: SwiftUI Image with resource/Data/file sources,
  resizable+scaledToFit/Fill modifiers

Integration test infrastructure added for all 3 platforms with
imageDemoApp exercising all 3 source types. 6 unit tests, all
94 tests pass.

Prompt: Implement the following plan: Image widget support (Issue jappeace#37)
Tokens: ~160k input, ~30k output

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The watchOS UIBridgeSetup.c was missing the setImageData function pointer
in g_watchos_callbacks, causing ui_set_image_data to fall through to the
stderr stub instead of routing to the Swift watchos_set_image_data function.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Wrap ImageResource Text in newtype ResourceName for type safety
- Change ImageFile Text to FilePath (standard Haskell type)
- Move imageDemoApp from library (App.hs) into test code (ImageDemoMain.hs)
- Add per-ScaleType unit tests (ScaleFit, ScaleFill, ScaleNone)
- Show "Image not found" placeholder on iOS/watchOS when resource/file
  fails to load; Android logs the error and shows empty ImageView
- Answer compile-time resource guarantee question in ResourceName docs:
  no guarantee possible since resources are platform-specific, but
  missing resources are handled gracefully at runtime

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Technical report covering how both frameworks handle rendering:
- React: fiber architecture, virtual DOM, Fabric renderer, JSI, Yoga layout, lanes scheduling
- Flutter: three trees, Impeller engine, constraint-based layout, layer compositing, Dart AOT
- Comparison section with lessons for haskell-mobile's architecture

Prompt: Investigate how both react and flutter do rendering. Make a report on this, write this report into the docs section of haskell-mobile
Tokens: ~68k total across research agents

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…parison

Add React Native vs Flutter rendering comparison doc
20-category feature matrix comparing Flutter's capabilities against
what haskell-mobile currently supports, with detailed per-category
analysis and a prioritized gap summary.

Key findings: haskell-mobile covers core widget types, 3 mobile
platforms (incl. watchOS which Flutter lacks), and has strong type
safety. Biggest gaps: incremental rendering, more widget types,
navigation, layout flexibility, gesture recognition, animation.

Prompt: Make a list of major features that flutter has, and then compare them with what haskell-mobile supports
Tokens: ~69k explore agent

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…re-comparison

Add Flutter vs haskell-mobile feature comparison
Remove the global IORef (globalMobileApp, runMobileApp, getMobileApp)
and the haskellCreateContext foreign export. Instead, the user's main
returns IO (Ptr AppContext) via startMobileApp, and the C bridge
captures the return value using rts_evalIO + rts_getPtr.

The AppContext now holds an acViewFunction IORef for the current view,
so handleException/errorWidget/renderView all read from the context
rather than a global. Each test creates its own isolated AppContext,
eliminating sequentialTestGroup and shared mutation.

Updated: run_main.c, HaskellMobile.h, jni_bridge.c, both Swift bridges,
nix/lib.nix linker symbols, all app entry points, all demo mains,
test suite, and Readme architecture docs.

Prompt: Implement the plan to eliminate globalMobileApp by returning
context from main. Change main :: IO () to main :: IO (Ptr AppContext),
use rts_evalIO in run_main.c, remove runMobileApp/getMobileApp/
haskellCreateContext, add startMobileApp/acViewFunction, rewrite all
consumers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
jappeace-sloth pushed a commit that referenced this pull request Apr 17, 2026
Enable per-function ELF sections via GHC's -split-sections flag and
linker dead-code elimination via --gc-sections, reducing Android .so
size by ~30% (75 MB → 53 MB after stripping).

## How it works

Without -split-sections, GHC compiles each Haskell module into a single
.o file with one monolithic .text section. The linker's granularity is
the .o file — it can either include the whole thing or discard it.
Since --whole-archive forces every .o from all 12 boot libraries into
the .so, nothing gets discarded. Even if you only use Data.Map.lookup
from containers, you get every function in that module's .o.

With -split-sections, GHC emits each top-level binding into its own
ELF section (e.g. .text.Data.Map.Internal.lookup,
.text.Data.Map.Internal.union, etc.). Now --gc-sections can trace
reachability from the 19 -u FFI entry points (haskellRunMain,
haskellRenderUI, etc.) and discard any section that nothing references.

So --whole-archive still forces the .o files in, but the linker can
now gut them — keeping only the functions that are transitively
reachable and discarding the rest. The 22 MB removed is dead code from
base, containers, ghc-prim, text, transformers, etc.: functions that
exist in those libraries but are never called by any path from the FFI
entry points.

## Measured results

| Metric         | Master  | This PR | Change |
|----------------|---------|---------|--------|
| Before strip   | 80-82MB | 55 MB   | -31%   |
| After strip    | 75-77MB | 53 MB   | -30%   |

## Remaining opportunity

The --whole-archive flag still forces all 12 boot package .a files into
the link. Replacing --whole-archive with selective -u symbols for each
boot library (optimization #2 from docs/so-size-reduction.md) would
compound on top of this reduction, since the linker could skip entire
.o files that contain no reachable sections at all.

## Changes

- hatter.cabal: add -split-sections to library ghc-options so .a files
  get per-function sections
- nix/lib.nix: add -split-sections to GHC compile/link invocations and
  --gc-sections to the linker, in both the pre-compiled (hatterObjs)
  and fallback paths

Prompt: add split-sections + gc-sections to Android .so builds, then
rebase onto master and write a detailed report in the commit message

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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