{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}

module Yesod.Routes.TH.ParseRoute
    ( -- ** ParseRoute
      mkParseRouteInstance
    , mkParseRouteInstanceOpts
    , mkParseRouteInstanceFor
      -- ** Clause construction (monad-polymorphic over 'Quote'; testable purely)
    , buildInlineParseClauses
    , generateParseRouteClause
    ) where

import qualified Control.Monad.Trans as Trans
import qualified Data.Set as Set
import Control.Monad
import Yesod.Routes.TH.Types
import Language.Haskell.TH (varE, varP)
import Language.Haskell.TH.Syntax hiding (newName)
import Language.Haskell.TH.Syntax.Compat (Quote(..), unsafeQToQuote)
import Yesod.Routes.Class
import Yesod.Routes.TH.RenderRoute
import Control.Monad.State.Strict
import Yesod.Routes.TH.Internal

-- | The trailing @_ -> Nothing@ clause appended to every generated
-- @parseRoute@\/@parseRouteNested@: a path matching none of the preceding
-- clauses fails to parse.
missingRouteClause :: Clause
missingRouteClause :: Clause
missingRouteClause = [Pat] -> Body -> [Dec] -> Clause
Clause [Pat
WildP] (Exp -> Body
NormalB (Name -> Exp
ConE 'Nothing)) []

mkParseRouteInstance :: TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
mkParseRouteInstance :: forall a. TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
mkParseRouteInstance =
    RouteOpts -> TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
forall a.
RouteOpts -> TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
mkParseRouteInstanceOpts RouteOpts
defaultOpts

-- | Generate a ParseRouteNested instance for a specific nested route target.
-- This is a convenience wrapper around mkParseRouteInstanceOpts with setFocusOnNestedRoute.
--
-- @since 1.7.0.0
mkParseRouteInstanceFor :: String -> [ResourceTree a] -> Q [Dec]
mkParseRouteInstanceFor :: forall a. String -> [ResourceTree a] -> Q [Dec]
mkParseRouteInstanceFor String
target [ResourceTree a]
ress = do
    let opts :: RouteOpts
opts = String -> RouteOpts -> RouteOpts
setFocusOnNestedRoute String
target RouteOpts
defaultOpts
        targetType :: Type
targetType = Name -> Type
ConT (String -> Name
mkName String
target)
    RouteOpts -> TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
forall a.
RouteOpts -> TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
mkParseRouteInstanceOpts RouteOpts
opts TyArgs
NoTyArgs [] Type
targetType [ResourceTree a]
ress

-- | Generate the 'ParseRoute' instance (and, under nested discovery, the
-- accompanying 'ParseRouteNested' instances) for a site, honoring the supplied
-- 'RouteOpts' and the site's 'TyArgs'. The options-driven core that
-- 'mkParseRouteInstanceFor' and the @mkYesod@ entry points build on.
--
-- @since 1.7.0.0
mkParseRouteInstanceOpts :: RouteOpts -> TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
mkParseRouteInstanceOpts :: forall a.
RouteOpts -> TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
mkParseRouteInstanceOpts RouteOpts
routeOpts TyArgs
origTyargs Cxt
cxt Type
typ [ResourceTree a]
unfocusedRess =
    case RouteOpts -> TyArgs -> DiscoveryMode
discoveryMode RouteOpts
routeOpts TyArgs
origTyargs of
        -- Backwards-compatible default: generate a single 'ParseRoute'
        -- instance with all nested routes inlined, and no 'ParseRouteNested'
        -- instances.
        DiscoveryMode
InlineCompat -> do
            clausess <- (ResourceTree a -> Q [Clause]) -> [ResourceTree a] -> Q [[Clause]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM ((Exp -> Exp) -> ResourceTree a -> Q [Clause]
forall (m :: * -> *) a.
Quote m =>
(Exp -> Exp) -> ResourceTree a -> m [Clause]
buildInlineParseClauses Exp -> Exp
forall a. a -> a
id) [ResourceTree a]
unfocusedRess
            let allClauses = [[Clause]] -> [Clause]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[Clause]]
clausess [Clause] -> [Clause] -> [Clause]
forall a. Semigroup a => a -> a -> a
<> [Clause
missingRouteClause]
            pure
                [ instanceD cxt (ConT ''ParseRoute `AppT` typ)
                    [ FunD 'parseRoute allClauses
                    ]
                ]
        DiscoveryMode
NestedDiscovery -> do
            ress <- [ResourceTree a] -> Q [ResourceTree a]
forall {m :: * -> *} {a}.
MonadFail m =>
[ResourceTree a] -> m [ResourceTree a]
focusTarget [ResourceTree a]
unfocusedRess
            existingInstances <- existingNestedInstances ress
            (clauses, childNames) <- flip runStateT mempty $ traverse (generateParseRouteClause existingInstances routeOpts) ress

            childInstances <- fmap join $ forM (Set.toList childNames) $ \String
childName ->
                RouteOpts -> TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
forall a.
RouteOpts -> TyArgs -> Cxt -> Type -> [ResourceTree a] -> Q [Dec]
mkParseRouteInstanceOpts RouteOpts
routeOpts { roFocusOnNestedRoute = Just childName } TyArgs
origTyargs Cxt
cxt (String -> Type
targetTypeFor String
childName) [ResourceTree a]
ress

            let allClauses = [Clause]
clauses [Clause] -> [Clause] -> [Clause]
forall a. Semigroup a => a -> a -> a
<> [Clause
missingRouteClause]

            let thisInstance =
                    case RouteOpts -> Maybe String
roFocusOnNestedRoute RouteOpts
routeOpts of
                        Just String
target ->
                            Cxt -> Type -> [Dec] -> Dec
instanceD Cxt
cxt (Name -> Type
ConT ''ParseRouteNested Type -> Type -> Type
`AppT` String -> Type
targetTypeFor String
target)
                                [ Name -> [Clause] -> Dec
FunD 'parseRouteNested [Clause]
allClauses
                                ]
                        Maybe String
Nothing ->
                            Cxt -> Type -> [Dec] -> Dec
instanceD Cxt
cxt (Name -> Type
ConT ''ParseRoute Type -> Type -> Type
`AppT` Type
typ)
                                [ Name -> [Clause] -> Dec
FunD 'parseRoute [Clause]
allClauses
                                ]

            pure $ thisInstance : childInstances
  where
    -- The route datatype named by @name@, applied to the site's type arguments.
    targetTypeFor :: String -> Type
targetTypeFor String
name = Type -> TyArgs -> Type
applyTyArgs (Name -> Type
ConT (String -> Name
mkName String
name)) TyArgs
origTyargs

    -- Narrow to the focused subtree's children via the shared lookup, failing
    -- loudly (matching Dispatch/RenderRoute) when the target is missing rather
    -- than silently producing an always-'Nothing' 'ParseRouteNested' instance.
    focusTarget :: [ResourceTree a] -> m [ResourceTree a]
focusTarget [ResourceTree a]
ts =
        case RouteOpts -> Maybe String
roFocusOnNestedRoute RouteOpts
routeOpts of
            Just String
target ->
                case String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
forall a.
String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute String
target [ResourceTree a]
ts of
                    Maybe ([Piece a], [ResourceTree a])
Nothing ->
                        String -> m [ResourceTree a]
forall a. HasCallStack => String -> m a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
String -> m a
fail (String -> m [ResourceTree a]) -> String -> m [ResourceTree a]
forall a b. (a -> b) -> a -> b
$ String
"Target '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
target String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"' was not found in resources."
                    Just ([Piece a]
_prePieces, [ResourceTree a]
children) ->
                        [ResourceTree a] -> m [ResourceTree a]
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [ResourceTree a]
children
            Maybe String
Nothing ->
                [ResourceTree a] -> m [ResourceTree a]
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [ResourceTree a]
ts

-- | Probe (in 'Q') which of the given resources' top-level parents already
-- have a 'ParseRouteNested' instance. Pulling these compiler queries
-- ('isInstance', via 'nestedInstanceExists') out of 'generateParseRouteClause'
-- is what lets that generator be monad-polymorphic over 'Quote' — and thus
-- runnable, and testable, at a pure 'Quote' instance.
--
-- @since 1.7.0.0
existingNestedInstances :: [ResourceTree a] -> Q (Set.Set String)
existingNestedInstances :: forall a. [ResourceTree a] -> Q (Set String)
existingNestedInstances [ResourceTree a]
ress = do
    flags <- (ResourceTree a -> Q [String]) -> [ResourceTree a] -> Q [[String]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM ResourceTree a -> Q [String]
forall {typ}. ResourceTree typ -> Q [String]
check [ResourceTree a]
ress
    pure $ Set.fromList (concat flags)
  where
    check :: ResourceTree typ -> Q [String]
check (ResourceParent String
name CheckOverlap
_ Set String
_ [Piece typ]
_ [ResourceTree typ]
_) = do
        rc <- String -> Q RouteCon
resolveRouteCon String
name
        has <- nestedInstanceExists ''ParseRouteNested rc
        pure [name | has]
    check ResourceLeaf{} = [String] -> Q [String]
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []

-- | Generate a single @parseRouteNested@-delegating clause for one resource
-- (under nested discovery). It records, into its 'StateT' accumulator, the
-- name of each parent that still needs a 'ParseRouteNested' instance generated.
--
-- The \"does this name already have an instance?\" decision is a compiler query
-- ('isInstance'), which would pin this to 'Q'; it is instead /hoisted out/ and
-- passed in as @existingInstances@, leaving only fresh-name generation as an
-- effect. That makes the generator monad-polymorphic over 'Quote': it runs at
-- 'Q' in production and at a pure 'Quote' instance (a monotonic counter) in
-- tests.
--
-- @since 1.7.0.0
generateParseRouteClause
    :: Quote m
    => Set.Set String
    -- ^ Route names that already have a 'ParseRouteNested' instance (so this
    -- clause should not re-request one). Computed by the caller in 'Q' via
    -- 'nestedInstanceExists'; pass 'mempty' in pure tests.
    -> RouteOpts
    -> ResourceTree a
    -> StateT (Set.Set String) m Clause
generateParseRouteClause :: forall (m :: * -> *) a.
Quote m =>
Set String
-> RouteOpts -> ResourceTree a -> StateT (Set String) m Clause
generateParseRouteClause Set String
existingInstances RouteOpts
routeOpts ResourceTree a
resourceTree =
    case ResourceTree a
resourceTree of
        ResourceLeaf (Resource String
name [Piece a]
pieces Dispatch a
dispatch [String]
_ CheckOverlap
_check) -> do
            (pats, dyns) <- m ([Pat], [Exp]) -> StateT (Set String) m ([Pat], [Exp])
forall (n :: * -> *) a. Monad n => n a -> StateT (Set String) n a
liftQ (m ([Pat], [Exp]) -> StateT (Set String) m ([Pat], [Exp]))
-> m ([Pat], [Exp]) -> StateT (Set String) m ([Pat], [Exp])
forall a b. (a -> b) -> a -> b
$ [Piece a] -> m ([Pat], [Exp])
forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Exp])
handlePiecesM [Piece a]
pieces

            case dispatch of
                Methods Maybe a
multi [String]
_ -> do
                    (finalTail, dyns') <-
                        case Maybe a
multi of
                            Maybe a
Nothing ->
                                (PathTail, [Exp]) -> StateT (Set String) m (PathTail, [Exp])
forall a. a -> StateT (Set String) m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PathTail
EndExact, [Exp]
dyns)
                            Just a
_ -> do
                                multiName <- m Name -> StateT (Set String) m Name
forall (n :: * -> *) a. Monad n => n a -> StateT (Set String) n a
liftQ (m Name -> StateT (Set String) m Name)
-> m Name -> StateT (Set String) m Name
forall a b. (a -> b) -> a -> b
$ String -> m Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"multi"
                                pure (EndMulti multiName, dyns ++ [VarE multiName])

                    queryParamsName <- liftQ $ newName "_queryParams"
                    let route = String -> [Exp] -> Exp
applyConPieces String
name [Exp]
dyns'
                        jroute = Name -> Exp
ConE 'Just Exp -> Exp -> Exp
`AppE` Exp
route
                        pathPat = PathTail -> [Pat] -> Pat
mkPathPat PathTail
finalTail [Pat]
pats
                        pat = [Pat] -> Pat
TupP [Pat
pathPat, Name -> Pat
VarP Name
queryParamsName]
                    pure $ Clause [pat] (NormalB jroute) []

                Subsite a
_ String
_ -> do
                    restName <- m Name -> StateT (Set String) m Name
forall (n :: * -> *) a. Monad n => n a -> StateT (Set String) n a
liftQ (m Name -> StateT (Set String) m Name)
-> m Name -> StateT (Set String) m Name
forall a b. (a -> b) -> a -> b
$ String -> m Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"rest"
                    queryParamsName <- liftQ $ newName "_queryParams"

                    let route = String -> [Exp] -> Exp
applyConPieces String
name [Exp]
dyns
                        pathPat = PathTail -> [Pat] -> Pat
mkPathPat (Name -> PathTail
EndRest Name
restName) [Pat]
pats
                        pat = [Pat] -> Pat
TupP [Pat
pathPat, Name -> Pat
VarP Name
queryParamsName]
                        tupExp = [Exp] -> Exp
mkTupE [Name -> Exp
VarE Name
restName, Name -> Exp
VarE Name
queryParamsName]
                        expr = Name -> Exp
VarE 'fmap
                            Exp -> Exp -> Exp
`AppE` Exp
route
                            Exp -> Exp -> Exp
`AppE` (Name -> Exp
VarE 'parseRoute Exp -> Exp -> Exp
`AppE` Exp
tupExp)
                    pure $ Clause [pat] (NormalB expr) []

        ResourceParent String
name CheckOverlap
_check Set String
_attrs [Piece a]
pieces [ResourceTree a]
_children -> do
            String -> StateT (Set String) m ()
forall {f :: * -> *}. MonadState (Set String) f => String -> f ()
recordNameIfNotInstance String
name

            (pats, dyns) <- m ([Pat], [Exp]) -> StateT (Set String) m ([Pat], [Exp])
forall (n :: * -> *) a. Monad n => n a -> StateT (Set String) n a
liftQ (m ([Pat], [Exp]) -> StateT (Set String) m ([Pat], [Exp]))
-> m ([Pat], [Exp]) -> StateT (Set String) m ([Pat], [Exp])
forall a b. (a -> b) -> a -> b
$ [Piece a] -> m ([Pat], [Exp])
forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Exp])
handlePiecesM [Piece a]
pieces

            let route = String -> [Exp] -> Exp
