{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
-- 'TemplateHaskellQuotes' is not enough here: on GHC < 9.0 it does not
-- enable nested @$(...)@ splices inside brackets (they parse as the @$@
-- operator and trigger cross-stage 'Lift' errors).
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}

module Yesod.Routes.TH.RenderRoute
    ( -- ** RenderRoute
      mkRenderRouteInstanceOpts
    , mkRouteConsOpts
    , shouldCreateResources

    , RouteOpts
    , defaultOpts
    , setEqDerived
    , setShowDerived
    , setReadDerived
    , setCreateResources
    , setFocusOnNestedRoute
    , unsetFocusOnNestedRoute
    , roFocusOnNestedRoute
    , roNestedRouteFallthrough
    , setParameterizedSubroute
    , setNestedRouteFallthrough
    , DiscoveryMode(..)
    , discoveryMode
    ) where

import Data.Maybe
import Yesod.Routes.TH.Types
import Language.Haskell.TH (varE, varP)
import Language.Haskell.TH.Syntax
import Control.Monad
import Data.Text (pack)
import Web.PathPieces (PathPiece (..), PathMultiPiece (..))
import Yesod.Routes.Class
import Data.Foldable
import Yesod.Routes.TH.Internal
import Data.Char
import Yesod.Core.Class.Dispatch.ToParentRoute

-- | General opts data type for generating yesod.
--
-- Contains options for customizing code generation for the router in
-- 'mkYesodData', including what type class instances will be derived for
-- the route datatype, whether to parameterize subroutes,
-- and whether or not to create the @resources :: [ResourceTree String]@ value.
-- Use the setting functions on `defaultOpts` to set specific fields.
--
-- @since 1.6.25.0
data RouteOpts = MkRouteOpts
    { RouteOpts -> Bool
roDerivedEq   :: Bool
    , RouteOpts -> Bool
roDerivedShow :: Bool
    , RouteOpts -> Bool
roDerivedRead :: Bool
    , RouteOpts -> Bool
roCreateResources :: Bool
    , RouteOpts -> Maybe String
roFocusOnNestedRoute :: Maybe String
    -- ^ If this option is set, then we will only generate datatypes for
    -- the nested subroute that matches this string.
    --
    -- @since 1.7.0.0
    , RouteOpts -> Bool
roParameterizedSubroute :: Bool
    , RouteOpts -> Bool
roNestedRouteFallthrough :: Bool
    -- ^ If 'True', then a nested route will fall through if it fails to
    -- match. If 'False', then a nested route will throw 'notFound' if it
    -- does not match.
    --
    -- Default: 'False'.
    --
    -- @since 1.7.0.0
    }

-- | Default options for generating routes.
--
-- The defaults are:
--
--   * 'setEqDerived', 'setShowDerived', 'setReadDerived': 'True' — derive
--     'Eq', 'Show' and 'Read' for the route datatype.
--   * 'setCreateResources': 'True' — emit the @resourcesSite ::
--     [ResourceTree String]@ term.
--   * 'setParameterizedSubroute': 'False' — subroutes are unparameterized.
--   * 'setFocusOnNestedRoute': unset — generate the whole route tree
--     rather than focusing on a single nested route.
--   * 'setNestedRouteFallthrough': 'False' — a nested route that fails to
--     match throws 'notFound' instead of falling through.
--
-- Use the @set*@ functions to override individual fields.
--
-- @since 1.6.25.0
defaultOpts :: RouteOpts
defaultOpts :: RouteOpts
defaultOpts = MkRouteOpts
    { roDerivedEq :: Bool
roDerivedEq = Bool
True
    , roDerivedShow :: Bool
roDerivedShow = Bool
True
    , roDerivedRead :: Bool
roDerivedRead = Bool
True
    , roCreateResources :: Bool
roCreateResources = Bool
True
    , roParameterizedSubroute :: Bool
roParameterizedSubroute = Bool
False
    , roFocusOnNestedRoute :: Maybe String
roFocusOnNestedRoute = Maybe String
forall a. Maybe a
Nothing
    , roNestedRouteFallthrough :: Bool
roNestedRouteFallthrough = Bool
False
    }

-- | If you set this with @routeName@, then the code generation will
-- generate code for the @routeName@ to be imported in the main dispatch
-- class. This allows you to generate code in separate modules.
--
-- Example:
--
-- First, you would put your route definitions into their own file.
--
-- @
-- module App.Routes.Resources where
--
-- import Yesod.Core
--
-- appResources :: [ResourceTree String]
-- appResources = [parseRoutes|
--     /  HomeR GET
--
--     /nest NestR:
--         /     NestIndexR GET POST
--         /#Int NestShowR  GET POST
--
-- |]
-- @
--
-- We have defined a nested route called @NestR@ here. A nested route is
-- created with the @:@ after the route name.
--
-- Then, in a module for the route specifically, we can generate the route
-- datatype and instances for later hooking in to the main instance.
--
-- @
-- module App.Routes.NestR where
--
-- import App.Routes.Resources
-- import Yesod.Core
--
-- mkYesodOpts (setFocusOnNestedRoute "NestR" defaultOpts) "App" appResources
-- @
--
-- If you only want to generate the datatypes, you can separate things
-- further using 'mkYesodDataOpts' and 'mkYesodDispatchOpts'.
--
-- Finally, import that type into your main yesod macro code.
--
-- @
-- module App where
--
-- import App.Routes.Resources (appResources)
-- import App.Routes.NestR (NestR(..))
--
-- mkYesod "App" appResources
-- @
--
-- The call to 'mkYesod' will delegate to the generated code for @NestR@
-- rather than regenerating it.
--
-- By default, 'defaultOpts' starts unfocused (the whole route tree is
-- generated). Use 'unsetFocusOnNestedRoute' to clear a previously-set focus.
--
-- For a full walkthrough — including subsites, linking to nested routes, and
-- why split sites should enable 'setNestedRouteFallthrough' — see the guide at
-- <https://github.com/yesodweb/yesod/blob/master/yesod-core/docs/split-route-compilation.md>.
--
-- @since 1.7.0.0
setFocusOnNestedRoute :: String -> RouteOpts -> RouteOpts
setFocusOnNestedRoute :: String -> RouteOpts -> RouteOpts
setFocusOnNestedRoute String
str RouteOpts
rdo = RouteOpts
rdo { roFocusOnNestedRoute = Just str }

-- | Clear any nested-route focus set by 'setFocusOnNestedRoute', so that
-- the whole route tree is generated.
--
-- 'defaultOpts' already starts unfocused, so this is only needed to undo a
-- previous 'setFocusOnNestedRoute'.
--
-- @since 1.7.0.0
unsetFocusOnNestedRoute :: RouteOpts -> RouteOpts
unsetFocusOnNestedRoute :: RouteOpts -> RouteOpts
unsetFocusOnNestedRoute RouteOpts
rdo = RouteOpts
rdo { roFocusOnNestedRoute = Nothing }

-- | When 'True', a nested route that fails to match falls through to the
-- enclosing dispatch rather than throwing 'notFound'. When 'False', a
-- non-matching nested route throws 'notFound'.
--
-- Default: 'False'.
--
-- @since 1.7.0.0
setNestedRouteFallthrough :: Bool -> RouteOpts -> RouteOpts
setNestedRouteFallthrough :: Bool -> RouteOpts -> RouteOpts
setNestedRouteFallthrough Bool
b RouteOpts
rdo = RouteOpts
rdo { roNestedRouteFallthrough = b }

-- | When 'True', derive an 'Eq' instance for the route datatype.
--
-- Default: 'True'.
--
-- @since 1.6.25.0
setEqDerived :: Bool -> RouteOpts -> RouteOpts
setEqDerived :: Bool -> RouteOpts -> RouteOpts
setEqDerived Bool
b RouteOpts
rdo = RouteOpts
rdo { roDerivedEq = b }

-- | When 'True', derive a 'Show' instance for the route datatype.
--
-- Default: 'True'.
--
-- @since 1.6.25.0
setShowDerived :: Bool -> RouteOpts -> RouteOpts
setShowDerived :: Bool -> RouteOpts -> RouteOpts
setShowDerived Bool
b RouteOpts
rdo = RouteOpts
rdo { roDerivedShow = b }

-- | When 'True', derive a 'Read' instance for the route datatype.
--
-- Default: 'True'.
--
-- @since 1.6.25.0
setReadDerived :: Bool -> RouteOpts -> RouteOpts
setReadDerived :: Bool -> RouteOpts -> RouteOpts
setReadDerived Bool
b RouteOpts
rdo = RouteOpts
rdo { roDerivedRead = b }

-- | Determine whether or not to generate the @resourcesApp@ value.
--
-- Disabling this can be useful if you are creating the @routes ::
-- [ResourceTree String]@ elsewhere in your module, and referring to it
-- here. The @resourcesApp@ can become very large in large applications,
-- and duplicating it can result in signifiacntly higher compile times.
--
-- Default: 'True'.
--
-- @since 1.6.28.0
setCreateResources :: Bool -> RouteOpts -> RouteOpts
setCreateResources :: Bool -> RouteOpts -> RouteOpts
setCreateResources Bool
b RouteOpts
rdo = RouteOpts
rdo { roCreateResources = b }

-- | Returns whether or not we should create the @resourcesSite ::
-- [ResourceTree String]@ value during code generation.
--
-- @since 1.6.28.0
shouldCreateResources :: RouteOpts -> Bool
shouldCreateResources :: RouteOpts -> Bool
shouldCreateResources = RouteOpts -> Bool
roCreateResources

