{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}

module Yesod.Routes.TH.Internal where

import Prelude hiding (exp)
import Data.List (foldl')
import Data.Maybe (mapMaybe)
-- newName is hidden so the only one in scope is the 'Quote' class method
-- (re-exported by th-compat); with template-haskell < 2.17 the monomorphic
-- 'Language.Haskell.TH.Syntax.newName' is a distinct, ambiguous name.
import Language.Haskell.TH.Syntax hiding (newName)
import Language.Haskell.TH.Syntax.Compat (Quote(..))
import Web.PathPieces (fromPathPiece, fromPathMultiPiece)
import Yesod.Routes.TH.Types

conPCompat :: Name -> [Pat] -> Pat
conPCompat :: Name -> [Pat] -> Pat
conPCompat Name
n [Pat]
pats = Name -> [Type] -> [Pat] -> Pat
ConP Name
n
#if MIN_VERSION_template_haskell(2,18,0)
                         []
#endif
                         [Pat]
pats

instanceD :: Cxt -> Type -> [Dec] -> Dec
instanceD :: [Type] -> Type -> [Dec] -> Dec
instanceD = Maybe Overlap -> [Type] -> Type -> [Dec] -> Dec
InstanceD Maybe Overlap
forall a. Maybe a
Nothing

mkTupE :: [Exp] -> Exp
mkTupE :: [Exp] -> Exp
mkTupE =
    [Maybe Exp] -> Exp
TupE
#if MIN_VERSION_template_haskell(2,16,0)
        ([Maybe Exp] -> Exp) -> ([Exp] -> [Maybe Exp]) -> [Exp] -> Exp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Exp -> Maybe Exp) -> [Exp] -> [Maybe Exp]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Exp -> Maybe Exp
forall a. a -> Maybe a
Just
#endif

-- | The expression form of a route's accumulated @ParentArgs@: @()@ when there
-- are no dynamic pieces, the lone expression when there is one, and a tuple of
-- them otherwise. This is the single spelling of the unit\/single\/tuple idiom
-- that recurred across the dispatch and render-route clause builders.
parentArgsExprFromExps :: [Exp] -> Exp
parentArgsExprFromExps :: [Exp] -> Exp
parentArgsExprFromExps []  = Name -> Exp
ConE '()
parentArgsExprFromExps [Exp
e] = Exp
e
parentArgsExprFromExps [Exp]
es  = [Exp] -> Exp
mkTupE [Exp]
es

-- | 'parentArgsExprFromExps' for the common case where the arguments are plain
-- variable names.
parentArgsExpr :: [Name] -> Exp
parentArgsExpr :: [Name] -> Exp
parentArgsExpr = [Exp] -> Exp
parentArgsExprFromExps ([Exp] -> Exp) -> ([Name] -> [Exp]) -> [Name] -> Exp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Name -> Exp) -> [Name] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Exp
VarE

-- | The /pattern/ form of a route's accumulated @ParentArgs@, for binding the
-- incoming parent arguments: @_@ when there are none (the @ParentArgs@ is @()@
-- and ignored), the lone variable when there is one, and a tuple otherwise.
parentArgsPat :: [Name] -> Pat
parentArgsPat :: [Name] -> Pat
parentArgsPat []  = Pat
WildP
parentArgsPat [Name
a] = Name -> Pat
VarP Name
a
parentArgsPat [Name]
as  = [Pat] -> Pat
TupP ((Name -> Pat) -> [Name] -> [Pat]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Pat
VarP [Name]
as)

-- | The /type/ form of a route's accumulated @ParentArgs@: the unit type when
-- there are no dynamic pieces, the lone type when there is one, and a tuple
-- type otherwise.
parentArgsType :: [Type] -> Type
parentArgsType :: [Type] -> Type
parentArgsType []  = Name -> Type
ConT ''()
parentArgsType [Type
t] = Type
t
parentArgsType [Type]
ts  = (Type -> Type -> Type) -> Type -> [Type] -> Type
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Type -> Type -> Type
AppT (Int -> Type
TupleT ([Type] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Type]
ts)) [Type]
ts

-- | The number of type parameters a type constructor declares (0 for a type
-- that isn't a data\/newtype\/type-synonym, or that we can't reify).
typeArity :: Name -> Q Int
typeArity :: Name -> Q Int
typeArity Name
typeName = do
    info <- Name -> Q Info
