#lang racket/base

;; ============================================================================
;; #lang mini-forth — Portable Racket / RacketScript Postfix Interpreter
;; Origin: 22 November 2026 Google AI Mode three-file #lang mini-forth sketch
;;         (fixed unbound `forth-colon` export; extended with fixed-point
;;         arithmetic, variables, structured control flow, and ASCII I/O).
;; Compiles cleanly with both native Racket 9.3 and RacketScript (`racks`).
;; ============================================================================

(provide run-mini-forth
         tokenize-forth)

;; ----------------------------------------------------------------------------
;; Tokenizer (mirrors mini-forth/lang/reader.rkt token stream)
;; ----------------------------------------------------------------------------

(define (whitespace-char? ch)
  (or (char=? ch #\space)
      (char=? ch #\tab)
      (char=? ch #\return)
      (char=? ch #\newline)))

(define (parse-integer-token s)
  (define len (string-length s))
  (cond
    [(= len 0) #f]
    [else
     (define start (if (char=? (string-ref s 0) #\-) 1 0))
     (if (>= start len)
         #f
         (let loop ([i start] [acc 0])
           (if (= i len)
               (if (= start 1) (- acc) acc)
               (let ([c (char->integer (string-ref s i))])
                 (if (and (>= c 48) (<= c 57))
                     (loop (+ i 1) (+ (* acc 10) (- c 48)))
                     #f)))))]))

(define (string-starts-with? s prefix)
  (define slen (string-length s))
  (define plen (string-length prefix))
  (and (>= slen plen)
       (let loop ([i 0])
         (cond
           [(= i plen) #t]
           [(char=? (string-ref s i) (string-ref prefix i)) (loop (+ i 1))]
           [else #f]))))

(define (strip-leading-ws s)
  (define len (string-length s))
  (let loop ([i 0])
    (if (and (< i len) (whitespace-char? (string-ref s i)))
        (loop (+ i 1))
        (substring s i len))))

(define (split-lines src)
  (define len (string-length src))
  (let loop ([i 0] [start 0] [acc '()])
    (cond
      [(= i len)
       (reverse (cons (substring src start len) acc))]
      [(char=? (string-ref src i) #\newline)
       (define end (if (and (> i start) (char=? (string-ref src (- i 1)) #\return))
                       (- i 1)
                       i))
       (loop (+ i 1) (+ i 1) (cons (substring src start end) acc))]
      [else
       (loop (+ i 1) start acc)])))

(define (strip-forth-line-comment line)
  (define len (string-length line))
  (let loop ([i 0])
    (cond
      [(= i len) line]
      [(and (char=? (string-ref line i) #\\)
            (or (= i 0) (whitespace-char? (string-ref line (- i 1)))))
       (substring line 0 i)]
      [else (loop (+ i 1))])))

(define (tokenize-line line acc)
  (define len (string-length line))
  (let skip ([i 0] [out acc])
    (cond
      [(>= i len) out]
      [(whitespace-char? (string-ref line i))
       (skip (+ i 1) out)]
      [else
       (let scan ([j (+ i 1)])
         (if (and (< j len) (not (whitespace-char? (string-ref line j))))
             (scan (+ j 1))
             (let* ([raw (substring line i j)]
                    [num (parse-integer-token raw)]
                    [tok (if num num raw)])
               (skip j (cons tok out)))))])))

(define (tokenize-forth source strict?)
  (let loop ([lines (split-lines source)] [acc '()])
    (if (null? lines)
        (list->vector (reverse acc))
        (let* ([raw (car lines)]
               [trimmed (strip-leading-ws raw)])
          (if (string-starts-with? trimmed "#lang ")
              (loop (cdr lines) acc)
              (let ([clean (if strict? raw (strip-forth-line-comment raw))])
                (loop (cdr lines) (tokenize-line clean acc))))))))

;; ----------------------------------------------------------------------------
;; Control-Flow Matchers (if/else/then, begin/while/repeat, begin/until)
;; ----------------------------------------------------------------------------

(define (find-if vec idx end)
  (let loop ([k (+ idx 1)] [depth 0] [else-idx -1])
    (if (>= k end)
        (error "Missing 'then' for 'if'")
        (let ([tok (vector-ref vec k)])
          (cond
            [(equal? tok "if")
             (loop (+ k 1) (+ depth 1) else-idx)]
            [(and (equal? tok "else") (= depth 0) (= else-idx -1))
             (loop (+ k 1) depth k)]
            [(equal? tok "then")
             (if (= depth 0)
                 (values else-idx k)
                 (loop (+ k 1) (- depth 1) else-idx))]
            [else
             (loop (+ k 1) depth else-idx)])))))

(define (find-begin vec idx end)
  (let loop ([k (+ idx 1)] [depth 0] [while-idx -1])
    (if (>= k end)
        (error "Missing 'repeat' or 'until' for 'begin'")
        (let ([tok (vector-ref vec k)])
          (cond
            [(equal? tok "begin")
             (loop (+ k 1) (+ depth 1) while-idx)]
            [(and (equal? tok "while") (= depth 0) (= while-idx -1))
             (loop (+ k 1) depth k)]
            [(equal? tok "repeat")
             (if (= depth 0)
                 (if (= while-idx -1)
                     (error "'repeat' without 'while'")
                     (values 'while while-idx k))
                 (loop (+ k 1) (- depth 1) while-idx))]
            [(equal? tok "until")
             (if (= depth 0)
                 (values 'until -1 k)
                 (loop (+ k 1) (- depth 1) while-idx))]
            [else
             (loop (+ k 1) depth while-idx)])))))

;; Balanced O(n log n) string concatenation (avoids JS argument-count limits)
(define (concat-strings strs)
  (cond
    [(null? strs) ""]
    [(null? (cdr strs)) (car strs)]
    [else
     (let pair-up ([xs strs] [acc '()])
       (cond
         [(null? xs) (concat-strings (reverse acc))]
         [(null? (cdr xs)) (concat-strings (reverse (cons (car xs) acc)))]
         [else
          (pair-up (cddr xs)
                   (cons (string-append (car xs) (cadr xs)) acc))]))]))

(define (format-stack-bottom-to-top stk)
  (define ordered (reverse stk))
  (let loop ([xs ordered] [acc '()])
    (cond
      [(null? xs) (concat-strings (reverse acc))]
      [(null? (cdr xs))
       (concat-strings (reverse (cons (number->string (car xs)) acc)))]
      [else
       (loop (cdr xs)
             (cons " " (cons (number->string (car xs)) acc)))])))

;; ----------------------------------------------------------------------------
;; Core Evaluator (returns #(output-string stack-string step-count))
;; ----------------------------------------------------------------------------

(define (run-mini-forth source strict?)
  (define max-steps 2000000)
  (define stack '())
  (define mem (make-vector 4096 0))
  (define mem-len 0)
  (define words (make-hash))
  (define out-rev '())
  (define steps 0)

  (define (tick!)
    (set! steps (+ steps 1))
    (when (> steps max-steps)
      (error (string-append "Step limit exceeded ("
                            (number->string max-steps)
                            " ops)"))))

  (define (push! v)
    (set! stack (cons v stack)))

  (define (pop!)
    (when (null? stack)
      (error "Stack underflow"))
    (define v (car stack))
    (set! stack (cdr stack))
    v)

  (define (emit-str! s)
    (set! out-rev (cons s out-rev)))

  ;; 6 built-in primitives from mini-forth/main.rkt
  (hash-set! words "+" (lambda () (push! (+ (pop!) (pop!)))))
  (hash-set! words "-" (lambda ()
                         (define b (pop!))
                         (define a (pop!))
                         (push! (- a b))))
  (hash-set! words "*" (lambda () (push! (* (pop!) (pop!)))))
  (hash-set! words "." (lambda ()
                         (emit-str! (string-append (number->string (pop!)) "\n"))))
  (hash-set! words "dup" (lambda ()
                           (define a (pop!))
                           (push! a)
                           (push! a)))
  (hash-set! words "swap" (lambda ()
                            (define b (pop!))
                            (define a (pop!))
                            (push! b)
                            (push! a)))

  ;; Extended primitives for ASCII Mandelbrot & structured Forth programs
  (unless strict?
    (hash-set! words "/" (lambda ()
                           (define b (pop!))
                           (define a (pop!))
                           (when (= b 0) (error "Division by zero"))
                           (push! (quotient a b))))
    (hash-set! words "mod" (lambda ()
                             (define b (pop!))
                             (define a (pop!))
                             (when (= b 0) (error "Division by zero"))
                             (push! (remainder a b))))
    (hash-set! words "negate" (lambda () (push! (- (pop!)))))
    (hash-set! words "abs" (lambda () (push! (abs (pop!)))))
    (hash-set! words "1+" (lambda () (push! (+ (pop!) 1))))
    (hash-set! words "1-" (lambda () (push! (- (pop!) 1))))
    (hash-set! words "drop" (lambda () (pop!)))
    (hash-set! words "over" (lambda ()
                              (define b (pop!))
                              (define a (pop!))
                              (push! a)
                              (push! b)
                              (push! a)))
    (hash-set! words "rot" (lambda ()
                             (define c (pop!))
                             (define b (pop!))
                             (define a (pop!))
                             (push! b)
                             (push! c)
                             (push! a)))
    (hash-set! words "2dup" (lambda ()
                              (define b (pop!))
                              (define a (pop!))
                              (push! a)
                              (push! b)
                              (push! a)
                              (push! b)))
    (hash-set! words "<" (lambda ()
                           (define b (pop!))
                           (define a (pop!))
                           (push! (if (< a b) -1 0))))
    (hash-set! words ">" (lambda ()
                           (define b (pop!))
                           (define a (pop!))
                           (push! (if (> a b) -1 0))))
    (hash-set! words "<=" (lambda ()
                            (define b (pop!))
                            (define a (pop!))
                            (push! (if (<= a b) -1 0))))
    (hash-set! words ">=" (lambda ()
                            (define b (pop!))
                            (define a (pop!))
                            (push! (if (>= a b) -1 0))))
    (hash-set! words "=" (lambda ()
                           (define b (pop!))
                           (define a (pop!))
                           (push! (if (= a b) -1 0))))
    (hash-set! words "<>" (lambda ()
                            (define b (pop!))
                            (define a (pop!))
                            (push! (if (= a b) 0 -1))))
    (hash-set! words "0=" (lambda ()
                            (push! (if (= (pop!) 0) -1 0))))
    (hash-set! words "0<" (lambda ()
                            (push! (if (< (pop!) 0) -1 0))))
    (hash-set! words "and" (lambda ()
                             (push! (bitwise-and (pop!) (pop!)))))
    (hash-set! words "or" (lambda ()
                            (push! (bitwise-ior (pop!) (pop!)))))
    (hash-set! words "@" (lambda ()
                           (define addr (pop!))
                           (when (or (< addr 0) (>= addr mem-len))
                             (error (string-append "Invalid address: "
                                                   (number->string addr))))
                           (push! (vector-ref mem addr))))
    (hash-set! words "!" (lambda ()
                           (define addr (pop!))
                           (define val (pop!))
                           (when (or (< addr 0) (>= addr mem-len))
                             (error (string-append "Invalid address: "
                                                   (number->string addr))))
                           (vector-set! mem addr val)))
    (hash-set! words "+!" (lambda ()
                            (define addr (pop!))
                            (define delta (pop!))
                            (when (or (< addr 0) (>= addr mem-len))
                              (error (string-append "Invalid address: "
                                                    (number->string addr))))
                            (vector-set! mem addr (+ (vector-ref mem addr) delta))))
    (hash-set! words "emit" (lambda ()
                              (emit-str! (string (integer->char (pop!))))))
    (hash-set! words "cr" (lambda () (emit-str! "\n")))
    (hash-set! words "space" (lambda () (emit-str! " "))))

  (define (make-word-thunk vec b-start b-end)
    (lambda () (eval-range vec b-start b-end)))

  (define (make-var-thunk addr)
    (lambda () (push! addr)))

  (define (eval-range vec start end)
    (let loop ([i start])
      (when (< i end)
        (tick!)
        (define t (vector-ref vec i))
        (cond
          [(number? t)
           (push! t)
           (loop (+ i 1))]
          [(equal? t ":")
           (when (>= (+ i 1) end)
             (error "Missing word name after ':'"))
           (define raw-name (vector-ref vec (+ i 1)))
           (define name (if (number? raw-name) (number->string raw-name) raw-name))
           (define body-start (+ i 2))
           (define semi-idx
             (let scan ([j body-start])
               (cond
                 [(>= j end) (error "Missing ';' in word definition")]
                 [(equal? (vector-ref vec j) ";") j]
                 [else (scan (+ j 1))])))
           (hash-set! words name (make-word-thunk vec body-start semi-idx))
           (loop (+ semi-idx 1))]
          [(and (not strict?) (equal? t "variable"))
           (when (>= (+ i 1) end)
             (error "Missing variable name"))
           (when (>= mem-len (vector-length mem))
             (error "Variable memory limit exceeded"))
           (define raw-vname (vector-ref vec (+ i 1)))
           (define vname (if (number? raw-vname) (number->string raw-vname) raw-vname))
           (define addr mem-len)
           (set! mem-len (+ mem-len 1))
           (vector-set! mem addr 0)
           (hash-set! words vname (make-var-thunk addr))
           (loop (+ i 2))]
          [(and (not strict?) (equal? t "if"))
           (let-values ([(else-idx then-idx) (find-if vec i end)])
             (if (not (= (pop!) 0))
                 (eval-range vec (+ i 1) (if (= else-idx -1) then-idx else-idx))
                 (when (not (= else-idx -1))
                   (eval-range vec (+ else-idx 1) then-idx)))
             (loop (+ then-idx 1)))]
          [(and (not strict?) (equal? t "begin"))
           (let-values ([(kind while-idx end-idx) (find-begin vec i end)])
             (if (eq? kind 'while)
                 (let wloop ()
                   (tick!)
                   (eval-range vec (+ i 1) while-idx)
                   (when (not (= (pop!) 0))
                     (eval-range vec (+ while-idx 1) end-idx)
                     (wloop)))
                 (let uloop ()
                   (tick!)
                   (eval-range vec (+ i 1) end-idx)
                   (when (= (pop!) 0)
                     (uloop))))
             (loop (+ end-idx 1)))]
          [else
           (define fn (hash-ref words t #f))
           (if fn
               (begin
                 (fn)
                 (loop (+ i 1)))
               (error (string-append "Unknown word: " t)))]))))

  (define toks (tokenize-forth source strict?))
  (eval-range toks 0 (vector-length toks))
  (vector (concat-strings (reverse out-rev))
          (format-stack-bottom-to-top stack)
          steps))
