aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/world/console.lux
blob: 0448637ca08cd88429ac75cc1fb1db437d33c07d (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
73
74
(;module:
  [lux #- open]
  (lux (control [monad #+ do])
       (data ["e" error]
             [text])
       (concurrency [promise]
                    [task #+ Task])
       (type object)
       [io #+ IO Process io]
       [host]))

(interface: #export Console
  (read-char [] (Task Text))
  (read-line [] (Task Text))
  (write [Text] (Task Unit))
  (close [] (Task Unit)))

(for {"JVM"
      (as-is (host;import java.lang.AutoCloseable
               (close [] #io #try void))
             
             (host;import java.io.InputStream)

             (host;import java.io.Reader)

             (host;import java.io.InputStreamReader
               (new [InputStream]))
             
             (host;import java.io.BufferedReader
               (new [Reader])
               (read [] #io #try int)
               (readLine [] #io #try String))

             (host;import java.io.PrintStream
               (print [String] #io #try void))

             (host;import java.lang.System
               (#static in java.io.InputStream)
               (#static out java.io.PrintStream))

             (class: JVM-Console Console
               {#input BufferedReader
                #output PrintStream}

               (def: read-char
                 (|>> get@Console
                      (get@ #input)
                      (BufferedReader.read [])
                      (:: io;Functor<Process> map (|>> int-to-nat text;from-code))
                      promise;future))
               
               (def: read-line
                 (|>> get@Console
                      (get@ #input)
                      (BufferedReader.readLine [])
                      promise;future))
               
               (def: (write message)
                 (|>> get@Console
                      (get@ #output)
                      (PrintStream.print [message])
                      promise;future))
               
               (def: (close self)
                 (promise;future
                  (do io;Monad<Process>
                    [_ (AutoCloseable.close [] (|> self get@Console (get@ #input)))]
                    (AutoCloseable.close [] (|> self get@Console (get@ #output)))))))

             (def: #export open
               (Process Console)
               (io (#e;Success (new@JVM-Console {#input (|> System.in InputStreamReader.new BufferedReader.new)
                                                 #output System.out})))))
      })