aboutsummaryrefslogtreecommitdiff
path: root/new-luxc/source/luxc/repl.lux
blob: 987cc247288b0701ca6dfa68895b934fb6d10a52 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
(.module:
  lux
  (lux (control [monad #+ do]
                ["ex" exception #+ exception:]
                ["p" parser]
                pipe)
       (data [maybe]
             ["e" error #+ Error]
             [text "text/" Eq<Text>]
             text/format
             (format [xml #+ XML]
                     [json #+ JSON])
             (coll [array]
                   [list "list/" Functor<List>]
                   (dictionary ["dict" unordered])))
       (time [instant #+ Instant]
             [duration #+ Duration]
             [date #+ Date])
       [function #+ const]
       [macro]
       (macro [code]
              [poly #+ Poly])
       (lang [syntax #+ Aliases]
             [type]
             (type [check]))
       (concurrency [promise]
                    [task #+ Task])
       [io]
       (world [file #+ File]
              [console #+ Console]))
  (luxc [lang]
        (lang [".L" module]
              [".L" scope]
              [".L" host]
              [".L" translation]
              [".L" eval]
              [".L" init]
              (translation (jvm [".T" runtime]))
              [".L" extension]
              (extension [".E" analysis]
                         [".E" synthesis]
                         [".E" translation]
                         [".E" statement]))))

(do-template [<name>]
  [(exception: #export (<name> {message Text})
     message)]

  [repl-initialization-failed]
  [repl-error]
  )

(def: repl-module "<REPL>")

(def: no-aliases Aliases (dict.new text.Hash<Text>))

(def: (initialize source-dirs target-dir console)
  (-> (List File) File Console (Task Lux))
  (do promise.Monad<Promise>
    [output (promise.future
             (do io.Monad<IO>
               [host hostL.init-host]
               (case (macro.run' (initL.compiler host)
                                 (moduleL.with-module +0 repl-module
                                   runtimeT.translate))
                 (#e.Success [compiler _])
                 (|> compiler
                     (set@ [#.info #.mode] #.REPL)
                     (set@ #.extensions
                           (:! Nothing
                               {#extensionL.analysis analysisE.defaults
                                #extensionL.synthesis synthesisE.defaults
                                #extensionL.translation translationE.defaults
                                #extensionL.statement statementE.defaults}))
                     (translationL.translate-module source-dirs target-dir translationL.prelude))

                 (#e.Error error)
                 (wrap (#e.Error error)))))]
    (case output
      (#e.Success compiler)
      (do task.Monad<Task>
        [_ (console.write (format "\nWelcome to the REPL!\n"
                                  "Type \"exit\" to leave.\n\n")
                          console)]
        (wrap compiler))
      
      (#e.Error message)
      (task.throw repl-initialization-failed message))))

(def: (add-line line [where offset input])
  (-> Text Source Source)
  [where offset (format input "\n" line)])

(type: Representation (-> Any Text))

(def: (represent-together representations values)
  (-> (List Representation) (List Any) (List Text))
  (|> (list.zip2 representations values)
      (list/map (function (_ [representation value]) (representation value)))))

(def: primitive-representation
  (Poly Representation)
  (`` ($_ p.either
          (do p.Monad<Parser>
            [_ (poly.this Any)]
            (wrap (const "[]")))
          
          (~~ (do-template [<type> <formatter>]
                [(do p.Monad<Parser>
                   [_ (poly.like <type>)]
                   (wrap (|>> (:! <type>) <formatter>)))]

                [Bool %b]
                [Nat %n]
                [Int %i]
                [Deg %d]
                [Frac %f]
                [Text %t])))))

(def: (special-representation representation)
  (-> (Poly Representation) (Poly Representation))
  (`` ($_ p.either
          (~~ (do-template [<type> <formatter>]
                [(do p.Monad<Parser>
                   [_ (poly.like <type>)]
                   (wrap (|>> (:! <type>) <formatter>)))]

                [Type %type]
                [Code %code]
                [Instant %instant]
                [Duration %duration]
                [Date %date]
                [JSON %json]
                [XML %xml]
                ))

          (do p.Monad<Parser>
            [[_ elemT] (poly.apply (p.seq (poly.this List) poly.any))
             elemR (poly.local (list elemT) representation)]
            (wrap (|>> (:! (List Any)) (%list elemR))))

          (do p.Monad<Parser>
            [[_ elemT] (poly.apply (p.seq (poly.this Maybe) poly.any))
             elemR (poly.local (list elemT) representation)]
            (wrap (|>> (:! (Maybe Any))
                       (case> #.None
                              "#.None"

                              (#.Some elemV)
                              (format "(#.Some " (elemR elemV) ")"))))))))

(def: (record-representation tags representation)
  (-> (List Ident) (Poly Representation) (Poly Representation))
  (do p.Monad<Parser>
    [membersR+ (poly.tuple (p.many representation))
     _ (p.assert "Number of tags does not match record type size."
                 (n/= (list.size tags) (list.size membersR+)))]
    (wrap (function (_ recordV)
            (let [record-body (loop [pairs-left (list.zip2 tags membersR+)
                                     recordV recordV]
                                (case pairs-left
                                  #.Nil
                                  ""

                                  (#.Cons [tag repr] #.Nil)
                                  (format (%code (code.tag tag)) " " (repr recordV))

                                  (#.Cons [tag repr] tail)
                                  (let [[leftV rightV] (:! [Any Any] recordV)]
                                    (format (%code (code.tag tag)) " " (repr leftV) " "
                                            (recur tail rightV)))))]
              (format "{" record-body "}"))))))

(def: (variant-representation tags representation)
  (-> (List Ident) (Poly Representation) (Poly Representation))
  (do p.Monad<Parser>
    [casesR+ (poly.variant (p.many representation))
     #let [num-tags (list.size tags)]
     _ (p.assert "Number of tags does not match variant type size."
                 (n/= num-tags (list.size casesR+)))]
    (wrap (function (_ variantV)
            (loop [cases-left (list.zip3 tags
                                         (list.n/range +0 (dec num-tags))
                                         casesR+)
                   variantV variantV]
              (case cases-left
                #.Nil
                ""

                (#.Cons [tag-name tag-idx repr] #.Nil)
                (let [[_tag _last? _value] (:! [Nat Text Any] variantV)]
                  (if (n/= tag-idx _tag)
                    (format "(" (%code (code.tag tag-name)) " " (repr _value) ")")
                    (undefined)))

                (#.Cons [tag-name tag-idx repr] tail)
                (let [[_tag _last? _value] (:! [Nat Text Any] variantV)]
                  (if (n/= tag-idx _tag)
                    (format "(" (%code (code.tag tag-name)) " " (repr _value) ")")
                    (recur tail variantV)))))))))

(def: (tagged-representation compiler representation)
  (-> Lux (Poly Representation) (Poly Representation))
  (do p.Monad<Parser>
    [[name anonymous] poly.named]
    (case (macro.run compiler (macro.tags-of name))
      (#e.Success ?tags)
      (case ?tags
        (#.Some tags)
        (poly.local (list anonymous)
                    (p.either (record-representation tags representation)
                              (variant-representation tags representation)))
        
        #.None
        representation)
      
      (#e.Error error)
      (p.fail error))))

(def: (tuple-representation representation)
  (-> (Poly Representation) (Poly Representation))
  (do p.Monad<Parser>
    [membersR+ (poly.tuple (p.many representation))]
    (wrap (function (_ tupleV)
            (let [tuple-body (loop [representations membersR+
                                    tupleV tupleV]
                               (case representations
                                 #.Nil
                                 ""
                                 
                                 (#.Cons lastR #.Nil)
                                 (lastR tupleV)
                                 
                                 (#.Cons headR tailR)
                                 (let [[leftV rightV] (:! [Any Any] tupleV)]
                                   (format (headR leftV) " " (recur tailR rightV)))))]
              (format "[" tuple-body "]"))))))

(def: (representation compiler)
  (-> Lux (Poly Representation))
  (p.rec
   (function (_ representation)
     ($_ p.either
         primitive-representation
         (special-representation representation)
         (tagged-representation compiler representation)
         (tuple-representation representation)

         (do p.Monad<Parser>
           [[funcT inputsT+] (poly.apply (p.seq poly.any (p.many poly.any)))]
           (case (type.apply inputsT+ funcT)
             (#.Some outputT)
             (poly.local (list outputT) representation)

             #.None
             (p.fail "")))

         (do p.Monad<Parser>
           [[name anonymous] poly.named]
           (poly.local (list anonymous) representation))

         (p.fail "")
         ))))

(def: (represent compiler type value)
  (-> Lux Type Any Text)
  (case (poly.run type (representation compiler))
    (#e.Success representation)
    (representation value)

    (#e.Error error)
    ". . . cannot represent value . . ."))

(def: (repl-translate source-dirs target-dir code)
  (-> (List File) File Code (Meta [Type Any]))
  (function (_ compiler)
    (case ((translationL.translate (translationL.translate-module source-dirs target-dir)
                                   no-aliases
                                   code)
           compiler)
      (#e.Success [compiler' aliases'])
      (#e.Success [compiler' [Nothing []]])

      (#e.Error error)
      (if (ex.match? translationL.Unrecognized-Statement error)
        ((do macro.Monad<Meta>
           [[var-id varT] (lang.with-type-env check.var)
            exprV (scopeL.with-scope repl-module
                    (evalL.eval varT code))
            ?exprT (lang.with-type-env (check.read var-id))]
           (wrap [(maybe.assume ?exprT) exprV]))
         compiler)
        (#e.Error error)))))

(def: fresh-source Source [[repl-module +1 +0] +0 ""])

(def: #export (run source-dirs target-dir)
  (-> (List File) File (Task Any))
  (do task.Monad<Task>
    [console (promise.future console.open)
     compiler (initialize source-dirs target-dir console)]
    (loop [compiler compiler
           source fresh-source
           multi-line? false]
      (do @
        [_ (if multi-line?
             (console.write "  " console)
             (console.write "> " console))
         line (console.read-line console)]
        (if (text/= "exit" line)
          (console.write "Till next time..." console)
          (case (do e.Monad<Error>
                  [[source' exprC] (syntax.read repl-module no-aliases (add-line line source))]
                  (macro.run' compiler
                              (lang.with-current-module repl-module
                                (do macro.Monad<Meta>
                                  [[exprT exprV] (repl-translate source-dirs target-dir exprC)]
                                  (wrap [source' exprT exprV])))))
            (#e.Success [compiler' [source' exprT exprV]])
            (do @
              [_ (console.write (format " Type: " (type.to-text exprT) "\n"
                                        "Value: " (represent compiler' exprT exprV) "\n\n")
                                console)]
              (recur compiler' source' false))

            (#e.Error error)
            (if (ex.match? syntax.end-of-file error)
              (recur compiler source true)
              (exec (log! (ex.construct repl-error error))
                (recur compiler fresh-source false))))))
      )))