reify Name
typeName
    pure $ case info of
        TyConI (DataD [Type]
_ Name
_ [TyVarBndr BndrVis]
vs Maybe Type
_ [Con]
_ [DerivClause]
_) -> [TyVarBndr BndrVis] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TyVarBndr BndrVis]
vs
        TyConI (NewtypeD [Type]
_ Name
_ [TyVarBndr BndrVis]
vs Maybe Type
_ Con
_ [DerivClause]
_) -> [TyVarBndr BndrVis] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TyVarBndr BndrVis]
vs
        TyConI (TySynD Name
_ [TyVarBndr BndrVis]
vs Type
_) -> [TyVarBndr BndrVis] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TyVarBndr BndrVis]
vs
        Info
_ -> Int
0

-- | Look up a type by 'Name' and return it fully applied with fresh
-- type variables. This is needed because nested route datatypes may
-- have type parameters (e.g., @NestedR subsite@), and TH functions
-- like 'isInstance' require fully-applied (kind 'Type') heads.
--
-- The application is to the datatype's /own/ reified 'typeArity', so the head
-- is saturated exactly — neither under- nor over-applied — and is therefore
-- well-kinded by construction. This holds for higher-kinded parameters too:
-- a parameter declared @(f :: Type -> Type)@ is filled with a bare,
-- unannotated @'VarT' a@, and GHC infers @a :: Type -> Type@ from the
-- datatype's declared kind, so we don't need to reconstruct each parameter's
-- kind ourselves. (Saturating by some /other/ arity — e.g. a caller's
-- 'TyArgs' count — is what historically built ill-kinded heads and made
-- 'isInstance' throw; see 'nestedInstanceExists'.)
fullyApplyType :: Name -> Q Type
fullyApplyType :: Name -> Q Type
fullyApplyType Name
typeName = do
    arity <- Name -> Q Int
typeArity Name
typeName
    vars <- mapM (\Int
i -> Name -> Type
VarT (Name -> Type) -> Q Name -> Q Type
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> Q Name
forall (m :: * -> *). Quote m => String -> m Name
newName (String
"a" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
i)) [1..arity]
    pure $ foldl' AppT (ConT typeName) vars

-- | A route datatype name paired with the result of resolving it in the
-- current splice environment. 'rcResolved' is 'Just' when the datatype is
-- already in scope (defined in an earlier splice or a separately compiled
-- module) and 'Nothing' when it is not yet — typically because it is being
-- generated in the same splice group.
--
-- The point is to resolve a route name /once/, at the boundary, and carry the
-- answer in a value rather than re-running 'lookupTypeName' at each use site
-- and independently re-deciding what an unresolved name means. The two
-- consumers that matter — \"does its nested instance already exist?\"
-- ('nestedInstanceExists') and \"what type head do I splice?\"
-- ('appliedRouteTypeCon') — then share a single resolution.
--
-- @since 1.7.0.0
data RouteCon = RouteCon
    { RouteCon -> String
rcName     :: String       -- ^ the route datatype name as written
    , RouteCon -> Maybe Name
rcResolved :: Maybe Name   -- ^ the resolved 'Name', if in scope
    }

-- | Resolve a route datatype name with 'lookupTypeName'. This is the single
-- boundary at which a route name is looked up; downstream code branches on the
-- resulting 'RouteCon' instead of resolving again.
--
-- @since 1.7.0.0
resolveRouteCon :: String -> Q RouteCon
resolveRouteCon :: String -> Q RouteCon
resolveRouteCon String
name = String -> Maybe Name -> RouteCon
RouteCon String
name (Maybe Name -> RouteCon) -> Q (Maybe Name) -> Q RouteCon
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> Q (Maybe Name)
lookupTypeName String
name