-- | If True, generate nested-discovery code (separate subroute datatypes and
-- @RenderRouteNested@ / dispatch instances) for a /parameterized/ site instead
-- of the backwards-compatible inline output. The subroute datatypes then carry
-- the parent site's type variables so that the @ParentSite@ \/ @ParentArgs@
-- associated types stay well-scoped.
--
-- Because the generated nested instances are parameterized over the site's
-- type variables, the splice emits instance heads with non-variable arguments;
-- a module using this typically needs @FlexibleContexts@, @FlexibleInstances@,
-- @MultiParamTypeClasses@, @TypeFamilies@ and, for a parameterized subsite
-- whose @master@ is determined by the @subsite@ (a @subsite -> master@
-- functional dependency on the user's class), @UndecidableInstances@.
--
-- Monomorphic sites always use nested discovery regardless of this flag; see
-- 'discoveryMode'.
--
-- Default: 'False'.
--
-- @since 1.6.28.0
setParameterizedSubroute :: Bool -> RouteOpts -> RouteOpts
setParameterizedSubroute :: Bool -> RouteOpts -> RouteOpts
setParameterizedSubroute Bool
b RouteOpts
rdo = RouteOpts
rdo { roParameterizedSubroute = b }

-- |
--
-- @since 1.6.25.0
instanceNamesFromOpts :: RouteOpts -> [Name]
instanceNamesFromOpts :: RouteOpts -> [Name]
instanceNamesFromOpts MkRouteOpts {Bool
Maybe String
roFocusOnNestedRoute :: RouteOpts -> Maybe String
roNestedRouteFallthrough :: RouteOpts -> Bool
roDerivedEq :: RouteOpts -> Bool
roDerivedShow :: RouteOpts -> Bool
roDerivedRead :: RouteOpts -> Bool
roCreateResources :: RouteOpts -> Bool
roParameterizedSubroute :: RouteOpts -> Bool
roDerivedEq :: Bool
roDerivedShow :: Bool
roDerivedRead :: Bool
roCreateResources :: Bool
roFocusOnNestedRoute :: Maybe String
roParameterizedSubroute :: Bool
roNestedRouteFallthrough :: Bool
..} = Bool -> Name -> [Name] -> [Name]
forall {a}. Bool -> a -> [a] -> [a]
prependIf Bool
roDerivedEq ''Eq ([Name] -> [Name]) -> [Name] -> [Name]
forall a b. (a -> b) -> a -> b
$ Bool -> Name -> [Name] -> [Name]
forall {a}. Bool -> a -> [a] -> [a]
prependIf Bool
roDerivedShow ''Show ([Name] -> [Name]) -> [Name] -> [Name]
forall a b. (a -> b) -> a -> b
$ Bool -> Name -> [Name] -> [Name]
forall {a}. Bool -> a -> [a] -> [a]
prependIf Bool
roDerivedRead ''Read []
    where prependIf :: Bool -> a -> [a] -> [a]
prependIf Bool
b = if Bool
b then (:) else ([a] -> [a]) -> a -> [a] -> [a]
forall a b. a -> b -> a
const [a] -> [a]
forall a. a -> a
id

-- | How a route datatype's children are generated.
--
-- @since 1.7.0.0
data DiscoveryMode
    = -- | The backwards-compatible default for a /parameterized/ site that has
      -- not opted in: subroute datatypes stay unparameterized (kind 'Type')
      -- and @renderRoute@ \/ @parseRoute@ \/ dispatch inline the children,
      -- exactly as pre-nested-discovery Yesod did. Generating the discovery
      -- machinery here would put the parent's type variables out of scope on
      -- the child datatype, so we don't.
      InlineCompat
    | -- | Generate the "nested route discovery" machinery: parameterized
      -- subroute datatypes plus the @RenderRouteNested@ \/ @ParseRouteNested@
      -- \/ @YesodDispatchNested@ \/ @ToParentRoute@ \/ @UrlToDispatch@ \/
      -- @RedirectUrl@ instances and the delegating method bodies that go with
      -- them.
      NestedDiscovery
    deriving (DiscoveryMode -> DiscoveryMode -> Bool
(DiscoveryMode -> DiscoveryMode -> Bool)
-> (DiscoveryMode -> DiscoveryMode -> Bool) -> Eq DiscoveryMode
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DiscoveryMode -> DiscoveryMode -> Bool
== :: DiscoveryMode -> DiscoveryMode -> Bool
$c/= :: DiscoveryMode -> DiscoveryMode -> Bool
/= :: DiscoveryMode -> DiscoveryMode -> Bool
Eq, Int -> DiscoveryMode -> ShowS
[DiscoveryMode] -> ShowS
DiscoveryMode -> String
(Int -> DiscoveryMode -> ShowS)
-> (DiscoveryMode -> String)
-> ([DiscoveryMode] -> ShowS)
-> Show DiscoveryMode
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DiscoveryMode -> ShowS
showsPrec :: Int -> DiscoveryMode -> ShowS
$cshow :: DiscoveryMode -> String
show :: DiscoveryMode -> String
$cshowList :: [DiscoveryMode] -> ShowS
showList :: [DiscoveryMode] -> ShowS
Show)

-- | Classify how a route datatype's children should be generated, given the
-- site's route options and its 'TyArgs'.
--
-- 'NestedDiscovery' is chosen when any of the following hold:
--
--   * The site has /no/ type parameters ('hasTyArgs' is 'False', e.g. a
--     monomorphic site like @App@). Subroute datatypes then need no type
--     variables, so the machinery is always safe, and this preserves the
--     historical behaviour of monomorphic sites (including splitting nested
--     routes across modules).
--
--   * Parameterized subroutes were explicitly requested
--     ('setParameterizedSubroute'). The subroute datatypes then carry the
--     parent's type variables so the @ParentSite@ \/ @ParentArgs@ associated
--     types are well-scoped.
--
--   * We are focusing on a nested route for module-splitting
--     ('setFocusOnNestedRoute').
--
-- @since 1.7.0.0
discoveryMode :: RouteOpts -> TyArgs -> DiscoveryMode
discoveryMode :: RouteOpts -> TyArgs -> DiscoveryMode
discoveryMode RouteOpts
opts TyArgs
tyargs
    | Bool -> Bool
not (TyArgs -> Bool
hasTyArgs TyArgs
tyargs)             = DiscoveryMode
NestedDiscovery
    | RouteOpts -> Bool
roParameterizedSubroute RouteOpts
opts       = DiscoveryMode
NestedDiscovery
    | Maybe String -> Bool
forall a. Maybe a -> Bool
isJust (RouteOpts -> Maybe String
roFocusOnNestedRoute RouteOpts
opts) = DiscoveryMode
NestedDiscovery
    | Bool
otherwise                          = DiscoveryMode
InlineCompat

-- | 'PlainTV' across template-haskell versions. @th-abstraction@ covers this,
-- but the version it was introduced in isn't always available — and the
-- 'TyVarBndr' /flag/ type also varies by version, so the result type is
-- CPP-guarded too. Used to build the type-variable binders of generated
-- subroute datatypes.
plainTVCompat :: Name ->
#if MIN_VERSION_template_haskell(2,21,0)
    TyVarBndr BndrVis
#elif MIN_VERSION_template_haskell(2,17,0)
    TyVarBndr ()
#else
    TyVarBndr
#endif
plainTVCompat :: Name -> TyVarBndr BndrVis
plainTVCompat =
#if MIN_VERSION_template_haskell(2,21,0)
    (Name -> BndrVis -> TyVarBndr BndrVis
forall flag. Name -> flag -> TyVarBndr flag
`PlainTV` BndrVis
BndrReq)
#elif MIN_VERSION_template_haskell(2,17,0)
    (`PlainTV` ())
#else
    PlainTV
#endif

-- | Build the data constructor for a route leaf: @LeafR ty… [multi] [Route Sub]@.
-- Shared by the full-tree ('mkRouteConsOpts') and focused-nested
-- ('mkRenderRouteNestedInstanceOpts') constructor generators, which previously
-- spelled this identically.
leafRouteCon :: Resource Type -> Con
leafRouteCon :: Resource Type -> Con
leafRouteCon Resource Type
res =
    Name -> [BangType] -> Con
NormalC (String -> Name
mkName (String -> Name) -> String -> Name
forall a b. (a -> b) -> a -> b
$ Resource Type -> String
forall typ. Resource typ -> String
resourceName Resource Type
res)
        ([BangType] -> Con) -> [BangType] -> Con
forall a b. (a -> b) -> a -> b
$ (Type -> BangType) -> [Type] -> [BangType]
forall a b. (a -> b) -> [a] -> [b]
map (Bang
notStrict,)
        ([Type] -> [BangType]) -> [Type] -> [BangType]
forall a b. (a -> b) -> a -> b
$ [[Type]] -> [Type]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[Type]
singles, [Type]
multi, [Type]
sub]
  where
    singles :: [Type]
singles = (Piece Type -> [Type]) -> [Piece Type] -> [Type]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Piece Type -> [Type]
forall {a}. Piece a -> [a]
toSingle ([Piece Type] -> [Type]) -> [Piece Type] -> [Type]
forall a b. (a -> b) -> a -> b
$ Resource Type -> [Piece Type]
forall typ. Resource typ -> [Piece typ]
resourcePieces Resource Type
res
    toSingle :: Piece a -> [a]
toSingle Static{}      = []
    toSingle (Dynamic a
typ) = [a
typ]
    multi :: [Type]
multi = Maybe Type -> [Type]
forall a. Maybe a -> [a]
maybeToList (Maybe Type -> [Type]) -> Maybe Type -> [Type]
forall a b. (a -> b) -> a -> b
$ Resource Type -> Maybe Type
forall typ. Resource typ -> Maybe typ
resourceMulti Resource Type
res
    sub :: [Type]
sub =
        case Resource Type -> Dispatch Type
forall typ. Resource typ -> Dispatch typ
resourceDispatch Resource Type
res of
            Subsite { subsiteType :: forall typ. Dispatch typ -> typ
subsiteType = Type
typ } -> [Name -> Type
ConT ''Route Type -> Type -> Type
`AppT` Type
typ]
            Dispatch Type
_ -> []

