{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ViewPatterns #-}

module Yesod.Routes.TH.Dispatch
    ( MkDispatchSettings (..)
    , mkDispatchClause
    , defaultGetHandler
    , SDC(..)
    , mkDispatchInstance
    , mkNestedDispatchInstance
    , mkNestedDispatchInstanceWith
    , NestedTarget (..)
    , SameSpliceNestedInstances (..)
    , mkMDS
    , mkYesodSubDispatch
    , mkYesodSubDispatchWith
    , mkYesodSubDispatchWithDelegate
    , subTopDispatch
    , parseYesodName
    ) where

import Text.Parsec (parse, many1, many, eof, try, option, sepBy1)
import Text.ParserCombinators.Parsec.Char (alphaNum, spaces, string, char)
import Data.Maybe
import Data.Proxy (Proxy(..))
import Yesod.Routes.TH.RenderRoute
import qualified Network.Wai as W
import Yesod.Core.Content (ToTypedContent (..))
import Language.Haskell.TH hiding (cxt, instanceD)
import Yesod.Core.Types hiding (Body)
import Yesod.Core.Class.Dispatch
import Prelude hiding (exp)
import Yesod.Routes.TH.Internal
import Control.Monad
import Control.Monad.Reader (ReaderT, runReaderT, asks, local, lift)
import Data.List (foldl')
import Yesod.Routes.TH.Types
import Data.Char (toLower)
import Yesod.Core.Internal.Run
import Yesod.Core.Handler
import Yesod.Core.Class.Dispatch.ToParentRoute (ToParentRoute(..))
import Yesod.Core.Class.Yesod (Yesod)

-- | This datatype describes how to create the dispatch clause for a route
-- path.
data MkDispatchSettings b site c = MkDispatchSettings
    { forall b site c. MkDispatchSettings b site c -> Q Exp
mdsRunHandler :: Q Exp
    , forall b site c. MkDispatchSettings b site c -> Q Exp
mdsSubDispatcher :: Q Exp
    , forall b site c. MkDispatchSettings b site c -> Q Exp
mdsGetPathInfo :: Q Exp
    , forall b site c. MkDispatchSettings b site c -> Q Exp
mdsSetPathInfo :: Q Exp
    , forall b site c. MkDispatchSettings b site c -> Q Exp
mdsMethod :: Q Exp
    , forall b site c. MkDispatchSettings b site c -> Q Exp
mds404 :: Q Exp
    , forall b site c. MkDispatchSettings b site c -> Q Exp
mds405 :: Q Exp
    , forall b site c.
MkDispatchSettings b site c -> Maybe [Char] -> [Char] -> Q Exp
mdsGetHandler :: Maybe String -> String -> Q Exp
    , forall b site c. MkDispatchSettings b site c -> Exp -> Q Exp
mdsUnwrapper :: Exp -> Q Exp
    , forall b site c. MkDispatchSettings b site c -> Bool
mdsNestedRouteFallthrough :: !Bool
    -- ^ When 'True', fall through if no route matches (except in the final
    -- case). When 'False', return 404 if the current route clause fails to
    -- match.
    --
    -- @since 1.7.0.0
    , forall b site c. MkDispatchSettings b site c -> NestedTarget
mdsNestedTarget :: NestedTarget
    -- ^ Whether this dispatch is for a top-level site or a subsite. Selects the
    -- nested-dispatch class to probe ('nestedTargetClass') and the
    -- nested-dispatch function to delegate to ('nestedTargetFn'):
    -- 'TopLevelNested' uses @YesodDispatchNested@\/@yesodDispatchNested@,
    -- 'SubsiteNested' uses @YesodSubDispatchNested@\/@yesodSubDispatchNested@.
    --
    -- @since 1.7.0.0
    , forall b site c.
MkDispatchSettings b site c -> SameSpliceNestedInstances
mdsSameSpliceNestedInstances :: !SameSpliceNestedInstances
    -- ^ Whether the caller emits the matching per-parent nested-dispatch
    -- instances in the same splice as this flat dispatch body; see
    -- 'SameSpliceNestedInstances' for how this affects a parent clause.
    -- 'mkMDS' defaults to 'NoSameSpliceNestedInstances'.
    --
    -- @since 1.7.0.0
    }

data SDC = SDC
    { SDC -> [Exp]
extraParams :: [Exp]
    , SDC -> [Exp]
extraCons :: [Exp]
    , SDC -> Exp
envExp :: Exp
    , SDC -> Exp
reqExp :: Exp
    }

-- | Which phase of clause generation we're in, which is the only thing that
-- decides how a matched result is wrapped (see 'wrapForPhase'). At the top level
-- the dispatch result is returned unwrapped; inside a parent's inline children
-- we generate helper clauses whose enclosing parent must tell a match from a
-- fall-through miss, so the result is wrapped in 'Just'. Generation starts at
-- 'TopLevelPhase' and flips to 'NestedPhase' on the first descent (and never
-- back), so the two phases are a single 'local'.
data DispatchPhase = TopLevelPhase | NestedPhase

-- | How a matched result is wrapped in a given phase. See 'DispatchPhase'.
wrapForPhase :: DispatchPhase -> Exp -> Exp
wrapForPhase :: DispatchPhase -> Exp -> Exp
wrapForPhase DispatchPhase
TopLevelPhase = Exp -> Exp
forall a. a -> a
id
wrapForPhase DispatchPhase
NestedPhase = \Exp
e -> Name -> Exp
ConE 'Just Exp -> Exp -> Exp
`AppE` Exp
e

-- | The reader environment threaded through 'mkDispatchClause's clause
-- generator. 'envSdc' is the accumulated dispatch context (extended via 'local'
-- as we descend into a parent's children); 'envPhase' selects how a matched
-- result is wrapped.
data Env = Env
    { Env -> SDC
envSdc :: SDC
    , Env -> DispatchPhase
envPhase :: DispatchPhase
    }

-- | The monad 'mkDispatchClause's clause generator runs in: 'Q' carrying an
-- 'Env' read through 'MonadReader'. Every helper that needs the dispatch
-- context or the result wrapper takes them from the environment ('asks' /
-- 'local') rather than as arguments; 'liftQ' lifts the concrete-'Q' primitives.
type DispatchM = ReaderT Env Q

-- | Whether nested-route dispatch is being generated for a top-level site or
-- for a subsite. This is the single bit that selects the whole top-vs-subsite
-- plumbing: the dispatch class to probe and the function to delegate to (used
-- by 'MkDispatchSettings' via 'mdsNestedTarget'), and the runner function,
-- dispatch function\/class, and subsite-environment construction used when
-- generating nested-dispatch instances. All of those follow from this enum via
-- the @nestedTarget*@ derivation functions below.
--
-- @since 1.7.0.0
data NestedTarget
    = TopLevelNested
    -- ^ A top-level site: @YesodDispatchNested@\/@yesodDispatchNested@, run via
    -- @yesodRunner@, constructing 'YesodSubRunnerEnv' directly.
    | SubsiteNested
    -- ^ A subsite: @YesodSubDispatchNested@\/@yesodSubDispatchNested@, run via
    -- @subHelper@, composing through the outer 'YesodSubRunnerEnv' (like
    -- 'subTopDispatch').
    deriving (NestedTarget -> NestedTarget -> Bool
(NestedTarget -> NestedTarget -> Bool)
-> (NestedTarget -> NestedTarget -> Bool) -> Eq NestedTarget
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: NestedTarget -> NestedTarget -> Bool
== :: NestedTarget -> NestedTarget -> Bool
$c/= :: NestedTarget -> NestedTarget -> Bool
/= :: NestedTarget -> NestedTarget -> Bool
Eq, Int -> NestedTarget -> ShowS
[NestedTarget] -> ShowS
NestedTarget -> [Char]
(Int -> NestedTarget -> ShowS)
-> (NestedTarget -> [Char])
-> ([NestedTarget] -> ShowS)
-> Show NestedTarget
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> NestedTarget -> ShowS
showsPrec :: Int -> NestedTarget -> ShowS
$cshow :: NestedTarget -> [Char]
show :: NestedTarget -> [Char]
$cshowList :: [NestedTarget] -> ShowS
showList :: [NestedTarget] -> ShowS
Show)

-- | Whether the splice emitting a flat dispatch body also generates the
-- matching per-parent nested-dispatch instances (@YesodDispatchNested@ \/
-- @YesodSubDispatchNested@) in the same declaration group.
--
-- @since 1.7.0.0
data SameSpliceNestedInstances
    = GeneratesNestedInstances
    -- ^ The caller emits the per-parent nested instances alongside the flat
    -- dispatch, so a parent clause /delegates/ to its instance even though the
    -- instance does not exist at probe time — GHC resolves it once the whole
    -- declaration group is spliced. This avoids inlining each nested leaf's
    -- dispatch into the flat body /and/ re-emitting it in the per-parent
    -- instance (see 'mkTopLevelDispatchInstance').
    | NoSameSpliceNestedInstances
    -- ^ Only the flat dispatch is emitted. A parent delegates only when its
    -- nested instance already exists (the cross-module split case) and inlines
    -- otherwise — required for standalone entry points like
    -- 'mkYesodSubDispatch', where delegating would reference a missing
    -- instance.
    deriving (SameSpliceNestedInstances -> SameSpliceNestedInstances -> Bool
(SameSpliceNestedInstances -> SameSpliceNestedInstances -> Bool)
-> (SameSpliceNestedInstances -> SameSpliceNestedInstances -> Bool)
-> Eq SameSpliceNestedInstances
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SameSpliceNestedInstances -> SameSpliceNestedInstances -> Bool
== :: SameSpliceNestedInstances -> SameSpliceNestedInstances -> Bool
$c/= :: SameSpliceNestedInstances -> SameSpliceNestedInstances -> Bool
/= :: SameSpliceNestedInstances -> SameSpliceNestedInstances -> Bool
Eq, Int -> SameSpliceNestedInstances -> ShowS
[SameSpliceNestedInstances] -> ShowS
SameSpliceNestedInstances -> [Char]
(Int -> SameSpliceNestedInstances -> ShowS)
-> (SameSpliceNestedInstances -> [Char])
-> ([SameSpliceNestedInstances] -> ShowS)
-> Show SameSpliceNestedInstances
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SameSpliceNestedInstances -> ShowS
showsPrec :: Int -> SameSpliceNestedInstances -> ShowS
$cshow :: SameSpliceNestedInstances -> [Char]
show :: SameSpliceNestedInstances -> [Char]
$cshowList :: [SameSpliceNestedInstances] -> ShowS
showList :: [SameSpliceNestedInstances] -> ShowS
Show)

-- | The nested-dispatch class to probe\/emit for a target:
-- @''YesodDispatchNested@ for top-level, @''YesodSubDispatchNested@ for subsites.
nestedTargetClass :: NestedTarget -> Name
nestedTargetClass :: NestedTarget -> Name
nestedTargetClass NestedTarget
TopLevelNested = ''YesodDispatchNested
nestedTargetClass NestedTarget
SubsiteNested  = ''YesodSubDispatchNested

-- | The nested-dispatch function to delegate to\/emit for a target:
-- @'yesodDispatchNested@ for top-level, @'yesodSubDispatchNested@ for subsites.
nestedTargetFn :: NestedTarget -> Name
nestedTargetFn :: NestedTarget -> Name
nestedTargetFn NestedTarget
TopLevelNested = 'yesodDispatchNested
nestedTargetFn NestedTarget
SubsiteNested  = 'yesodSubDispatchNested

-- | The runner function used inside generated nested-dispatch clauses:
-- @'yesodRunner@ for top-level, @'subHelper@ for subsites.
nestedTargetRunner :: NestedTarget -> Name
nestedTargetRunner :: NestedTarget -> Name
nestedTargetRunner NestedTarget
TopLevelNested = 'yesodRunner
nestedTargetRunner NestedTarget
SubsiteNested  = 'subHelper

-- | The 'ArityCallSite' for arity-mismatch error messages: a top-level site is
-- reached through @mkYesod@, a subsite through @mkYesodSubDispatchInstance@.
nestedTargetCallSite :: NestedTarget -> ArityCallSite
nestedTargetCallSite :: NestedTarget -> ArityCallSite
nestedTargetCallSite NestedTarget
TopLevelNested = ArityCallSite
TopLevelCall
nestedTargetCallSite NestedTarget
SubsiteNested  = ArityCallSite
SubsiteCall

-- | A simpler version of Yesod.Routes.TH.Dispatch.mkDispatchClause, based on
-- view patterns.
--
-- The function returns the dispatch 'Clause' along with a @['String']@ of the
-- names of nested route types that require a delegation instance to be
-- generated. For 'YesodDispatch', those are 'YesodDispatchNested' instances; for
-- the subsite case, 'YesodSubDispatchNested'.
--
-- @since 1.7.0.0 — the leading @[Name]@\/@[Exp]@ parameters were dropped and the
-- result type changed from @Clause@ to @Q ([String], Clause)@.
mkDispatchClause :: forall a b site c. TyArgs -> MkDispatchSettings b site c -> [ResourceTree a] -> Q ([String], Clause)
mkDispatchClause :: forall a b site c.
TyArgs
-> MkDispatchSettings b site c
-> [ResourceTree a]
-> Q ([[Char]], Clause)
mkDispatchClause TyArgs
tyargs MkDispatchSettings {Bool
Q Exp
SameSpliceNestedInstances
NestedTarget
Maybe [Char] -> [Char] -> Q Exp
Exp -> Q Exp
mdsRunHandler :: forall b site c. MkDispatchSettings b site c -> Q Exp
mdsSubDispatcher :: forall b site c. MkDispatchSettings b site c -> Q Exp
mdsGetPathInfo :: forall b site c. MkDispatchSettings b site c -> Q Exp
mdsSetPathInfo :: forall b site c. MkDispatchSettings b site c -> Q Exp
mdsMethod :: forall b site c. MkDispatchSettings b site c -> Q Exp
mds404 :: forall b site c. MkDispatchSettings b site c -> Q Exp
mds405 :: forall b site c. MkDispatchSettings b site c -> Q Exp
mdsGetHandler :: forall b site c.
MkDispatchSettings b site c -> Maybe [Char] -> [Char] -> Q Exp
mdsUnwrapper :: forall b site c. MkDispatchSettings b site c -> Exp -> Q Exp
mdsNestedRouteFallthrough :: forall b site c. MkDispatchSettings b site c -> Bool
mdsNestedTarget :: forall b site c. MkDispatchSettings b site c -> NestedTarget
mdsSameSpliceNestedInstances :: forall b site c.
MkDispatchSettings b site c -> SameSpliceNestedInstances
mdsRunHandler :: Q Exp
mdsSubDispatcher :: Q Exp
mdsGetPathInfo :: Q Exp
mdsSetPathInfo :: Q Exp
mdsMethod :: Q Exp
mds404 :: Q Exp
mds405 :: Q Exp
mdsGetHandler :: Maybe [Char] -> [Char] -> Q Exp
mdsUnwrapper :: Exp -> Q Exp
mdsNestedRouteFallthrough :: Bool
mdsNestedTarget :: NestedTarget
mdsSameSpliceNestedInstances :: SameSpliceNestedInstances
..} [ResourceTree a]
resources = do
    envName <- [Char] -> Q Name
forall (m :: * -> *). Quote m => [Char] -> m Name
newName [Char]
"env"
    reqName <- newName "req"
    helperName <- newName "dispatchHelper"

    let envE = Name -> Exp
VarE Name
envName
        reqE = Name -> Exp
VarE Name
reqName
        helperE = Name -> Exp
VarE Name
helperName

    clause404' <- mkClause404 envE reqE
    getPathInfo <- mdsGetPathInfo
    let pathInfo = Exp
getPathInfo Exp -> Exp -> Exp
`AppE` Exp
reqE

    let sdc = SDC
            { extraParams :: [Exp]
extraParams = []
            , extraCons :: [Exp]
extraCons = []
            , envExp :: Exp
envExp = Exp
envE
            , reqExp :: Exp
reqExp = Exp
reqE
            }
    -- Generate the dispatch clauses. 'go' runs in @'ReaderT' 'Env' Q@: the
    -- top-level call starts at @envPhase = TopLevelPhase@ so the top-level
    -- resources produce the final (unwrapped) dispatch result and report which
    -- parents need a nested-dispatch instance generated. Descending into a
    -- parent's inline children flips @envPhase@ to 'NestedPhase' (via 'local'),
    -- so children are 'Just'-wrapped helper clauses the enclosing parent can
    -- fall through on; their reported names are dropped (only top-level parents
    -- matter).
    let topEnv = Env { envSdc :: SDC
envSdc = SDC
sdc, envPhase :: DispatchPhase
envPhase = DispatchPhase
TopLevelPhase }
    (childNames, clauses) <- mconcat <$> runReaderT (mapM go resources) topEnv

    pure
        ( childNames
        , Clause
            [VarP envName, VarP reqName]
            (NormalB $ helperE `AppE` pathInfo)
            [FunD helperName $ clauses ++ [clause404']]
        )
  where
    -- Lift a concrete-'Q' action (the TH primitives and this package's own
    -- @Q@-typed helpers) into 'DispatchM'.
    liftQ :: Q x -> DispatchM x
    liftQ :: forall x. Q x -> DispatchM x
liftQ = Q x -> ReaderT Env Q x
forall (m :: * -> *) a. Monad m => m a -> ReaderT Env m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift

    -- The current phase's result wrapper (see 'wrapForPhase').
    askWrap :: DispatchM (Exp -> Exp)
    askWrap :: DispatchM (Exp -> Exp)
askWrap = (Env -> Exp -> Exp) -> DispatchM (Exp -> Exp)
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks (DispatchPhase -> Exp -> Exp
wrapForPhase (DispatchPhase -> Exp -> Exp)
-> (Env -> DispatchPhase) -> Env -> Exp -> Exp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Env -> DispatchPhase
envPhase)

    -- Run an action in the scope of a parent's inline children: extend the
    -- accumulated dynamics and parent constructors with this parent's, and flip
    -- to 'NestedPhase'. This single 'local' — entered once at the top→nested
    -- boundary and never undone — is the entire top-vs-nested phase distinction.
    withChildScope :: [Exp] -> Exp -> DispatchM r -> DispatchM r
    withChildScope :: forall r. [Exp] -> Exp -> DispatchM r -> DispatchM r
withChildScope [Exp]
dyns Exp
constr = (Env -> Env) -> ReaderT Env Q r -> ReaderT Env Q r
forall a. (Env -> Env) -> ReaderT Env Q a -> ReaderT Env Q a
forall r (m :: * -> *) a. MonadReader r m => (r -> r) -> m a -> m a
local ((Env -> Env) -> ReaderT Env Q r -> ReaderT Env Q r)
-> (Env -> Env) -> ReaderT Env Q r -> ReaderT Env Q r
forall a b. (a -> b) -> a -> b
$ \Env
e ->
        let sdc :: SDC
sdc = Env -> SDC
envSdc Env
e
        in Env
e { envSdc = sdc
                 { extraParams = extraParams sdc ++ dyns
                 , extraCons = extraCons sdc ++ [constr]
                 }
             , envPhase = NestedPhase
             }

    -- | Generate the dispatch clauses for a resource tree node, plus the
    -- @['String']@ of parents that need a nested-dispatch instance generated.
    -- Names are reported for every parent here, but only the top-level call
    -- keeps them; the parent arm drops its children's names (the deeper
    -- instances are generated by a separate recursion in
    -- 'mkNestedDispatchInstanceWith').
    go :: ResourceTree a -> DispatchM ([String], [Clause])
    go :: ResourceTree a -> ReaderT Env Q ([[Char]], [Clause])
go (ResourceParent [Char]
name Bool
_check Set [Char]
_attrs [Piece a]
pieces [ResourceTree a]
children) = do
        -- Delegate to the child's nested-dispatch instance when one already
        -- exists (the configured class: YesodDispatchNested for top-level,
        -- YesodSubDispatchNested for subsites). This is what makes splitting
        -- a parent's nested routes across modules work. When no such instance
        -- exists — the ordinary single-module case — the check fails and we
        -- inline the children below, so this stays backwards compatible.
        -- 'nestedInstanceExists' is the shared probe: it resolves the name once
        -- and saturates by the child's own reified arity, so it never aborts
        -- the splice (see its haddock).
        instanceExists <-
            Q Bool -> DispatchM Bool
forall x. Q x -> DispatchM x
liftQ (Name -> RouteCon -> Q Bool
nestedInstanceExists (NestedTarget -> Name
nestedTargetClass NestedTarget
mdsNestedTarget) (RouteCon -> Q Bool) -> Q RouteCon -> Q Bool
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< [Char] -> Q RouteCon
resolveRouteCon [Char]
name)

        -- Delegate to the nested-dispatch instance either when one already
        -- exists (cross-module split) or when the caller will generate it in
        -- this same splice ('mdsSameSpliceNestedInstances'). In the latter case
        -- the instance does not exist at probe time, but GHC resolves it after
        -- the whole declaration group is spliced — so we avoid inlining every
        -- nested leaf's dispatch logic here only to re-emit it in the parent's
        -- 'YesodDispatchNested' instance. We still report the name below so that
        -- instance actually gets generated.
        let delegate =
                Bool
instanceExists Bool -> Bool -> Bool
|| SameSpliceNestedInstances
mdsSameSpliceNestedInstances SameSpliceNestedInstances -> SameSpliceNestedInstances -> Bool
forall a. Eq a => a -> a -> Bool
== SameSpliceNestedInstances
GeneratesNestedInstances

        (pats, dyns) <- liftQ $ handlePiecesM pieces
        restName <- liftQ $ newName "_rest"
        helperName <- liftQ $ newName ("helper" ++ name)
        let helperCall = Name -> Exp
VarE Name
helperName Exp -> Exp -> Exp
`AppE` Name -> Exp
VarE Name
restName
            constr = [Char] -> [Exp] -> Exp
applyConPieces [Char]
name [Exp]
dyns

        helperClauses <-
            if delegate
                then do
                    expr <- delegateToNestedInstance name dyns
                    pure [Clause [VarP restName] (NormalB expr) []]
                else do
                    -- Inline dispatch: descend into the children with the
                    -- extended scope and 'Just' wrapping; their reported names
                    -- are dropped (only top-level parents matter).
                    childClauses <-
                        concatMap snd <$> withChildScope dyns constr (mapM go children)
                    pure $ childClauses ++ [Clause [WildP] (NormalB (ConE 'Nothing)) []]

        body <- parentBody helperCall

        -- Report this parent as needing a nested-dispatch instance whenever one
        -- does not already exist — both when we inlined and when we delegated to
        -- a yet-to-be-generated same-splice instance
        -- ('mdsSameSpliceNestedInstances').
        -- Whether the caller acts on this (i.e. actually generates the instance)
        -- is the caller's decision — see 'mkDispatchInstance'.
        pure
            ( [name | not instanceExists]
            , [ Clause
                [mkPathPat (EndRest restName) pats]
                body
                [FunD helperName helperClauses] ]
            )

    go (ResourceLeaf (Resource [Char]
name [Piece a]
pieces Dispatch a
dispatch [[Char]]
_ Bool
_check)) = do
        (pats, dyns) <- Q ([Pat], [Exp]) -> DispatchM ([Pat], [Exp])
forall x. Q x -> DispatchM x
liftQ (Q ([Pat], [Exp]) -> DispatchM ([Pat], [Exp]))
-> Q ([Pat], [Exp]) -> DispatchM ([Pat], [Exp])
forall a b. (a -> b) -> a -> b
$ [Piece a] -> Q ([Pat], [Exp])
forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Exp])
handlePiecesM [Piece a]
pieces
        (chooseMethod, finalPat) <- handleDispatch name dispatch dyns
        wrap <- askWrap
        let clauseBody = Exp -> Body
NormalB (Exp -> Exp
wrap Exp
chooseMethod)
        pure ([], [Clause [mkPathPat finalPat pats] clauseBody []])

    -- | Delegate body for a parent that already has a nested-dispatch instance:
    -- call the configured nested-dispatch function, passing this route's
    -- dynamics — plus the accumulated parent dynamics from the environment — as
    -- ParentArgs.
    delegateToNestedInstance :: String -> [Exp] -> DispatchM Exp
    delegateToNestedInstance :: [Char] -> [Exp] -> DispatchM Exp
delegateToNestedInstance [Char]
name [Exp]
dyns = do
        sdc <- (Env -> SDC) -> ReaderT Env Q SDC
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks Env -> SDC
envSdc
        let thisRouteParentArgs = SDC -> [Exp]
extraParams SDC
sdc [Exp] -> [Exp] -> [Exp]
forall a. [a] -> [a] -> [a]
++ [Exp]
dyns
        liftQ (nestedDispatchCall (nestedTargetFn mdsNestedTarget) name dyns tyargs sdc thisRouteParentArgs)

    -- | The body of a parent dispatch clause. @helperCall@ runs the parent's
    -- inline helper on the remaining path; per the fallthrough flag we either
    -- fall through on a 'Nothing' (pattern guard) or commit to a 404. The
    -- matched result is run through the current phase's wrapper.
    parentBody :: Exp -> DispatchM Body
    parentBody :: Exp -> DispatchM Body
parentBody Exp
helperCall = do
        wrap <- DispatchM (Exp -> Exp)
askWrap
        if mdsNestedRouteFallthrough
            then liftQ $ mkGuardedBody helperCall (\Name
match' -> Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Exp -> Exp
wrap (Name -> Exp
VarE Name
match')))
            else do
                sdc <- asks envSdc
                liftQ $ do
                    matchName <- newName "match"
                    baseNotFoundExp <-
                        [| $(mdsRunHandler) $(mds404) $(pure (envExp sdc)) Nothing $(pure (reqExp sdc)) |]
                    pure $ NormalB $ CaseE helperCall
                        [ Match (conPCompat 'Just [VarP matchName]) (NormalB (wrap (VarE matchName))) []
                        , Match (conPCompat 'Nothing []) (NormalB (wrap baseNotFoundExp)) []
                        ]

    -- | Build the chosen-method expression and final path tail for a leaf,
    -- reading the dispatch context ('extraParams' / 'extraCons' / 'envExp' /
    -- 'reqExp') from the environment.
    handleDispatch :: String -> Dispatch a -> [Exp] -> DispatchM (Exp, PathTail)
    handleDispatch :: [Char] -> Dispatch a -> [Exp] -> DispatchM (Exp, PathTail)
handleDispatch [Char]
name Dispatch a
dispatch' [Exp]
dyns = do
        SDC {..} <- (Env -> SDC) -> ReaderT Env Q SDC
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks Env -> SDC
envSdc
        liftQ $ case dispatch' of
                Methods Maybe a
multi [[Char]]
methods -> do
                    (finalPat, mfinalE) <-
                        case Maybe a
multi of
                            Maybe a
Nothing -> (PathTail, Maybe Exp) -> Q (PathTail, Maybe Exp)
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return (PathTail
EndExact, Maybe Exp
forall a. Maybe a
Nothing)
                            Just a
_ -> do
                                multiName <- [Char] -> Q Name
forall (m :: * -> *). Quote m => [Char] -> m Name
newName [Char]
"multi"
                                return (EndMulti multiName, Just $ VarE multiName)

                    let dynsMulti =
                            case Maybe Exp
mfinalE of
                                Maybe Exp
Nothing -> [Exp]
dyns
                                Just Exp
e -> [Exp]
dyns [Exp] -> [Exp] -> [Exp]
forall a. [a] -> [a] -> [a]
++ [Exp
e]
                        thisRoute = [Char] -> [Exp] -> Exp
applyConPieces [Char]
name [Exp]
dynsMulti
                        fullRoute = (Exp -> Exp -> Exp) -> Exp -> [Exp] -> Exp
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Exp -> Exp -> Exp
AppE Exp
thisRoute [Exp]
extraCons
                        jroute = Name -> Exp
ConE 'Just Exp -> Exp -> Exp
`AppE` Exp
fullRoute
                        allDyns = [Exp]
extraParams [Exp] -> [Exp] -> [Exp]
forall a. [a] -> [a] -> [a]
++ [Exp]
dynsMulti
                        mkRunExp Maybe [Char]
mmethod = do
                            runHandlerE <- Q Exp
mdsRunHandler
                            handlerE' <- mdsGetHandler mmethod name
                            handlerE <- mdsUnwrapper $ foldl' AppE handlerE' allDyns
                            return $ runHandlerE
                                `AppE` handlerE
                                `AppE` envExp
                                `AppE` jroute
                                `AppE` reqExp

                    func <-
                        case methods of
                            [] -> Maybe [Char] -> Q Exp
mkRunExp Maybe [Char]
forall a. Maybe a
Nothing
                            [[Char]]
_ -> do
                                getMethod <- Q Exp
mdsMethod
                                let methodE = Exp
getMethod Exp -> Exp -> Exp
`AppE` Exp
reqExp
                                matches <- forM methods $ \[Char]
method -> do
                                    exp <- Maybe [Char] -> Q Exp
mkRunExp ([Char] -> Maybe [Char]
forall a. a -> Maybe a
Just [Char]
method)
                                    return $ Match (LitP $ StringL method) (NormalB exp) []
                                match405 <- do
                                    runHandlerE <- mdsRunHandler
                                    handlerE <- mds405
                                    let exp = Exp
runHandlerE
                                            Exp -> Exp -> Exp
`AppE` Exp
handlerE
                                            Exp -> Exp -> Exp
`AppE` Exp
envExp
                                            Exp -> Exp -> Exp
`AppE` Exp
jroute
                                            Exp -> Exp -> Exp
`AppE` Exp
reqExp
                                    return $ Match WildP (NormalB exp) []
                                return $ CaseE methodE $ matches ++ [match405]

                    return (func, finalPat)

                Subsite a
_ [Char]
getSub -> do
                    restPath <- [Char] -> Q Name
forall (m :: * -> *). Quote m => [Char] -> m Name
newName [Char]
"restPath"
                    let allDyns = [Exp]
extraParams [Exp] -> [Exp] -> [Exp]
forall a. [a] -> [a] -> [a]
++ [Exp]
dyns
                    sub2 <- mkLambda "sub" $ \Name
sub ->
                        Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$ (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
a Exp
b -> Exp
a Exp -> Exp -> Exp
`AppE` Exp
b) (Name -> Exp
VarE ([Char] -> Name
mkName [Char]
getSub) Exp -> Exp -> Exp
`AppE` Name -> Exp
VarE Name
sub) [Exp]
allDyns
                    routeBuilder <- mkLambda "sroute" $ \Name
sroute ->
                        Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$ let thisRoute :: Exp
thisRoute = [Char] -> [Exp] -> Exp
applyConPieces [Char]
name [Exp]
dyns
                               in (Exp -> Exp -> Exp) -> Exp -> [Exp] -> Exp
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Exp -> Exp -> Exp
AppE (Exp -> Exp -> Exp
AppE Exp
thisRoute (Exp -> Exp) -> Exp -> Exp
forall a b. (a -> b) -> a -> b
$ Name -> Exp
VarE Name
sroute) [Exp]
extraCons
                    exp <-
                        [| $(mdsSubDispatcher)
                            $(mdsRunHandler)
                            $(pure sub2)
                            $(pure routeBuilder)
                            $(pure envExp)
                            ($(mdsSetPathInfo) $(varE restPath) $(pure reqExp)) |]
                    return (exp, EndRest restPath)

    -- The dispatch helper produced by 'mkDispatchClause' is always a terminal
    -- authority (the top-level / subsite entry point), so a final miss commits
    -- to a 404 here. Inline nested helpers built by 'go' under 'withChildScope'
    -- bake their own @Nothing@ fallback at their call site instead.
    mkClause404 :: Exp -> Exp -> Q Clause
mkClause404 Exp
envE Exp
reqE = do
        exp <- [| $(Q Exp
mdsRunHandler) $(Q Exp
mds404) $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
envE) Nothing $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
reqE) |]
        return $ Clause [WildP] (NormalB exp) []

-- | This function generates code to call the nested dispatch function
-- (either 'yesodDispatchNested' or 'yesodSubDispatchNested').
nestedDispatchCall
    :: Name
    -- ^ The dispatch function to call (e.g. 'yesodDispatchNested' or 'yesodSubDispatchNested')
    -> String
    -- ^ The name of the nested route (e.g., "FirstFooR")
    -> [Exp]
    -- ^ The dynamic arguments for this route constructor
    -> TyArgs
    -- ^ Type arguments for parameterized routes
    -> SDC
    -- ^ The accumulated 'SDC'.
    -> [Exp]
    -- ^ The parent dynamic bound variables (for passing as ParentArgs).
    -> Q Exp
nestedDispatchCall :: Name -> [Char] -> [Exp] -> TyArgs -> SDC -> [Exp] -> Q Exp
nestedDispatchCall Name
dispatchFn [Char]
routeName [Exp]
routeDyns TyArgs
tyargs SDC
sdc [Exp]
parentDyns = do
    routeType <- [Char] -> TyArgs -> Q Pred
appliedRouteTypeNamed [Char]
routeName TyArgs
tyargs
    let wrapper = (Exp -> Exp -> Exp) -> Exp -> [Exp] -> Exp
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Exp -> Exp -> Exp
composeE ([Char] -> [Exp] -> Exp
applyConPieces [Char]
routeName [Exp]
routeDyns) (SDC -> [Exp]
extraCons SDC
sdc)
    [| $(varE dispatchFn)
        (Proxy :: Proxy $(pure routeType))
        $(pure $ parentArgsExprFromExps parentDyns)
        $(pure wrapper)
        $(pure $ envExp sdc)
        $(pure $ reqExp sdc)
     |]

-- | Given an 'Exp' which should result in a @'Maybe' a@, does:
--
-- @
--   | Just a <- exp = mkRhs a
-- @
--
mkGuardedBody
    :: Exp
    -- ^ The expression to match Just with
    -> (Name -> Q Exp)
    -- ^ The function to take a 'Name' and create the right hand value on
    -- successful match.
    -> Q Body
mkGuardedBody :: Exp -> (Name -> Q Exp) -> Q Body
mkGuardedBody Exp
exp Name -> Q Exp
mkRhs = do
    matchName <- [Char] -> Q Name
forall (m :: * -> *). Quote m => [Char] -> m Name
newName [Char]
"match"
    result <- mkRhs matchName
    let patGuard =
            [Stmt] -> Guard
PatG [Pat -> Exp -> Stmt
BindS (Name -> [Pat] -> Pat
conPCompat 'Just [Name -> Pat
VarP Name
matchName]) Exp
exp]
    pure $ GuardedB [(patGuard, result)]

defaultGetHandler :: Maybe String -> String -> Q Exp
defaultGetHandler :: Maybe [Char] -> [Char] -> Q Exp
defaultGetHandler Maybe [Char]
Nothing [Char]
s = Exp -> Q Exp
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$ Name -> Exp
VarE (Name -> Exp) -> Name -> Exp
forall a b. (a -> b) -> a -> b
$ [Char] -> Name
mkName ([Char] -> Name) -> [Char] -> Name
forall a b. (a -> b) -> a -> b
$ [Char]
"handle" [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
s
defaultGetHandler (Just [Char]
method) [Char]
s = Exp -> Q Exp
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$ Name -> Exp
VarE (Name -> Exp) -> Name -> Exp
forall a b. (a -> b) -> a -> b
$ [Char] -> Name
mkName ([Char] -> Name) -> [Char] -> Name
forall a b. (a -> b) -> a -> b
$ (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
method [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
s

-- | If the generation of @'YesodDispatch'@ instance require finer
-- control of the types, contexts etc. using this combinator. You will
-- hardly need this generality. However, in certain situations, like
-- when writing library/plugin for yesod, this combinator becomes
-- handy.
mkDispatchInstance
    :: RouteOpts
    -> Type
    -- ^ The master site type
    -> Cxt
    -- ^ Context of the instance
    -> TyArgs
    -- ^ type arguments to constructors
    -> (Exp -> Q Exp)
    -- ^ Unwrap handler
    -> [ResourceTree Type]
    -- ^ The resource
    -> DecsQ
mkDispatchInstance :: RouteOpts
-> Pred
-> [Pred]
-> TyArgs
-> (Exp -> Q Exp)
-> [ResourceTree Pred]
-> DecsQ
mkDispatchInstance RouteOpts
routeOpts Pred
master [Pred]
cxt TyArgs
tyargs Exp -> Q Exp
unwrapper [ResourceTree Pred]
res =
    -- Branch on the focus target via the accessor rather than a constructor
    -- pattern, so 'RouteOpts' can stay abstract (its constructor is not
    -- exported). 'Just target' focuses a single nested route for
    -- module-splitting; 'Nothing' generates the full top-level instance.
    case RouteOpts -> Maybe [Char]
roFocusOnNestedRoute RouteOpts
routeOpts of
        Just [Char]
target ->
            RouteOpts
-> [Char]
-> Pred
-> [Pred]
-> TyArgs
-> (Exp -> Q Exp)
-> [ResourceTree Pred]
-> DecsQ
mkNestedDispatchInstance RouteOpts
routeOpts [Char]
target Pred
master [Pred]
cxt TyArgs
tyargs Exp -> Q Exp
unwrapper [ResourceTree Pred]
res
        Maybe [Char]
Nothing ->
            RouteOpts
-> Pred
-> [Pred]
-> TyArgs
-> (Exp -> Q Exp)
-> [ResourceTree Pred]
-> DecsQ
mkTopLevelDispatchInstance RouteOpts
routeOpts Pred
master [Pred]
cxt TyArgs
tyargs Exp -> Q Exp
unwrapper [ResourceTree Pred]
res

mkTopLevelDispatchInstance
    :: RouteOpts
    -> Type
    -> Cxt
    -> TyArgs
    -> (Exp -> Q Exp)
    -> [ResourceTree Type]
    -> DecsQ
mkTopLevelDispatchInstance :: RouteOpts
-> Pred
-> [Pred]
-> TyArgs
-> (Exp -> Q Exp)
-> [ResourceTree Pred]
-> DecsQ
mkTopLevelDispatchInstance RouteOpts
routeOpts Pred
master [Pred]
cxt TyArgs
tyargs Exp -> Q Exp
unwrapper [ResourceTree Pred]
res = do
    let mds :: MkDispatchSettings a site b
mds =
            (Exp -> Q Exp) -> Q Exp -> Q Exp -> MkDispatchSettings a site b
forall a site b.
(Exp -> Q Exp) -> Q Exp -> Q Exp -> MkDispatchSettings a site b
mkMDS
                Exp -> Q Exp
unwrapper
                [|yesodRunner|]
                [|\parentRunner getSub toParent env -> yesodSubDispatch
                    YesodSubRunnerEnv
                    { ysreParentRunner = parentRunner
                    , ysreGetSub = getSub
                    , ysreToParentRoute = toParent
                    , ysreParentEnv = env
                    }
                |]
        -- Under nested discovery this instance also emits a
        -- 'YesodDispatchNested' instance per top-level parent (see
        -- 'childNamesToGenerate'). When it does, the flat @yesodDispatch@ clause
        -- can /delegate/ each parent to that same-splice instance rather than
        -- inlining the whole subtree's dispatch logic (which the nested instance
        -- would then re-emit). Under 'InlineCompat' no nested instances are
        -- generated, so the flat clause must inline as before.
        usesNestedDiscovery :: Bool
usesNestedDiscovery =
            case RouteOpts -> TyArgs -> DiscoveryMode
discoveryMode RouteOpts
routeOpts TyArgs
tyargs of
                DiscoveryMode
NestedDiscovery -> Bool
True
                DiscoveryMode
InlineCompat    -> Bool
False
        mdsWithNestedDispatch :: MkDispatchSettings b site c
mdsWithNestedDispatch = MkDispatchSettings (ZonkAny 2) (ZonkAny 1) (ZonkAny 0)
forall {a} {site} {b}. MkDispatchSettings a site b
mds
            { mdsNestedRouteFallthrough = roNestedRouteFallthrough routeOpts
            , mdsSameSpliceNestedInstances =
                if usesNestedDiscovery
                    then GeneratesNestedInstances
                    else NoSameSpliceNestedInstances
            }
    (childNames, clause') <- TyArgs
-> MkDispatchSettings (ZonkAny 5) (ZonkAny 4) (ZonkAny 3)
-> [ResourceTree Pred]
-> Q ([[Char]], Clause)
forall a b site c.
TyArgs
-> MkDispatchSettings b site c
-> [ResourceTree a]
-> Q ([[Char]], Clause)
mkDispatchClause TyArgs
tyargs MkDispatchSettings (ZonkAny 5) (ZonkAny 4) (ZonkAny 3)
forall {a} {site} {b}. MkDispatchSettings a site b
mdsWithNestedDispatch [ResourceTree Pred]
res
    let thisDispatch = Name -> [Clause] -> Dec
FunD 'yesodDispatch [Clause
clause']
        -- Only generate 'YesodDispatchNested' instances for children when this
        -- site uses nested discovery. A parameterized site that has not opted
        -- in keeps unparameterized subroute datatypes (see 'discoveryMode' in
        -- RenderRoute), so generating nested instances — which would reference
        -- the parameterized form — must be suppressed to stay consistent.
        childNamesToGenerate =
            if Bool
usesNestedDiscovery then [[Char]]
childNames else []
    childInstances <-
        fmap mconcat $ forM childNamesToGenerate $ \[Char]
name -> do
            RouteOpts
-> [Char]
-> Pred
-> [Pred]
-> TyArgs
-> (Exp -> Q Exp)
-> [ResourceTree Pred]
-> DecsQ
mkNestedDispatchInstance RouteOpts
routeOpts [Char]
name Pred
master [Pred]
cxt TyArgs
tyargs Exp -> Q Exp
unwrapper [ResourceTree Pred]
res
    return (instanceD cxt yDispatch [thisDispatch] : childInstances)
  where
    yDispatch :: Pred
yDispatch = Name -> Pred
ConT ''YesodDispatch Pred -> Pred -> Pred
`AppT` Pred
master

-- | Generate the top-level @YesodDispatchNested@ instance (and the
-- @UrlToDispatch@\/@RedirectUrl@ instances for fragments with no dynamic parent
-- pieces) for a nested route target. A thin wrapper over
-- 'mkNestedDispatchInstanceWith' with the top-level config and the master site.
--
-- @since 1.7.0.0
mkNestedDispatchInstance
    :: RouteOpts
    -> String
    -> Type
    -> Cxt
    -> TyArgs -- ^ tyargs
    -> (Exp -> Q Exp)
    -> [ResourceTree Type]
    -> Q [Dec]
mkNestedDispatchInstance :: RouteOpts
-> [Char]
-> Pred
-> [Pred]
-> TyArgs
-> (Exp -> Q Exp)
-> [ResourceTree Pred]
-> DecsQ
mkNestedDispatchInstance RouteOpts
routeOpts [Char]
target Pred
master [Pred]
cxt TyArgs
tyargs Exp -> Q Exp
unwrapper [ResourceTree Pred]
res =
    NestedTarget
-> Maybe Pred
-> RouteOpts
-> [Char]
-> [Pred]
-> TyArgs
-> (Exp -> Q Exp)
-> [ResourceTree Pred]
-> DecsQ
mkNestedDispatchInstanceWith NestedTarget
TopLevelNested (Pred -> Maybe Pred
forall a. a -> Maybe a
Just Pred
master)
        RouteOpts
routeOpts [Char]
target [Pred]
cxt TyArgs
tyargs Exp -> Q Exp
unwrapper [ResourceTree Pred]
res

-- | The shared body of the top-level ('mkNestedDispatchInstance') and subsite
-- (@mkNestedSubDispatchInstance@, in "Yesod.Core.Internal.TH") nested-dispatch
-- instance generators. Both
-- find the target, build the parent-dynamics pattern, generate the dispatch
-- clauses via 'genNestedDispatchClauses', emit one
-- 'nestedTargetClass'\/'nestedTargetFn' instance, and recurse into nested
-- children. They differ only in the 'NestedTarget' (which selects the
-- dispatch function\/class, runner, and subsite-env construction) and whether a
-- master site is in play: a @'Just' master@ marks the top-level case and additionally emits
-- the @UrlToDispatch@\/@RedirectUrl@ instances, which the subsite case
-- ('Nothing') never produces.
mkNestedDispatchInstanceWith
    :: NestedTarget
    -> Maybe Type            -- ^ @Just master@ ⇒ top-level (also emit UrlToDispatch\/RedirectUrl); @Nothing@ ⇒ subsite
    -> RouteOpts
    -> String
    -> Cxt
    -> TyArgs
    -> (Exp -> Q Exp)
    -> [ResourceTree Type]
    -> Q [Dec]
mkNestedDispatchInstanceWith :: NestedTarget
-> Maybe Pred
-> RouteOpts
-> [Char]
-> [Pred]
-> TyArgs
-> (Exp -> Q Exp)
-> [ResourceTree Pred]
-> DecsQ
mkNestedDispatchInstanceWith NestedTarget
nestedTarget Maybe Pred
mmaster RouteOpts
routeOpts [Char]
target [Pred]
cxt TyArgs
tyargs Exp -> Q Exp
unwrapper [ResourceTree Pred]
res = do
    -- Resolve the target subtree from the root exactly once. The recursion into
    -- nested children below threads the already-resolved @(prePieces, subres)@
    -- straight through ('go'), rather than re-passing the full root and walking
    -- it from scratch for every descendant (which was O(nodes × depth)).
    case [Char]
-> [ResourceTree Pred] -> Maybe ([Piece Pred], [ResourceTree Pred])
forall a.
[Char] -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute [Char]
target [ResourceTree Pred]
res of
        Maybe ([Piece Pred], [ResourceTree Pred])
Nothing ->
            [Char] -> DecsQ
forall a. HasCallStack => [Char] -> Q a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
[Char] -> m a
fail ([Char] -> DecsQ) -> [Char] -> DecsQ
forall a b. (a -> b) -> a -> b
$ [Char]
"Target '" [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
target [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
"' was not found in resources."
        Just ([Piece Pred]
prePieces, [ResourceTree Pred]
subres) ->
            [Char] -> [Piece Pred] -> [ResourceTree Pred] -> DecsQ
go [Char]
target [Piece Pred]
prePieces [ResourceTree Pred]
subres
  where
   go :: [Char] -> [Piece Pred] -> [ResourceTree Pred] -> DecsQ
go [Char]
curTarget [Piece Pred]
prePieces [ResourceTree Pred]
subres = do
    -- The parent's static depth and how many dynamic pieces it consumes (only
    -- the count matters below, for the parent-dynamics pattern and the
    -- no-dynamics UrlToDispatch case).
    let parentDepth :: Int
parentDepth = [Piece Pred] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Piece Pred]
prePieces
        preDyns :: [()]
preDyns = [() | Dynamic Pred
_ <- [Piece Pred]
prePieces]
        targetT :: Pred
targetT = Pred -> TyArgs -> Pred
applyTyArgs (Name -> Pred
ConT ([Char] -> Name
mkName [Char]
curTarget)) TyArgs
tyargs

    -- UrlToDispatch/RedirectUrl is a top-level-only convenience and only
    -- possible when ParentArgs ~ () (no dynamic parent pieces).
    urlToDispatchInstances <- case (Maybe Pred
mmaster, [()]
preDyns) of
        (Just Pred
master, []) ->
            [Pred] -> [Char] -> Pred -> Pred -> DecsQ
mkUrlToDispatchRedirectInstances [Pred]
cxt [Char]
curTarget Pred
targetT Pred
master
        (Maybe Pred, [()])
_ ->
            [Dec] -> DecsQ
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []

    -- Generate the parent dynamic argument variables once, and derive the
    -- binding pattern from them. The clause-generator is handed the @['Name']@
    -- directly (it used to re-decode them out of the pattern).
    parentDynVars <- forM preDyns $ \()
_ -> [Char] -> Q Name
forall (m :: * -> *). Quote m => [Char] -> m Name
newName [Char]
"parentDyn"
    let parentDynsP = [Name] -> Pat
parentArgsPat [Name]
parentDynVars

    -- Generate names for the instance parameters
    toParentN <- newName "toParentRoute"
    envN <- newName "env"
    reqN <- newName "req"

    -- Generate dispatch clauses for each child resource
    clauses <- genNestedDispatchClauses
        nestedTarget
        routeOpts
        parentDynVars
        (VarE toParentN)
        (VarE envN)
        (VarE reqN)
        unwrapper
        tyargs
        subres

    dropExp <- [| drop parentDepth (W.pathInfo $(varE reqN)) |]
    let dispatchNestedT = Name -> Pred
ConT (NestedTarget -> Name
nestedTargetClass NestedTarget
nestedTarget) Pred -> Pred -> Pred
`AppT` Pred
targetT
        thisDispatch = Name -> [Clause] -> Dec
FunD (NestedTarget -> Name
nestedTargetFn NestedTarget
nestedTarget)
            [[Pat] -> Body -> [Dec] -> Clause
Clause
                [Pat
WildP, Pat
parentDynsP, Name -> Pat
VarP Name
toParentN, Name -> Pat
VarP Name
envN, Name -> Pat
VarP Name
reqN]
                (Exp -> Body
NormalB (Exp -> Body) -> Exp -> Body
forall a b. (a -> b) -> a -> b
$ Exp -> [Match] -> Exp
CaseE Exp
dropExp [Match]
clauses)
                []
            ]

    childInstances <-
        fmap mconcat $ forM subres $ \ResourceTree Pred
childRes -> do
            case ResourceTree Pred
childRes of
                ResourceParent [Char]
name Bool
_ Set [Char]
_ [Piece Pred]
childPieces [ResourceTree Pred]
grandchildren -> do
                    rc <- [Char] -> Q RouteCon
resolveRouteCon [Char]
name
                    instanceExists <- nestedInstanceExists (nestedTargetClass nestedTarget) rc
                    if instanceExists
                        then pure []
                        else do
                            -- Run the same arity guard the top-level
                            -- 'mkYesodSubDispatchInstance' applies, so a
                            -- 2nd-level-or-deeper nested datatype whose
                            -- parameter count doesn't match the (sub)site's
                            -- type arguments fails with the actionable message
                            -- rather than a cryptic kind error from generated
                            -- code. A no-op for the monomorphic (0-arity) case.
                            assertNestedSubArity
                                (nestedTargetCallSite nestedTarget)
                                (SubsiteName curTarget)
                                (SubsiteArity (tyArgsArity tyargs))
                                rc
                            -- Recurse on the already-resolved subtree: this
                            -- child's accumulated prefix is the parent's plus
                            -- this child's own pieces.
                            go name (prePieces <> childPieces) grandchildren
                ResourceTree Pred
_ -> [Dec] -> DecsQ
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []

    return
        ( instanceD cxt dispatchNestedT
            [ thisDispatch
            ]
        : childInstances <> urlToDispatchInstances
        )

-- | The top-level-only @UrlToDispatch@ + @RedirectUrl@ instances for a nested
-- route fragment whose @ParentArgs ~ ()@ (no dynamic parent pieces), letting
-- the fragment's constructor be used directly in @setUrl@\/@redirect@ without
-- the @WithParentArgs@ wrapper. Subsite nested dispatch emits none of these.
mkUrlToDispatchRedirectInstances
    :: Cxt
    -> String  -- ^ target route name (for the in-scope ToParentRoute check)
    -> Type    -- ^ the applied target route type
    -> Type    -- ^ the master site type
    -> Q [Dec]
mkUrlToDispatchRedirectInstances :: [Pred] -> [Char] -> Pred -> Pred -> DecsQ
mkUrlToDispatchRedirectInstances [Pred]
cxt [Char]
target Pred
targetT Pred
master = do
    urlToDispatchT <- [t| UrlToDispatch $(Pred -> Q Pred
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Pred
targetT) $(Pred -> Q Pred
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Pred
master) |]
    urlToDispatchFn <- [e| toWaiAppYreNested (Proxy :: Proxy $(pure targetT)) () |]
    mYesodConstraint <- do
        hasYesodInstance <- isInstance ''Yesod [master]
        if hasYesodInstance
            then pure []
            else do
                yesodContext <- [t| Yesod $(pure master) |]
                pure [yesodContext]
    mToParentRouteConstraint <- do
        mtypeName <- lookupTypeName target
        parentRouteCxt <- [t| ToParentRoute $(pure targetT) |]
        case mtypeName of
            Maybe Name
Nothing -> do
                -- must be generating it still. assume we don't
                -- have the instance in scope.
                [Pred] -> Q [Pred]
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [Pred
parentRouteCxt]
            Just Name
_ -> do
                -- type is around, let's make sure it's not
                -- redundant?
                hasToParentRouteInstance <- Name -> [Pred] -> Q Bool
isInstance ''ToParentRoute [Pred
targetT]
                if hasToParentRouteInstance
                    then pure []
                    else do
                        pure [parentRouteCxt]
    redirectT <- [t| RedirectUrl $(pure master) $(pure targetT) |]
    redirectUrlFn <- [e| toTextUrl . WithParentArgs () |]
    pure
        [ instanceD (cxt <> mYesodConstraint <> mToParentRouteConstraint) urlToDispatchT
            [ FunD 'urlToDispatch
                [ Clause [ WildP ] (NormalB urlToDispatchFn) []
                ]
            ]
        -- OVERLAPPABLE so a strictly more specific hand-written instance (e.g.
        -- one carrying type variables, as for a parameterized site) takes
        -- precedence over this generated convenience instance. Note that a
        -- hand-written instance with an identical fully-concrete head still
        -- collides as a duplicate, regardless of this pragma.
        , InstanceD (Just Overlappable) (cxt <> mToParentRouteConstraint) redirectT
            [ FunD 'toTextUrl
                [ Clause [ ] (NormalB redirectUrlFn) [] ]
            ]
        ]


-- | Generate dispatch clauses for nested dispatch instances.
-- Parameterized by 'NestedTarget' to support both
-- 'YesodDispatchNested' (top-level) and 'YesodSubDispatchNested' (subsite).
genNestedDispatchClauses
    :: NestedTarget
    -> RouteOpts
    -> [Name] -- ^ parent dynamic arg variables
    -> Exp -- ^ toParentRoute expression
    -> Exp -- ^ yre expression (YesodRunnerEnv or YesodSubRunnerEnv)
    -> Exp -- ^ req expression
    -> (Exp -> Q Exp) -- ^ unwrapper
    -> TyArgs -- ^ type arguments for parameterized routes
    -> [ResourceTree Type]
    -> Q [Match]
genNestedDispatchClauses :: NestedTarget
-> RouteOpts
-> [Name]
-> Exp
-> Exp
-> Exp
-> (Exp -> Q Exp)
-> TyArgs
-> [ResourceTree Pred]
-> Q [Match]
genNestedDispatchClauses NestedTarget
nestedTarget RouteOpts
routeOpts [Name]
parentDynVars Exp
toParentE Exp
yreE Exp
reqE Exp -> Q Exp
unwrapper TyArgs
tyargs [ResourceTree Pred]
resources = do
    resourceClauses <- (ResourceTree Pred -> Q [Match])
-> [ResourceTree Pred] -> Q [[Match]]
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 ResourceTree Pred -> Q [Match]
genClauseForResource [ResourceTree Pred]
resources

    -- Terminal-miss clause: a nested dispatch instance ALWAYS returns 'Nothing'
    -- when no clause matches the remaining path, regardless of this module's
    -- fallthrough flag. 'yesodDispatchNested'/'yesodSubDispatchNested' are
    -- documented to return 'Nothing' on a miss so that the *caller* (the
    -- delegating parent clause, or the top-level/subsite terminal authority)
    -- decides whether the miss commits to a 404 or falls through to a sibling.
    -- Baking a 404 in here when fallthrough is disabled would let a split-out
    -- child silently override a fallthrough-wanting parent compiled in another
    -- module. The commit semantics of @fallthrough = False@ instead live at the
    -- delegating clauses (the 'ResourceParent' arm below and the inline parent
    -- body in 'mkDispatchClause') and at the terminal authorities.
    let fallbackClause = Pat -> Body -> [Dec] -> Match
Match Pat
WildP (Exp -> Body
NormalB (Name -> Exp
ConE 'Nothing)) []

    return $ concat resourceClauses ++ [fallbackClause]
  where
    genClauseForResource :: ResourceTree Type -> Q [Match]
    genClauseForResource :: ResourceTree Pred -> Q [Match]
genClauseForResource (ResourceLeaf (Resource [Char]
name [Piece Pred]
pieces Dispatch Pred
dispatch [[Char]]
_ Bool
_check)) = do
        (pats, dynVars) <- [Piece Pred] -> Q ([Pat], [Name])
forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Name])
handlePiecesNames [Piece Pred]
pieces
        let routeCon = [Char] -> [Exp] -> Exp
applyConPieces [Char]
name ((Name -> Exp) -> [Name] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Exp
VarE [Name]
dynVars)
            allDynVars = [Name]
parentDynVars [Name] -> [Name] -> [Name]
forall a. [a] -> [a] -> [a]
++ [Name]
dynVars

        case dispatch of
            Methods Maybe Pred
mmulti [[Char]]
methods -> do
                -- Mirror the inline path (see 'handleDispatch' in
                -- 'mkDispatchClause'): a trailing multipiece binds a fresh
                -- @multi@ via 'EndMulti', and that value must be appended both
                -- to the route constructor's arguments and to the handler's
                -- arguments. Hardcoding 'EndExact' here would 404 any non-empty
                -- tail and build the constructor one argument short.
                (finalPat, mMultiE) <- case Maybe Pred
mmulti of
                    Maybe Pred
Nothing -> (PathTail, Maybe Exp) -> Q (PathTail, Maybe Exp)
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PathTail
EndExact, Maybe Exp
forall a. Maybe a
Nothing)
                    Just Pred
_ -> do
                        multiName <- [Char] -> Q Name
forall (m :: * -> *). Quote m => [Char] -> m Name
newName [Char]
"multi"
                        pure (EndMulti multiName, Just (VarE multiName))
                let dynExpsMulti = case Maybe Exp
mMultiE of
                        Maybe Exp
Nothing -> (Name -> Exp) -> [Name] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Exp
VarE [Name]
dynVars
                        Just Exp
e  -> (Name -> Exp) -> [Name] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Exp
VarE [Name]
dynVars [Exp] -> [Exp] -> [Exp]
forall a. [a] -> [a] -> [a]
++ [Exp
e]
                    routeExp = Exp
toParentE Exp -> Exp -> Exp
`AppE` [Char] -> [Exp] -> Exp
applyConPieces [Char]
name [Exp]
dynExpsMulti
                    allDynExps = (Name -> Exp) -> [Name] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Exp
VarE [Name]
parentDynVars [Exp] -> [Exp] -> [Exp]
forall a. [a] -> [a] -> [a]
++ [Exp]
dynExpsMulti
                handlerExp <- genHandlerCase name methods allDynExps
                body <-
                    [| Just ($(varE (nestedTargetRunner nestedTarget))
                                $(pure handlerExp)
                                $(pure yreE)
                                (Just $(pure routeExp))
                                $(pure reqE)) |]
                return [Match (mkPathPat finalPat pats) (NormalB body) []]

            Subsite Pred
_ [Char]
getSub -> do
                restPath <- [Char] -> Q Name
forall (m :: * -> *). Quote m => [Char] -> m Name
newName [Char]
"restPath"
                sub2 <- mkLambda "sub" $ \Name
sub ->
                    Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$ (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
VarE ([Char] -> Name
mkName [Char]
getSub) Exp -> Exp -> Exp
`AppE` Name -> Exp
VarE Name
sub) ((Name -> Exp) -> [Name] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Exp
VarE [Name]
allDynVars)
                routeLam <- mkLambda "sroute" $ \Name
srouteN ->
                    [e| $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
toParentE) ( $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
routeCon) $(Name -> Q Exp
forall (m :: * -> *). Quote m => Name -> m Exp
varE Name
srouteN)) |]
                let reqExp' = Exp -> [FieldExp] -> Exp
RecUpdE Exp
reqE [('W.pathInfo, Name -> Exp
VarE Name
restPath)]
                body <- case nestedTarget of
                    NestedTarget
TopLevelNested ->
                        -- Top-level: construct YesodSubRunnerEnv directly
                        [| Just (yesodSubDispatch
                            YesodSubRunnerEnv
                                { ysreParentRunner = yesodRunner
                                , ysreGetSub = $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
sub2)
                                , ysreToParentRoute = $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
routeLam)
                                , ysreParentEnv = $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
yreE)
                                }
                            $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
reqExp')) |]
                    NestedTarget
SubsiteNested ->
                        -- Subsite: compose through the outer YesodSubRunnerEnv
                        [| Just (yesodSubDispatch
                            YesodSubRunnerEnv
                                { ysreParentRunner = ysreParentRunner $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
yreE)
                                , ysreGetSub = $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
sub2) . ysreGetSub $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
yreE)
                                , ysreToParentRoute = ysreToParentRoute $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
yreE) . $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
routeLam)
                                , ysreParentEnv = ysreParentEnv $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
yreE)
                                }
                            $(Exp -> Q Exp
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Exp
reqExp')) |]
                return [Match (mkPathPat (EndRest restPath) pats) (NormalB body) []]

    genClauseForResource (ResourceParent [Char]
name Bool
_check Set [Char]
_attrs [Piece Pred]
pieces [ResourceTree Pred]
_children) = do
        (pats, dynVars) <- [Piece Pred] -> Q ([Pat], [Name])
forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Name])
handlePiecesNames [Piece Pred]
pieces

        -- Build the parent args tuple for the nested call
        let allDynVars = [Name]