-- | Does an instance of the given (nested-discovery) class — e.g.
-- @''YesodDispatchNested@, @''RenderRouteNested@, @''ParseRouteNested@,
-- @''RouteAttrsNested@ — already exist for this route datatype? This is the
-- single delegation probe shared by all the generators: when it answers 'True'
-- the parent delegates to the existing instance, and when 'False' it inlines
-- (or generates) the child itself.
--
-- Two rules, applied uniformly so the probe can never abort a splice:
--
--   * An unresolved 'RouteCon' (the datatype is being generated in the same
--     splice) trivially has no instance yet, so the answer is 'False'.
--   * A resolved one is saturated by its /own/ reified arity via
--     'fullyApplyType' — never by the site's 'TyArgs'. Applying the site's
--     type args to a child that was generated at a different arity (e.g. a
--     kind-'Type' child of a parameterized site) builds an ill-kinded head,
--     and 'isInstance' /throws/ a kind error rather than returning 'False',
--     aborting the splice. Saturating by the datatype's own arity keeps the
--     probed head well-kinded in every case.
--
-- /Can the abstract parameters make 'isInstance' fail?/ No. Once the head is
-- well-kinded (above), 'isInstance' answers by head unification — \"could
-- /any/ visible instance match this head?\" — which is a total query: it
-- returns 'True' or 'False' but cannot crash on an abstract @'VarT' a@. The
-- one theoretical imprecision is /over-matching/: because the argument is an
-- unconstrained variable, an instance written only at a more specific type
-- (e.g. @instance C (R Int)@) would still unify with @C (R a)@ and report
-- 'True'. That is harmless here because our codegen emits the nested-discovery
-- instances uniformly, one per route datatype at a fully abstract parameter
-- (e.g. @instance YesodDispatchNested (R a)@), so \"could match\" and \"does
-- match\" coincide — there is no narrower instance for the probe to confuse a
-- variable with. (Higher-kinded parameters are covered by the same argument;
-- see 'fullyApplyType'.)
--
-- @since 1.7.0.0
nestedInstanceExists :: Name -> RouteCon -> Q Bool
nestedInstanceExists :: Name -> RouteCon -> Q Bool
nestedInstanceExists Name
klass RouteCon
rc =
    case RouteCon -> Maybe Name
rcResolved RouteCon
rc of
        Maybe Name
Nothing       -> Bool -> Q Bool
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False
        Just Name
typeName -> do
            appliedT <- Name -> Q Type
fullyApplyType Name
typeName
            isInstance klass [appliedT]

-- | The fully-applied route 'Type' for a 'RouteCon', as used for an instance
-- head. This is the single place the \"saturate by site 'TyArgs' vs. by the
-- datatype's own reified arity\" choice is made:
--
--   * With explicit 'TyArgs' (a parameterized site) the supplied type
--     arguments are applied to the constructor — the resolved 'Name' if in
--     scope, otherwise the bare 'mkName' (so a datatype being generated in the
--     same splice still gets a head to reference).
--   * With 'NoTyArgs' a resolved datatype is reified and saturated with fresh
--     type variables (needed for e.g. @mkYesodSubDispatch@, which doesn't know
--     the parent's type args); an unresolved one falls back to the bare
--     constructor.
--
-- @since 1.7.0.0
appliedRouteTypeCon :: RouteCon -> TyArgs -> Q Type
appliedRouteTypeCon :: RouteCon -> TyArgs -> Q Type
appliedRouteTypeCon RouteCon
rc TyArgs
tyargs =
    case (RouteCon -> Maybe Name
rcResolved RouteCon
rc, TyArgs
tyargs) of
        (Just Name
typeName, TyArgs
NoTyArgs)     -> Name -> Q Type
fullyApplyType Name
typeName
        (Just Name
typeName, SomeTyArgs{}) -> Type -> Q Type
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Type -> Q Type) -> Type -> Q Type
forall a b. (a -> b) -> a -> b
$ Type -> TyArgs -> Type
applyTyArgs (Name -> Type
ConT Name
typeName) TyArgs
tyargs
        (Maybe Name
Nothing,       TyArgs
_)            -> Type -> Q Type
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Type -> Q Type) -> Type -> Q Type
forall a b. (a -> b) -> a -> b
$ Type -> TyArgs -> Type
applyTyArgs (Name -> Type
ConT (String -> Name
mkName (RouteCon -> String
rcName RouteCon
rc))) TyArgs
tyargs

-- | 'appliedRouteTypeCon' starting from the route datatype's name as a
-- 'String': resolve it ('resolveRouteCon') and apply the type arguments. The
-- fallback for an unresolved name (the bare constructor) is why this can't be
-- a plain @'lookupTypeName' >>=@ that requires the name to be in scope.
appliedRouteTypeNamed :: String -> TyArgs -> Q Type
appliedRouteTypeNamed :: String -> TyArgs -> Q Type
appliedRouteTypeNamed String
routeName TyArgs
tyargs = do
    rc <- String -> Q RouteCon
resolveRouteCon String
routeName
    appliedRouteTypeCon rc tyargs