-- | Build the data constructor for a route parent: @ParentR ty… (ChildR tyargs…)@,
-- whose trailing field is the (possibly type-argument-applied) child route
-- datatype. Shared by the full-tree and focused-nested constructor generators.
parentRouteCon :: String -> [Piece Type] -> TyArgs -> Con
parentRouteCon :: String -> [Piece Type] -> TyArgs -> Con
parentRouteCon String
name [Piece Type]
pieces TyArgs
tyargs =
    Name -> [BangType] -> Con
NormalC (String -> Name
mkName String
name)
        ([BangType] -> Con) -> [BangType] -> Con
forall a b. (a -> b) -> a -> b
$ (Type -> BangType) -> [Type] -> [BangType]
forall a b. (a -> b) -> [a] -> [b]
map (Bang
notStrict,)
        ([Type] -> [BangType]) -> [Type] -> [BangType]
forall a b. (a -> b) -> a -> b
$ [Type]
singles [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type -> TyArgs -> Type
applyTyArgs (Name -> Type
ConT (String -> Name
mkName String
name)) TyArgs
tyargs]
  where
    singles :: [Type]
singles = (Piece Type -> [Type]) -> [Piece Type] -> [Type]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Piece Type -> [Type]
forall {a}. Piece a -> [a]
toSingle [Piece Type]
pieces
    toSingle :: Piece a -> [a]
toSingle Static{}      = []
    toSingle (Dynamic a
typ) = [a
typ]

-- | The deriving context for a child\/subroute datatype. The site's instance
-- context only makes sense on a child that actually carries the type
-- arguments; an unparameterized child (the backwards-compatible default)
-- can't, so deriving with that context would leave the variables ambiguous.
-- Nullify the context in that case, mirroring historical Yesod.
childDerivCxt :: TyArgs -> Cxt -> Cxt
childDerivCxt :: TyArgs -> [Type] -> [Type]
childDerivCxt TyArgs
tyargs [Type]
cxt
    | TyArgs -> Bool
hasTyArgs TyArgs
tyargs = [Type]
cxt
    | Bool
otherwise        = []

-- | Generate the constructors of a route data type, with custom
-- 'RouteOpts'.
--
-- The first element in the return is the list of constructors for the
-- @Route site@ datatype. The second element is the list of 'Dec' to
-- declare nested datatypes or class instances of the 'RenderRouteNested'
-- for those instances.
--
-- @since 1.6.25.0
mkRouteConsOpts :: RouteOpts -> Cxt -> TyArgs -> Type -> [ResourceTree Type] -> Q ([Con], [Dec])
mkRouteConsOpts :: RouteOpts
-> [Type]
-> TyArgs
-> Type
-> [ResourceTree Type]
-> Q ([Con], [Dec])
mkRouteConsOpts RouteOpts
opts [Type]
cxt TyArgs
origTyargs Type
master [ResourceTree Type]
resourceTrees = do
    (prePieces, focusedTrees) <-
        case RouteOpts -> Maybe String
roFocusOnNestedRoute RouteOpts
opts of
            Maybe String
Nothing ->
                ([Piece Type], [ResourceTree Type])
-> Q ([Piece Type], [ResourceTree Type])
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([], [ResourceTree Type]
resourceTrees)
            Just String
target -> do
                let mnestedRoute :: Maybe ([Piece Type], [ResourceTree Type])
mnestedRoute = String
-> [ResourceTree Type] -> Maybe ([Piece Type], [ResourceTree Type])
forall a.
String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute String
target [ResourceTree Type]
resourceTrees
                case Maybe ([Piece Type], [ResourceTree Type])
mnestedRoute of
                    Maybe ([Piece Type], [ResourceTree Type])
Nothing ->
                        String -> Q ([Piece Type], [ResourceTree Type])
forall a. String -> Q a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Q ([Piece Type], [ResourceTree Type]))
-> String -> Q ([Piece Type], [ResourceTree Type])
forall a b. (a -> b) -> a -> b
$ String
"Target '" String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
target String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
"' was not found in resources."
                    Just ([Piece Type], [ResourceTree Type])
r ->
                        ([Piece Type], [ResourceTree Type])
-> Q ([Piece Type], [ResourceTree Type])
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Piece Type], [ResourceTree Type])
r
    mkRouteConsOpts' prePieces focusedTrees
  where
    -- When nested route discovery is enabled, child datatypes carry the
    -- parent's type variables, because RenderRouteNested has associated type
    -- families (ParentSite, ParentArgs) that reference the parent type;
    -- without the type variables on the child datatype, they'd be out of
    -- scope on the RHS of the type family instance.
    --
    -- When it is disabled (the backwards-compatible default), child
    -- datatypes are unparameterized (kind 'Type'), matching the historical
    -- output. See 'discoveryMode'. Computed once and reused below.
    mode :: DiscoveryMode
mode = RouteOpts -> TyArgs -> DiscoveryMode
discoveryMode RouteOpts
opts TyArgs
origTyargs
    tyargs :: TyArgs
tyargs =
        case DiscoveryMode
mode of
            DiscoveryMode
NestedDiscovery -> TyArgs
origTyargs
            DiscoveryMode
InlineCompat    -> TyArgs
NoTyArgs
    subrouteDecTypeArgs :: [TyVarBndr BndrVis]
subrouteDecTypeArgs = (Name -> TyVarBndr BndrVis) -> [Name] -> [TyVarBndr BndrVis]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Name -> TyVarBndr BndrVis
plainTVCompat (TyArgs -> [Name]
tyArgsBinders TyArgs
tyargs)

    -- Derives for the child (subroute) datatypes. See 'childDerivCxt'.
    childCxt :: [Type]
childCxt = TyArgs -> [Type] -> [Type]
childDerivCxt TyArgs
tyargs [Type]
cxt
    ([DerivClause]
inlineDerives, Type -> [Dec]
mkStandaloneDerives) = RouteOpts -> [Type] -> ([DerivClause], Type -> [Dec])
getDerivesFor RouteOpts
opts [Type]
childCxt

    mkRouteConsOpts' :: [Piece Type] -> [ResourceTree Type] -> Q ([Con], [Dec])
    mkRouteConsOpts' :: [Piece Type] -> [ResourceTree Type] -> Q ([Con], [Dec])
mkRouteConsOpts' [Piece Type]
prePieces [ResourceTree Type]
trees = do
        results <- (ResourceTree Type -> Q ([Con], [Dec]))
-> [ResourceTree Type] -> Q [([Con], [Dec])]
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 ([Piece Type] -> ResourceTree Type -> Q ([Con], [Dec])
mkRouteCon [Piece Type]
prePieces) [ResourceTree Type]
trees
        pure (mconcat results)

    mkRouteCon :: [Piece Type] -> ResourceTree Type -> Q ([Con], [Dec])
    mkRouteCon :: [Piece Type] -> ResourceTree Type -> Q ([Con], [Dec])
mkRouteCon [Piece Type]
_ (ResourceLeaf Resource Type
res) =
        -- A leaf is always a constructor of the (possibly focused) datatype:
        -- in focus mode we have already narrowed @resourceTrees@ to the
        -- target's children, so every leaf reached here is a leaf of the
        -- focused route.
        ([Con], [Dec]) -> Q ([Con], [Dec])
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Resource Type -> Con
leafRouteCon Resource Type
res], [])

    mkRouteCon [Piece Type]
prePieces (ResourceParent String
name Bool
_check Set String
_attrs [Piece Type]
pieces [ResourceTree Type]
children) = do
        -- Accumulate pieces for children: combine parent pieces with this route's pieces
        let accumulatedPieces :: [Piece Type]
accumulatedPieces = [Piece Type]
prePieces [Piece Type] -> [Piece Type] -> [Piece Type]
forall a. Semigroup a => a -> a -> a
<> [Piece Type]
pieces
        (cons, decs) <- [Piece Type] -> [ResourceTree Type] -> Q ([Con], [Dec])
mkRouteConsOpts' [Piece Type]
accumulatedPieces [ResourceTree Type]
children
        let childDataName = String -> Name
mkName String
name

        -- Generate the child datatype if it has not been generated
        -- already, but only if we are *not* focusing on some other
        -- datatype.
        mname' <- lookupTypeName name
        mdec <- case mname' of
            Just Name
_ -> do
                -- datatype already exists, definitely don't generate it
                Maybe [Dec] -> Q (Maybe [Dec])
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe [Dec]
forall a. Maybe a
Nothing
            Maybe Name
Nothing -> do
                let childData :: Dec
childData = Name -> [Con] -> [DerivClause] -> Dec
mkChildDataGen Name
childDataName [Con]
cons [DerivClause]
inlineDerives
                    childDataType :: Type
childDataType = Type -> TyArgs -> Type
applyTyArgs (Name -> Type
ConT Name
childDataName) TyArgs
tyargs
                case RouteOpts -> Maybe String
roFocusOnNestedRoute RouteOpts
opts of
                    Just String
target | String
target String -> String -> Bool
forall a. Eq a => a -> a -> Bool
/= String
name ->
                        -- If we have a target, and this ain't it, don't
                        -- generate
                        Maybe [Dec] -> Q (Maybe [Dec])
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe [Dec]
forall a. Maybe a
Nothing
                    Maybe String
_ | DiscoveryMode
InlineCompat <- DiscoveryMode
mode ->
                        -- Backwards-compatible default: emit just the
                        -- (unparameterized) child datatype and its standalone
                        -- derives. No RenderRouteNested instance; renderRoute
                        -- inlines the children.
                        Maybe [Dec] -> Q (Maybe [Dec])
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe [Dec] -> Q (Maybe [Dec])) -> Maybe [Dec] -> Q (Maybe [Dec])
forall a b. (a -> b) -> a -> b
$ [Dec] -> Maybe [Dec]
forall a. a -> Maybe a
Just (Dec
childData Dec -> [Dec] -> [Dec]
forall a. a -> [a] -> [a]
: Type -> [Dec]
mkStandaloneDerives Type
childDataType)
                    Maybe String
