This post was translated from Chinese by DeepSeek V4.1. Original (Chinese): https://zhuanlan.zhihu.com/p/2109720909967840645
the guile_cpp code is https://github.com/PikachuHy/guile_cpp
the texmacs compat code is https://github.com/PikachuHy/texmacs_upsilon/tree/guile_cpp_dev
I recently started using Google Neon and tried having it write code for me. My conclusion from the experience: it is very strong at writing code. It puts its head down and works, without much chatter, and then gives a good answer.
I used Google Neon to rewrite guile 1.8.8 in C++, and then to get TeXmacs running on the Mac.
Here is what I tried.
Converting the C code of guile 1.8.8 to C++. The prompt I gave was very simple:
Rewrite guile 1.8.8 in C++
The guile 1.8.8 source is at /Users/xxx/code/guile
I did not expect it to work so surprisingly well. A single goal nearly used up my $20 / 5-hour quota. The functionality was largely finished, but performance was not great.
Performance of the first attempt (original → rewrite; the figure is how many times slower):
-
Cold startup (
-q -c '(exit 0)', average of 10 runs): original 13.4 ms → rewrite 63.5 ms (4.7x slower) -
call/cc, 20,000 captures + escapes: original 70 ms → rewrite 700 ms (10.0x slower) -
Bignum factorial
3000!(GMP binding): original 10 ms → rewrite 120 ms (12.0x slower) -
Official test subset (
numbers+srfi-1+goops): original 227 ms → rewrite 8,114 ms (35.7x slower) - GOOPS generic dispatch (20,000 calls): original 10 ms → rewrite 970 ms (97x slower)
-
fib(28), recursive: original 110 ms → rewrite 17,960 ms (163x slower) -
List construction + reversal (
500knodes + GC): original 60 ms → rewrite 11,690 ms (195x slower) -
Tail-recursive idle loop (
1,000,000iterations): original 100 ms → rewrite 21,320 ms (213x slower) - Hash table (50k insertions + 50k lookups): original 10 ms → rewrite 3,000 ms (300x slower)
So I wrote a second prompt to have it tune performance. The second prompt was also very simple:
Match the performance of the original guile 1.8.8
That nearly used up my $20 / 5-hour quota again too, and performance went up right away. The main optimization was adding a bytecode VM
Performance after optimization (original → before → after; the last figure is the speedup over the original):
-
Cold startup (
-q -c '(exit 0)'): 7.76 ms → 63.5 ms → 8.14 ms (~1.0x, roughly on par) -
fib(28)(recursive fixnum): 66.12 ms → 17,960 ms → 10.32 ms (6.41x faster) -
tail-loop(1M)(named-letloop): 77.51 ms → 21,320 ms → 12.64 ms (6.13x faster) -
cons+reverse(500k)(allocation + GC): 62.37 ms → 11,690 ms → 18.18 ms (3.43x faster) -
bignum-fact(3000)(GMP factorial): 0.94 ms → 120 ms → 0.80 ms (1.17x faster) -
hashtab(50k+50k)(hashv-set!/ref): 20.14 ms → 3,000 ms → 4.54 ms (4.44x faster) -
call/cc(20k)(continuation capture and invocation): 145.84 ms → 700 ms → 1.68 ms (86.76x faster) -
goops-dispatch(20k)(60k generic dispatches): 2.20 ms → 970 ms → 1.17 ms (1.87x faster) -
Official test suite (
numbers+srfi-1+goops): 179.68 ms → 8,114 ms → 178.95 ms (1.00x, on par / slightly faster)
After that I chased a few more, mainly benchmarking against Chez. Its main change was adding a JIT. I cannot make heads or tails of the instructions in the JIT part, so I will not comment on it.
Against Chez Scheme (no-JIT → JIT → Chez; then how each build compares with Chez, and the JIT’s gain over no-JIT):
- tak.scm: 4,349.16 ms → 263.00 ms → 471.19 ms · no-JIT 9.23x slower than Chez, JIT 1.79x faster than Chez · JIT is 16.54x faster than no-JIT
- cpstak.scm: 2,742.39 ms → 142.73 ms → 186.21 ms · no-JIT 14.73x slower than Chez, JIT 1.30x faster than Chez · JIT is 19.21x faster than no-JIT
- nqueens.scm: 1,561.69 ms → 180.83 ms → 253.83 ms · no-JIT 6.15x slower than Chez, JIT 1.40x faster than Chez · JIT is 8.64x faster than no-JIT
- sieve.scm: 143.58 ms → 24.41 ms → 56.25 ms · no-JIT 2.55x slower than Chez, JIT 2.30x faster than Chez · JIT is 5.88x faster than no-JIT
- spectral-norm.scm: 35.61 ms → 14.86 ms → 54.18 ms · no-JIT 1.52x faster than Chez, JIT 3.65x faster than Chez · JIT is 2.40x faster than no-JIT
- dynamic.scm: 44.92 ms → 48.20 ms → 51.88 ms · no-JIT 1.15x faster than Chez, JIT 1.08x faster than Chez · JIT is 0.93x of no-JIT
- boyer.scm: 26.87 ms → 23.41 ms → 45.53 ms · no-JIT 1.69x faster than Chez, JIT 1.94x faster than Chez · JIT is 1.15x faster than no-JIT
Background
TeXmacs is an ancient project. I first picked it up for its live formula editing. I was doing deep learning and needed to write formulas. I even went as far as patching TeXmacs itself so it would start up under Qt6. I never did manage to get a grip on their development process, though, and that attempt quietly died too.
A while ago I saw TeXmacs Upsilon: an enhanced, bleeding-edge TeXmacs to try and was stunned that such a large amount of work had been completed. Then I saw that chez could get TeXmacs running: TeXmacs Chez port (BETA). That suddenly reminded me of a Scheme interpreter I had worked on before.
I remember first sharing my toy Scheme interpreter (pscm, PikachuHy’s Scheme) in What’s the status of the new scheme on TeXmacs? Also, what is the status of the new release?. Its goal was to get TeXmacs running. At the time there was another goal: to build TeXmacs on Windows with MSVC. The very first step got stuck on the Scheme interpreter. I tried compiling guile 1.8.8 with MSVC and did not succeed; that branch is still around, on the guile 1.8.8 msvc branch. I remember it depended on longjmp, and MSVC does not have that function. On top of that, guile’s code is not very pleasant to read: lots of macros, plus some odd characters. Whether in VS Code or CLion, it was especially painful.
Later I thought, why not just write an interpreter myself. So I found a version on GitHub, PicoScheme, and started modifying it bit by bit. I remember there was a call/cc feature whose implementation I simply could not figure out no matter how much I thought about it. Honestly, even today I do not really understand that feature; I only have a general idea of how it works. And there was the even more terrifying dynamic-wind. Put those two together, and back then, while writing the interpreter, it was a nightmare.
I wrote code for this interpreter on and off over a long period. A fairly milestone-worthy event was getting vau running, details in Run Vau success with pscm. But when it came to running TeXmacs, there were always bugs of every kind. Debugging was extremely painful. TeXmacs has a lot of macros, and the code got transformed into something unrecognizable. When something went wrong, I had no idea where the problem was. Later I did not have much time, and I gave up on the whole thing.
Meaning and the Future
While thinking about this article I thought about a lot of things, but when it came time to actually write it down, it seems I did not write much.
Google Neon completed in a single afternoon what I had wanted to complete for years. I was shocked, and I also began to doubt the behavior of staying up until midnight debugging Scheme interpreter bugs in the past; these things look so laughable and incompetent in the face of today’s powerful AI coding ability. I do not know what to say, or perhaps there is nothing to say.
As for the Scheme interpreter: I have not changed a single line of the guile_cpp code, and I have not even read it line by line; I have only read part of it.
the guile_cpp’s positioning is simply a C++ rewrite of guile 1.8.8, serving TeXmacs. Going forward it will only get compatibility enhancements and bug fixes. If I can find some old antique projects that use guile 1.8.8, I can run their tests against it too.
pscm will be replaced with this version of guile_cpp. Later, if I have time, I can look into r7rs: drop guile’s distinctive features and implement standard r7rs instead.
Appendix
Results of the first prompt
Completed the **C++20 rewrite** of **GNU Guile 1.8.8**. The project is located at `/Users/xxx/code/scheme_guile_cpp`.
### Core implementation overview
- **Code size**: 34 C++20 source files + 3 core headers, about **20,356 lines of C++20 code** in total, compiling with `-Wall -Wextra` with **zero warnings** (build configuration in CMakeLists.txt, full architecture and usage in README.md).
- **Core runtime**:
- 64-bit tagged `SCM` value system and object model: scm.hpp, vm.hpp
- Mark-sweep GC (conservative stack scanning, weak tables/weak vectors, Guardians, weak environment observers): gc.cpp
- **CEK virtual machine** with heap-allocated continuation frames (genuine O(1)-stack tail recursion, multi-shot `call/cc`, `dynamic-wind`, `catch`/`lazy-catch`/`with-throw-handler`, multiple values via `values`, Fluids, R5RS/SRFI-61 syntax validation, `defmacro` + `ice-9/syncase` hygienic macros): eval.cpp, fluids.cpp
- Complete numerical tower (Fixnum, GMP Bignum, Fraction rationals, exact IEEE 754 rounding, complex numbers, continued-fraction `rationalize`, bases 2–36): numbers.cpp
- Complete **GOOPS** object-oriented runtime (26-slot class layout, metaclasses, method-cache dispatch, dynamic class redefinition `%modify-class`/`%modify-instance`, `change-class`, primitive generic dispatch): goops.cpp, struct.cpp
- Module system and first-class environments (`leaf`/`eval`/`import`/`export-environment`, plus strong/weak observers): modules.cpp, environments.cpp
- Fully bootstraps the original Guile 1.8.8's `ice-9/boot-9.scm`, `ice-9/*`, `oop/goops` and `srfi/*`, and provides the standard `guile` CLI and REPL (main.cpp).
### Verification results
1. **Compilation check**: `cmake --build build --clean-first -j8` builds all 38 targets with **0 warnings, 0 errors**.
2. **C++ unit and integration tests** (cpp_tests.cpp): `./build/guile_cpp_tests` **39 / 39 all pass** (including 100,000 tail recursions, `call/cc` + `dynamic-wind`, IEEE 754 large-integer rounding, GOOPS class redefinition, first-class environments, IPv6 Socket utilities, and a 200,000-iteration GC stress test).
3. **GNU Guile 1.8.8 official test suite** (`test-suite/tests/*.test`):
- All 78 non-network official `.test` files: **11,848 passes, 0 errors, 1 failure** (the only failure is `r5rs_pitfall.test: 8.3`, because this implementation's CEK `map` is `call/cc`-safe and returns `(0 0 0)`; the original comment explicitly notes that this difference is acceptable; there are also 6 unexpected `list.test: append!` passes, because this implementation detects improper/circular lists more strictly than the original).
- `socket.test`: all byte-order/address encoding and decoding, `make-socket-address`, `bind` and `listen` tests pass (the local `connect`/`sendto` tests need to run in an environment that permits local socket connections).
4. **CLI mode verification**: `-v`, `-h`, `-c`, `--use-srfi=1`, `-s`, `-e`, `-L` and the piped REPL all work normally.
Follow-up on performance
I ran a measured comparison in the same environment on this machine against the original **Homebrew GNU Guile 1.8.8** (`/opt/homebrew/bin/guile`) (macOS arm64, `-O2` build). The conclusion is very direct: **functionality and test coverage currently basically match the original, but interpreter execution performance is clearly slower than the original** (cold startup about **4.7x** slower, C/GMP-intensive and `call/cc` scenarios about **10–12x** slower, pure-Scheme tight loops about **160–210x** slower).
### Measured data comparison
| Benchmark | Original Guile 1.8.8 (C) | C++20 rewrite (`guile_cpp`) | Times slower |
|---|---:|---:|---:|
| Cold startup (`-q -c '(exit 0)'`, average of 10 runs) | 13.4 ms | 63.5 ms | 4.7x |
| `call/cc`, 20,000 captures + escapes | 70 ms | 700 ms | 10.0x |
| Bignum factorial `3000!` (GMP binding) | 10 ms | 120 ms | 12.0x |
| Official test subset (`numbers` + `srfi-1` + `goops`) | 227 ms | 8,114 ms | 35.7x |
| GOOPS generic dispatch (20,000 calls) | 10 ms | 970 ms | 97x |
| `fib(28)`, recursive | 110 ms | 17,960 ms | 163x |
| List construction + reversal (`500k` nodes + GC) | 60 ms | 11,690 ms | 195x |
| Tail-recursive idle loop (`1,000,000` iterations) | 100 ms | 21,320 ms | 213x |
| Hash table (50k insertions + 50k lookups) | 10 ms | 3,000 ms | 300x |
> Notably, the `call/cc` gap is the smallest (only 10x): because the original Guile 1.8.8 relies on copying the C stack to implement continuations, whereas this implementation uses heap-allocated CEK continuation frames, so capture itself is an O(1) pointer operation.
---
### The 5 core bottlenecks behind the performance gap
The current rewrite phase prioritized **100% semantic correctness and test pass rate**, and has not yet done virtual-machine-level performance optimization. The bottlenecks are very concentrated:
1. **No AST memoization (lexical address `iloc` / special form `isym`)**
- The original Guile 1.8 rewrites local variables in place to `(frame, slot)` offsets on first evaluation, caches globals directly as `Variable*`, and turns special forms into immediate tags `isym`.
- The current eval.cpp redoes the symbol-chain lookup + macro check + syntax structure validation on every iteration.
2. **Every evaluation step does `new ContFrameObj` on the heap + copies `std::vector<SCM>`**
- In the current CEK loop, every sub-expression evaluation (e.g. `(- i 1)`, `(= i 0)`) calls the system `new` to allocate a `ContFrameObj`, and copies a `std::vector<SCM>` in `AppArgs`; tail calls also rebuild the environment chain via `cons`.
- The original uses a **16-byte Cell Freelist memory pool** (allocation in a few instructions) + native C stack evaluation, so ordinary calls involve almost no heap allocation.
3. **Variadic arithmetic/comparison primitives build an argument list every time**
- In the current numbers.cpp, `+`, `-`, `*`, `=`, `<` are registered as variadic `(0, 0, true)`, so every `(+ acc 1)` has to `cons` the arguments into a list and then unpack it, instead of going directly through a binary Fixnum inline fast path.
4. **High-frequency short-lived objects trigger full-heap mark-sweep GC**
- `ContFrameObj` and argument lists produce millions of short-lived objects per second, causing the single-linked-list full-heap-scan GC to fire frequently; and `new`'s scattered allocation leads to poor CPU cache locality.
5. **`std::function` indirect calls and dynamic argument containers in inner loops**
- `SubrObj` wraps lambdas in `std::function`, and `CekState::args` repeatedly writes into a heap-allocated `std::vector`.
Results of the second prompt
The performance optimization goal has been completed: `guile_cpp` has **matched or significantly surpassed the original GNU Guile 1.8.8 (C)** on all core micro-benchmarks, cold startup, and official test-suite run times, while keeping all 78 official test files and 39 C++ unit tests at 100% pass with 0 compilation warnings.
---
### Performance comparison (Apple Silicon arm64, `-O3`, median of microsecond-level `gettimeofday` / `perf_counter`)
| Benchmark | Original Guile 1.8.8 (C) | `guile_cpp` before optimization | `guile_cpp` after optimization (C++20) | Speedup vs. original |
|---|---:|---:|---:|---:|
| Cold startup (`-q -c '(exit 0)'`) | 7.76 ms | 63.5 ms | **8.14 ms** | **~1.0x** (roughly on par) |
| `fib(28)` (recursive fixnum) | 66.12 ms | 17,960 ms | **10.32 ms** | **6.41x** |
| `tail-loop(1M)` (named-`let` loop) | 77.51 ms | 21,320 ms | **12.64 ms** | **6.13x** |
| `cons+reverse(500k)` (allocation + GC) | 62.37 ms | 11,690 ms | **18.18 ms** | **3.43x** |
| `bignum-fact(3000)` (GMP factorial) | 0.94 ms | 120 ms | **0.80 ms** | **1.17x** |
| `hashtab(50k+50k)` (`hashv-set!`/`ref`) | 20.14 ms | 3,000 ms | **4.54 ms** | **4.44x** |
| `call/cc(20k)` (continuation capture and invocation) | 145.84 ms | 700 ms | **1.68 ms** | **86.76x** |
| `goops-dispatch(20k)` (60k generic dispatches) | 2.20 ms | 970 ms | **1.17 ms** | **1.87x** |
| Official test suite (`numbers`+`srfi-1`+`goops`) | 179.68 ms | 8,114 ms | **178.95 ms** | **1.00x** (on par / slightly faster) |
---
### Core optimization architecture changes
1. **Slab memory pool and zero-overhead GC** (scm.hpp, vm.hpp, gc.cpp)
- Removed `Obj`'s virtual destructor (saving 8B vptr per object; `PairObj` is now only 32B), completely removing the per-allocation `malloc`/hash `live_set_`.
- Introduced a contiguous `SlabPool<T, N>` freelist allocator with range checks for `PairObj`, `ContFrameObj`, `ClosureObj`, `VariableObj`, `RealObj`, `FractionObj`, `BignumObj`, `BoxObj`, `EvalClosureObj`.
- Introduced an inline `SmallScmVec` (6-slot in-stack buffer) for `ContFrameObj`, eliminating 95%+ of heap allocations on the CEK evaluation path.
2. **Tiered bytecode compiler and Computed-Goto flat-stack virtual machine** (bytecode.cpp, eval.cpp, vm.cpp)
- 32-bit fixed-width instruction set + persistent flat value stack/call frame stack + computed-goto dispatch.
- Zero-allocation inlined named-`let` / `do` loops and fused super-instructions (`OP_LOCAL_ADD_IMM`, `OP_LOCAL_LT_IMM_JF`, `OP_LOCAL_EQ_IMM_JF`); support for compiling depth-1 `quasiquote` and `case`.
- Native VM stack-snapshot `call/cc` (supports multi-shot, upward continuations, and interoperation with CEK `dynamic-wind`/`catch`/`with-throw-handler`), native `apply` / `map` / `for-each` and full boxed mutable locals (passes R5RS Pitfall 7.3/7.4 and the `r4rs.test` `leaf-eq?` coroutine).
- Tiered compilation thresholds (one-shot thunks run directly in the fast CEK; loops or calls ≥ 2 times are compiled immediately), registering inline primitive guards (`VAR_FLAG_FAST_ARITH` / `VAR_FLAG_FAST_CORE` / `VAR_FLAG_FAST_CALLCC`) after `boot-9.scm` startup completes.
3. **GOOPS monomorphic inline caching and Bignum single-limb fast path** (goops.cpp, numbers.cpp, eq.cpp, CMakeLists.txt)
- Added 1/2-argument monomorphic inline dispatch caches on `StructObj` (automatically invalidated when `entity_proc` changes) and a `cmethod -> ClosureObj` cache, so `L_CALL`/`L_TAIL_CALL` jump directly to the compiled method bytecode.
- `raw_varargs` skips rest-list construction for variadic primitives; `scm_num_mul` and `L_MUL2` use GMP `mpz_mul_si` / `mpz_mul` zero-copy paths directly.
4. **Documentation update** (README.md)
- Updated the architecture description and the measured performance comparison tables.
---
### Final verification results
- **Clean Build (`-O3 -Wall -Wextra`)**: 39/39 targets compile, **0 warnings, 0 errors**.
- **C++ unit tests (`./build/guile_cpp_tests`)**: **39 / 39 passed, 0 failed**.
- **GNU Guile 1.8.8 official test suite (all 78 non-socket `.test` files)**: **11,845 passes, 0 errors**, with only 1 expected acceptable failure (`r5rs_pitfall.test: 8.3`, because our `map` is `call/cc`-safe); total CPU time for all 78 files is only **~0.8s**.
A look at how the different backends start up
The TeXmacs Upsilon Cocoa build looks the best.
The TeXmacs Upsilon Qt6 build comes second.
The worst is the latest commit on the original TeXmacs’s svn_mirrors branch.


