;;; write-to-string-shim.lsp -- portable write-to-string for tiers
;;; without the native builtin (asm).
;;;
;;; Python & C tiers ship `write-to-string` as a builtin; do NOT
;;; load this file on those tiers, you'll shadow the fast native
;;; version with a slower Scheme one.
;;;
;;; asm tier launch script (see launch-asm.lsp) loads this first
;;; so wire.lsp's wire-send can call write-to-string unconditionally.

(define (write-to-string x)
  (cond
    ((null? x) "()")
    ((pair? x)
     (string-append "("
                    (write-to-string (car x))
                    (sexp->list-tail (cdr x))))
    ((symbol? x) (symbol->string x))
    ((number? x) (number->string x))
    ((string? x) (string-append "\"" x "\""))
    ((eq? x #t) "#t")
    ((eq? x #f) "#f")
    (else "?")))

(define (sexp->list-tail rest)
  (cond
    ((null? rest) ")")
    ((pair? rest)
     (string-append " "
                    (write-to-string (car rest))
                    (sexp->list-tail (cdr rest))))
    (else
     (string-append " . " (write-to-string rest) ")"))))
