never executed always true always false
1 {-# LANGUAGE DeriveGeneric, DeriveDataTypeable, DeriveFunctor, DeriveTraversable, DeriveFoldable #-}
2
3 module Conjure.Language.Expression.Op.Flatten where
4
5 import Conjure.Prelude
6 import Conjure.Language.Expression.Op.Internal.Common
7
8 import qualified Data.Aeson as JSON -- aeson
9 import qualified Data.Aeson.KeyMap as KM
10
11 import qualified Data.Vector as V -- vector
12
13
14 data OpFlatten x = OpFlatten (Maybe Int) x
15 deriving (Eq, Ord, Show, Data, Functor, Traversable, Foldable, Typeable, Generic)
16
17 instance Serialize x => Serialize (OpFlatten x)
18 instance Hashable x => Hashable (OpFlatten x)
19 instance ToJSON x => ToJSON (OpFlatten x) where toJSON = genericToJSON jsonOptions
20 instance FromJSON x => FromJSON (OpFlatten x) where parseJSON = genericParseJSON jsonOptions
21
22 instance (TypeOf x, Pretty x) => TypeOf (OpFlatten x) where
23 typeOf p@(OpFlatten Nothing m) = do
24 let flattenType (TypeList inner) = flattenType inner
25 flattenType (TypeMatrix _ inner) = flattenType inner
26 flattenType ty = ty
27 ty <- typeOf m
28 case ty of
29 TypeList n -> return (TypeList (flattenType n))
30 TypeMatrix _ n -> return (TypeList (flattenType n))
31 _ -> raiseTypeError $ vcat [ pretty p
32 , "The argument has type:" <+> pretty ty
33 ]
34 typeOf p@(OpFlatten (Just n) m) = do
35 let flattenType lvl ty | lvl < 0 = return ty
36 flattenType lvl (TypeList inner) = flattenType (lvl-1) inner
37 flattenType lvl (TypeMatrix _ inner) = flattenType (lvl-1) inner
38 flattenType _ _ = raiseTypeError $ vcat [pretty p, "Cannot flatten" <+> pretty n <+> "levels."]
39 ty <- typeOf m
40 TypeList <$> flattenType n ty
41
42 instance SimplifyOp OpFlatten x where
43 simplifyOp _ = na "simplifyOp{OpFlatten}"
44
45 instance Pretty x => Pretty (OpFlatten x) where
46 prettyPrec _ (OpFlatten Nothing m) = "flatten" <> prParens (pretty m)
47 prettyPrec _ (OpFlatten (Just n) m) = "flatten" <> prettyList prParens "," [pretty n, pretty m]
48
49 instance VarSymBreakingDescription x => VarSymBreakingDescription (OpFlatten x) where
50 varSymBreakingDescription (OpFlatten n m) = JSON.Object $ KM.fromList
51 [ ("type", JSON.String "OpFlatten")
52 , ("children", JSON.Array $ V.fromList
53 [ toJSON n
54 , varSymBreakingDescription m
55 ])
56 ]