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
- 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 andreactivity.redare 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. - 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:
RedCore(Foundation only): lexer, values, evaluator, natives and actions,parse, objects with change events, preprocessor support, boot loader, embedded Red sources, file/network/process I/O.RedView(AppKit): thesystem/view/platformnatives,event!behaviour, widgets, Draw, images, timers, dialogs, and a headless test backend.redexecutable:red file.red [args]runs a script; bareredstarts the REPL.
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:
- Mechanical rules: skip
#system [...]/#system-global [...]at text level; turnname: routine [...] [...]into the same-named Swift native; evaluate#if/#either/#switchagainst aconfigobject (OS: 'macOS,GUI-engine: 'nativeor'test,modules: [view]); resolve#includerelative to the including file. - Anchor patches (
VendorPatches.swift): a short table of{file, exact anchor text, action}. Each anchor must match exactly once or boot aborts, which is how upstream drift gets caught.red --verify-bootruns the check.
| 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.
- Datatypes:
unset none logic integer float percent char pair point2D point3D tuple time date money, all word kinds,refinement issue,block paren hash vector, the four path kinds,string file url tag email ref binary,map bitset typeset datatype object error,function native action op routine(as a type only),image event handle.hash!starts as a block with linear search and gets a real index in M8. - Value: Swift enum, scalars inline (
integer!is Int32 with overflow promoting to float,/gives a float unless exact), class-backed series (shared buffer + 1-based index), objects, functions, maps.event!,image!andhandle!payloads are plain data inRedCore;RedViewattaches behaviour through hooks. - Strings are stored as arrays of Unicode scalars, so index,
pokeandparseare O(1) and share one engine with blocks. - Symbols: one id per spelling plus a canonical (case-folded) id. Contexts and
=use the canonical id;==andmolduse the spelling. - Binding: words carry
(context, index). Function bodies are deep-copied and bound at creation.functioncollects deep set-words andforeach/repeatwords as locals and honours/extern. - Calls: one shared value stack; each function context holds a
frameBasesaved and restored per call. Gives recursion and GUI re-entrancy with no per-call allocation, and matches Red’s “no closures” rule. - Evaluation: strict left-to-right infix with one-cell op lookahead, argument modes
word/'lit/:get, refinements consumed in path order, dynamic refinements (f/:ref) on natives too. - Control flow: Swift typed throws with a payload-free
Signalenum (break, continue, return, exit, throw, error, halt, quit); payloads parked on the interpreter.break/continuecross function boundaries,return/exitstop at them,catch/namematchesthrow/nameonly. - Errors: objects built from
system/catalog/errors, printed in upstream format (*** Script Error: ...,*** Where:,*** Near :,*** Stack:). - Objects:
make proto specclones series and rebinds function bodies;on-change* [word old new]fires from set-words, set-paths,setand component writes such asface/offset/x: 1, withwordbound to the object (the face code usesindex? wordas the dirty bit).set-quietbypasses it. - Ownership: every series mutation goes through about six primitives per buffer class (insert, remove, change, clear, move/swap, sort/reverse). Those fire the pre/post
on-deep-change*events, so the dozens of actions built on them stay correct. parse: the full dialect on block, string, binary and path input, includingcollect/keep,into,case, bitsets, integer ranges andparse/trace.- Preprocessor: the mechanical rules above for boot; upstream
preprocessor.rfor user scripts (#include,#do,#if,#either,#switch,#case,#macro,#process). - Hot path:
finalclasses, specs precompiled to argument descriptors with type masks, args evaluated straight onto the stack,first/second/last/empty?overridden as natives. Othello’s search is time-budgeted, so depth reached is the performance measure.
CLI application support
- Console I/O:
print prin probe ?? ask input(upstreamask/inputlogic on a Swift line reader),write-stdout,system/options/args,system/script/args,system/script/header,quit/returnexit codes, shebang lines. - Files and directories:
read writewith/binary /lines /part /seek /append /info,load savewith/as,exists? dir? size? query delete rename make-dir change-dir what-dir list-dir clean-path split-path to-local-file to-red-file,do %file. - Processes and environment:
callwith/wait /output /error /input /shell /console /show,get-env set-env list-env,nowin all refinements,wait,browse. - Network:
read/writeonhttp://andhttps://URLs throughURLSession, includingwrite/info url [POST [headers] body],/binary,/lines;decode-url encode-url. - Codecs and data: JSON and CSV (upstream Red source),
enbase debase(2, 16, 58, 64),checksum(CRC32, MD5, SHA1, SHA256, SHA384, SHA512, TCP, hash, with/withfor HMAC),compress decompress(gzip, zlib, deflate),enhex dehex,to-hex. - Clipboard:
read-clipboard write-clipboardviaNSPasteboard. - Debug tooling:
help ? source what about,dt/clock,stats,do/tracewithtrace/profilefromtools.red(late milestone).
GUI layer
- Backends: a
ViewBackendprotocol withAppKitBackendandTestBackend. The test backend mirrorsmodules/view/backends/test/(dummy handles,size-text= 1x1, screen 2000x1000, events synthesized throughsystem/view/awake) and is chosen byConfig: [GUI-engine: 'test]in a script header or--gui-engine test. - App lifecycle:
NSApplicationis created lazily on firstview(activation policy.regular, minimal main menu), so plain scripts stay terminal-only.viewruns a nestednextEvent/sendEventloop as Red’s macOS backend does; destroying a window ends the innermost loop. - Event-loop fidelity (my call): match upstream macOS exactly.
do-events/no-waithandles one pass, andwaitsleeps and then pumps once. Being more responsive than real Red would hide the timing bugs this tool is meant to expose. - Styles, all of upstream’s table (
styles.red), following upstream’s class mapping (backends/macOS/gui.reds): window (flipped content view, flagsmodal popup resize no-title no-border no-min no-max no-buttons); base/box/image/panel as a custom flippedNSViewthat paints colour, image, text, then the Draw block; button/toggle/check/radio asNSButton; text, h1-h5 and field (NSTextField, password flag); area (NSTextView); text-list (NSTableView); drop-list (NSPopUpButton); drop-down (NSComboBox); slider; progress; scroller; group-box; tab-panel; calendar (NSDatePicker); rich-text with the RTD dialect (Core Text,text-box-metricsforcaret-to-offset,offset-to-caret, line metrics). Font size is Red size x 94/72, as upstream. Camera is the one style left out. - Facets:
update-viewreads the dirty mask instate/2and applies every facet; incremental pane and list-data changes arrive throughon-change-facet. Font, para and scroller objects update their faces. - Events, all of
system/view/evt-names: mouse (down/up/mid/alt/aux, click, dbl-click, over withaway?, wheel), keyboard (key, key-down, key-up, enter, modifier flags), focus/unfocus, change/select, time, drawing (on-drawing+draw-face), menu, window (close, move, moving, resize, resizing), plus the drag events Red synthesizes forloosefaces.make event!andsend-eventwork. A guard stops Red-driven updates echoing back as events; views are retained during dispatch. - Menus and dialogs: face
menufacet (window menu bar and context menus),alert,request-file,request-dir,request-font(native panels),request-color(upstream’s Red picker). - Timers:
ratefacet (integer ortime!) maps toNSTimerand atimeevent. - Draw, the whole dialect: a pure
DrawParser(ported fromdraw.red; validates, emits a command stream) plus aDrawSinkprotocol with CoreGraphics and null implementations. Commands:pen fill-pen(colours, linear/radial/diamond gradients, pattern and bitmap brushes),line-width line-join line-cap line-pattern anti-alias,line box triangle polygon circle ellipse arc curve spline,text font image(with key colour, crop, 4-point forms),shadow,clip,shapewith its sub-dialect,matrix transform rotate scale translate skew reset-matrix invert-matrix push. - Images:
image!withmake, pixelpick/poke,/size /rgb /alpha /argb,copy/part; PNG, JPEG, GIF, BMP and TIFF load and PNG/JPEG/BMP/GIF save through ImageIO;drawonto an image;to-image face. - Scripted checks:
--headless(real views, windows never shown) plusto-imageandsave %x.png, so visual results can be captured from a script.
REPL
- Written in Swift;
help ? source what aboutcome from the vendoredhelp.red. - Prompt
>>, results as== value, multi-line continuation on open brackets, history and line editing via libedit, upstream error format, console wordsls ll pwd cd dir q halt. - A reader thread owns stdin and hands each line to the main thread through a mailbox plus a posted application event (not the main dispatch queue, which does not drain inside a nested
view). The main thread pumps AppKit while waiting, soview/no-waitwindows stay live at the prompt. - stdout is line-buffered so output survives a killed windowed run. Ctrl-C sets a halt flag polled at loop back-edges and calls.
Out of scope
- Red/System:
#system, user-definedroutine,#import, libRed. - Compiling and encapping (
-c,-r), redbin format, the GUI console, GPIO scheme, Android and terminal (TUI) backends. camerastyle and dark-mode calls.- Possible later add-on, not planned:
red --bundle app.redto wrap a script and the interpreter into a standalone executable or.app.
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
- Evaluator:
runtime/interpreter.reds(infixcheck-infix1524-1544, args 892, paths 660, calls 391) - Lexer:
docs/lexer/lexer-states.txt(whole state machine in text),runtime/lexer.reds - Objects and events:
runtime/datatypes/object.reds(make 1106-1150, rebind 784-819),context.reds261-284,runtime/ownership.reds - Datatype semantics: one file each under
runtime/datatypes/; conversion, comparison and math matrices indocs/*.xlsx parse:runtime/parse.reds- Draw grammar:
modules/view/draw.red(parse-draw at 750, parse-shape at 636); primitive list:modules/view/backends/test/draw.reds; rendering:backends/macOS/draw.reds - AppKit behaviour:
modules/view/backends/macOS/{gui,delegates,events,font,menu,tab-panel,text-box,comdlgs}.reds - Headless backend template:
modules/view/backends/test/ - Console input:
environment/console/CLI/input.red
Risks
- 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.
- Semantic long tail (mold/form, comparison, conversion, pair/point2D mixing) silently breaking VID arithmetic. Covered by the M3 view suite and the ratcheting baseline.
- Ownership event ordering being subtly wrong. Covered by single mutation primitives plus
show-sync-testandface-tree-test. - AppKit from an unbundled CLI (activation, focus, menus, timers under App Nap). Proven early by the M0 spike.
- Control metrics in
platform.redwere tuned for older macOS bezels; buttons may look slightly off. Handled with an override map applied afterinit, never by editing vendored data. - Evaluator speed. Measured at M2, M5 and M9 against Othello’s search depth.
- Upstream drift if the checkout moves. Pinned commit plus exactly-once anchors.
Verification (end to end)
swift build -c releaseandswift test(conformance baseline, view suite onTestBackend, headless game scripts, I/O tests).red --verify-bootafter any vendor sync.red tictactoe.redandred othello.redfrom a terminal: full games, including computer-vs-computer.- The demo scripts listed under M6 and M8 run without errors; I capture each window with
--headless+to-imageand you confirm look and feel by eye. - CLI: a script using args,
ask, file I/O,calland JSON, run withred script.red a b, with exit code checked. - REPL:
red, thenhelp append, a multi-line function definition, an error, andview/no-wait [button "Hi" [print "hi"]]with the prompt still live.
Not done without asking
Installing the binary onto your PATH or replacing the dead /usr/local/bin/red; pushing the new repo to GitHub.