red-swift

Stopgap Red interpreter for 64-bit Mac

View on GitHub

Red interpreter in Swift for Apple Silicon (“red-swift”)

Context

The official Red toolchain is 32-bit only, so it cannot run on this Mac (the installed /usr/local/bin/red is a 2019 i386 binary). The goal is a private stopgap: an interpreter, written in Swift, with a simple REPL, that lets you develop and run Red CLI and GUI applications here and then run the same code under real Red elsewhere.

Scope: the Red language and its View/VID/Draw GUI system as a typical Red application uses them, so that most common Red programs run unmodified. Only Red/System and compiler-specific features are excluded (see “Out of scope”).

First gates, not the finish line: ~/Claude/developer/tictactoe-red/tictactoe.red and ~/Claude/developer/othello/othello.red, unmodified. After them the gates are Red’s own unit suite, its headless View suite, and the roughly 44 demo scripts in red/tests/ (demo.red, vid*.red, react-test*.red, draw.red, shape-test.red, matrix-test.red, modal.red, tabbing.red, and so on).

Reference source: ~/Claude/developer/red (v0.6.6 + 823 commits, f4e9d17f1). It agrees with the 0.6.6 release on the syntax both programs use.

Sizing, stated plainly: “simple” describes the tool, not the build. This is roughly 35k lines of Swift plus about 11k lines of Red loaded from the repo, built over many sessions. Milestones are ordered so each ends in something usable: both games at M5, general GUI apps at M6, general CLI apps at M7.

Approaches considered

  1. Run Red’s own GUI source (chosen). Swift implements the language core, parse, an AppKit platform layer and the Draw renderer. view.red, VID.red, the style table and reactivity.red are loaded from the repo nearly unchanged. Layout and behaviour match real Red; any VID feature works without extra Swift. Cost: the interpreter must be fairly complete before the first window.
  2. Hand-port the GUI to Swift. Sooner first window, smaller interpreter, but every VID keyword is hand work and behaviour drifts from real Red, which defeats testing on the Mac. You chose 1.

The same principle is applied throughout: wherever upstream implements something in Red (mezzanines, help, JSON/CSV codecs, rich-text dialect, preprocessor, colour picker), load that source rather than re-writing it.

Design

Shape

New SwiftPM package at ~/Claude/developer/red-swift (own git repo; name is a placeholder, rename freely). Three targets:

Settings: tools-version 6.2+, .defaultIsolation(MainActor.self) on every target (the interpreter and AppKit share the main thread; only the stdin reader is nonisolated). Release builds of RedCore use -O; the red binary links with a 64 MB stack.

What comes from the Red repo, and how

Pristine copies live in Vendor/red/ (same relative paths as upstream), embedded into the binary by scripts/sync-red.sh <checkout> <commit>. RED_BOOT_DIR points the loader at files on disk during development. Nothing in Vendor/ is hand-edited; all adaptation happens at load time:

Loaded nearly as-is Patch needed
environment/natives.red, actions.red Specs come from here; Swift attaches implementations by name
environment/scalars.red, colors.red, css-colors.red, reactivity.red, networking.red, console/help.red scalars.red:35 null handle
environment/functions.red Drop routine: (13-15); replace the #do keep generator (92-164) with Swift-generated type? predicates, to-* wrappers and *-of reflectors; natives for the #system-bodied trig funcs (1014-1096)
environment/system.red About a dozen substitutions (version, date, config, system/words, platform 'macOS, args)
environment/codecs/JSON.red, CSV.red JSON’s one routine (unescape) becomes a native
utils/preprocessor.r None expected; gives full #include #do #macro #process for user scripts
modules/view/view.red, VID.red, styles.red, rules.red, utils.red, RTD.red, request-color.red, backends/macOS/rules.red, backends/macOS/styles.red None beyond the mechanical rules
modules/view/backends/platform.red (only the Red-level tail: refresh-screens, init with the macOS metrics tables) platform.red:1291 #system [gui/init] becomes a call to a Swift gui-init

Not loaded: operators.red (Swift registers the ops), routines.red (Swift natives), draw.red (Red/System; rewritten in Swift), image codec stubs (Swift via ImageIO), console/engine.red (REPL is Swift).

Language core

Coverage target: all 101 natives and 59 actions in environment/natives.red and actions.red, every datatype a normal program can create, and every mezzanine in functions.red. Anything not yet implemented raises a Red error naming the missing feature, never a crash or silent wrong answer.

CLI application support

GUI layer

REPL

Out of scope

Milestones

Each ends in something runnable. Conformance uses a Swift runner over the upstream quick-test files: it evaluates expression by expression, logs an error and skips to the next --test--, and reports a per-file pass rate checked against Tests/conformance/baseline.txt, which only ratchets up.

# Builds Check
M0 Package scaffold, lexer, values, mold; 60-line AppKit spike (lazy NSApp, nested loop, reader thread + posted event) Lex and re-mold every vendored file, every tests/source/units/*.red, and both games; lexer-test at 80%+; spike window opens and closes from a terminal run
M1 Evaluator, scalars, basic series, functions, errors, REPL v0; native specs booted from natives.red/actions.red Units at 90%+: integer logic conditional loop switch case function evaluation unset throw try comparison same strict-equal type char power tuple pair time. Script: run tictactoe.red lines 8-152 and assert minimax returns a legal move and blocks an immediate loss
M2 Objects, change events, ownership, parse, map/bitset/typeset; environment boots (scalars colors functions system reactivity help) Units at 85%+: object binding parse reactivity words-of map bitset system points make path. REPL: help append, source rejoin. Headless othello per its CLAUDE.md: a full computer-vs-computer game through tick terminates; record last-depth
M3 View boots on TestBackend: view.red, platform tail, VID.red, Draw parser (validation only) The 16 small files in tests/source/view/ at 90%+ (516 asserts in the folder). Scripts: layout init-ttt then do-actor square5 none 'click; layout init-window yields 64 base faces and reactions fire after new-game
M4 AppKit: window, base, button, text, fonts, size-text, view/unview/do-events/wait, close, timers red tictactoe.red fully playable (Computer Move animation, Again?, Quit); --headless screenshot
M5 Basic Draw rendering (pens, shapes, text, transforms), base text styling, performance pass red othello.red: human and computer-vs-computer games to completion; last-depth after 1 s at least the M2 figure
M6 General GUI apps: all remaining styles except rich-text, all events, keyboard/focus/tab, menus, alert and request-*, drag (loose), window flags, incremental pane/list updates base-self-test.red on TestBackend at 85%+. Run and screenshot tests/vid.red … vid6.red, view-test.red, react-test*.red, modal.red, tabbing.red, dyn-gui.red, events-flow.red, demo.red
M7 General CLI apps: full file/dir I/O, call, ask/input, args, env, HTTP(S), JSON/CSV, enbase/checksum/compress, clipboard, full date!, upstream preprocessor for user scripts; REPL polish (history, multi-line, Ctrl-C, console words) Units at 85%+: series append insert change find select replace move mold load convert date file url serialization json csv checksum debase enbase decompress preprocessor clipboard. tests/source/environment/functions-test.red at 90%+. Script tests: a call/pipe round trip, a local-file JSON round trip, an HTTPS read
M8 Full Draw, images, rich-text: gradients, patterns, shadows, shape, matrix ops, on-drawing; image! and codecs; rich-text + RTD + request-color; vector! money! point3D!, indexed hash! Units at 85%+: image draw vector money. Run and screenshot tests/draw.red, shape-test.red, matrix-test.red, clip-test.red, complexpen-test.red, shield.red, font-weight-demo.red, select-text.red
M9 Hardening: every unit file in all-tests.txt that does not need the compiler, regression-test-red subset, do/trace + tools.red, boot-time and evaluator profiling Whole-suite pass rate 90%+ with a per-file list of what still fails and why; release boot under 150 ms (View booted lazily)

Source tree (new files)

red-swift/
  Package.swift
  Vendor/red/...                      pristine upstream .red files
  scripts/sync-red.sh, scripts/embed.py
  Sources/RedCore/
    Value.swift Symbols.swift Context.swift SeriesBuffers.swift Scalars.swift DateTime.swift
    Typeset.swift MapBitset.swift Vector.swift Money.swift ImageData.swift
    Lexer.swift LexerScan.swift
    Interpreter.swift Eval.swift PathEval.swift Call.swift Stack.swift Signals.swift Errors.swift
    Objects.swift Binding.swift Functions.swift
    Natives{Control,Data,Math,Series,System}.swift Compare.swift Convert.swift Reflect.swift
    Actions{Block,String,Binary,Number,Scalar,Map,Object}.swift Sort.swift Random.swift
    IO{Files,Network,Process,Console}.swift Codecs{Base,Checksum,Compress}.swift
    Mold.swift Form.swift Parse.swift ParseRules.swift
    Preprocessor.swift VendorLoader.swift VendorPatches.swift NativeRegistry.swift
    Generated/VendoredSources.swift
  Sources/RedView/
    ViewBackend.swift PlatformNatives.swift FaceReader.swift
    AppKitBackend.swift EventLoop.swift Events.swift Timers.swift Menus.swift Dialogs.swift
    Widgets{Window,Base,Buttons,Text,Lists,Range,Containers,Tabs,Calendar,RichText}.swift
    Fonts.swift Metrics.swift
    DrawParser.swift DrawShape.swift DrawSinkCG.swift DrawBrushes.swift
    ImageSupport.swift TestBackend.swift
  Sources/red/  main.swift CLI.swift REPL.swift LineReader.swift
  Tests/RedCoreTests/  ConformanceRunner.swift LexerTests.swift EvalTests.swift IOTests.swift
  Tests/RedViewTests/  view suite on TestBackend, headless game scripts, demo-script smoke runs
  Tests/conformance/baseline.txt
  docs/design.md                      this plan, committed at the start

Upstream references to port from

Risks

  1. Breadth. “Most common Red programs” has a long tail. Handled by ordering (language, then GUI, then CLI, then Draw/images), by loading upstream Red source wherever it exists, and by the rule that unimplemented features raise a named error.
  2. Semantic long tail (mold/form, comparison, conversion, pair/point2D mixing) silently breaking VID arithmetic. Covered by the M3 view suite and the ratcheting baseline.
  3. Ownership event ordering being subtly wrong. Covered by single mutation primitives plus show-sync-test and face-tree-test.
  4. AppKit from an unbundled CLI (activation, focus, menus, timers under App Nap). Proven early by the M0 spike.
  5. Control metrics in platform.red were tuned for older macOS bezels; buttons may look slightly off. Handled with an override map applied after init, never by editing vendored data.
  6. Evaluator speed. Measured at M2, M5 and M9 against Othello’s search depth.
  7. Upstream drift if the checkout moves. Pinned commit plus exactly-once anchors.

Verification (end to end)

Not done without asking

Installing the binary onto your PATH or replacing the dead /usr/local/bin/red; pushing the new repo to GitHub.