_ ->
                        -- Nested discovery: either `Just target | target ==
                        -- name` (matching a target, and this is it) or
                        -- `Nothing` (no target, or we already found it). Emit
                        -- the child datatype plus its RenderRouteNested
                        -- instance so the parent's renderRoute can delegate.
                        [Dec] -> Maybe [Dec]
forall a. a -> Maybe a
Just ([Dec] -> Maybe [Dec]) -> Q [Dec] -> Q (Maybe [Dec])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
                            RouteOpts
-> [Type]
-> [Type]
-> TyArgs
-> Type
-> Name
-> [Con]
-> [Piece Type]
-> [ResourceTree Type]
-> Q [Dec]
nestedChildDataAndInstance
                                RouteOpts
opts [Type]
cxt [Type]
childCxt TyArgs
tyargs Type
master Name
childDataName [Con]
cons
                                ([Piece Type]
prePieces [Piece Type] -> [Piece Type] -> [Piece Type]
forall a. Semigroup a => a -> a -> a
<> [Piece Type]
pieces) [ResourceTree Type]
children

        return ([parentRouteCon name pieces tyargs], maybe id (<>) mdec decs)
      where
        mkChildDataGen :: Name -> [Con] -> [DerivClause] -> Dec
        mkChildDataGen :: Name -> [Con] -> [DerivClause] -> Dec
mkChildDataGen Name
childDataName [Con]
cons [DerivClause]
conts =
            [Type]
-> Name
-> [TyVarBndr BndrVis]
-> Maybe Type
-> [Con]
-> [DerivClause]
-> Dec
DataD [] Name
childDataName [TyVarBndr BndrVis]
subrouteDecTypeArgs Maybe Type
forall a. Maybe a
Nothing [Con]
cons [DerivClause]
conts

-- | The shared preamble for rendering a 'ResourceParent': fresh names for the
-- parent's dynamic pieces and for the wrapped @child@ route, plus the
-- constructor pattern @Name dyn… child@ binding them. Returns the dynamic
-- names, the child name, and the pattern.
parentConPat :: String -> [Piece a] -> Q ([Name], Name, Pat)
parentConPat :: forall a. String -> [Piece a] -> Q ([Name], Name, Pat)
parentConPat String
name [Piece a]
pieces = do
    let cnt :: Int
cnt = [()] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [() | Dynamic{} <- [Piece a]
pieces]
    dyns <- Int -> Q Name -> Q [Name]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
cnt (Q Name -> Q [Name]) -> Q Name -> Q [Name]
forall a b. (a -> b) -> a -> b
$ String -> Q Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"dyn"
    child <- newName "child"
    pure (dyns, child, conPCompat (mkName name) $ map VarP $ dyns ++ [child])

-- | Is this path piece a dynamic capture, as opposed to a static segment?
isDynamic :: Piece t -> Bool
isDynamic :: forall t. Piece t -> Bool
isDynamic Dynamic{} = Bool
True
isDynamic Piece t
_ = Bool
False

-- | Render a route's path pieces to a list of @Text@-valued expressions,
-- pairing each 'Dynamic' piece with its bound variable in order. Fails the
-- splice if the piece list and the binder list are out of sync (a dynamic
-- piece with no corresponding bound variable).
mkPieces :: (String -> Exp) -> Exp -> [Piece t] -> [Name] -> Q [Exp]
mkPieces :: forall t. (String -> Exp) -> Exp -> [Piece t] -> [Name] -> Q [Exp]
mkPieces String -> Exp
_ Exp
_ [] [Name]
_ = [Exp] -> Q [Exp]
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
mkPieces String -> Exp
toText Exp
tsp (Static String
s:[Piece t]
ps) [Name]
dyns = (String -> Exp
toText String
s Exp -> [Exp] -> [Exp]
forall a. a -> [a] -> [a]
:) ([Exp] -> [Exp]) -> Q [Exp] -> Q [Exp]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (String -> Exp) -> Exp -> [Piece t] -> [Name] -> Q [Exp]
forall t. (String -> Exp) -> Exp -> [Piece t] -> [Name] -> Q [Exp]
mkPieces String -> Exp
toText Exp
tsp [Piece t]
ps [Name]
dyns
mkPieces String -> Exp
toText Exp
tsp (Dynamic{}:[Piece t]
ps) (Name
d:[Name]
dyns) = (Exp
tsp Exp -> Exp -> Exp
`AppE` Name -> Exp
VarE Name
d Exp -> [Exp] -> [Exp]
forall a. a -> [a] -> [a]
:) ([Exp] -> [Exp]) -> Q [Exp] -> Q [Exp]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (String -> Exp) -> Exp -> [Piece t] -> [Name] -> Q [Exp]
forall t. (String -> Exp) -> Exp -> [Piece t] -> [Name] -> Q [Exp]
mkPieces String -> Exp
toText Exp
tsp [Piece t]
ps [Name]
dyns
mkPieces String -> Exp
_ Exp
_ (Dynamic t
_ : [Piece t]
_) [] =
    String -> Q [Exp]
forall a. String -> Q a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"RenderRoute.mkPieces: a dynamic path piece has no corresponding bound variable (route definition and piece-binder list are out of sync)"

-- | Clauses for the 'renderRoute' method. This should be called from the
-- instance derivation for 'RenderRoute'.
mkRenderRouteClauses :: RouteOpts -> TyArgs -> [ResourceTree Type] -> Q [Clause]
mkRenderRouteClauses :: RouteOpts -> TyArgs -> [ResourceTree Type] -> Q [Clause]
mkRenderRouteClauses RouteOpts
opts TyArgs
origTyargs =
    [ResourceTree Type] -> Q [Clause]
forall {typ}. [ResourceTree typ] -> Q [Clause]
goList
  where
    goList :: [ResourceTree typ] -> Q [Clause]
goList = ([[Clause]] -> [Clause]) -> Q [[Clause]] -> Q [Clause]
forall a b. (a -> b) -> Q a -> Q b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [[Clause]] -> [Clause]
forall a. Monoid a => [a] -> a
mconcat (Q [[Clause]] -> Q [Clause])
-> ([ResourceTree typ] -> Q [[Clause]])
-> [ResourceTree typ]
-> Q [Clause]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ResourceTree typ -> Q [Clause])
-> [ResourceTree typ] -> 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 ResourceTree typ -> Q [Clause]
go

    mode :: DiscoveryMode
mode = RouteOpts -> TyArgs -> DiscoveryMode
discoveryMode RouteOpts
opts TyArgs
origTyargs

    go :: ResourceTree typ -> Q [Clause]
go (ResourceParent String
name Bool
_check Set String
_attrs [Piece typ]
pieces [ResourceTree typ]
children) =
        case DiscoveryMode
mode of
            -- Opted in to nested discovery: the parent's renderRoute delegates
            -- to the child's RenderRouteNested instance.
            DiscoveryMode
NestedDiscovery -> Q [Clause]
goNested
            -- Backwards-compatible default: inline the child clauses,
            -- prepending this parent's path pieces, exactly as historical
            -- Yesod did.
            DiscoveryMode
InlineCompat -> Q [Clause]
goInline
      where
        goNested :: Q [Clause]
goNested = do
            (dyns, child, pat) <- String -> [Piece typ] -> Q ([Name], Name, Pat)
forall a. String -> [Piece a] -> Q ([Name], Name, Pat)
parentConPat String
name [Piece typ]
pieces

            body <- [| renderRouteNested $(pure (parentArgsExpr dyns)) $(pure (VarE child)) |]
            pure [Clause [pat] (NormalB body) []]

        goInline :: Q [Clause]
goInline = do
            (dyns, child, pat) <- String -> [Piece typ] -> Q ([Name], Name, Pat)
forall a. String -> [Piece a] -> Q ([Name], Name, Pat)
parentConPat String
name [Piece typ]
pieces

            pack' <- [|pack|]
            tsp <- [|toPathPiece|]
            piecesSingle <- mkPieces (AppE pack' . LitE . StringL) tsp pieces dyns

            childRender <- newName "childRender"
            childClauses <- goList children

            body <- delegatingBody piecesSingle (VarE childRender) (VarE child)

            pure [Clause [pat] (NormalB body) [FunD childRender childClauses]]

    go (ResourceLeaf Resource typ
res) = do
        let cnt :: Int
cnt = [Piece typ] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ((Piece typ -> Bool) -> [Piece typ] -> [Piece typ]
forall a. (a -> Bool) -> [a] -> [a]
filter Piece typ -> Bool
forall t. Piece t -> Bool
isDynamic ([Piece typ] -> [Piece typ]) -> [Piece typ] -> [Piece typ]
forall a b. (a -> b) -> a -> b
$ Resource typ -> [Piece typ]
forall typ. Resource typ -> [Piece typ]
resourcePieces Resource typ
res) Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int -> (typ -> Int) -> Maybe typ -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int
0 (Int -> typ -> Int
forall a b. a -> b -> a
const Int
1) (Resource typ -> Maybe typ
forall typ. Resource typ -> Maybe typ
resourceMulti Resource typ
res)
        dyns <- Int -> Q Name -> Q [Name]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
cnt (Q Name -> Q [Name]) -> Q Name -> Q [Name]
forall a b. (a -> b) -> a -> b
$ String -> Q Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"dyn"
        sub <-
            case resourceDispatch res of
                Subsite{} -> Name -> [Name]
forall a. a -> [a]
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> [Name]) -> Q Name -> Q [Name]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> Q Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"sub"
                Dispatch typ
_ -> [Name] -> Q [Name]
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return []
        let pat = Name -> [Pat] -> Pat
