{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}

module Yesod.Core.Internal.TH
    ( mkYesod
    , mkYesodOpts

    , mkYesodWith

    , mkYesodData
    , mkYesodDataOpts

    , mkYesodSubData
    , mkYesodSubDataOpts

    , mkYesodWithParser
    , mkYesodWithParserOpts

    , mkYesodDispatch
    , mkYesodDispatchOpts

    , masterTypeSyns

    , mkYesodGeneral
    , mkYesodGeneralOpts

    , mkMDS
    , mkDispatchInstance

    , mkYesodSubDispatch
    , mkYesodSubDispatchInstance
    , mkYesodSubDispatchInstanceOpts
    , mkNestedSubDispatchInstance

    , subTopDispatch

    , RouteOpts
    , defaultOpts
    , setEqDerived
    , setShowDerived
    , setReadDerived
    , setCreateResources
    , setFocusOnNestedRoute
    , unsetFocusOnNestedRoute
    , setParameterizedSubroute
    , setNestedRouteFallthrough
    )
 where

import Prelude hiding (exp)
import Yesod.Core.Handler
import Language.Haskell.TH hiding (cxt, instanceD)
import Language.Haskell.TH.Syntax
import Data.ByteString.Lazy.Char8 ()
import Data.List (foldl')
import Data.Maybe
import Control.Monad
import Yesod.Routes.TH
import Yesod.Routes.TH.Dispatch
    (parseYesodName, mkYesodSubDispatchWithDelegate, SameSpliceNestedInstances (..))
import Yesod.Routes.TH.Internal (instanceD, typeArity, assertNestedSubArity, ArityCallSite(..), SubsiteName(..), SubsiteArity(..), resolveRouteCon, nestedInstanceExists)
import Yesod.Routes.Parse
import Yesod.Core.Types
import Yesod.Core.Class.Dispatch (YesodSubDispatch(..), YesodSubDispatchNested(..))

-- | Generates URL datatype and site function for the given 'Resource's. This
-- is used for creating sites, /not/ subsites. See 'mkYesodSubData' and 'mkYesodSubDispatch' for the latter.
-- Use 'parseRoutes' to create the 'Resource's.
--
-- Contexts and type variables in the name of the datatype are parsed.
-- For example, a datatype @App a@ with typeclass constraint @MyClass a@ can be written as @\"(MyClass a) => App a\"@.
mkYesod :: String -- ^ name of the argument datatype
        -> [ResourceTree String]
        -> Q [Dec]
mkYesod :: String -> [ResourceTree String] -> Q [Dec]
mkYesod = RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodOpts RouteOpts
defaultOpts

-- | `mkYesod` but with custom options.
--
-- @since 1.6.25.0
mkYesodOpts :: RouteOpts
            -> String
            -> [ResourceTree String]
            -> Q [Dec]
mkYesodOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodOpts RouteOpts
opts String
name = (([Dec], [Dec]) -> [Dec]) -> Q ([Dec], [Dec]) -> Q [Dec]
forall a b. (a -> b) -> Q a -> Q b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (([Dec] -> [Dec] -> [Dec]) -> ([Dec], [Dec]) -> [Dec]
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry [Dec] -> [Dec] -> [Dec]
forall a. [a] -> [a] -> [a]
(++)) (Q ([Dec], [Dec]) -> Q [Dec])
-> ([ResourceTree String] -> Q ([Dec], [Dec]))
-> [ResourceTree String]
-> Q [Dec]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RouteOpts
-> String
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodWithParserOpts RouteOpts
opts String
name Bool
False Exp -> Q Exp
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return


{-# DEPRECATED mkYesodWith "Contexts and type variables are now parsed from the name in `mkYesod`. <https://github.com/yesodweb/yesod/pull/1366>" #-}
-- | Similar to 'mkYesod', except contexts and type variables are not parsed.
-- Instead, they are explicitly provided.
-- You can write @(MyClass a) => App a@ with @mkYesodWith [[\"MyClass\",\"a\"]] \"App\" [\"a\"] ...@.
mkYesodWith :: [[String]] -- ^ list of contexts
            -> String -- ^ name of the argument datatype
            -> [String] -- ^ list of type variables
            -> [ResourceTree String]
            -> Q [Dec]
mkYesodWith :: [[String]]
-> String -> [String] -> [ResourceTree String] -> Q [Dec]
mkYesodWith [[String]]
cxts String
name [String]
args = (([Dec], [Dec]) -> [Dec]) -> Q ([Dec], [Dec]) -> Q [Dec]
forall a b. (a -> b) -> Q a -> Q b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (([Dec] -> [Dec] -> [Dec]) -> ([Dec], [Dec]) -> [Dec]
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry [Dec] -> [Dec] -> [Dec]
forall a. [a] -> [a] -> [a]
(++)) (Q ([Dec], [Dec]) -> Q [Dec])
-> ([ResourceTree String] -> Q ([Dec], [Dec]))
-> [ResourceTree String]
-> Q [Dec]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [[String]]
-> String
-> [String]
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodGeneral [[String]]
cxts String
name [String]
args Bool
False Exp -> Q Exp
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return


-- | Sometimes, you will want to declare your routes in one file and define
-- your handlers elsewhere. For example, this is the only way to break up a
-- monolithic file into smaller parts. Use this function, paired with
-- 'mkYesodDispatch', to do just that.
mkYesodData :: String -> [ResourceTree String] -> Q [Dec]
mkYesodData :: String -> [ResourceTree String] -> Q [Dec]
mkYesodData = RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodDataOpts RouteOpts
defaultOpts

-- | `mkYesodData` but with custom options.
--
-- @since 1.6.25.0
mkYesodDataOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodDataOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodDataOpts RouteOpts
opts String
name [ResourceTree String]
resS = ([Dec], [Dec]) -> [Dec]
forall a b. (a, b) -> a
fst (([Dec], [Dec]) -> [Dec]) -> Q ([Dec], [Dec]) -> Q [Dec]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> RouteOpts
-> String
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodWithParserOpts RouteOpts
opts String
name Bool
False Exp -> Q Exp
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return [ResourceTree String]
resS


mkYesodSubData :: String -> [ResourceTree String] -> Q [Dec]
mkYesodSubData :: String -> [ResourceTree String] -> Q [Dec]
mkYesodSubData = RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodSubDataOpts RouteOpts
defaultOpts

-- |
--
-- @since 1.6.25.0
mkYesodSubDataOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodSubDataOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodSubDataOpts RouteOpts
opts String
name [ResourceTree String]
resS = ([Dec], [Dec]) -> [Dec]
forall a b. (a, b) -> a
fst (([Dec], [Dec]) -> [Dec]) -> Q ([Dec], [Dec]) -> Q [Dec]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> RouteOpts
-> String
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodWithParserOpts RouteOpts
opts String
name Bool
True Exp -> Q Exp
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return [ResourceTree String]
resS


-- | Run 'parseYesodName' in 'Q', failing the splice with the parse error
-- instead of returning an 'Either'. Shared by the @mkYesod@ and
-- @mkYesodSubDispatch@ entry points.
parseYesodNameQ :: String -> Q (String, [String], [[String]])
parseYesodNameQ :: String -> Q (String, [String], [[String]])
parseYesodNameQ String
name =
    case String -> Either String (String, [String], [[String]])
parseYesodName String
name of
        Left String
err -> String -> Q (String, [String], [[String]])
forall a. HasCallStack => String -> Q a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
String -> m a
fail String
err
        Right (String, [String], [[String]])
a  -> (String, [String], [[String]]) -> Q (String, [String], [[String]])
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (String, [String], [[String]])
a

-- | Parses contexts and type arguments out of name before generating TH.
mkYesodWithParser :: String                    -- ^ foundation type
                  -> Bool                      -- ^ is this a subsite
                  -> (Exp -> Q Exp)            -- ^ unwrap handler
                  -> [ResourceTree String]
                  -> Q([Dec],[Dec])
mkYesodWithParser :: String
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodWithParser = RouteOpts
-> String
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodWithParserOpts RouteOpts
defaultOpts

-- | Parses contexts and type arguments out of name before generating TH.
--
-- @since 1.6.25.0
mkYesodWithParserOpts :: RouteOpts                 -- ^ Additional route options
                      -> String                    -- ^ foundation type
                      -> Bool                      -- ^ is this a subsite
                      -> (Exp -> Q Exp)            -- ^ unwrap handler
                      -> [ResourceTree String]
                      -> Q([Dec],[Dec])
mkYesodWithParserOpts :: RouteOpts
-> String
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodWithParserOpts RouteOpts
opts String
name Bool
isSub Exp -> Q Exp
f [ResourceTree String]
resS = do
    (name', rest, cxt) <- String -> Q (String, [String], [[String]])
parseYesodNameQ String
name

    mkYesodGeneralOpts opts cxt name' rest isSub f resS


-- | See 'mkYesodData'.
mkYesodDispatch :: String -> [ResourceTree String] -> Q [Dec]
mkYesodDispatch :: String -> [ResourceTree String] -> Q [Dec]
mkYesodDispatch = RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodDispatchOpts RouteOpts
defaultOpts

-- | See 'mkYesodDataOpts'
--
-- @since 1.6.25.0
mkYesodDispatchOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodDispatchOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodDispatchOpts RouteOpts
opts String
name = (([Dec], [Dec]) -> [Dec]) -> Q ([Dec], [Dec]) -> Q [Dec]
forall a b. (a -> b) -> Q a -> Q b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ([Dec], [Dec]) -> [Dec]
forall a b. (a, b) -> b
snd (Q ([Dec], [Dec]) -> Q [Dec])
-> ([ResourceTree String] -> Q ([Dec], [Dec]))
-> [ResourceTree String]
-> Q [Dec]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RouteOpts
-> String
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodWithParserOpts RouteOpts
opts String
name Bool
False Exp -> Q Exp
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return


-- | Build an instance context ('Cxt') from the parsed @=>@ class-application
-- groups produced by 'parseYesodName'. Each group is a class name applied to
-- type arguments, e.g. @["MyClass","a"]@ becomes @MyClass a@. Shared by
-- 'mkYesodGeneralOpts' and 'mkYesodSubDispatchInstanceOpts'.
buildAppCxt :: [[String]] -> Q Cxt
buildAppCxt :: [[String]] -> Q Cxt
buildAppCxt = ([String] -> Q Pred) -> [[String]] -> Q Cxt
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (([String] -> Q Pred) -> [[String]] -> Q Cxt)
-> ([String] -> Q Pred) -> [[String]] -> Q Cxt
forall a b. (a -> b) -> a -> b
$ \[String]
ctxs ->
    case [String]
ctxs of
        String
c:[String]
rest ->
            Pred -> Q Pred
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Pred -> Q Pred) -> Pred -> Q Pred
forall a b. (a -> b) -> a -> b
$ (Pred -> String -> Pred) -> Pred -> [String] -> Pred
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (\Pred
acc String
v -> Pred
acc Pred -> Pred -> Pred
`AppT` (Pred, Name) -> Pred
forall a b. (a, b) -> a
fst (String -> (Pred, Name)
nameToType String
v)) (Name -> Pred
ConT (Name -> Pred) -> Name -> Pred
forall a b. (a -> b) -> a -> b
$ String -> Name
mkName String
c) [String]
rest
        [] -> String -> Q Pred
forall a. HasCallStack => String -> Q a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
String -> m a
fail (String -> Q Pred) -> String -> Q Pred
forall a b. (a -> b) -> a -> b
$ String
"mkYesod: empty type-class context in route definition: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ [String] -> String
forall a. Show a => a -> String
show [String]
ctxs

-- | Get the Handler and Widget type synonyms for the given site.
masterTypeSyns :: [Name] -> Type -> [Dec] -- FIXME remove from here, put into the scaffolding itself?
masterTypeSyns :: [Name] -> Pred -> [Dec]
masterTypeSyns [Name]
vs Pred
site =
    [ Name -> [TyVarBndr BndrVis] -> Pred -> Dec
TySynD (String -> Name
mkName String
"Handler") ((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
forall flag. DefaultBndrFlag flag => Name -> TyVarBndr flag
plainTV [Name]
vs)
      (Pred -> Dec) -> Pred -> Dec
forall a b. (a -> b) -> a -> b
$ Name -> Pred
ConT ''HandlerFor Pred -> Pred -> Pred
`AppT` Pred
site
    , Name -> [TyVarBndr BndrVis] -> Pred -> Dec
TySynD (String -> Name
mkName String
"Widget")  ((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
forall flag. DefaultBndrFlag flag => Name -> TyVarBndr flag
plainTV [Name]
vs)
      (Pred -> Dec) -> Pred -> Dec
forall a b. (a -> b) -> a -> b
$ Name -> Pred
ConT ''WidgetFor Pred -> Pred -> Pred
`AppT` Pred
site Pred -> Pred -> Pred
`AppT` Name -> Pred
ConT ''()
    ]


mkYesodGeneral :: [[String]]                -- ^ Appliction context. Used in RenderRoute, RouteAttrs, and ParseRoute instances.
               -> String                    -- ^ foundation type
               -> [String]                  -- ^ arguments for the type
               -> Bool                      -- ^ is this a subsite
               -> (Exp -> Q Exp)            -- ^ unwrap handler
               -> [ResourceTree String]
               -> Q([Dec],[Dec])
mkYesodGeneral :: [[String]]
-> String
-> [String]
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodGeneral = RouteOpts
-> [[String]]
-> String
-> [String]
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodGeneralOpts RouteOpts
defaultOpts

-- | Convert the parsed-from-source 'String' route types into real 'Type's at a
-- splice site. A malformed type or an unclosed @#{…}@ bracket surfaces as an
-- attributed compile error (via 'fail') rather than a raw 'error' thrown lazily
-- when the resulting tree is forced. This is the single 'String'-to-'Type'
-- boundary: callers downstream only ever handle @['ResourceTree' 'Type']@.
parseResourceTypes :: [ResourceTree String] -> Q [ResourceTree Type]
parseResourceTypes :: [ResourceTree String] -> Q [ResourceTree Pred]
parseResourceTypes = (ResourceTree String -> Q (ResourceTree Pred))
-> [ResourceTree String] -> Q [ResourceTree Pred]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ((String -> Q Pred) -> ResourceTree String -> Q (ResourceTree Pred)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> ResourceTree a -> f (ResourceTree b)
traverse (\String
s -> String -> Q String
forall (m :: * -> *). MonadFail m => String -> m String
dropBracketM String
s Q String -> (String -> Q Pred) -> Q Pred
forall a b. Q a -> (a -> Q b) -> Q b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= String -> Q Pred
forall (m :: * -> *). MonadFail m => String -> m Pred
parseTypeM))

-- | Generate a @YesodSubDispatchNested@ instance for a nested route within a
-- subsite, for hand-written split-route modules (see the subsite-splitting
-- recipe in @docs/split-route-compilation.md@).
--
-- Takes the resources as @['ResourceTree' 'String']@ — exactly the form the
-- @parseRoutes@ quasi-quoter produces — and parses them to 'Type' internally
-- via 'parseResourceTypes', so the caller never touches the partial
-- 'parseType'\/'dropBracket'. A malformed type fails the splice with an
-- attributed error instead.
--
-- @since 1.7.0.0
mkNestedSubDispatchInstance
    :: RouteOpts
    -> String                -- ^ target nested route name
    -> Cxt                   -- ^ instance context
    -> TyArgs                -- ^ type arguments
    -> (Exp -> Q Exp)        -- ^ unwrapper
    -> [ResourceTree String] -- ^ all resources (as parsed from source)
    -> Q [Dec]
mkNestedSubDispatchInstance :: RouteOpts
-> String
-> Cxt
-> TyArgs
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q [Dec]
mkNestedSubDispatchInstance RouteOpts
routeOpts String
target Cxt
cxt TyArgs
tyargs Exp -> Q Exp
unwrapper [ResourceTree String]
resS = do
    res <- [ResourceTree String] -> Q [ResourceTree Pred]
parseResourceTypes [ResourceTree String]
resS
    -- Guard the top target's arity here. 'mkNestedDispatchInstanceWith' only
    -- arity-checks nested *children*, so without this a hand-written recipe
    -- pairing a parameterized subsite with an unparameterized target datatype
    -- would apply the subsite's type args to a kind-'Type' head and surface a
    -- cryptic kind error from generated code rather than this actionable one.
    -- A no-op when the datatype is not in scope (unknowable arity) or when the
    -- arities match.
    rc <- resolveRouteCon target
    assertNestedSubArity SubsiteCall (SubsiteName target)
        (SubsiteArity (tyArgsArity tyargs)) rc
    mkNestedDispatchInstanceWith SubsiteNested Nothing
        routeOpts target cxt tyargs unwrapper res

-- | The resolved foundation type shared by 'mkYesodGeneralOpts' and
-- 'mkYesodSubDispatchInstanceOpts': the @boundNames@ from the explicitly-written
-- type args plus enough fresh @t@ variables to fill the reified arity, the fully
-- applied @site@ type, and the parsed resources. The callers differ only in how
-- they roll these into 'TyArgs' (and the synonym-head vars), so that part stays
-- with each caller.
data ResolvedFoundation = ResolvedFoundation
    { ResolvedFoundation -> [(Pred, Name)]
rfBoundNames :: [(Type, Name)]  -- ^ explicitly-written type args
    , ResolvedFoundation -> [Name]
rfFillVars   :: [Name]          -- ^ fresh vars filling the reified arity
    , ResolvedFoundation -> Pred
rfSite       :: Type            -- ^ the fully applied site type
    , ResolvedFoundation -> [ResourceTree Pred]
rfResources  :: [ResourceTree Type]
    }

resolveFoundation :: String -> [String] -> [ResourceTree String] -> Q ResolvedFoundation
resolveFoundation :: String -> [String] -> [ResourceTree String] -> Q ResolvedFoundation
resolveFoundation String
namestr [String]
mtys [ResourceTree String]
resS = do
    mname <- String -> Q (Maybe Name)
lookupTypeName String
namestr
    arity <- maybe (pure 0) typeArity mname
    let name = String -> Name
mkName String
namestr
    -- Generate as many variable names as the arity indicates
    vns <- replicateM (arity - length mtys) $ newName "t"
    let boundNames = (String -> (Pred, Name)) -> [String] -> [(Pred, Name)]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> (Pred, Name)
nameToType [String]
mtys
        argtypes = ((Pred, Name) -> Pred) -> [(Pred, Name)] -> Cxt
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Pred, Name) -> Pred
forall a b. (a, b) -> a
fst [(Pred, Name)]
boundNames Cxt -> Cxt -> Cxt
forall a. [a] -> [a] -> [a]
++ (Name -> Pred) -> [Name] -> Cxt
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Name -> Pred
VarT [Name]
vns
        site = (Pred -> Pred -> Pred) -> Pred -> Cxt -> Pred
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Pred -> Pred -> Pred
AppT (Name -> Pred
ConT Name
name) Cxt
argtypes
    res <- parseResourceTypes resS
    pure ResolvedFoundation
        { rfBoundNames = boundNames
        , rfFillVars = vns
        , rfSite = site
        , rfResources = res
        }

-- |
--
-- @since 1.6.25.0
mkYesodGeneralOpts :: RouteOpts                 -- ^ Options to adjust route creation
                   -> [[String]]                -- ^ Application context. Used in RenderRoute, RouteAttrs, and ParseRoute instances.
                   -> String                    -- ^ foundation type
                   -> [String]                  -- ^ arguments for the type
                   -> Bool                      -- ^ is this a subsite
                   -> (Exp -> Q Exp)            -- ^ unwrap handler
                   -> [ResourceTree String]
                   -> Q([Dec],[Dec])
mkYesodGeneralOpts :: RouteOpts
-> [[String]]
-> String
-> [String]
-> Bool
-> (Exp -> Q Exp)
-> [ResourceTree String]
-> Q ([Dec], [Dec])
mkYesodGeneralOpts RouteOpts
opts [[String]]
appCxt' String
namestr [String]
mtys Bool
isSub Exp -> Q Exp
f [ResourceTree String]
resS = do
    appCxt <- [[String]] -> Q Cxt
buildAppCxt [[String]]
appCxt'
    foundation <- resolveFoundation namestr mtys resS
    -- The explicitly-written args plus the fresh vars filling the reified
    -- arity. Both are part of the site's full application ('rfSite'), so both
    -- must travel in the 'TyArgs' handed to 'discoveryMode' and the generators
    -- — otherwise a parameterized foundation invoked without explicit type args
    -- would be misclassified as monomorphic and emit ill-scoped nested
    -- instances.
    let fillNames = (Name -> (Pred, Name)) -> [Name] -> [(Pred, Name)]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\Name
v -> (Name -> Pred
VarT Name
v, Name
v)) (ResolvedFoundation -> [Name]
rfFillVars ResolvedFoundation
foundation)
        tyArgs = [(Pred, Name)] -> TyArgs
toTyArgs (ResolvedFoundation -> [(Pred, Name)]
rfBoundNames ResolvedFoundation
foundation [(Pred, Name)] -> [(Pred, Name)] -> [(Pred, Name)]
forall a. [a] -> [a] -> [a]
++ [(Pred, Name)]
fillNames)
    -- typevars that should appear in synonym head
    let argvars = ((String -> Name) -> [String] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> Name
mkName ([String] -> [Name])
-> ([String] -> [String]) -> [String] -> [Name]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter String -> Bool
isTvar) [String]
mtys [Name] -> [Name] -> [Name]
forall a. [a] -> [a] -> [a]
++ ResolvedFoundation -> [Name]
rfFillVars ResolvedFoundation
foundation
    renderRouteDec <-
        mkRenderRouteInstanceOpts opts appCxt tyArgs (rfSite foundation) (rfResources foundation)
    routeAttrsDec  <-
        case roFocusOnNestedRoute opts of
            Maybe String
Nothing -> do
                -- The flat 'RouteAttrs (Route site)' instance, plus — in
                -- nested-discovery mode — a 'RouteAttrsNested' instance for each
                -- child fragment, mirroring the RenderRouteNested /
                -- ParseRouteNested / YesodDispatchNested instances generated for
                -- the same children. Without this, 'routeAttrsNested ChildR'
                -- would fail to resolve for a single-module 'mkYesod' site even
                -- though the other nested-delegation methods resolve.
                flatAttrs <- Cxt -> Pred -> [ResourceTree Pred] -> Q Dec
forall a. Cxt -> Pred -> [ResourceTree a] -> Q Dec
mkRouteAttrsInstance Cxt
appCxt (ResolvedFoundation -> Pred
rfSite ResolvedFoundation
foundation) (ResolvedFoundation -> [ResourceTree Pred]
rfResources ResolvedFoundation
foundation)
                nestedAttrs <-
                    case discoveryMode opts tyArgs of
                        DiscoveryMode
NestedDiscovery ->
                            Cxt -> TyArgs -> [ResourceTree Pred] -> Q [Dec]
forall a. Cxt -> TyArgs -> [ResourceTree a] -> Q [Dec]
mkRouteAttrsNestedInstances Cxt
appCxt TyArgs
tyArgs (ResolvedFoundation -> [ResourceTree Pred]
rfResources ResolvedFoundation
foundation)
                        DiscoveryMode
InlineCompat    -> [Dec] -> Q [Dec]
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
                pure (flatAttrs : nestedAttrs)
            Just String
target ->
                -- Apply the site's type arguments to the focused child's
                -- constructor, matching the focused ParseRoute / RenderRoute
                -- paths; a bare 'ConT' here is a kind error for a
                -- parameterized site.
                Cxt -> Pred -> String -> [ResourceTree Pred] -> Q [Dec]
forall a. Cxt -> Pred -> String -> [ResourceTree a] -> Q [Dec]
mkRouteAttrsInstanceFor
                    Cxt
appCxt
                    (Pred -> TyArgs -> Pred
applyTyArgs (Name -> Pred
ConT (String -> Name
mkName String
target)) TyArgs
tyArgs)
                    String
target
                    (ResolvedFoundation -> [ResourceTree Pred]
rfResources ResolvedFoundation
foundation)

    dispatchDec <-
        mkDispatchInstance opts (rfSite foundation) appCxt tyArgs f (rfResources foundation)
    parseRouteDec <-
        mkParseRouteInstanceOpts opts tyArgs appCxt (rfSite foundation) (rfResources foundation)
    let rname = String -> Name
mkName (String -> Name) -> String -> Name
forall a b. (a -> b) -> a -> b
$ String
"resources" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
namestr
    resourcesDec <-
        if shouldCreateResources opts
            then do
                eres <- lift resS
                pure
                    [ SigD rname $ ListT `AppT` (ConT ''ResourceTree `AppT` ConT ''String)
                    , FunD rname [Clause [] (NormalB eres) []]
                    ]
            else do
                pure []
    let dataDec = [[Dec]] -> [Dec]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat
            [ [Dec]
parseRouteDec
            , [Dec]
renderRouteDec
            , [Dec]
routeAttrsDec
            , if Maybe String -> Bool
forall a. Maybe a -> Bool
isJust (RouteOpts -> Maybe String
roFocusOnNestedRoute RouteOpts
opts) then [] else [Dec]
resourcesDec
            , if Bool
isSub Bool -> Bool -> Bool
|| Maybe String -> Bool
forall a. Maybe a -> Bool
isJust (RouteOpts -> Maybe String
roFocusOnNestedRoute RouteOpts
opts)
                then []
                else [Name] -> Pred -> [Dec]
masterTypeSyns [Name]
argvars (ResolvedFoundation -> Pred
rfSite ResolvedFoundation
foundation)
            ]
    return (dataDec, dispatchDec)

-- | Generate both 'YesodSubDispatch' and 'YesodSubDispatchNested' instances
-- for a parameterized subsite. This is the subsite equivalent of using
-- @mkYesod@ for top-level sites.
--
-- Usage:
--
-- @
-- mkYesodSubDispatchInstance "(MyClass a) => MySub a" resourcesMySub
-- @
--
-- This generates:
--
-- 1. A 'YesodSubDispatch' instance using 'mkYesodSubDispatch'
-- 2. 'YesodSubDispatchNested' instances for any nested route fragments
--
-- The generated instances quantify over the @master@ site and constrain it
-- only through the subsite's own class. For a parameterized subsite this
-- normally means the subsite's class carries a @subsite -> master@ functional
-- dependency (so @master@ is determined) and the using module enables
-- @UndecidableInstances@ (the instance contexts mention type-family
-- applications and non-variable arguments), along with @FlexibleContexts@,
-- @FlexibleInstances@, @MultiParamTypeClasses@ and @TypeFamilies@. The nested
-- route datatype must also declare exactly as many type parameters as the
-- subsite has type arguments (see the arity note below).
--
-- @since 1.7.0.0
mkYesodSubDispatchInstance
    :: String                -- ^ Foundation type with optional context, e.g. @"(MyClass a) => MySub a"@
    -> [ResourceTree String] -- ^ Resources (e.g. @resourcesMySub@)
    -> Q [Dec]
mkYesodSubDispatchInstance :: String -> [ResourceTree String] -> Q [Dec]
mkYesodSubDispatchInstance = RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodSubDispatchInstanceOpts RouteOpts
defaultOpts

-- | Like 'mkYesodSubDispatchInstance', but takes a 'RouteOpts' so a subsite can
-- control nested-route generation — most usefully 'setNestedRouteFallthrough'
-- (which 'mkYesodSubDispatchInstance' leaves at its default of 'False'). The
-- flag is threaded into both the @yesodSubDispatch@ body (so the subsite's own
-- top-level parent clauses fall through to later siblings on an inner miss) and
-- the generated @YesodSubDispatchNested@ fragment instances.
--
-- @since 1.7.0.0
mkYesodSubDispatchInstanceOpts
    :: RouteOpts
    -> String                -- ^ Foundation type with optional context, e.g. @"(MyClass a) => MySub a"@
    -> [ResourceTree String] -- ^ Resources (e.g. @resourcesMySub@)
    -> Q [Dec]
mkYesodSubDispatchInstanceOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec]
mkYesodSubDispatchInstanceOpts RouteOpts
opts String
nameStr [ResourceTree String]
resS = do
    -- Parse the name string to extract context, type name, and type args
    -- (the same parser the top-level mkYesod entry points use).
    (namestr, mtys, appCxt') <- String -> Q (String, [String], [[String]])
parseYesodNameQ String
nameStr

    appCxt <- buildAppCxt appCxt'

    foundation <- resolveFoundation namestr mtys resS
    -- The explicitly-written args plus the fresh vars filling the reified
    -- arity. Both are part of the subsite's full application ('rfSite'), so both
    -- must travel in the 'TyArgs' handed to 'discoveryMode' and the generators
    -- — otherwise a parameterized subsite invoked without explicit type args
    -- (e.g. @mkYesodSubDispatchInstance "MySub"@ for @MySub a@) would be
    -- misclassified as monomorphic and emit ill-scoped nested instances. This
    -- mirrors the 'fillNames' fix in 'mkYesodGeneralOpts'.
    let fillNames = (Name -> (Pred, Name)) -> [Name] -> [(Pred, Name)]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\Name
v -> (Name -> Pred
VarT Name
v, Name
v)) (ResolvedFoundation -> [Name]
rfFillVars ResolvedFoundation
foundation)
        tyArgs = [(Pred, Name)] -> TyArgs
toTyArgs (ResolvedFoundation -> [(Pred, Name)]
rfBoundNames ResolvedFoundation
foundation [(Pred, Name)] -> [(Pred, Name)] -> [(Pred, Name)]
forall a. [a] -> [a] -> [a]
++ [(Pred, Name)]
fillNames)

    -- Generate the YesodSubDispatch instance
    masterN <- newName "master"
    let masterT = Name -> Pred
VarT Name
masterN
        -- Thread the opts (in particular 'roNestedRouteFallthrough') into the
        -- generated @yesodSubDispatch@ body so a subsite's own top-level parent
        -- clauses honor 'setNestedRouteFallthrough', matching the top-level
        -- 'mkTopLevelDispatchInstance' path. 'GeneratesNestedInstances': this
        -- entry point emits a 'YesodSubDispatchNested' instance per parent in
        -- this same splice (below), so the flat @yesodSubDispatch@ body
        -- delegates each parent to that instance instead of inlining the
        -- subtree dispatch (which the nested instance would re-emit), avoiding
        -- the doubled codegen. This mirrors 'mkTopLevelDispatchInstance' on the
        -- top-level path. Standalone 'mkYesodSubDispatch'/'mkYesodSubDispatchWith'
        -- stay at 'NoSameSpliceNestedInstances'.
        subDispatchExp =
            SameSpliceNestedInstances
-> RouteOpts -> [ResourceTree Pred] -> Q Exp
forall a.
SameSpliceNestedInstances -> RouteOpts -> [ResourceTree a] -> Q Exp
mkYesodSubDispatchWithDelegate
                SameSpliceNestedInstances
GeneratesNestedInstances
                RouteOpts
opts
                (ResolvedFoundation -> [ResourceTree Pred]
rfResources ResolvedFoundation
foundation)
    subDispatchBody <- subDispatchExp
    let yesodSubDispatchInst = Cxt -> Pred -> [Dec] -> Dec
instanceD
            Cxt
appCxt
            (Name -> Pred
ConT ''YesodSubDispatch Pred -> Pred -> Pred
`AppT` ResolvedFoundation -> Pred
rfSite ResolvedFoundation
foundation Pred -> Pred -> Pred
`AppT` Pred
masterT)
            [ Name -> [Clause] -> Dec
FunD 'yesodSubDispatch
                [ [Pat] -> Body -> [Dec] -> Clause
Clause [] (Exp -> Body
NormalB Exp
subDispatchBody) [] ]
            ]

    -- The top-level nested parents, each of which gets a
    -- YesodSubDispatchNested instance generated below.
    let nestedNames = [ String
n | ResourceParent String
n Bool
_ Set String
_ [Piece Pred]
_ [ResourceTree Pred]
_ <- ResolvedFoundation -> [ResourceTree Pred]
rfResources ResolvedFoundation
foundation ]

    nestedInstances <- fmap mconcat $ forM nestedNames $ \String
nestedName -> do
        -- Resolve the nested datatype once and reuse it for both the
        -- "instance already exists?" probe and the arity check below.
        -- 'nestedInstanceExists' saturates by the datatype's own reified arity,
        -- so it can't throw a kind error on an arity-mismatched in-scope
        -- datatype — which is exactly the misuse the 'checkNestedSubArity'
        -- below diagnoses. That keeps the friendly arity check reachable
        -- instead of being preempted by a cryptic kind error from the probe.
        rc <- String -> Q RouteCon
resolveRouteCon String
nestedName
        instanceExists <- nestedInstanceExists ''YesodSubDispatchNested rc
        if instanceExists
            then pure []
            else do
                -- This API targets parameterized subsites whose nested subroute
                -- datatypes carry the parent's type arguments (the subsite's
                -- 'tyArgs' are applied to the nested datatype directly below).
                -- Guard the misuse where the
                -- subsite is parameterized but the nested datatype is not:
                -- otherwise applying the subsite's type args to a kind-'Type'
                -- datatype produces a cryptic kind error from generated code.
                -- Only check when the datatype actually resolved — an
                -- unresolved name has no knowable arity (defaulting it to 0
                -- would wrongly report "0 type parameter(s)"), and downstream
                -- codegen reports the not-in-scope case on its own.
                assertNestedSubArity
                    SubsiteCall
                    (SubsiteName namestr)
                    (SubsiteArity (tyArgsArity tyArgs))
                    rc
                -- Call the worker directly with the foundation's
                -- already-parsed 'Type' resources, rather than re-parsing the
                -- 'String' resources through the public 'mkNestedSubDispatchInstance'.
                -- The generator applies 'tyArgs' to the nested datatype directly
                -- and never consults 'roParameterizedSubroute' (it only reads
                -- 'roNestedRouteFallthrough'), so passing 'opts' through
                -- unchanged is correct — forcing 'setParameterizedSubroute' here
                -- was a no-op.
                mkNestedDispatchInstanceWith SubsiteNested Nothing
                    opts
                    nestedName appCxt tyArgs return (rfResources foundation)

    return $ yesodSubDispatchInst : nestedInstances