-- | A subsite's type-constructor name. Distinct from 'RouteName' so the two
-- can't be swapped at a 'checkNestedSubArity' call site without a type error.
--
-- @since 1.7.0.0
newtype SubsiteName = SubsiteName String deriving (SubsiteName -> SubsiteName -> Bool
(SubsiteName -> SubsiteName -> Bool)
-> (SubsiteName -> SubsiteName -> Bool) -> Eq SubsiteName
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SubsiteName -> SubsiteName -> Bool
== :: SubsiteName -> SubsiteName -> Bool
$c/= :: SubsiteName -> SubsiteName -> Bool
/= :: SubsiteName -> SubsiteName -> Bool
Eq, Int -> SubsiteName -> String -> String
[SubsiteName] -> String -> String
SubsiteName -> String
(Int -> SubsiteName -> String -> String)
-> (SubsiteName -> String)
-> ([SubsiteName] -> String -> String)
-> Show SubsiteName
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> SubsiteName -> String -> String
showsPrec :: Int -> SubsiteName -> String -> String
$cshow :: SubsiteName -> String
show :: SubsiteName -> String
$cshowList :: [SubsiteName] -> String -> String
showList :: [SubsiteName] -> String -> String
Show)

-- | A nested route datatype's name. See 'SubsiteName'.
--
-- @since 1.7.0.0
newtype RouteName = RouteName String deriving (RouteName -> RouteName -> Bool
(RouteName -> RouteName -> Bool)
-> (RouteName -> RouteName -> Bool) -> Eq RouteName
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RouteName -> RouteName -> Bool
== :: RouteName -> RouteName -> Bool
$c/= :: RouteName -> RouteName -> Bool
/= :: RouteName -> RouteName -> Bool
Eq, Int -> RouteName -> String -> String
[RouteName] -> String -> String
RouteName -> String
(Int -> RouteName -> String -> String)
-> (RouteName -> String)
-> ([RouteName] -> String -> String)
-> Show RouteName
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> RouteName -> String -> String
showsPrec :: Int -> RouteName -> String -> String
$cshow :: RouteName -> String
show :: RouteName -> String
$cshowList :: [RouteName] -> String -> String
showList :: [RouteName] -> String -> String
Show)

-- | How many type arguments a subsite has. Distinct from 'RouteArity' so the
-- two arities can't be swapped (the equality predicate is symmetric, but the
-- error message is not).
--
-- @since 1.7.0.0
newtype SubsiteArity = SubsiteArity Int deriving (SubsiteArity -> SubsiteArity -> Bool
(SubsiteArity -> SubsiteArity -> Bool)
-> (SubsiteArity -> SubsiteArity -> Bool) -> Eq SubsiteArity
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SubsiteArity -> SubsiteArity -> Bool
== :: SubsiteArity -> SubsiteArity -> Bool
$c/= :: SubsiteArity -> SubsiteArity -> Bool
/= :: SubsiteArity -> SubsiteArity -> Bool
Eq, Int -> SubsiteArity -> String -> String
[SubsiteArity] -> String -> String
SubsiteArity -> String
(Int -> SubsiteArity -> String -> String)
-> (SubsiteArity -> String)
-> ([SubsiteArity] -> String -> String)
-> Show SubsiteArity
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> SubsiteArity -> String -> String
showsPrec :: Int -> SubsiteArity -> String -> String
$cshow :: SubsiteArity -> String
show :: SubsiteArity -> String
$cshowList :: [SubsiteArity] -> String -> String
showList :: [SubsiteArity] -> String -> String
Show)

-- | The declared type-parameter arity of a nested route datatype. See
-- 'SubsiteArity'.
--
-- @since 1.7.0.0
newtype RouteArity = RouteArity Int deriving (RouteArity -> RouteArity -> Bool
(RouteArity -> RouteArity -> Bool)
-> (RouteArity -> RouteArity -> Bool) -> Eq RouteArity
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RouteArity -> RouteArity -> Bool
== :: RouteArity -> RouteArity -> Bool
$c/= :: RouteArity -> RouteArity -> Bool
/= :: RouteArity -> RouteArity -> Bool
Eq, Int -> RouteArity -> String -> String
[RouteArity] -> String -> String
RouteArity -> String
(Int -> RouteArity -> String -> String)
-> (RouteArity -> String)
-> ([RouteArity] -> String -> String)
-> Show RouteArity
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> RouteArity -> String -> String
showsPrec :: Int -> RouteArity -> String -> String
$cshow :: RouteArity -> String
show :: RouteArity -> String
$cshowList :: [RouteArity] -> String -> String
showList :: [RouteArity] -> String -> String
Show)