conPCompat (String -> Name
mkName (String -> Name) -> String -> Name
forall a b. (a -> b) -> a -> b
$ Resource typ -> String
forall typ. Resource typ -> String
resourceName Resource typ
res) ([Pat] -> Pat) -> [Pat] -> Pat
forall a b. (a -> b) -> a -> b
$ (Name -> Pat) -> [Name] -> [Pat]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Pat
VarP ([Name] -> [Pat]) -> [Name] -> [Pat]
forall a b. (a -> b) -> a -> b
$ [Name]
dyns [Name] -> [Name] -> [Name]
forall a. [a] -> [a] -> [a]
++ [Name]
sub

        pack' <- [|pack|]
        tsp <- [|toPathPiece|]
        piecesSingle <- mkPieces (AppE pack' . LitE . StringL) tsp (resourcePieces res) dyns

        piecesMulti <-
            case resourceMulti res of
                Maybe typ
Nothing -> 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
$ [Exp] -> Exp
ListE []
                Just{} -> do
                    tmp <- [|toPathMultiPiece|]
                    return $ tmp `AppE` VarE (last dyns)

        body <-
            case sub of
                [Name
x] -> do
                    rr <- [|renderRoute|]
                    delegatingBody piecesSingle rr (VarE x)
                [Name]
_ ->
                    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
$ [Exp] -> Exp
mkTupE [(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
consE Exp
piecesMulti [Exp]
piecesSingle, [Exp] -> Exp
ListE []]

        return [Clause [pat] (NormalB body) []]

-- | Build a renderRoute body that delegates its tail to another render
-- function — either a nested child's @renderRouteNested@ (the inline
-- 'ResourceParent' arm) or an embedded subsite's @renderRoute@ (the
-- 'ResourceLeaf' subsite arm). The path-piece list passed in is prepended to
-- the delegate's path list (callers include any parent pieces themselves) and
-- the query string is threaded through unchanged.
delegatingBody
    :: [Exp]    -- ^ this route's own path pieces (already including any parent pieces)
    -> Exp      -- ^ the delegate render function
    -> Exp      -- ^ the child/subsite route argument to render
    -> Q Exp
delegatingBody :: [Exp] -> Exp -> Exp -> Q Exp
delegatingBody [Exp]
piecesSingle Exp
rr Exp
childArg = do
    a <- String -> Q Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"a"
    b <- newName "b"
    let pieces' = (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
consE (Name -> Exp
VarE Name
a) [Exp]
piecesSingle
    [e| ( \ ( $(varP a), $(varP b) ) -> ( $(pure pieces'), $(varE b) ) )
        ( $(pure rr) $(pure childArg) )
        |]

-- | Like 'mkRenderRouteClauses', but instead generates clauses for the
-- definition of 'renderRouteNested'.
--
-- @since 1.7.0.0
mkRenderRouteNestedClauses
    :: [Either String Name]
    -- ^ Either the static path piece or the names of the tuple of the parent arg.
    --
    -- These are both necessary to re-synthesize the total route.
    -> [ResourceTree Type]
    -> Q [Clause]
mkRenderRouteNestedClauses :: [Either String Name] -> [ResourceTree Type] -> Q [Clause]
mkRenderRouteNestedClauses [Either String Name]
parentArgsNames [ResourceTree Type]
resources = do
    ([[Clause]] -> [Clause]) -> Q [[Clause]] -> Q [Clause]
forall a b. (a -> b) -> Q a -> Q b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [[Clause]] -> [Clause]
forall a. Monoid a => [a] -> a
mconcat (Q [[Clause]] -> Q [Clause])
-> ([ResourceTree Type] -> Q [[Clause]])
-> [ResourceTree Type]
-> Q [Clause]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ResourceTree Type -> Q [Clause])
-> [ResourceTree Type] -> 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 ResourceTree Type -> Q [Clause]
forall {typ}. ResourceTree typ -> Q [Clause]
go ([ResourceTree Type] -> Q [Clause])
-> [ResourceTree Type] -> Q [Clause]
forall a b. (a -> b) -> a -> b
$ [ResourceTree Type]
resources
  where
    go :: ResourceTree typ -> Q [Clause]
go (ResourceParent String
name Bool
_check Set String
_attrs [Piece typ]
pieces [ResourceTree typ]
_children) = do
        (dyns, child, pat) <- String -> [Piece typ] -> Q ([Name], Name, Pat)
forall a. String -> [Piece a] -> Q ([Name], Name, Pat)
parentConPat String
name [Piece typ]
pieces

        -- Extract parent dynamic variables from parentArgsNames
        let parentDyns = (Either String Name -> Maybe Name)
-> [Either String Name] -> [Name]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe ((String -> Maybe Name)
-> (Name -> Maybe Name) -> Either String Name -> Maybe Name
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe Name -> String -> Maybe Name
forall a b. a -> b -> a
const Maybe Name
forall a. Maybe a
Nothing) Name -> Maybe Name
forall a. a -> Maybe a
Just) [Either String Name]
parentArgsNames

        -- Accumulate parent args: combine parent dynamic vars with this route's dynamic vars
        let allDyns = [Name]
parentDyns [Name] -> [Name] -> [Name]
forall a. [a] -> [a] -> [a]
++ [Name]
dyns
            accumulatedParentArgsExp = [Name] -> Exp
parentArgsExpr [Name]
allDyns

        -- The body should call renderRouteNested with accumulated parent args
        body <- [| renderRouteNested $(pure accumulatedParentArgsExp) $(pure (VarE child)) |]
        pure [Clause [parentArgsPat parentDyns, pat] (NormalB body) []]

    go (ResourceLeaf Resource typ
res) = do
        let cnt :: Int
cnt = [Piece typ] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ((Piece typ -> Bool) -> [Piece typ] -> [Piece typ]
forall a. (a -> Bool) -> [a] -> [a]
filter Piece typ -> Bool
forall t. Piece t -> Bool
isDynamic ([Piece typ] -> [Piece typ]) -> [Piece typ] -> [Piece typ]
forall a b. (a -> b) -> a -> b
$ Resource typ -> [Piece typ]
forall typ. Resource typ -> [Piece typ]
resourcePieces Resource typ
res) Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int -> (typ -> Int) -> Maybe typ -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int
0 (Int -> typ -> Int
forall a b. a -> b -> a
const Int
1) (Resource typ -> Maybe typ
forall typ. Resource typ -> Maybe typ
resourceMulti Resource typ
res)
        dyns <- Int -> Q Name -> Q [Name]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
cnt (Q Name -> Q [Name]) -> Q Name -> Q [Name]
forall a b. (a -> b) -> a -> b
$ String -> Q Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"dyn"
        sub <-
            case resourceDispatch res of
                Subsite{} -> Name -> [Name]
forall a. a -> [a]
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> [Name]) -> Q Name -> Q [Name]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> Q Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"sub"
                Dispatch typ
_ -> [Name] -> Q [Name]
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return []
        let pat = Name -> [Pat] -> Pat
conPCompat (String -> Name
mkName (String -> Name) -> String -> Name
forall a b. (a -> b) -> a -> b
$ Resource typ -> String
forall typ. Resource typ -> String
resourceName Resource typ
res) ([Pat] -> Pat) -> [Pat] -> Pat
forall a b. (a -> b) -> a -> b
$ (Name -> Pat) -> [Name] -> [Pat]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Pat
VarP ([Name] -> [Pat]) -> [Name] -> [Pat]
forall a b. (a -> b) -> a -> b
$ [Name]
dyns [Name] -> [Name] -> [Name]
forall a. [a] -> [a] -> [a]
++ [Name]
sub

        pack' <- [|pack|]
        tsp <- [|toPathPiece|]

        -- Build the FULL path including parent pieces
        -- parentArgsNames contains Either String Name for each piece in the parent path
        let parentDyns = (Either String Name -> Maybe Name)
-> [Either String Name] -> [Name]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe ((String -> Maybe Name)
-> (Name -> Maybe Name) -> Either String Name -> Maybe Name
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe Name -> String -> Maybe Name
forall a b. a -> b -> a
const Maybe Name
forall a. Maybe a
Nothing) Name -> Maybe Name
forall a. a -> Maybe a
Just) [Either String Name]
parentArgsNames

        -- Build parent path pieces from parentArgsNames
        parentPieces <- mkParentPieces pack' tsp parentArgsNames parentDyns
        -- Build this resource's own pieces
        thisResourcePieces <- mkPieces (AppE pack' . LitE . StringL) tsp (resourcePieces res) dyns

        piecesMulti <-
            case resourceMulti res of
                Maybe typ
Nothing -> 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
$ [Exp] -> Exp
ListE []
                Just{} -> do
                    tmp <- [|toPathMultiPiece|]
                    return $ tmp `AppE` VarE (last dyns)

        body <-
            case sub of
                [Name
x] -> do
                    rr <- [|renderRoute|]
                    -- Combine parent pieces with this resource's pieces
                    delegatingBody (parentPieces ++ thisResourcePieces) rr (VarE x)
                [Name]
_ -> do
                    colon <- [|(:)|]
                    let cons Exp
a Exp
b = Maybe Exp -> Exp -> Maybe Exp -> Exp
InfixE (Exp -> Maybe Exp
forall a. a -> Maybe a
Just Exp
a) Exp
colon (Exp -> Maybe Exp
forall a. a -> Maybe a
Just Exp
b)
                    -- Combine parent pieces with this resource's pieces
                    let allPieces = [Exp]
parentPieces [Exp] -> [Exp] -> [Exp]
forall a. [a] -> [a] -> [a]
++ [Exp]
thisResourcePieces
                    return $ mkTupE [foldr cons piecesMulti allPieces, ListE []]

        return [Clause [parentArgsPat parentDyns, pat] (NormalB body) []]

    -- Build path pieces from parentArgsNames (which contains both static and dynamic pieces)
    mkParentPieces :: Exp -> Exp -> [Either String Name] -> [Name] -> Q [Exp]
    mkParentPieces :: Exp -> Exp -> [Either String Name] -> [Name] -> Q [Exp]
mkParentPieces Exp
pack' Exp
tsp [Either String Name]
parentArgsNames' [Name]
parentDyns = [Either String Name] -> [Name] -> Q [Exp]
forall {f :: * -> *} {b}.
MonadFail f =>
[Either String b] -> [Name] -> f [Exp]
goParentPieces [Either String Name]
parentArgsNames' [Name]
parentDyns
      where
        goParentPieces :: [Either String b] -> [Name] -> f [Exp]
goParentPieces [] [Name]
_ = [Exp] -> f [Exp]
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
        goParentPieces (Left String
staticStr : [Either String b]
rest) [Name]
dyns =
            ((Exp
pack' Exp -> Exp -> Exp
`AppE` Lit -> Exp
LitE (String -> Lit
StringL String
staticStr)) Exp -> [Exp] -> [Exp]
forall a. a -> [a] -> [a]
:) ([Exp] -> [Exp]) -> f [Exp] -> f [Exp]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Either String b] -> [Name] -> f [Exp]
goParentPieces [Either String b]
rest [Name]
dyns
        goParentPieces (Right b
_ : [Either String b]
rest) (Name
dyn : [Name]
dyns) =
            ((Exp
tsp Exp -> Exp -> Exp
`AppE` Name -> Exp
VarE Name
dyn) Exp -> [Exp] -> [Exp]
forall a. a -> [a] -> [a]
:) ([Exp] -> [Exp]) -> f [Exp] -> f [Exp]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Either String b] -> [Name] -> f [Exp]
goParentPieces [Either String b]
rest [Name]
dyns
        goParentPieces (Right b
_ : [Either String b]
_) [] =
            String -> f [Exp]
