Worked examples of where dependent types help NixLab.
git clone git@nixlab.openfp.net:horizon/dependent-nixlab-examples.git{-# LANGUAGE DependentTypes #-}
{-# LANGUAGE ListTuplePuns #-}
-- | Laws from horizon-dsl's law kit, proven rather than sampled.
--
-- The law kit states each law as an equation between two declaration
-- programs and checks it under the policy-input model over finite domains
-- (four stages, two roles, a few package names). Here the same laws are
-- theorems: they hold for every starting state and every continuation.
module NixLab.Dependent.Laws (
Stage (..),
Role (..),
Decl (..),
Inputs (..),
step,
run,
laterStageReplaces,
laterRoleReplaces,
stageRoleCommute,
compilerNotAnInput,
) where
import Prelude.Dependent
data Stage = Development | Patched | Release | Disgusting
data Role = Project | Platform
-- | The declarations the laws mention, as data.
data Decl
= SetStage Stage
| SetRole Role
| SetCompiler String
| SetIndexState String
-- | What the policy sees: the model's observation.
data Inputs = Inputs
{ inputsStage :: Stage
, inputsRole :: Role
, inputsIndexState :: Maybe String
}
-- | The pure policy-input model of one declaration.
step :: Inputs -> Decl -> Inputs
step (Inputs _ r x) (SetStage s) = Inputs s r x
step (Inputs s _ x) (SetRole r) = Inputs s r x
step i (SetCompiler _) = i
step (Inputs s r _) (SetIndexState x) = Inputs s r (Just x)
-- | Run a declaration program from a starting state.
run :: Inputs -> [Decl] -> Inputs
run i [] = i
run i (d : ds) = run (step i d) ds
-- | Law kit: "a later stage replaces an earlier one".
laterStageReplaces ::
foreach (a :: Stage) -> foreach (b :: Stage) ->
foreach (i :: Inputs) -> foreach (rest :: [Decl]) ->
run i (SetStage a : SetStage b : rest) :~: run i (SetStage b : rest)
laterStageReplaces _ _ (Inputs _ _ _) _ = Refl
-- | Law kit: "a later role replaces an earlier one".
laterRoleReplaces ::
foreach (a :: Role) -> foreach (b :: Role) ->
foreach (i :: Inputs) -> foreach (rest :: [Decl]) ->
run i (SetRole a : SetRole b : rest) :~: run i (SetRole b : rest)
laterRoleReplaces _ _ (Inputs _ _ _) _ = Refl
-- | Law kit: "stage and role commute".
stageRoleCommute ::
foreach (s :: Stage) -> foreach (r :: Role) ->
foreach (i :: Inputs) -> foreach (rest :: [Decl]) ->
run i (SetStage s : SetRole r : rest) :~: run i (SetRole r : SetStage s : rest)
stageRoleCommute _ _ (Inputs _ _ _) _ = Refl
-- | Law kit: "the compiler is not a policy input".
compilerNotAnInput ::
foreach (c :: String) ->
foreach (i :: Inputs) -> foreach (rest :: [Decl]) ->
run i (SetCompiler c : rest) :~: run i rest
compilerNotAnInput _ (Inputs _ _ _) _ = Refl