{-
This second-order term syntax was created from the following second-order syntax description:

syntax CommMonoid | CM

type
  * : 0-ary

term
  unit : * | ε
  add  : *  *  ->  * | _⊕_ l20

theory
  (εU⊕ᴸ) a |> add (unit, a) = a
  (εU⊕ᴿ) a |> add (a, unit) = a
  (⊕A) a b c |> add (add(a, b), c) = add (a, add(b, c))
  (⊕C) a b |> add(a, b) = add(b, a)
-}


module CommMonoid.Syntax where

open import SOAS.Common
open import SOAS.Context
open import SOAS.Variable
open import SOAS.Families.Core
open import SOAS.Construction.Structure
open import SOAS.ContextMaps.Inductive

open import SOAS.Metatheory.Syntax

open import CommMonoid.Signature

private
  variable
    Γ Δ Π : Ctx
    α : *T
    𝔛 : Familyₛ

-- Inductive term declaration
module CM:Terms (𝔛 : Familyₛ) where

  data CM : Familyₛ where
    var  :  ⇾̣ CM
    mvar : 𝔛 α Π  Sub CM Π Γ  CM α Γ

    ε   : CM * Γ
    _⊕_ : CM * Γ  CM * Γ  CM * Γ

  infixl 20 _⊕_

  open import SOAS.Metatheory.MetaAlgebra ⅀F 𝔛

  CMᵃ : MetaAlg CM
  CMᵃ = record
    { 𝑎𝑙𝑔 = λ where
      (unitₒ  _)      ε
      (addₒ   a , b)  _⊕_ a b
    ; 𝑣𝑎𝑟 = var ; 𝑚𝑣𝑎𝑟 = λ 𝔪   mvar 𝔪 (tabulate ) }

  module CMᵃ = MetaAlg CMᵃ

  module _ {𝒜 : Familyₛ}(𝒜ᵃ : MetaAlg 𝒜) where

    open MetaAlg 𝒜ᵃ

    𝕤𝕖𝕞 : CM ⇾̣ 𝒜
    𝕊 : Sub CM Π Γ  Π ~[ 𝒜 ]↝ Γ
    𝕊 (t  σ) new = 𝕤𝕖𝕞 t
    𝕊 (t  σ) (old v) = 𝕊 σ v
    𝕤𝕖𝕞 (mvar 𝔪 ) = 𝑚𝑣𝑎𝑟 𝔪 (𝕊 )
    𝕤𝕖𝕞 (var v) = 𝑣𝑎𝑟 v

    𝕤𝕖𝕞  ε        = 𝑎𝑙𝑔 (unitₒ  tt)
    𝕤𝕖𝕞 (_⊕_ a b) = 𝑎𝑙𝑔 (addₒ   𝕤𝕖𝕞 a , 𝕤𝕖𝕞 b)

    𝕤𝕖𝕞ᵃ⇒ : MetaAlg⇒ CMᵃ 𝒜ᵃ 𝕤𝕖𝕞
    𝕤𝕖𝕞ᵃ⇒ = record
      { ⟨𝑎𝑙𝑔⟩ = λ{ {t = t}  ⟨𝑎𝑙𝑔⟩ t }
      ; ⟨𝑣𝑎𝑟⟩ = refl
      ; ⟨𝑚𝑣𝑎𝑟⟩ = λ{ {𝔪 = 𝔪}{}  cong (𝑚𝑣𝑎𝑟 𝔪) (dext (𝕊-tab )) }  }
      where
      open ≡-Reasoning
      ⟨𝑎𝑙𝑔⟩ : (t :  CM α Γ)  𝕤𝕖𝕞 (CMᵃ.𝑎𝑙𝑔 t)  𝑎𝑙𝑔 (⅀₁ 𝕤𝕖𝕞 t)
      ⟨𝑎𝑙𝑔⟩ (unitₒ  _) = refl
      ⟨𝑎𝑙𝑔⟩ (addₒ   _) = refl

      𝕊-tab : ( : Π ~[ CM ]↝ Γ)(v :  α Π)  𝕊 (tabulate ) v  𝕤𝕖𝕞 ( v)
      𝕊-tab  new = refl
      𝕊-tab  (old v) = 𝕊-tab (  old) v

    module _ (g : CM ⇾̣ 𝒜)(gᵃ⇒ : MetaAlg⇒ CMᵃ 𝒜ᵃ g) where

      open MetaAlg⇒ gᵃ⇒

      𝕤𝕖𝕞! : (t : CM α Γ)  𝕤𝕖𝕞 t  g t
      𝕊-ix : ( : Sub CM Π Γ)(v :  α Π)  𝕊  v  g (index  v)
      𝕊-ix (x  ) new = 𝕤𝕖𝕞! x
      𝕊-ix (x  ) (old v) = 𝕊-ix  v
      𝕤𝕖𝕞! (mvar 𝔪 ) rewrite cong (𝑚𝑣𝑎𝑟 𝔪) (dext (𝕊-ix ))
        = trans (sym ⟨𝑚𝑣𝑎𝑟⟩) (cong (g  mvar 𝔪) (tab∘ix≈id ))
      𝕤𝕖𝕞! (var v) = sym ⟨𝑣𝑎𝑟⟩

      𝕤𝕖𝕞! ε = sym ⟨𝑎𝑙𝑔⟩
      𝕤𝕖𝕞! (_⊕_ a b) rewrite 𝕤𝕖𝕞! a | 𝕤𝕖𝕞! b = sym ⟨𝑎𝑙𝑔⟩


-- Syntax instance for the signature
CM:Syn : Syntax
CM:Syn = record
  { ⅀F = ⅀F
  ; ⅀:CS = ⅀:CompatStr
  ; mvarᵢ = CM:Terms.mvar
  ; 𝕋:Init = λ 𝔛  let open CM:Terms 𝔛 in record
    {  = CM  CMᵃ
    ; ⊥-is-initial = record { ! = λ{ {𝒜  𝒜ᵃ}  𝕤𝕖𝕞 𝒜ᵃ  𝕤𝕖𝕞ᵃ⇒ 𝒜ᵃ }
    ; !-unique = λ{ {𝒜  𝒜ᵃ} (f  fᵃ⇒) {x = t}  𝕤𝕖𝕞! 𝒜ᵃ f fᵃ⇒ t } } } }

-- Instantiation of the syntax and metatheory
open Syntax CM:Syn public
open CM:Terms public
open import SOAS.Families.Build public
open import SOAS.Syntax.Shorthands CMᵃ public
open import SOAS.Metatheory CM:Syn public