Progress ledger
Plan: docs/design.md. One line per finished step; rulings record where the build departs from the plan and why.
M0 — lexer, values, mold, AppKit spike
- Scaffold: SwiftPM package, three targets, MainActor default isolation, Swift Testing.
- Value model (
Value.swift,Context.swift,Objects.swift,Symbols.swift), lexer (Lexer.swift), mold/form (Mold.swift). - AppKit spike (
red --spike,Sources/RedView/EventLoop.swift,Spike.swift): lazy NSApplication from a plain CLI process, a no-wait pass, a timer firing inside the blocking loop, a line handed over from another thread, and loop exit on window close. Output checked:no-wait pass: idle,from reader thread: line("print 1 + 2"),loop exited, window visible: false, ticks > 3: true. Not yet checked by eye that the window is drawn (first screenshot check is M4). - Tests:
swift test→ 10 passed (8 lexer tests, corpus round trip over 170 upstream files and both games, mailbox test). - M0 complete.
Rulings
- Ruling:
lexer-test.redat 80% is moved from M0 to M1 — the file is a quick-test script, so it needs the evaluator to run — cost if wrong: none, the M0 corpus round trip covers the lexer meanwhile. - Ruling: the lexer is a hand-written scanner following
docs/lexer/lexer-states.txt, not a port of the state table — easier to read and debug — cost if wrong: edge-case token differences, caught bylexer-test.redin M1. - Ruling: where the lexer doc and upstream tests disagree (
-<-and=<=are words; Unicode blanks delimit), the tests win. - Ruling:
float-test.redandlexer-test.redare exempt from the round-trip equality check — both contain the largest double, which Red itself molds with 16 digits and so cannot read back. - Ruling: core types are
public(notpackage) so RedView and the CLI can use them — cost if wrong: none for a private tool.
M1 — evaluator, natives, errors, REPL v0
- Vendoring:
scripts/sync-red.shcopies the 24 files inscripts/manifest.txtintoVendor/red(pinned atf4e9d17f1) andscripts/embed.pyembeds them inSources/RedCore/Generated/VendoredSources.swift.RED_BOOT_DIRreads them from disk instead. - Evaluator (
Interpreter.swift,Call.swift,PathEval.swift,Runtime.swift): shared value stack with per-call frames,(context, index)word bindings, left-to-right infix, refinements in path order, typed-throwSignalcontrol flow, objects with prototype cloning andon-change*/on-deep-change*plumbing. - Natives and actions: specs come from upstream
natives.redandactions.red; Swift attaches implementations by name and checks the frame layout it assumes (red --specs,docs/native-specs.txt). Control flow, series, maths, comparison,make/to, reflection, sets, basic file I/O. - Environment:
scalars.red,colors.redandfunctions.redload through the directive preprocessor with 0 boot problems (red --boot-report). - Errors: catalog and templates read from upstream
system.red; console format*** Script Error: ... / *** Where: / *** Near :. - CLI:
red file.red [args],red -e "code", bareredis a line-based REPL with bracket continuation. - Conformance:
red --conform [--notes] file...(andscripts/conform-m1.sh) runs upstream quick-test files expression by expression. M1 list: 22 files, 5,900+ assertions, 94% overall; per-file floors inTests/conformance/baseline.txt, enforced byswift test. - Headless tictactoe: the game’s AI (lines 8-152) loads and plays correctly (
ticTacToeAIPlaysSensibly). - Tests:
swift test→ 21 passed. - M1 complete.
Rulings
- Ruling:
evaluation-test.redstays at 75% for now — its failing groups aredo/trace,traceandsystem/..., which the plan places in M9 and M2 — cost if wrong: none; upstream itself skips this file in interpreted mode. - Ruling:
try-test.redis at 87.7%, under the 90% target — five edge cases oftry/allaroundbreak/continuewith values — cost if wrong: a script relying ontry/allto swallow a straybreaksees an error instead; revisit in M9. - Ruling: the conformance pass rate is passed / (passed + failed + skipped), where skipped counts assertions an error prevented from running — the lexical count of
--assertwords over-counts assertions that are meant never to run (after athrow). - Ruling: every native closure carries an explicit
throws(Signal)signature, and natives containingdo/catchare functions — Swift 6.4 only infers typed throws for closures with that annotation. - Ruling:
break,continue,return,exitandthrowraise their error at the call site when no loop, function orcatchis active (tracked by depth counters), as upstream does, so plaintrycan catch them. - Ruling:
randomuses a SplitMix64 generator, not upstream’s Mersenne Twister —random/seedis repeatable here but does not reproduce real Red’s sequences. - Ruling: maps and
hash!use linear search for now (indexing arrives in M8, as planned forhash!). - Ruling: float division by zero raises
zero-dividelike integer division — float-test passes at 96% with it; cost if wrong: scripts expecting1.#INFfrom1.0 / 0.0.
M2 — parse, objects, environment
parsedialect (Parse.swift): block, string and binary input;some any opt while to thru skip end not ahead set copy collect keep into quote if remove insert change case break reject fail none, counts and ranges, datatype/typeset/bitset matching. Upstreamparse-test.red: 92.5%.- Environment:
system.red(four text patches inVendorPatches.swift, each anchored and checked),reactivity.red,networking.redandconsole/help.rednow load;red --boot-report→ 0 problems.help append,source rejoin,collect,split,replaceandreactwork on upstream’s own code. - Bitsets follow upstream’s representation (stored membership bits plus a “tail is ones” flag); maps keep keys whose value is
none. - Headless Othello (
othelloPlaysAFullGameHeadlessly): definitions above; ---- main ----load,valid-moves INIT-BOARD 1 = [20 27 38 45], and a computer-vs-computer game throughtickruns to the end with all 64 squares accounted for. - M2 performance figure: release build, default
THINK-TIMEof 1 s, opening position:last-depth= 6. (fib 27: 0.83 s; tictactoe full opening search: 0.70 s; start-up: 17 ms.) - Conformance (M2 list): object 87.4, binding 96.0, parse 92.5, reactivity 95.6, words-of 100, map 89.5, bitset 95.4, system 80.0 (4 of 5), points 86.6, make 100, path 91.5. Baseline now covers 33 files.
- Tests:
swift test→ 22 passed. The conformance test runs the files in theredbinary (64 MB stack) rather than in the test process. - M2 complete.
Rulings
- Ruling:
system-test.redstays at 4 of 5 — the failing assertion expectsfile?to be aroutine!, and this interpreter has no routines — cost if wrong: none for real programs. - Ruling: boot-file directives are resolved on the loaded block, not on the text (the plan said text level for
#system) — every vendored file lexes cleanly as Red, so block-level handling is simpler and equally safe — cost if wrong: a future upstream#systemblock that does not lex would surface as a boot problem. - Ruling:
#do keep [...]in the vendored files is dropped (or replaced bynonein value position), with the generated definitions supplied natively.
M3 — View on the test backend
- Red’s View module loads from upstream source:
view.red,backends/platform.red,VID.red,styles.red,rules.red,utils.red,RTD.red,request-color.red, the macOS rules and the test backend’sgui.red. One anchored patch (#system [gui/init]→gui-init self).red --boot-report test→ 0 problems. - Routines become natives automatically: a
name: routine [spec] [body]in a vendored file turns into a native that keeps upstream’s spec and takes its body fromInterpreter.routines(PlatformNatives.swift); unregistered ones raise “not implemented”. event!is a core datatype (make event!, field access, settabletype);handle!values carry backend ids.ViewBackendprotocol withTestBackend(dummy handles, 2000x1000 screen, 1x1 text, no event loop), selected byConfig: [GUI-engine: 'test]in a script header.- Compiled-body mode: upstream’s View code is normally compiled, where a function’s local word that holds a function is a plain value. The interpreter would call it (VID’s
pre-loadbroke on the wordreturn). Function bodies defined in vendored files are therefore flagged, and inside them a local word holding a function is not invoked, except in blocks passed todo/do-safe, which upstream also interprets. - Upstream headless View tests (
tests/source/view, 16 files): 269/279 = 96.4%, 11 files at 100%; floors inTests/conformance/baseline-view.txt. - Games on the test backend (
Tests/RedViewTests/GamesOnTestBackendTests.swift): tictactoe’s window builds (13 faces, 3x3 grid of 100x100 buttons) and a game played throughdo-actorends in “Player O won!” with the winning squares red; Othello’s window builds (64 squares), reactions drive status, counts and stones, a click flips stones, and the button row follows its reactor. - Tests:
swift test→ 26 passed. - M3 complete.
Rulings
- Ruling: the Draw parser/validator moves from M3 to M5, next to the renderer —
draw-parse-test.redstays at 71% until then — cost if wrong: an invalid Draw block is accepted silently for now. - Ruling:
base-self-test.redis not in the M3 list (the plan has it in M6). - Ruling: compiled-body mode is decided per block by a flag set at load time on vendored function bodies (and their nested blocks), not by analysing which natives the compiler would inline — cost if wrong: a vendored function that passes a data block containing a local function call to something other than
do/do-safewould not call it; none found so far. - Ruling:
Package.swifttargets macOS 15 — typed-throws function types need its runtime.
M4 — AppKit backend
AppKitBackend.swift: windows (flipped content view, close button sends acloseevent, flagsresize/no-title/no-border),base-family faces as a custom flipped view (colour, centred text),button/toggle/check/radioasNSButton(rounded bezel when VID’s rules assigned a size class, square otherwise; font colour through the attributed title),textandfieldasNSTextField. Fonts scale by 94/72 as upstream. (The light appearance was forced here; since the “Appearance” section below, windows follow the system.)- Events reach Red through
system/view/awake(send): click, down, up, dbl-click, alt-down/up, wheel, change, enter, close, time.ratefacets drive timers. Destroying a window posts the quit message that ends the innermost loop, so nestedviewcalls andunviewbehave as upstream. waitsleeps and then pumps one pass, anddo-events/no-waitruns one pass, as upstream’s macOS backend.- CLI options for scripted checks:
--headless(windows built and drawn, never shown),--snapshot file.png --after seconds, and--events "click X,Y; wait S; ..."which posts real mouse events into the window. - Verified with
tictactoe.redunmodified, in a real window with real mouse events: a click on the centre square shows O; “Computer Move” answers with X; a second press plays both sides to “It’s a tie!” with the half-second animation; “Again?” closes the window and opens a fresh game; “Quit” exits with status 0. Screenshots were inspected for each step. Commands:red --events "click 170,210; wait 0.5; click 70,405; wait 1.5; click 70,405" --snapshot out.png --after 8 tictactoe.red
- Observed upstream quirk (reproduced faithfully, not a bug here): the macOS
Cancel-OKrule swaps the OK button with whichever face is last in the window, not with the Cancel button, when other faces follow the buttons. - Tests:
swift test→ 27 passed (adds a headless render of the tictactoe window). - M4 complete.
Rulings
- Ruling: scripted clicks need the window on screen — AppKit drops mouse events sent to a window that was never ordered in — so
--eventsruns are not headless; the automated test covers rendering only, and the click path is verified by the command above. - Ruling: the snapshot is taken with a CLI option rather than
to-image/savefor now (image codecs are M8).
M5 — Draw and Othello
Draw.swift:DrawParserturns a Draw block intoDrawOpvalues (validation without a graphics context; errors areinvalid-drawas upstream), andDrawRendererexecutes them with CoreGraphics. Commands:pen fill-pen line-width line-join line-cap anti-alias line box triangle polygon circle ellipse arc curve spline text font image push translate scale rotate skew matrix reset-matrix clip, named colours and hex issues, nested blocks, scoped transforms.drawonto animage!renders into its pixels.image!:make image! 40x40,[size colour],/size /rgb /alpha /argb, pixel access by index or pair.- Verified with
othello.redunmodified in a real window: the board, stones, status line and counts render; a scripted click on square 20 places a white stone and flips one; the computer replies through itsrate 10timer and iterative-deepening search; and with both sides set to Computer a full game runs to “White wins 50 to 14” with all 64 squares filled. Screenshots inspected.red --events "click 288,282" --snapshot out.png --after 4.5 othello.redred --events "click 90,740" --snapshot out.png --after 135 othello.red
- Performance pass: release builds of
RedCoredrop dynamic exclusivity checks (-enforce-exclusivity=unchecked), which the evaluator’s constant indexing of its value stack paid for heavily. fib 27: 0.71 s → 0.23 s. Othellolast-depthafter 1 s from the opening: 8 (M2 figure: 6). - Upstream headless View tests: 278/279 (99.6%).
- Tests:
swift test→ 27 passed. - M5 complete: both sample programs run unmodified.
Rulings
- Ruling: the renderer executes
DrawOpvalues directly instead of going through aDrawSinkprotocol — there is one renderer, used for both views and images — cost if wrong: a second sink later means extracting the protocol then. - Ruling: Draw gradients, pattern and bitmap pens,
shadow,shape,transform,invert-matrixandline-patternare not parsed yet (M8); a block using them raisesinvalid-draw.
REPL (brought forward from M7)
Sources/red/REPL.swift: a reader thread owns the terminal through libedit (CEditLinesystem-library target: line editing and history) and hands lines to the main thread viaLineMailboxand a posted wake-up event. The main thread runs the AppKit loop while it waits, so a window opened withview/no-waitstays live at the prompt.- Multi-line input continues while a bracket, paren or brace is open, with upstream’s continuation prompts; results print as
== value, cut to the terminal width with...; errors print in console format. - View is loaded at console start; console words
q pwd cd ls dir. - Checked by piping input: expressions, a multi-line function, an error,
help first,view/no-wait [...]followed by reading the window’s faces andunview. - Not yet done from M7’s REPL list: Ctrl-C to halt a running evaluation.
M6 — general GUI apps
- Widgets (
Widgets.swift):area(NSTextViewin a scroll view),text-list(NSTableView),drop-list(NSPopUpButton),drop-down(NSComboBox),slider,progress,scroller,calendar(NSDatePicker),tab-panel(segmented control over the panes),group-box(drawn frame and title), password fields and field hints,imagefacet painting.textfaces report clicks. Button titles use nearly the full button width (RedButtonCell), because VID sizes buttons for the narrower bezel insets of older macOS. - Events (
Input.swift):key-down/key/key-upwith chars or key words,overon enter/leave (every move forall-overand draggable faces),focus/unfocus,change/select/enterfrom the widgets, windowmove/resize/resizingwith offset and size written back, focus fromwindow/selected(set-focus). - Menus: a window’s
menublock becomes menu-bar items, other faces get context menus; picking sends amenuevent with the id. - Dialogs:
alert(upstream’s VID modal, nested loop),request-fileandrequest-dir(native panels). - User scripts:
#if/#either/#switch config/...,#include(from disk, relative to the script),#doand#do keepare resolved;expand-directivesexists so upstream’sdo %fileworks; a script runs with its own folder as the current directory. - Scripted input for checks:
--eventsalso takestype text(\nfor Return),drag x1,y1 x2,y2andmenu id; input and snapshots act on the newest window. - Verified with real input (
click/type/drag/menuevents, output read back): check, radio, field typing with change and enter, slider, list selection, tab switching and a button inside the second tab, key events on a base face afterset-focus, a button relabelling itself, a text face’s click actor, alooseface dragged by exactly the drag distance (on-drop), a window resized from Red firingon-resize,alertopened and dismissed, menu items including a nested one, andunviewfrom a button. - Demo scripts from
red/testsrun without errors and were captured headlessly:vid.red…vid6.red,react-test.red…react-test6.red,modal.red,tabbing.red,dyn-gui.red,events-flow.red,view-test.red(950 lines: lists, area, tabs, calendar, a Draw canvas),matrix-test.red,shield.red,font-weight-demo.red.demo.redis a console script and prints its ASCII art. I inspected the screenshots ofvid.red,vid2.redandview-test.red. - Tests:
swift test→ 27 passed; upstream headless View tests 278/279. - M6 complete.
Rulings
- Ruling:
base-self-test.redis dropped from the M6 gate — upstream wraps the whole file insystem/platform = 'Windows(“currently these tests are hopeless on MacOS”), so nothing in it runs here. - Ruling:
tab-panelandgroup-boxare custom views rather thanNSTabView/NSBox— Red positions their children relative to the face, which those AppKit containers would offset — cost if wrong: they look slightly less native. - Ruling: upstream’s macOS path creates a tab-panel’s panes before the tab-panel itself; the backend adopts the already-made pane views when the tab-panel is created.
- Ruling: pointing at a real menu or an open drop-list was not scripted (they run a modal tracking loop that swallows the posted events); menus were checked by picking items by id, drop-lists by rendering only. Hover (
over) and the file/folder panels were not exercised. - Not done from the M6 list:
request-font,camera, live key events insidefield/area(they reportchange,enter,focus,unfocus), window flagsmodal/popup/no-min/no-maxbeyond title and resize.
M7 — general CLI apps
vector!as a typed series (brought forward from M8 because the append/insert/change tests need it).- Series semantics from upstream’s tests:
index?reports the stored position of a past-tail series,/partrules for strings and binaries, paths are spliced like blocks,reverse/skip,copy/partwith a pair,copy/deepreportsno-cycle,find/matchreturns the match position,find/sameon strings is case-sensitive, string-like values of different types compare equal by text. - Dates:
make date!from every block form (time or h/m/s, zone as time or h/m), settingweekday,weekandisoweek. - Codecs (
Codecs.swift):checksum(CRC32, adler32, TCP, MD5, SHA1/256/384/512, HMAC with/with),enbase/debase(64, 58, 16, 2, with comments),compress/decompress(gzip, zlib, deflate). Upstream’sJSON.redandCSV.redare loaded;load/savepick them by file suffix. - Preprocessor: upstream’s
utils/preprocessor.ris loaded, so user scripts get#macro,#do,#if/#either/#switch/#case,#includeand#processexactly as upstream;system/build/configcarriesOS,target,GUI-engine,modules. - Compiled-body mode refined: a block evaluated by
dois interpreted even when it sits in a vendored function (upstream’scollectrebindingkeeprelies on that), until the next function call. - Console and processes (
NativesProcess.swift):ask(/hide),input,callwith/wait /output /error /input /shell /console,browse,query,rename;system/options/argsandsystem/script/args;quit/returnsets the exit status. - Network:
readandwriteonhttp(s)URLs with/binary /lines /info, andwrite url [METHOD [headers] body]. - Clipboard:
read-clipboard,write-clipboard. - REPL: Ctrl-C halts a running evaluation.
- Checks:
Tests/fixtures/cli.redrun byswift testwith arguments and piped input (args,ask,callexit code/stdout/stderr/stdin pipe, JSON and CSV round trips, line files, append, directories, delete, SHA-256, base64, gzip, env, exit status 7);Tests/fixtures/macro.redfor macros;read/info https://example.comreturned status 200 when tried by hand (not in the automated tests, which stay offline). - Conformance: the baseline now covers 57 unit files. M7 list: series 91.5, append 89.6, insert 95.3, change 91.7, find 94.3, select 100, replace 90.2, move 86.0, mold 85.2, load 91.1, convert 90.8, date 95.6, file 100, url 100, serialization 94.1, json 89.4, csv 100, checksum 90.4, debase 100, enbase 100, preprocessor 100, clipboard 100;
functions-test.red95.7. - Tests:
swift test→ 29 passed. - M7 complete.
Rulings
- Ruling:
decompress-test.redstays at 70.7% — the rest is Zstandard, which macOS does not ship a public library for — cost if wrong: a script usingcompress/decompresswith'zstdgets an error. - Ruling:
askandinputread plain lines (no line editing inside a running script); at the REPL prompt libedit still applies. - Ruling: Ctrl-C at an idle prompt is not handled specially (it sets the halt flag, which the next evaluation clears).
- Ruling: a compiler crash in Swift 6.4 (a typed-throw closure assigned directly into a dictionary) is avoided by registering routines through a helper function.
M8 — full Draw, images, rich-text, vector, money
- Draw (
Draw.swift): linear/radial/diamond gradients forpenandfill-pen(stops, explicit points, radius, focal point),patternpens drawn from a Draw block andbitmappens from an image (tile, flip-x, flip-y, flip-xy), the pen-targeted matrix forms (rotate 'fill-pen,scale 'pen,translate,skew,matrix,reset-matrix,invert-matrix), the wholeshapesub-dialect (move, line, hline, vline, arc with sweep/large, curve, curv, qcurve, qcurv, close, and the relative lit-word forms),shadow,line-pattern,clipto a shape,transform,invert-matrix, fontunderline/strikeand the newweightfacet (sharedFontSupport). A face clips its painting to its own bounds. on-drawing: a face with that actor and no draw block gets adrawingevent while it paints;system/view/platform/draw-facerenders into it.image!(ImageOps.swift) is now a series like upstream’s: integer and pair indexing,next/back/skip/at/head/tail,pick/poke,copyandcopy/part(pair or image),change,foreach,/size /rgb /alpha /argb(readable and settable),make image! [size rgb alpha], upstream’s mold layout. Codecs through ImageIO: PNG, JPEG, GIF, BMP, TIFF, registered insystem/codecswith upstream’s names and suffixes, soload %x.png,load/as bin 'png,save %x.gif imgandsave/as #{} img 'pngwork.- Rich-text (
RichText.swift, TextKit): faces of typerich-textwith styles fromdata(ranges, bold, italic, underline, strike, colours, backdrop, font name and size),rtd-layout,text pos <box>in Draw, andtext-box-metricsbehindsize-text,caret-to-offset,offset-to-caret,offset-to-char,rich-text/line-height?andline-count?. - Upstream’s own colour picker (
request-color.red) now runs: function bodies inside a vendoreddo [...]block are interpreted, not treated as compiled. - View is loaded for every script, with or without
Needs: Viewin the header, as in upstream’s console (about 20 ms; no window system is touched until a window is shown). Conformance files that look atsystem/viewget it too. vector!(VectorOps.swift): elements are truncated to the element width, vector-with-vector maths makes a new vector, vector-with-scalar maths changes it in place,and/or/xor, ordering, path access, strictfind.money!(Money.swift) rebuilt on exact 128-bit decimal arithmetic followingmoney.reds: currencies checked againstsystem/locale/currencies/list, add/subtract/multiply/divide/remainder with upstream’s overflow and type rules, float operands clipped to five digits,roundin every mode, comparisons with numbers,sortorder, strictfind,to/makein every form,as-money, accessors,form(grouped) vsmoldvsmold/all,system/options/money-digits.point2D!/point3D!:reverse, accessors,make point3D!, scalar-first maths, tolerant equality,round/towith a point scale,min/max,absolute.- Owner events:
on-deep-change*is handed the value given toappend/insert, as upstream (it got a block of the inserted values before); the currency list’s own guard depends on it. - Checks: the demo scripts
draw.red,shape-test.red,clip-test.red,matrix-test.red,shield.red,font-weight-demo.red,select-text.redand all pages ofcomplexpen-test.redreached by real clicks were run and their screenshots inspected;request-colorand a rich-text sample likewise. - Conformance: baseline now covers 63 unit files. M8 list: image 100 (87/87), draw 100 (19/19), vector 100 (338/338), money 100 (1032/1032), points 100 (164/164), pair 94.7.
- Tests:
swift test→ 29 passed. - M8 complete.
Rulings
- Ruling:
hash!keeps its linear search (no index) — every result is the same as with an index and no test depends on the speed; an index that every direct buffer write must keep in step is a risk I did not take — cost if wrong: lookups in very large hashes are slow. - Ruling: gradient pens follow upstream’s macOS backend exactly: the pen matrix moves the gradient’s points about the origin and the spread word (
repeat,reflect) is accepted but drawn aspad; adiamondgradient is drawn as radial — cost if wrong: such gradients look different from Red on Windows. - Ruling:
request-color/nativereports “cancelled” (none); the default picker is upstream’s own Red dialog, which works — cost if wrong: no system colour panel. - Ruling: comparing money with a float that has more than five fractional digits is ordered by value instead of raising upstream’s error — cost if wrong: a script that relies on that error does not get it.
- Ruling: the screenshot helper now paints the window’s background under the content (it was transparent before, which some viewers show as black).
M9 — hardening, do/trace, profiling
do/trace: the evaluator reports upstream’s events (init end enter exit fetch push open call return prolog epilog set expr error throw) with code, offset, value and reference; paths report their own steps; vendored (upstream-compiled) function bodies stay silent, as in real Red. Upstream’senvironment/tools.redis loaded, sotrace,trace/deep,trace/all,trace/raw,profileanddebugwork as written upstream. Tracing costs nothing when off (fib 27 unchanged at 0.22 s).applyrewritten to upstream’s dialect: inline/ref flag args,apply/all,apply/safer, dynamic refinements in a path.setchecks everything before it assigns (unset values, bad targets), also for objects and maps.trim(strings, binaries, blocks) andsortfollow upstream’s code line by line; the default sort is a port of upstream’s own unstable quicksort (Sort.swift), so elements that compare equal come out in the same order as in real Red;/stableis a merge sort.map!has a hash index (300,000 inserts: 0.16 s; it was quadratic).unique,union,intersect,difference,excludeare hashed too, and compare the characters of strings without case unless/case.- Series primitives no longer trust an index across an
on-deep-change*handler (a handler that shrinks the series could crash the interpreter). /partonappend/insertselects a stretch of the value (count, negative count, or a position in it);change/partwith a negative range;/dupwith an impossible count is an error.movefollows upstream (forward moves land after the target element);formof a block puts a space after every element as upstream; pathformforms its elements;caseevaluates a non-block branch; pair arithmetic that overflows or does not divide exactly gives apoint2D!; time compares with numbers;nowrefuses meaningless refinement pairs;read/seek,read/part,write/seek,write/part;remove-eachreturns the series;do/nextkeeps the series type;parse’skeep copy; file and URL paths join with one slash;min/maxwith NaN.- Whole unit suite (
tests/source/units, 65 files): 95.1% of 16,721 assertions (it was 94.6% of 15,730 with one file not finishing). 64 files are in the ratcheting baseline. Files under 95%, and why:redbin-codec-test(not run): Redbin is a compiler format, out of scope.decompress-test70.7: Zstandard.system-test80 (4/5): one platform check.mold-test85.2:mold/partlayouts for object, vector, hash, image, binary, error.try-test87.8:try/keepstack traces.object-test87.9:copy/types, ordering objects with<, someon-change*re-entrancy cases.lexer-test88.4:transcode/traceevents, raw strings in some forms, a few error positions.json-test89.4,map-test89.5,replace-test90.2,checksum-test90.4,convert-test90.8,load-test91.1: scattered single cases (not grouped by one cause).regression-test-red91.4: Redbin cases, GC and memory statistics, compiler-only checks, plus a tail of single behaviours.parse-test93.7:parse/trace, position get-words afterchange/insert/remove, somecollectforms.evaluation-test94.0: the raw trace tests compare upstream’s internal stack-frame sizes.series-test95.2,change-test95.4,insert-test97.6,append-test98.2:copy/types,takeon hash with a negative part, a few/partcorner cases.
- Speed: fib 27 in 0.22 s (release). Start-up: 20 ms for
red -e, about 70 ms for a script (View is always loaded, see M8), under the 150 ms target. - Tests:
swift test→ 29 passed. - M9 complete.
Rulings
- Ruling: the raw
do/tracetests (trace-1…trace-11) stay failing — they compare the size of upstream’s own evaluation stack frame at each event, which only upstream’s stack layout can produce; the events, offsets, values and references match, and upstream’strace/profile/debugtools run on them — cost if wrong: a custom tracer that readsframe/y - frame/xsees different numbers (here: block nesting depth and values pushed). - Ruling:
copy/typesis not implemented (the refinement is accepted and ignored) — it is recent and I found no script using it — cost if wrong: such a copy shares the nested series it was meant to copy. - Ruling:
hash!still has no index (see M8);map!has one. - Ruling:
/dupcounts above about 268 million elements raiseno-memoryinstead of being attempted.
Final review (whole branch, fresh reviewer)
A reviewer with no part in the work read the branch, tried about a thousand hostile inputs and reproduced every finding below. All Critical and Important findings were fixed in one pass; each has a test in Tests/RedCoreTests/ReviewTests.swift that failed before the fix (12 tests, 40 failing checks) and passes now. Suite after the pass: swift test → 41 passed.
- Final: fixed
deleteremoving a whole folder tree (now one file or one empty folder, as upstream) —deleteRefusesANonEmptyFolderRED→GREEN. - Final: fixed
=on objects or maps that refer to each other crashing the process —cyclicObjectsAndMapsCompareRED→GREEN. - Final: fixed
write/lineswith a single value writing no line break —writeLinesEndsASingleValueWithANewlineRED→GREEN. - Final: fixed user errors (
do make error! "boom") printing an empty message —userErrorsShowTheirMessageRED→GREEN. - Final: fixed an error or throw raised inside a
do/tracecallback losing its value, andthrowevents not being reported after an earlier traced throw —traceCallbackErrorsAndThrowsKeepTheirPayloadRED→GREEN. - Final: fixed
callalways going through the shell (now words are run directly unless/shell, as upstream) and a deadlock when feeding large input —callWithoutShellDoesNotInterpretShellSyntaxAndTakesLargeInputRED→GREEN.Tests/fixtures/cli.rednow sayscall/shellwhere it uses;. - Final: fixed crashes when user code shrinks a series in the middle of
sort/compare,reverseorrandom—seriesSurviveBeingShrunkByUserCodeMidOperationRED→GREEN. - Final: fixed
changedestroying the data when the value is the series itself, or when the value is rejected —changeWithTheSeriesItselfKeepsTheDataRED→GREEN. - Final: fixed binary map keys not being copied —
binaryMapKeysAreCopiedRED→GREEN. - Final: fixed
forallandremove-eachrefusingbinary!,vector!(andforallonimage!) —forallAndRemoveEachTakeEverySeriesRED→GREEN. - Final: fixed process-killing traps on out-of-range numbers (
even?/odd?on huge or non-finite floats, time and date fields,absoluteon a pair, char vector maths,make vector!/make image!with absurd sizes, a non-finite Draw pattern size) —outOfRangeNumbersRaiseErrorsInsteadOfTrappingRED→GREEN (17 cases). - Final: fixed
changeon an image with an empty image returning a position before the head —imageChangeWithAnEmptyImageStaysInRangeRED→GREEN. -
Final: fixed Ctrl-C at the prompt during a blocking
viewleaving every later event handler dead: the halt now ends that event loop and returns to the prompt with the window still live; an error in an event handler no longer resets the evaluation stack under theviewthat is running. Checked by hand with the reviewer’s reproduction (SIGINT during a timer-driven window:(halted), the next lines run, the timer keeps counting); no automated test, since it needs a signal sent to a live REPL. - Final: minor (deferred): degenerate counts hang instead of failing fast (
append/dup [] [] 2147483647,new-line/skipwith a huge skip,to-hex/size 255 2147483647,make bitset! 2147483647;1 ** 2000000000takes 7 s). - Final: minor (deferred): blocks nested about 20,000 deep overflow the stack in
mold,loadand=(5,000 is fine). - Final: minor (deferred):
select/caseon a map ignores/case. - Final: minor (deferred):
swapandputcan place a value of the wrong type into a vector. - Final: minor (deferred):
on-deep-change*is not called for in-place changes to strings (reverse,sort,random,swap,trim,uppercase), for any binary change, or forswap/trimon blocks — souppercase face/textdoes not refresh a face. - Final: minor (deferred):
do/traceon a file or URL returns the value unevaluated (upstream’s own tools go throughdo-file, which works). - Final: minor (deferred):
round/to 2147483647 10wraps around instead of promoting to float. - Final: minor (deferred):
make-diron a path that is an existing file reports success. - Final: minor (deferred):
readof a file that is not valid UTF-8 substitutes U+FFFD instead of raising upstream’s error. - Final: minor (deferred): the conformance floors compare a pass rate rounded to 0.1%, so a file can lose one to four assertions unnoticed (and a new pass can hide a new failure).
- Final: minor (deferred): two game tests depend on line numbers and a marker in the sample scripts.
- Final: minor (deferred): by reading only —
random -2147483648can trap once in 2³¹ calls; a Mac with no display attached would trap inscreens()[0]; loops that run entirely inside a native (parse "aaa" [while []]) cannot be stopped with Ctrl-C.
Rulings
- Final: Ruling: set operations treat
1and1.0(and1x1and(1, 1)) as different members although=calls them equal — values of different types never share a hash bucket; I believe upstream’s hashed sets behave the same but did not confirm it — cost if wrong:unique [1 1.0]keeps both where real Red would keep one. - Final: Ruling: recursion is limited to 3,000 nested calls counting natives, about 1,500 levels of a recursive Red function — deeper needs a larger native stack — cost if wrong: a deeply recursive script reports
stack overflowhere that might still run on real Red. - Final: Ruling:
findon a map returns the stored key itself, so changing it in place loses the entry — same hazard as upstream, as far as I can tell. - Final: Ruling:
refinement!andissue!keys match word keys of the same spelling in a map — kept; cost if wrong: two keys real Red keeps apart collide here. - Final: Ruling:
sort/stable/comparewith a<=comparator is not stable — this follows upstream’s mapping of a logic result (true means “greater”). - Final: Ruling: removing keys from a map inside
foreachover that map can skip entries — left as is. - Final: Ruling: GIF encoding goes through the system encoder, whose palette can round very dark colours to black.
- Final: Ruling:
haltin a script ends it with status 0, as upstream’s non-console definition does. - Final: Ruling:
do/tracewith a callback that is not a function evaluates untraced instead of raising an error. - Final: Ruling:
RED_BOOT_DIR(the developer switch that loads the boot sources from a folder) stays; it runs whatever that folder holds — cost if wrong: none unless someone sets that variable for you. - Final: Ruling:
callwithout/shellreports “cannot parse” and returns 255 when the command uses shell operators, where upstream prints its own message from the child and exits with -1 — same outcome, different wording. - Final: Ruling: images are limited to 100 million pixels and vectors to about 268 million elements; a bigger request raises
no-memory.
Rulings (REPL step)
- Ruling:
appendreturns the head of the series, as upstream’s doc string says andclean-pathrelies on (it returned the given position before;cdbroke on it). - Known gap for M7:
append-test.redis at 44% andseries-test.reddoes not complete; neither is in a baseline yet.
Appearance (dark mode), 2026-12-03
Asked for after the milestones: windows stayed light on a Mac in dark mode.
- Windows now follow the system appearance.
red --appearance light|dark|auto file.redorRED_APPEARANCE=light|darkoverrides it. AppKitBackend.ink(_:): text and Draw lines with no colour of their own are black (Red’s default) wherever the script painted a background, on the face or anything it sits in, and follow the system label colour elsewhere.AppKitBackend.tone(_:_:): a face with its owncolorkeeps the light look for everything inside it (control bezels, default text). So a window with abackdrophas a dark title bar and its content as the script coloured it.- Tests:
windowsFollowTheRequestedAppearance,textOnAScriptsOwnBackgroundStaysBlackInDarkMode,defaultDrawPenIsVisibleInDarkMode(RED→GREEN, suite 44/44). - Ruling: on the system’s dark background, default text and the default Draw pen are light, not Red’s black — black on dark grey would be unreadable — costs: a script that relies on the default pen being exactly black on an uncoloured face draws light lines in dark mode;
--appearance lightgives upstream’s look. - Ruling:
drawonto animage!keeps the black default pen in every appearance — an image has no background to follow — costs nothing known. - Not checked: the title bar itself in a screenshot (screen capture is not permitted from this session); the content was checked from snapshots in both appearances.
Console syntax highlighting, 2026-12-03
Asked for after publication: colour the console’s input the way Red’s VS Code extension colours a file.
SyntaxHighlighter.swift(RedCore): a tolerant tokeniser, separate from the real lexer because it must never fail on half-typed input and must run off the main thread. Categories follow the extension’s TextMate grammar (Red.tmLanguage.json): comments (alsocomment {...}/comment [...]), strings and their relatives, files/URLs/emails, numbers of every shape, set-/get-/lit-words, refinements and path parts, datatypes, the script header, stray closing brackets and commas. Words are coloured by what they are bound to (Interpreter.wordClasses(), re-read after every evaluation), not from a fixed list.LineEditor.swift(RedCore): replaces libedit, which cannot colour input. Cursor and word movement, kill/yank, transpose, history with Ctrl-R search, Ctrl-L, Ctrl-Z, redraw on every change with wrapping worked out per character (wide characters and emoji count two columns). Talks to the terminal only throughLineEditor.IO, so tests drive it against a small terminal emulator.Terminal.swift(red): raw mode only while a line is being typed, restored on every exit path (atexitand fatal signals); a running script gets the normal terminal.- Console: the
== resultline is coloured too; Ctrl-C at the prompt now drops a half-typed expression and stops a window handler that runs away while the prompt waits; a prompt after output with no final newline starts on its own row with a%mark.CEditLineis gone. - Tests: 13 highlighter tests, 19 editor tests (suite 76/76). Checked against the real binary through a pseudo-terminal: colours, continuation lines, history,
askin normal terminal mode,NO_COLOR, quit from a window handler, SIGTERM, Ctrl-Z andfgunder zsh, a 50-character line at 30 columns. - Ruling: the terminal’s eight basic colours and “faint” for comments, not VS Code’s palette — the terminal’s background is unknown, and the bright colours are greys in some themes — costs: shades differ from VS Code; faint text is terminal-dependent.
- Ruling: the parse keywords the VS Code grammar colours everywhere (
thru,some,end, …) are not coloured — outside a parse rule they are ordinary words — costs: parse rules look plainer than in VS Code. - Ruling: operators bound to an
op!(+,=) take the function colour, since colouring follows the binding. - Ruling: history is still kept per typed line and only for the session, as it was with libedit; Tab inserts four spaces (no completion).
- Not done: bracket matching, completion, a history file; output printed by a window handler while a line is being typed still lands in the middle of that line (as before).