Worked examples of where dependent types help NixLab.
git clone git@nixlab.openfp.net:horizon/dependent-nixlab-examples.git{-# LANGUAGE DependentTypes #-}
{-# LANGUAGE ListTuplePuns #-}
-- | A QC review report carries exactly one verdict per rule of its edition,
-- and a merge can only be requested with evidence that every verdict passes.
module NixLab.Dependent.Review (
Edition (..),
Rule (..),
rules,
Verdict (..),
Report (..),
Passes (..),
checkPasses,
Merged (..),
merge,
mergeReport,
Verdicts (..),
) where
import Prelude.Dependent
-- | Handbook editions known to the forge.
data Edition = Edition0_15 | Edition0_16
-- | A handbook rule, by displayed name.
newtype Rule = Rule String
-- | The rules an edition requires a review to grade.
rules :: Edition -> [Rule]
rules Edition0_15 = [Rule "HS.UseTypedPaths", Rule "NIX.PinTaggedInputs"]
rules Edition0_16 =
[Rule "HS.UseTypedPaths", Rule "NIX.PinTaggedInputs", Rule "AG.OmitToolAttribution"]
data Verdict = Pass | Fail String | NotApplicable
-- | The verdicts for one edition: exactly one per rule.
data Verdicts (e :: Edition) = Verdicts (Vec Verdict (size (rules e)))
-- | A report for one edition; the number of verdicts is fixed by 'edition'.
data Report = Report
{ edition :: Edition
, verdicts :: Verdicts edition
}
-- | Evidence that no verdict in a vector fails.
type Passes :: forall n. Vec Verdict n -> Type
data Passes vs where
PassesNil :: Passes VNil
PassesPass :: Passes vs -> Passes (VCons Pass vs)
PassesNotApplicable :: Passes vs -> Passes (VCons NotApplicable vs)
-- | Decide whether a report passes, returning the evidence when it does.
checkPasses :: foreach (vs :: Vec Verdict n) -> Maybe (Passes vs)
checkPasses VNil = Just PassesNil
checkPasses (VCons Pass vs) = fmap PassesPass (checkPasses vs)
checkPasses (VCons NotApplicable vs) = fmap PassesNotApplicable (checkPasses vs)
checkPasses (VCons (Fail _) _) = Nothing
newtype Merged = Merged String
-- | Merging takes the report and the proof that it passes; there is no way
-- to call it with a failing or incomplete review.
merge :: foreach (vs :: Vec Verdict n) -> Passes vs -> String -> Merged
merge _ _ branch = Merged branch
-- | Merge from a report: check it once, then merge with the evidence.
mergeReport :: Report -> String -> Maybe Merged
mergeReport (Report _ (Verdicts vs)) branch = case checkPasses vs of
Just passes -> Just (merge vs passes branch)
Nothing -> Nothing