(.require
 [library
  [lux (.except)
   [abstract
    [equivalence (.only Equivalence)]
    [hash (.only Hash)]]
   [control
    ["[0]" pipe]]
   [data
    [text
     ["%" \\format (.only Format)]]]
   [math
    [number
     ["n" nat]
     ["i" int]]]
   [meta
    [macro
     ["^" pattern]]]]])

(type .public Register
  Nat)

(type .public Variable
  (Variant
   {#Local Register}
   {#Foreign Register}))

(def .public equivalence
  (Equivalence Variable)
  (implementation
   (def (= reference sample)
     (when [reference sample]
       (^.with_template [<tag>]
         [[{<tag> reference'} {<tag> sample'}]
          (n.= reference' sample')])
       ([#Local] [#Foreign])

       _
       false))))

(def .public hash
  (Hash Variable)
  (implementation
   (def equivalence
     ..equivalence)
   
   (def hash
     (|>> (pipe.when
            (^.with_template [<factor> <tag>]
              [{<tag> register}
               (|> register
                   (at n.hash hash)
                   (n.* <factor>))])
            ([2 #Local]
             [3 #Foreign]))))))

(def .public self
  (template (self)
    [{..#Local 0}]))

(def .public self?
  (-> Variable Bit)
  (|>> (pipe.when
         (..self)
         true

         _
         false)))

(def .public format
  (Format Variable)
  (|>> (pipe.when
         {#Local local}
         (%.format "+" (%.nat local))
         
         {#Foreign foreign}
         (%.format "-" (%.nat foreign)))))
