1{-# LANGUAGE CPP #-}
2{-# LANGUAGE EmptyDataDecls #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE FunctionalDependencies #-}
6{-# LANGUAGE KindSignatures #-}
7{-# LANGUAGE MultiParamTypeClasses #-}
8{-# LANGUAGE PatternGuards #-}
9{-# LANGUAGE Rank2Types #-}
10{-# LANGUAGE ScopedTypeVariables #-}
11#if __GLASGOW_HASKELL__ >= 706
12{-# LANGUAGE DataKinds #-}
13{-# LANGUAGE PolyKinds #-}
14{-# LANGUAGE TypeOperators #-}
15#define USE_TYPE_LITS 1
16#endif
17#ifdef MIN_VERSION_template_haskell
18# if __GLASGOW_HASKELL__ >= 800
19-- TH-subset that works with stage1 & unregisterised GHCs
20{-# LANGUAGE TemplateHaskellQuotes #-}
21# else
22{-# LANGUAGE TemplateHaskell #-}
23# endif
24#endif
25
26{-# LANGUAGE TypeFamilies #-}
27{-# LANGUAGE DeriveDataTypeable #-}
28{-# LANGUAGE UndecidableInstances #-}
29
30{-# OPTIONS_GHC -fno-cse #-}
31{-# OPTIONS_GHC -fno-full-laziness #-}
32{-# OPTIONS_GHC -fno-float-in #-}
33{-# OPTIONS_GHC -fno-warn-orphans #-}
34{-# OPTIONS_GHC -fno-warn-unused-binds #-}
35
36#ifndef MIN_VERSION_base
37#define MIN_VERSION_base(x,y,z) 1
38#endif
39
40----------------------------------------------------------------------------
41-- |
42-- Module     : Data.Reflection
43-- Copyright  : 2009-2015 Edward Kmett,
44--              2012 Elliott Hird,
45--              2004 Oleg Kiselyov and Chung-chieh Shan
46-- License    : BSD3
47--
48-- Maintainer  : Edward Kmett <ekmett@gmail.com>
49-- Stability   : experimental
50-- Portability : non-portable
51--
52-- Reifies arbitrary terms at the type level. Based on the Functional
53-- Pearl: Implicit Configurations paper by Oleg Kiselyov and
54-- Chung-chieh Shan.
55--
56-- <http://okmij.org/ftp/Haskell/tr-15-04.pdf>
57--
58-- The approach from the paper was modified to work with Data.Proxy
59-- and to cheat by using knowledge of GHC's internal representations
60-- by Edward Kmett and Elliott Hird.
61--
62-- Usage comes down to two combinators, 'reify' and 'reflect'.
63--
64-- >>> reify 6 (\p -> reflect p + reflect p)
65-- 12
66--
67-- The argument passed along by reify is just a @data 'Proxy' t =
68-- Proxy@, so all of the information needed to reconstruct your value
69-- has been moved to the type level.  This enables it to be used when
70-- constructing instances (see @examples/Monoid.hs@).
71--
72-- In addition, a simpler API is offered for working with singleton
73-- values such as a system configuration, etc.
74-------------------------------------------------------------------------------
75module Data.Reflection
76    (
77    -- * Reflection
78      Reifies(..)
79    , reify
80#if __GLASGOW_HASKELL__ >= 708
81    , reifyNat
82    , reifySymbol
83#endif
84    , reifyTypeable
85    -- * Given
86    , Given(..)
87    , give
88#ifdef MIN_VERSION_template_haskell
89    -- * Template Haskell reflection
90    , int, nat
91#endif
92    -- * Useful compile time naturals
93    , Z, D, SD, PD
94
95    -- * Reified Monoids
96    , ReifiedMonoid(..)
97    , ReflectedMonoid(..)
98    , reifyMonoid
99    , foldMapBy
100    , foldBy
101
102    -- * Reified Applicatives
103    , ReifiedApplicative(..)
104    , ReflectedApplicative(..)
105    , reifyApplicative
106    , traverseBy
107    , sequenceBy
108    ) where
109
110import Control.Applicative
111
112#ifdef MIN_VERSION_template_haskell
113import Control.Monad
114#endif
115
116import Data.Bits
117
118#if __GLASGOW_HASKELL__ < 710
119import Data.Foldable
120#endif
121
122import Data.Semigroup as Sem
123import Data.Proxy
124
125#if __GLASGOW_HASKELL__ < 710
126import Data.Traversable
127#endif
128
129import Data.Typeable
130import Data.Word
131import Foreign.Ptr
132import Foreign.StablePtr
133
134#if (__GLASGOW_HASKELL__ >= 707) || (defined(MIN_VERSION_template_haskell) && USE_TYPE_LITS)
135import GHC.TypeLits
136# if MIN_VERSION_base(4,10,0)
137import Numeric.Natural (Natural)
138# elif __GLASGOW_HASKELL__ >= 707
139import Control.Exception (ArithException(..), throw)
140# endif
141#endif
142
143#ifdef __HUGS__
144import Hugs.IOExts
145#endif
146
147#ifdef MIN_VERSION_template_haskell
148import Language.Haskell.TH hiding (reify)
149#endif
150
151import System.IO.Unsafe
152
153#ifndef __HUGS__
154import Unsafe.Coerce
155#endif
156
157#ifdef HLINT
158{-# ANN module "HLint: ignore Avoid lambda" #-}
159#endif
160
161------------------------------------------------------------------------------
162-- Reifies
163------------------------------------------------------------------------------
164
165class Reifies s a | s -> a where
166  -- | Recover a value inside a 'reify' context, given a proxy for its
167  -- reified type.
168  reflect :: proxy s -> a
169
170newtype Magic a r = Magic (forall (s :: *). Reifies s a => Proxy s -> r)
171
172-- | Reify a value at the type level, to be recovered with 'reflect'.
173reify :: forall a r. a -> (forall (s :: *). Reifies s a => Proxy s -> r) -> r
174reify a k = unsafeCoerce (Magic k :: Magic a r) (const a) Proxy
175{-# INLINE reify #-}
176
177#if __GLASGOW_HASKELL__ >= 707
178instance KnownNat n => Reifies n Integer where
179  reflect = natVal
180
181instance KnownSymbol n => Reifies n String where
182  reflect = symbolVal
183#endif
184
185#if __GLASGOW_HASKELL__ >= 708
186
187--------------------------------------------------------------------------------
188-- KnownNat
189--------------------------------------------------------------------------------
190
191newtype MagicNat r = MagicNat (forall (n :: Nat). KnownNat n => Proxy n -> r)
192
193-- | This upgraded version of 'reify' can be used to generate a 'KnownNat' suitable for use with other APIs.
194--
195-- Attemping to pass a negative 'Integer' as an argument will result in an
196-- 'Underflow' exception.
197--
198-- /Available only on GHC 7.8+/
199--
200-- >>> reifyNat 4 natVal
201-- 4
202--
203-- >>> reifyNat 4 reflect
204-- 4
205
206reifyNat :: forall r. Integer -> (forall (n :: Nat). KnownNat n => Proxy n -> r) -> r
207reifyNat n k = unsafeCoerce (MagicNat k :: MagicNat r)
208# if MIN_VERSION_base(4,10,0)
209                             -- Starting with base-4.10, the internal
210                             -- representation of KnownNat changed from Integer
211                             -- to Natural, so make sure to perform the same
212                             -- conversion before unsafeCoercing.
213                             (fromInteger n :: Natural)
214# else
215                             (if n < 0 then throw Underflow else n)
216# endif
217                             Proxy
218
219--------------------------------------------------------------------------------
220-- KnownSymbol
221--------------------------------------------------------------------------------
222
223newtype MagicSymbol r = MagicSymbol (forall (n :: Symbol). KnownSymbol n => Proxy n -> r)
224
225-- | This upgraded version of 'reify' can be used to generate a 'KnownSymbol' suitable for use with other APIs.
226--
227-- /Available only on GHC 7.8+/
228--
229-- >>> reifySymbol "hello" symbolVal
230-- "hello"
231--
232-- >>> reifySymbol "hello" reflect
233-- "hello"
234reifySymbol :: forall r. String -> (forall (n :: Symbol). KnownSymbol n => Proxy n -> r) -> r
235reifySymbol n k = unsafeCoerce (MagicSymbol k :: MagicSymbol r) n Proxy
236
237#endif
238
239------------------------------------------------------------------------------
240-- Given
241------------------------------------------------------------------------------
242
243-- | This is a version of 'Reifies' that allows for only a single value.
244--
245-- This is easier to work with than 'Reifies' and permits extended defaulting,
246-- but it only offers a single reflected value of a given type at a time.
247class Given a where
248  -- | Recover the value of a given type previously encoded with 'give'.
249  given :: a
250
251newtype Gift a r = Gift (Given a => r)
252
253-- | Reify a value into an instance to be recovered with 'given'.
254--
255-- You should /only/ 'give' a single value for each type. If multiple instances
256-- are in scope, then the behavior is implementation defined.
257give :: forall a r. a -> (Given a => r) -> r
258give a k = unsafeCoerce (Gift k :: Gift a r) a
259{-# INLINE give #-}
260
261--------------------------------------------------------------------------------
262-- Explicit Numeric Reflection
263--------------------------------------------------------------------------------
264
265-- | 0
266data Z
267-- | 2/n/
268data D  (n :: *)
269-- | 2/n/ + 1
270data SD (n :: *)
271-- | 2/n/ - 1
272data PD (n :: *)
273
274instance Reifies Z Int where
275  reflect _ = 0
276  {-# INLINE reflect #-}
277
278retagD :: (Proxy n -> a) -> proxy (D n) -> a
279retagD f _ = f Proxy
280{-# INLINE retagD #-}
281
282retagSD :: (Proxy n -> a) -> proxy (SD n) -> a
283retagSD f _ = f Proxy
284{-# INLINE retagSD #-}
285
286retagPD :: (Proxy n -> a) -> proxy (PD n) -> a
287retagPD f _ = f Proxy
288{-# INLINE retagPD #-}
289
290instance Reifies n Int => Reifies (D n) Int where
291  reflect = (\n -> n + n) `fmap` retagD reflect
292  {-# INLINE reflect #-}
293
294instance Reifies n Int => Reifies (SD n) Int where
295  reflect = (\n -> n + n + 1) `fmap` retagSD reflect
296  {-# INLINE reflect #-}
297
298instance Reifies n Int => Reifies (PD n) Int where
299  reflect = (\n -> n + n - 1) `fmap` retagPD reflect
300  {-# INLINE reflect #-}
301
302#ifdef MIN_VERSION_template_haskell
303-- | This can be used to generate a template haskell splice for a type level version of a given 'int'.
304--
305-- This does not use GHC TypeLits, instead it generates a numeric type by hand similar to the ones used
306-- in the \"Functional Pearl: Implicit Configurations\" paper by Oleg Kiselyov and Chung-Chieh Shan.
307--
308-- @instance Num (Q Exp)@ provided in this package allows writing @$(3)@
309-- instead of @$(int 3)@. Sometimes the two will produce the same
310-- representation (if compiled without the @-DUSE_TYPE_LITS@ preprocessor
311-- directive).
312int :: Int -> TypeQ
313int n = case quotRem n 2 of
314  (0, 0) -> conT ''Z
315  (q,-1) -> conT ''PD `appT` int q
316  (q, 0) -> conT ''D  `appT` int q
317  (q, 1) -> conT ''SD `appT` int q
318  _     -> error "ghc is bad at math"
319
320-- | This is a restricted version of 'int' that can only generate natural numbers. Attempting to generate
321-- a negative number results in a compile time error. Also the resulting sequence will consist entirely of
322-- Z, D, and SD constructors representing the number in zeroless binary.
323nat :: Int -> TypeQ
324nat n
325  | n >= 0 = int n
326  | otherwise = error "nat: negative"
327
328#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 704
329instance Show (Q a) where
330  show _ = "Q"
331instance Eq (Q a) where
332  _ == _ = False
333#endif
334instance Num a => Num (Q a) where
335  (+) = liftM2 (+)
336  (*) = liftM2 (*)
337  (-) = liftM2 (-)
338  negate = fmap negate
339  abs = fmap abs
340  signum = fmap signum
341  fromInteger = return . fromInteger
342
343instance Fractional a => Fractional (Q a) where
344  (/) = liftM2 (/)
345  recip = fmap recip
346  fromRational = return . fromRational
347
348-- | This permits the use of $(5) as a type splice.
349instance Num Type where
350#ifdef USE_TYPE_LITS
351  LitT (NumTyLit a) + LitT (NumTyLit b) = LitT (NumTyLit (a+b))
352  a + b = AppT (AppT (VarT ''(+)) a) b
353
354  LitT (NumTyLit a) * LitT (NumTyLit b) = LitT (NumTyLit (a*b))
355  (*) a b = AppT (AppT (VarT ''(GHC.TypeLits.*)) a) b
356#if MIN_VERSION_base(4,8,0)
357  a - b = AppT (AppT (VarT ''(-)) a) b
358#else
359  (-) = error "Type.(-): undefined"
360#endif
361  fromInteger = LitT . NumTyLit
362#else
363  (+) = error "Type.(+): undefined"
364  (*) = error "Type.(*): undefined"
365  (-) = error "Type.(-): undefined"
366  fromInteger n = case quotRem n 2 of
367      (0, 0) -> ConT ''Z
368      (q,-1) -> ConT ''PD `AppT` fromInteger q
369      (q, 0) -> ConT ''D  `AppT` fromInteger q
370      (q, 1) -> ConT ''SD `AppT` fromInteger q
371      _ -> error "ghc is bad at math"
372#endif
373  abs = error "Type.abs"
374  signum = error "Type.signum"
375
376onProxyType1 :: (Type -> Type) -> (Exp -> Exp)
377onProxyType1 f
378    (SigE _ ta@(AppT (ConT proxyName)  (VarT _)))
379    | proxyName == ''Proxy = ConE 'Proxy `SigE` (ConT ''Proxy `AppT` f ta)
380onProxyType1 f a =
381        LamE [SigP WildP na] body `AppE` a
382    where
383          body = ConE 'Proxy `SigE` (ConT ''Proxy `AppT` f na)
384          na = VarT (mkName "na")
385
386onProxyType2 :: Name -> (Type -> Type -> Type) -> (Exp -> Exp -> Exp)
387onProxyType2 _fName f
388    (SigE _ (AppT (ConT proxyName)  ta))
389    (SigE _ (AppT (ConT proxyName') tb))
390    | proxyName == ''Proxy,
391      proxyName' == ''Proxy = ConE 'Proxy `SigE`
392                                        (ConT ''Proxy `AppT` f ta tb)
393-- the above case should only match for things like $(2 + 2)
394onProxyType2 fName _f a b = VarE fName `AppE` a `AppE` b
395
396-- | This permits the use of $(5) as an expression splice,
397-- which stands for @Proxy :: Proxy $(5)@
398instance Num Exp where
399  (+) = onProxyType2 'addProxy (+)
400  (*) = onProxyType2 'mulProxy (*)
401  (-) = onProxyType2 'subProxy (-)
402  negate = onProxyType1 negate
403  abs = onProxyType1 abs
404  signum = onProxyType1 signum
405  fromInteger n = ConE 'Proxy `SigE` (ConT ''Proxy `AppT` fromInteger n)
406
407#ifdef USE_TYPE_LITS
408addProxy :: Proxy a -> Proxy b -> Proxy (a + b)
409addProxy _ _ = Proxy
410mulProxy :: Proxy a -> Proxy b -> Proxy (a * b)
411mulProxy _ _ = Proxy
412#if MIN_VERSION_base(4,8,0)
413subProxy :: Proxy a -> Proxy b -> Proxy (a - b)
414subProxy _ _ = Proxy
415#else
416subProxy :: Proxy a -> Proxy b -> Proxy c
417subProxy _ _ = error "Exp.(-): undefined"
418#endif
419--  fromInteger = LitT . NumTyLit
420#else
421addProxy :: Proxy a -> Proxy b -> Proxy c
422addProxy _ _ = error "Exp.(+): undefined"
423mulProxy :: Proxy a -> Proxy b -> Proxy c
424mulProxy _ _ = error "Exp.(*): undefined"
425subProxy :: Proxy a -> Proxy b -> Proxy c
426subProxy _ _ = error "Exp.(-): undefined"
427#endif
428
429#endif
430
431--------------------------------------------------------------------------------
432-- * Typeable Reflection
433--------------------------------------------------------------------------------
434
435
436class Typeable s => B s where
437  reflectByte :: proxy s -> IntPtr
438
439#define BYTES(GO) \
440  GO(T0,0) GO(T1,1) GO(T2,2) GO(T3,3) GO(T4,4) GO(T5,5) GO(T6,6) GO(T7,7) GO(T8,8) GO(T9,9) GO(T10,10) GO(T11,11) \
441  GO(T12,12) GO(T13,13) GO(T14,14) GO(T15,15) GO(T16,16) GO(T17,17) GO(T18,18) GO(T19,19) GO(T20,20) GO(T21,21) GO(T22,22) \
442  GO(T23,23) GO(T24,24) GO(T25,25) GO(T26,26) GO(T27,27) GO(T28,28) GO(T29,29) GO(T30,30) GO(T31,31) GO(T32,32) GO(T33,33) \
443  GO(T34,34) GO(T35,35) GO(T36,36) GO(T37,37) GO(T38,38) GO(T39,39) GO(T40,40) GO(T41,41) GO(T42,42) GO(T43,43) GO(T44,44) \
444  GO(T45,45) GO(T46,46) GO(T47,47) GO(T48,48) GO(T49,49) GO(T50,50) GO(T51,51) GO(T52,52) GO(T53,53) GO(T54,54) GO(T55,55) \
445  GO(T56,56) GO(T57,57) GO(T58,58) GO(T59,59) GO(T60,60) GO(T61,61) GO(T62,62) GO(T63,63) GO(T64,64) GO(T65,65) GO(T66,66) \
446  GO(T67,67) GO(T68,68) GO(T69,69) GO(T70,70) GO(T71,71) GO(T72,72) GO(T73,73) GO(T74,74) GO(T75,75) GO(T76,76) GO(T77,77) \
447  GO(T78,78) GO(T79,79) GO(T80,80) GO(T81,81) GO(T82,82) GO(T83,83) GO(T84,84) GO(T85,85) GO(T86,86) GO(T87,87) GO(T88,88) \
448  GO(T89,89) GO(T90,90) GO(T91,91) GO(T92,92) GO(T93,93) GO(T94,94) GO(T95,95) GO(T96,96) GO(T97,97) GO(T98,98) GO(T99,99) \
449  GO(T100,100) GO(T101,101) GO(T102,102) GO(T103,103) GO(T104,104) GO(T105,105) GO(T106,106) GO(T107,107) GO(T108,108) \
450  GO(T109,109) GO(T110,110) GO(T111,111) GO(T112,112) GO(T113,113) GO(T114,114) GO(T115,115) GO(T116,116) GO(T117,117) \
451  GO(T118,118) GO(T119,119) GO(T120,120) GO(T121,121) GO(T122,122) GO(T123,123) GO(T124,124) GO(T125,125) GO(T126,126) \
452  GO(T127,127) GO(T128,128) GO(T129,129) GO(T130,130) GO(T131,131) GO(T132,132) GO(T133,133) GO(T134,134) GO(T135,135) \
453  GO(T136,136) GO(T137,137) GO(T138,138) GO(T139,139) GO(T140,140) GO(T141,141) GO(T142,142) GO(T143,143) GO(T144,144) \
454  GO(T145,145) GO(T146,146) GO(T147,147) GO(T148,148) GO(T149,149) GO(T150,150) GO(T151,151) GO(T152,152) GO(T153,153) \
455  GO(T154,154) GO(T155,155) GO(T156,156) GO(T157,157) GO(T158,158) GO(T159,159) GO(T160,160) GO(T161,161) GO(T162,162) \
456  GO(T163,163) GO(T164,164) GO(T165,165) GO(T166,166) GO(T167,167) GO(T168,168) GO(T169,169) GO(T170,170) GO(T171,171) \
457  GO(T172,172) GO(T173,173) GO(T174,174) GO(T175,175) GO(T176,176) GO(T177,177) GO(T178,178) GO(T179,179) GO(T180,180) \
458  GO(T181,181) GO(T182,182) GO(T183,183) GO(T184,184) GO(T185,185) GO(T186,186) GO(T187,187) GO(T188,188) GO(T189,189) \
459  GO(T190,190) GO(T191,191) GO(T192,192) GO(T193,193) GO(T194,194) GO(T195,195) GO(T196,196) GO(T197,197) GO(T198,198) \
460  GO(T199,199) GO(T200,200) GO(T201,201) GO(T202,202) GO(T203,203) GO(T204,204) GO(T205,205) GO(T206,206) GO(T207,207) \
461  GO(T208,208) GO(T209,209) GO(T210,210) GO(T211,211) GO(T212,212) GO(T213,213) GO(T214,214) GO(T215,215) GO(T216,216) \
462  GO(T217,217) GO(T218,218) GO(T219,219) GO(T220,220) GO(T221,221) GO(T222,222) GO(T223,223) GO(T224,224) GO(T225,225) \
463  GO(T226,226) GO(T227,227) GO(T228,228) GO(T229,229) GO(T230,230) GO(T231,231) GO(T232,232) GO(T233,233) GO(T234,234) \
464  GO(T235,235) GO(T236,236) GO(T237,237) GO(T238,238) GO(T239,239) GO(T240,240) GO(T241,241) GO(T242,242) GO(T243,243) \
465  GO(T244,244) GO(T245,245) GO(T246,246) GO(T247,247) GO(T248,248) GO(T249,249) GO(T250,250) GO(T251,251) GO(T252,252) \
466  GO(T253,253) GO(T254,254) GO(T255,255)
467
468#define GO(Tn,n) \
469  newtype Tn = Tn Tn deriving Typeable; \
470  instance B Tn where { \
471    reflectByte _ = n \
472  };
473BYTES(GO)
474#undef GO
475
476impossible :: a
477impossible = error "Data.Reflection.reifyByte: impossible"
478
479reifyByte :: Word8 -> (forall (s :: *). B s => Proxy s -> r) -> r
480reifyByte w k = case w of {
481#define GO(Tn,n) n -> k (Proxy :: Proxy Tn);
482BYTES(GO)
483#undef GO
484_ -> impossible
485}
486
487newtype W (b0 :: *) (b1 :: *) (b2 :: *) (b3 :: *) = W (W b0 b1 b2 b3) deriving Typeable
488newtype Stable (w0 :: *) (w1 :: *) (a :: *) = Stable (Stable w0 w1 a) deriving Typeable
489
490stable :: p b0 -> p b1 -> p b2 -> p b3 -> p b4 -> p b5 -> p b6 -> p b7
491       -> Proxy (Stable (W b0 b1 b2 b3) (W b4 b5 b6 b7) a)
492stable _ _ _ _ _ _ _ _ = Proxy
493{-# INLINE stable #-}
494
495stablePtrToIntPtr :: StablePtr a -> IntPtr
496stablePtrToIntPtr = ptrToIntPtr . castStablePtrToPtr
497{-# INLINE stablePtrToIntPtr #-}
498
499intPtrToStablePtr :: IntPtr -> StablePtr a
500intPtrToStablePtr = castPtrToStablePtr . intPtrToPtr
501{-# INLINE intPtrToStablePtr #-}
502
503byte0 :: p (Stable (W b0 b1 b2 b3) w1 a) -> Proxy b0
504byte0 _ = Proxy
505
506byte1 :: p (Stable (W b0 b1 b2 b3) w1 a) -> Proxy b1
507byte1 _ = Proxy
508
509byte2 :: p (Stable (W b0 b1 b2 b3) w1 a) -> Proxy b2
510byte2 _ = Proxy
511
512byte3 :: p (Stable (W b0 b1 b2 b3) w1 a) -> Proxy b3
513byte3 _ = Proxy
514
515byte4 :: p (Stable w0 (W b4 b5 b6 b7) a) -> Proxy b4
516byte4 _ = Proxy
517
518byte5 :: p (Stable w0 (W b4 b5 b6 b7) a) -> Proxy b5
519byte5 _ = Proxy
520
521byte6 :: p (Stable w0 (W b4 b5 b6 b7) a) -> Proxy b6
522byte6 _ = Proxy
523
524byte7 :: p (Stable w0 (W b4 b5 b6 b7) a) -> Proxy b7
525byte7 _ = Proxy
526
527argument :: (p s -> r) -> Proxy s
528argument _ = Proxy
529
530instance (B b0, B b1, B b2, B b3, B b4, B b5, B b6, B b7, w0 ~ W b0 b1 b2 b3, w1 ~ W b4 b5 b6 b7)
531    => Reifies (Stable w0 w1 a) a where
532  reflect = r where
533      r = unsafePerformIO $ const <$> deRefStablePtr p <* freeStablePtr p
534      s = argument r
535      p = intPtrToStablePtr $
536        reflectByte (byte0 s) .|.
537        (reflectByte (byte1 s) `shiftL` 8) .|.
538        (reflectByte (byte2 s) `shiftL` 16) .|.
539        (reflectByte (byte3 s) `shiftL` 24) .|.
540        (reflectByte (byte4 s) `shiftL` 32) .|.
541        (reflectByte (byte5 s) `shiftL` 40) .|.
542        (reflectByte (byte6 s) `shiftL` 48) .|.
543        (reflectByte (byte7 s) `shiftL` 56)
544  {-# NOINLINE reflect #-}
545
546-- This had to be moved to the top level, due to an apparent bug in
547-- the ghc inliner introduced in ghc 7.0.x
548reflectBefore :: forall (proxy :: * -> *) s b. (Proxy s -> b) -> proxy s -> b
549reflectBefore f = const $! f Proxy
550{-# NOINLINE reflectBefore #-}
551
552-- | Reify a value at the type level in a 'Typeable'-compatible fashion, to be recovered with 'reflect'.
553--
554-- This can be necessary to work around the changes to @Data.Typeable@ in GHC HEAD.
555reifyTypeable :: Typeable a => a -> (forall (s :: *). (Typeable s, Reifies s a) => Proxy s -> r) -> r
556#if MIN_VERSION_base(4,4,0)
557reifyTypeable a k = unsafeDupablePerformIO $ do
558#else
559reifyTypeable a k = unsafePerformIO $ do
560#endif
561  p <- newStablePtr a
562  let n = stablePtrToIntPtr p
563  reifyByte (fromIntegral n) (\s0 ->
564    reifyByte (fromIntegral (n `shiftR` 8)) (\s1 ->
565      reifyByte (fromIntegral (n `shiftR` 16)) (\s2 ->
566        reifyByte (fromIntegral (n `shiftR` 24)) (\s3 ->
567          reifyByte (fromIntegral (n `shiftR` 32)) (\s4 ->
568            reifyByte (fromIntegral (n `shiftR` 40)) (\s5 ->
569              reifyByte (fromIntegral (n `shiftR` 48)) (\s6 ->
570                reifyByte (fromIntegral (n `shiftR` 56)) (\s7 ->
571                  reflectBefore (fmap return k) $
572                    stable s0 s1 s2 s3 s4 s5 s6 s7))))))))
573
574
575data ReifiedMonoid a = ReifiedMonoid { reifiedMappend :: a -> a -> a, reifiedMempty :: a }
576
577instance Reifies s (ReifiedMonoid a) => Sem.Semigroup (ReflectedMonoid a s) where
578  ReflectedMonoid x <> ReflectedMonoid y = reflectResult (\m -> ReflectedMonoid (reifiedMappend m x y))
579
580instance Reifies s (ReifiedMonoid a) => Monoid (ReflectedMonoid a s) where
581#if !(MIN_VERSION_base(4,11,0))
582  mappend = (<>)
583#endif
584  mempty = reflectResult (\m -> ReflectedMonoid (reifiedMempty  m    ))
585
586reflectResult :: forall f s a. Reifies s a => (a -> f s) -> f s
587reflectResult f = f (reflect (Proxy :: Proxy s))
588
589newtype ReflectedMonoid a s = ReflectedMonoid a
590
591unreflectedMonoid :: ReflectedMonoid a s -> proxy s -> a
592unreflectedMonoid (ReflectedMonoid a) _ = a
593
594reifyMonoid :: (a -> a -> a) -> a -> (forall (s :: *). Reifies s (ReifiedMonoid a) => t -> ReflectedMonoid a s) -> t -> a
595reifyMonoid f z m xs = reify (ReifiedMonoid f z) (unreflectedMonoid (m xs))
596
597-- | Fold a value using its 'Foldable' instance using
598-- explicitly provided 'Monoid' operations. This is like 'fold'
599-- where the 'Monoid' instance can be manually specified.
600--
601-- @
602-- 'foldBy' 'mappend' 'mempty' ≡ 'fold'
603-- @
604--
605-- >>> foldBy (++) [] ["hello","world"]
606-- "helloworld"
607foldBy :: Foldable t => (a -> a -> a) -> a -> t a -> a
608foldBy f z = reifyMonoid f z (foldMap ReflectedMonoid)
609
610-- | Fold a value using its 'Foldable' instance using
611-- explicitly provided 'Monoid' operations. This is like 'foldMap'
612-- where the 'Monoid' instance can be manually specified.
613--
614-- @
615-- 'foldMapBy' 'mappend' 'mempty' ≡ 'foldMap'
616-- @
617--
618-- >>> foldMapBy (+) 0 length ["hello","world"]
619-- 10
620foldMapBy :: Foldable t => (r -> r -> r) -> r -> (a -> r) -> t a -> r
621foldMapBy f z g = reifyMonoid f z (foldMap (ReflectedMonoid #. g))
622
623data ReifiedApplicative f = ReifiedApplicative { reifiedPure :: forall a. a -> f a, reifiedAp :: forall a b. f (a -> b) -> f a -> f b }
624
625newtype ReflectedApplicative f s a = ReflectedApplicative (f a)
626
627instance Reifies s (ReifiedApplicative f) => Functor (ReflectedApplicative f s) where
628  fmap = liftA
629
630instance Reifies s (ReifiedApplicative f) => Applicative (ReflectedApplicative f s) where
631  pure a = reflectResult1 (\m -> ReflectedApplicative (reifiedPure m a))
632  ReflectedApplicative x <*> ReflectedApplicative y = reflectResult1 (\m -> ReflectedApplicative (reifiedAp m x y))
633
634reflectResult1 :: forall f s a b. Reifies s a => (a -> f s b) -> f s b
635reflectResult1 f = f (reflect (Proxy :: Proxy s))
636
637unreflectedApplicative :: ReflectedApplicative f s a -> proxy s -> f a
638unreflectedApplicative (ReflectedApplicative a) _ = a
639
640reifyApplicative :: (forall x. x -> f x) -> (forall x y. f (x -> y) -> f x -> f y) -> (forall (s :: *). Reifies s (ReifiedApplicative f) => t -> ReflectedApplicative f s a) -> t -> f a
641reifyApplicative f g m xs = reify (ReifiedApplicative f g) (unreflectedApplicative (m xs))
642
643-- | Traverse a container using its 'Traversable' instance using
644-- explicitly provided 'Applicative' operations. This is like 'traverse'
645-- where the 'Applicative' instance can be manually specified.
646traverseBy :: Traversable t => (forall x. x -> f x) -> (forall x y. f (x -> y) -> f x -> f y) -> (a -> f b) -> t a -> f (t b)
647traverseBy pur app f = reifyApplicative pur app (traverse (ReflectedApplicative #. f))
648
649-- | Sequence a container using its 'Traversable' instance using
650-- explicitly provided 'Applicative' operations. This is like 'sequence'
651-- where the 'Applicative' instance can be manually specified.
652sequenceBy :: Traversable t => (forall x. x -> f x) -> (forall x y. f (x -> y) -> f x -> f y) -> t (f a) -> f (t a)
653sequenceBy pur app = reifyApplicative pur app (traverse ReflectedApplicative)
654
655(#.) :: (b -> c) -> (a -> b) -> a -> c
656(#.) _ = unsafeCoerce
657