2026-11-30 20:49:26 +01:00
|
|
|
;; A small REPL shell: brackets make a new line, Tab completes a few words,
|
|
|
|
|
;; and the history is kept in a file.
|
|
|
|
|
;;
|
|
|
|
|
;; bjo run examples/repl.bjo
|
|
|
|
|
|
|
|
|
|
(import (std prelude))
|
|
|
|
|
(import (bjoterm terminal))
|
|
|
|
|
(import (bjoterm line))
|
|
|
|
|
|
|
|
|
|
(: (Vec string))
|
|
|
|
|
(def words ["define" "display" "lambda" "let" "letrec" "vector-ref" "vector-set!"])
|
|
|
|
|
|
|
|
|
|
;; Completes the word before the cursor from `words`.
|
|
|
|
|
(: (-> string Completion))
|
|
|
|
|
(defun (complete before)
|
|
|
|
|
(def chars (string->vec before))
|
|
|
|
|
(def start (let go ((i (vec-length chars)))
|
|
|
|
|
(if (and (> i 0) (not (string-contains? " ()" (char->string (vec-ref chars (- i 1))))))
|
|
|
|
|
(go (- i 1))
|
|
|
|
|
i)))
|
|
|
|
|
(def word (string-join (vec-map char->string (vec-slice chars start (- (vec-length chars) start))) ""))
|
|
|
|
|
(Completion (prefix word)
|
|
|
|
|
(candidates (vec-filter (fun (w) (string-starts-with? w word)) words))))
|
|
|
|
|
|
|
|
|
|
;; Done when every open bracket is closed.
|
|
|
|
|
(: (-> string bool))
|
|
|
|
|
(defun (balanced? text)
|
|
|
|
|
(<= (loop (:for c (in-vec (string->vec text)))
|
|
|
|
|
(:acc d (summing (cond ((= c #\() 1) ((= c #\)) -1) (else 0)))))
|
|
|
|
|
0))
|
|
|
|
|
|
|
|
|
|
(defun (main args)
|
|
|
|
|
(def (Ok term) (terminal-open) :leave ((Err e) (println (terminal-error-message e)) 1))
|
|
|
|
|
(def ed (make-line-editor #:completer (Some complete) #:input-done? (Some balanced?)))
|
|
|
|
|
(def history (path-combine (match (getenv "HOME") ((Some h) h) (None ".")) ".bjoterm-repl-history"))
|
|
|
|
|
(ignore (line-history-load! ed history))
|
|
|
|
|
(let go ()
|
|
|
|
|
(match (line-read ed term (styled "λ> " [(StyleFg (Ansi 2)) StyleBold]) #:continuation (Some ".. "))
|
|
|
|
|
((LineText text) (println (str "read: " (written text))) (go))
|
|
|
|
|
(LineCancelled (go))
|
2026-12-01 13:07:56 +01:00
|
|
|
(LineEof unit)
|
|
|
|
|
((LineKey _ _) (go))))
|
2026-11-30 20:49:26 +01:00
|
|
|
(ignore (line-history-save ed history))
|
|
|
|
|
0)
|