-- | A detected mismatch between a subsite's type-argument count and its nested
-- route datatype's declared arity. Carrying the four facts (rather than a
-- pre-rendered 'String') lets the caller decide how to surface it and lets
-- tests assert on structure instead of substring-matching a message.
--
-- @since 1.7.0.0
data ArityMismatch = ArityMismatch
    { ArityMismatch -> SubsiteName
amSubsiteName  :: SubsiteName
    , ArityMismatch -> RouteName
amRouteName    :: RouteName
    , ArityMismatch -> SubsiteArity
amSubsiteArity :: SubsiteArity
    , ArityMismatch -> RouteArity
amRouteArity   :: RouteArity
    } deriving (ArityMismatch -> ArityMismatch -> Bool
(ArityMismatch -> ArityMismatch -> Bool)
-> (ArityMismatch -> ArityMismatch -> Bool) -> Eq ArityMismatch
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ArityMismatch -> ArityMismatch -> Bool
== :: ArityMismatch -> ArityMismatch -> Bool
$c/= :: ArityMismatch -> ArityMismatch -> Bool
/= :: ArityMismatch -> ArityMismatch -> Bool
Eq, Int -> ArityMismatch -> String -> String
[ArityMismatch] -> String -> String
ArityMismatch -> String
(Int -> ArityMismatch -> String -> String)
-> (ArityMismatch -> String)
-> ([ArityMismatch] -> String -> String)
-> Show ArityMismatch
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> ArityMismatch -> String -> String
showsPrec :: Int -> ArityMismatch -> String -> String
$cshow :: ArityMismatch -> String
show :: ArityMismatch -> String
$cshowList :: [ArityMismatch] -> String -> String
showList :: [ArityMismatch] -> String -> String
Show)

-- | Validate that a parameterized subsite's nested route datatype carries
-- exactly as many type parameters as the subsite has type arguments: 'Nothing'
-- when the arities match, or a structured 'ArityMismatch' otherwise.
--
-- 'mkYesodSubDispatchInstance' applies the subsite's type arguments to each
-- nested route datatype (e.g. @NestedR subsite@) and uses the result directly
-- as the head of a @YesodSubDispatchNested@ instance, which expects a fully
-- applied (kind 'Type') route. So the arities must match exactly:
--
--   * Too few parameters on the nested datatype (e.g. it was generated by
--     plain 'mkYesodSubData', kind 'Type') over-applies it.
--   * Too many leaves it partially applied (kind @Type -> ...@).
--
-- Either way the result is a kind error reported deep inside generated code.
-- Surfacing it here (the caller passes the 'ArityMismatch' to 'fail') turns
-- it into an actionable, attributable message.
--
-- Pure so it can be unit-tested directly.
--
-- @since 1.7.0.0
checkNestedSubArity
    :: SubsiteName
    -> RouteName
    -> SubsiteArity
    -> RouteArity
    -> Maybe ArityMismatch
checkNestedSubArity :: SubsiteName
-> RouteName -> SubsiteArity -> RouteArity -> Maybe ArityMismatch
checkNestedSubArity SubsiteName
subName RouteName
routeName (SubsiteArity Int
subArgs) (RouteArity Int
nestedArity)
    | Int
subArgs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
nestedArity = Maybe ArityMismatch
forall a. Maybe a
Nothing
    | Bool
otherwise = ArityMismatch -> Maybe ArityMismatch
forall a. a -> Maybe a
Just (ArityMismatch -> Maybe ArityMismatch)
-> ArityMismatch -> Maybe ArityMismatch
forall a b. (a -> b) -> a -> b
$ SubsiteName
-> RouteName -> SubsiteArity -> RouteArity -> ArityMismatch
ArityMismatch SubsiteName
subName RouteName
routeName (Int -> SubsiteArity
SubsiteArity Int
subArgs) (Int -> RouteArity
RouteArity Int
nestedArity)