forall a. String -> f a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"RenderRoute.mkParentPieces: a dynamic parent path piece has no corresponding bound variable"

-- | The shared core of every 'RenderRouteNested' instance body. From a parent
-- route's accumulated path pieces and its child resources it computes the
-- @ParentArgs@ tuple 'Type' and the @renderRouteNested@ method clauses. The
-- three instance-emitting sites (the inline child datatype in
-- 'mkRenderRouteInstanceOpts', the focused target in
-- 'mkRenderRouteNestedInstanceOpts', and that target's nested children) differ
-- only in the instance head, the @ParentSite@ right-hand side, and the context
-- they wrap around this — so only those wrappers remain at the call sites, and
-- the piece-naming\/clause-building boilerplate (including the dynamic-binder
-- name derivation) lives here once.
renderRouteNestedBody
    :: [Piece Type]            -- ^ accumulated parent path pieces
    -> [ResourceTree Type]     -- ^ child resources
    -> Q (Type, [Clause])      -- ^ (ParentArgs tuple type, renderRouteNested clauses)
renderRouteNestedBody :: [Piece Type] -> [ResourceTree Type] -> Q (Type, [Clause])
renderRouteNestedBody [Piece Type]
prepieces [ResourceTree Type]
children = do
    let piecesAndNames :: [Either String Type]
piecesAndNames =
            (Piece Type -> Either String Type)
-> [Piece Type] -> [Either String Type]
forall a b. (a -> b) -> [a] -> [b]
map (\Piece Type
p -> case Piece Type
p of
                    Static String
str -> String -> Either String Type
forall a b. a -> Either a b
Left String
str
                    Dynamic Type
a -> Type -> Either String Type
forall a b. b -> Either a b
Right Type
a)
                [Piece Type]
prepieces
        preDyns :: [Type]
preDyns = (Either String Type -> Maybe Type)
-> [Either String Type] -> [Type]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe ((String -> Maybe Type)
-> (Type -> Maybe Type) -> Either String Type -> Maybe Type
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe Type -> String -> Maybe Type
forall a b. a -> b -> a
const Maybe Type
forall a. Maybe a
Nothing) Type -> Maybe Type
forall a. a -> Maybe a
Just) [Either String Type]
piecesAndNames
    let parentDynT :: Type
parentDynT = [Type] -> Type
parentArgsType [Type]
preDyns
    parentNames <- [Either String Type]
-> (Either String Type -> Q (Either String Name))
-> Q [Either String Name]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM [Either String Type]
piecesAndNames ((Either String Type -> Q (Either String Name))
 -> Q [Either String Name])
-> (Either String Type -> Q (Either String Name))
-> Q [Either String Name]
forall a b. (a -> b) -> a -> b
$ \Either String Type
epiece'name ->
        case Either String Type
epiece'name of
            Left String
piece -> Either String Name -> Q (Either String Name)
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (String -> Either String Name
forall a b. a -> Either a b
Left String
piece)
            Right Type
t ->
                case (Char -> Bool) -> ShowS
forall a. (a -> Bool) -> [a] -> [a]
filter Char -> Bool
isAlphaNum (Type -> String
forall a. Show a => a -> String
show Type
t) of
                    (Char
a : String
as) -> Name -> Either String Name
forall a b. b -> Either a b
Right (Name -> Either String Name) -> Q Name -> Q (Either String Name)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> Q Name
forall (m :: * -> *). Quote m => String -> m Name
newName (Char -> Char
toLower Char
a Char -> ShowS
forall a. a -> [a] -> [a]
: String
as)
                    []       -> String -> Q (Either String Name)
forall a. String -> Q a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail
                        String
"renderRouteNested: a dynamic piece's type renders with no alphanumeric characters, so no binder name can be derived from it"
    childClauses <- mkRenderRouteNestedClauses parentNames children
    pure (parentDynT, childClauses)

-- | Generate the 'RenderRoute' instance.
--
-- This includes both the 'Route' associated type and the
-- 'renderRoute' method.  This function uses both 'mkRouteConsOpts' and
-- 'mkRenderRouteClauses'.
--
-- @since 1.6.25.0
mkRenderRouteInstanceOpts
    :: RouteOpts
    -> Cxt
    -- ^ The context passed around for the instances
    -> TyArgs
    -- ^ Type arguments
    -> Type
    -- ^ The type of the foundation resource
    -> [ResourceTree Type]
    -- ^ The actual tree of routes to generate code for
    -> Q [Dec]
mkRenderRouteInstanceOpts :: RouteOpts
-> [Type] -> TyArgs -> Type -> [ResourceTree Type] -> Q [Dec]
mkRenderRouteInstanceOpts RouteOpts
opts [Type]
cxt TyArgs
tyargs Type
typ [ResourceTree Type]
ress = do
    case RouteOpts -> Maybe String
roFocusOnNestedRoute RouteOpts
opts of
        Maybe String
Nothing -> do
            cls <- RouteOpts -> TyArgs -> [ResourceTree Type] -> Q [Clause]
mkRenderRouteClauses RouteOpts
opts TyArgs
tyargs [ResourceTree Type]
ress
            (cons, decs) <- mkRouteConsOpts opts cxt tyargs typ ress
            let did = [Type]
-> Maybe [TyVarBndr ()]
-> Type
-> Maybe Type
-> [Con]
-> [DerivClause]
-> Dec
DataInstD []
#if MIN_VERSION_template_haskell(2,15,0)
                    Maybe [TyVarBndr ()]
forall a. Maybe a
Nothing Type
routeDataName
#else
                    ''Route [typ]
#endif
                    Maybe Type
forall a. Maybe a
Nothing [Con]
cons [DerivClause]
inlineDerives
            -- ToParentRoute instances are only needed by the nested-discovery
            -- machinery; the backwards-compatible default emits none.
            parentRouteInstancesDecs <-
                case discoveryMode opts tyargs of
                    DiscoveryMode
NestedDiscovery -> [Type] -> TyArgs -> [ResourceTree Type] -> Q [Dec]
mkToParentRouteInstances [Type]
cxt TyArgs
tyargs [ResourceTree Type]
ress
                    DiscoveryMode
InlineCompat    -> [Dec] -> Q [Dec]
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
            pure $ mconcat
                [ pure $ instanceD cxt (ConT ''RenderRoute `AppT` typ)
                    [ did
                    , FunD 'renderRoute cls
                    ]
                , mkStandaloneDerives routeDataName
                , decs
                , parentRouteInstancesDecs
                ]
        Just String
target ->
            case String
-> [ResourceTree Type] -> Maybe ([Piece Type], [ResourceTree Type])
forall a.
String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute String
target [ResourceTree Type]
ress of
                Maybe ([Piece Type], [ResourceTree Type])
Nothing ->
                    String -> Q [Dec]
forall a. String -> Q a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Q [Dec]) -> String -> Q [Dec]
forall a b. (a -> b) -> a -> b
$ String
"Target '" String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
target String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
"' was not found in resources."
                Just ([Piece Type]
prepieces, [ResourceTree Type]
ress') ->
                    RouteOpts
-> [Type]
-> TyArgs
-> Type
-> [Piece Type]
-> String
-> [ResourceTree Type]
-> Q [Dec]
mkRenderRouteNestedInstanceOpts RouteOpts
opts [Type]
cxt TyArgs
tyargs Type
typ [Piece Type]
prepieces String
target [ResourceTree Type]
ress'
  where
    routeDataName :: Type
routeDataName = Name -> Type
ConT ''Route Type -> Type -> Type
`AppT` Type
typ
    ([DerivClause]
inlineDerives, Type -> [Dec]
mkStandaloneDerives) = RouteOpts -> [Type] -> ([DerivClause], Type -> [Dec])
getDerivesFor RouteOpts
opts [Type]
cxt

-- | Get the simple derivation clauses and the standalone derivation clauses
-- for a given type and context.
--
-- If there are any additional classes needed for context, we just produce standalone
-- clauses. Else, we produce basic deriving clauses for a declaration.
getDerivesFor :: RouteOpts -> Cxt -> ([DerivClause], Type ->  [Dec])
getDerivesFor :: RouteOpts -> [Type] -> ([DerivClause], Type -> [Dec])
getDerivesFor RouteOpts
opts [Type]
cxt
    | [Type] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Type]
