~subsetpark/ec

ref: 8c90cfc6ae2baefd4800e61a5894a97ba4a8367b ec/main.janet -rw-r--r-- 1.1 KiB
8c90cfc6 — Zach Smith Basic error handling 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
(import /src/calc)
(import /src/print)
(import /src/parser)

(defn display
  [data]
  (print (print/p data))
  "")

(defn display-all
  [stack]
  (let [inner (map print/p stack)]
    (print (string/join inner " ")))
  "")

(defn handle-commands
  [in s]
  (case (freeze (string/trim in))
    "" (os/exit 0)
    "." (display (calc/peek s))
    "p" (display (calc/pop s))
    "s" (display-all (s :data))
    in))

(defn repl
  []
  (let [s (:new calc/Stack)]
    (while true
      (let [buf @""
            prompt (string/format "(%s)> " (print/p (calc/peek s)))
            in (getline prompt buf parser/dictionary)
            after-commands (handle-commands in s)
            parsed (parser/parse after-commands)]

        (let [bak (array/slice (s :data))]
          (try (calc/push-all s parsed)
               ([err]
                (eprint err)
                (put s :data bak))))))))

(defn handle-line
  [line]
  (let [s (:new calc/Stack)]
    (->> line
         (parser/parse)
         (calc/push-all s))
    (display-all (s :data))))

(defn main
  [_cmd & args]
  (if (empty? args)
    (repl)
    (handle-line (string/join args " "))))