-- | Which generator is running the arity check. The arity facts are identical
-- either way; this only steers 'arityMismatchMessage' so the failure names the
-- right entry point and calls the parameterized thing by its correct term
-- (a top-level site reached through the nested-dispatch recursion is not a
-- \"subsite\").
--
-- @since 1.7.0.0
data ArityCallSite
    = SubsiteCall   -- ^ a subsite, generated by 'mkYesodSubDispatchInstance'
    | TopLevelCall  -- ^ a top-level site's nested-dispatch recursion
    deriving (ArityCallSite -> ArityCallSite -> Bool
(ArityCallSite -> ArityCallSite -> Bool)
-> (ArityCallSite -> ArityCallSite -> Bool) -> Eq ArityCallSite
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ArityCallSite -> ArityCallSite -> Bool
== :: ArityCallSite -> ArityCallSite -> Bool
$c/= :: ArityCallSite -> ArityCallSite -> Bool
/= :: ArityCallSite -> ArityCallSite -> Bool
Eq, Int -> ArityCallSite -> String -> String
[ArityCallSite] -> String -> String
ArityCallSite -> String
(Int -> ArityCallSite -> String -> String)
-> (ArityCallSite -> String)
-> ([ArityCallSite] -> String -> String)
-> Show ArityCallSite
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> ArityCallSite -> String -> String
showsPrec :: Int -> ArityCallSite -> String -> String
$cshow :: ArityCallSite -> String
show :: ArityCallSite -> String
$cshowList :: [ArityCallSite] -> String -> String
showList :: [ArityCallSite] -> String -> String
Show)

-- | Run 'checkNestedSubArity' for a (possibly unresolved) nested route
-- datatype and 'fail' with 'arityMismatchMessage' on a mismatch. A no-op when
-- the datatype is not in scope — an unresolved name has no knowable arity, so
-- the error (if any) surfaces from the generated code instead. This is the
-- single arity-guard shared by 'mkYesodSubDispatchInstance' and the nested
-- dispatch-instance recursion.
--
-- @since 1.7.0.0
assertNestedSubArity :: ArityCallSite -> SubsiteName -> SubsiteArity -> RouteCon -> Q ()
assertNestedSubArity :: ArityCallSite -> SubsiteName -> SubsiteArity -> RouteCon -> Q ()
assertNestedSubArity ArityCallSite
callSite SubsiteName
subName SubsiteArity
subArity RouteCon
rc =
    case RouteCon -> Maybe Name
rcResolved RouteCon
rc of
        Maybe Name
Nothing -> () -> Q ()
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        Just Name
tyname -> do
            nestedArity <- Name -> Q Int
typeArity Name
tyname
            maybe (pure ()) (fail . arityMismatchMessage callSite) $
                checkNestedSubArity subName (RouteName (rcName rc)) subArity (RouteArity nestedArity)

-- | The actionable @fail@ message for an 'ArityMismatch', phrased for the
-- 'ArityCallSite' that detected it.
--
-- @since 1.7.0.0
arityMismatchMessage :: ArityCallSite -> ArityMismatch -> String
arityMismatchMessage :: ArityCallSite -> ArityMismatch -> String
arityMismatchMessage ArityCallSite
callSite (ArityMismatch (SubsiteName String
subName) (RouteName String
routeName) (SubsiteArity Int
subArgs) (RouteArity Int
nestedArity)) =
    [String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat
        [ String
prefix, String
": the nested route datatype `", String
routeName
        , String
"` has ", Int -> String
forall a. Show a => a -> String
show Int
nestedArity, String
" type parameter(s), but the ", String
term, String
" `"
        , String
subName, String
"` has ", Int -> String
forall a. Show a => a -> String
show Int
subArgs
        , String
". The subroute datatypes must carry exactly the ", String
term, String
"'s type "
        , String
"parameter(s) — generate the ", String
term, String
"'s routes with "
        , String
"`mkYesodSubDataOpts (setParameterizedSubroute True defaultOpts) ...` "
        , String
"so a parameterized ", String
term, String
" gets parameterized subroutes."
        ]
  where
    (String
prefix, String
term) = case ArityCallSite
callSite of
        ArityCallSite
SubsiteCall  -> (String
"mkYesodSubDispatchInstance", String
"subsite")
        ArityCallSite
TopLevelCall -> (String
"mkYesod", String
"site")

-- | Turn a single route piece into a match pattern, returning the freshly
-- bound 'Name' for dynamic pieces (and 'Nothing' for static ones). The
-- fresh-'Name' supply is the 'Quote' @m@ it runs in: the 'Q' code generators
-- run at 'Q' (hygienic 'newName'), while the pure, deterministic inline-parse
-- path runs at a 'Quote' instance over a monotonic counter (see the test
-- harness). This is the single source of truth for the
-- @ViewP fromPathPiece (Just x)@ dynamic encoding shared by the parse and
-- dispatch clause builders.
handlePieceM :: Quote m => Piece a -> m (Pat, Maybe Name)
handlePieceM :: forall (m :: * -> *) a. Quote m => Piece a -> m (Pat, Maybe Name)
handlePieceM (Static String
str) = (Pat, Maybe Name) -> m (Pat, Maybe Name)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Lit -> Pat
LitP (Lit -> Pat) -> Lit -> Pat
forall a b. (a -> b) -> a -> b
$ String -> Lit
StringL String
str, Maybe Name
forall a. Maybe a
Nothing)
handlePieceM (Dynamic a
_) = Name -> (Pat, Maybe Name)
mk (Name -> (Pat, Maybe Name)) -> m Name -> m (Pat, Maybe Name)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> m Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"dyn"
  where
    mk :: Name -> (Pat, Maybe Name)
mk Name
x = (Exp -> Pat -> Pat
ViewP (Name -> Exp
VarE 'fromPathPiece) (Name -> [Pat] -> Pat
conPCompat 'Just [Name -> Pat
VarP Name
x]), Name -> Maybe Name
forall a. a -> Maybe a
Just Name
x)

