aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/world/console.lux
blob: 93365f61edcb9e3da7efc4cad109546e64e86342 (plain)
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
(.module:
  [lux #*
   [control
    [monad (#+ do)]
    ["ex" exception (#+ exception:)]]
   [data
    ["." error]
    ["." text
     format]]
   [concurrency
    ["." promise]
    ["." task (#+ Task)]]
   ["." io (#+ IO Process io)]
   [host (#+ import:)]])

(exception: #export (cannot-close)
  "")

(signature: #export (Console m)
  (: (-> [] (m Nat))
     read)
  (: (-> [] (m Text))
     read-line)
  (: (-> [Text] (m Any))
     write)
  (: (-> [] (m Any))
     close))

(for {"JVM"
      (as-is (import: java/lang/String)

             (import: #long java/io/Console
               (readLine [] #io #try String))

             (import: java/io/InputStream
               (read [] #io #try int))

             (import: java/io/PrintStream
               (print [String] #io #try void))

             (import: java/lang/System
               (#static console [] #io #try java/io/Console)
               (#static in java/io/InputStream)
               (#static out java/io/PrintStream))

             (def: #export open
               (Process (Console Task))
               (do io.Monad<Process>
                 [jvm-console (System::console [])
                  #let [jvm-input System::in
                        jvm-output System::out]]
                 (wrap (: (Console Task)
                          (structure
                           (def: (read _)
                             (|> jvm-input
                                 (InputStream::read [])
                                 (:: io.Functor<Process> map .nat)
                                 promise.future))
                           
                           (def: (read-line _)
                             (|> jvm-console (java/io/Console::readLine []) promise.future))
                           
                           (def: (write message)
                             (|> jvm-output (PrintStream::print [message]) promise.future))
                           
                           (def: close
                             (|>> (ex.construct cannot-close) task.fail))))))))
      })

(def: #export (write-line message console)
  (All [m] (-> Text (Console m) (m Any)))
  (:: console write (format message "")))