Yet another REPL

Started by William James, April 04, 2012, 03:17:40 PM

Previous topic - Next topic

William James

Allows you to spread your expressions over several lines.



: (
factor
99999999991

)
(83 1289 934693)


If botched input keeps the prompt from appearing, control-Z (under Windows; for Linux, try control-D) should clear up the problem:

:  * 2 3)
)
)
^Z
ERR: string expected : nil


A work in progress.  Modify as you see fit.



(define (input__complete? str)
  (if (or (find "^s*$" str 0)
          (find "^s*;[^n]*$" str 0))
    true
    (let (error-message ""
          scanned 0)
      (if
        (catch
          (begin
            (read-expr str)
            (setq scanned $0))
          'error-message)
        (input__complete? (slice str scanned))
        false))))

(let ((repl__line "")
      (repl__accum '())
      (repl__expression ""))
  (do-while true
    (unless
      (catch
        (begin
          (if (null? repl__accum) (print ": "))
          (setq repl__line (read-line))
          (push repl__line repl__accum)
          (setq repl__expression
            (join (reverse (copy repl__accum)) "n"))
          (if (input__complete? repl__expression)
            (begin
              (setq repl__accum '())
              (setq repl__expression
                (read-expr (string "(begin " repl__expression ")")))
              (println (eval repl__expression)))))
        'error-message)
      (setq repl__accum '())
      (println error-message))))

William James

#1
Slightly improved.  To quit, type "(exit)".



(define (input__complete? str)
  (if (or (find "^s*$" str 0)
          (find "^s*;[^n]*$" str 0))
    true
    (let (error-message ""
          scanned 0)
      (if
        (catch
          (begin
            (read-expr str)
            (setq scanned $0))
          'error-message)
        (input__complete? (slice str scanned))
        (when (find {^ERR: symbol expected}
               error-message 0)
          (replace "(?s:^ERR: |[rn].*$)" error-message "" 0)
          (throw-error error-message)
        )
        false))))

(let ((repl__line "")
      (repl__accum '())
      (repl__expression ""))
  (do-while true
    (unless
      (catch
        (begin
          (when (empty? repl__accum)
            (unless (= 'MAIN (context)) (print (context)))
            (print ": "))
          (setq repl__line (read-line))
          (push repl__line repl__accum)
          (setq repl__expression
            (join (reverse (copy repl__accum)) "n"))
          (if (input__complete? repl__expression)
            (begin
              (setq repl__accum '())
              (setq repl__expression
                (read-expr (string "(begin " repl__expression ")")))
              (println (eval repl__expression)))))
        'error-message)
      (setq repl__accum '())
      (println error-message))))