Generics.hs 46.3 KB
Newer Older
1
{-# LANGUAGE CPP                    #-}
2
{-# LANGUAGE DataKinds              #-}
3
{-# LANGUAGE DeriveFunctor          #-}
4
{-# LANGUAGE DeriveGeneric          #-}
5 6 7
{-# LANGUAGE FlexibleContexts       #-}
{-# LANGUAGE FlexibleInstances      #-}
{-# LANGUAGE GADTs                  #-}
8 9 10
{-# LANGUAGE KindSignatures         #-}
{-# LANGUAGE MagicHash              #-}
{-# LANGUAGE NoImplicitPrelude      #-}
11 12
{-# LANGUAGE PolyKinds              #-}
{-# LANGUAGE ScopedTypeVariables    #-}
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
13
{-# LANGUAGE StandaloneDeriving     #-}
14 15
{-# LANGUAGE Trustworthy            #-}
{-# LANGUAGE TypeFamilies           #-}
16
{-# LANGUAGE TypeInType             #-}
17 18 19
{-# LANGUAGE TypeOperators          #-}
{-# LANGUAGE TypeSynonymInstances   #-}
{-# LANGUAGE UndecidableInstances   #-}
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
20

21 22 23
-----------------------------------------------------------------------------
-- |
-- Module      :  GHC.Generics
24
-- Copyright   :  (c) Universiteit Utrecht 2010-2011, University of Oxford 2012-2014
25
-- License     :  see libraries/base/LICENSE
26
--
27 28 29 30
-- Maintainer  :  libraries@haskell.org
-- Stability   :  internal
-- Portability :  non-portable
--
31
-- @since 4.6.0.0
32
--
dreixel's avatar
dreixel committed
33
-- If you're using @GHC.Generics@, you should consider using the
34
-- <http://hackage.haskell.org/package/generic-deriving> package, which
dreixel's avatar
dreixel committed
35
-- contains many useful generic functions.
36

jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
37
module GHC.Generics  (
dreixel's avatar
dreixel committed
38 39 40 41
-- * Introduction
--
-- |
--
Gabor Greif's avatar
Gabor Greif committed
42
-- Datatype-generic functions are based on the idea of converting values of
dreixel's avatar
dreixel committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
-- a datatype @T@ into corresponding values of a (nearly) isomorphic type @'Rep' T@.
-- The type @'Rep' T@ is
-- built from a limited set of type constructors, all provided by this module. A
-- datatype-generic function is then an overloaded function with instances
-- for most of these type constructors, together with a wrapper that performs
-- the mapping between @T@ and @'Rep' T@. By using this technique, we merely need
-- a few generic instances in order to implement functionality that works for any
-- representable type.
--
-- Representable types are collected in the 'Generic' class, which defines the
-- associated type 'Rep' as well as conversion functions 'from' and 'to'.
-- Typically, you will not define 'Generic' instances by hand, but have the compiler
-- derive them for you.

-- ** Representing datatypes
--
-- |
--
-- The key to defining your own datatype-generic functions is to understand how to
-- represent datatypes using the given set of type constructors.
--
-- Let us look at an example first:
--
-- @
-- data Tree a = Leaf a | Node (Tree a) (Tree a)
--   deriving 'Generic'
-- @
--
-- The above declaration (which requires the language pragma @DeriveGeneric@)
-- causes the following representation to be generated:
--
-- @
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
75
-- instance 'Generic' (Tree a) where
dreixel's avatar
dreixel committed
76
--   type 'Rep' (Tree a) =
77 78
--     'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)
--       ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False)
79
--          ('S1' '(MetaSel 'Nothing
Ryan Scott's avatar
Ryan Scott committed
80 81 82
--                          'NoSourceUnpackedness
--                          'NoSourceStrictness
--                          'DecidedLazy)
83
--                 ('Rec0' a))
dreixel's avatar
dreixel committed
84
--        ':+:'
85
--        'C1' ('MetaCons \"Node\" 'PrefixI 'False)
86 87 88 89 90
--          ('S1' ('MetaSel 'Nothing
--                          'NoSourceUnpackedness
--                          'NoSourceStrictness
--                          'DecidedLazy)
--                ('Rec0' (Tree a))
dreixel's avatar
dreixel committed
91
--           ':*:'
92 93 94 95 96
--           'S1' ('MetaSel 'Nothing
--                          'NoSourceUnpackedness
--                          'NoSourceStrictness
--                          'DecidedLazy)
--                ('Rec0' (Tree a))))
dreixel's avatar
dreixel committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
--   ...
-- @
--
-- /Hint:/ You can obtain information about the code being generated from GHC by passing
-- the @-ddump-deriv@ flag. In GHCi, you can expand a type family such as 'Rep' using
-- the @:kind!@ command.
--
-- This is a lot of information! However, most of it is actually merely meta-information
-- that makes names of datatypes and constructors and more available on the type level.
--
-- Here is a reduced representation for 'Tree' with nearly all meta-information removed,
-- for now keeping only the most essential aspects:
--
-- @
-- instance 'Generic' (Tree a) where
--   type 'Rep' (Tree a) =
113
--     'Rec0' a
dreixel's avatar
dreixel committed
114 115 116 117 118 119 120 121
--     ':+:'
--     ('Rec0' (Tree a) ':*:' 'Rec0' (Tree a))
-- @
--
-- The @Tree@ datatype has two constructors. The representation of individual constructors
-- is combined using the binary type constructor ':+:'.
--
-- The first constructor consists of a single field, which is the parameter @a@. This is
122
-- represented as @'Rec0' a@.
dreixel's avatar
dreixel committed
123 124 125 126 127 128 129
--
-- The second constructor consists of two fields. Each is a recursive field of type @Tree a@,
-- represented as @'Rec0' (Tree a)@. Representations of individual fields are combined using
-- the binary type constructor ':*:'.
--
-- Now let us explain the additional tags being used in the complete representation:
--
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
--    * The @'S1' ('MetaSel 'Nothing 'NoSourceUnpackedness 'NoSourceStrictness
--      'DecidedLazy)@ tag indicates several things. The @'Nothing@ indicates
--      that there is no record field selector associated with this field of
--      the constructor (if there were, it would have been marked @'Just
--      \"recordName\"@ instead). The other types contain meta-information on
--      the field's strictness:
--
--      * There is no @{\-\# UNPACK \#-\}@ or @{\-\# NOUNPACK \#-\}@ annotation
--        in the source, so it is tagged with @'NoSourceUnpackedness@.
--
--      * There is no strictness (@!@) or laziness (@~@) annotation in the
--        source, so it is tagged with @'NoSourceStrictness@.
--
--      * The compiler infers that the field is lazy, so it is tagged with
--        @'DecidedLazy@. Bear in mind that what the compiler decides may be
--        quite different from what is written in the source. See
--        'DecidedStrictness' for a more detailed explanation.
--
--      The @'MetaSel@ type is also an instance of the type class 'Selector',
--      which can be used to obtain information about the field at the value
--      level.
dreixel's avatar
dreixel committed
151
--
152 153
--    * The @'C1' ('MetaCons \"Leaf\" 'PrefixI 'False)@ and
--      @'C1' ('MetaCons \"Node\" 'PrefixI 'False)@ invocations indicate that the enclosed part is
dreixel's avatar
dreixel committed
154
--      the representation of the first and second constructor of datatype @Tree@, respectively.
155 156 157 158 159 160 161 162 163 164 165 166
--      Here, the meta-information regarding constructor names, fixity and whether
--      it has named fields or not is encoded at the type level. The @'MetaCons@
--      type is also an instance of the type class 'Constructor'. This type class can be used
--      to obtain information about the constructor at the value level.
--
--    * The @'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)@ tag
--      indicates that the enclosed part is the representation of the
--      datatype @Tree@. Again, the meta-information is encoded at the type level.
--      The @'MetaData@ type is an instance of class 'Datatype', which
--      can be used to obtain the name of a datatype, the module it has been
--      defined in, the package it is located under, and whether it has been
--      defined using @data@ or @newtype@ at the value level.
dreixel's avatar
dreixel committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

-- ** Derived and fundamental representation types
--
-- |
--
-- There are many datatype-generic functions that do not distinguish between positions that
-- are parameters or positions that are recursive calls. There are also many datatype-generic
-- functions that do not care about the names of datatypes and constructors at all. To keep
-- the number of cases to consider in generic functions in such a situation to a minimum,
-- it turns out that many of the type constructors introduced above are actually synonyms,
-- defining them to be variants of a smaller set of constructors.

-- *** Individual fields of constructors: 'K1'
--
-- |
--
183
-- The type constructor 'Rec0' is a variant of 'K1':
dreixel's avatar
dreixel committed
184 185 186 187 188
--
-- @
-- type 'Rec0' = 'K1' 'R'
-- @
--
189 190 191 192
-- Here, 'R' is a type-level proxy that does not have any associated values.
--
-- There used to be another variant of 'K1' (namely 'Par0'), but it has since
-- been deprecated.
dreixel's avatar
dreixel committed
193 194 195 196 197 198 199 200 201 202 203 204 205

-- *** Meta information: 'M1'
--
-- |
--
-- The type constructors 'S1', 'C1' and 'D1' are all variants of 'M1':
--
-- @
-- type 'S1' = 'M1' 'S'
-- type 'C1' = 'M1' 'C'
-- type 'D1' = 'M1' 'D'
-- @
--
206
-- The types 'S', 'C' and 'D' are once again type-level proxies, just used to create
dreixel's avatar
dreixel committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
-- several variants of 'M1'.

-- *** Additional generic representation type constructors
--
-- |
--
-- Next to 'K1', 'M1', ':+:' and ':*:' there are a few more type constructors that occur
-- in the representations of other datatypes.

-- **** Empty datatypes: 'V1'
--
-- |
--
-- For empty datatypes, 'V1' is used as a representation. For example,
--
-- @
-- data Empty deriving 'Generic'
-- @
--
-- yields
--
-- @
-- instance 'Generic' Empty where
230 231
--   type 'Rep' Empty =
--     'D1' ('MetaData \"Empty\" \"Main\" \"package-name\" 'False) 'V1'
dreixel's avatar
dreixel committed
232 233 234 235 236 237 238 239 240 241 242 243
-- @

-- **** Constructors without fields: 'U1'
--
-- |
--
-- If a constructor has no arguments, then 'U1' is used as its representation. For example
-- the representation of 'Bool' is
--
-- @
-- instance 'Generic' Bool where
--   type 'Rep' Bool =
244 245
--     'D1' ('MetaData \"Bool\" \"Data.Bool\" \"package-name\" 'False)
--       ('C1' ('MetaCons \"False\" 'PrefixI 'False) 'U1' ':+:' 'C1' ('MetaCons \"True\" 'PrefixI 'False) 'U1')
dreixel's avatar
dreixel committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
-- @

-- *** Representation of types with many constructors or many fields
--
-- |
--
-- As ':+:' and ':*:' are just binary operators, one might ask what happens if the
-- datatype has more than two constructors, or a constructor with more than two
-- fields. The answer is simple: the operators are used several times, to combine
-- all the constructors and fields as needed. However, users /should not rely on
-- a specific nesting strategy/ for ':+:' and ':*:' being used. The compiler is
-- free to choose any nesting it prefers. (In practice, the current implementation
-- tries to produce a more or less balanced nesting, so that the traversal of the
-- structure of the datatype from the root to a particular component can be performed
-- in logarithmic rather than linear time.)

-- ** Defining datatype-generic functions
--
-- |
--
-- A datatype-generic function comprises two parts:
--
--    1. /Generic instances/ for the function, implementing it for most of the representation
--       type constructors introduced above.
--
--    2. A /wrapper/ that for any datatype that is in `Generic`, performs the conversion
--       between the original value and its `Rep`-based representation and then invokes the
--       generic instances.
--
-- As an example, let us look at a function 'encode' that produces a naive, but lossless
-- bit encoding of values of various datatypes. So we are aiming to define a function
--
-- @
-- encode :: 'Generic' a => a -> [Bool]
-- @
--
-- where we use 'Bool' as our datatype for bits.
--
-- For part 1, we define a class @Encode'@. Perhaps surprisingly, this class is parameterized
-- over a type constructor @f@ of kind @* -> *@. This is a technicality: all the representation
-- type constructors operate with kind @* -> *@ as base kind. But the type argument is never
-- being used. This may be changed at some point in the future. The class has a single method,
-- and we use the type we want our final function to have, but we replace the occurrences of
-- the generic type argument @a@ with @f p@ (where the @p@ is any argument; it will not be used).
--
-- > class Encode' f where
-- >   encode' :: f p -> [Bool]
--
-- With the goal in mind to make @encode@ work on @Tree@ and other datatypes, we now define
-- instances for the representation type constructors 'V1', 'U1', ':+:', ':*:', 'K1', and 'M1'.

-- *** Definition of the generic representation types
--
-- |
--
-- In order to be able to do this, we need to know the actual definitions of these types:
--
-- @
-- data    'V1'        p                       -- lifted version of Empty
-- data    'U1'        p = 'U1'                  -- lifted version of ()
-- data    (':+:') f g p = 'L1' (f p) | 'R1' (g p) -- lifted version of 'Either'
307
-- data    (':*:') f g p = (f p) ':*:' (g p)     -- lifted version of (,)
dreixel's avatar
dreixel committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
-- newtype 'K1'    i c p = 'K1' { 'unK1' :: c }    -- a container for a c
-- newtype 'M1'  i t f p = 'M1' { 'unM1' :: f p }  -- a wrapper
-- @
--
-- So, 'U1' is just the unit type, ':+:' is just a binary choice like 'Either',
-- ':*:' is a binary pair like the pair constructor @(,)@, and 'K1' is a value
-- of a specific type @c@, and 'M1' wraps a value of the generic type argument,
-- which in the lifted world is an @f p@ (where we do not care about @p@).

-- *** Generic instances
--
-- |
--
-- The instance for 'V1' is slightly awkward (but also rarely used):
--
-- @
-- instance Encode' 'V1' where
--   encode' x = undefined
-- @
--
-- There are no values of type @V1 p@ to pass (except undefined), so this is
-- actually impossible. One can ask why it is useful to define an instance for
-- 'V1' at all in this case? Well, an empty type can be used as an argument to
-- a non-empty type, and you might still want to encode the resulting type.
-- As a somewhat contrived example, consider @[Empty]@, which is not an empty
-- type, but contains just the empty list. The 'V1' instance ensures that we
-- can call the generic function on such types.
--
-- There is exactly one value of type 'U1', so encoding it requires no
-- knowledge, and we can use zero bits:
--
-- @
-- instance Encode' 'U1' where
--   encode' 'U1' = []
-- @
--
-- In the case for ':+:', we produce 'False' or 'True' depending on whether
-- the constructor of the value provided is located on the left or on the right:
--
-- @
-- instance (Encode' f, Encode' g) => Encode' (f ':+:' g) where
--   encode' ('L1' x) = False : encode' x
--   encode' ('R1' x) = True  : encode' x
-- @
--
-- In the case for ':*:', we append the encodings of the two subcomponents:
--
-- @
-- instance (Encode' f, Encode' g) => Encode' (f ':*:' g) where
--   encode' (x ':*:' y) = encode' x ++ encode' y
-- @
--
-- The case for 'K1' is rather interesting. Here, we call the final function
-- 'encode' that we yet have to define, recursively. We will use another type
-- class 'Encode' for that function:
--
-- @
-- instance (Encode c) => Encode' ('K1' i c) where
--   encode' ('K1' x) = encode x
-- @
--
-- Note how 'Par0' and 'Rec0' both being mapped to 'K1' allows us to define
-- a uniform instance here.
--
-- Similarly, we can define a uniform instance for 'M1', because we completely
-- disregard all meta-information:
--
-- @
-- instance (Encode' f) => Encode' ('M1' i t f) where
--   encode' ('M1' x) = encode' x
-- @
--
-- Unlike in 'K1', the instance for 'M1' refers to 'encode'', not 'encode'.

-- *** The wrapper and generic default
--
-- |
--
-- We now define class 'Encode' for the actual 'encode' function:
--
-- @
-- class Encode a where
--   encode :: a -> [Bool]
Ben Gamari's avatar
Ben Gamari committed
391
--   default encode :: (Generic a, Encode' (Rep a)) => a -> [Bool]
dreixel's avatar
dreixel committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
--   encode x = encode' ('from' x)
-- @
--
-- The incoming 'x' is converted using 'from', then we dispatch to the
-- generic instances using 'encode''. We use this as a default definition
-- for 'encode'. We need the 'default encode' signature because ordinary
-- Haskell default methods must not introduce additional class constraints,
-- but our generic default does.
--
-- Defining a particular instance is now as simple as saying
--
-- @
-- instance (Encode a) => Encode (Tree a)
-- @
--
#if 0
-- /TODO:/ Add usage example?
--
#endif
-- The generic default is being used. In the future, it will hopefully be
-- possible to use @deriving Encode@ as well, but GHC does not yet support
-- that syntax for this situation.
--
-- Having 'Encode' as a class has the advantage that we can define
-- non-generic special cases, which is particularly useful for abstract
-- datatypes that have no structural representation. For example, given
-- a suitable integer encoding function 'encodeInt', we can define
--
-- @
-- instance Encode Int where
--   encode = encodeInt
-- @

-- *** Omitting generic instances
--
-- |
--
-- It is not always required to provide instances for all the generic
-- representation types, but omitting instances restricts the set of
-- datatypes the functions will work for:
--
--    * If no ':+:' instance is given, the function may still work for
--      empty datatypes or datatypes that have a single constructor,
--      but will fail on datatypes with more than one constructor.
--
--    * If no ':*:' instance is given, the function may still work for
--      datatypes where each constructor has just zero or one field,
--      in particular for enumeration types.
--
--    * If no 'K1' instance is given, the function may still work for
--      enumeration types, where no constructor has any fields.
--
--    * If no 'V1' instance is given, the function may still work for
--      any datatype that is not empty.
--
--    * If no 'U1' instance is given, the function may still work for
--      any datatype where each constructor has at least one field.
--
-- An 'M1' instance is always required (but it can just ignore the
-- meta-information, as is the case for 'encode' above).
#if 0
-- *** Using meta-information
--
-- |
--
-- TODO
#endif
-- ** Generic constructor classes
--
-- |
--
-- Datatype-generic functions as defined above work for a large class
-- of datatypes, including parameterized datatypes. (We have used 'Tree'
-- as our example above, which is of kind @* -> *@.) However, the
-- 'Generic' class ranges over types of kind @*@, and therefore, the
-- resulting generic functions (such as 'encode') must be parameterized
-- by a generic type argument of kind @*@.
--
-- What if we want to define generic classes that range over type
-- constructors (such as 'Functor', 'Traversable', or 'Foldable')?

-- *** The 'Generic1' class
--
-- |
--
-- Like 'Generic', there is a class 'Generic1' that defines a
-- representation 'Rep1' and conversion functions 'from1' and 'to1',
Ryan Scott's avatar
Ryan Scott committed
479 480 481
-- only that 'Generic1' ranges over types of kind @* -> *@. (More generally,
-- it can range over types of kind @k -> *@, for any kind @k@, if the
-- @PolyKinds@ extension is enabled. More on this later.)
dreixel's avatar
dreixel committed
482 483 484 485 486 487 488 489 490 491 492 493
-- The 'Generic1' class is also derivable.
--
-- The representation 'Rep1' is ever so slightly different from 'Rep'.
-- Let us look at 'Tree' as an example again:
--
-- @
-- data Tree a = Leaf a | Node (Tree a) (Tree a)
--   deriving 'Generic1'
-- @
--
-- The above declaration causes the following representation to be generated:
--
494
-- @
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
495
-- instance 'Generic1' Tree where
dreixel's avatar
dreixel committed
496
--   type 'Rep1' Tree =
497 498
--     'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)
--       ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False)
499 500 501 502 503
--          ('S1' ('MetaSel 'Nothing
--                          'NoSourceUnpackedness
--                          'NoSourceStrictness
--                          'DecidedLazy)
--                'Par1')
dreixel's avatar
dreixel committed
504
--        ':+:'
505
--        'C1' ('MetaCons \"Node\" 'PrefixI 'False)
506 507 508 509 510
--          ('S1' ('MetaSel 'Nothing
--                          'NoSourceUnpackedness
--                          'NoSourceStrictness
--                          'DecidedLazy)
--                ('Rec1' Tree)
dreixel's avatar
dreixel committed
511
--           ':*:'
512 513 514 515 516
--           'S1' ('MetaSel 'Nothing
--                          'NoSourceUnpackedness
--                          'NoSourceStrictness
--                          'DecidedLazy)
--                ('Rec1' Tree)))
dreixel's avatar
dreixel committed
517
--   ...
Ryan Scott's avatar
Ryan Scott committed
518
-- @
dreixel's avatar
dreixel committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
--
-- The representation reuses 'D1', 'C1', 'S1' (and thereby 'M1') as well
-- as ':+:' and ':*:' from 'Rep'. (This reusability is the reason that we
-- carry around the dummy type argument for kind-@*@-types, but there are
-- already enough different names involved without duplicating each of
-- these.)
--
-- What's different is that we now use 'Par1' to refer to the parameter
-- (and that parameter, which used to be @a@), is not mentioned explicitly
-- by name anywhere; and we use 'Rec1' to refer to a recursive use of @Tree a@.

-- *** Representation of @* -> *@ types
--
-- |
--
534
-- Unlike 'Rec0', the 'Par1' and 'Rec1' type constructors do not
dreixel's avatar
dreixel committed
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
-- map to 'K1'. They are defined directly, as follows:
--
-- @
-- newtype 'Par1'   p = 'Par1' { 'unPar1' ::   p } -- gives access to parameter p
-- newtype 'Rec1' f p = 'Rec1' { 'unRec1' :: f p } -- a wrapper
-- @
--
-- In 'Par1', the parameter @p@ is used for the first time, whereas 'Rec1' simply
-- wraps an application of @f@ to @p@.
--
-- Note that 'K1' (in the guise of 'Rec0') can still occur in a 'Rep1' representation,
-- namely when the datatype has a field that does not mention the parameter.
--
-- The declaration
--
-- @
-- data WithInt a = WithInt Int a
--   deriving 'Generic1'
-- @
--
-- yields
--
-- @
Ryan Scott's avatar
Ryan Scott committed
558
-- instance 'Generic1' WithInt where
dreixel's avatar
dreixel committed
559
--   type 'Rep1' WithInt =
560 561
--     'D1' ('MetaData \"WithInt\" \"Main\" \"package-name\" 'False)
--       ('C1' ('MetaCons \"WithInt\" 'PrefixI 'False)
562 563 564 565 566
--         ('S1' ('MetaSel 'Nothing
--                         'NoSourceUnpackedness
--                         'NoSourceStrictness
--                         'DecidedLazy)
--               ('Rec0' Int)
dreixel's avatar
dreixel committed
567
--          ':*:'
568 569 570 571 572
--          'S1' ('MetaSel 'Nothing
--                          'NoSourceUnpackedness
--                          'NoSourceStrictness
--                          'DecidedLazy)
--               'Par1'))
dreixel's avatar
dreixel committed
573 574 575 576 577 578 579 580 581 582 583 584
-- @
--
-- If the parameter @a@ appears underneath a composition of other type constructors,
-- then the representation involves composition, too:
--
-- @
-- data Rose a = Fork a [Rose a]
-- @
--
-- yields
--
-- @
Ryan Scott's avatar
Ryan Scott committed
585
-- instance 'Generic1' Rose where
dreixel's avatar
dreixel committed
586
--   type 'Rep1' Rose =
587 588
--     'D1' ('MetaData \"Rose\" \"Main\" \"package-name\" 'False)
--       ('C1' ('MetaCons \"Fork\" 'PrefixI 'False)
589 590 591 592 593
--         ('S1' ('MetaSel 'Nothing
--                         'NoSourceUnpackedness
--                         'NoSourceStrictness
--                         'DecidedLazy)
--               'Par1'
dreixel's avatar
dreixel committed
594
--          ':*:'
595 596 597 598 599
--          'S1' ('MetaSel 'Nothing
--                          'NoSourceUnpackedness
--                          'NoSourceStrictness
--                          'DecidedLazy)
--               ([] ':.:' 'Rec1' Rose)))
dreixel's avatar
dreixel committed
600 601 602 603 604 605 606
-- @
--
-- where
--
-- @
-- newtype (':.:') f g p = 'Comp1' { 'unComp1' :: f (g p) }
-- @
607

Ryan Scott's avatar
Ryan Scott committed
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
-- *** Representation of @k -> *@ types
--
-- |
--
-- The 'Generic1' class can be generalized to range over types of kind
-- @k -> *@, for any kind @k@. To do so, derive a 'Generic1' instance with the
-- @PolyKinds@ extension enabled. For example, the declaration
--
-- @
-- data Proxy (a :: k) = Proxy deriving 'Generic1'
-- @
--
-- yields a slightly different instance depending on whether @PolyKinds@ is
-- enabled. If compiled without @PolyKinds@, then @'Rep1' Proxy :: * -> *@, but
-- if compiled with @PolyKinds@, then @'Rep1' Proxy :: k -> *@.

624 625 626 627 628 629 630
-- *** Representation of unlifted types
--
-- |
--
-- If one were to attempt to derive a Generic instance for a datatype with an
-- unlifted argument (for example, 'Int#'), one might expect the occurrence of
-- the 'Int#' argument to be marked with @'Rec0' 'Int#'@. This won't work,
Ryan Scott's avatar
Ryan Scott committed
631 632
-- though, since 'Int#' is of an unlifted kind, and 'Rec0' expects a type of
-- kind @*@.
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
--
-- One solution would be to represent an occurrence of 'Int#' with 'Rec0 Int'
-- instead. With this approach, however, the programmer has no way of knowing
-- whether the 'Int' is actually an 'Int#' in disguise.
--
-- Instead of reusing 'Rec0', a separate data family 'URec' is used to mark
-- occurrences of common unlifted types:
--
-- @
-- data family URec a p
--
-- data instance 'URec' ('Ptr' ()) p = 'UAddr'   { 'uAddr#'   :: 'Addr#'   }
-- data instance 'URec' 'Char'     p = 'UChar'   { 'uChar#'   :: 'Char#'   }
-- data instance 'URec' 'Double'   p = 'UDouble' { 'uDouble#' :: 'Double#' }
-- data instance 'URec' 'Int'      p = 'UFloat'  { 'uFloat#'  :: 'Float#'  }
-- data instance 'URec' 'Float'    p = 'UInt'    { 'uInt#'    :: 'Int#'    }
-- data instance 'URec' 'Word'     p = 'UWord'   { 'uWord#'   :: 'Word#'   }
-- @
--
-- Several type synonyms are provided for convenience:
--
-- @
-- type 'UAddr'   = 'URec' ('Ptr' ())
-- type 'UChar'   = 'URec' 'Char'
-- type 'UDouble' = 'URec' 'Double'
-- type 'UFloat'  = 'URec' 'Float'
-- type 'UInt'    = 'URec' 'Int'
-- type 'UWord'   = 'URec' 'Word'
-- @
--
-- The declaration
--
-- @
-- data IntHash = IntHash Int#
--   deriving 'Generic'
-- @
--
-- yields
--
-- @
-- instance 'Generic' IntHash where
--   type 'Rep' IntHash =
675 676
--     'D1' ('MetaData \"IntHash\" \"Main\" \"package-name\" 'False)
--       ('C1' ('MetaCons \"IntHash\" 'PrefixI 'False)
677 678 679 680 681
--         ('S1' ('MetaSel 'Nothing
--                         'NoSourceUnpackedness
--                         'NoSourceStrictness
--                         'DecidedLazy)
--               'UInt'))
682 683 684 685
-- @
--
-- Currently, only the six unlifted types listed above are generated, but this
-- may be extended to encompass more unlifted types in the future.
dreixel's avatar
dreixel committed
686 687 688 689 690 691 692 693 694 695 696 697
#if 0
-- *** Limitations
--
-- |
--
-- /TODO/
--
-- /TODO:/ Also clear up confusion about 'Rec0' and 'Rec1' not really indicating recursion.
--
#endif
-----------------------------------------------------------------------------

jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
698 699 700 701
  -- * Generic representation types
    V1, U1(..), Par1(..), Rec1(..), K1(..), M1(..)
  , (:+:)(..), (:*:)(..), (:.:)(..)

702 703 704 705 706
  -- ** Unboxed representation types
  , URec(..)
  , type UAddr, type UChar, type UDouble
  , type UFloat, type UInt, type UWord

jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
707
  -- ** Synonyms for convenience
708
  , Rec0, R
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
709 710 711
  , D1, C1, S1, D, C, S

  -- * Meta-information
712
  , Datatype(..), Constructor(..), Selector(..)
713
  , Fixity(..), FixityI(..), Associativity(..), prec
714
  , SourceUnpackedness(..), SourceStrictness(..), DecidedStrictness(..)
715
  , Meta(..)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
716 717 718 719 720 721 722

  -- * Generic type classes
  , Generic(..), Generic1(..)

  ) where

-- We use some base types
723 724
import Data.Either ( Either (..) )
import Data.Maybe  ( Maybe(..), fromMaybe )
725
import GHC.Integer ( Integer, integerToInt )
726 727
import GHC.Prim    ( Addr#, Char#, Double#, Float#, Int#, Word# )
import GHC.Ptr     ( Ptr )
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
728 729 730
import GHC.Types

-- Needed for instances
731 732 733
import GHC.Arr     ( Ix )
import GHC.Base    ( Alternative(..), Applicative(..), Functor(..)
                   , Monad(..), MonadPlus(..), String )
734
import GHC.Classes ( Eq(..), Ord(..) )
735
import GHC.Enum    ( Bounded, Enum )
736 737
import GHC.Read    ( Read(..), lex, readParen )
import GHC.Show    ( Show(..), showString )
738 739

-- Needed for metadata
740
import Data.Proxy   ( Proxy(..) )
741
import GHC.TypeLits ( Nat, Symbol, KnownSymbol, KnownNat, symbolVal, natVal )
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
742 743 744 745 746 747

--------------------------------------------------------------------------------
-- Representation types
--------------------------------------------------------------------------------

-- | Void: used for datatypes without constructors
Ryan Scott's avatar
Ryan Scott committed
748
data V1 (p :: k)
749 750 751 752 753 754
  deriving (Functor, Generic, Generic1)

deriving instance Eq   (V1 p)
deriving instance Ord  (V1 p)
deriving instance Read (V1 p)
deriving instance Show (V1 p)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
755 756

-- | Unit: used for constructors without arguments
Ryan Scott's avatar
Ryan Scott committed
757
data U1 (p :: k) = U1
758 759
  deriving (Generic, Generic1)

760
-- | @since 4.9.0.0
761 762 763
instance Eq (U1 p) where
  _ == _ = True

764
-- | @since 4.9.0.0
765 766 767
instance Ord (U1 p) where
  compare _ _ = EQ

768
-- | @since 4.9.0.0
769 770 771
instance Read (U1 p) where
  readsPrec d = readParen (d > 10) (\r -> [(U1, s) | ("U1",s) <- lex r ])

772
-- | @since 4.9.0.0
773 774 775
instance Show (U1 p) where
  showsPrec _ _ = showString "U1"

776
-- | @since 4.9.0.0
777 778
instance Functor U1 where
  fmap _ _ = U1
779

780
-- | @since 4.9.0.0
781 782
instance Applicative U1 where
  pure _ = U1
783
  _ <*> _ = U1
784

785
-- | @since 4.9.0.0
786 787
instance Alternative U1 where
  empty = U1
788
  _ <|> _ = U1
789

790
-- | @since 4.9.0.0
791
instance Monad U1 where
792 793
  _ >>= _ = U1

794
-- | @since 4.9.0.0
795
instance MonadPlus U1
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
796 797 798

-- | Used for marking occurrences of the parameter
newtype Par1 p = Par1 { unPar1 :: p }
799 800
  deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)

801
-- | @since 4.9.0.0
802 803 804 805
instance Applicative Par1 where
  pure a = Par1 a
  Par1 f <*> Par1 x = Par1 (f x)

806
-- | @since 4.9.0.0
807 808
instance Monad Par1 where
  Par1 x >>= f = f x
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
809

Ryan Scott's avatar
Ryan Scott committed
810 811 812
-- | Recursive calls of kind @* -> *@ (or kind @k -> *@, when @PolyKinds@
-- is enabled)
newtype Rec1 (f :: k -> *) (p :: k) = Rec1 { unRec1 :: f p }
813 814
  deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)

815
-- | @since 4.9.0.0
816 817 818 819
instance Applicative f => Applicative (Rec1 f) where
  pure a = Rec1 (pure a)
  Rec1 f <*> Rec1 x = Rec1 (f <*> x)

820
-- | @since 4.9.0.0
821 822 823 824
instance Alternative f => Alternative (Rec1 f) where
  empty = Rec1 empty
  Rec1 l <|> Rec1 r = Rec1 (l <|> r)

825
-- | @since 4.9.0.0
826 827 828
instance Monad f => Monad (Rec1 f) where
  Rec1 x >>= f = Rec1 (x >>= \a -> unRec1 (f a))

829
-- | @since 4.9.0.0
830
instance MonadPlus f => MonadPlus (Rec1 f)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
831

Ryan Scott's avatar
Ryan Scott committed
832 833
-- | Constants, additional parameters and recursion of kind @*@
newtype K1 (i :: *) c (p :: k) = K1 { unK1 :: c }
834 835
  deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)

836
-- | @since 4.9.0.0
837 838 839 840
instance Applicative f => Applicative (M1 i c f) where
  pure a = M1 (pure a)
  M1 f <*> M1 x = M1 (f <*> x)

841
-- | @since 4.9.0.0
842 843 844 845
instance Alternative f => Alternative (M1 i c f) where
  empty = M1 empty
  M1 l <|> M1 r = M1 (l <|> r)

846
-- | @since 4.9.0.0
847 848 849
instance Monad f => Monad (M1 i c f) where
  M1 x >>= f = M1 (x >>= \a -> unM1 (f a))

850
-- | @since 4.9.0.0
851
instance MonadPlus f => MonadPlus (M1 i c f)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
852 853

-- | Meta-information (constructor names, etc.)
Ryan Scott's avatar
Ryan Scott committed
854
newtype M1 (i :: *) (c :: Meta) (f :: k -> *) (p :: k) = M1 { unM1 :: f p }
855
  deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
856 857 858

-- | Sums: encode choice between constructors
infixr 5 :+:
Ryan Scott's avatar
Ryan Scott committed
859
data (:+:) (f :: k -> *) (g :: k -> *) (p :: k) = L1 (f p) | R1 (g p)
860
  deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
861 862 863

-- | Products: encode multiple arguments to constructors
infixr 6 :*:
Ryan Scott's avatar
Ryan Scott committed
864
data (:*:) (f :: k -> *) (g :: k -> *) (p :: k) = f p :*: g p
865 866
  deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)

867
-- | @since 4.9.0.0
868 869 870 871
instance (Applicative f, Applicative g) => Applicative (f :*: g) where
  pure a = pure a :*: pure a
  (f :*: g) <*> (x :*: y) = (f <*> x) :*: (g <*> y)

872
-- | @since 4.9.0.0
873 874 875 876
instance (Alternative f, Alternative g) => Alternative (f :*: g) where
  empty = empty :*: empty
  (x1 :*: y1) <|> (x2 :*: y2) = (x1 <|> x2) :*: (y1 <|> y2)

877
-- | @since 4.9.0.0
878 879 880 881 882 883
instance (Monad f, Monad g) => Monad (f :*: g) where
  (m :*: n) >>= f = (m >>= \a -> fstP (f a)) :*: (n >>= \a -> sndP (f a))
    where
      fstP (a :*: _) = a
      sndP (_ :*: b) = b

884
-- | @since 4.9.0.0
885
instance (MonadPlus f, MonadPlus g) => MonadPlus (f :*: g)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
886 887 888

-- | Composition of functors
infixr 7 :.:
Ryan Scott's avatar
Ryan Scott committed
889 890
newtype (:.:) (f :: k2 -> *) (g :: k1 -> k2) (p :: k1) =
    Comp1 { unComp1 :: f (g p) }
891 892
  deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)

893
-- | @since 4.9.0.0
894 895 896 897
instance (Applicative f, Applicative g) => Applicative (f :.: g) where
  pure x = Comp1 (pure (pure x))
  Comp1 f <*> Comp1 x = Comp1 (fmap (<*>) f <*> x)

898
-- | @since 4.9.0.0
899 900 901
instance (Alternative f, Applicative g) => Alternative (f :.: g) where
  empty = Comp1 empty
  Comp1 x <|> Comp1 y = Comp1 (x <|> y)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
902

Ryan Scott's avatar
Ryan Scott committed
903
-- | Constants of unlifted kinds
904 905
--
-- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
906
data family URec (a :: *) (p :: k)
907 908

-- | Used for marking occurrences of 'Addr#'
909 910
--
-- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
911
data instance URec (Ptr ()) (p :: k) = UAddr { uAddr# :: Addr# }
912
  deriving (Eq, Ord, Functor, Generic, Generic1)
913 914

-- | Used for marking occurrences of 'Char#'
915 916
--
-- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
917
data instance URec Char (p :: k) = UChar { uChar# :: Char# }
918
  deriving (Eq, Ord, Show, Functor, Generic, Generic1)
919 920

-- | Used for marking occurrences of 'Double#'
921 922
--
-- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
923
data instance URec Double (p :: k) = UDouble { uDouble# :: Double# }
924
  deriving (Eq, Ord, Show, Functor, Generic, Generic1)
925 926

-- | Used for marking occurrences of 'Float#'
927 928
--
-- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
929
data instance URec Float (p :: k) = UFloat { uFloat# :: Float# }
930
  deriving (Eq, Ord, Show, Functor, Generic, Generic1)
931 932

-- | Used for marking occurrences of 'Int#'
933 934
--
-- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
935
data instance URec Int (p :: k) = UInt { uInt# :: Int# }
936
  deriving (Eq, Ord, Show, Functor, Generic, Generic1)
937 938

-- | Used for marking occurrences of 'Word#'
939 940
--
-- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
941
data instance URec Word (p :: k) = UWord { uWord# :: Word# }
942
  deriving (Eq, Ord, Show, Functor, Generic, Generic1)
943

Ryan Scott's avatar
Ryan Scott committed
944
-- | Type synonym for @'URec' 'Addr#'@
945 946
--
-- @since 4.9.0.0
947
type UAddr   = URec (Ptr ())
Ryan Scott's avatar
Ryan Scott committed
948
-- | Type synonym for @'URec' 'Char#'@
949 950
--
-- @since 4.9.0.0
951
type UChar   = URec Char
952

Ryan Scott's avatar
Ryan Scott committed
953
-- | Type synonym for @'URec' 'Double#'@
954 955
--
-- @since 4.9.0.0
956
type UDouble = URec Double
957

Ryan Scott's avatar
Ryan Scott committed
958
-- | Type synonym for @'URec' 'Float#'@
959 960
--
-- @since 4.9.0.0
961
type UFloat  = URec Float
962

Ryan Scott's avatar
Ryan Scott committed
963
-- | Type synonym for @'URec' 'Int#'@
964 965
--
-- @since 4.9.0.0
966
type UInt    = URec Int
967

Ryan Scott's avatar
Ryan Scott committed
968
-- | Type synonym for @'URec' 'Word#'@
969 970
--
-- @since 4.9.0.0
971 972
type UWord   = URec Word

Ryan Scott's avatar
Ryan Scott committed
973
-- | Tag for K1: recursion (of kind @*@)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
974 975
data R

Ryan Scott's avatar
Ryan Scott committed
976
-- | Type synonym for encoding recursion (of kind @*@)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
type Rec0  = K1 R

-- | Tag for M1: datatype
data D
-- | Tag for M1: constructor
data C
-- | Tag for M1: record selector
data S

-- | Type synonym for encoding meta-information for datatypes
type D1 = M1 D

-- | Type synonym for encoding meta-information for constructors
type C1 = M1 C

-- | Type synonym for encoding meta-information for record selectors
type S1 = M1 S

-- | Class for datatypes that represent datatypes
996
class Datatype d where
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
997
  -- | The name of the datatype (unqualified)
Ryan Scott's avatar
Ryan Scott committed
998
  datatypeName :: t d (f :: k -> *) (a :: k) -> [Char]
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
999
  -- | The fully-qualified name of the module where the type is declared
Ryan Scott's avatar
Ryan Scott committed
1000
  moduleName   :: t d (f :: k -> *) (a :: k) -> [Char]
1001
  -- | The package name of the module where the type is declared
Ryan Scott's avatar
Ryan Scott committed
1002 1003
  --
  -- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
1004
  packageName :: t d (f :: k -> *) (a :: k) -> [Char]
1005
  -- | Marks if the datatype is actually a newtype
Ryan Scott's avatar
Ryan Scott committed
1006 1007
  --
  -- @since 4.7.0.0
Ryan Scott's avatar
Ryan Scott committed
1008
  isNewtype    :: t d (f :: k -> *) (a :: k) -> Bool
1009
  isNewtype _ = False
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1010

1011
-- | @since 4.9.0.0
1012 1013 1014 1015 1016 1017
instance (KnownSymbol n, KnownSymbol m, KnownSymbol p, SingI nt)
    => Datatype ('MetaData n m p nt) where
  datatypeName _ = symbolVal (Proxy :: Proxy n)
  moduleName   _ = symbolVal (Proxy :: Proxy m)
  packageName  _ = symbolVal (Proxy :: Proxy p)
  isNewtype    _ = fromSing  (sing  :: Sing nt)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1018 1019

-- | Class for datatypes that represent data constructors
1020
class Constructor c where
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1021
  -- | The name of the constructor
Ryan Scott's avatar
Ryan Scott committed
1022
  conName :: t c (f :: k -> *) (a :: k) -> [Char]
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1023 1024

  -- | The fixity of the constructor
Ryan Scott's avatar
Ryan Scott committed
1025
  conFixity :: t c (f :: k -> *) (a :: k) -> Fixity
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1026 1027 1028
  conFixity _ = Prefix

  -- | Marks if this constructor is a record
Ryan Scott's avatar
Ryan Scott committed
1029
  conIsRecord :: t c (f :: k -> *) (a :: k) -> Bool
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1030 1031
  conIsRecord _ = False

1032
-- | @since 4.9.0.0
1033 1034 1035 1036 1037
instance (KnownSymbol n, SingI f, SingI r)
    => Constructor ('MetaCons n f r) where
  conName     _ = symbolVal (Proxy :: Proxy n)
  conFixity   _ = fromSing  (sing  :: Sing f)
  conIsRecord _ = fromSing  (sing  :: Sing r)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1038 1039 1040 1041

-- | Datatype to represent the fixity of a constructor. An infix
-- | declaration directly corresponds to an application of 'Infix'.
data Fixity = Prefix | Infix Associativity Int
1042
  deriving (Eq, Show, Ord, Read, Generic)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1043

1044
-- | This variant of 'Fixity' appears at the type level.
Ryan Scott's avatar
Ryan Scott committed
1045 1046
--
-- @since 4.9.0.0
1047 1048
data FixityI = PrefixI | InfixI Associativity Nat

jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1049 1050 1051 1052 1053 1054 1055 1056 1057
-- | Get the precedence of a fixity value.
prec :: Fixity -> Int
prec Prefix      = 10
prec (Infix _ n) = n

-- | Datatype to represent the associativity of a constructor
data Associativity = LeftAssociative
                   | RightAssociative
                   | NotAssociative
1058
  deriving (Eq, Show, Ord, Read, Enum, Bounded, Ix, Generic)
jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1059

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
-- | The unpackedness of a field as the user wrote it in the source code. For
-- example, in the following data type:
--
-- @
-- data E = ExampleConstructor     Int
--            {\-\# NOUNPACK \#-\} Int
--            {\-\#   UNPACK \#-\} Int
-- @
--
-- The fields of @ExampleConstructor@ have 'NoSourceUnpackedness',
-- 'SourceNoUnpack', and 'SourceUnpack', respectively.
Ryan Scott's avatar
Ryan Scott committed
1071 1072
--
-- @since 4.9.0.0
1073 1074 1075
data SourceUnpackedness = NoSourceUnpackedness
                        | SourceNoUnpack
                        | SourceUnpack
1076
  deriving (Eq, Show, Ord, Read, Enum, Bounded, Ix, Generic)
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

-- | The strictness of a field as the user wrote it in the source code. For
-- example, in the following data type:
--
-- @
-- data E = ExampleConstructor Int ~Int !Int
-- @
--
-- The fields of @ExampleConstructor@ have 'NoSourceStrictness',
-- 'SourceLazy', and 'SourceStrict', respectively.
Ryan Scott's avatar
Ryan Scott committed
1087 1088
--
-- @since 4.9.0.0
1089 1090 1091
data SourceStrictness = NoSourceStrictness
                      | SourceLazy
                      | SourceStrict
1092
  deriving (Eq, Show, Ord, Read, Enum, Bounded, Ix, Generic)
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113

-- | The strictness that GHC infers for a field during compilation. Whereas
-- there are nine different combinations of 'SourceUnpackedness' and
-- 'SourceStrictness', the strictness that GHC decides will ultimately be one
-- of lazy, strict, or unpacked. What GHC decides is affected both by what the
-- user writes in the source code and by GHC flags. As an example, consider
-- this data type:
--
-- @
-- data E = ExampleConstructor {\-\# UNPACK \#-\} !Int !Int Int
-- @
--
-- * If compiled without optimization or other language extensions, then the
--   fields of @ExampleConstructor@ will have 'DecidedStrict', 'DecidedStrict',
--   and 'DecidedLazy', respectively.
--
-- * If compiled with @-XStrictData@ enabled, then the fields will have
--   'DecidedStrict', 'DecidedStrict', and 'DecidedStrict', respectively.
--
-- * If compiled with @-O2@ enabled, then the fields will have 'DecidedUnpack',
--   'DecidedStrict', and 'DecidedLazy', respectively.
Ryan Scott's avatar
Ryan Scott committed
1114 1115
--
-- @since 4.9.0.0
1116 1117 1118
data DecidedStrictness = DecidedLazy
                       | DecidedStrict
                       | DecidedUnpack
1119
  deriving (Eq, Show, Ord, Read, Enum, Bounded, Ix, Generic)
1120

1121 1122 1123
-- | Class for datatypes that represent records
class Selector s where
  -- | The name of the selector
Ryan Scott's avatar
Ryan Scott committed
1124
  selName :: t s (f :: k -> *) (a :: k) -> [Char]
1125
  -- | The selector's unpackedness annotation (if any)
Ryan Scott's avatar
Ryan Scott committed
1126 1127
  --
  -- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
1128
  selSourceUnpackedness :: t s (f :: k -> *) (a :: k) -> SourceUnpackedness
1129
  -- | The selector's strictness annotation (if any)
Ryan Scott's avatar
Ryan Scott committed
1130 1131
  --
  -- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
1132
  selSourceStrictness :: t s (f :: k -> *) (a :: k) -> SourceStrictness
1133
  -- | The strictness that the compiler inferred for the selector
Ryan Scott's avatar
Ryan Scott committed
1134 1135
  --
  -- @since 4.9.0.0
Ryan Scott's avatar
Ryan Scott committed
1136
  selDecidedStrictness :: t s (f :: k -> *) (a :: k) -> DecidedStrictness
1137

1138
-- | @since 4.9.0.0
1139 1140 1141 1142 1143 1144
instance (SingI mn, SingI su, SingI ss, SingI ds)
    => Selector ('MetaSel mn su ss ds) where
  selName _ = fromMaybe "" (fromSing (sing :: Sing mn))
  selSourceUnpackedness _ = fromSing (sing :: Sing su)
  selSourceStrictness   _ = fromSing (sing :: Sing ss)
  selDecidedStrictness  _ = fromSing (sing :: Sing ds)
1145

jpm@cs.ox.ac.uk's avatar
jpm@cs.ox.ac.uk committed
1146 1147 1148 1149 1150 1151 1152 1153 1154