applyConPieces String
name [Exp]
dyns

            restName <- liftQ $ newName "rest"
            queryParamsName <- liftQ $ newName "_queryParams"

            let parseRouteOnRest =
                    Name -> Exp
VarE 'parseRouteNested
                        Exp -> Exp -> Exp
`AppE` [Exp] -> Exp
mkTupE [Name -> Exp
VarE Name
restName, Name -> Exp
VarE Name
queryParamsName]

            body <-
                    if roNestedRouteFallthrough routeOpts
                        then do
                            resultName <- liftQ $ newName "result"
                            let stmt = Pat -> Exp -> Stmt
BindS (Name -> Pat -> Pat
AsP Name
resultName (Name -> [Pat] -> Pat
conPCompat 'Just [Pat
WildP])) Exp
parseRouteOnRest
                                expr = Name -> Exp
VarE 'fmap Exp -> Exp -> Exp
`AppE` Exp
route Exp -> Exp -> Exp
`AppE` Name -> Exp
VarE Name
resultName
                            pure $ GuardedB [(PatG [stmt], expr)]
                        else
                            pure $ NormalB (VarE 'fmap `AppE` route `AppE` parseRouteOnRest)

            let pat = [Pat] -> Pat
TupP [PathTail -> [Pat] -> Pat
mkPathPat (Name -> PathTail
EndRest Name
restName) [Pat]
pats, Name -> Pat
VarP Name
queryParamsName]
            pure $ Clause [pat] body []

  where
    liftQ :: Monad n => n a -> StateT (Set.Set String) n a
    liftQ :: forall (n :: * -> *) a. Monad n => n a -> StateT (Set String) n a
liftQ = n a -> StateT (Set String) n a
forall (n :: * -> *) a. Monad n => n a -> StateT (Set String) n a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
Trans.lift

    -- Record that @name@ still needs a 'ParseRouteNested' instance generated.
    -- The instance-existence decision is hoisted out (into @existingInstances@,
    -- computed in 'Q' by the caller), so this stays pure.
    recordNameIfNotInstance :: String -> f ()
recordNameIfNotInstance String
name =
        CheckOverlap -> f () -> f ()
forall (f :: * -> *). Applicative f => CheckOverlap -> f () -> f ()
unless (String
name String -> Set String -> CheckOverlap
forall a. Ord a => a -> Set a -> CheckOverlap
`Set.member` Set String
existingInstances) (f () -> f ()) -> f () -> f ()
forall a b. (a -> b) -> a -> b
$
            (Set String -> Set String) -> f ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify (String -> Set String -> Set String
forall a. Ord a => a -> Set a -> Set a
Set.insert String
name)

-- | Backwards-compatible inline @parseRoute@ clause generation. It assembles
-- the @parseRoute@ clauses for the inline path directly as AST, drawing fresh
-- names from a 'Quote' name supply and building tuples\/applications by hand
-- rather than through quotation brackets
-- (brackets are monomorphic 'Q' before template-haskell 2.17; the one
-- exception goes through 'unsafeQToQuote').
--
-- Each call yields one clause per resource tree: a leaf is its own matching
-- clause, while a parent is a single clause that matches its path prefix and
-- then cases the remaining @(path, queryParams)@ over its children (their
-- clauses turned into match alternatives) ending in a @_ -> 'Nothing'@
-- fallback. That fallback is the commit-on-parent-prefix behaviour: once the
-- parent prefix matches, a child miss is a definite 'Nothing' rather than a
-- fall-through to a sibling top-level route.
--
-- It is monad-polymorphic in the name supply via 'Quote': production runs it at
-- 'Q' (so binders are hygienic 'newName's), while tests run it at a pure
-- 'Quote' instance backed by a monotonic counter, where names are deterministic
-- and the '[Clause]' output can be asserted on directly without splicing or
-- 'runQ'. Under the deterministic supply every name is a freshly-bound pattern
-- variable scoped to its clause, the shared counter keeps them distinct within a
-- tree, and it is threaded through the parent\/child recursion so a parent
-- binder never collides with a child's.
--
-- @since 1.7.0.0
buildInlineParseClauses
    :: Quote m
    => (Exp -> Exp)
    -- ^ Wrap a child-route expression in the accumulated parent constructors.
    -> ResourceTree a
    -> m [Clause]
buildInlineParseClauses :: forall (m :: * -> *) a.
Quote m =>
(Exp -> Exp) -> ResourceTree a -> m [Clause]
buildInlineParseClauses Exp -> Exp
wrap ResourceTree a
resourceTree =
    (Match -> Clause) -> [Match] -> [Clause]
forall a b. (a -> b) -> [a] -> [b]
map Match -> Clause
matchToClause ([Match] -> [Clause]) -> m [Match] -> m [Clause]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Exp -> Exp) -> ResourceTree a -> m [Match]
forall (m :: * -> *) a.
Quote m =>
(Exp -> Exp) -> ResourceTree a -> m [Match]
buildInlineParseMatches Exp -> Exp
wrap ResourceTree a
resourceTree
  where
    -- Each parse match is a single @(path, queryParams)@ pattern with a body,
    -- which is exactly a top-level @parseRoute@ clause. Total by construction —
    -- 'Match' and 'Clause' carry the same body\/@where@ shape — so no partial
    -- destructure is needed.
    matchToClause :: Match -> Clause
    matchToClause :: Match -> Clause
