-- The scope-extension constraint of 'sinkContextUnchecked' (a coercion) is
-- a contract for its callers, not an argument it uses, so GHC calls it
-- redundant. It is kept as the contract.
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE DataKinds           #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE KindSignatures      #-}
{-# LANGUAGE LambdaCase          #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | The typing context of the new checker: what every name in scope is, the
-- tope context, the direction of a comparison, the options, and the stack of
-- judgements kept for diagnostics.
--
-- Every entry holds values: the type of the name, and for a definition its
-- value, evaluated once. The context is also the evaluation context of
-- free-foil-NBE (the instance is in "Rzk.Check.Value"), so evaluation reads
-- definitions and topes from the same place the checker does.
module Rzk.Check.Context
  ( -- * Values
    Value
    -- * Pieces
  , Variance (..)
  , opposite
  , Verbosity (..)
  , LocationInfo (..)
  , atPosition
  , HoleMode (..)
  , Options (..)
  , defaultOptions
  , Approximation (..)
  , Unfolding (..)
    -- * Entries
  , EntryKind (..)
  , Entry (..)
  , localEntry
  , Section (..)
    -- * Diagnostics
  , Action (..)
  , Diag (..)
  , emptyDiag
    -- * The context
  , Context (..)
  , emptyContext
  , lookupEntry
  , lookupNamed
  , entriesInScope
  , enterPattern
  , sinkContextUnchecked
  , insertEntry
  , withVariance
  ) where

import           Control.Monad.Foil          (DExt, Distinct, NameMap, Scope)
import qualified Control.Monad.Foil          as Foil
import           Data.Map                    (Map)
import qualified Data.Map                    as Map
import           Unsafe.Coerce               (unsafeCoerce)

import qualified FreeFoil.NbE                as NbE
import           FreeFoil.NbE.Definitions    (Unfolding (..))

import           Language.Rzk.Foil.Names     (RzkPosition (..), TModality (..),
                                              VarIdent)
import           Rzk.Check.Foil.Extras       (replaceName)
import           Rzk.Check.Syntax
import           Rzk.Check.Topes             (Tope, TopeContext,
                                              emptyTopeContext)

-- * Values

-- | A value of the core: free-foil-NBE's, over the pattern binder and the
-- signature.
type Value = NbE.Value Pattern Sig

-- * Pieces

-- | The direction of a comparison: whether the expected side is the
-- supertype, the subtype, or neither.
data Variance = Covariant | Contravariant | Invariant
  deriving (Variance -> Variance -> Bool
(Variance -> Variance -> Bool)
-> (Variance -> Variance -> Bool) -> Eq Variance
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Variance -> Variance -> Bool
== :: Variance -> Variance -> Bool
$c/= :: Variance -> Variance -> Bool
/= :: Variance -> Variance -> Bool
Eq, Int -> Variance -> ShowS
[Variance] -> ShowS
Variance -> String
(Int -> Variance -> ShowS)
-> (Variance -> String) -> ([Variance] -> ShowS) -> Show Variance
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Variance -> ShowS
showsPrec :: Int -> Variance -> ShowS
$cshow :: Variance -> String
show :: Variance -> String
$cshowList :: [Variance] -> ShowS
showList :: [Variance] -> ShowS
Show)

opposite :: Variance -> Variance
opposite :: Variance -> Variance
opposite = \case
  Variance
Covariant     -> Variance
Contravariant
  Variance
Contravariant -> Variance
Covariant
  Variance
Invariant     -> Variance
Invariant

data Verbosity = Debug | Normal | Silent
  deriving (Verbosity -> Verbosity -> Bool
(Verbosity -> Verbosity -> Bool)
-> (Verbosity -> Verbosity -> Bool) -> Eq Verbosity
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Verbosity -> Verbosity -> Bool
== :: Verbosity -> Verbosity -> Bool
$c/= :: Verbosity -> Verbosity -> Bool
/= :: Verbosity -> Verbosity -> Bool
Eq, Eq Verbosity
Eq Verbosity =>
(Verbosity -> Verbosity -> Ordering)
-> (Verbosity -> Verbosity -> Bool)
-> (Verbosity -> Verbosity -> Bool)
-> (Verbosity -> Verbosity -> Bool)
-> (Verbosity -> Verbosity -> Bool)
-> (Verbosity -> Verbosity -> Verbosity)
-> (Verbosity -> Verbosity -> Verbosity)
-> Ord Verbosity
Verbosity -> Verbosity -> Bool
Verbosity -> Verbosity -> Ordering
Verbosity -> Verbosity -> Verbosity
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Verbosity -> Verbosity -> Ordering
compare :: Verbosity -> Verbosity -> Ordering
$c< :: Verbosity -> Verbosity -> Bool
< :: Verbosity -> Verbosity -> Bool
$c<= :: Verbosity -> Verbosity -> Bool
<= :: Verbosity -> Verbosity -> Bool
$c> :: Verbosity -> Verbosity -> Bool
> :: Verbosity -> Verbosity -> Bool
$c>= :: Verbosity -> Verbosity -> Bool
>= :: Verbosity -> Verbosity -> Bool
$cmax :: Verbosity -> Verbosity -> Verbosity
max :: Verbosity -> Verbosity -> Verbosity
$cmin :: Verbosity -> Verbosity -> Verbosity
min :: Verbosity -> Verbosity -> Verbosity
Ord, Int -> Verbosity -> ShowS
[Verbosity] -> ShowS
Verbosity -> String
(Int -> Verbosity -> ShowS)
-> (Verbosity -> String)
-> ([Verbosity] -> ShowS)
-> Show Verbosity
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Verbosity -> ShowS
showsPrec :: Int -> Verbosity -> ShowS
$cshow :: Verbosity -> String
show :: Verbosity -> String
$cshowList :: [Verbosity] -> ShowS
showList :: [Verbosity] -> ShowS
Show)

-- | Where a diagnostic points: the start of the declaration being checked,
-- narrowed to the sub-term as the checker descends into it.
data LocationInfo = LocationInfo
  { LocationInfo -> Maybe String
locationFilePath :: Maybe FilePath
  , LocationInfo -> Maybe Int
locationLine     :: Maybe Int
  , LocationInfo -> Maybe Int
locationColumn   :: Maybe Int
  } deriving (LocationInfo -> LocationInfo -> Bool
(LocationInfo -> LocationInfo -> Bool)
-> (LocationInfo -> LocationInfo -> Bool) -> Eq LocationInfo
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: LocationInfo -> LocationInfo -> Bool
== :: LocationInfo -> LocationInfo -> Bool
$c/= :: LocationInfo -> LocationInfo -> Bool
/= :: LocationInfo -> LocationInfo -> Bool
Eq, Int -> LocationInfo -> ShowS
[LocationInfo] -> ShowS
LocationInfo -> String
(Int -> LocationInfo -> ShowS)
-> (LocationInfo -> String)
-> ([LocationInfo] -> ShowS)
-> Show LocationInfo
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LocationInfo -> ShowS
showsPrec :: Int -> LocationInfo -> ShowS
$cshow :: LocationInfo -> String
show :: LocationInfo -> String
$cshowList :: [LocationInfo] -> ShowS
showList :: [LocationInfo] -> ShowS
Show)

-- | Point a location at a position in the same file.
atPosition :: RzkPosition -> LocationInfo -> LocationInfo
atPosition :: RzkPosition -> LocationInfo -> LocationInfo
atPosition RzkPosition
pos LocationInfo
loc = case RzkPosition -> BNFC'Position
rzkLineCol RzkPosition
pos of
  BNFC'Position
Nothing          -> LocationInfo
loc
  Just (Int
line, Int
col) -> LocationInfo
loc { locationLine = Just line, locationColumn = Just col }

-- | How a user hole is treated.
data HoleMode
  = HolesAreErrors
    -- ^ reject an unsolved hole; the default for finished work and CI
  | HolesDeferred
    -- ^ record the goal and let the hole stand for a term of any type
  | HolesStructural
    -- ^ record the goal, but tolerate a mismatch only at a hole leaf of an
    -- otherwise matching structure
  deriving (HoleMode -> HoleMode -> Bool
(HoleMode -> HoleMode -> Bool)
-> (HoleMode -> HoleMode -> Bool) -> Eq HoleMode
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: HoleMode -> HoleMode -> Bool
== :: HoleMode -> HoleMode -> Bool
$c/= :: HoleMode -> HoleMode -> Bool
/= :: HoleMode -> HoleMode -> Bool
Eq, Int -> HoleMode -> ShowS
[HoleMode] -> ShowS
HoleMode -> String
(Int -> HoleMode -> ShowS)
-> (HoleMode -> String) -> ([HoleMode] -> ShowS) -> Show HoleMode
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> HoleMode -> ShowS
showsPrec :: Int -> HoleMode -> ShowS
$cshow :: HoleMode -> String
show :: HoleMode -> String
$cshowList :: [HoleMode] -> ShowS
showList :: [HoleMode] -> ShowS
Show)

-- | The options a run or a file sets.
data Options = Options
  { Options -> Verbosity
optVerbosity           :: Verbosity
    -- ^ how much progress and debugging output to print
  , Options -> HoleMode
optHoles               :: HoleMode
    -- ^ how to treat user holes
  , Options -> [VarIdent]
optHintLemmas          :: [VarIdent]
    -- ^ lemmas requested as hints; the new checker does not use them yet
  , Options -> Bool
optWarnOverhang        :: Bool
    -- ^ whether to warn when a face or guard overhangs the local context
  , Options -> Bool
optWarnTopeFamilyDomain :: Bool
    -- ^ whether to warn when a tope family needs its domain conjoined
  , Options -> Maybe String
optRender              :: Maybe String
    -- ^ the render backend, which the new checker accepts but does not run
  } deriving (Options -> Options -> Bool
(Options -> Options -> Bool)
-> (Options -> Options -> Bool) -> Eq Options
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Options -> Options -> Bool
== :: Options -> Options -> Bool
$c/= :: Options -> Options -> Bool
/= :: Options -> Options -> Bool
Eq, Int -> Options -> ShowS
[Options] -> ShowS
Options -> String
(Int -> Options -> ShowS)
-> (Options -> String) -> ([Options] -> ShowS) -> Show Options
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Options -> ShowS
showsPrec :: Int -> Options -> ShowS
$cshow :: Options -> String
show :: Options -> String
$cshowList :: [Options] -> ShowS
showList :: [Options] -> ShowS
Show)

-- | The default options.
--
-- >>> defaultOptions
-- Options {optVerbosity = Normal, optHoles = HolesAreErrors, optHintLemmas = [], optWarnOverhang = False, optWarnTopeFamilyDomain = True, optRender = Nothing}
defaultOptions :: Options
defaultOptions :: Options
defaultOptions = Options
  { optVerbosity :: Verbosity
optVerbosity = Verbosity
Normal
  , optHoles :: HoleMode
optHoles = HoleMode
HolesAreErrors
  , optHintLemmas :: [VarIdent]
optHintLemmas = []
  , optWarnOverhang :: Bool
optWarnOverhang = Bool
False
  , optWarnTopeFamilyDomain :: Bool
optWarnTopeFamilyDomain = Bool
True
  , optRender :: Maybe String
optRender = Maybe String
forall a. Maybe a
Nothing
  }

-- | The state of a conversion check, after the approximate conversion
-- checking of Kovács's smalltt. A check starts 'ApproxRigid'. Two glued
-- values of one defined name compare their folded sides 'ApproxFlex', with
-- no unfolding, and if these differ their unfolded sides 'ApproxFull'.
data Approximation
  = ApproxRigid
    -- ^ unfold distinct definitions; equal ones may first compare folded
  | ApproxFlex
    -- ^ compare folded sides of one definition, without unfolding
  | ApproxFull
    -- ^ allow a full unfolded comparison after the folded attempt
  deriving (Approximation -> Approximation -> Bool
(Approximation -> Approximation -> Bool)
-> (Approximation -> Approximation -> Bool) -> Eq Approximation
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Approximation -> Approximation -> Bool
== :: Approximation -> Approximation -> Bool
$c/= :: Approximation -> Approximation -> Bool
/= :: Approximation -> Approximation -> Bool
Eq, Int -> Approximation -> ShowS
[Approximation] -> ShowS
Approximation -> String
(Int -> Approximation -> ShowS)
-> (Approximation -> String)
-> ([Approximation] -> ShowS)
-> Show Approximation
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Approximation -> ShowS
showsPrec :: Int -> Approximation -> ShowS
$cshow :: Approximation -> String
show :: Approximation -> String
$cshowList :: [Approximation] -> ShowS
showList :: [Approximation] -> ShowS
Show)

-- * Entries

data EntryKind
  = EntryLocal
    -- ^ a local binder, not collected when a section closes
  | EntryAssumption
    -- ^ a section assumption, abstracted away when the section closes
  | EntryTopLevel
    -- ^ a definition or postulate that survives the section
  deriving (EntryKind -> EntryKind -> Bool
(EntryKind -> EntryKind -> Bool)
-> (EntryKind -> EntryKind -> Bool) -> Eq EntryKind
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: EntryKind -> EntryKind -> Bool
== :: EntryKind -> EntryKind -> Bool
$c/= :: EntryKind -> EntryKind -> Bool
/= :: EntryKind -> EntryKind -> Bool
Eq, Int -> EntryKind -> ShowS
[EntryKind] -> ShowS
EntryKind -> String
(Int -> EntryKind -> ShowS)
-> (EntryKind -> String)
-> ([EntryKind] -> ShowS)
-> Show EntryKind
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EntryKind -> ShowS
showsPrec :: Int -> EntryKind -> ShowS
$cshow :: EntryKind -> String
show :: EntryKind -> String
$cshowList :: [EntryKind] -> ShowS
showList :: [EntryKind] -> ShowS
Show)

-- | What is known about a name in scope.
data Entry n = Entry
  { forall (n :: S). Entry n -> Value n
entryType     :: Value n
    -- ^ the type of the name
  , forall (n :: S). Entry n -> Maybe (Value n)
entryValue    :: Maybe (Value n)
    -- ^ the value of a definition, evaluated once; a glued value is made
    -- of it at every lookup
  , forall (n :: S). Entry n -> TModality
entryModality :: TModality
    -- ^ the modality at which the name was bound
  , forall (n :: S). Entry n -> TModality
entryLocks    :: TModality
    -- ^ accumulated locks; reserved for modal term checking
  , forall (n :: S). Entry n -> EntryKind
entryKind     :: EntryKind
    -- ^ whether the name is local, an assumption, or a top-level entry
  , forall (n :: S). Entry n -> Maybe VarIdent
entryName     :: Maybe VarIdent
    -- ^ the name the user wrote, for display
  , forall (n :: S). Entry n -> Maybe LocationInfo
entryLocation :: Maybe LocationInfo
    -- ^ where the entry was introduced
  , forall (n :: S). Entry n -> [Name n]
entryUses     :: [Foil.Name n]
    -- ^ the variables a declaration says it uses
  , forall (n :: S). Entry n -> Maybe (Core n)
entryTypeCore  :: Maybe (Core n)
    -- ^ a top-level entry's type as elaborated, which closing a section
    -- reads its dependencies off and abstracts
  , forall (n :: S). Entry n -> Maybe (Core n)
entryValueCore :: Maybe (Core n)
    -- ^ a definition's body as elaborated
  }

instance Foil.Sinkable Entry where
  sinkabilityProof :: forall (n :: S) (l :: S). (Name n -> Name l) -> Entry n -> Entry l
sinkabilityProof Name n -> Name l
rename Entry n
entry = Entry n
entry
    { entryType = Foil.sinkabilityProof rename (entryType entry)
    , entryValue = Foil.sinkabilityProof rename <$> entryValue entry
    , entryUses = map rename (entryUses entry)
    , entryTypeCore = Foil.sinkabilityProof rename <$> entryTypeCore entry
    , entryValueCore = Foil.sinkabilityProof rename <$> entryValueCore entry
    }

-- | The entry of a local name of a type.
localEntry :: TModality -> Maybe VarIdent -> Maybe LocationInfo -> Value n -> Entry n
localEntry :: forall (n :: S).
TModality
-> Maybe VarIdent -> Maybe LocationInfo -> Value n -> Entry n
localEntry TModality
md Maybe VarIdent
mname Maybe LocationInfo
loc Value n
ty = Entry
  { entryType :: Value n
entryType = Value n
ty
  , entryValue :: Maybe (Value n)
entryValue = Maybe (Value n)
forall a. Maybe a
Nothing
  , entryModality :: TModality
entryModality = TModality
md
  , entryLocks :: TModality
entryLocks = TModality
Id
  , entryKind :: EntryKind
entryKind = EntryKind
EntryLocal
  , entryName :: Maybe VarIdent
entryName = Maybe VarIdent
mname
  , entryLocation :: Maybe LocationInfo
entryLocation = Maybe LocationInfo
loc
  , entryUses :: [Name n]
entryUses = []
  , entryTypeCore :: Maybe (Core n)
entryTypeCore = Maybe (Core n)
forall a. Maybe a
Nothing
  , entryValueCore :: Maybe (Core n)
entryValueCore = Maybe (Core n)
forall a. Maybe a
Nothing
  }

-- | An open section: its name, and the top-level entries made in it,
-- newest first. The module itself is an anonymous section, so that an
-- assumption outside any named section is abstracted at the end of the
-- module.
data Section n = Section
  { forall (n :: S). Section n -> Maybe String
sectionName    :: Maybe String
  , forall (n :: S). Section n -> [Name n]
sectionEntries :: [Foil.Name n]
  }

sinkEntries :: DExt n l => NameMap n (Entry n) -> NameMap n (Entry l)
sinkEntries :: forall (n :: S) (l :: S).
DExt n l =>
NameMap n (Entry n) -> NameMap n (Entry l)
sinkEntries = NameMap n (Entry n) -> NameMap n (Entry l)
forall (f :: * -> *) (e :: S -> *) (n :: S) (l :: S).
(Functor f, Sinkable e, DExt n l) =>
f (e n) -> f (e l)
Foil.sink1

-- * Diagnostics

-- | The judgement being performed, for the trace and the error report.
data Action n
  = ActionCheck (Raw n) (Value n)
    -- ^ check a raw term against a type value
  | ActionInfer (Raw n)
    -- ^ infer the type of a raw term
  | ActionConvert (Value n) (Value n)
    -- ^ compare an expected value with an actual one
  | ActionEntails [Tope n] (Tope n)
    -- ^ check that the listed context topes entail a goal
  | ActionEntailsUnion [Tope n] [Tope n]
    -- ^ check that the listed context topes are covered by a union
  | ActionCheckLetValue (Maybe VarIdent)
    -- ^ check or infer a local definition's value
  | ActionCloseSection (Maybe String)
    -- ^ close a named section, or the anonymous module section

-- | What a full run keeps for its diagnostics: the stack of judgements.
data Diag n = Diag
  { forall (n :: S). Diag n -> [Action n]
diagActions :: [Action n]
    -- ^ the current judgements, innermost first
  , forall (n :: S). Diag n -> Int
diagDepth   :: !Int
    -- ^ the number of nested judgements, used by the termination cap
  }

emptyDiag :: Diag n
emptyDiag :: forall (n :: S). Diag n
emptyDiag = [Action n] -> Int -> Diag n
forall (n :: S). [Action n] -> Int -> Diag n
Diag [] Int
0

-- * The context

data Context n = Context
  { forall (n :: S). Context n -> Scope n
ctxScope         :: Scope n
    -- ^ the names in scope
  , forall (n :: S). Context n -> NameMap n (Entry n)
ctxEntries       :: NameMap n (Entry n)
    -- ^ total on 'ctxScope'
  , forall (n :: S). Context n -> Map VarIdent (Name n)
ctxNamed         :: Map VarIdent (Foil.Name n)
    -- ^ the surface name of each entry that has one
  , forall (n :: S). Context n -> [Name n]
ctxBound         :: [Foil.Name n]
    -- ^ every name in scope, most recently bound first
  , forall (n :: S). Context n -> TopeContext n
ctxTopes         :: TopeContext n
    -- ^ the assumed topes and their cached saturation
  , forall (n :: S). Context n -> Variance
ctxVariance      :: Variance
    -- ^ the direction of the current comparison
  , forall (n :: S). Context n -> Unfolding
ctxUnfolding     :: Unfolding
    -- ^ the side of a defined name that readback follows
  , forall (n :: S). Context n -> Approximation
ctxApproximation :: Approximation
    -- ^ the current glued-comparison strategy
  , forall (n :: S). Context n -> Options
ctxOptions       :: Options
    -- ^ options inherited from the run and source commands
  , forall (n :: S). Context n -> Maybe LocationInfo
ctxLocation      :: Maybe LocationInfo
    -- ^ the location narrowed to the current command and judgement
  , forall (n :: S). Context n -> [Section n]
ctxSections      :: [Section n]
    -- ^ the open sections, innermost first
  , forall (n :: S). Context n -> Diag n
ctxDiag          :: Diag n
    -- ^ the stack of current judgements and its depth
  }

-- | The empty context, with 'defaultOptions'. Conversion starts covariantly,
-- with definitions unfolded and the rigid approximation strategy.
--
-- >>> ctxVariance emptyContext
-- Covariant
-- >>> case ctxUnfolding emptyContext of { Unfolded -> True; Folded -> False }
-- True
-- >>> ctxApproximation emptyContext
-- ApproxRigid
emptyContext :: Context Foil.VoidS
emptyContext :: Context 'VoidS
emptyContext = Context
  { ctxScope :: Scope 'VoidS
ctxScope = Scope 'VoidS
Foil.emptyScope
  , ctxEntries :: NameMap 'VoidS (Entry 'VoidS)
ctxEntries = NameMap 'VoidS (Entry 'VoidS)
forall a. NameMap 'VoidS a
Foil.emptyNameMap
  , ctxNamed :: Map VarIdent (Name 'VoidS)
ctxNamed = Map VarIdent (Name 'VoidS)
forall k a. Map k a
Map.empty
  , ctxBound :: [Name 'VoidS]
ctxBound = []
  , ctxTopes :: TopeContext 'VoidS
ctxTopes = TopeContext 'VoidS
forall (n :: S). TopeContext n
emptyTopeContext
  , ctxVariance :: Variance
ctxVariance = Variance
Covariant
  , ctxUnfolding :: Unfolding
ctxUnfolding = Unfolding
Unfolded
  , ctxApproximation :: Approximation
ctxApproximation = Approximation
ApproxRigid
  , ctxOptions :: Options
ctxOptions = Options
defaultOptions
  , ctxLocation :: Maybe LocationInfo
ctxLocation = Maybe LocationInfo
forall a. Maybe a
Nothing
  , ctxSections :: [Section 'VoidS]
ctxSections = []
  , ctxDiag :: Diag 'VoidS
ctxDiag = Diag 'VoidS
forall (n :: S). Diag n
emptyDiag
  }

-- | What a name stands for. Total: every name in scope has an entry.
lookupEntry :: Foil.Name n -> Context n -> Entry n
lookupEntry :: forall (n :: S). Name n -> Context n -> Entry n
lookupEntry Name n
name Context n
ctx = Name n -> NameMap n (Entry n) -> Entry n
forall (n :: S) a. Name n -> NameMap n a -> a
Foil.lookupName Name n
name (Context n -> NameMap n (Entry n)
forall (n :: S). Context n -> NameMap n (Entry n)
ctxEntries Context n
ctx)

lookupNamed :: VarIdent -> Context n -> Maybe (Foil.Name n)
lookupNamed :: forall (n :: S). VarIdent -> Context n -> Maybe (Name n)
lookupNamed VarIdent
name Context n
ctx = VarIdent -> Map VarIdent (Name n) -> Maybe (Name n)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup VarIdent
name (Context n -> Map VarIdent (Name n)
forall (n :: S). Context n -> Map VarIdent (Name n)
ctxNamed Context n
ctx)

-- | Every entry in scope, oldest binding first.
entriesInScope :: Context n -> [(Foil.Name n, Entry n)]
entriesInScope :: forall (n :: S). Context n -> [(Name n, Entry n)]
entriesInScope Context n
ctx = [ (Name n
name, Name n -> Context n -> Entry n
forall (n :: S). Name n -> Context n -> Entry n
lookupEntry Name n
name Context n
ctx) | Name n
name <- [Name n] -> [Name n]
forall a. [a] -> [a]
reverse (Context n -> [Name n]
forall (n :: S). Context n -> [Name n]
ctxBound Context n
ctx) ]

-- | Sink a context along a scope extension. Unsound on its own: the scope
-- and the entries still describe the old scope, so the caller must extend
-- both, as 'enterPattern' does. Everything else in the context mentions
-- the scope only through values and names, which sink by coercion.
sinkContextUnchecked :: DExt n l => Context n -> Context l
sinkContextUnchecked :: forall (n :: S) (l :: S). DExt n l => Context n -> Context l
sinkContextUnchecked = Context n -> Context l
forall a b. a -> b
unsafeCoerce

-- | Enter the scope of a pattern: extend the scope with its names and
-- record an entry for each, in binding order.
enterPattern
  :: (Distinct n, DExt n l)
  => Pattern n l -> [Entry l] -> Context n -> Context l
enterPattern :: forall (n :: S) (l :: S).
(Distinct n, DExt n l) =>
Pattern n l -> [Entry l] -> Context n -> Context l
enterPattern Pattern n l
pat [Entry l]
entries Context n
ctx = (Context n -> Context l
forall (n :: S) (l :: S). DExt n l => Context n -> Context l
sinkContextUnchecked Context n
ctx)
  { ctxScope = Foil.extendScopePattern pat (ctxScope ctx)
  , ctxEntries = Foil.addNameBinders pat entries (sinkEntries (ctxEntries ctx))
  , ctxBound = reverse (map snd names) <> sinkNames (ctxBound ctx)
  , ctxNamed = foldr named (sinkNamed (ctxNamed ctx)) names
  }
  where
    names :: [(Maybe VarIdent, Name l)]
names = Pattern n l -> [(Maybe VarIdent, Name l)]
forall (n :: S) (l :: S).
(Distinct n, Distinct l) =>
Pattern n l -> [(Maybe VarIdent, Name l)]
patternNames Pattern n l
pat
    named :: (Maybe k, a) -> Map k a -> Map k a
named (Just k
x, a
name) = k -> a -> Map k a -> Map k a
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert k
x a
name
    named (Maybe k
Nothing, a
_)   = Map k a -> Map k a
forall a. a -> a
id

sinkNames :: DExt n l => [Foil.Name n] -> [Foil.Name l]
sinkNames :: forall (n :: S) (l :: S). DExt n l => [Name n] -> [Name l]
sinkNames = [Name n] -> [Name l]
forall (f :: * -> *) (e :: S -> *) (n :: S) (l :: S).
(Functor f, Sinkable e, DExt n l) =>
f (e n) -> f (e l)
Foil.sink1

sinkNamed :: DExt n l => Map VarIdent (Foil.Name n) -> Map VarIdent (Foil.Name l)
sinkNamed :: forall (n :: S) (l :: S).
DExt n l =>
Map VarIdent (Name n) -> Map VarIdent (Name l)
sinkNamed = Map VarIdent (Name n) -> Map VarIdent (Name l)
forall (f :: * -> *) (e :: S -> *) (n :: S) (l :: S).
(Functor f, Sinkable e, DExt n l) =>
f (e n) -> f (e l)
Foil.sink1

-- | Replace what a name stands for.
insertEntry :: Foil.Name n -> Entry n -> Context n -> Context n
insertEntry :: forall (n :: S). Name n -> Entry n -> Context n -> Context n
insertEntry Name n
name Entry n
entry Context n
ctx = Context n
ctx { ctxEntries = replaceName name entry (ctxEntries ctx) }

withVariance :: Variance -> Context n -> Context n
withVariance :: forall (n :: S). Variance -> Context n -> Context n
withVariance Variance
v Context n
ctx = Context n
ctx { ctxVariance = v }