parentDynVars [Name] -> [Name] -> [Name]
forall a. [a] -> [a] -> [a]
++ [Name]
dynVars
            parentArgsExp = [Name] -> Exp
parentArgsExpr [Name]
allDynVars
            routeConWrapper = [Char] -> [Exp] -> Exp
applyConPieces [Char]
name ((Name -> Exp) -> [Name] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Exp
VarE [Name]
dynVars)

        routeType <- appliedRouteTypeNamed name tyargs

        resultName <- newName "k"

        nestedCall <-
            [| $(varE (nestedTargetFn nestedTarget))
                (Proxy :: Proxy $(pure routeType))
                $(pure parentArgsExp)
                ($(pure toParentE) . $(pure routeConWrapper))
                $(pure yreE)
                $(pure reqE) |]

        if roNestedRouteFallthrough routeOpts
            then do
                -- Fallthrough enabled: pattern-guard on a 'Just' result, so a
                -- 'Nothing' from the delegated child lets dispatch fall through
                -- to sibling clauses (and ultimately the 'Nothing' fallback).
                let patGuard = Pat -> Exp -> Stmt
BindS (Name -> [Pat] -> Pat
conPCompat 'Just [Name -> Pat
VarP Name
resultName]) Exp
nestedCall
                    guardedBody = [(Guard, Exp)] -> Body