matchToClause (Match Pat
pat Body
body [Dec]
decs) = [Pat] -> Body -> [Dec] -> Clause
Clause [Pat
pat] Body
body [Dec]
decs

-- | The matching alternatives behind 'buildInlineParseClauses', one per
-- resource tree. Producing 'Match'es (rather than 'Clause's) is what lets a
-- parent splice its children straight into a @case@: a leaf is one
-- @(path, queryParams)@ alternative, and a parent is one alternative that
-- matches its path prefix then cases the remaining @(path, queryParams)@ over
-- its children's alternatives, ending in a @_ -> 'Nothing'@ fallback. At top
-- level 'buildInlineParseClauses' turns each alternative back into its own
-- @parseRoute@ clause.
buildInlineParseMatches
    :: Quote m
    => (Exp -> Exp)
    -- ^ Wrap a child-route expression in the accumulated parent constructors.
    -> ResourceTree a
    -> m [Match]
buildInlineParseMatches :: forall (m :: * -> *) a.
Quote m =>
(Exp -> Exp) -> ResourceTree a -> m [Match]
buildInlineParseMatches Exp -> Exp
wrap ResourceTree a
resourceTree =
    case ResourceTree a
resourceTree of
        ResourceLeaf (Resource String
name [Piece a]
pieces Dispatch a
dispatch [String]
_ CheckOverlap
_check) -> do
            (pats, dyns) <- [Piece a] -> m ([Pat], [Exp])
forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Exp])
handlePiecesM [Piece a]
pieces
            case dispatch of
                Methods Maybe a
multi [String]
_ -> do
                    (finalTail, dyns') <-
                        case Maybe a
multi of
                            Maybe a
Nothing ->
                                (PathTail, [Exp]) -> m (PathTail, [Exp])
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PathTail
EndExact, [Exp]
dyns)
                            Just a
_ -> do
                                multiName <- String -> m Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"multi"
                                pure (EndMulti multiName, dyns ++ [VarE multiName])
                    queryParamsName <- newName "_queryParams"
                    let route = String -> [Exp] -> Exp
applyConPieces String
name [Exp]
dyns'
                        jroute = Name -> Exp
ConE 'Just Exp -> Exp -> Exp
`AppE` Exp -> Exp
wrap Exp
route
                        pathPat = PathTail -> [Pat] -> Pat
mkPathPat PathTail
finalTail [Pat]
pats
                        pat = [Pat] -> Pat
TupP [Pat
pathPat, Name -> Pat
VarP Name
queryParamsName]
                    pure [Match pat (NormalB jroute) []]

                Subsite a
_ String
_ -> do
                    restName <- String -> m Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"rest"
                    queryParamsName <- newName "_queryParams"
                    subName <- newName "sub"
                    let route = String -> [Exp] -> Exp
