~subsetpark/ec

ref: 90ec763d7df1952b79d9c13cfd13f9f5b9e9818c ec/main.janet -rw-r--r-- 1.6 KiB
90ec763d — Zach Smith Some help functions 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
(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 display-help
  []
  (each [k v] (pairs parser/dictionary)
    (printf "%s: %s" k (string (v :type))))
  "")

(defn describe
  [elem]
  (printf "%s: %s"
          (string (elem :type))
          (elem :doc)))

(defn describe-all
  [q]
  (each item (q :data)
    (describe item))
  "")

(defn handle-commands
  [in s]

  (when (= (string in) "") (os/exit 0))

  (case (freeze (string/trim in))
    "." (display (calc/peek s))
    "p" (display (calc/pop s))
    "s" (display-all (s :data))
    "?" (describe-all (calc/pop s))
    "??" (display-help)
    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 fib]
              (eprint err)
              (if (os/getenv "EC_TRACEBACK")
                (propagate err fib)
                (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 " "))))