{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}

module Yesod.Routes.TH.RouteAttrs
    ( mkRouteAttrsInstance
    , mkRouteAttrsInstanceFor
    , mkRouteAttrsNestedInstances
    ) where

import Yesod.Routes.TH.Types
import Yesod.Routes.TH.Internal (nestedInstanceExists, resolveRouteCon, instanceD, conPCompat, findNestedRoute)
import Yesod.Routes.Class
import Language.Haskell.TH.Syntax
import Data.Foldable (toList)
import qualified Data.Set  as Set
import qualified Data.Text as Text
import Control.Monad

mkRouteAttrsInstance :: Cxt -> Type -> [ResourceTree a] -> Q Dec
mkRouteAttrsInstance :: forall a. Cxt -> Type -> [ResourceTree a] -> Q Dec
mkRouteAttrsInstance Cxt
cxt Type
typ [ResourceTree a]
ress = do
    clauses <- (ResourceTree a -> Q [Clause]) -> [ResourceTree a] -> Q [[Clause]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (Maybe String -> (Pat -> Pat) -> ResourceTree a -> Q [Clause]
forall a.
Maybe String -> (Pat -> Pat) -> ResourceTree a -> Q [Clause]
goTree Maybe String
forall a. Maybe a
Nothing Pat -> Pat
forall a. a -> a
id) [ResourceTree a]
ress
    return $ instanceD cxt (ConT ''RouteAttrs `AppT` typ)
        [ FunD 'routeAttrs $ concat clauses ++
                [Clause [ WildP ] (NormalB $ VarE 'mempty) []]
        ]

-- | Like 'mkRouteAttrsInstance', but uses a 'String' name of a nested
-- subroute to generate nested instances instead of generating the full
-- instance for all routes.
--
-- @since 1.7.0.0
mkRouteAttrsInstanceFor :: Cxt -> Type -> String -> [ResourceTree a] -> Q [Dec]
mkRouteAttrsInstanceFor :: forall a. Cxt -> Type -> String -> [ResourceTree a] -> Q [Dec]
mkRouteAttrsInstanceFor Cxt
cxt Type
typ String
target [ResourceTree a]
ress = do
    -- Fail loudly (matching Dispatch/RenderRoute/ParseRoute) when the focus
    -- target is missing, rather than silently emitting an always-'mempty'
    -- 'RouteAttrsNested' instance.
    case String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
forall a.
String -> [ResourceTree a] -> Maybe ([Piece a], [ResourceTree a])
findNestedRoute String
target [ResourceTree a]
ress of
        Maybe ([Piece a], [ResourceTree a])
Nothing ->
            String -> Q ()
forall a. HasCallStack => String -> Q a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
String -> m a
fail (String -> Q ()) -> String -> Q ()
forall a b. (a -> b) -> a -> b
$ String
"Target '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
target String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"' was not found in resources."
        Just ([Piece a], [ResourceTree a])
_ ->
            () -> Q ()
forall a. a -> Q a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    clauses <- (ResourceTree a -> Q [Clause]) -> [ResourceTree a] -> Q [[Clause]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (Maybe String -> (Pat -> Pat) -> ResourceTree a -> Q [Clause]
forall a.
Maybe String -> (Pat -> Pat) -> ResourceTree a -> Q [Clause]
goTree (String -> Maybe String
forall a. a -> Maybe a
Just String
target) Pat -> Pat
forall a. a -> a
id) [ResourceTree a]
ress
    return [instanceD cxt (ConT ''RouteAttrsNested `AppT` typ)
        [ FunD 'routeAttrsNested $ concat clauses ++
                [Clause [ WildP ] (NormalB $ VarE 'mempty) []]
        ]
        ]

-- | Generate a 'RouteAttrsNested' instance for every nested parent route in
-- the tree (recursively), skipping any whose instance already exists (e.g. one
-- generated in another module when routes are split). This is the
-- 'RouteAttrs' counterpart to the @RenderRouteNested@ \/ @ParseRouteNested@ \/
-- @YesodDispatchNested@ instances that a plain 'mkYesod' already emits for its
-- child route fragments, so that @routeAttrsNested ChildR@ resolves for a
-- single-module site just like the other nested-delegation methods do.
--
-- @since 1.7.0.0
mkRouteAttrsNestedInstances :: Cxt -> TyArgs -> [ResourceTree a] -> Q [Dec]
mkRouteAttrsNestedInstances :: forall a. Cxt -> TyArgs -> [ResourceTree a] -> Q [Dec]
mkRouteAttrsNestedInstances Cxt
cxt TyArgs
tyargs [ResourceTree a]
ress =
    [[Dec]] -> [Dec]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[Dec]] -> [Dec]) -> Q [[Dec]] -> Q [Dec]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (String -> Q [Dec]) -> [String] -> 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 String -> Q [Dec]
perParent ([ResourceTree a] -> [String]
forall {typ}. [ResourceTree typ] -> [String]
parentNames [ResourceTree a]
ress)
  where
    parentNames :: [ResourceTree typ] -> [String]
parentNames [ResourceTree typ]
trees = [[String]] -> [String]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat
        [ String
name String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [ResourceTree typ] -> [String]
parentNames [ResourceTree typ]
children
        | ResourceParent String
name CheckOverlap
_ Set String
_ [Piece typ]
_ [ResourceTree typ]
children <- [ResourceTree typ]
trees
        ]
    perParent :: String -> Q [Dec]
perParent String
name = do
        exists <- Name -> RouteCon -> Q CheckOverlap
nestedInstanceExists ''RouteAttrsNested (RouteCon -> Q CheckOverlap) -> Q RouteCon -> Q CheckOverlap
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< String -> Q RouteCon
resolveRouteCon String
name
        if exists
            then pure []
            else mkRouteAttrsInstanceFor cxt (applyTyArgs (ConT (mkName name)) tyargs) name ress

goTree :: Maybe String -> (Pat -> Pat) -> ResourceTree a -> Q [Clause]
goTree :: forall a.
Maybe String -> (Pat -> Pat) -> ResourceTree a -> Q [Clause]
goTree Maybe String
mtarget Pat -> Pat
front (ResourceLeaf Resource a
res) =
    case Maybe String
mtarget of
        Maybe String
Nothing ->
            [Clause] -> Q [Clause]
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Clause] -> Q [Clause]) -> [Clause] -> Q [Clause]
forall a b. (a -> b) -> a -> b
$ Maybe Clause -> [Clause]
forall a. Maybe a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (Maybe Clause -> [Clause]) -> Maybe Clause -> [Clause]
forall a b. (a -> b) -> a -> b
$ (Pat -> Pat) -> Resource a -> Maybe Clause
forall a. (Pat -> Pat) -> Resource a -> Maybe Clause
goRes Pat -> Pat
front Resource a
res
        Just String
_ ->
            [Clause] -> Q [Clause]
forall a. a -> Q a
forall (m :: * -> *) a. Monad m => a -> m a
return []
goTree (Just String
target) Pat -> Pat
front (ResourceParent String
name CheckOverlap
_check Set String
_attrs [Piece a]
_pieces [ResourceTree a]
trees)
    | String
target String -> String -> CheckOverlap
forall a. Eq a => a -> a -> CheckOverlap
/= String
name = [[Clause]] -> [Clause]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[Clause]] -> [Clause]) -> Q [[Clause]] -> Q [Clause]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ResourceTree a -> Q [Clause]) -> [ResourceTree a] -> Q [[Clause]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (Maybe String -> (Pat -> Pat) -> ResourceTree a -> Q [Clause]
forall a.
Maybe String -> (Pat -> Pat) -> ResourceTree a -> Q [Clause]
goTree (String -> Maybe String
forall a. a -> Maybe a
Just String
target) Pat -> Pat
front) [ResourceTree a]
trees
goTree Maybe String
mtarget Pat -> Pat
front (ResourceParent String
name CheckOverlap
_check Set String
_attrs [Piece a]
pieces [ResourceTree a]
trees) = do
    doesNestedInstanceExist <- Name -> RouteCon -> Q CheckOverlap
nestedInstanceExists ''RouteAttrsNested (RouteCon -> Q CheckOverlap) -> Q RouteCon -> Q CheckOverlap
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< String -> Q RouteCon
resolveRouteCon String
name

    if doesNestedInstanceExist
        then do
            x <- newName "x"
            pure [Clause [front (conPCompat (mkName name) (ignored (VarP x)))] (NormalB $ VarE 'routeAttrsNested `AppE` VarE x) []]
        else do
            -- We only reach this clause when @mtarget@ is 'Nothing' (full
            -- instance) or @Just name@ (we found the focus target); clause 2
            -- above peeled off the non-matching @Just other@ case. Either way
            -- the remaining subtree is generated unfocused (@Nothing@). The
            -- focus target itself is the route boundary, so its own
            -- constructor is not prepended (@front@); ordinary parents in the
            -- full instance do prepend theirs (@front'@).
            let front'' =
                    if String -> Maybe String
forall a. a -> Maybe a
Just String
name Maybe String -> Maybe String -> CheckOverlap
forall a. Eq a => a -> a -> CheckOverlap
== Maybe String
mtarget
                        then Pat -> Pat
front
                        else Pat -> Pat
front'
            concat <$> mapM (goTree Nothing front'') trees
  where
    ignored :: Pat -> [Pat]
ignored = (Int -> Pat -> [Pat]
forall a. Int -> a -> [a]
replicate Int
toIgnore Pat
WildP [Pat] -> [Pat] -> [Pat]
forall a. [a] -> [a] -> [a]
++) ([Pat] -> [Pat]) -> (Pat -> [Pat]) -> Pat -> [Pat]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Pat -> [Pat]
forall a. a -> [a]
forall (m :: * -> *) a. Monad m => a -> m a
return
    toIgnore :: Int
toIgnore = [Piece a] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([Piece a] -> Int) -> [Piece a] -> Int
forall a b. (a -> b) -> a -> b
$ (Piece a -> CheckOverlap) -> [Piece a] -> [Piece a]
forall a. (a -> CheckOverlap) -> [a] -> [a]
filter Piece a -> CheckOverlap
forall {typ}. Piece typ -> CheckOverlap
isDynamic [Piece a]
pieces
    isDynamic :: Piece typ -> CheckOverlap
isDynamic Dynamic{} = CheckOverlap
True
    isDynamic Static{} = CheckOverlap
False
    front' :: Pat -> Pat
front' = Pat -> Pat
front (Pat -> Pat) -> (Pat -> Pat) -> Pat -> Pat
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Name -> [Pat] -> Pat
conPCompat (String -> Name
mkName String
name)
                   ([Pat] -> Pat) -> (Pat -> [Pat]) -> Pat -> Pat
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Pat -> [Pat]
ignored

goRes :: (Pat -> Pat) -> Resource a -> Maybe Clause
goRes :: forall a. (Pat -> Pat) -> Resource a -> Maybe Clause
goRes Pat -> Pat
front Resource {CheckOverlap
String
[String]
[Piece a]
Dispatch a
resourceName :: String
resourcePieces :: [Piece a]
resourceDispatch :: Dispatch a
resourceAttrs :: [String]
resourceCheck :: CheckOverlap
resourceCheck :: forall typ. Resource typ -> CheckOverlap
resourceAttrs :: forall typ. Resource typ -> [String]
resourceDispatch :: forall typ. Resource typ -> Dispatch typ
resourcePieces :: forall typ. Resource typ -> [Piece typ]
resourceName :: forall typ. Resource typ -> String
..} = do
    CheckOverlap -> Maybe ()
forall (f :: * -> *). Alternative f => CheckOverlap -> f ()
guard (CheckOverlap -> CheckOverlap
not ([String] -> CheckOverlap
forall a. [a] -> CheckOverlap
forall (t :: * -> *) a. Foldable t => t a -> CheckOverlap
null [String]
resourceAttrs))
    Clause -> Maybe Clause
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return (Clause -> Maybe Clause) -> Clause -> Maybe Clause
forall a b. (a -> b) -> a -> b
$ [Pat] -> Body -> [Dec] -> Clause
Clause
        [Pat -> Pat
front (Pat -> Pat) -> Pat -> Pat
forall a b. (a -> b) -> a -> b
$ Name -> [FieldPat] -> Pat
RecP (String -> Name
mkName String
resourceName) []]
        (Exp -> Body
NormalB (Exp -> Body) -> Exp -> Body
forall a b. (a -> b) -> a -> b
$ Name -> Exp
VarE 'Set.fromList Exp -> Exp -> Exp
`AppE` [Exp] -> Exp
ListE ((String -> Exp) -> [String] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map String -> Exp
toText [String]
resourceAttrs))
        []
  where
    toText :: String -> Exp
toText String
s = Name -> Exp
VarE 'Text.pack Exp -> Exp -> Exp
`AppE` Lit -> Exp
LitE (String -> Lit
StringL String
s)