cxt =
        ( [Maybe DerivStrategy -> [Type] -> DerivClause
DerivClause Maybe DerivStrategy
forall a. Maybe a
Nothing [Type]
clazzes']
        , [Dec] -> Type -> [Dec]
forall a b. a -> b -> a
const []
        )
    | Bool
otherwise =
        ( []
        , \Type
typ -> (Type -> Dec) -> [Type] -> [Dec]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Maybe DerivStrategy -> [Type] -> Type -> Dec
StandaloneDerivD Maybe DerivStrategy
forall a. Maybe a
Nothing [Type]
cxt (Type -> Dec) -> (Type -> Type) -> Type -> Dec
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Type -> Type -> Type
`AppT` Type
typ)) [Type]
clazzes'
        )
  where
    clazzes' :: [Type]
clazzes' = Name -> Type
ConT (Name -> Type) -> [Name] -> [Type]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> RouteOpts -> [Name]
instanceNamesFromOpts RouteOpts
opts

-- | For each datatype, generate an instance of 'ToParentRoute' for the
-- datatype. Instances should mostly look like this:
--
-- > instance ToParentRoute FooR where
-- >     toParentRoute (a0, a1) = FooR a0 a1
mkToParentRouteInstances :: Cxt -> TyArgs -> [ResourceTree Type] -> Q [Dec]
mkToParentRouteInstances :: [Type] -> TyArgs -> [ResourceTree Type] -> Q [Dec]
mkToParentRouteInstances [Type]
cxt TyArgs
origTyargs [ResourceTree Type]
ress = do
    [[Dec]] -> [Dec]
forall a. Monoid a => [a] -> a
mconcat ([[Dec]] -> [Dec]) -> Q [[Dec]] -> Q [Dec]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ResourceTree Type -> Q [Dec]) -> [ResourceTree Type] -> Q [[Dec]]
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 (([Piece Type], [(Name, Int)]) -> ResourceTree Type -> Q [Dec]
forall {f :: * -> *} {a}.
Quote f =>
([Piece a], [(Name, Int)]) -> ResourceTree a -> f [Dec]
go ([], [])) [ResourceTree Type]
ress
  where
    go :: ([Piece a], [(Name, Int)]) -> ResourceTree a -> f [Dec]
go ([Piece a], [(Name, Int)])
_ (ResourceLeaf Resource a
_) =
        [Dec] -> f [Dec]
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
    go ([Piece a]
accPieces, [(Name, Int)]
parentConstructors) (ResourceParent String
name Bool
_check Set String
_attrs [Piece a]
pieces [ResourceTree a]
children) = do
        -- Extract dynamic types from accumulated parent pieces
        let accDynTypes :: [a]
accDynTypes = [a
t | Dynamic a
t <- [Piece a]
accPieces]
        accDynVars <- (a -> f Name) -> [a] -> f [Name]
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 (\a
_ -> String -> f Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"parent") [a]
accDynTypes

        -- Extract dynamic types from this route's pieces
        let piecesDynTypes = [a
t | Dynamic a
t <- [Piece a]
pieces]
        piecesDynVars <- mapM (\a
_ -> String -> f Name
forall (m :: * -> *). Quote m => String -> m Name
newName String
"piece") piecesDynTypes

        -- Child route variable
        child <- newName "child"

        -- ParentArgs includes BOTH acc and pieces dynamic vars
        let allParentDynVars = [Name]
accDynVars [Name] -> [Name] -> [Name]
forall a. [a] -> [a] -> [a]
++ [Name]
piecesDynVars

        -- Build the full route by applying all parent constructors
        -- We need to partition allParentDynVars according to each constructor's piece count
        let applyConToParentArgs = [(Name, Int)] -> Name -> [Name] -> Exp -> Exp
buildRouteExpr [(Name, Int)]
parentConstructors (String -> Name
mkName String
name) [Name]
allParentDynVars (Name -> Exp
VarE Name
child)

        let toParentRouteD =
                Name -> [Clause] -> Dec
FunD 'toParentRoute
                    [ [Pat] -> Body -> [Dec] -> Clause
Clause
                        [[Name] -> Pat
parentArgsPat [Name]
allParentDynVars, Name -> Pat
VarP Name
child]
                        (Exp -> Body
NormalB Exp
applyConToParentArgs)
                        []
                    ]

        let thisInstance =
                [Type] -> Type -> [Dec] -> Dec
instanceD [Type]
cxt (Name -> Type
ConT ''ToParentRoute Type -> Type -> Type
`AppT` String -> Type
applyTypeVariables String
name) [Dec
toParentRouteD]

        -- Accumulate pieces and constructor info for children
        let thisPieceCount = [a] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [a]