applyConPieces String
name [Exp]
dyns
                        wrapSub = Exp -> Exp
wrap (Exp
route Exp -> Exp -> Exp
`AppE` Name -> Exp
VarE Name
subName)
                        pathPat = PathTail -> [Pat] -> Pat
mkPathPat (Name -> PathTail
EndRest Name
restName) [Pat]
pats
                        pat = [Pat] -> Pat
TupP [Pat
pathPat, Name -> Pat
VarP Name
queryParamsName]
                    -- 'unsafeQToQuote' because brackets are monomorphic 'Q'
                    -- on template-haskell < 2.17. It is safe here: the only
                    -- effect a bracket performs is drawing hygiene names for
                    -- its binders, and this one has none (the lambda binder
                    -- comes from a splice).
                    expr <- unsafeQToQuote [e|
                        fmap
                            (\ $(varP subName) -> $(pure wrapSub) )
                            (parseRoute ( $(varE restName), $(varE queryParamsName) ) )
                        |]
                    pure [Match pat (NormalB expr) []]

        ResourceParent String
name CheckOverlap
_check Set String
_attrs [Piece a]
pieces [ResourceTree a]
children -> do
            (pats, dyns) <- [Piece a] -> m ([Pat], [Exp])
forall (m :: * -> *) a. Quote m => [Piece a] -> m ([Pat], [Exp])
handlePiecesM [Piece a]
pieces
            restName <- newName "rest"
            queryParamsName <- newName "_queryParams"
            let parentCon Exp
