(.module:
  lux
  (lux (control [monad #+ do]
                ["ex" exception #+ exception:]
                ["p" parser])
       (data ["e" error]
             [text]
             text/format
             [number]
             (coll [list "list/" Functor<List>]
                   (dictionary ["dict" unordered #+ Dict])))
       [macro #+ with-gensyms]
       (macro [code]
              ["s" syntax #+ syntax:])
       [host])
  (luxc ["&" lang]
        (lang ["la" analysis]
              ["ls" synthesis]
              (host [r #+ Expression])))
  [///]
  (/// [".T" runtime]
       [".T" case]
       [".T" function]
       [".T" loop]))

## [Types]
(type: #export Translator
  (-> ls.Synthesis (Meta Expression)))

(type: #export Proc
  (-> Translator (List ls.Synthesis) (Meta Expression)))

(type: #export Bundle
  (Dict Text Proc))

(syntax: (Vector {size s.nat} elemT)
  (wrap (list (` [(~+ (list.repeat size elemT))]))))

(type: #export Nullary (-> (Vector +0 Expression) Expression))
(type: #export Unary   (-> (Vector +1 Expression) Expression))
(type: #export Binary  (-> (Vector +2 Expression) Expression))
(type: #export Trinary (-> (Vector +3 Expression) Expression))
(type: #export Variadic (-> (List Expression) Expression))

## [Utils]
(def: #export (install name unnamed)
  (-> Text (-> Text Proc)
      (-> Bundle Bundle))
  (dict.put name (unnamed name)))

(def: #export (prefix prefix bundle)
  (-> Text Bundle Bundle)
  (|> bundle
      dict.entries
      (list/map (function (_ [key val]) [(format prefix " " key) val]))
      (dict.from-list text.Hash<Text>)))

(def: (wrong-arity proc expected actual)
  (-> Text Nat Nat Text)
  (format "Wrong number of arguments for " (%t proc) "\n"
          "Expected: " (|> expected .int %i) "\n"
          "  Actual: " (|> actual .int %i)))

(syntax: (arity: {name s.local-identifier} {arity s.nat})
  (with-gensyms [g!_ g!proc g!name g!translate g!inputs]
    (do {@ macro.monad}
      [g!input+ (monad.seq @ (list.repeat arity (macro.gensym "input")))]
      (wrap (list (` (def: #export ((~ (code.local-identifier name)) (~ g!proc))
                       (-> (-> (..Vector (~ (code.nat arity)) Expression) Expression)
                           (-> Text ..Proc))
                       (function ((~ g!_) (~ g!name))
                         (function ((~ g!_) (~ g!translate) (~ g!inputs))
                           (case (~ g!inputs)
                             (^ (list (~+ g!input+)))
                             (do macro.Monad<Meta>
                               [(~+ (|> g!input+
                                        (list/map (function (_ g!input)
                                                    (list g!input (` ((~ g!translate) (~ g!input))))))
                                        list.concat))]
                               ((~' wrap) ((~ g!proc) [(~+ g!input+)])))

                             (~' _)
                             (macro.fail (wrong-arity (~ g!name) +1 (list.size (~ g!inputs))))))))))))))

(arity: nullary +0)
(arity: unary +1)
(arity: binary +2)
(arity: trinary +3)

(def: #export (variadic proc)
  (-> Variadic (-> Text Proc))
  (function (_ proc-name)
    (function (_ translate inputsS)
      (do {@ macro.Monad<Meta>}
        [inputsI (monad.map @ translate inputsS)]
        (wrap (proc inputsI))))))

## [Procedures]
## [[Lux]]
(def: (lux//is [leftO rightO])
  Binary
  (r.apply (list leftO rightO)
           (r.global "identical")))

(def: (lux//if [testO thenO elseO])
  Trinary
  (caseT.translate-if testO thenO elseO))

(def: (lux//try riskyO)
  Unary
  (runtimeT.lux//try riskyO))

(exception: #export (Wrong-Syntax {message Text})
  message)

(def: #export (wrong-syntax procedure args)
  (-> Text (List ls.Synthesis) Text)
  (format "Procedure: " procedure "\n"
          "Arguments: " (%code (code.tuple args))))

(def: lux//loop
  (-> Text Proc)
  (function (_ proc-name)
    (function (_ translate inputsS)
      (case (s.run inputsS ($_ p.seq s.nat (s.tuple (p.many s.any)) s.any))
        (#e.Success [offset initsS+ bodyS])
        (loopT.translate-loop translate offset initsS+ bodyS)

        (#e.Error error)
        (&.throw Wrong-Syntax (wrong-syntax proc-name inputsS)))
      )))

(def: lux//recur
  (-> Text Proc)
  (function (_ proc-name)
    (function (_ translate inputsS)
      (loopT.translate-recur translate inputsS))))

(def: lux-procs
  Bundle
  (|> (dict.new text.Hash<Text>)
      (install "is" (binary lux//is))
      (install "try" (unary lux//try))
      (install "if" (trinary lux//if))
      (install "loop" lux//loop)
      (install "recur" lux//recur)
      ))

## [[Bits]]
(template [<name> <op>]
  [(def: (<name> [subjectO paramO])
     Binary
     (<op> paramO subjectO))]
  
  [bit//and runtimeT.bit//and]
  [bit//or  runtimeT.bit//or]
  [bit//xor runtimeT.bit//xor]
  )

(template [<name> <op>]
  [(def: (<name> [subjectO paramO])
     Binary
     (<op> (runtimeT.int64-low paramO) subjectO))]

  [bit//left-shift          runtimeT.bit//left-shift]
  [bit//arithmetic-right-shift  runtimeT.bit//arithmetic-right-shift]
  [bit//logical-right-shift runtimeT.bit//logical-right-shift]
  )

(def: bit-procs
  Bundle
  (<| (prefix "bit")
      (|> (dict.new text.Hash<Text>)
          (install "and" (binary bit//and))
          (install "or" (binary bit//or))
          (install "xor" (binary bit//xor))
          (install "left-shift" (binary bit//left-shift))
          (install "logical-right-shift" (binary bit//logical-right-shift))
          (install "arithmetic-right-shift" (binary bit//arithmetic-right-shift))
          )))

## [[Numbers]]
(host.import: java/lang/Double
  (#static MIN_VALUE Double)
  (#static MAX_VALUE Double))

(template [<name> <const> <encode>]
  [(def: (<name> _)
     Nullary
     (<encode> <const>))]

  [frac//smallest Double::MIN_VALUE            r.float]
  [frac//min      (f/* -1.0 Double::MAX_VALUE) r.float]
  [frac//max      Double::MAX_VALUE            r.float]
  )

(template [<name> <op>]
  [(def: (<name> [subjectO paramO])
     Binary
     (|> subjectO (<op> paramO)))]

  [int//add        runtimeT.int//+]
  [int//sub        runtimeT.int//-]
  [int//mul        runtimeT.int//*]
  [int//div        runtimeT.int///]
  [int//rem        runtimeT.int//%]
  )

(template [<name> <op>]
  [(def: (<name> [subjectO paramO])
     Binary
     (<op> paramO subjectO))]

  [frac//add r.+]
  [frac//sub r.-]
  [frac//mul r.*]
  [frac//div r./]
  [frac//rem r.%%]
  [frac//=   r.=]
  [frac//<   r.<]

  [text//=   r.=]
  [text//<   r.<]
  )

(template [<name> <cmp>]
  [(def: (<name> [subjectO paramO])
     Binary
     (<cmp> paramO subjectO))]

  [int//= runtimeT.int//=]
  [int//< runtimeT.int//<]
  )

(def: (apply1 func)
  (-> Expression (-> Expression Expression))
  (function (_ value)
    (r.apply (list value) func)))

(def: int//char (|>> runtimeT.int64-low (apply1 (r.global "intToUtf8"))))

(def: int-procs
  Bundle
  (<| (prefix "int")
      (|> (dict.new text.Hash<Text>)
          (install "+" (binary int//add))
          (install "-" (binary int//sub))
          (install "*" (binary int//mul))
          (install "/" (binary int//div))
          (install "%" (binary int//rem))
          (install "=" (binary int//=))
          (install "<" (binary int//<))
          (install "to-frac" (unary runtimeT.int//to-float))
          (install "char" (unary int//char)))))

(def: (frac//encode value)
  (-> Expression Expression)
  (r.apply (list (r.string "%f") value) (r.global "sprintf")))

(def: frac-procs
  Bundle
  (<| (prefix "frac")
      (|> (dict.new text.Hash<Text>)
          (install "+" (binary frac//add))
          (install "-" (binary frac//sub))
          (install "*" (binary frac//mul))
          (install "/" (binary frac//div))
          (install "%" (binary frac//rem))
          (install "=" (binary frac//=))
          (install "<" (binary frac//<))
          (install "smallest" (nullary frac//smallest))
          (install "min" (nullary frac//min))
          (install "max" (nullary frac//max))
          (install "to-int" (unary (apply1 (r.global "as.integer"))))
          (install "encode" (unary frac//encode))
          (install "decode" (unary runtimeT.frac//decode)))))

## [[Text]]
(def: (text//concat [subjectO paramO])
  Binary
  (r.apply (list subjectO paramO) (r.global "paste0")))

(def: (text//char [subjectO paramO])
  Binary
  (runtimeT.text//char subjectO paramO))

(def: (text//clip [subjectO paramO extraO])
  Trinary
  (runtimeT.text//clip subjectO paramO extraO))

(def: (text//index [textO partO startO])
  Trinary
  (runtimeT.text//index textO partO startO))

(def: text-procs
  Bundle
  (<| (prefix "text")
      (|> (dict.new text.Hash<Text>)
          (install "=" (binary text//=))
          (install "<" (binary text//<))
          (install "concat" (binary text//concat))
          (install "index" (trinary text//index))
          (install "size" (unary (|>> (apply1 (r.global "nchar")) runtimeT.int//from-float)))
          (install "char" (binary text//char))
          (install "clip" (trinary text//clip))
          )))

## [[IO]]
(def: (io//exit input)
  Unary
  (r.apply-kw (list)
              (list ["status" (runtimeT.int//to-float input)])
              (r.global "quit")))

(def: (void code)
  (-> Expression Expression)
  (r.block (r.then code runtimeT.unit)))

(def: io-procs
  Bundle
  (<| (prefix "io")
      (|> (dict.new text.Hash<Text>)
          (install "log" (unary (|>> r.print ..void)))
          (install "error" (unary r.stop))
          (install "exit" (unary io//exit))
          (install "current-time" (nullary (function (_ _)
                                             (runtimeT.io//current-time! runtimeT.unit)))))))

## [Bundles]
(def: #export procedures
  Bundle
  (<| (prefix "lux")
      (|> lux-procs
          (dict.merge bit-procs)
          (dict.merge int-procs)
          (dict.merge frac-procs)
          (dict.merge text-procs)
          (dict.merge io-procs)
          )))