Login
7 branches 0 tags
Ben (X13/Arch) Added [closure!] which allows mutation of λs f183ae9 4 years ago 186 Commits
nujel / binlib / repl.nuj
[def ctx [current-closure]]

[def display/error [let*
        [defun wrap [i text]
                [cond [[eq? i 0] [ansi-red text]]
                      [[eq? i 1] [string text]]
                      [[eq? i 2] [ansi-yellow [str/write text]]]
                      [#t text]
                ]
        ]

        [defun iter [error i]
                [if error
                    [cons [wrap i [car error]]
                          [iter [cdr error] [++ i]]]
                    [cons "" #nil]]
        ]

        [λ [error]
                "Display ERROR in a nice, human readable way"
                [display [join [iter error 0] "\r\n"]]
        ]
]]

[defun repl/exception-handler [error]
        [display/error error]
]

[def repl/history #nil]


[defun repl/prompt []
           "> "
]

[def repl/wasm [let*
        [λ [line]
           "Evaluate LINE in the wasm context"
           [try repl/exception-handler
                [def raw [read line]]
                [def expr [cons 'do raw]]
                [def cexpr [cons [compile expr]]]
                [apply ctx cexpr]
           ]
        ]
]]

[defun repl/readline [ctx]
        [def line [readline [repl/prompt]]]
        [when [nil? line]
              [display "Bye!\r\n"]
              [exit 0]
        ]
        [readline/history/add line]
        [def raw [read line]]
        [def expr [cons 'do raw]]
        [def cexpr [cons [compile expr]]]
        [def result [apply ctx cexpr]]
        [set! repl/history [cons line repl/history]]
        [display [cat [if [nil? result]
                          ""
                          [str/write result]]
                      "\n"
                 ]]
]

[defun repl []
        [readline/history/load [readline/history/path]]
        [while #t
               [try repl/exception-handler
                    [repl/readline ctx]
               ]
               [readline/history/save [readline/history/path]]
        ]
]