childRoute =
                    String -> [Exp] -> Exp
applyConPieces String
name [Exp]
dyns Exp -> Exp -> Exp
`AppE` Exp
childRoute
                wrap' = Exp -> Exp
wrap (Exp -> Exp) -> (Exp -> Exp) -> Exp -> Exp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Exp -> Exp
parentCon

            -- Build each child's matching alternative relative to the remaining
            -- @(rest, queryParams)@ scope, then fold them into a single @case@
            -- that commits at this parent: a child miss falls to the
            -- @_ -> Nothing@ alternative instead of escaping to a sibling
            -- top-level route.
            childMatches <- concat <$> mapM (buildInlineParseMatches wrap') children
            let restTup = [Exp] -> Exp
mkTupE [Name -> Exp
VarE Name
restName, Name -> Exp
VarE Name
queryParamsName]
                fallbackMatch = Pat -> Body -> [Dec] -> Match
Match Pat
WildP (Exp -> Body
NormalB (Name -> Exp
ConE 'Nothing)) []
                caseExpr = Exp -> [Match] -> Exp
CaseE Exp
restTup ([Match]
childMatches [Match] -> [Match] -> [Match]
forall a. [a] -> [a] -> [a]
++ [Match
fallbackMatch])
                pathPat = PathTail -> [Pat] -> Pat
mkPathPat (Name -> PathTail
EndRest Name
restName) [Pat]
pats
                pat = [Pat] -> Pat
TupP [Pat
pathPat, Name -> Pat
VarP Name
queryParamsName]
            pure [Match pat (NormalB caseExpr) []]