piecesDynTypes
            acc' =
                ( [Piece a]
accPieces [Piece a] -> [Piece a] -> [Piece a]
forall a. Semigroup a => a -> a -> a
<> [Piece a]
pieces
                , [(Name, Int)]
parentConstructors [(Name, Int)] -> [(Name, Int)] -> [(Name, Int)]
forall a. [a] -> [a] -> [a]
++ [(String -> Name
mkName String
name, Int
thisPieceCount)]
                )

        childrenInstances <- mconcat <$> mapM (go acc') children
        pure $ thisInstance : childrenInstances

    applyTypeVariables :: String -> Type
applyTypeVariables String
name =
        Type -> TyArgs -> Type
applyTyArgs (Name -> Type
ConT (String -> Name
mkName String
name)) TyArgs
origTyargs

    -- Build the route expression by applying constructors from outermost to innermost
    buildRouteExpr :: [(Name, Int)] -> Name -> [Name] -> Exp -> Exp
    buildRouteExpr :: [(Name, Int)] -> Name -> [Name] -> Exp -> Exp
buildRouteExpr [(Name, Int)]
parentCtors Name
thisCtor [Name]
allDynVars Exp
childExpr =
        let -- All constructors including this one
            thisPieceCount :: Int
thisPieceCount = [Name] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Name]
allDynVars Int -> Int -> Int
forall a. Num a => a -> a -> a
- [Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum (((Name, Int) -> Int) -> [(Name, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Name, Int) -> Int
forall a b. (a, b) -> b
snd [(Name, Int)]
parentCtors)
            allCtors :: [(Name, Int)]
allCtors = [(Name, Int)]
parentCtors [(Name, Int)] -> [(Name, Int)] -> [(Name, Int)]
forall a. [a] -> [a] -> [a]
++ [(Name
thisCtor, Int
thisPieceCount)]

            -- Partition dynamic vars for each constructor
            partitionedVars :: [[Name]]
partitionedVars = [Name] -> [(Name, Int)] -> [[Name]]
forall {a} {a}. [a] -> [(a, Int)] -> [[a]]
go' [Name]
allDynVars [(Name, Int)]
allCtors
              where
                go' :: [a] -> [(a, Int)] -> [[a]]
go' [a]
_ [] = []
                go' [a]
vars ((a
_, Int
count) : [(a, Int)]
rest) =
                    let ([a]
varsForThis, [a]
remaining) = Int -> [a] -> ([a], [a])
forall a. Int -> [a] -> ([a], [a])
splitAt Int
count [a]
vars
                    in [a]
varsForThis [a] -> [[a]] -> [[a]]
forall a. a -> [a] -> [a]
: [a] -> [(a, Int)] -> [[a]]
go' [a]
remaining [(a, Int)]
rest

            -- Build expression from inside out using foldr
            finalExpr :: Exp
finalExpr = ((Name, [Name]) -> Exp -> Exp) -> Exp -> [(Name, [Name])] -> Exp
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr
                (\(Name
ctorName, [Name]
varsForThis) Exp
innerExpr ->
                    (Exp -> Exp -> Exp) -> Exp -> [Exp] -> Exp
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Exp -> Exp -> Exp
AppE (Name -> Exp
ConE Name
ctorName) ((Name -> Exp) -> [Name] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Exp
VarE [Name]
varsForThis [Exp] -> [Exp] -> [Exp]
forall a. [a] -> [a] -> [a]
++ [Exp
innerExpr]))
                Exp
childExpr
                ([Name] -> [[Name]] -> [(Name, [Name])]
forall a b. [a] -> [b] -> [(a, b)]
zip (((Name, Int) -> Name) -> [(Name, Int)] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map (Name, Int) -> Name
forall a b. (a, b) -> a
fst [(Name, Int)]
allCtors) [[Name]]
partitionedVars)
        in Exp
finalExpr

notStrict :: Bang
notStrict :: Bang
notStrict = SourceUnpackedness -> SourceStrictness -> Bang
Bang SourceUnpackedness
NoSourceUnpackedness SourceStrictness
NoSourceStrictness

-- | Assemble a @RenderRouteNested@ instance from the pieces that vary between
-- the three sites that emit one (the inline child datatype in
-- 'mkRouteConsOpts', the focused target and its nested children in
-- 'mkRenderRouteNestedInstanceOpts'). The context, child route 'Type',
-- @ParentSite@ right-hand side (the foundation 'Type') and @ParentArgs@ tuple
-- 'Type' plus the @renderRouteNested@ clauses are all that differ; everything
-- else is shared here.
--
-- @since 1.7.0.0
mkRenderRouteNestedInstanceD
    :: Cxt        -- ^ instance context
    -> Type       -- ^ the child route datatype (instance head argument)
    -> Type       -- ^ the @ParentSite@ right-hand side (the foundation type)
    -> Type       -- ^ the @ParentArgs@ tuple type
    -> [Clause]   -- ^ the @renderRouteNested@ method clauses
    -> Dec
mkRenderRouteNestedInstanceD :: [Type] -> Type -> Type -> Type -> [Clause] -> Dec
mkRenderRouteNestedInstanceD [Type]
instCxt Type
childRouteType Type
parentSiteRHS Type
parentArgsT [Clause]
clauses =
    [Type] -> Type -> [Dec] -> Dec
instanceD
        [Type]
instCxt
        (Name -> Type
ConT ''RenderRouteNested Type -> Type -> Type
`AppT` Type
childRouteType)
        [ TySynEqn -> Dec
TySynInstD (TySynEqn -> Dec) -> TySynEqn -> Dec
forall a b. (a -> b) -> a -> b
$ Maybe [TyVarBndr ()] -> Type -> Type -> TySynEqn
TySynEqn Maybe [TyVarBndr ()]
forall a. Maybe a
Nothing (Name -> Type
ConT ''ParentSite Type -> Type -> Type
`AppT` Type
childRouteType) Type
parentSiteRHS
        , TySynEqn -> Dec
TySynInstD (TySynEqn -> Dec) -> TySynEqn -> Dec
forall a b. (a -> b) -> a -> b
$ Maybe [TyVarBndr ()] -> Type -> Type -> TySynEqn
TySynEqn Maybe [TyVarBndr ()]
forall a. Maybe a
Nothing (Name -> Type
ConT ''ParentArgs Type -> Type -> Type
`AppT` Type
childRouteType) Type
parentArgsT
        , Name -> [Clause] -> Dec
FunD 'renderRouteNested [Clause]
clauses
        ]

-- | Generate the declarations for a nested-discovery /child/ datatype: the
-- (parameterized) datatype declaration, its @RenderRouteNested@ instance, and
-- any standalone deriving clauses. Shared by every nested-discovery
-- constructor generator ('mkRouteConsOpts' and 'mkRenderRouteNestedInstanceOpts')
-- so the datatype shape, instance context, and @ParentSite@\/@ParentArgs@ wiring
-- stay in one place. The focus\/inline gating that decides /whether/ to emit
-- these stays at the call sites, since that differs between them.
--
-- @since 1.7.0.0
nestedChildDataAndInstance
    :: RouteOpts
    -> Cxt           -- ^ instance context for the @RenderRouteNested@ instance
    -> Cxt           -- ^ deriving context for the child datatype (nullified when
                     --   the child carries no type arguments; see 'mkRouteConsOpts')
    -> TyArgs        -- ^ type arguments carried by the child datatype
    -> Type          -- ^ the @ParentSite@ right-hand side (the foundation type)
    -> Name          -- ^ the child datatype name
    -> [Con]         -- ^ the child datatype's constructors
    -> [Piece Type]  -- ^ accumulated parent path pieces for this child
    -> [ResourceTree Type] -- ^ the child's own children
    -> Q [Dec]
nestedChildDataAndInstance :: RouteOpts
-> [Type]
-> [Type]
-> TyArgs
-> Type
-> Name
-> [Con]
-> [Piece Type]
-> [ResourceTree Type]
-> Q [Dec]
nestedChildDataAndInstance RouteOpts
opts [Type]
instCxt [Type]
derivCxt TyArgs
tyargs Type
parentSiteRHS Name
childDataName [Con]
cons [Piece Type]
accPieces [ResourceTree Type]
children = do
    let subrouteDecTypeArgs :: [TyVarBndr BndrVis]
subrouteDecTypeArgs = (Name -> TyVarBndr BndrVis) -> [Name] -> [TyVarBndr BndrVis]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Name -> TyVarBndr BndrVis
plainTVCompat (TyArgs -> [Name]
tyArgsBinders TyArgs
tyargs)
        ([DerivClause]
inlineDerives, Type -> [Dec]
mkStandaloneDerives) = RouteOpts -> [Type] -> ([DerivClause], Type -> [Dec])
getDerivesFor RouteOpts
opts [Type]
derivCxt
        childData :: Dec
childData = [Type]
-> Name
-> [TyVarBndr BndrVis]
-> Maybe Type
-> [Con]
-> [DerivClause]
-> Dec
DataD [] Name
childDataName [TyVarBndr BndrVis]
subrouteDecTypeArgs Maybe Type
forall a. Maybe a
Nothing [Con]
cons [DerivClause]
inlineDerives
        childDataType :: Type
childDataType = Type -> TyArgs -> Type
applyTyArgs (Name -> Type
ConT Name
childDataName) TyArgs
tyargs
    (parentDynT, childClauses) <- [Piece Type] -> [ResourceTree Type] -> Q (Type, [Clause])
renderRouteNestedBody [Piece Type]
accPieces [ResourceTree Type]
children
    let childInstance =
            [Type] -> Type -> Type -> Type -> [Clause] -> Dec
mkRenderRouteNestedInstanceD [Type]
instCxt Type
childDataType Type
parentSiteRHS Type
parentDynT [Clause]
childClauses
    pure (childData : childInstance : mkStandaloneDerives childDataType)

mkRenderRouteNestedInstanceOpts
    :: RouteOpts
    -> Cxt
    -> TyArgs
    -> Type
    -> [Piece Type]
    -> String
    -> [ResourceTree Type]
    -> Q [Dec]
mkRenderRouteNestedInstanceOpts :: RouteOpts
-> [Type]
-> TyArgs
-> Type
-> [Piece Type]
-> String
-> [ResourceTree Type]
-> Q [Dec]
mkRenderRouteNestedInstanceOpts RouteOpts
routeOpts [Type]
cxt TyArgs
tyargs Type
typ [Piece Type]
prepieces String
target [ResourceTree Type]
ress = do
    -- Generate constructors for all children
    (cons, childDecs) <- [Piece Type] -> [ResourceTree Type] -> Q ([Con], [Dec])
mkFocusedChildCons [Piece Type]
prepieces [ResourceTree Type]
ress

    let targetName = String -> Name
mkName String
target
        targetDecs =
            -- The focused target datatype and its RenderRouteNested instance
            -- are emitted through the same shared builder as the in-module
            -- and nested-child paths, so the instance context is plain @cxt@
            -- (matching the in-module generator); demanding extra
            -- Eq/Show/Read constraints on the site type arguments here would
            -- be undischargeable at the delegating RenderRoute instance.
            RouteOpts
-> [Type]
-> [Type]
-> TyArgs
-> Type
-> Name
-> [Con]
-> [Piece Type]
-> [ResourceTree Type]
-> Q [Dec]
nestedChildDataAndInstance
                RouteOpts
routeOpts [Type]
cxt [Type]
childCxt TyArgs
tyargs Type
typ Name
targetName [Con]
cons [Piece Type]
prepieces [ResourceTree Type]
ress

    -- Return the datatype declaration, instance, and any standalone derives,
    -- followed by the declarations for any nested children.
    (<> childDecs) <$> targetDecs
  where
    -- The focused datatype carries the site's type arguments. See 'childDerivCxt'.
    childCxt :: [Type]
childCxt = TyArgs -> [Type] -> [Type]
childDerivCxt TyArgs
tyargs [Type]
cxt

    -- Generate constructors and nested-instance declarations for the children
    -- of the focused target. Structurally similar to 'mkRouteConsOpts'' inner
    -- @mkRouteCon@, but deliberately NOT shared: there we are walking the whole
    -- site and must honour the focus gate (skip datatypes other than the
    -- target) and the InlineCompat branch. Here every tree is already *inside*
    -- the focused target, so each parent unconditionally gets its
    -- RenderRouteNested instance — applying the focus gate here would wrongly
    -- skip grandchild instances.
    mkFocusedChildCons :: [Piece Type] -> [ResourceTree Type] -> Q ([Con], [Dec])
    mkFocusedChildCons :: [Piece Type] -> [ResourceTree Type] -> Q ([Con], [Dec])
mkFocusedChildCons [Piece Type]
prePieces [ResourceTree Type]
trees =
        [([Con], [Dec])] -> ([Con], [Dec])
forall a. Monoid a => [a] -> a
mconcat ([([Con], [Dec])] -> ([Con], [Dec]))
-> Q [([Con], [Dec])] -> Q ([Con], [Dec])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ResourceTree Type -> Q ([Con], [Dec]))
-> [ResourceTree Type] -> Q [([Con], [Dec])]
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 ([Piece Type] -> ResourceTree Type -> Q ([Con], [Dec])
mkFocusedChildCon [Piece Type]
prePieces) [ResourceTree Type]
trees

    mkFocusedChildCon :: [Piece Type] -> ResourceTree Type -> Q ([Con], [Dec])
    mkFocusedChildCon :: [Piece Type] -> ResourceTree Type -> Q ([Con], [Dec])
mkFocusedChildCon [Piece Type]
_ (ResourceLeaf Resource Type
res) =
        ([Con], [Dec]) -> Q ([Con], [Dec])
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Resource Type -> Con
leafRouteCon Resource Type
res], [])

    mkFocusedChildCon [Piece Type]
prePieces (ResourceParent String
name Bool
_check Set String
_attrs [Piece Type]
pieces [ResourceTree Type]
children) = do
        let accumulatedPieces :: [Piece Type]
accumulatedPieces = [Piece Type]
prePieces [Piece Type] -> [Piece Type] -> [Piece Type]
forall a. Semigroup a => a -> a -> a
<> [Piece Type]
pieces
        (cons, decs) <- [Piece Type] -> [ResourceTree Type] -> Q ([Con], [Dec])
mkFocusedChildCons [Piece Type]
accumulatedPieces [ResourceTree Type]
children
        let childDataName = String -> Name
mkName String
name

        -- Generate the child datatype and its RenderRouteNested instance unless
        -- the datatype already exists (generated by another split-out module).
        mname' <- lookupTypeName name
        mdec <- case mname' of
            Just Name
_ -> Maybe [Dec] -> Q (Maybe [Dec])
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe [Dec]
forall a. Maybe a
Nothing
            Maybe Name
Nothing ->
                [Dec] -> Maybe [Dec]
forall a. a -> Maybe a
Just ([Dec] -> Maybe [Dec]) -> Q [Dec] -> Q (Maybe [Dec])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
                    RouteOpts
-> [Type]
-> [Type]
-> TyArgs
-> Type
-> Name
-> [Con]
-> [Piece Type]
-> [ResourceTree Type]
-> Q [Dec]
nestedChildDataAndInstance
                        RouteOpts
routeOpts [Type]
cxt [Type]
childCxt TyArgs
tyargs Type
typ Name
childDataName [Con]
cons
                        [Piece Type]
accumulatedPieces [ResourceTree Type]
children

        return ([parentRouteCon name pieces tyargs], maybe id (<>) mdec decs)