-- | The list form of 'handlePieceM' projecting the dynamic binders as 'Name's,
-- for callers that consume the bound variables directly (e.g. nested-dispatch
-- handler arguments).
handlePiecesNames :: Quote m => [Piece a] -> m ([Pat], [Name])
handlePiecesNames :: forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Name])
handlePiecesNames =
    ([(Pat, Maybe Name)] -> ([Pat], [Name]))
-> m [(Pat, Maybe Name)] -> m ([Pat], [Name])
forall a b. (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\[(Pat, Maybe Name)]
pps -> (((Pat, Maybe Name) -> Pat) -> [(Pat, Maybe Name)] -> [Pat]
forall a b. (a -> b) -> [a] -> [b]
map (Pat, Maybe Name) -> Pat
forall a b. (a, b) -> a
fst [(Pat, Maybe Name)]
pps, ((Pat, Maybe Name) -> Maybe Name) -> [(Pat, Maybe Name)] -> [Name]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Pat, Maybe Name) -> Maybe Name
forall a b. (a, b) -> b
snd [(Pat, Maybe Name)]
pps)) (m [(Pat, Maybe Name)] -> m ([Pat], [Name]))
-> ([Piece a] -> m [(Pat, Maybe Name)])
-> [Piece a]
-> m ([Pat], [Name])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Piece a -> m (Pat, Maybe Name))
-> [Piece a] -> m [(Pat, Maybe Name)]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Piece a -> m (Pat, Maybe Name)
forall (m :: * -> *) a. Quote m => Piece a -> m (Pat, Maybe Name)
handlePieceM

-- | The list form of 'handlePieceM' projecting the dynamic binders as 'VarE'
-- expressions, for callers that rebuild a route by applying its constructor to
-- the captured pieces.
handlePiecesM :: Quote m => [Piece a] -> m ([Pat], [Exp])
handlePiecesM :: forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Exp])
handlePiecesM =
    (([Pat], [Name]) -> ([Pat], [Exp]))
-> m ([Pat], [Name]) -> m ([Pat], [Exp])
forall a b. (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\([Pat]
pats, [Name]
names) -> ([Pat]
pats, (Name -> Exp) -> [Name] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Exp
VarE [Name]
names)) (m ([Pat], [Name]) -> m ([Pat], [Exp]))
-> ([Piece a] -> m ([Pat], [Name]))
-> [Piece a]
-> m ([Pat], [Exp])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Piece a] -> m ([Pat], [Name])
forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Name])
handlePiecesNames

-- | Rebuild a route by applying its constructor (named by 'String', resolved
-- with 'mkName') to the captured dynamic-piece expressions — the companion to
-- 'handlePiecesM', which produces the @['Exp']@. This is the single spelling
-- of the @'foldl'' 'AppE' ('ConE' ('mkName' name))@ route-construction idiom
-- that recurred across the dispatch and parse clause builders.
applyConPieces :: String -> [Exp] -> Exp
applyConPieces :: String -> [Exp] -> Exp
applyConPieces String
name = (Exp -> Exp -> Exp) -> Exp -> [Exp] -> Exp
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Exp -> Exp -> Exp
AppE (Name -> Exp
ConE (String -> Name
mkName String
name))

-- | @composeE f g@ is the expression @f . g@.
composeE :: Exp -> Exp -> Exp
composeE :: Exp -> Exp -> Exp
composeE Exp
f Exp
g = Maybe Exp -> Exp -> Maybe Exp -> Exp
InfixE (Exp -> Maybe Exp
forall a. a -> Maybe a
Just Exp
f) (Name -> Exp
VarE '(.)) (Exp -> Maybe Exp
forall a. a -> Maybe a
Just Exp
g)

-- | @consE x xs@ is the expression @x : xs@.
consE :: Exp -> Exp -> Exp
consE :: Exp -> Exp -> Exp
consE Exp
x Exp
xs = Maybe Exp -> Exp -> Maybe Exp -> Exp
InfixE (Exp -> Maybe Exp
forall a. a -> Maybe a
Just Exp
x) (Name -> Exp
ConE '(:)) (Exp -> Maybe Exp
forall a. a -> Maybe a
Just Exp
xs)