GuardedB [([Stmt] -> Guard
PatG [Stmt
patGuard], Name -> Exp
ConE 'Just Exp -> Exp -> Exp
`AppE` Name -> Exp
VarE Name
resultName)]
                return [Match (mkPathPat EndWild pats) guardedBody []]
            else do
                -- Fallthrough disabled: once this parent's path prefix matches we
                -- commit to its subtree. If the delegated child dispatch returns
                -- 'Nothing', convert it to a 404 handler call rather than letting
                -- the 'Nothing' propagate (which, under an outer fallthrough
                -- caller, would let it fall through to siblings). This mirrors the
                -- inline no-fallthrough path's @Nothing -> Just 404@ shape.
                committedBody <-
                    [| Just (fromMaybe
                        ($(varE (nestedTargetRunner nestedTarget))
                            (void notFound) $(pure yreE) Nothing $(pure reqE))
                        $(pure nestedCall)) |]
                return [Match (mkPathPat EndWild pats) (NormalB committedBody) []]

    genHandlerCase :: String -> [String] -> [Exp] -> Q Exp
    genHandlerCase :: [Char] -> [[Char]] -> [Exp] -> Q Exp
genHandlerCase [Char]
name [[Char]]
methods [Exp]
allDynExps = do
        let handlerExpFor :: Maybe [Char] -> Q Exp
handlerExpFor Maybe [Char]
mmethod = do
                handlerName <- Maybe [Char] -> [Char] -> Q Exp
defaultGetHandler Maybe [Char]
mmethod [Char]
name
                unwrapper $ foldl' AppE handlerName allDynExps

        if [[Char]] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [[Char]]
methods
            then do
                -- No specific methods, just call handler
                handlerE <- Maybe [Char] -> Q Exp
handlerExpFor Maybe [Char]
forall a. Maybe a
Nothing
                [| fmap toTypedContent $(pure handlerE) |]
            else do
                -- Generate method case
                -- Wrap each handler with fmap toTypedContent so all branches have the same type
                methodMatches <- [[Char]] -> ([Char] -> Q Match) -> Q [Match]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM [[Char]]
methods (([Char] -> Q Match) -> Q [Match])
-> ([Char] -> Q Match) -> Q [Match]
forall a b. (a -> b) -> a -> b
$ \[Char]
method -> do
                    handlerE <- Maybe [Char] -> Q Exp
handlerExpFor ([Char] -> Maybe [Char]
forall a. a -> Maybe a
Just [Char]
method)
                    wrappedHandler <- [| fmap toTypedContent $(pure handlerE) |]
                    return $ Match (LitP $ StringL method) (NormalB wrappedHandler) []

                badMethodHandler <- unwrapper (VarE 'badMethod)
                let badMethodMatch = Pat -> Body -> [Dec] -> Match
Match Pat
WildP (Exp -> Body
NormalB Exp
badMethodHandler) []
                scrutinee <- [| W.requestMethod $(pure reqE) |]
                return $ CaseE scrutinee (methodMatches ++ [badMethodMatch])

mkYesodSubDispatch :: [ResourceTree a] -> Q Exp
mkYesodSubDispatch :: forall a. [ResourceTree a] -> Q Exp
mkYesodSubDispatch = RouteOpts -> [ResourceTree a] -> Q Exp
forall a. RouteOpts -> [ResourceTree a] -> Q Exp
mkYesodSubDispatchWith RouteOpts
defaultOpts

-- | Like 'mkYesodSubDispatch', but threads a 'RouteOpts' into the generated
-- @yesodSubDispatch@ body. The only option that affects the body is
-- 'roNestedRouteFallthrough', which controls whether a subsite's top-level
-- parent clause falls through to a later sibling on an inner miss (mirroring
-- 'mkTopLevelDispatchInstance'). 'mkYesodSubDispatch' keeps the opts-less
-- signature for backwards compatibility.
--
-- This standalone entry point never delegates a parent's dispatch to a
-- same-splice 'YesodSubDispatchNested' instance: when called on its own there
-- are no such instances being generated alongside it (delegating would emit a
-- reference to a missing instance). 'mkYesodSubDispatchInstanceOpts', which
-- /does/ generate the matching nested instances in the same splice, uses
-- 'mkYesodSubDispatchWithDelegate' to opt into delegation.
--
-- @since 1.7.0.0
mkYesodSubDispatchWith :: RouteOpts -> [ResourceTree a] -> Q Exp
mkYesodSubDispatchWith :: forall a. RouteOpts -> [ResourceTree a] -> Q Exp
mkYesodSubDispatchWith = SameSpliceNestedInstances -> RouteOpts -> [ResourceTree a] -> Q Exp
forall a.
SameSpliceNestedInstances -> RouteOpts -> [ResourceTree a] -> Q Exp
mkYesodSubDispatchWithDelegate SameSpliceNestedInstances
NoSameSpliceNestedInstances

-- | The body-generation core shared by the standalone 'mkYesodSubDispatchWith'
-- and the instance-generating 'mkYesodSubDispatchInstanceOpts'. The
-- 'SameSpliceNestedInstances' argument says whether the caller emits the
-- per-parent 'YesodSubDispatchNested' instances in the same splice — see that
-- type for what each choice means for the generated body.
--
-- @since 1.7.0.0
mkYesodSubDispatchWithDelegate
    :: SameSpliceNestedInstances -> RouteOpts -> [ResourceTree a] -> Q Exp
mkYesodSubDispatchWithDelegate :: forall a.
SameSpliceNestedInstances -> RouteOpts -> [ResourceTree a] -> Q Exp
mkYesodSubDispatchWithDelegate SameSpliceNestedInstances
sameSplice RouteOpts
routeOpts [ResourceTree a]
res = do
    let mds :: MkDispatchSettings b site c
mds = ((Exp -> Q Exp)
-> Q Exp
-> Q Exp
-> MkDispatchSettings (ZonkAny 8) (ZonkAny 7) (ZonkAny 6)
forall a site b.
(Exp -> Q Exp) -> Q Exp -> Q Exp -> MkDispatchSettings a site b
mkMDS
                Exp -> Q Exp
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return
                [|subHelper|]
                [|subTopDispatch|])
                { mdsNestedTarget = SubsiteNested
                , mdsNestedRouteFallthrough = roNestedRouteFallthrough routeOpts
                , mdsSameSpliceNestedInstances = sameSplice
                }
    (_childNames, clause') <-
        TyArgs
-> MkDispatchSettings (ZonkAny 11) (ZonkAny 10) (ZonkAny 9)
-> [ResourceTree a]
-> Q ([[Char]], Clause)
forall a b site c.
TyArgs
-> MkDispatchSettings b site c
-> [ResourceTree a]
-> Q ([[Char]], Clause)
mkDispatchClause
            TyArgs
NoTyArgs
            MkDispatchSettings (ZonkAny 11) (ZonkAny 10) (ZonkAny 9)
forall {a} {site} {b}. MkDispatchSettings a site b
mds
            [ResourceTree a]
res
    inner <- newName "inner"
    let innerFun = Name -> [Clause] -> Dec
FunD Name
inner [Clause
clause']
    helper <- newName "helper"
    let fun = Name -> [Clause] -> Dec
FunD Name
helper
                [ [Pat] -> Body -> [Dec] -> Clause
Clause
                    []
                    (Exp -> Body
NormalB (Exp -> Body) -> Exp -> Body
forall a b. (a -> b) -> a -> b
$ Name -> Exp
VarE Name
inner)
                    [Dec
innerFun]
                ]
    return $ LetE [fun] (VarE helper)


subTopDispatch ::
    (YesodSubDispatch sub master) =>
        (forall content. ToTypedContent content =>
            SubHandlerFor child master content ->
            YesodSubRunnerEnv child master ->
            Maybe (Route child) ->
            W.Application
        ) ->
        (mid -> sub) ->
        (Route sub -> Route mid) ->
        YesodSubRunnerEnv mid master ->
        W.Application
subTopDispatch :: forall sub master child mid.
YesodSubDispatch sub master =>
(forall content.
 ToTypedContent content =>
 SubHandlerFor child master content
 -> YesodSubRunnerEnv child master
 -> Maybe (Route child)
 -> Application)
-> (mid -> sub)
-> (Route sub -> Route mid)
-> YesodSubRunnerEnv mid master
-> Application
subTopDispatch forall content.
ToTypedContent content =>
SubHandlerFor child master content
-> YesodSubRunnerEnv child master
-> Maybe (Route child)
-> Application
_ mid -> sub
getSub Route sub -> Route mid
toParent YesodSubRunnerEnv mid master
env =
    YesodSubRunnerEnv sub master -> Application
forall sub master.
YesodSubDispatch sub master =>
YesodSubRunnerEnv sub master -> Application
yesodSubDispatch
        ( YesodSubRunnerEnv
            { ysreParentRunner :: ParentRunner master
ysreParentRunner = YesodSubRunnerEnv mid master -> ParentRunner master
forall sub parent.
YesodSubRunnerEnv sub parent -> ParentRunner parent
ysreParentRunner YesodSubRunnerEnv mid master
env
            , ysreGetSub :: master -> sub
ysreGetSub = mid -> sub
getSub (mid -> sub) -> (master -> mid) -> master -> sub
forall b c a. (b -> c) -> (a -> b) -> a -> c
. YesodSubRunnerEnv mid master -> master -> mid
forall sub parent. YesodSubRunnerEnv sub parent -> parent -> sub
ysreGetSub YesodSubRunnerEnv mid master
env
            , ysreToParentRoute :: Route sub -> Route master
ysreToParentRoute = YesodSubRunnerEnv mid master -> Route mid -> Route master
forall sub parent.
YesodSubRunnerEnv sub parent -> Route sub -> Route parent
ysreToParentRoute YesodSubRunnerEnv mid master
env (Route mid -> Route master)
-> (Route sub -> Route mid) -> Route sub -> Route master
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Route sub -> Route mid
toParent
            , ysreParentEnv :: YesodRunnerEnv master
ysreParentEnv = YesodSubRunnerEnv mid master -> YesodRunnerEnv master
forall sub parent.
YesodSubRunnerEnv sub parent -> YesodRunnerEnv parent
ysreParentEnv YesodSubRunnerEnv mid master
env
            }
        )

mkMDS :: (Exp -> Q Exp) -> Q Exp -> Q Exp -> MkDispatchSettings a site b
mkMDS :: forall a site b.
(Exp -> Q Exp) -> Q Exp -> Q Exp -> MkDispatchSettings a site b
mkMDS Exp -> Q Exp
unwrapper Q Exp
runHandlerE Q Exp
subDispatcher = MkDispatchSettings
    { mdsRunHandler :: Q Exp
mdsRunHandler = Q Exp
runHandlerE
    , mdsSubDispatcher :: Q Exp
mdsSubDispatcher = Q Exp
subDispatcher
    , mdsGetPathInfo :: Q Exp
mdsGetPathInfo = [|W.pathInfo|]
    , mdsSetPathInfo :: Q Exp
mdsSetPathInfo = [|\p r -> r { W.pathInfo = p }|]
    , mdsMethod :: Q Exp
mdsMethod = [|W.requestMethod|]
    , mds404 :: Q Exp
mds404 = [|void notFound|]
    , mds405 :: Q Exp
mds405 = [|void badMethod|]
    , mdsGetHandler :: Maybe [Char] -> [Char] -> Q Exp
mdsGetHandler = Maybe [Char] -> [Char] -> Q Exp
defaultGetHandler
    , mdsUnwrapper :: Exp -> Q Exp
mdsUnwrapper = Exp -> Q Exp
unwrapper
    , mdsNestedRouteFallthrough :: Bool
mdsNestedRouteFallthrough = Bool
False
    , mdsNestedTarget :: NestedTarget
mdsNestedTarget = NestedTarget
TopLevelNested
    , mdsSameSpliceNestedInstances :: SameSpliceNestedInstances
mdsSameSpliceNestedInstances = SameSpliceNestedInstances
NoSameSpliceNestedInstances
    }

-- | Parse the foundation-type string given to @mkYesod@ into its components:
-- the type-constructor name, its type arguments, and the @=>@ class-context
-- groups (each a class name applied to type arguments). Returns 'Left' with a
-- parse-error message on malformed input.
--
-- @since 1.7.0.0
parseYesodName :: String -> Either String (String, [String], [[String]])
parseYesodName :: [Char] -> Either [Char] ([Char], [[Char]], [[[Char]]])
parseYesodName [Char]
name = do
    (ParseError -> Either [Char] ([Char], [[Char]], [[[Char]]]))
-> (([Char], [[Char]], [[[Char]]])
    -> Either [Char] ([Char], [[Char]], [[[Char]]]))
-> Either ParseError ([Char], [[Char]], [[[Char]]])
-> Either [Char] ([Char], [[Char]], [[[Char]]])
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ([Char] -> Either [Char] ([Char], [[Char]], [[[Char]]])
forall a b. a -> Either a b
Left ([Char] -> Either [Char] ([Char], [[Char]], [[[Char]]]))
-> (ParseError -> [Char])
-> ParseError
-> Either [Char] ([Char], [[Char]], [[[Char]]])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ParseError -> [Char]
forall a. Show a => a -> [Char]
show) ([Char], [[Char]], [[[Char]]])
-> Either [Char] ([Char], [[Char]], [[[Char]]])
forall a b. b -> Either a b
Right (Either ParseError ([Char], [[Char]], [[[Char]]])
 -> Either [Char] ([Char], [[Char]], [[[Char]]]))
-> Either ParseError ([Char], [[Char]], [[[Char]]])
-> Either [Char] ([Char], [[Char]], [[[Char]]])
forall a b. (a -> b) -> a -> b
$ Parsec [Char] () ([Char], [[Char]], [[[Char]]])
-> [Char]
-> [Char]
-> Either ParseError ([Char], [[Char]], [[[Char]]])
forall s t a.
Stream s Identity t =>
Parsec s () a -> [Char] -> s -> Either ParseError a
parse Parsec [Char] () ([Char], [[Char]], [[[Char]]])
forall {u}.
ParsecT [Char] u Identity ([Char], [[Char]], [[[Char]]])
parseName [Char]
"" [Char]
name
    where
        parseName :: ParsecT [Char] u Identity ([Char], [[Char]], [[[Char]]])
parseName = do
            cxt <- [[[Char]]]
-> ParsecT [Char] u Identity [[[Char]]]
-> ParsecT [Char] u Identity [[[Char]]]
forall s (m :: * -> *) t a u.
Stream s m t =>
a -> ParsecT s u m a -> ParsecT s u m a
option [] ParsecT [Char] u Identity [[[Char]]]
forall {u}. ParsecT [Char] u Identity [[[Char]]]
parseContext
            name' <- parseWord
            args <- many parseWord
            spaces
            eof
            return ( name', args, cxt)

        parseWord :: ParsecT [Char] u Identity [Char]
parseWord = do
            ParsecT [Char] u Identity ()
forall s (m :: * -> *) u. Stream s m Char => ParsecT s u m ()
spaces
            ParsecT [Char] u Identity Char -> ParsecT [Char] u Identity [Char]
forall s u (m :: * -> *) a. ParsecT s u m a -> ParsecT s u m [a]
many1 ParsecT [Char] u Identity Char
forall s (m :: * -> *) u. Stream s m Char => ParsecT s u m Char
alphaNum

        parseContext :: ParsecT [Char] u Identity [[[Char]]]
parseContext = ParsecT [Char] u Identity [[[Char]]]
-> ParsecT [Char] u Identity [[[Char]]]
forall s u (m :: * -> *) a. ParsecT s u m a -> ParsecT s u m a
try (ParsecT [Char] u Identity [[[Char]]]
 -> ParsecT [Char] u Identity [[[Char]]])
-> ParsecT [Char] u Identity [[[Char]]]
-> ParsecT [Char] u Identity [[[Char]]]
forall a b. (a -> b) -> a -> b
$ do
            cxts <- ParsecT [Char] u Identity [[[Char]]]
-> ParsecT [Char] u Identity [[[Char]]]
forall {s} {m :: * -> *} {u} {b}.
Stream s m Char =>
ParsecT s u m b -> ParsecT s u m b
parseParen ParsecT [Char] u Identity [[[Char]]]
forall {u}. ParsecT [Char] u Identity [[[Char]]]
parseContexts
            spaces
            _ <- string "=>"
            return cxts

        parseParen :: ParsecT s u m b -> ParsecT s u m b
parseParen ParsecT s u m b
p = do
            ParsecT s u m ()
forall s (m :: * -> *) u. Stream s m Char => ParsecT s u m ()
spaces
            _ <- Char -> ParsecT s u m Char
forall s (m :: * -> *) u.
Stream s m Char =>
Char -> ParsecT s u m Char
char Char
'('
            r <- p
            spaces
            _ <- char ')'
            return r

        parseContexts :: ParsecT [Char] u Identity [[[Char]]]
parseContexts =
            ParsecT [Char] u Identity [[Char]]
-> ParsecT [Char] u Identity ()
-> ParsecT [Char] u Identity [[[Char]]]
forall s (m :: * -> *) t u a sep.
Stream s m t =>
ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
sepBy1 (ParsecT [Char] u Identity [Char]
-> ParsecT [Char] u Identity [[Char]]
forall s u (m :: * -> *) a. ParsecT s u m a -> ParsecT s u m [a]
many1 ParsecT [Char] u Identity [Char]
forall {u}. ParsecT [Char] u Identity [Char]
parseWord) (ParsecT [Char] u Identity ()
forall s (m :: * -> *) u. Stream s m Char => ParsecT s u m ()
spaces ParsecT [Char] u Identity ()
-> ParsecT [Char] u Identity Char -> ParsecT [Char] u Identity Char
forall a b.
ParsecT [Char] u Identity a
-> ParsecT [Char] u Identity b -> ParsecT [Char] u Identity b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Char -> ParsecT [Char] u Identity Char
forall s (m :: * -> *) u.
Stream s m Char =>
Char -> ParsecT s u m Char
char Char
',' ParsecT [Char] u Identity Char
-> ParsecT [Char] u Identity () -> ParsecT [Char] u Identity ()
forall a b.
ParsecT [Char] u Identity a
-> ParsecT [Char] u Identity b -> ParsecT [Char] u Identity b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> ParsecT [Char] u Identity ()
forall a. a -> ParsecT [Char] u Identity a
forall (m :: * -> *) a. Monad m => a -> m a
return ())