-- | How a path match pattern ends, after its matched piece patterns. Only
-- these four shapes are ever valid as a path tail, so making it a closed type
-- (rather than an arbitrary 'Pat') stops a caller from silently matching the
-- wrong number of segments — e.g. binding a @rest@ where the path was meant to
-- end exactly.
data PathTail
    = EndExact      -- ^ @[]@ — the path ends exactly here
    | EndRest Name  -- ^ bind the remaining segments to the given variable
    | EndWild       -- ^ @_@ — ignore any remaining segments
    | EndMulti Name -- ^ a trailing multipiece: @'fromPathMultiPiece' -> 'Just' n@

-- | The 'Pat' a 'PathTail' denotes (the seed the matched piece patterns are
-- consed onto in 'mkPathPat').
pathTailPat :: PathTail -> Pat
pathTailPat :: PathTail -> Pat
pathTailPat PathTail
EndExact     = Name -> [Pat] -> Pat
conPCompat '[] []
pathTailPat (EndRest Name
n)  = Name -> Pat
VarP Name
n
pathTailPat PathTail
EndWild      = Pat
WildP
pathTailPat (EndMulti Name
n) = Exp -> Pat -> Pat
ViewP (Name -> Exp
VarE 'fromPathMultiPiece) (Name -> [Pat] -> Pat
conPCompat 'Just [Name -> Pat
VarP Name
n])

-- | Build a path match pattern: a list pattern of the given piece patterns
-- ending in the given 'PathTail'.
mkPathPat :: PathTail -> [Pat] -> Pat
mkPathPat :: PathTail -> [Pat] -> Pat
mkPathPat PathTail
tl = (Pat -> Pat -> Pat) -> Pat -> [Pat] -> Pat
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (\Pat
x Pat
y -> Name -> [Pat] -> Pat
conPCompat '(:) [Pat
x, Pat
y]) (PathTail -> Pat
pathTailPat PathTail
tl)

-- | Generate a single-argument lambda expression with a fresh name.
-- Takes a base name hint, generates a unique 'Name', and passes it
-- to a callback that produces the lambda body. Returns the complete
-- 'LamE' expression.
--
-- For multi-argument lambdas, nest calls — @\\x y -> body@ is
-- equivalent to @\\x -> \\y -> body@.
mkLambda :: String -> (Name -> Q Exp) -> Q Exp
mkLambda :: String -> (Name -> Q Exp) -> Q Exp
mkLambda String
hint Name -> Q Exp
mkBody = do
    n <- String -> Q Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
hint
    bdy <- mkBody n
    pure $ LamE [VarP n] bdy

-- | Given a target 'String', find the 'ResourceParent' in the
-- @['ResourceTree' a]@ corresponding to that target and return it.
-- Also return the @['Piece' a]@ captures that precede it.
findNestedRoute :: String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute :: forall a.
String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute String
_ [] = Maybe ([Piece a], [ResourceTree a])
forall a. Maybe a
Nothing
findNestedRoute String
target (ResourceTree a
res : [ResourceTree a]
ress) =
    case ResourceTree a
res of
        ResourceLeaf Resource a
_ ->
            String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
forall a.
String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute String
target [ResourceTree a]
ress
        ResourceParent String
name Bool
_overlap Set String
_attrs [Piece a]
pieces [ResourceTree a]
children -> do
            if String
name String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
target
                then ([Piece a], [ResourceTree a])
-> Maybe ([Piece a], [ResourceTree a])
forall a. a -> Maybe a
Just ([Piece a]
pieces, [ResourceTree a]
children)
                else
                    let mresult :: Maybe ([Piece a], [ResourceTree a])
mresult = String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
forall a.
String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute String
target [ResourceTree a]
children
                    in
                        case Maybe ([Piece a], [ResourceTree a])
mresult of
                            Maybe ([Piece a], [ResourceTree a])
Nothing -> do
                                String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
forall a.
String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute String
target [ResourceTree a]
ress
                            Just ([Piece a]
typs, [ResourceTree a]
childRoute) -> do
                                ([Piece a], [ResourceTree a])
-> Maybe ([Piece a], [ResourceTree a])
forall a. a -> Maybe a
Just ([Piece a]
pieces [Piece a] -> [Piece a] -> [Piece a]
forall a. Semigroup a => a -> a -> a
<> [Piece a]
typs, [ResourceTree a]
childRoute)