-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Convenient imperative eDSL over Lorentz. -- -- Syntax and implementation of Indigo eDSL. @package indigo @version 0.2.2 -- | This module is intended to be imported instead of -- morley-prelude by Backend Indigo modules. -- -- This only serves the purpose of listing hiding rules once and -- avoid boilerplate. module Indigo.Backend.Prelude -- | Append two lists, i.e., -- --
--   [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
--   [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
--   
-- -- If the first list is not finite, the result is the first list. (++) :: [a] -> [a] -> [a] infixr 5 ++ -- | The value of seq a b is bottom if a is bottom, and -- otherwise equal to b. In other words, it evaluates the first -- argument a to weak head normal form (WHNF). seq is -- usually introduced to improve performance by avoiding unneeded -- laziness. -- -- A note on evaluation order: the expression seq a b does -- not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq -- returns a value. In particular, this means that b may be -- evaluated before a. If you need to guarantee a specific order -- of evaluation, you must use the function pseq from the -- "parallel" package. seq :: a -> b -> b infixr 0 `seq` -- | O(n). filter, applied to a predicate and a list, returns -- the list of those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
-- --
--   >>> filter odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | O(min(m,n)). zip takes two lists and returns a list of -- corresponding pairs. -- --
--   zip [1, 2] ['a', 'b'] = [(1, 'a'), (2, 'b')]
--   
-- -- If one input list is short, excess elements of the longer list are -- discarded: -- --
--   zip [1] ['a', 'b'] = [(1, 'a')]
--   zip [1, 2] ['a'] = [(1, 'a')]
--   
-- -- zip is right-lazy: -- --
--   zip [] _|_ = []
--   zip _|_ [] = _|_
--   
-- -- zip is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zip :: [a] -> [b] -> [(a, b)] -- | Extract the first component of a pair. fst :: (a, b) -> a -- | Extract the second component of a pair. snd :: (a, b) -> b -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
--   f x | x < 0     = ...
--       | otherwise = ...
--   
otherwise :: Bool -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
--   f $ g $ h x  =  f (g (h x))
--   
-- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is levity-polymorphic in its result -- type, so that foo $ True where foo :: Bool -> -- Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b -- | Conditional failure of Alternative computations. Defined by -- --
--   guard True  = pure ()
--   guard False = empty
--   
-- --

Examples

-- -- Common uses of guard include conditionally signaling an error -- in an error monad and conditionally rejecting the current choice in an -- Alternative-based parser. -- -- As an example of signaling an error in the error monad Maybe, -- consider a safe division function safeDiv x y that returns -- Nothing when the denominator y is zero and -- Just (x `div` y) otherwise. For example: -- --
--   >>> safeDiv 4 0
--   Nothing
--   >>> safeDiv 4 2
--   Just 2
--   
-- -- A definition of safeDiv using guards, but not guard: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y | y /= 0    = Just (x `div` y)
--               | otherwise = Nothing
--   
-- -- A definition of safeDiv using guard and Monad -- do-notation: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y = do
--     guard (y /= 0)
--     return (x `div` y)
--   
guard :: Alternative f => Bool -> f () -- | The join function is the conventional monad join operator. It -- is used to remove one level of monadic structure, projecting its bound -- argument into the outer level. -- --

Examples

-- -- A common use of join is to run an IO computation -- returned from an STM transaction, since STM transactions -- can't perform IO directly. Recall that -- --
--   atomically :: STM a -> IO a
--   
-- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
--   atomically :: STM (IO b) -> IO (IO b)
--   join       :: IO (IO b)  -> IO b
--   
-- -- we can compose them as -- --
--   join . atomically :: STM (IO b) -> IO b
--   
-- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- -- -- --
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y >= fromEnum x = maxBound
--             | otherwise                = minBound
--   
class Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- -- enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..] with [n,n'..] = -- enumFromThen n n', a possible implementation being -- enumFromThen n n' = n : n' : worker (f x) (f x n'), -- worker s v = v : worker s (s v), x = fromEnum n' - -- fromEnum n and f n y | n > 0 = f (n - 1) (succ y) | n < -- 0 = f (n + 1) (pred y) | otherwise = y For example: -- -- enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m] with [n..m] = -- enumFromTo n m, a possible implementation being enumFromTo n -- m | n <= m = n : enumFromTo (succ n) m | otherwise = []. For -- example: -- -- enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m] with [n,n'..m] -- = enumFromThenTo n n' m, a possible implementation being -- enumFromThenTo n n' m = worker (f x) (c x) n m, x = -- fromEnum n' - fromEnum n, c x = bool (>=) ((x -- 0) f n y | n > 0 = f (n - 1) (succ y) | n < 0 = f (n + -- 1) (pred y) | otherwise = y and worker s c v m | c v m = v : -- worker s c (s v) m | otherwise = [] For example: -- -- enumFromThenTo :: Enum a => a -> a -> a -> [a] -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- The Haskell Report defines no laws for Eq. However, == -- is customarily expected to implement an equivalence relationship where -- two values comparing equal are indistinguishable by "public" -- functions, with a "public" function being one not allowing to see -- implementation details. For example, for a type representing -- non-normalised natural numbers modulo 100, a "public" function doesn't -- make the difference between 1 and 201. It is expected to have the -- following properties: -- -- -- -- Minimal complete definition: either == or /=. class Eq a (==) :: Eq a => a -> a -> Bool (/=) :: Eq a => a -> a -> Bool infix 4 == infix 4 /= -- | Trigonometric and hyperbolic functions and related functions. -- -- The Haskell Report defines no laws for Floating. However, -- (+), (*) and exp are -- customarily expected to define an exponential field and have the -- following properties: -- -- class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a infixr 8 ** -- | Fractional numbers, supporting real division. -- -- The Haskell Report defines no laws for Fractional. However, -- (+) and (*) are customarily expected -- to define a division ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- Fractional implement a field. However, all instances in -- base do. class Num a => Fractional a -- | Fractional division. (/) :: Fractional a => a -> a -> a -- | Reciprocal fraction. recip :: Fractional a => a -> a -- | Conversion from a Rational (that is Ratio -- Integer). A floating literal stands for an application of -- fromRational to a value of type Rational, so such -- literals have type (Fractional a) => a. fromRational :: Fractional a => Rational -> a infixl 7 / -- | Integral numbers, supporting integer division. -- -- The Haskell Report defines no laws for Integral. However, -- Integral instances are customarily expected to define a -- Euclidean domain and have the following properties for the -- div/mod and quot/rem pairs, given suitable -- Euclidean functions f and g: -- -- -- -- An example of a suitable Euclidean function, for Integer's -- instance, is abs. class (Real a, Enum a) => Integral a -- | integer division truncated toward zero quot :: Integral a => a -> a -> a -- | integer remainder, satisfying -- --
--   (x `quot` y)*y + (x `rem` y) == x
--   
rem :: Integral a => a -> a -> a -- | integer division truncated toward negative infinity div :: Integral a => a -> a -> a -- | integer modulus, satisfying -- --
--   (x `div` y)*y + (x `mod` y) == x
--   
mod :: Integral a => a -> a -> a -- | simultaneous quot and rem quotRem :: Integral a => a -> a -> (a, a) -- | simultaneous div and mod divMod :: Integral a => a -> a -> (a, a) -- | conversion to Integer toInteger :: Integral a => a -> Integer infixl 7 `quot` infixl 7 `rem` infixl 7 `div` infixl 7 `mod` -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: Type -> Type) -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. class Functor (f :: Type -> Type) fmap :: Functor f => (a -> b) -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | Basic numeric class. -- -- The Haskell Report defines no laws for Num. However, -- (+) and (*) are customarily expected -- to define a ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- both Num and Ord implement an ordered ring. Indeed, in -- base only Integer and Rational do. class Num a (+) :: Num a => a -> a -> a (-) :: Num a => a -> a -> a (*) :: Num a => a -> a -> a -- | Unary negation. negate :: Num a => a -> a -- | Absolute value. abs :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | Conversion from an Integer. An integer literal represents the -- application of the function fromInteger to the appropriate -- value of type Integer, so such literals have type -- (Num a) => a. fromInteger :: Num a => Integer -> a infixl 6 + infixl 7 * infixl 6 - -- | The Ord class is used for totally ordered datatypes. -- -- Instances of Ord can be derived for any user-defined datatype -- whose constituent types are in Ord. The declared order of the -- constructors in the data declaration determines the ordering in -- derived Ord instances. The Ordering datatype allows a -- single comparison to determine the precise ordering of two objects. -- -- The Haskell Report defines no laws for Ord. However, -- <= is customarily expected to implement a non-strict partial -- order and have the following properties: -- -- -- -- Note that the following operator interactions are expected to hold: -- --
    --
  1. x >= y = y <= x
  2. --
  3. x < y = x <= y && x /= y
  4. --
  5. x > y = y < x
  6. --
  7. x < y = compare x y == LT
  8. --
  9. x > y = compare x y == GT
  10. --
  11. x == y = compare x y == EQ
  12. --
  13. min x y == if x <= y then x else y = True
  14. --
  15. max x y == if x >= y then x else y = True
  16. --
-- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering (<) :: Ord a => a -> a -> Bool (<=) :: Ord a => a -> a -> Bool (>) :: Ord a => a -> a -> Bool (>=) :: Ord a => a -> a -> Bool max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a infix 4 >= infix 4 > infix 4 <= infix 4 < -- | Parsing of Strings, producing values. -- -- Derived instances of Read make the following assumptions, which -- derived instances of Show obey: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readsPrec d r =  readParen (d > app_prec)
--                            (\r -> [(Leaf m,t) |
--                                    ("Leaf",s) <- lex r,
--                                    (m,t) <- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d > up_prec)
--                            (\r -> [(u:^:v,w) |
--                                    (u,s) <- readsPrec (up_prec+1) r,
--                                    (":^:",t) <- lex s,
--                                    (v,w) <- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   
-- -- Note that right-associativity of :^: is unused. -- -- The derived instance in GHC is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" <- lexP
--                                    m <- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u <- step readPrec
--                                    Symbol ":^:" <- lexP
--                                    v <- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   
-- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
--   instance Read T where
--     readPrec     = ...
--     readListPrec = readListPrecDefault
--   
class Read a class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- -- -- -- The default definitions of the ceiling, floor, -- truncate and round functions are in terms of -- properFraction. properFraction :: (RealFrac a, Integral b) => a -> (b, a) -- | truncate x returns the integer nearest x -- between zero and x truncate :: (RealFrac a, Integral b) => a -> b -- | round x returns the nearest integer to x; the -- even integer if x is equidistant between two integers round :: (RealFrac a, Integral b) => a -> b -- | ceiling x returns the least integer not less than -- x ceiling :: (RealFrac a, Integral b) => a -> b -- | floor x returns the greatest integer not greater than -- x floor :: (RealFrac a, Integral b) => a -> b -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Show is equivalent to -- --
--   instance (Show a) => Show (Tree a) where
--   
--          showsPrec d (Leaf m) = showParen (d > app_prec) $
--               showString "Leaf " . showsPrec (app_prec+1) m
--            where app_prec = 10
--   
--          showsPrec d (u :^: v) = showParen (d > up_prec) $
--               showsPrec (up_prec+1) u .
--               showString " :^: "      .
--               showsPrec (up_prec+1) v
--            where up_prec = 5
--   
-- -- Note that right-associativity of :^: is ignored. For example, -- -- class Show a -- | The class Typeable allows a concrete representation of a type -- to be calculated. class Typeable (a :: k) -- | When a value is bound in do-notation, the pattern on the left -- hand side of <- might not match. In this case, this class -- provides a function to recover. -- -- A Monad without a MonadFail instance may only be used in -- conjunction with pattern that always match, such as newtypes, tuples, -- data types with only a single data constructor, and irrefutable -- patterns (~pat). -- -- Instances of MonadFail should satisfy the following law: -- fail s should be a left zero for >>=, -- --
--   fail s >>= f  =  fail s
--   
-- -- If your Monad is also MonadPlus, a popular definition is -- --
--   fail _ = mzero
--   
class Monad m => MonadFail (m :: Type -> Type) fail :: MonadFail m => String -> m a -- | Class for string-like datastructures; used by the overloaded string -- extension (-XOverloadedStrings in GHC). class IsString a fromString :: IsString a => String -> a -- | A functor with application, providing operations to -- -- -- -- A minimal complete definition must include implementations of -- pure and of either <*> or liftA2. If it -- defines both, then they must behave the same as their default -- definitions: -- --
--   (<*>) = liftA2 id
--   
-- --
--   liftA2 f x y = f <$> x <*> y
--   
-- -- Further, any definition must satisfy the following: -- -- -- -- The other methods have the following default definitions, which may be -- overridden with equivalent specialized implementations: -- -- -- -- As a consequence of these laws, the Functor instance for -- f will satisfy -- -- -- -- It may be useful to note that supposing -- --
--   forall x y. p (q x y) = f x . g y
--   
-- -- it follows from the above that -- --
--   liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v
--   
-- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: Type -> Type) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: Applicative f => f (a -> b) -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. (*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <*> infixl 4 *> infixl 4 <* -- | Data structures that can be folded. -- -- For example, given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Foldable Tree where
--      foldMap f Empty = mempty
--      foldMap f (Leaf x) = f x
--      foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r
--   
-- -- This is suitable even for abstract types, as the monoid is assumed to -- satisfy the monoid laws. Alternatively, one could define -- foldr: -- --
--   instance Foldable Tree where
--      foldr f z Empty = z
--      foldr f z (Leaf x) = f x z
--      foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l
--   
-- -- Foldable instances are expected to satisfy the following -- laws: -- --
--   foldr f z t = appEndo (foldMap (Endo . f) t ) z
--   
-- --
--   foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
--   
-- --
--   fold = foldMap id
--   
-- --
--   length = getSum . foldMap (Sum . const  1)
--   
-- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
--   sum = getSum . foldMap Sum
--   
-- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
--   foldMap f = fold . fmap f
--   
-- -- which implies that -- --
--   foldMap f . fmap g = foldMap (f . g)
--   
class Foldable (t :: Type -> Type) -- | Functors representing data structures that can be traversed from left -- to right. -- -- A definition of traverse must satisfy the following laws: -- -- -- -- A definition of sequenceA must satisfy the following laws: -- -- -- -- where an applicative transformation is a function -- --
--   t :: (Applicative f, Applicative g) => f a -> g a
--   
-- -- preserving the Applicative operations, i.e. -- --
--   t (pure x) = pure x
--   t (f <*> x) = t f <*> t x
--   
-- -- and the identity functor Identity and composition functors -- Compose are from Data.Functor.Identity and -- Data.Functor.Compose. -- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to Functor, e.g. given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Traversable Tree where
--      traverse f Empty = pure Empty
--      traverse f (Leaf x) = Leaf <$> f x
--      traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
--   
-- -- This is suitable even for abstract types, as the laws for -- <*> imply a form of associativity. -- -- The superclass instances should satisfy the following: -- -- class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) -- | Evaluate each action in the structure from left to right, and collect -- the results. For a version that ignores the results see -- sequenceA_. sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class Generic a -- | This class gives the integer associated with a type-level natural. -- There are instances of the class for every concrete literal: 0, 1, 2, -- etc. class KnownNat (n :: Nat) class IsLabel (x :: Symbol) a fromLabel :: IsLabel x a => a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the following: -- -- class Semigroup a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in O(1) by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. stimes :: (Semigroup a, Integral b) => b -> a -> a infixr 6 <> -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = (<>) since -- base-4.11.0.0. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. mconcat :: Monoid a => [a] -> a data Bool False :: Bool True :: Bool -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data Char -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double D# :: Double# -> Double -- | Single-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- single-precision type. data Float F# :: Float# -> Float -- | A fixed-precision integer type with at least the range [-2^29 .. -- 2^29-1]. The exact range for a given implementation can be -- determined by using minBound and maxBound from the -- Bounded class. data Int -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | Invariant: Jn# and Jp# are used iff value doesn't fit in -- S# -- -- Useful properties resulting from the invariants: -- -- data Integer -- | Type representing arbitrary-precision non-negative integers. -- --
--   >>> 2^100 :: Natural
--   1267650600228229401496703205376
--   
-- -- Operations whose result would be negative throw -- (Underflow :: ArithException), -- --
--   >>> -1 :: Natural
--   *** Exception: arithmetic underflow
--   
data Natural -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | Rational numbers, with numerator and denominator of some -- Integral type. -- -- Note that Ratio's instances inherit the deficiencies from the -- type parameter's. For example, Ratio Natural's Num -- instance has similar problems to Natural's. data Ratio a (:%) :: !a -> !a -> Ratio a -- | Arbitrary-precision rational numbers, represented as a ratio of two -- Integer values. A rational number may be constructed using the -- % operator. type Rational = Ratio Integer -- | A value of type IO a is a computation which, when -- performed, does some I/O before returning a value of type a. -- -- There is really only one way to "perform" an I/O action: bind it to -- Main.main in your program. When your program is run, the I/O -- will be performed. It isn't possible to perform I/O from an arbitrary -- function, unless that function is itself in the IO monad and -- called at some point, directly or indirectly, from Main.main. -- -- IO is a monad, so IO actions can be combined using -- either the do-notation or the >> and >>= -- operations from the Monad class. data IO a -- | A Word is an unsigned integral type, with the same size as -- Int. data Word -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 -- | A value of type Ptr a represents a pointer to an -- object, or an array of objects, which may be marshalled to or from -- Haskell values of type a. -- -- The type a will often be an instance of class Storable -- which provides the marshalling operations. However this is not -- essential, and you can provide your own operations to access the -- pointer. For example you might write small foreign functions to get or -- set the fields of a C struct. data Ptr a -- | A value of type FunPtr a is a pointer to a function -- callable from foreign code. The type a will normally be a -- foreign type, a function type with zero or more arguments where -- -- -- -- A value of type FunPtr a may be a pointer to a foreign -- function, either returned by another foreign function or imported with -- a a static address import like -- --
--   foreign import ccall "stdlib.h &free"
--     p_free :: FunPtr (Ptr a -> IO ())
--   
-- -- or a pointer to a Haskell function created using a wrapper stub -- declared to produce a FunPtr of the correct type. For example: -- --
--   type Compare = Int -> Int -> Bool
--   foreign import ccall "wrapper"
--     mkCompare :: Compare -> IO (FunPtr Compare)
--   
-- -- Calls to wrapper stubs like mkCompare allocate storage, which -- should be released with freeHaskellFunPtr when no longer -- required. -- -- To convert FunPtr values to corresponding Haskell functions, -- one can define a dynamic stub for the specific foreign type, -- e.g. -- --
--   type IntFunction = CInt -> IO ()
--   foreign import ccall "dynamic"
--     mkFun :: FunPtr IntFunction -> IntFunction
--   
data FunPtr a -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --

Examples

-- -- The type Either String Int is the type -- of values which can be either a String or an Int. The -- Left constructor can be used only on Strings, and the -- Right constructor can be used only on Ints: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> s
--   Left "foo"
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> n
--   Right 3
--   
--   >>> :type s
--   s :: Either String Int
--   
--   >>> :type n
--   n :: Either String Int
--   
-- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> fmap (*2) s
--   Left "foo"
--   
--   >>> fmap (*2) n
--   Right 6
--   
-- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
--   >>> import Data.Char ( digitToInt, isDigit )
--   
--   >>> :{
--       let parseEither :: Char -> Either String Int
--           parseEither c
--             | isDigit c = Right (digitToInt c)
--             | otherwise = Left "parse error"
--   
--   >>> :}
--   
-- -- The following should work, since both '1' and '2' -- can be parsed as Ints. -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither '1'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Right 3
--   
-- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither 'm'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Left "parse error"
--   
data Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The kind of constraints, like Show a data Constraint -- | Comparison of type-level naturals, as a function. type family CmpNat (a :: Nat) (b :: Nat) :: Ordering -- | Coercible is a two-parameter class that has instances for -- types a and b if the compiler can infer that they -- have the same representation. This class does not have regular -- instances; instead they are created on-the-fly during type-checking. -- Trying to manually declare an instance of Coercible is an -- error. -- -- Nevertheless one can pretend that the following three kinds of -- instances exist. First, as a trivial base-case: -- --
--   instance Coercible a a
--   
-- -- Furthermore, for every type constructor there is an instance that -- allows to coerce under the type constructor. For example, let -- D be a prototypical type constructor (data or -- newtype) with three type arguments, which have roles -- nominal, representational resp. phantom. -- Then there is an instance of the form -- --
--   instance Coercible b b' => Coercible (D a b c) (D a b' c')
--   
-- -- Note that the nominal type arguments are equal, the -- representational type arguments can differ, but need to have -- a Coercible instance themself, and the phantom type -- arguments can be changed arbitrarily. -- -- The third kind of instance exists for every newtype NT = MkNT -- T and comes in two variants, namely -- --
--   instance Coercible a T => Coercible a NT
--   
-- --
--   instance Coercible T b => Coercible NT b
--   
-- -- This instance is only usable if the constructor MkNT is in -- scope. -- -- If, as a library author of a type constructor like Set a, you -- want to prevent a user of your module to write coerce :: Set T -- -> Set NT, you need to set the role of Set's type -- parameter to nominal, by writing -- --
--   type role Set nominal
--   
-- -- For more details about this feature, please refer to Safe -- Coercions by Joachim Breitner, Richard A. Eisenberg, Simon Peyton -- Jones and Stephanie Weirich. class a ~R# b => Coercible (a :: k) (b :: k) -- | CallStacks are a lightweight method of obtaining a partial -- call-stack at any point in the program. -- -- A function can request its call-site with the HasCallStack -- constraint. For example, we can define -- --
--   putStrLnWithCallStack :: HasCallStack => String -> IO ()
--   
-- -- as a variant of putStrLn that will get its call-site and -- print it, along with the string given as argument. We can access the -- call-stack inside putStrLnWithCallStack with -- callStack. -- --
--   putStrLnWithCallStack :: HasCallStack => String -> IO ()
--   putStrLnWithCallStack msg = do
--     putStrLn msg
--     putStrLn (prettyCallStack callStack)
--   
-- -- Thus, if we call putStrLnWithCallStack we will get a -- formatted call-stack alongside our string. -- --
--   >>> putStrLnWithCallStack "hello"
--   hello
--   CallStack (from HasCallStack):
--     putStrLnWithCallStack, called at <interactive>:2:1 in interactive:Ghci1
--   
-- -- GHC solves HasCallStack constraints in three steps: -- --
    --
  1. If there is a CallStack in scope -- i.e. the enclosing -- function has a HasCallStack constraint -- GHC will append the -- new call-site to the existing CallStack.
  2. --
  3. If there is no CallStack in scope -- e.g. in the GHCi -- session above -- and the enclosing definition does not have an -- explicit type signature, GHC will infer a HasCallStack -- constraint for the enclosing definition (subject to the monomorphism -- restriction).
  4. --
  5. If there is no CallStack in scope and the enclosing -- definition has an explicit type signature, GHC will solve the -- HasCallStack constraint for the singleton CallStack -- containing just the current call-site.
  6. --
-- -- CallStacks do not interact with the RTS and do not require -- compilation with -prof. On the other hand, as they are built -- up explicitly via the HasCallStack constraints, they will -- generally not contain as much information as the simulated call-stacks -- maintained by the RTS. -- -- A CallStack is a [(String, SrcLoc)]. The -- String is the name of function that was called, the -- SrcLoc is the call-site. The list is ordered with the most -- recently called function at the head. -- -- NOTE: The intrepid user may notice that HasCallStack is just an -- alias for an implicit parameter ?callStack :: CallStack. This -- is an implementation detail and should not be considered part -- of the CallStack API, we may decide to change the -- implementation in the future. data CallStack -- | Haskell defines operations to read and write characters from and to -- files, represented by values of type Handle. Each value of -- this type is a handle: a record used by the Haskell run-time -- system to manage I/O with file system objects. A handle has at -- least the following properties: -- -- -- -- Most handles will also have a current I/O position indicating where -- the next input or output operation will occur. A handle is -- readable if it manages only input or both input and output; -- likewise, it is writable if it manages only output or both -- input and output. A handle is open when first allocated. Once -- it is closed it can no longer be used for either input or output, -- though an implementation cannot re-use its storage while references -- remain to it. Handles are in the Show and Eq classes. -- The string produced by showing a handle is system dependent; it should -- include enough information to identify the handle for debugging. A -- handle is equal according to == only to itself; no attempt is -- made to compare the internal state of different handles for equality. data Handle -- | Right-to-left composition of functors. The composition of applicative -- functors is always applicative, but the composition of monads is not -- always a monad. newtype Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) Compose :: f (g a) -> Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) [getCompose] :: Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) -> f (g a) infixr 9 `Compose` infixr 9 `Compose` -- | If Void is uninhabited then any Functor that holds only -- values of type Void is holding no values. vacuous :: Functor f => f Void -> f a -- | Since Void values logically don't exist, this witnesses the -- logical reasoning tool of "ex falso quodlibet". -- --
--   >>> let x :: Either Void Int; x = Right 5
--   
--   >>> :{
--   case x of
--       Right r -> r
--       Left l  -> absurd l
--   :}
--   5
--   
absurd :: Void -> a -- | Uninhabited data type data Void -- | Repeat a value n times. -- --
--   mtimesDefault n a = a <> a <> ... <> a  -- using <> (n-1) times
--   
-- -- Implemented using stimes and mempty. -- -- This is a suitable definition for an mtimes member of -- Monoid. mtimesDefault :: (Integral b, Monoid a) => b -> a -> a -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | Provide a Semigroup for an arbitrary Monoid. -- -- NOTE: This is not needed anymore since Semigroup became -- a superclass of Monoid in base-4.11 and this newtype be -- deprecated at some point in the future. data WrappedMonoid m -- | Option is effectively Maybe with a better instance of -- Monoid, built off of an underlying Semigroup instead of -- an underlying Monoid. -- -- Ideally, this type would not exist at all and we would just fix the -- Monoid instance of Maybe. -- -- In GHC 8.4 and higher, the Monoid instance for Maybe has -- been corrected to lift a Semigroup instance instead of a -- Monoid instance. Consequently, this type is no longer useful. -- It will be marked deprecated in GHC 8.8 and removed in GHC 8.10. newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | The sortWith function sorts a list of elements using the user -- supplied function to project something out of each element sortWith :: Ord b => (a -> b) -> [a] -> [a] -- | A bifunctor is a type constructor that takes two type arguments and is -- a functor in both arguments. That is, unlike with -- Functor, a type constructor such as Either does not need -- to be partially applied for a Bifunctor instance, and the -- methods in this class permit mapping functions over the Left -- value or the Right value, or both at the same time. -- -- Formally, the class Bifunctor represents a bifunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where both the first and second -- arguments are covariant. -- -- You can define a Bifunctor by either defining bimap or -- by defining both first and second. -- -- If you supply bimap, you should ensure that: -- --
--   bimap id idid
--   
-- -- If you supply first and second, ensure: -- --
--   first idid
--   second idid
--   
-- -- If you supply both, you should also ensure: -- --
--   bimap f g ≡ first f . second g
--   
-- -- These ensure by parametricity: -- --
--   bimap  (f . g) (h . i) ≡ bimap f h . bimap g i
--   first  (f . g) ≡ first  f . first  g
--   second (f . g) ≡ second f . second g
--   
class Bifunctor (p :: Type -> Type -> Type) -- | Map over both arguments at the same time. -- --
--   bimap f g ≡ first f . second g
--   
-- --

Examples

-- --
--   >>> bimap toUpper (+1) ('j', 3)
--   ('J',4)
--   
-- --
--   >>> bimap toUpper (+1) (Left 'j')
--   Left 'J'
--   
-- --
--   >>> bimap toUpper (+1) (Right 3)
--   Right 4
--   
bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d -- | Map covariantly over the first argument. -- --
--   first f ≡ bimap f id
--   
-- --

Examples

-- --
--   >>> first toUpper ('j', 3)
--   ('J',3)
--   
-- --
--   >>> first toUpper (Left 'j')
--   Left 'J'
--   
first :: Bifunctor p => (a -> b) -> p a c -> p b c -- | Map covariantly over the second argument. -- --
--   secondbimap id
--   
-- --

Examples

-- --
--   >>> second (+1) ('j', 3)
--   ('j',4)
--   
-- --
--   >>> second (+1) (Right 3)
--   Right 4
--   
second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | Extract everything except the last element of the stream. init :: NonEmpty a -> [a] -- | Extract the last element of the stream. last :: NonEmpty a -> a -- | Extract the possibly-empty tail of the stream. tail :: NonEmpty a -> [a] -- | Extract the first element of the stream. head :: NonEmpty a -> a -- | nonEmpty efficiently turns a normal list into a NonEmpty -- stream, producing Nothing if the input is empty. nonEmpty :: [a] -> Maybe (NonEmpty a) -- | Get a string representation of the current execution stack state. showStackTrace :: IO (Maybe String) -- | Get a trace of the current execution stack state. -- -- Returns Nothing if stack trace support isn't available on -- host machine. getStackTrace :: IO (Maybe [Location]) -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | Direct MonadPlus equivalent of filter. -- --

Examples

-- -- The filter function is just mfilter specialized to the -- list monad: -- --
--   filter = ( mfilter :: (a -> Bool) -> [a] -> [a] )
--   
-- -- An example using mfilter with the Maybe monad: -- --
--   >>> mfilter odd (Just 1)
--   Just 1
--   >>> mfilter odd (Just 2)
--   Nothing
--   
mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | The foldM function is analogous to foldl, except that -- its result is encapsulated in a monad. Note that foldM works -- from left-to-right over the list arguments. This could be an issue -- where (>>) and the `folded function' are not -- commutative. -- --
--   foldM f a1 [x1, x2, ..., xm]
--   
--   ==
--   
--   do
--     a2 <- f a1 x1
--     a3 <- f a2 x2
--     ...
--     f am xm
--   
-- -- If right-to-left evaluation is required, the input list should be -- reversed. -- -- Note: foldM is the same as foldlM foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | The mapAndUnzipM function maps its first argument over a list, -- returning the result as a pair of lists. This function is mainly used -- with complicated data structures or a state monad. mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c]) -- | Repeat an action indefinitely. -- --

Examples

-- -- A common use of forever is to process input from network -- sockets, Handles, and channels (e.g. MVar and -- Chan). -- -- For example, here is how we might implement an echo server, -- using forever both to listen for client connections on a -- network socket and to echo client input on client connection handles: -- --
--   echoServer :: Socket -> IO ()
--   echoServer socket = forever $ do
--     client <- accept socket
--     forkFinally (echo client) (\_ -> hClose client)
--     where
--       echo :: Handle -> IO ()
--       echo client = forever $
--         hGetLine client >>= hPutStrLn client
--   
forever :: Applicative f => f a -> f b -- | Right-to-left composition of Kleisli arrows. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
--   (.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
--   (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
--   
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 <=< -- | Left-to-right composition of Kleisli arrows. (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element of -- a structure, passing an accumulating parameter from left to right, and -- returning a final value of this accumulator together with the new -- structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | One or none. optional :: Alternative f => f a -> f (Maybe a) -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | Fanout: send the input to both argument arrows and combine their -- output. -- -- The default definition may be overridden with a more efficient version -- if desired. (&&&) :: Arrow a => a b c -> a b c' -> a b (c, c') infixr 3 &&& -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | A handle managing output to the Haskell program's standard error -- channel. stderr :: Handle -- | A handle managing input from the Haskell program's standard input -- channel. stdin :: Handle -- | Perform some computation without adding new entries to the -- CallStack. withFrozenCallStack :: HasCallStack => (HasCallStack => a) -> a -- | Return the current CallStack. -- -- Does *not* include the call-site of callStack. callStack :: HasCallStack => CallStack -- | Write the supplied value into a TVar. writeTVar :: TVar a -> a -> STM () -- | Return the current value stored in a TVar. readTVar :: TVar a -> STM a -- | Create a new TVar holding a value supplied newTVar :: a -> STM (TVar a) -- | A monad supporting atomic memory transactions. data STM a -- | Shared memory locations that support atomic memory transactions. data TVar a -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | A mutable variable in the IO monad data IORef a -- | File and directory names are values of type String, whose -- precise meaning is operating system dependent. Files can be opened, -- yielding a handle which can then be used to operate on the contents of -- that file. type FilePath = String -- | Pretty print a CallStack. prettyCallStack :: CallStack -> String -- | Pretty print a SrcLoc. prettySrcLoc :: SrcLoc -> String -- | Any type that you wish to throw or catch as an exception must be an -- instance of the Exception class. The simplest case is a new -- exception type directly below the root: -- --
--   data MyException = ThisException | ThatException
--       deriving Show
--   
--   instance Exception MyException
--   
-- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
--   *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
--   Caught ThisException
--   
-- -- In more complicated examples, you may wish to define a whole hierarchy -- of exceptions: -- --
--   ---------------------------------------------------------------------
--   -- Make the root exception type for all the exceptions in a compiler
--   
--   data SomeCompilerException = forall e . Exception e => SomeCompilerException e
--   
--   instance Show SomeCompilerException where
--       show (SomeCompilerException e) = show e
--   
--   instance Exception SomeCompilerException
--   
--   compilerExceptionToException :: Exception e => e -> SomeException
--   compilerExceptionToException = toException . SomeCompilerException
--   
--   compilerExceptionFromException :: Exception e => SomeException -> Maybe e
--   compilerExceptionFromException x = do
--       SomeCompilerException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make a subhierarchy for exceptions in the frontend of the compiler
--   
--   data SomeFrontendException = forall e . Exception e => SomeFrontendException e
--   
--   instance Show SomeFrontendException where
--       show (SomeFrontendException e) = show e
--   
--   instance Exception SomeFrontendException where
--       toException = compilerExceptionToException
--       fromException = compilerExceptionFromException
--   
--   frontendExceptionToException :: Exception e => e -> SomeException
--   frontendExceptionToException = toException . SomeFrontendException
--   
--   frontendExceptionFromException :: Exception e => SomeException -> Maybe e
--   frontendExceptionFromException x = do
--       SomeFrontendException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make an exception type for a particular frontend compiler exception
--   
--   data MismatchedParentheses = MismatchedParentheses
--       deriving Show
--   
--   instance Exception MismatchedParentheses where
--       toException   = frontendExceptionToException
--       fromException = frontendExceptionFromException
--   
-- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
--   *** Exception: MismatchedParentheses
--   
class (Typeable e, Show e) => Exception e toException :: Exception e => e -> SomeException fromException :: Exception e => SomeException -> Maybe e -- | Render this exception value in a human-friendly manner. -- -- Default implementation: show. displayException :: Exception e => e -> String -- | The Const functor. newtype Const a (b :: k) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | The least element of a non-empty structure with respect to the given -- comparison function. minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | The concatenation of all the elements of a container of lists. concat :: Foldable t => t [a] -> [a] -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | Maybe monoid returning the leftmost non-Nothing value. -- -- First a is isomorphic to Alt Maybe -- a, but precedes it historically. -- --
--   >>> getFirst (First (Just "hello") <> First Nothing <> First (Just "world"))
--   Just "hello"
--   
-- -- Use of this type is discouraged. Note the following equivalence: -- --
--   Data.Monoid.First x === Maybe (Data.Semigroup.First x)
--   
-- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
--   >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world"))
--   Just "world"
--   
-- -- Use of this type is discouraged. Note the following equivalence: -- --
--   Data.Monoid.Last x === Maybe (Data.Semigroup.Last x)
--   
-- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n). stimesIdempotent :: Integral b => b -> a -> a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
--   >>> getDual (mappend (Dual "Hello") (Dual "World"))
--   "WorldHello"
--   
newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | The monoid of endomorphisms under composition. -- --
--   >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--   
--   >>> appEndo computation "Haskell"
--   "Hello, Haskell!"
--   
newtype Endo a Endo :: (a -> a) -> Endo a [appEndo] :: Endo a -> a -> a -- | Boolean monoid under conjunction (&&). -- --
--   >>> getAll (All True <> mempty <> All False)
--   False
--   
-- --
--   >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8]))
--   False
--   
newtype All All :: Bool -> All [getAll] :: All -> Bool -- | Boolean monoid under disjunction (||). -- --
--   >>> getAny (Any True <> mempty <> Any False)
--   True
--   
-- --
--   >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8]))
--   True
--   
newtype Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | Monoid under addition. -- --
--   >>> getSum (Sum 1 <> Sum 2 <> mempty)
--   3
--   
newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
--   >>> getProduct (Product 3 <> Product 4 <> mempty)
--   12
--   
newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | Monoid under <|>. newtype Alt (f :: k -> Type) (a :: k) Alt :: f a -> Alt (f :: k -> Type) (a :: k) [getAlt] :: Alt (f :: k -> Type) (a :: k) -> f a -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: forall (n :: Nat) proxy. KnownNat n => proxy n -> Natural -- | This type represents unknown type-level natural numbers. data SomeNat SomeNat :: Proxy n -> SomeNat -- | The unfoldr function is a `dual' to foldr: while -- foldr reduces a list to a summary value, unfoldr builds -- a list from a seed value. The function takes the element and returns -- Nothing if it is done producing the list or returns Just -- (a,b), in which case, a is a prepended to the list -- and b is used as the next element in a recursive call. For -- example, -- --
--   iterate f == unfoldr (\x -> Just (x, f x))
--   
-- -- In some cases, unfoldr can undo a foldr operation: -- --
--   unfoldr f' (foldr f z xs) == xs
--   
-- -- if the following holds: -- --
--   f' (f x y) = Just (x,y)
--   f' z       = Nothing
--   
-- -- A simple use of unfoldr: -- --
--   >>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
--   [10,9,8,7,6,5,4,3,2,1]
--   
unfoldr :: (b -> Maybe (a, b)) -> b -> [a] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
--   >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | The sortBy function is the non-overloaded version of -- sort. -- --
--   >>> sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortBy :: (a -> a -> Ordering) -> [a] -> [a] -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
--   >>> sort [1,6,4,3,2,5]
--   [1,2,3,4,5,6]
--   
sort :: Ord a => [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
--   >>> permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   
permutations :: [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
--   >>> subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   
subsequences :: [a] -> [[a]] -- | O(n). The tails function returns all final segments of -- the argument, longest first. For example, -- --
--   >>> tails "abc"
--   ["abc","bc","c",""]
--   
-- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: [a] -> [[a]] -- | The inits function returns all initial segments of the -- argument, shortest first. For example, -- --
--   >>> inits "abc"
--   ["","a","ab","abc"]
--   
-- -- Note that inits has the following strictness property: -- inits (xs ++ _|_) = inits xs ++ _|_ -- -- In particular, inits _|_ = [] : _|_ inits :: [a] -> [[a]] -- | The group function takes a list and returns a list of lists -- such that the concatenation of the result is equal to the argument. -- Moreover, each sublist in the result contains only equal elements. For -- example, -- --
--   >>> group "Mississippi"
--   ["M","i","ss","i","ss","i","pp","i"]
--   
-- -- It is a special case of groupBy, which allows the programmer to -- supply their own equality test. group :: Eq a => [a] -> [[a]] -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericDrop function is an overloaded version of -- drop, which accepts any Integral value as the number of -- elements to drop. genericDrop :: Integral i => i -> [a] -> [a] -- | The genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | O(n). The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The transpose function transposes the rows and columns of its -- argument. For example, -- --
--   >>> transpose [[1,2,3],[4,5,6]]
--   [[1,4],[2,5],[3,6]]
--   
-- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
--   >>> transpose [[10,11],[20],[],[30,31,32]]
--   [[10,20,30],[11,31],[32]]
--   
transpose :: [[a]] -> [[a]] -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
--   >>> intercalate ", " ["Lorem", "ipsum", "dolor"]
--   "Lorem, ipsum, dolor"
--   
intercalate :: [a] -> [[a]] -> [a] -- | O(n). The intersperse function takes an element and a -- list and `intersperses' that element between the elements of the list. -- For example, -- --
--   >>> intersperse ',' "abcde"
--   "a,b,c,d,e"
--   
intersperse :: a -> [a] -> [a] -- | O(min(m,n)). The isPrefixOf function takes two lists and -- returns True iff the first list is a prefix of the second. -- --
--   >>> "Hello" `isPrefixOf` "Hello World!"
--   True
--   
-- --
--   >>> "Hello" `isPrefixOf` "Wello Horld!"
--   False
--   
isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. -- --
--   >>> readMaybe "123" :: Maybe Int
--   Just 123
--   
-- --
--   >>> readMaybe "hello" :: Maybe Int
--   Nothing
--   
readMaybe :: Read a => String -> Maybe a -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | Return True if the given value is a Right-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> isRight (Left "foo")
--   False
--   
--   >>> isRight (Right 3)
--   True
--   
-- -- Assuming a Left value signifies some sort of error, we can use -- isRight to write a very simple reporting function that only -- outputs "SUCCESS" when a computation has succeeded. -- -- This example shows how isRight might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
--   >>> import Control.Monad ( when )
--   
--   >>> let report e = when (isRight e) $ putStrLn "SUCCESS"
--   
--   >>> report (Left "parse error")
--   
--   >>> report (Right 1)
--   SUCCESS
--   
isRight :: Either a b -> Bool -- | Return True if the given value is a Left-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> isLeft (Left "foo")
--   True
--   
--   >>> isLeft (Right 3)
--   False
--   
-- -- Assuming a Left value signifies some sort of error, we can use -- isLeft to write a very simple error-reporting function that -- does absolutely nothing in the case of success, and outputs "ERROR" if -- any error occurred. -- -- This example shows how isLeft might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
--   >>> import Control.Monad ( when )
--   
--   >>> let report e = when (isLeft e) $ putStrLn "ERROR"
--   
--   >>> report (Right 1)
--   
--   >>> report (Left "parse error")
--   ERROR
--   
isLeft :: Either a b -> Bool -- | Partitions a list of Either into two lists. All the Left -- elements are extracted, in order, to the first component of the -- output. Similarly the Right elements are extracted to the -- second component of the output. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list
--   (["foo","bar","baz"],[3,7])
--   
-- -- The pair returned by partitionEithers x should be the -- same pair as (lefts x, rights x): -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list == (lefts list, rights list)
--   True
--   
partitionEithers :: [Either a b] -> ([a], [b]) -- | Extracts from a list of Either all the Right elements. -- All the Right elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> rights list
--   [3,7]
--   
rights :: [Either a b] -> [b] -- | Extracts from a list of Either all the Left elements. -- All the Left elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> lefts list
--   ["foo","bar","baz"]
--   
lefts :: [Either a b] -> [a] -- | Case analysis for the Either type. If the value is -- Left a, apply the first function to a; if it -- is Right b, apply the second function to b. -- --

Examples

-- -- We create two values of type Either String -- Int, one using the Left constructor and another -- using the Right constructor. Then we apply "either" the -- length function (if we have a String) or the "times-two" -- function (if we have an Int): -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> either length (*2) s
--   3
--   
--   >>> either length (*2) n
--   6
--   
either :: (a -> c) -> (b -> c) -> Either a b -> c -- |
--   comparing p x y = compare (p x) (p y)
--   
-- -- Useful combinator for use in conjunction with the xxxBy -- family of functions from Data.List, for example: -- --
--   ... sortBy (comparing fst) ...
--   
comparing :: Ord a => (b -> a) -> b -> b -> Ordering -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). If a has -- an Ord instance associated with it then comparing two -- values thus wrapped will give you the opposite of their normal sort -- order. This is particularly useful when sorting in generalised list -- comprehensions, as in: then sortWith by Down x newtype Down a Down :: a -> Down a -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the undefined :: a idiom. -- --
--   >>> Proxy :: Proxy (Void, Int -> Int)
--   Proxy
--   
-- -- Proxy can even hold types of higher kinds, -- --
--   >>> Proxy :: Proxy Either
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy Functor
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy complicatedStructure
--   Proxy
--   
data Proxy (t :: k) Proxy :: Proxy (t :: k) -- | See openFile data IOMode ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Swap bytes in Word16. byteSwap16 :: Word16 -> Word16 -- | Bitwise "xor" xor :: Bits a => a -> a -> a infixl 6 `xor` integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFrom :: (Integral a, Bounded a) => a -> [a] gcdWord' :: Word -> Word -> Word gcdInt' :: Int -> Int -> Int -- | lcm x y is the smallest positive integer that both -- x and y divide. lcm :: Integral a => a -> a -> a -- | gcd x y is the non-negative factor of both x -- and y of which every common factor of x and -- y is also a factor; for example gcd 4 2 = 2, -- gcd (-4) 6 = 2, gcd 0 4 = 4. -- gcd 0 0 = 0. (That is, the common divisor -- that is "greatest" in the divisibility preordering.) -- -- Note: Since for signed fixed-width integer types, abs -- minBound < 0, the result may be negative if one of the -- arguments is minBound (and necessarily is if the other -- is 0 or minBound) for such types. gcd :: Integral a => a -> a -> a (^^%^^) :: Integral a => Rational -> a -> Rational (^%^) :: Integral a => Rational -> a -> Rational -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ -- | raise a number to a non-negative integral power (^) :: (Num a, Integral b) => a -> b -> a infixr 8 ^ odd :: Integral a => a -> Bool even :: Integral a => a -> Bool numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThen :: Fractional a => a -> a -> [a] numericEnumFrom :: Fractional a => a -> [a] -- | Extract the denominator of the ratio in reduced form: the numerator -- and denominator have no common factor and the denominator is positive. denominator :: Ratio a -> a -- | Extract the numerator of the ratio in reduced form: the numerator and -- denominator have no common factor and the denominator is positive. numerator :: Ratio a -> a -- | reduce is a subsidiary function used only in this module. It -- normalises a ratio by dividing both numerator and denominator by their -- greatest common divisor. reduce :: Integral a => a -> a -> Ratio a notANumber :: Rational infinity :: Rational ratioPrec1 :: Int ratioPrec :: Int underflowError :: a overflowError :: a ratioZeroDenominatorError :: a divZeroError :: a boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. unzip3 :: [(a, b, c)] -> ([a], [b], [c]) -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. unzip :: [(a, b)] -> ([a], [b]) -- | O(min(m,n)). zipWith generalises zip by zipping -- with the function given as the first argument, instead of a tupling -- function. For example, zipWith (+) is applied to two -- lists to produce the list of corresponding sums: -- --
--   >>> zipWith (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   zipWith f [] _|_ = []
--   
-- -- zipWith is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. It is capable of list fusion, but it is restricted to -- its first list argument and its resulting list. zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: [a] -> [a] -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
--   break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
--   break (< 9) [1,2,3] == ([],[1,2,3])
--   break (> 9) [1,2,3] == ([1,2,3],[])
--   
-- -- break p is equivalent to span (not . -- p). break :: (a -> Bool) -> [a] -> ([a], [a]) -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
--   splitAt 6 "Hello World!" == ("Hello ","World!")
--   splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
--   splitAt 1 [1,2,3] == ([1],[2,3])
--   splitAt 3 [1,2,3] == ([1,2,3],[])
--   splitAt 4 [1,2,3] == ([1,2,3],[])
--   splitAt 0 [1,2,3] == ([],[1,2,3])
--   splitAt (-1) [1,2,3] == ([],[1,2,3])
--   
-- -- It is equivalent to (take n xs, drop n xs) when -- n is not _|_ (splitAt _|_ xs = _|_). -- splitAt is an instance of the more general -- genericSplitAt, in which n may be of any integral -- type. splitAt :: Int -> [a] -> ([a], [a]) -- | drop n xs returns the suffix of xs after the -- first n elements, or [] if n > length -- xs: -- --
--   drop 6 "Hello World!" == "World!"
--   drop 3 [1,2,3,4,5] == [4,5]
--   drop 3 [1,2] == []
--   drop 3 [] == []
--   drop (-1) [1,2] == [1,2]
--   drop 0 [1,2] == [1,2]
--   
-- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: Int -> [a] -> [a] -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n > length xs: -- --
--   take 5 "Hello World!" == "Hello"
--   take 3 [1,2,3,4,5] == [1,2,3]
--   take 3 [1,2] == [1,2]
--   take 3 [] == []
--   take (-1) [1,2] == []
--   take 0 [1,2] == []
--   
-- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs: -- --
--   dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
--   dropWhile (< 9) [1,2,3] == []
--   dropWhile (< 0) [1,2,3] == [1,2,3]
--   
dropWhile :: (a -> Bool) -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p: -- --
--   takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
--   takeWhile (< 9) [1,2,3] == [1,2,3]
--   takeWhile (< 0) [1,2,3] == []
--   
takeWhile :: (a -> Bool) -> [a] -> [a] -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. cycle :: [a] -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. replicate :: Int -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. repeat :: a -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
--   iterate f x == [x, f x, f (f x), ...]
--   
-- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See -- iterate' for a strict variant of this function. iterate :: (a -> a) -> a -> [a] -- | O(n). scanr is the right-to-left dual of scanl. -- Note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
scanr :: (a -> b -> b) -> b -> [a] -> [b] -- | O(n). scanl is similar to foldl, but returns a -- list of successive reduced values from the left: -- --
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   
-- -- Note that -- --
--   last (scanl f z xs) == foldl f z xs.
--   
scanl :: (b -> a -> b) -> b -> [a] -> [b] -- | The mapMaybe function is a version of map which can -- throw out elements. In particular, the functional argument returns -- something of type Maybe b. If this is Nothing, -- no element is added on to the result list. If it is Just -- b, then b is included in the result list. -- --

Examples

-- -- Using mapMaybe f x is a shortcut for -- catMaybes $ map f x in most cases: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> let readMaybeInt = readMaybe :: String -> Maybe Int
--   
--   >>> mapMaybe readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
--   >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
-- -- If we map the Just constructor, the entire list should be -- returned: -- --
--   >>> mapMaybe Just [1,2,3]
--   [1,2,3]
--   
mapMaybe :: (a -> Maybe b) -> [a] -> [b] -- | The catMaybes function takes a list of Maybes and -- returns a list of all the Just values. -- --

Examples

-- -- Basic usage: -- --
--   >>> catMaybes [Just 1, Nothing, Just 3]
--   [1,3]
--   
-- -- When constructing a list of Maybe values, catMaybes can -- be used to return all of the "success" results (if the list is the -- result of a map, then mapMaybe would be more -- appropriate): -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [Just 1,Nothing,Just 3]
--   
--   >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [1,3]
--   
catMaybes :: [Maybe a] -> [a] -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --

Examples

-- -- Basic usage: -- --
--   >>> listToMaybe []
--   Nothing
--   
-- --
--   >>> listToMaybe [9]
--   Just 9
--   
-- --
--   >>> listToMaybe [1,2,3]
--   Just 1
--   
-- -- Composing maybeToList with listToMaybe should be the -- identity on singleton/empty lists: -- --
--   >>> maybeToList $ listToMaybe [5]
--   [5]
--   
--   >>> maybeToList $ listToMaybe []
--   []
--   
-- -- But not on lists with more than one element: -- --
--   >>> maybeToList $ listToMaybe [1,2,3]
--   [1]
--   
listToMaybe :: [a] -> Maybe a -- | The maybeToList function returns an empty list when given -- Nothing or a singleton list when given Just. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: Maybe a -> [a] -- | The fromMaybe function takes a default value and and -- Maybe value. If the Maybe is Nothing, it returns -- the default values; otherwise, it returns the value contained in the -- Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: a -> Maybe a -> a -- | The isNothing function returns True iff its argument is -- Nothing. -- --

Examples

-- -- Basic usage: -- --
--   >>> isNothing (Just 3)
--   False
--   
-- --
--   >>> isNothing (Just ())
--   False
--   
-- --
--   >>> isNothing Nothing
--   True
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isNothing (Just Nothing)
--   False
--   
isNothing :: Maybe a -> Bool -- | The isJust function returns True iff its argument is of -- the form Just _. -- --

Examples

-- -- Basic usage: -- --
--   >>> isJust (Just 3)
--   True
--   
-- --
--   >>> isJust (Just ())
--   True
--   
-- --
--   >>> isJust Nothing
--   False
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isJust (Just Nothing)
--   True
--   
isJust :: Maybe a -> Bool -- | The maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybe False odd (Just 3)
--   True
--   
-- --
--   >>> maybe False odd Nothing
--   False
--   
-- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> maybe 0 (*2) (readMaybe "5")
--   10
--   
--   >>> maybe 0 (*2) (readMaybe "")
--   0
--   
-- -- Apply show to a Maybe Int. If we have Just n, -- we want to show the underlying Int n. But if we have -- Nothing, we return the empty string instead of (for example) -- "Nothing": -- --
--   >>> maybe "" show (Just 5)
--   "5"
--   
--   >>> maybe "" show Nothing
--   ""
--   
maybe :: b -> (a -> b) -> Maybe a -> b -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --

Examples

-- -- Basic usage: -- --
--   >>> bool "foo" "bar" True
--   "bar"
--   
--   >>> bool "foo" "bar" False
--   "foo"
--   
-- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
--   >>> let p = True; x = "bar"; y = "foo"
--   
--   >>> bool x y p == if p then y else x
--   True
--   
--   >>> let p = False
--   
--   >>> bool x y p == if p then y else x
--   True
--   
bool :: a -> a -> Bool -> a -- | & is a reverse application operator. This provides -- notational convenience. Its precedence is one higher than that of the -- forward application operator $, which allows & to be -- nested in $. -- --
--   >>> 5 & (+1) & show
--   "6"
--   
(&) :: a -> (a -> b) -> b infixl 1 & -- | on b u x y runs the binary function b -- on the results of applying unary function u to two -- arguments x and y. From the opposite perspective, it -- transforms two inputs and combines the outputs. -- --
--   ((+) `on` f) x y = f x + f y
--   
-- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- -- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 `on` -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix argument, hence the recursion is reintroduced. fix :: (a -> a) -> a -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --

Examples

-- -- Replace the contents of a Maybe Int with unit: -- --
--   >>> void Nothing
--   Nothing
--   
--   >>> void (Just 3)
--   Just ()
--   
-- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int (): -- --
--   >>> void (Left 8675309)
--   Left 8675309
--   
--   >>> void (Right 8675309)
--   Right ()
--   
-- -- Replace every element of a list with unit: -- --
--   >>> void [1,2,3]
--   [(),(),()]
--   
-- -- Replace the second element of a pair with unit: -- --
--   >>> void (1,2)
--   (1,())
--   
-- -- Discard the result of an IO action: -- --
--   >>> mapM print [1,2]
--   1
--   2
--   [(),()]
--   
--   >>> void $ mapM print [1,2]
--   1
--   2
--   
void :: Functor f => f a -> f () -- | Flipped version of <$. -- --

Examples

-- -- Replace the contents of a Maybe Int with a -- constant String: -- --
--   >>> Nothing $> "foo"
--   Nothing
--   
--   >>> Just 90210 $> "foo"
--   Just "foo"
--   
-- -- Replace the contents of an Either Int -- Int with a constant String, resulting in an -- Either Int String: -- --
--   >>> Left 8675309 $> "foo"
--   Left 8675309
--   
--   >>> Right 8675309 $> "foo"
--   Right "foo"
--   
-- -- Replace each element of a list with a constant String: -- --
--   >>> [1,2,3] $> "foo"
--   ["foo","foo","foo"]
--   
-- -- Replace the second element of a pair with a constant String: -- --
--   >>> (1,2) $> "foo"
--   (1,"foo")
--   
($>) :: Functor f => f a -> b -> f b infixl 4 $> -- | Flipped version of <$>. -- --
--   (<&>) = flip fmap
--   
-- --

Examples

-- -- Apply (+1) to a list, a Just and a Right: -- --
--   >>> Just 2 <&> (+1)
--   Just 3
--   
-- --
--   >>> [1,2,3] <&> (+1)
--   [2,3,4]
--   
-- --
--   >>> Right 3 <&> (+1)
--   Right 4
--   
(<&>) :: Functor f => f a -> (a -> b) -> f b infixl 1 <&> -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
--    ($)  ::              (a -> b) ->   a ->   b
--   (<$>) :: Functor f => (a -> b) -> f a -> f b
--   
-- -- Whereas $ is function application, <$> is function -- application lifted over a Functor. -- --

Examples

-- -- Convert from a Maybe Int to a Maybe -- String using show: -- --
--   >>> show <$> Nothing
--   Nothing
--   
--   >>> show <$> Just 3
--   Just "3"
--   
-- -- Convert from an Either Int Int to an -- Either Int String using show: -- --
--   >>> show <$> Left 17
--   Left 17
--   
--   >>> show <$> Right 17
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> (*2) <$> [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> even <$> (2,2)
--   (2,True)
--   
(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | Swap the components of a pair. swap :: (a, b) -> (b, a) -- | uncurry converts a curried function to a function on pairs. -- --

Examples

-- --
--   >>> uncurry (+) (1,2)
--   3
--   
-- --
--   >>> uncurry ($) (show, 1)
--   "1"
--   
-- --
--   >>> map (uncurry max) [(1,2), (3,4), (6,8)]
--   [2,4,8]
--   
uncurry :: (a -> b -> c) -> (a, b) -> c -- | curry converts an uncurried function to a curried function. -- --

Examples

-- --
--   >>> curry fst 1 2
--   1
--   
curry :: ((a, b) -> c) -> a -> b -> c -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a box, which may be empty or full. data MVar a -- | the same as flip (-). -- -- Because - is treated specially in the Haskell grammar, -- (- e) is not a section, but an application of -- prefix negation. However, (subtract -- exp) is equivalent to the disallowed section. subtract :: Num a => a -> a -> a -- | Returns a [String] representing the current call stack. This -- can be useful for debugging. -- -- The implementation uses the call-stack simulation maintained by the -- profiler, so it only works if the program was compiled with -- -prof and contains suitable SCC annotations (e.g. by using -- -fprof-auto). Otherwise, the list returned is likely to be -- empty or uninformative. currentCallStack :: IO [String] -- | asTypeOf is a type-restricted version of const. It is -- usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- second. asTypeOf :: a -> a -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c -- | Function composition. (.) :: (b -> c) -> (a -> b) -> a -> c infixr 9 . -- | const x is a unary function which evaluates to x for -- all inputs. -- --
--   >>> const 42 "hello"
--   42
--   
-- --
--   >>> map (const 42) [0..3]
--   [42,42,42,42]
--   
const :: a -> b -> a -- | Identity function. -- --
--   id x = x
--   
id :: a -> a maxInt :: Int minInt :: Int -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
--   return f `ap` x1 `ap` ... `ap` xn
--   
-- -- is equivalent to -- --
--   liftMn f x1 x2 ... xn
--   
ap :: Monad m => m (a -> b) -> m a -> m b -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
--   liftM2 (+) [0,1] [0,2] = [0,2,1,3]
--   liftM2 (+) (Just 1) Nothing = Nothing
--   
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | Conditional execution of Applicative expressions. For example, -- --
--   when debug (putStrLn "Debugging")
--   
-- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | Lift a ternary function to actions. liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | One or more. some :: Alternative f => f a -> f [a] -- | Zero or more. many :: Alternative f => f a -> f [a] infixl 3 <|> -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) -- | The identity of mplus. It should also satisfy the equations -- --
--   mzero >>= f  =  mzero
--   v >> mzero   =  mzero
--   
-- -- The default definition is -- --
--   mzero = empty
--   
mzero :: MonadPlus m => m a -- | An associative operation. The default definition is -- --
--   mplus = (<|>)
--   
mplus :: MonadPlus m => m a -> m a -> m a -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | Extract a list of call-sites from the CallStack. -- -- The list is ordered by most recent call. getCallStack :: CallStack -> [([Char], SrcLoc)] -- | Request a CallStack. -- -- NOTE: The implicit parameter ?callStack :: CallStack is an -- implementation detail and should not be considered part of the -- CallStack API, we may decide to change the implementation in -- the future. type HasCallStack = ?callStack :: CallStack -- | This is a valid definition of stimes for an idempotent -- Monoid. -- -- When mappend x x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n) stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | The SomeException type is the root of the exception type -- hierarchy. When an exception of type e is thrown, behind the -- scenes it is encapsulated in a SomeException. data SomeException SomeException :: e -> SomeException -- | Boolean "and" (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or" (||) :: Bool -> Bool -> Bool infixr 2 || -- | Boolean "not" not :: Bool -> Bool -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data ByteString -- | A map of integers to values a. data IntMap a -- | A set of integers. data IntSet -- | A Map from keys k to values a. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data Map k a -- | General-purpose finite sequences. data Seq a -- | A set of values a. data Set a -- | a variant of deepseq that is useful in some circumstances: -- --
--   force x = x `deepseq` x
--   
-- -- force x fully evaluates x, and then returns it. Note -- that force x only performs evaluation when the value of -- force x itself is demanded, so essentially it turns shallow -- evaluation into deep evaluation. -- -- force can be conveniently used in combination with -- ViewPatterns: -- --
--   {-# LANGUAGE BangPatterns, ViewPatterns #-}
--   import Control.DeepSeq
--   
--   someFun :: ComplexData -> SomeResult
--   someFun (force -> !arg) = {- 'arg' will be fully evaluated -}
--   
-- -- Another useful application is to combine force with -- evaluate in order to force deep evaluation relative to other -- IO operations: -- --
--   import Control.Exception (evaluate)
--   import Control.DeepSeq
--   
--   main = do
--     result <- evaluate $ force $ pureComputation
--     {- 'result' will be fully evaluated at this point -}
--     return ()
--   
-- -- Finally, here's an exception safe variant of the readFile' -- example: -- --
--   readFile' :: FilePath -> IO String
--   readFile' fn = bracket (openFile fn ReadMode) hClose $ \h ->
--                          evaluate . force =<< hGetContents h
--   
force :: NFData a => a -> a -- | the deep analogue of $!. In the expression f $!! x, -- x is fully evaluated before the function f is -- applied to it. ($!!) :: NFData a => (a -> b) -> a -> b infixr 0 $!! -- | deepseq: fully evaluates the first argument, before returning -- the second. -- -- The name deepseq is used to illustrate the relationship to -- seq: where seq is shallow in the sense that it only -- evaluates the top level of its argument, deepseq traverses the -- entire data structure evaluating it completely. -- -- deepseq can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also -- useful in conjunction with parallel Strategies (see the -- parallel package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in any -- order or in parallel. To impose an actual order on evaluation, use -- pseq from Control.Parallel in the parallel -- package. deepseq :: NFData a => a -> b -> b -- | A class of types that can be fully evaluated. class NFData a -- | rnf should reduce its argument to normal form (that is, fully -- evaluate all sub-components), and then return (). -- --

Generic NFData deriving

-- -- Starting with GHC 7.2, you can automatically derive instances for -- types possessing a Generic instance. -- -- Note: Generic1 can be auto-derived starting with GHC 7.4 -- --
--   {-# LANGUAGE DeriveGeneric #-}
--   
--   import GHC.Generics (Generic, Generic1)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1)
--   
--   instance NFData a => NFData (Foo a)
--   instance NFData1 Foo
--   
--   data Colour = Red | Green | Blue
--                 deriving Generic
--   
--   instance NFData Colour
--   
-- -- Starting with GHC 7.10, the example above can be written more -- concisely by enabling the new DeriveAnyClass extension: -- --
--   {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
--   
--   import GHC.Generics (Generic)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1, NFData, NFData1)
--   
--   data Colour = Red | Green | Blue
--                 deriving (Generic, NFData)
--   
-- --

Compatibility with previous deepseq versions

-- -- Prior to version 1.4.0.0, the default implementation of the rnf -- method was defined as -- --
--   rnf a = seq a ()
--   
-- -- However, starting with deepseq-1.4.0.0, the default -- implementation is based on DefaultSignatures allowing for -- more accurate auto-derived NFData instances. If you need the -- previously used exact default rnf method implementation -- semantics, use -- --
--   instance NFData Colour where rnf x = seq x ()
--   
-- -- or alternatively -- --
--   instance NFData Colour where rnf = rwhnf
--   
-- -- or -- --
--   {-# LANGUAGE BangPatterns #-}
--   instance NFData Colour where rnf !_ = ()
--   
rnf :: NFData a => a -> () -- | A space efficient, packed, unboxed Unicode text type. data Text -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: forall (m :: Type -> Type) e a. Functor m => e -> MaybeT m a -> ExceptT e m a -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: forall (m :: Type -> Type) e a. Functor m => ExceptT e m a -> MaybeT m a -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | Function type for handling a coding error. It is supplied with two -- inputs: -- -- -- -- If the handler returns a value wrapped with Just, that value -- will be used in the output as the replacement for the invalid input. -- If it returns Nothing, no value will be used in the output. -- -- Should the handler need to abort processing, it should use -- error or throw an exception (preferably a -- UnicodeException). It may use the description provided to -- construct a more helpful error report. type OnError a b = String -> Maybe a -> Maybe b -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Decode a ByteString containing UTF-8 encoded text. -- -- NOTE: The replacement character returned by -- OnDecodeError MUST be within the BMP plane; surrogate code -- points will automatically be remapped to the replacement char -- U+FFFD (since 0.11.3.0), whereas code points beyond -- the BMP will throw an error (since 1.2.3.1); For earlier -- versions of text using those unsupported code points would -- result in undefined behavior. decodeUtf8With :: OnDecodeError -> ByteString -> Text -- | Decode a ByteString containing UTF-8 encoded text. -- -- If the input contains any invalid UTF-8 data, the relevant exception -- will be returned, otherwise the decoded text. decodeUtf8' :: ByteString -> Either UnicodeException Text -- | O(n) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [Text] -- | O(n) Breaks a Text up into a list of Texts at -- newline Chars. The resulting strings do not contain newlines. lines :: Text -> [Text] -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [Text] -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Convert a lazy Text into a strict Text. toStrict :: Text -> Text -- | O(c) Convert a strict Text into a lazy Text. fromStrict :: Text -> Text -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execStateT :: Monad m => StateT s m a -> s -> m s -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalStateT :: Monad m => StateT s m a -> s -> m a -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: (s -> s) -> State s a -> State s a -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: State s a -> s -> s -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalState :: State s a -> s -> a -- | Unwrap a state monad computation as a function. (The inverse of -- state.) runState :: State s a -> s -> (a, s) -- | A state monad parameterized by the type s of the state to -- carry. -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. type State s = StateT s Identity -- | A state transformer monad parameterized by: -- -- -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. newtype StateT s (m :: Type -> Type) a StateT :: (s -> m (a, s)) -> StateT s (m :: Type -> Type) a [runStateT] :: StateT s (m :: Type -> Type) a -> s -> m (a, s) -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e a) -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | The trivial monad transformer, which maps a monad to an equivalent -- monad. data IdentityT (f :: k -> Type) (a :: k) -- | The class of monad transformers. Instances should satisfy the -- following laws, which state that lift is a monad -- transformation: -- -- class MonadTrans (t :: Type -> Type -> Type -> Type) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a -- | The parameterizable reader monad. -- -- Computations are functions of a shared environment. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. type Reader r = ReaderT r Identity -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. newtype ReaderT r (m :: Type -> Type) a ReaderT :: (r -> m a) -> ReaderT r (m :: Type -> Type) a [runReaderT] :: ReaderT r (m :: Type -> Type) a -> r -> m a -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: Type -> Type) | m -> s -- | Return the state from the internals of the monad. get :: MonadState s m => m s -- | Replace the state inside the monad. put :: MonadState s m => s -> m () -- | Embed a simple state action into the monad. state :: MonadState s m => (s -> (a, s)) -> m a -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: Type -> Type) | m -> r -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | Executes a computation in a modified environment. local :: MonadReader r m => (r -> r) -> m a -> m a -- | Retrieves a function of the current environment. reader :: MonadReader r m => (r -> a) -> m a -- | Retrieves a function of the current environment. asks :: MonadReader r m => (r -> a) -> m a -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => (s -> a) -> m a -- | Monadic state transformer. -- -- Maps an old state to a new state inside a state monad. The old state -- is thrown away. -- --
--   Main> :t modify ((+1) :: Int -> Int)
--   modify (...) :: (MonadState Int a) => a ()
--   
-- -- This says that modify (+1) acts over any Monad that is a -- member of the MonadState class, with an Int state. modify :: MonadState s m => (s -> s) -> m () -- | A monad transformer that adds exceptions to other monads. -- -- ExceptT constructs a monad parameterized over two things: -- -- -- -- The return function yields a computation that produces the -- given value, while >>= sequences two subcomputations, -- exiting on the first exception. newtype ExceptT e (m :: Type -> Type) a ExceptT :: m (Either e a) -> ExceptT e (m :: Type -> Type) a -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype MaybeT (m :: Type -> Type) a MaybeT :: m (Maybe a) -> MaybeT (m :: Type -> Type) a [runMaybeT] :: MaybeT (m :: Type -> Type) a -> m (Maybe a) (%~) :: ASetter s t a b -> (a -> b) -> s -> t (.~) :: ASetter s t a b -> b -> s -> t (^.) :: s -> Getting a s a -> a (^..) :: s -> Getting (Endo [a]) s a -> [a] (^?) :: s -> Getting (First a) s a -> Maybe a over :: ASetter s t a b -> (a -> b) -> s -> t set :: ASetter s t a b -> b -> s -> t preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a) preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a) use :: MonadState s m => Getting a s a -> m a view :: MonadReader s m => Getting a s a -> m a bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c bracket_ :: MonadMask m => m a -> m b -> m c -> m c catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a catchAny :: MonadCatch m => m a -> (SomeException -> m a) -> m a finally :: MonadMask m => m a -> m b -> m a handleAny :: MonadCatch m => (SomeException -> m a) -> m a -> m a onException :: MonadMask m => m a -> m b -> m a throwM :: (MonadThrow m, Exception e) => e -> m a try :: (MonadCatch m, Exception e) => m a -> m (Either e a) tryAny :: MonadCatch m => m a -> m (Either SomeException a) pass :: Applicative f => f () ($!) :: (a -> b) -> a -> b guardM :: MonadPlus m => m Bool -> m () ifM :: Monad m => m Bool -> m a -> m a -> m a unlessM :: Monad m => m Bool -> m () -> m () whenM :: Monad m => m Bool -> m () -> m () asum :: (Container t, Alternative f, Element t ~ f a) => t -> f a flipfoldl' :: (Container t, Element t ~ a) => (a -> b -> b) -> b -> t -> b forM_ :: (Container t, Monad m) => t -> (Element t -> m b) -> m () for_ :: (Container t, Applicative f) => t -> (Element t -> f b) -> f () mapM_ :: (Container t, Monad m) => (Element t -> m b) -> t -> m () product :: (Container t, Num (Element t)) => t -> Element t sequenceA_ :: (Container t, Applicative f, Element t ~ f a) => t -> f () sequence_ :: (Container t, Monad m, Element t ~ m a) => t -> m () sum :: (Container t, Num (Element t)) => t -> Element t traverse_ :: (Container t, Applicative f) => (Element t -> f b) -> t -> f () error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => Text -> a trace :: Text -> a -> a traceId :: Text -> Text traceIdWith :: (a -> Text) -> a -> a traceM :: Monad m => Text -> m () traceShow :: Show a => a -> b -> b traceShowId :: Show a => a -> a traceShowIdWith :: Show s => (a -> s) -> a -> a traceShowM :: (Show a, Monad m) => a -> m () undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a evaluateNF :: (NFData a, MonadIO m) => a -> m a evaluateNF_ :: (NFData a, MonadIO m) => a -> m () evaluateWHNF :: MonadIO m => a -> m a evaluateWHNF_ :: MonadIO m => a -> m () pattern Exc :: Exception e => e -> SomeException bug :: (HasCallStack, Exception e) => e -> a note :: MonadError e m => e -> Maybe a -> m a (<<$>>) :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b) map :: Functor f => (a -> b) -> f a -> f b atomically :: MonadIO m => STM a -> m a newEmptyMVar :: MonadIO m => m (MVar a) newMVar :: MonadIO m => a -> m (MVar a) newTVarIO :: MonadIO m => a -> m (TVar a) putMVar :: MonadIO m => MVar a -> a -> m () readMVar :: MonadIO m => MVar a -> m a readTVarIO :: MonadIO m => TVar a -> m a swapMVar :: MonadIO m => MVar a -> a -> m a takeMVar :: MonadIO m => MVar a -> m a tryPutMVar :: MonadIO m => MVar a -> a -> m Bool tryReadMVar :: MonadIO m => MVar a -> m (Maybe a) tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) die :: MonadIO m => String -> m a exitFailure :: MonadIO m => m a exitSuccess :: MonadIO m => m a exitWith :: MonadIO m => ExitCode -> m a appendFile :: MonadIO m => FilePath -> Text -> m () getLine :: MonadIO m => m Text hClose :: MonadIO m => Handle -> m () openFile :: MonadIO m => FilePath -> IOMode -> m Handle withFile :: (MonadIO m, MonadMask m) => FilePath -> IOMode -> (Handle -> m a) -> m a atomicModifyIORef :: MonadIO m => IORef a -> (a -> (a, b)) -> m b atomicModifyIORef' :: MonadIO m => IORef a -> (a -> (a, b)) -> m b atomicWriteIORef :: MonadIO m => IORef a -> a -> m () modifyIORef :: MonadIO m => IORef a -> (a -> a) -> m () modifyIORef' :: MonadIO m => IORef a -> (a -> a) -> m () newIORef :: MonadIO m => a -> m (IORef a) readIORef :: MonadIO m => IORef a -> m a writeIORef :: MonadIO m => IORef a -> a -> m () uncons :: [a] -> Maybe (a, [a]) whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f () whenNotNullM :: Monad m => m [a] -> (NonEmpty a -> m ()) -> m () allM :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool andM :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool anyM :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool concatForM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => l a -> (a -> f m) -> f m concatMapM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => (a -> f m) -> l a -> f m orM :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool fromLeft :: a -> Either a b -> a fromRight :: b -> Either a b -> b leftToMaybe :: Either l r -> Maybe l maybeToLeft :: r -> Maybe l -> Either l r maybeToRight :: l -> Maybe r -> Either l r rightToMaybe :: Either l r -> Maybe r whenLeft :: Applicative f => Either l r -> (l -> f ()) -> f () whenLeftM :: Monad m => m (Either l r) -> (l -> m ()) -> m () whenRight :: Applicative f => Either l r -> (r -> f ()) -> f () whenRightM :: Monad m => m (Either l r) -> (r -> m ()) -> m () (?:) :: Maybe a -> a -> a whenJust :: Applicative f => Maybe a -> (a -> f ()) -> f () whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () whenNothing :: Applicative f => Maybe a -> f a -> f a whenNothingM :: Monad m => m (Maybe a) -> m a -> m a whenNothingM_ :: Monad m => m (Maybe a) -> m () -> m () whenNothing_ :: Applicative f => Maybe a -> f () -> f () evaluatingState :: s -> State s a -> a evaluatingStateT :: Functor f => s -> StateT s f a -> f a executingState :: s -> State s a -> s executingStateT :: Functor f => s -> StateT s f a -> f s usingReader :: r -> Reader r a -> a usingReaderT :: r -> ReaderT r m a -> m a usingState :: s -> State s a -> (a, s) usingStateT :: s -> StateT s m a -> m (a, s) maybeToMonoid :: Monoid m => Maybe m -> m hashNub :: (Eq a, Hashable a) => [a] -> [a] ordNub :: Ord a => [a] -> [a] sortNub :: Ord a => [a] -> [a] unstableNub :: (Eq a, Hashable a) => [a] -> [a] hPrint :: (MonadIO m, Show a) => Handle -> a -> m () hPutStr :: (Print a, MonadIO m) => Handle -> a -> m () hPutStrLn :: (Print a, MonadIO m) => Handle -> a -> m () print :: forall a m. (MonadIO m, Show a) => a -> m () putLText :: MonadIO m => Text -> m () putLTextLn :: MonadIO m => Text -> m () putStr :: (Print a, MonadIO m) => a -> m () putStrLn :: (Print a, MonadIO m) => a -> m () putText :: MonadIO m => Text -> m () putTextLn :: MonadIO m => Text -> m () readEither :: (ToString a, Read b) => a -> Either Text b show :: forall b a. (Show a, IsString b) => a -> b class MonadThrow m => MonadCatch (m :: Type -> Type) class MonadCatch m => MonadMask (m :: Type -> Type) mask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b uninterruptibleMask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b generalBracket :: MonadMask m => m a -> (a -> ExitCase b -> m c) -> (a -> m b) -> m (b, c) class Monad m => MonadThrow (m :: Type -> Type) class Hashable a hashWithSalt :: Hashable a => Int -> a -> Int _1 :: Field1 s t a b => Lens s t a b _2 :: Field2 s t a b => Lens s t a b _3 :: Field3 s t a b => Lens s t a b _4 :: Field4 s t a b => Lens s t a b _5 :: Field5 s t a b => Lens s t a b type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t type Lens' s a = Lens s s a a type Traversal s t a b = forall (f :: Type -> Type). Applicative f => a -> f b -> s -> f t type Traversal' s a = Traversal s s a a class Container t where { type family Element t; type Element t = ElementDefault t; } toList :: Container t => t -> [Element t] null :: Container t => t -> Bool foldr :: Container t => (Element t -> b -> b) -> b -> t -> b foldl :: Container t => (b -> Element t -> b) -> b -> t -> b foldl' :: Container t => (b -> Element t -> b) -> b -> t -> b length :: Container t => t -> Int elem :: Container t => Element t -> t -> Bool maximum :: Container t => t -> Element t minimum :: Container t => t -> Element t foldMap :: (Container t, Monoid m) => (Element t -> m) -> t -> m fold :: Container t => t -> Element t foldr' :: Container t => (Element t -> b -> b) -> b -> t -> b foldr1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t foldl1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t notElem :: Container t => Element t -> t -> Bool all :: Container t => (Element t -> Bool) -> t -> Bool any :: Container t => (Element t -> Bool) -> t -> Bool and :: Container t => t -> Bool or :: Container t => t -> Bool find :: Container t => (Element t -> Bool) -> t -> Maybe (Element t) safeHead :: Container t => t -> Maybe (Element t) type family Element t class One x where { type family OneItem x; } one :: One x => OneItem x -> x type family OneItem x class ToPairs t toPairs :: ToPairs t => t -> [(Key t, Val t)] keys :: ToPairs t => t -> [Key t] elems :: ToPairs t => t -> [Val t] data Undefined Undefined :: Undefined data Bug Bug :: SomeException -> CallStack -> Bug class Print a class ConvertUtf8 a b encodeUtf8 :: ConvertUtf8 a b => a -> b decodeUtf8 :: ConvertUtf8 a b => b -> a decodeUtf8Strict :: ConvertUtf8 a b => b -> Either UnicodeException a type LByteString = ByteString type LText = Text class ToLText a toLText :: ToLText a => a -> Text class ToString a toString :: ToString a => a -> String class ToText a toText :: ToText a => a -> Text type (f :: k1 -> k) $ (a :: k1) = f a type family Each (c :: [k -> Constraint]) (as :: [k]) type With (a :: [k -> Constraint]) (b :: k) = a <+> b class SuperComposition a b c | a b -> c (...) :: SuperComposition a b c => a -> b -> c data HashMap k v data HashSet a data Vector a -- | This module is intended to be imported instead of Lorentz by -- Indigo modules. -- -- The idea is to avoid repeating common hiding rules and to not -- export any of Lorentz's Instructions and Macros. module Indigo.Lorentz data Bool False :: Bool True :: Bool -- | Invariant: Jn# and Jp# are used iff value doesn't fit in -- S# -- -- Useful properties resulting from the invariants: -- -- data Integer -- | Type representing arbitrary-precision non-negative integers. -- --
--   >>> 2^100 :: Natural
--   1267650600228229401496703205376
--   
-- -- Operations whose result would be negative throw -- (Underflow :: ArithException), -- --
--   >>> -1 :: Natural
--   *** Exception: arithmetic underflow
--   
data Natural -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data ByteString -- | A Map from keys k to values a. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data Map k a -- | A set of values a. data Set a -- | Note that calling given entrypoints involves constructing -- UParam. pbsUParam :: forall (ctorName :: Symbol). KnownSymbol ctorName => ParamBuildingStep -- | Make up UParam from ADT sum. -- -- Entry points template will consist of (constructorName, -- constructorFieldType) pairs. Each constructor is expected to have -- exactly one field. uparamFromAdt :: UParamLinearize up => up -> UParam (UParamLinearized up) -- | Like caseUParam, but accepts a tuple of clauses, not a -- Rec. caseUParamT :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]) clauses. (clauses ~ Rec (CaseClauseU inp out) entries, RecFromTuple clauses, CaseUParam entries) => IsoRecTuple clauses -> UParamFallback inp out -> (UParam entries : inp) :-> out -- | Pattern-match on given UParam entries. -- -- You have to provide all case branches and a fallback action on case -- when entrypoint is not found. caseUParam :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]). (CaseUParam entries, RequireUniqueEntrypoints entries) => Rec (CaseClauseU inp out) entries -> UParamFallback inp out -> (UParam entries : inp) :-> out -- | Default implementation for UParamFallback, simply reports an -- error. uparamFallbackFail :: forall (inp :: [Type]) (out :: [Type]). UParamFallback inp out -- | Helper instruction which extracts content of UParam. unwrapUParam :: forall (entries :: [EntrypointKind]) (s :: [Type]). (UParam entries : s) :-> ((MText, ByteString) : s) -- | Construct a UParam safely. mkUParam :: forall a (name :: Symbol) (entries :: [EntrypointKind]). (NicePackedValue a, LookupEntrypoint name entries ~ a, RequireUniqueEntrypoints entries) => Label name -> a -> UParam entries -- | An entrypoint is described by two types: its name and type of -- argument. type EntrypointKind = (Symbol, Type) -- | A convenient alias for type-level name-something pair. type (n :: Symbol) ?: (a :: k) = '(n, a) -- | Encapsulates parameter for one of entry points. It keeps entrypoint -- name and corresponding argument serialized. -- -- In Haskell world, we keep an invariant of that contained value relates -- to one of entry points from entries list. newtype UParam (entries :: [EntrypointKind]) UParamUnsafe :: (MText, ByteString) -> UParam (entries :: [EntrypointKind]) -- | Pseudo value for UParam type variable. type SomeInterface = '[ '("SomeEntrypoints", Void)] -- | Homomorphic version of UParam, forgets the exact interface. type UParam_ = UParam SomeInterface -- | Get type of entrypoint argument by its name. type family LookupEntrypoint (name :: Symbol) (entries :: [EntrypointKind]) -- | Ensure that given entry points do no contain duplicated names. type family RequireUniqueEntrypoints (entries :: [EntrypointKind]) -- | This type can store any value that satisfies a certain constraint. data ConstrainedSome (c :: Type -> Constraint) [ConstrainedSome] :: forall (c :: Type -> Constraint) a. c a => a -> ConstrainedSome c -- | This class is needed to implement unpackUParam. class UnpackUParam (c :: Type -> Constraint) (entries :: [EntrypointKind]) -- | Turn UParam into a Haskell value. Since we don't know its type -- in compile time, we have to erase it using ConstrainedSome. The -- user of this function can require arbitrary constraint to hold -- (depending on how they want to use the result). unpackUParam :: UnpackUParam c entries => UParam entries -> Either EntrypointLookupError (MText, ConstrainedSome c) data EntrypointLookupError NoSuchEntrypoint :: MText -> EntrypointLookupError ArgumentUnpackFailed :: EntrypointLookupError -- | Implementations of some entry points. -- -- Note that this thing inherits properties of Rec, e.g. you can -- Data.Vinyl.Core.rappend implementations for two entrypoint -- sets when assembling scattered parts of a contract. type EntrypointsImpl (inp :: [Type]) (out :: [Type]) (entries :: [EntrypointKind]) = Rec CaseClauseU inp out entries -- | An action invoked when user-provided entrypoint is not found. type UParamFallback (inp :: [Type]) (out :: [Type]) = (MText, ByteString) : inp :-> out -- | Make up a "case" over entry points. class CaseUParam (entries :: [EntrypointKind]) -- | Constraint required by uparamFromAdt. type UParamLinearize p = (Generic p, GUParamLinearize Rep p) -- | Entry points template derived from given ADT sum. type UParamLinearized p = GUParamLinearized Rep p entryCaseSimple_ :: forall cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp & inp) :-> out -- | Whether finalizeParamCallingDoc has already been applied to -- these steps. areFinalizedParamBuildingSteps :: [ParamBuildingStep] -> Bool -- | Wrapper for documenting single entrypoint which parameter isn't going -- to be unwrapped from some datatype. -- -- entryCase unwraps a datatype, however, sometimes we want to -- have entrypoint parameter to be not wrapped into some datatype. documentEntrypoint :: forall kind (epName :: Symbol) param (s :: [Type]) (out :: [Type]). (KnownSymbol epName, DocItem (DEntrypoint kind), TypeHasDoc param, HasAnnotation param, KnownValue param) => ((param & s) :-> out) -> (param & s) :-> out -- | Go over contract code and update every occurrence of -- DEntrypointArg documentation item, adding the given step to its -- "how to build parameter" description. clarifyParamBuildingSteps :: forall (inp :: [Type]) (out :: [Type]). ParamBuildingStep -> (inp :-> out) -> inp :-> out mkDEntrypointArgSimple :: (KnownValue t, HasAnnotation t, TypeHasDoc t) => DEntrypointArg mkDEpUType :: (KnownValue t, HasAnnotation t) => Type emptyDEpArg :: DEntrypointArg constructDEpArg :: (TypeHasDoc arg, HasAnnotation arg, KnownValue arg) => DEntrypointArg -- | Make a ParamBuildingStep that tells about wrapping an argument -- into a constructor with given name and uses given ParamBuilder -- as description of Michelson part. mkPbsWrapIn :: Text -> ParamBuilder -> ParamBuildingStep -- | Default implementation of docItemToMarkdown for entry points. diEntrypointToMarkdown :: HeaderLevel -> DEntrypoint level -> Markdown -- | Gathers information about single entrypoint. -- -- We assume that entry points might be of different kinds, which is -- designated by phantom type parameter. For instance, you may want to -- have several groups of entry points corresponding to various parts of -- a contract - specifying different kind type argument for each -- of those groups will allow you defining different DocItem -- instances with appropriate custom descriptions for them. data DEntrypoint kind DEntrypoint :: Text -> SubDoc -> DEntrypoint kind [depName] :: DEntrypoint kind -> Text [depSub] :: DEntrypoint kind -> SubDoc -- | Default value for DEntrypoint type argument. data PlainEntrypointsKind data DEntrypointReference DEntrypointReference :: Text -> Anchor -> DEntrypointReference -- | When describing the way of parameter construction - piece of -- incremental builder for this description. newtype ParamBuilder ParamBuilder :: (Markdown -> Markdown) -> ParamBuilder -- | Argument stands for previously constructed parameter piece, and -- returned value - a piece constructed after our step. [unParamBuilder] :: ParamBuilder -> Markdown -> Markdown data ParamBuildingDesc ParamBuildingDesc :: Markdown -> ParamBuilder -> ParamBuilder -> ParamBuildingDesc -- | Plain english description of this step. [pbdEnglish] :: ParamBuildingDesc -> Markdown -- | How to construct parameter in Haskell code. [pbdHaskell] :: ParamBuildingDesc -> ParamBuilder -- | How to construct parameter working on raw Michelson. [pbdMichelson] :: ParamBuildingDesc -> ParamBuilder -- | Describes a parameter building step. -- -- This can be wrapping into (Haskell) constructor, or a more complex -- transformation. data ParamBuildingStep -- | Wraps something into constructor with given name. Constructor should -- be the one which corresponds to an entrypoint defined via field -- annotation, for more complex cases use PbsCustom. PbsWrapIn :: Text -> ParamBuildingDesc -> ParamBuildingStep -- | Directly call an entrypoint marked with a field annotation. PbsCallEntrypoint :: EpName -> ParamBuildingStep -- | Other action. PbsCustom :: ParamBuildingDesc -> ParamBuildingStep -- | This entrypoint cannot be called, which is possible when an explicit -- default entrypoint is present. This is not a true entrypoint but just -- some intermediate node in or tree and neither it nor any of -- its parents are marked with a field annotation. -- -- It contains dummy ParamBuildingSteps which were assigned before -- entrypoints were taken into account. PbsUncallable :: [ParamBuildingStep] -> ParamBuildingStep -- | Describes argument of an entrypoint. data DEntrypointArg DEntrypointArg :: Maybe DType -> [ParamBuildingStep] -> Type -> DEntrypointArg -- | Argument of the entrypoint. Pass Nothing if no argument is -- required. [epaArg] :: DEntrypointArg -> Maybe DType -- | Describes a way to lift an entrypoint argument into full parameter -- which can be passed to the contract. -- -- Steps are supposed to be applied in the order opposite to one in which -- they are given. E.g. suppose that an entrypoint is called as Run -- (Service1 arg); then the first step (actual last) should describe -- wrapping into Run constructor, and the second step (actual -- first) should be about wrapping into Service1 constructor. [epaBuilding] :: DEntrypointArg -> [ParamBuildingStep] -- | Untyped representation of entrypoint, used for printing its michelson -- type representation. [epaType] :: DEntrypointArg -> Type -- | Pick a type documentation from CtorField. class KnownSymbol con => DeriveCtorFieldDoc (con :: Symbol) (cf :: CtorField) deriveCtorFieldDoc :: DeriveCtorFieldDoc con cf => DEntrypointArg -- | Constraint for documentEntrypoints. type DocumentEntrypoints kind a = (Generic a, GDocumentEntrypoints kind Rep a) -- | Provides arror for convenient entrypoint documentation class EntryArrow (kind :: k) (name :: Symbol) body -- | Lift entrypoint implementation. -- -- Entrypoint names should go with "e" prefix. (#->) :: EntryArrow kind name body => (Label name, Proxy kind) -> body -> body type family RequireFlatParamEps cp type family RequireFlatEpDerivation (cp :: t) deriv -- | Utility to create EntrypointsFields from an entrypoint name -- (epName) and an EntrypointLambda implementation. Note -- that you need to merge multiple of these (with <>) if -- your field contains more than one entrypoint lambda. mkStoreEp :: forall (epName :: Symbol) epParam epStore. Label epName -> EntrypointLambda epParam epStore -> EntrypointsField epParam epStore composeStoreEntrypointOps :: forall (nameInStore :: Symbol) store substore (epName :: Symbol) epParam epStore. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreEntrypointOps substore epName epParam epStore -> StoreEntrypointOps store epName epParam epStore -- | Chain implementations of field and submap operations. composeStoreSubmapOps :: forall (nameInStore :: Symbol) store substore (mname :: Symbol) key value. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreSubmapOps substore mname key value -> StoreSubmapOps store mname key value -- | Chain two implementations of field operations. -- -- Suits for a case when your store does not contain its fields directly -- rather has a nested structure. composeStoreFieldOps :: forall (nameInStore :: Symbol) store substore (nameInSubstore :: Symbol) field. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreFieldOps substore nameInSubstore field -> StoreFieldOps store nameInSubstore field -- | Pretend that given StoreEntrypointOps implementation is made up -- for entrypoint with name desiredName, not its actual name. -- Logic of the implementation remains the same. -- -- See also storeSubmapOpsReferTo. storeEntrypointOpsReferTo :: forall (epName :: Symbol) store epParam epStore (desiredName :: Symbol). Label epName -> StoreEntrypointOps store epName epParam epStore -> StoreEntrypointOps store desiredName epParam epStore -- | Pretend that given StoreFieldOps implementation is made up for -- field with name desiredName, not its actual name. Logic of -- the implementation remains the same. -- -- See also storeSubmapOpsReferTo. storeFieldOpsReferTo :: forall (name :: Symbol) storage field (desiredName :: Symbol). Label name -> StoreFieldOps storage name field -> StoreFieldOps storage desiredName field -- | Pretend that given StoreSubmapOps implementation is made up for -- submap with name desiredName, not its actual name. Logic of -- the implementation remains the same. -- -- Use case: imagine that your code requires access to submap named -- X, but in your storage that submap is called Y. Then -- you implement the instance which makes X refer to Y: -- --
--   instance StoreHasSubmap Store X Key Value where
--     storeSubmapOps = storeSubmapOpsReferTo #Y storeSubmapOpsForY
--   
storeSubmapOpsReferTo :: forall (name :: Symbol) storage key value (desiredName :: Symbol). Label name -> StoreSubmapOps storage name key value -> StoreSubmapOps storage desiredName key value -- | Implementation of StoreHasEntrypoint for a data type which has -- an instance of StoreHasEntrypoint inside. For instance, it can -- be used for top-level storage. storeEntrypointOpsDeeper :: forall store (nameInStore :: Symbol) substore (epName :: Symbol) epParam epStore. (HasFieldOfType store nameInStore substore, StoreHasEntrypoint substore epName epParam epStore) => Label nameInStore -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasSubmap for a data type which has an -- instance of StoreHasSubmap inside. For instance, it can be used -- for top-level storage. storeSubmapOpsDeeper :: forall storage (bigMapPartName :: Symbol) fields (mname :: Symbol) key value. (HasFieldOfType storage bigMapPartName fields, StoreHasSubmap fields mname key value) => Label bigMapPartName -> StoreSubmapOps storage mname key value -- | Implementation of StoreHasField for a data type which has an -- instance of StoreHasField inside. For instance, it can be used -- for top-level storage. storeFieldOpsDeeper :: forall storage (fieldsPartName :: Symbol) fields (fname :: Symbol) ftype. (HasFieldOfType storage fieldsPartName fields, StoreHasField fields fname ftype) => Label fieldsPartName -> StoreFieldOps storage fname ftype -- | Implementation of StoreHasEntrypoint for a datatype that has a -- StoreHasSubmap that contains the entrypoint and a -- StoreHasField for the field such entrypoint operates on. storeEntrypointOpsSubmapField :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (StoreHasSubmap store epmName MText (EntrypointLambda epParam epStore), StoreHasField store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasEntrypoint for a datatype that has a -- StoreHasField for an EntrypointsField that contains the -- entrypoint and a StoreHasField for the field such entrypoint -- operates on. storeEntrypointOpsFields :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (StoreHasField store epmName (EntrypointsField epParam epStore), StoreHasField store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasEntrypoint for a datatype keeping a -- pack of fields, among which one has contains the entrypoint and -- another is what such entrypoint operates on. storeEntrypointOpsADT :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (HasFieldOfType store epmName (EntrypointsField epParam epStore), HasFieldOfType store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasField for case of datatype keeping a -- pack of fields. storeFieldOpsADT :: forall dt (fname :: Symbol) ftype. HasFieldOfType dt fname ftype => StoreFieldOps dt fname ftype -- | Update the sub-storage that the entrypoint operates on. stSetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epStore : (store : s)) :-> (store : s) -- | Get the sub-storage that the entrypoint operates on, preserving the -- storage itself on the stack. stGetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : (store : s)) -- | Pick the sub-storage that the entrypoint operates on. stToEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : s) -- | Stores the entrypoint lambda in the storage. Fails if already set. stSetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) -- | Get stored entrypoint lambda, preserving the storage itself on the -- stack. stGetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : (store : s)) -- | Pick stored entrypoint lambda. stToEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) -- | Extracts and executes the epName entrypoint lambda from -- storage, returing the updated full storage (store) and the -- produced Operations. stEntrypoint :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epParam : (store : s)) :-> (([Operation], store) : s) -- | Add a value in storage, but fail if it will overwrite some existing -- entry. stInsertNew :: forall store (mname :: Symbol) key value (s :: [Type]). StoreHasSubmap store mname key value => Label mname -> (forall (s0 :: [Type]) (any :: [Type]). () => (key : s0) :-> any) -> (key : (value : (store : s))) :-> (store : s) -- | Add a value in storage. stInsert :: forall store (mname :: Symbol) key value (s :: [Type]). StoreHasSubmap store mname key value => Label mname -> (key : (value : (store : s))) :-> (store : s) -- | Delete a value in storage. stDelete :: forall store (mname :: Symbol) key value (s :: [Type]). (StoreHasSubmap store mname key value, KnownValue value) => Label mname -> (key : (store : s)) :-> (store : s) -- | Update a value in storage. stUpdate :: forall store (mname :: Symbol) key value (s :: [Type]). StoreHasSubmap store mname key value => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s) -- | Get value in storage. stGet :: forall store (mname :: Symbol) key value (s :: [Type]). (StoreHasSubmap store mname key value, KnownValue value) => Label mname -> (key : (store : s)) :-> (Maybe value : s) -- | Check value presence in storage. stMem :: forall store (mname :: Symbol) key value (s :: [Type]). StoreHasSubmap store mname key value => Label mname -> (key : (store : s)) :-> (Bool : s) -- | Update storage field. stSetField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (ftype : (store : s)) :-> (store : s) -- | Get storage field, preserving the storage itself on stack. stGetField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (store : s) :-> (ftype : (store : s)) -- | Pick storage field. stToField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (store : s) :-> (ftype : s) -- | Datatype containing the full implementation of StoreHasField -- typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreFieldOps store (fname :: Symbol) ftype StoreFieldOps :: (forall (s :: [Type]). () => Label fname -> (store : s) :-> (ftype : s)) -> (forall (s :: [Type]). () => Label fname -> (ftype : (store : s)) :-> (store : s)) -> StoreFieldOps store (fname :: Symbol) ftype [sopToField] :: StoreFieldOps store (fname :: Symbol) ftype -> forall (s :: [Type]). () => Label fname -> (store : s) :-> (ftype : s) [sopSetField] :: StoreFieldOps store (fname :: Symbol) ftype -> forall (s :: [Type]). () => Label fname -> (ftype : (store : s)) :-> (store : s) -- | Provides operations on fields for storage. class StoreHasField store (fname :: Symbol) ftype | store fname -> ftype storeFieldOps :: StoreHasField store fname ftype => StoreFieldOps store fname ftype -- | Datatype containing the full implementation of StoreHasSubmap -- typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreSubmapOps store (mname :: Symbol) key value StoreSubmapOps :: (forall (s :: [Type]). () => Label mname -> (key : (store : s)) :-> (Bool : s)) -> (forall (s :: [Type]). KnownValue value => Label mname -> (key : (store : s)) :-> (Maybe value : s)) -> (forall (s :: [Type]). () => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s)) -> (forall (s :: [Type]). () => Maybe (Label mname -> (key : (store : s)) :-> (store : s))) -> (forall (s :: [Type]). () => Maybe (Label mname -> (key : (value : (store : s))) :-> (store : s))) -> StoreSubmapOps store (mname :: Symbol) key value [sopMem] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Label mname -> (key : (store : s)) :-> (Bool : s) [sopGet] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). KnownValue value => Label mname -> (key : (store : s)) :-> (Maybe value : s) [sopUpdate] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s) [sopDelete] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Maybe (Label mname -> (key : (store : s)) :-> (store : s)) [sopInsert] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Maybe (Label mname -> (key : (value : (store : s))) :-> (store : s)) -- | Provides operations on submaps of storage. class StoreHasSubmap store (mname :: Symbol) key value | store mname -> key value storeSubmapOps :: StoreHasSubmap store mname key value => StoreSubmapOps store mname key value -- | Type synonym for a Lambda that can be used as an entrypoint type EntrypointLambda param store = Lambda (param, store) ([Operation], store) -- | Type synonym of a BigMap mapping MText (entrypoint -- names) to EntrypointLambda. -- -- This is useful when defining instances of StoreHasEntrypoint as -- a storage field containing one or more entrypoints (lambdas) of the -- same type. type EntrypointsField param store = BigMap MText EntrypointLambda param store -- | Datatype containing the full implementation of -- StoreHasEntrypoint typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreEntrypointOps store (epName :: Symbol) epParam epStore StoreEntrypointOps :: (forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s)) -> (forall (s :: [Type]). () => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s)) -> (forall (s :: [Type]). () => Label epName -> (store : s) :-> (epStore : s)) -> (forall (s :: [Type]). () => Label epName -> (epStore : (store : s)) :-> (store : s)) -> StoreEntrypointOps store (epName :: Symbol) epParam epStore [sopToEpLambda] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) [sopSetEpLambda] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) [sopToEpStore] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (store : s) :-> (epStore : s) [sopSetEpStore] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (epStore : (store : s)) :-> (store : s) -- | Provides operations on stored entrypoints. -- -- store is the storage containing both the entrypoint -- epName (note: it has to be in a BigMap to take -- advantage of lazy evaluation) and the epStore field this -- operates on. class StoreHasEntrypoint store (epName :: Symbol) epParam epStore | store epName -> epParam epStore storeEpOps :: StoreHasEntrypoint store epName epParam epStore => StoreEntrypointOps store epName epParam epStore -- | Indicates a submap with given key and value types. data (k2 :: k) ~> (v :: k1) infix 9 ~> -- | Indicates a stored entrypoint with the given param and -- store types. data (param :: k) ::-> (store :: k1) infix 9 ::-> -- | Concise way to write down constraints with expected content of a -- storage. -- -- Use it like follows: -- --
--   type StorageConstraint store = StorageContains store
--     [ "fieldInt" := Int
--     , "fieldNat" := Nat
--     , "epsToNat" := Int ::-> Nat
--     , "balances" := Address ~> Int
--     ]
--   
type family StorageContains store (content :: [NamedField]) -- | Unwrap a constructor with the given name. Useful for sum types. unwrapUnsafe_ :: forall dt (name :: Symbol) (st :: [Type]). InstrUnwrapC dt name => Label name -> (dt & st) :-> (CtorOnlyField name dt : st) -- | Wrap entry in single-field constructor. Useful for sum types. wrapOne :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapOneC dt name => Label name -> (CtorOnlyField name dt : st) :-> (dt & st) -- | Wrap entry in constructor. Useful for sum types. wrap_ :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapC dt name => Label name -> AppendCtorField (GetCtorField dt name) st :-> (dt & st) -- | Lift an instruction to field constructor. fieldCtor :: forall (st :: [Type]) f. HasCallStack => (st :-> (f & st)) -> FieldConstructor st f -- | Decompose a complex object into its fields deconstruct :: forall dt (fields :: [Type]) (st :: [Type]). (InstrDeconstructC dt, KnownList fields, ToTs fields ~ ToTs (ConstructorFieldTypes dt)) => (dt & st) :-> (fields ++ st) -- | Construct an object from fields on the stack. constructStack :: forall dt (fields :: [Type]) (st :: [Type]). (InstrConstructC dt, ToTs fields ~ ToTs (ConstructorFieldTypes dt), KnownList fields) => (fields ++ st) :-> (dt & st) -- | Apply given modifier to a datatype field. modifyField :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, InstrSetFieldC dt name) => Label name -> (forall (st0 :: [Type]). () => (GetFieldType dt name : st0) :-> (GetFieldType dt name : st0)) -> (dt & st) :-> (dt & st) -- | Like getField, but leaves field named. getFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> ((name :! GetFieldType dt name) & (dt : st)) -- | Extract a field of a datatype, leaving the original datatype on stack. getField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> (GetFieldType dt name & (dt : st)) -- | Like toField, but leaves field named. toFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> ((name :! GetFieldType dt name) & st) -- | Extract a field of a datatype replacing the value of this datatype -- with the extracted field. -- -- For this and the following functions you have to specify field name -- which is either record name or name attached with (:!) -- operator. toField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> (GetFieldType dt name & st) -- | Like HasField, but allows constrainting field type. type HasFieldOfType dt (fname :: Symbol) fieldTy = (HasField dt fname, GetFieldType dt fname ~ fieldTy) -- | A pair of field name and type. data NamedField NamedField :: Symbol -> Type -> NamedField type (n :: Symbol) := ty = 'NamedField n ty infixr 0 := -- | Shortcut for multiple HasFieldOfType constraints. type family HasFieldsOfType dt (fs :: [NamedField]) -- | Lorentz analogy of CaseClause, it works on plain Type -- types. data CaseClauseL (inp :: [Type]) (out :: [Type]) (param :: CaseClauseParam) [CaseClauseL] :: forall (x :: CtorField) (inp :: [Type]) (out :: [Type]) (ctor :: Symbol). (AppendCtorField x inp :-> out) -> CaseClauseL inp out ('CaseClauseParam ctor x) -- | Provides "case" arrow which works on different wrappers for clauses. class CaseArrow (name :: Symbol) body clause | clause -> name, clause -> body -- | Lift an instruction to case clause. -- -- You should write out constructor name corresponding to the clause -- explicitly. Prefix constructor name with "c" letter, otherwise your -- label will not be recognized by Haskell parser. Passing constructor -- name can be circumvented but doing so is not recomended as mentioning -- contructor name improves readability and allows avoiding some -- mistakes. (/->) :: CaseArrow name body clause => Label name -> body -> clause infixr 0 /-> type CaseTC dt (out :: [Type]) (inp :: [Type]) clauses = (InstrCaseC dt, RMap CaseClauses dt, RecFromTuple clauses, clauses ~ Rec CaseClauseL inp out CaseClauses dt) -- | Handlers for most common errors defined in Lorentz. baseErrorDocHandlers :: [NumericErrorDocHandler] -- | Handler for VoidResult. voidResultDocHandler :: NumericErrorDocHandler -- | Handler for all CustomErrors. customErrorDocHandler :: NumericErrorDocHandler -- | Extended version of applyErrorTagToErrorsDoc which accepts -- error handlers. -- -- In most cases that function should be enough for your purposes, but it -- uses a fixed set of base handlers which may be not enough in case when -- you define your own errors. In this case define and pass all the -- necessary handlers to this function. -- -- It fails with error if some of the errors used in the contract -- cannot be handled with given handlers. applyErrorTagToErrorsDocWith :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [NumericErrorDocHandler] -> ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Modify documentation generated for given code so that all -- CustomError mention not their textual error tag rather -- respective numeric one from the given map. -- -- If some documented error is not present in the map, it remains -- unmodified. This function may fail with error if contract uses -- some uncommon errors, see applyErrorTagToErrorsDocWith for -- details. applyErrorTagToErrorsDoc :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Adds a section which explains error tag mapping. data DDescribeErrorTagMap DDescribeErrorTagMap :: Text -> DDescribeErrorTagMap -- | Describes where the error tag map is defined in Haskell code. [detmSrcLoc] :: DDescribeErrorTagMap -> Text -- | Errors for NumericErrorDocHandler data NumericErrorDocHandlerError -- | Handler which changes documentation for one particular error type. data NumericErrorDocHandler -- | Some error with a numeric tag attached. data NumericErrorWrapper (numTag :: Nat) err -- | Make migration script which initializes UStore from scratch. fillUStore :: UStoreTraversable FillUStoreTW template => template -> UStoreMigration () template -- | Like ustoreDecompose, but requires all entries from -- UStore to be recognized. ustoreDecomposeFull :: UStoreTraversable DecomposeUStoreTW template => UStore template -> Either Text template -- | Decompose UStore into separate big_maps and fields. -- -- Since this function needs to UNPACK content of -- UStore to actual keys and values, you have to provide -- UnpackEnv. -- -- Along with resulting value, you get a list of UStore entries -- which were not recognized as belonging to any submap or field -- according to UStore's template - this should be empty unless -- UStore invariants were violated. ustoreDecompose :: UStoreTraversable DecomposeUStoreTW template => UStore template -> Either Text (UStoreContent, template) -- | Make UStore from separate big_maps and fields. mkUStore :: UStoreTraversable MkUStoreTW template => template -> UStore template -- | Declares handlers for UStore creation from template. data MkUStoreTW -- | Declares handlers for UStore conversion to template. data DecomposeUStoreTW -- | Declares handlers for UStore filling via lambda. data FillUStoreTW -- | Get the old version of storage. -- -- This can be applied only in the beginning of migration. -- -- In fact this function is not very useful, all required operations -- should be available for MUStore, but leaving it here just in -- case. mustoreToOld :: forall (touched :: [Symbol]) oldTemplate newTemplate (remDiff :: [DiffItem]) (s :: [Type]). RequireBeInitial touched => (MUStore oldTemplate newTemplate remDiff touched : s) :-> (UStore oldTemplate : s) -- | Modify field which should stay in new version of storage. This does -- not affect remaining diff. migrateModifyField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (s :: [Type]). (HasUField field fieldTy oldTempl, HasUField field fieldTy newTempl) => Label field -> (fieldTy : (MUStore oldTempl newTempl diff touched : s)) :-> (MUStore oldTempl newTempl diff touched : s) -- | Remove field and write new one in place of it. -- -- This is semantically equivalent to dip (migrateRemoveField label) -- >> migrateAddField label, but is cheaper. migrateOverwriteField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy oldFieldTy (marker :: UStoreMarkerType) (oldMarker :: UStoreMarkerType) (newDiff :: [DiffItem]) (newDiff0 :: [DiffItem]) (s :: [Type]). ('(UStoreFieldExt oldMarker oldFieldTy, newDiff0) ~ CoverDiff 'DcRemove field diff, '(UStoreFieldExt marker fieldTy, newDiff) ~ CoverDiff 'DcAdd field newDiff0, HasUField field fieldTy newTempl) => Label field -> (fieldTy : (MUStore oldTempl newTempl diff touched : s)) :-> (MUStore oldTempl newTempl newDiff (field : touched) : s) -- | Get and remove a field from old version of UStore. -- -- You probably want to use this more often than plain -- migrateRemoveField. migrateExtractField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (newDiff :: [DiffItem]) (marker :: UStoreMarkerType) (s :: [Type]). ('(UStoreFieldExt marker fieldTy, newDiff) ~ CoverDiff 'DcRemove field diff, HasUField field fieldTy oldTempl, RequireUntouched field (IsElem field touched)) => Label field -> (MUStore oldTempl newTempl diff touched : s) :-> (fieldTy : (MUStore oldTempl newTempl newDiff (field : touched) : s)) -- | Remove a field which should not be present in new version of storage. -- This covers one removal from the diff. -- -- In fact, this action could be performed automatically, but since -- removal is a destructive operation, being explicit about it seems like -- a good thing. migrateRemoveField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (newDiff :: [DiffItem]) (marker :: UStoreMarkerType) (s :: [Type]). ('(UStoreFieldExt marker fieldTy, newDiff) ~ CoverDiff 'DcRemove field diff, HasUField field fieldTy oldTempl) => Label field -> (MUStore oldTempl newTempl diff touched : s) :-> (MUStore oldTempl newTempl newDiff (field : touched) : s) -- | Add a field which was not present before. This covers one addition -- from the diff and any removals of field with given name. -- -- This function cannot overwrite existing field with the same name, if -- this is necessary use migrateOverwriteField which would declare -- removal explicitly. migrateAddField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (newDiff :: [DiffItem]) (marker :: UStoreMarkerType) (s :: [Type]). ('(UStoreFieldExt marker fieldTy, newDiff) ~ CoverDiff 'DcAdd field diff, HasUField field fieldTy newTempl) => Label field -> (fieldTy : (MUStore oldTempl newTempl diff touched : s)) :-> (MUStore oldTempl newTempl newDiff (field : touched) : s) -- | Get a field present in old version of UStore. migrateGetField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (s :: [Type]). (HasUField field fieldTy oldTempl, RequireUntouched field (IsElem field touched)) => Label field -> (MUStore oldTempl newTempl diff touched : s) :-> (fieldTy : (MUStore oldTempl newTempl diff touched : s)) -- | Like setField, but for UStore. ustoreSetField :: forall store (name :: Symbol) (s :: [Type]). FieldAccessC store name => Label name -> (GetUStoreField store name : (UStore store : s)) :-> (UStore store : s) -- | Like getField, but for UStore. -- -- This may fail only if UStore was made up incorrectly during -- contract initialization. ustoreGetField :: forall store (name :: Symbol) (s :: [Type]). FieldAccessC store name => Label name -> (UStore store : s) :-> (GetUStoreField store name : (UStore store : s)) -- | Like toField, but for UStore. -- -- This may fail only if UStore was made up incorrectly during -- contract initialization. ustoreToField :: forall store (name :: Symbol) (s :: [Type]). FieldAccessC store name => Label name -> (UStore store : s) :-> (GetUStoreField store name : s) ustoreDelete :: forall store (name :: Symbol) (s :: [Type]). KeyAccessC store name => Label name -> (GetUStoreKey store name : (UStore store : s)) :-> (UStore store : s) -- | Insert a key-value pair, but fail if it will overwrite some existing -- entry. ustoreInsertNew :: forall store (name :: Symbol) (s :: [Type]). (KeyAccessC store name, ValueAccessC store name) => Label name -> (forall (s0 :: [Type]) (any :: [Type]). () => (GetUStoreKey store name : s0) :-> any) -> (GetUStoreKey store name : (GetUStoreValue store name : (UStore store : s))) :-> (UStore store : s) ustoreInsert :: forall store (name :: Symbol) (s :: [Type]). (KeyAccessC store name, ValueAccessC store name) => Label name -> (GetUStoreKey store name : (GetUStoreValue store name : (UStore store : s))) :-> (UStore store : s) ustoreUpdate :: forall store (name :: Symbol) (s :: [Type]). (KeyAccessC store name, ValueAccessC store name) => Label name -> (GetUStoreKey store name : (Maybe (GetUStoreValue store name) : (UStore store : s))) :-> (UStore store : s) ustoreGet :: forall store (name :: Symbol) (s :: [Type]). (KeyAccessC store name, ValueAccessC store name) => Label name -> (GetUStoreKey store name : (UStore store : s)) :-> (Maybe (GetUStoreValue store name) : s) ustoreMem :: forall store (name :: Symbol) (s :: [Type]). KeyAccessC store name => Label name -> (GetUStoreKey store name : (UStore store : s)) :-> (Bool : s) -- | This constraint can be used if a function needs to work with -- big store, but needs to know only about some submap(s) of it. -- -- It can use all UStore operations for a particular name, key and value -- without knowing whole template. type HasUStore (name :: Symbol) key value store = (KeyAccessC store name, ValueAccessC store name, GetUStoreKey store name ~ key, GetUStoreValue store name ~ value) -- | This constraint can be used if a function needs to work with -- big store, but needs to know only about some field of it. type HasUField (name :: Symbol) ty store = (FieldAccessC store name, GetUStoreField store name ~ ty) -- | Write down all sensisble constraints which given store -- satisfies and apply them to constrained. -- -- This store should have |~> and UStoreField fields in -- its immediate fields, no deep inspection is performed. type HasUStoreForAllIn store constrained = (Generic store, GHasStoreForAllIn constrained Rep store) voidResultTag :: MText -- | view type synonym as described in A1. data View a r -- | void type synonym as described in A1. data Void_ a b -- | Newtype over void result type used in tests to distinguish successful -- void result from other errors. -- -- Usage example: lExpectFailWith (== VoidResult roleMaster)` -- -- This error is special - it can contain arguments of different types -- depending on entrypoint which raises it. data VoidResult r -- | Unlift an UStore to a smaller UStore which is part of -- the former. -- -- This function is not intended for use in migrations, only in normal -- entry points. -- -- Surprisingly, despite smaller UStore may have extra entries, -- this function is safe when used in contract code. Truly, all getters -- and setters are still safe to use. Also, there is no way for the -- resulting small UStore to leak outside of the contract since -- the only place where big_map can appear is contract storage, -- so this small UStore can be either dropped or lifted back via -- liftUStore to appear as part of the new contract's state. -- -- When this function is run as part of standalone instructions sequence, -- not as part of contract code (e.g. in tests), you may get an -- UStore with entries not inherent to it. unliftUStore :: forall template (name :: Symbol) (s :: [Type]). Generic template => Label name -> (UStore template : s) :-> (UStore (GetFieldType template name) : s) -- | Lift an UStore to another UStore which contains all the -- entries of the former under given field. -- -- This function is not intended for use in migrations, only in normal -- entry points. -- -- Note that this function ensures that template of resulting store does -- not contain inner nested templates with duplicated fields, otherwise -- UStore invariants could get broken. liftUStore :: forall template (name :: Symbol) (s :: [Type]). (Generic template, RequireAllUniqueFields template) => Label name -> (UStore (GetFieldType template name) : s) :-> (UStore template : s) -- | Get migration script in case of simple (non-batched) migration. migrationToScript :: UStoreMigration os ns -> MigrationScript os ns -- | Get migration script in case of simple (non-batched) migration. migrationToScriptI :: UStoreMigration os ns -> Identity (MigrationScript os ns) -- | Safe way to create migration scripts for UStore. -- -- You have to supply a code which would transform MUStore, -- coverring required diff step-by-step. All basic instructions work, -- also use migrate* functions from this module to operate with -- MUStore. -- -- This method produces a whole migration, it cannot be splitted in -- batches. In case if your migration is too big to be applied within a -- single transaction, use mkUStoreBatchedMigration. mkUStoreMigration :: forall oldTempl newTempl (_1 :: [Symbol]). Lambda (MUStore oldTempl newTempl (BuildDiff oldTempl newTempl) ('[] :: [Symbol])) (MUStore oldTempl newTempl ('[] :: [DiffItem]) _1) -> UStoreMigration oldTempl newTempl -- | Turn Migration into a whole piece of code for transforming -- storage. -- -- This is not want you'd want to use for contract deployment because of -- gas and operation size limits that Tezos applies to transactions. migrationToLambda :: UStoreMigration oldTemplate newTemplate -> Lambda (UStore oldTemplate) (UStore newTemplate) -- | Keeps information about migration between UStores with two -- given templates. data UStoreMigration oldTempl newTempl -- | Code of migration for UStore. -- -- Invariant: preferably should fit into op size / gas limits (quite -- obvious). Often this stands for exactly one stage of migration (one -- Tezos transaction). newtype MigrationScript oldStore newStore MigrationScript :: Lambda UStore_ UStore_ -> MigrationScript oldStore newStore [unMigrationScript] :: MigrationScript oldStore newStore -> Lambda UStore_ UStore_ type MigrationScript_ = MigrationScript SomeUTemplate SomeUTemplate -- | Information for UStore template required for documentation. -- -- You only need to instantiate this for templates used directly in -- UStore, nested subtemplates do not need this instance. class Typeable template => UStoreTemplateHasDoc template -- | UStore template name as it appears in documentation. -- -- Should be only 1 word. ustoreTemplateDocName :: UStoreTemplateHasDoc template => Text -- | Description of template. ustoreTemplateDocDescription :: UStoreTemplateHasDoc template => Markdown -- | Description of template entries. ustoreTemplateDocContents :: UStoreTemplateHasDoc template => Markdown ustoreTemplateDocDependencies :: UStoreTemplateHasDoc template => [SomeTypeWithDoc] -- | Instantiated for documented UStore markers. class KnownUStoreMarker marker => UStoreMarkerHasDoc (marker :: UStoreMarkerType) -- | Specifies key encoding. -- -- You accept description of field name, and should return how is it -- encoded as key of big_map bytes bytes. ustoreMarkerKeyEncoding :: UStoreMarkerHasDoc marker => Text -> Text -- | Constraint for UStore traversal. type UStoreTraversable way a = (Generic a, GUStoreTraversable way Rep a, UStoreTraversalWay way) -- | Gathers multple fields and BigMaps under one object. -- -- Type argument of this datatype stands for a "store template" - a -- datatype with one constructor and multiple fields, each containing an -- object of type UStoreField or |~> and corresponding -- to single virtual field or BigMap respectively. It's also -- possible to parameterize it with a larger type which is a product of -- types satisfying the above property. data UStore a -- | Describes one virtual big map in the storage. newtype k |~> v UStoreSubMap :: Map k v -> (|~>) k v [unUStoreSubMap] :: (|~>) k v -> Map k v -- | Describes plain field in the storage. newtype UStoreFieldExt (m :: UStoreMarkerType) v UStoreField :: v -> UStoreFieldExt (m :: UStoreMarkerType) v [unUStoreField] :: UStoreFieldExt (m :: UStoreMarkerType) v -> v -- | Specific kind used to designate markers for UStoreFieldExt. -- -- We suggest that fields may serve different purposes and so annotated -- with special markers accordingly, which influences translation to -- Michelson. See example below. -- -- This Haskell kind is implemented like that because we want markers to -- differ from all other types in kind; herewith UStoreMarkerType -- is still an open kind (has potentially infinite number of -- inhabitants). type UStoreMarkerType = UStoreMarker -> Type -- | Just a plain field used as data. type UStoreField = UStoreFieldExt UMarkerPlainField -- | Display type-level information about UStore field with given marker -- and field value type. Used for error messages. type family ShowUStoreField (marker :: UStoreMarkerType) v :: ErrorMessage -- | Allows to specify format of key under which fields of this type are -- stored. Useful to avoid collisions. class KnownUStoreMarker (marker :: UStoreMarkerType) where { -- | Display type-level information about UStore field with given marker -- and field value type. Used for error messages. type family ShowUStoreField (marker :: UStoreMarkerType) v :: ErrorMessage; type ShowUStoreField (marker :: UStoreMarkerType) v = 'Text "field of type " :<>: 'ShowType v; } -- | By field name derive key under which field should be stored. mkFieldMarkerUKey :: KnownUStoreMarker marker => MText -> ByteString -- | Get type of submap key. type GetUStoreKey store (name :: Symbol) = MSKey GetUStore name store -- | Get type of submap value. type GetUStoreValue store (name :: Symbol) = MSValue GetUStore name store -- | Get type of plain field. This ignores marker with field type. type GetUStoreField store (name :: Symbol) = FSValue GetUStore name store -- | Get kind of field. type GetUStoreFieldMarker store (name :: Symbol) = FSMarker GetUStore name store -- | Collect all fields with the given marker. type PickMarkedFields (marker :: UStoreMarkerType) template = GPickMarkedFields marker Rep template -- | Implementation of castDummy for types composed from smaller -- types. It helps to ensure that all necessary constraints are requested -- in instance head. castDummyG :: (Generic a, Generic b, GCanCastTo (Rep a) (Rep b)) => Proxy a -> Proxy b -> () -- | Locally provide bidirectional CanCastTo instance. allowCheckedCoerce :: forall k1 k2 (a :: k1) (b :: k2). Dict (CanCastTo a b, CanCastTo b a) -- | Locally provide given CanCastTo instance. allowCheckedCoerceTo :: forall k1 k2 (b :: k1) (a :: k2). Dict (CanCastTo a b) -- | Pretends that the top item of the stack was coerced. checkedCoercing_ :: forall a b (s :: [Type]). Coercible_ a b => ((b : s) :-> (b : s)) -> (a : s) :-> (a : s) -- | Coerce between types which have an explicit permission for that in the -- face of CanCastTo constraint. checkedCoerce_ :: forall a b (s :: [Type]). Castable_ a b => (a : s) :-> (b : s) -- | Coercion in Haskell world which respects CanCastTo. checkedCoerce :: (CanCastTo a b, Coercible a b) => a -> b -- | Unpack named value. fromNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (NamedF Identity a name : s) :-> (a : s) -- | Lift given value to a named value. toNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (a : s) :-> (NamedF Identity a name : s) -- | Specialized version of coerce_ to unwrap a haskell newtype. coerceUnwrap :: forall a (s :: [Type]). Wrappable a => (a : s) :-> (Unwrappable a : s) -- | Specialized version of coerce_ to wrap into a haskell -- newtype. coerceWrap :: forall a (s :: [Type]). Wrappable a => (Unwrappable a : s) :-> (a : s) fakeCoercing :: forall (s1 :: [Type]) (s2 :: [Type]) (s1' :: [Type]) (s2' :: [Type]). (s1 :-> s2) -> s1' :-> s2' -- | Convert between two stacks via failing. fakeCoerce :: forall (s1 :: [Type]) (s2 :: [Type]). s1 :-> s2 gForcedCoerce_ :: forall k t (a :: k) (b :: k) (s :: [Type]). MichelsonCoercible (t a) (t b) => (t a : s) :-> (t b : s) -- | Convert between values of types that have the same representation. -- -- This function is not safe in a sense that this allows breaking -- invariants of casted type (example: UStore) or may stop -- compile on code changes (example: coercion of pair to a datatype with -- two fields will break if new field is added). Still, produced -- Michelson code will always be valid. -- -- Prefer using one of more specific functions from this module. forcedCoerce_ :: forall a b (s :: [Type]). MichelsonCoercible a b => (a & s) :-> (b & s) -- | Coercion for Haskell world. -- -- We discourage using this function on Lorentz types, consider using -- coerce instead. One of the reasons forthat is that in Lorentz -- it's common to declare types as newtypes consisting of existing -- primitives, and forcedCoerce tends to ignore all phantom type -- variables of newtypes thus violating their invariants. forcedCoerce :: Coercible a b => a -> b -- | Whether two types have the same Michelson representation. type MichelsonCoercible a b = ToT a ~ ToT b -- | Explicitly allowed coercions. -- -- a CanCastTo b proclaims that a can be casted -- to b without violating any invariants of b. -- -- This relation is reflexive; it may be symmetric or not. It -- tends to be composable: casting complex types usually requires -- permission to cast their respective parts; for such types consider -- using castDummyG as implementation of the method of this -- typeclass. -- -- For cases when a cast from a to b requires some -- validation, consider rather making a dedicated function which performs -- the necessary checks and then calls forcedCoerce. class CanCastTo (a :: k) (b :: k1) -- | An optional method which helps passing -Wredundant-constraints check. -- Also, you can set specific implementation for it with specific sanity -- checks. castDummy :: CanCastTo a b => Proxy a -> Proxy b -> () -- | Coercion from a to b is permitted and safe. type Castable_ a b = (MichelsonCoercible a b, CanCastTo a b) -- | Coercions between a to b are permitted and safe. type Coercible_ a b = (MichelsonCoercible a b, CanCastTo a b, CanCastTo b a) -- | If you apply numeric error representation in your contract, -- errorToVal will stop working because it doesn't know about this -- transformation. This function takes this transformation into account. -- If a string is used as a tag, but it is not found in the passed map, -- we conservatively preserve that string (because this whole approach is -- rather a heuristic). errorToValNumeric :: IsError e => ErrorTagMap -> e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r -- | If you apply numeric error representation in your contract, -- errorFromVal will stop working because it doesn't know about -- this transformation. This function takes this transformation into -- account. If a number is used as a tag, but it is not found in the -- passed map, we conservatively preserve that number (because this whole -- approach is rather a heuristic). errorFromValNumeric :: forall (t :: T) e. (KnownT t, IsError e) => ErrorTagMap -> Value t -> Either Text e -- | This function implements the simplest scenario of using this module's -- functionality: 1. Gather all error tags from a single instruction. 2. -- Turn them into error conversion map. 3. Apply this conversion. useNumericErrors :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> (inp :-> out, ErrorTagMap) -- | Similar to applyErrorTagMap, but for case when you have -- excluded some tags from map via excludeErrorTags. Needed, -- because both excludeErrorTags and this function do not tolerate -- unknown errors in contract code (for your safety). applyErrorTagMapWithExclusions :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> ErrorTagExclusions -> (inp :-> out) -> inp :-> out -- | For each typical FAILWITH that uses a string to represent error -- tag this function changes error tag to be a number using the supplied -- conversion map. It assumes that supplied map contains all such strings -- (and will error out if it does not). It will always be the case if you -- gather all error tags using gatherErrorTags and build -- ErrorTagMap from them using addNewErrorTags. applyErrorTagMap :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Remove some error tags from map. This way you say to remain these -- string tags intact, while others will be converted to numbers when -- this map is applied. -- -- Note that later you have to apply this map using -- applyErrorTagMapWithExclusions, otherwise an error would be -- raised. excludeErrorTags :: HasCallStack => ErrorTagExclusions -> ErrorTagMap -> ErrorTagMap -- | Build ErrorTagMap from a set of textual tags. buildErrorTagMap :: HashSet MText -> ErrorTagMap -- | Add more error tags to an existing ErrorTagMap. It is useful -- when your contract consists of multiple parts (e. g. in case of -- contract upgrade), you have existing map for some part and want to add -- tags from another part to it. You can pass empty map as existing one -- if you just want to build ErrorTagMap from a set of textual -- tags. See buildErrorTagMap. addNewErrorTags :: ErrorTagMap -> HashSet MText -> ErrorTagMap -- | Find all textual error tags that are used in typical FAILWITH -- patterns within given instruction. Map them to natural numbers. gatherErrorTags :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> HashSet MText -- | This is a bidirectional map with correspondence between numeric and -- textual error tags. type ErrorTagMap = Bimap Natural MText -- | Tags excluded from map. type ErrorTagExclusions = HashSet MText -- | QuasiQuote that helps generating TypeHasDoc instance. -- -- Usage: -- --
--   [typeDoc| <type> <description> |]
--   [typeDoc| Storage "This is storage description"  |]
--   
-- -- See this tutorial which includes this quasiquote. typeDoc :: QuasiQuoter -- | QuasiQuote that helps generating CustomErrorHasDoc instance. -- -- Usage: -- --
--   [errorDoc| <error-name> <error-type> <error-description> |]
--   [errorDoc| "errorName" exception "Error description" |]
--   
-- -- See this tutorial which includes this quasiquote. errorDoc :: QuasiQuoter -- | QuasiQuote that helps generating ParameterHasEntrypoints -- instance. -- -- Usage: -- --
--   [entrypointDoc| Parameter <parameter-type> <optional-root-annotation> |]
--   [entrypointDoc| Parameter plain |]
--   [entrypointDoc| Parameter plain "root"|]
--   
-- -- See this tutorial which includes this quasiquote. entrypointDoc :: QuasiQuoter -- | Implementation of typeDocMdDescription (of TypeHasDoc -- typeclass) for Haskell types which sole purpose is to be error. typeDocMdDescriptionReferToError :: IsError e => Markdown errorTagToText :: forall (tag :: Symbol). KnownSymbol tag => Text -- | Demote error tag to term level. errorTagToMText :: forall (tag :: Symbol). Label tag -> MText -- | Description of error representation in Haskell. customErrorDocHaskellRepGeneral :: forall (tag :: Symbol). (SingI (ToT (ErrorArg tag)), IsError (CustomError tag), TypeHasDoc (ErrorArg tag), CustomErrorHasDoc tag) => Text -> Proxy tag -> Markdown -- | Fail, providing a reference to the place in the code where this -- function is called. -- -- Like error in Haskell code, this instruction is for internal -- errors only. failUnexpected :: forall (s :: [Type]) (t :: [Type]). MText -> s :-> t -- | Fail with the given Haskell value. failUsing :: forall e (s :: [Type]) (t :: [Type]). IsError e => e -> s :-> t -- | Implementation of errorFromVal via IsoValue. isoErrorFromVal :: forall (t :: T) e. (Typeable t, Typeable (ToT e), IsoValue e) => Value t -> Either Text e -- | Implementation of errorToVal via IsoValue. isoErrorToVal :: (KnownError e, IsoValue e) => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r type ErrorScope (t :: T) = (Typeable t, ConstantScope t) -- | Haskell type representing error. class (Typeable e, ErrorHasDoc e) => IsError e -- | Converts a Haskell error into Value representation. errorToVal :: IsError e => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r -- | Converts a Value into Haskell error. errorFromVal :: forall (t :: T). (IsError e, KnownT t) => Value t -> Either Text e -- | Constraints which we require in a particular instance. You are not -- oblidged to often instantiate this correctly, it is only useful for -- some utilities. type family ErrorRequirements e class Typeable e => ErrorHasDoc e where { -- | Constraints which we require in a particular instance. You are not -- oblidged to often instantiate this correctly, it is only useful for -- some utilities. type family ErrorRequirements e; type ErrorRequirements e = (); } -- | Name of error as it appears in the corresponding section title. errorDocName :: ErrorHasDoc e => Text -- | What should happen for this error to be raised. errorDocMdCause :: ErrorHasDoc e => Markdown -- | Brief version of errorDocMdCause. -- -- This will appear along with the error when mentioned in entrypoint -- description. By default, the first sentence of the full description is -- used. errorDocMdCauseInEntrypoint :: ErrorHasDoc e => Markdown -- | How this error is represented in Haskell. errorDocHaskellRep :: ErrorHasDoc e => Markdown -- | Error class. errorDocClass :: ErrorHasDoc e => ErrorClass -- | Which definitions documentation for this error mentions. errorDocDependencies :: ErrorHasDoc e => [SomeDocDefinitionItem] -- | Captured constraints which we require in a particular instance. This -- is a way to encode a bidirectional instance in the nowaday Haskell, -- for class MyConstraint => ErrorHasDoc MyType instance it -- lets deducing MyConstraint by ErrorHasDoc MyType. -- -- You are not oblidged to always instantiate, it is only useful for some -- utilities which otherwise would not compile. errorDocRequirements :: ErrorHasDoc e => Dict (ErrorRequirements e) -- | Use this type as replacement for () when you really -- want to leave error cause unspecified. data UnspecifiedError UnspecifiedError :: UnspecifiedError -- | Type wrapper for an IsError. data SomeError SomeError :: e -> SomeError -- | Declares a custom error, defining error name - error argument -- relation. -- -- If your error is supposed to carry no argument, then provide -- (). -- -- Note that this relation is defined globally rather than on -- per-contract basis, so define errors accordingly. If your error has -- argument specific to your contract, call it such that error name -- reflects its belonging to this contract. -- -- This is the basic [error format]. type family ErrorArg (tag :: Symbol) -- | Material custom error. -- -- Use this in pattern matches against error (e.g. in tests). data CustomError (tag :: Symbol) CustomError :: Label tag -> ErrorArg tag -> CustomError (tag :: Symbol) [ceTag] :: CustomError (tag :: Symbol) -> Label tag [ceArg] :: CustomError (tag :: Symbol) -> ErrorArg tag type RequireNoArgError (tag :: Symbol) (msg :: ErrorMessage) = (TypeErrorUnless ErrorArg tag == () msg, msg ~ 'Text "Expected no-arg error, but given error requires argument of type " :<>: 'ShowType ErrorArg tag) -- | Error class on how the error should be handled by the client. data ErrorClass -- | Normal expected error. Examples: "insufficient balance", "wallet does -- not exist". ErrClassActionException :: ErrorClass -- | Invalid argument passed to entrypoint. Examples: your entrypoint -- accepts an enum represented as nat, and unknown value is -- provided. This includes more complex cases which involve multiple -- entrypoints. E.g. API provides iterator interface, middleware should -- care about using it hiding complex details and exposing a simpler API -- to user; then an attempt to request non-existing element would also -- correspond to an error from this class. ErrClassBadArgument :: ErrorClass -- | Unexpected error. Most likely it means that there is a bug in the -- contract or the contract has been deployed incorrectly. ErrClassContractInternal :: ErrorClass -- | It's possible to leave error class unspecified. ErrClassUnknown :: ErrorClass class (KnownSymbol tag, TypeHasDoc ErrorArg tag, IsError CustomError tag) => CustomErrorHasDoc (tag :: Symbol) -- | What should happen for this error to be raised. customErrDocMdCause :: CustomErrorHasDoc tag => Markdown -- | Brief version of customErrDocMdCause. This will appear along -- with the error when mentioned in entrypoint description. -- -- By default, the first sentence of the full description is used. customErrDocMdCauseInEntrypoint :: CustomErrorHasDoc tag => Markdown -- | Error class. -- -- By default this returns "unknown error" class; though you should -- provide explicit implementation in order to avoid a warning. customErrClass :: CustomErrorHasDoc tag => ErrorClass -- | Clarification of error argument meaning. -- -- Provide when it's not obvious, e.g. argument is not named with -- :!. -- -- NOTE: This should not be an entire sentence, rather just the -- semantic backbone. -- -- Bad: * Error argument stands for the previous value of -- approval. -- -- Good: * the previous value of approval * pair, first -- argument of which is one thing, and the second is another customErrArgumentSemantics :: CustomErrorHasDoc tag => Maybe Markdown -- | Mentions that contract uses given error. data DError [DError] :: forall e. ErrorHasDoc e => Proxy e -> DError -- | Documentation for custom errors. -- -- Mentions that entrypoint throws given error. data DThrows [DThrows] :: forall e. ErrorHasDoc e => Proxy e -> DThrows mkDEntrypointExample :: NiceParameter a => a -> DEntrypointExample -- | Leave only instructions related to documentation. -- -- This function is useful when your method executes a lambda coming from -- outside, but you know its properties and want to propagate its -- documentation to your contract code. cutLorentzNonDoc :: forall (inp :: [Type]) (out :: [Type]) (s :: [Type]). (inp :-> out) -> s :-> s renderLorentzDocWithGitRev :: forall (inp :: [Type]) (out :: [Type]). DGitRevision -> (inp :-> out) -> LText renderLorentzDoc :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> LText buildLorentzDocWithGitRev :: forall (inp :: [Type]) (out :: [Type]). DGitRevision -> (inp :-> out) -> ContractDoc buildLorentzDoc :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> ContractDoc -- | Modify the example value of an entrypoint data DEntrypointExample DEntrypointExample :: Value t -> DEntrypointExample -- | Remove element with the given type from the stack. dropT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). (DipT inp a inp dinp dout out, dinp ~ (a : dout)) => inp :-> out -- | Dip repeatedly until element of the given type is on top of the stack. -- -- If stack contains multiple entries of this type, compile error is -- raised. dipT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). DipT inp a inp dinp dout out => (dinp :-> dout) -> inp :-> out -- | Duplicate an element of stack referring it by type. -- -- If stack contains multiple entries of this type, compile error is -- raised. dupT :: forall a (st :: [Type]). DupT st a st => st :-> (a : st) class NonZero t -- | Pretty-print a Lorentz contract into Michelson code. printLorentzContract :: (NiceParameterFull cp, NiceStorage st) => Bool -> Contract cp st -> LText -- | Pretty-print a Haskell value as Michelson one. printLorentzValue :: NicePrintedValue v => Bool -> v -> LText -- | Lorentz version of analyzer. analyzeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> AnalyzerRes -- | Like interpretLorentzInstr, but works on lambda rather than -- arbitrary instruction. interpretLorentzLambda :: (IsoValue inp, IsoValue out) => ContractEnv -> Lambda inp out -> inp -> Either MichelsonFailed out -- | Interpret a Lorentz instruction, for test purposes. Note that this -- does not run the optimizer. interpretLorentzInstr :: forall (inp :: [Type]) (out :: [Type]). (IsoValuesStack inp, IsoValuesStack out) => ContractEnv -> (inp :-> out) -> Rec Identity inp -> Either MichelsonFailed (Rec Identity out) -- | Compile a whole contract to Michelson. -- -- Note that compiled contract can be ill-typed in terms of Michelson -- code when some of the compilation options are used (e.g. when -- ccoDisableInitialCast is True, resulted contract can -- be ill-typed). However, compilation with -- defaultContractCompilationOptions should be valid. compileLorentzContract :: (NiceParameterFull cp, NiceStorage st) => Contract cp st -> Contract (ToT cp) (ToT st) -- | Compile contract with defaultCompilationOptions and -- cDisableInitialCast set to False. defaultContract :: ContractCode cp st -> Contract cp st -- | Compile Lorentz code, optionally running the optimizer, string and -- byte transformers. compileLorentzWithOptions :: forall (inp :: [Type]) (out :: [Type]). CompilationOptions -> (inp :-> out) -> Instr (ToTs inp) (ToTs out) -- | For use outside of Lorentz. Will use defaultCompilationOptions. compileLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) -- | Runs Michelson optimizer with default config and does not touch -- strings and bytes. defaultCompilationOptions :: CompilationOptions -- | Options to control Lorentz to Michelson compilation. data CompilationOptions CompilationOptions :: Maybe OptimizerConf -> (Bool, MText -> MText) -> (Bool, ByteString -> ByteString) -> CompilationOptions -- | Config for Michelson optimizer. [coOptimizerConf] :: CompilationOptions -> Maybe OptimizerConf -- | Function to transform strings with. See -- transformStringsLorentz. [coStringTransformer] :: CompilationOptions -> (Bool, MText -> MText) -- | Function to transform byte strings with. See -- transformBytesLorentz. [coBytesTransformer] :: CompilationOptions -> (Bool, ByteString -> ByteString) -- | Wrap parameter into this to locally assign a way to derive entrypoints -- for it. newtype ParameterWrapper deriv cp ParameterWrapper :: cp -> ParameterWrapper deriv cp [unParameterWraper] :: ParameterWrapper deriv cp -> cp type family Unwrappable s -- | Wrappable is similar to lens Wrapped class without the -- method. It provides type family that is mainly used as constraint when -- unwrapping Lorentz instruction into a Haskell newtype and vice versa. class ToT s ~ ToT Unwrappable s => Wrappable s where { type family Unwrappable s; type Unwrappable s = GUnwrappable Rep s; } type family ArithResHs aop n m -- | Lifted ArithOp. class (ArithOp aop ToT n ToT m, NiceComparable n, NiceComparable m, ToT ArithResHs aop n m ~ ArithRes aop ToT n ToT m) => ArithOpHs aop n m where { type family ArithResHs aop n m; } type family UnaryArithResHs aop n -- | Lifted UnaryArithOp. class (UnaryArithOp aop ToT n, NiceComparable n, ToT UnaryArithResHs aop n ~ UnaryArithRes aop ToT n) => UnaryArithOpHs aop n where { type family UnaryArithResHs aop n; } -- | Implementation of ParameterHasEntrypoints which fits for case -- when your contract exposes multiple entrypoints via having sum type as -- its parameter. -- -- In particular, each constructor would produce a homonymous entrypoint -- with argument type equal to type of constructor field (each -- constructor should have only one field). Constructor called -- Default will designate the default entrypoint. data EpdPlain -- | Extension of EpdPlain on parameters being defined as several -- nested datatypes. -- -- In particular, this will traverse sum types recursively, stopping at -- Michelson primitives (like Natural) and constructors with -- number of fields different from one. -- -- It does not assign names to intermediate nodes of Or tree, only -- to the very leaves. -- -- If some entrypoint arguments have custom IsoValue instance, -- this derivation way will not work. As a workaround, you can wrap your -- argument into some primitive (e.g. :!). data EpdRecursive -- | Extension of EpdPlain on parameters being defined as several -- nested datatypes. -- -- In particular, it will traverse the immediate sum type, and require -- another ParameterHasEntrypoints for the inner complex -- datatypes. Only those inner types are considered which are the only -- fields in their respective constructors. Inner types should not -- themselves declare default entrypoint, we enforce this for better -- modularity. Each top-level constructor will be treated as entrypoint -- even if it contains a complex datatype within, in such case that would -- be an entrypoint corresponding to intermediate node in or -- tree. -- -- Comparing to EpdRecursive this gives you more control over -- where and how entrypoints will be derived. data EpdDelegate -- | Extension of EpdPlain, EpdRecursive, and -- EpdDelegate which allow specifying root annotation for the -- parameters. data EpdWithRoot (r :: Symbol) (epd :: k) type List = [] type family MemOpKeyHs c -- | Lifted MemOpKey. class (MemOp ToT c, ToT MemOpKeyHs c ~ MemOpKey ToT c) => MemOpHs c where { type family MemOpKeyHs c; } -- | A useful property which holds for reasonable MapOp instances. -- -- It's a separate thing from MapOpHs because it mentions -- b type parameter. type family IsoMapOpRes c b type family MapOpResHs c :: Type -> Type type family MapOpInpHs c -- | Lifted MapOp. class (MapOp ToT c, ToT MapOpInpHs c ~ MapOpInp ToT c, ToT MapOpResHs c () ~ MapOpRes ToT c ToT ()) => MapOpHs c where { type family MapOpInpHs c; type family MapOpResHs c :: Type -> Type; } type family IterOpElHs c -- | Lifted IterOp. class (IterOp ToT c, ToT IterOpElHs c ~ IterOpEl ToT c) => IterOpHs c where { type family IterOpElHs c; } -- | Lifted SizeOp. -- -- This could be just a constraint alias, but to avoid T types -- appearance in error messages we make a full type class with concrete -- instances. class SizeOp ToT c => SizeOpHs c type family UpdOpParamsHs c type family UpdOpKeyHs c -- | Lifted UpdOp. class (UpdOp ToT c, ToT UpdOpKeyHs c ~ UpdOpKey ToT c, ToT UpdOpParamsHs c ~ UpdOpParams ToT c) => UpdOpHs c where { type family UpdOpKeyHs c; type family UpdOpParamsHs c; } type family GetOpValHs c type family GetOpKeyHs c -- | Lifted GetOp. class (GetOp ToT c, ToT GetOpKeyHs c ~ GetOpKey ToT c, ToT GetOpValHs c ~ GetOpVal ToT c) => GetOpHs c where { type family GetOpKeyHs c; type family GetOpValHs c; } -- | Lifted ConcatOp. class ConcatOp ToT c => ConcatOpHs c -- | Lifted SliceOp. class SliceOp ToT c => SliceOpHs c type family EModOpResHs n m type family EDivOpResHs n m -- | Lifted EDivOp. class (EDivOp ToT n ToT m, NiceComparable n, NiceComparable m, ToT EDivOpResHs n m ~ EDivOpRes ToT n ToT m, ToT EModOpResHs n m ~ EModOpRes ToT n ToT m) => EDivOpHs n m where { type family EDivOpResHs n m; type family EModOpResHs n m; } -- | Similar to valueToScriptExpr, but for values encoded as -- Expressions. This is only used in tests. expressionToScriptExpr :: Expression -> ByteString -- | This function transforms Lorentz values into script_expr. -- -- script_expr is used in RPC as an argument in entrypoint -- designed for getting value by key from the big_map in Babylon. In -- order to convert value to the script_expr we have to pack it, -- take blake2b hash and add specific expr prefix. Take a look -- at -- https://gitlab.com/tezos/tezos/blob/6e25ae8eb385d9975a30388c7a7aa2a9a65bf184/src/proto_005_PsBabyM1/lib_protocol/script_expr_hash.ml -- and -- https://gitlab.com/tezos/tezos/blob/6e25ae8eb385d9975a30388c7a7aa2a9a65bf184/src/proto_005_PsBabyM1/lib_protocol/contract_services.ml#L136 -- for more information. valueToScriptExpr :: NicePackedValue t => t -> ByteString lEncodeValue :: NicePrintedValue a => a -> ByteString lUnpackValue :: NiceUnpackedValue a => ByteString -> Either UnpackError a lPackValue :: NicePackedValue a => a -> ByteString stackType :: forall (s :: [Type]). s :-> s testAssert :: forall (out :: [Type]) (inp :: [Type]). (Typeable (ToTs out), HasCallStack) => Text -> PrintComment (ToTs inp) -> (inp :-> (Bool & out)) -> inp :-> inp printComment :: forall (s :: [Type]). PrintComment (ToTs s) -> s :-> s stackRef :: forall (gn :: Nat) (st :: [T]) (n :: Peano). (n ~ ToPeano gn, SingI n, KnownPeano n, RequireLongerThan st n) => PrintComment st convertContractRef :: forall cp contract2 contract1. (ToContractRef cp contract1, FromContractRef cp contract2) => contract1 -> contract2 -- | Specification of callTAddress to call the default entrypoint. callingDefTAddress :: NiceParameterFull cp => TAddress cp -> ContractRef (GetDefaultEntrypointArg cp) -- | Turn TAddress to ContractRef in Haskell world. -- -- This is an analogy of address to contract convertion -- in Michelson world, thus you have to supply an entrypoint (or call the -- default one explicitly). callingTAddress :: forall cp (mname :: Maybe Symbol). NiceParameterFull cp => TAddress cp -> EntrypointRef mname -> ContractRef (GetEntrypointArgCustom cp mname) -- | Address which remembers the parameter type of the contract it refers -- to. -- -- It differs from Michelson's contract type because it cannot -- contain entrypoint, and it always refers to entire contract parameter -- even if this contract has explicit default entrypoint. newtype TAddress (p :: k) TAddress :: Address -> TAddress (p :: k) [unTAddress] :: TAddress (p :: k) -> Address -- | Address associated with value of contract arg type. -- -- Places where ContractRef can appear are now severely limited, -- this type gives you type-safety of ContractRef but still can be -- used everywhere. This type is not a full-featured one rather a helper; -- in particular, once pushing it on stack, you cannot return it back to -- Haskell world. -- -- Note that it refers to an entrypoint of the contract, not just the -- contract as a whole. In this sense this type differs from -- TAddress. -- -- Unlike with ContractRef, having this type you still cannot be -- sure that the referred contract exists and need to perform a lookup -- before calling it. newtype FutureContract arg FutureContract :: ContractRef arg -> FutureContract arg [unFutureContract] :: FutureContract arg -> ContractRef arg -- | Convert something to Address in Haskell world. -- -- Use this when you want to access state of the contract and are not -- interested in calling it. class ToAddress a toAddress :: ToAddress a => a -> Address -- | Convert something referring to a contract (not specific entrypoint) to -- TAddress in Haskell world. class ToTAddress cp a toTAddress :: ToTAddress cp a => a -> TAddress cp -- | Convert something to ContractRef in Haskell world. class ToContractRef cp contract toContractRef :: ToContractRef cp contract => contract -> ContractRef cp -- | Convert something from ContractAddr in Haskell world. class FromContractRef cp contract fromContractRef :: FromContractRef cp contract => ContractRef cp -> contract -- | Single entrypoint of a contract. -- -- Note that we cannot make it return [[Operation], store] -- because such entrypoint should've been followed by pair, and -- this is not possible if entrypoint implementation ends with -- failWith. type Entrypoint param store = '[param, store] :-> ContractOut store -- | Version of Entrypoint which accepts no argument. type Entrypoint_ store = '[store] :-> ContractOut store optimizeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> inp :-> out optimizeLorentzWithConf :: forall (inp :: [Type]) (out :: [Type]). OptimizerConf -> (inp :-> out) -> inp :-> out -- | Lorentz version of transformBytes. transformBytesLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (ByteString -> ByteString) -> (inp :-> out) -> inp :-> out -- | Lorentz version of transformStrings. transformStringsLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (MText -> MText) -> (inp :-> out) -> inp :-> out -- | Parse textual representation of a Michelson value and turn it into -- corresponding Haskell value. -- -- Note: it won't work in some complex cases, e. g. if there is a lambda -- which uses an instruction which depends on current contract's type. -- Obviously it can not work, because we don't have any information about -- a contract to which this value belongs (there is no such contract at -- all). parseLorentzValue :: KnownValue v => Text -> Either ParseLorentzError v -- | Version of # which performs some optimizations immediately. (##) :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]). (a :-> b) -> (b :-> c) -> a :-> c (#) :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]). (a :-> b) -> (b :-> c) -> a :-> c infixl 8 # -- | Wrap Lorentz instruction with variable annotations, annots -- list has to be non-empty, otherwise this function raises an error. iWithVarAnnotations :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [Text] -> (inp :-> out) -> inp :-> out iForceNotFail :: forall (i :: [Type]) (o :: [Type]). (i :-> o) -> i :-> o iMapAnyCode :: forall (i1 :: [Type]) (i2 :: [Type]) (o :: [Type]). (forall (o' :: [T]). () => Instr (ToTs i1) o' -> Instr (ToTs i2) o') -> (i1 :-> o) -> i2 :-> o iNonFailingCode :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> Instr (ToTs inp) (ToTs out) iAnyCode :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) iGenericIf :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]) (s :: [Type]). (forall (s' :: [T]). () => Instr (ToTs a) s' -> Instr (ToTs b) s' -> Instr (ToTs c) s') -> (a :-> s) -> (b :-> s) -> c :-> s pattern I :: Instr (ToTs inp) (ToTs out) -> inp :-> out pattern FI :: (forall (out' :: [T]). () => Instr (ToTs inp) out') -> inp :-> out -- | Alias for instruction which hides inner types representation via -- T. newtype (inp :: [Type]) :-> (out :: [Type]) LorentzInstr :: RemFail Instr (ToTs inp) (ToTs out) -> (:->) (inp :: [Type]) (out :: [Type]) [unLorentzInstr] :: (:->) (inp :: [Type]) (out :: [Type]) -> RemFail Instr (ToTs inp) (ToTs out) infixr 1 :-> -- | Alias for :->, seems to make signatures more readable -- sometimes. -- -- Let's someday decide which one of these two should remain. type (%>) = (:->) infixr 1 %> type ContractOut st = '[([Operation], st)] type ContractCode cp st = '[(cp, st)] :-> ContractOut st data SomeContractCode [SomeContractCode] :: forall cp st. (NiceParameterFull cp, NiceStorage st) => ContractCode cp st -> SomeContractCode type a & (b :: [Type]) = a : b infixr 2 & type Lambda i o = '[i] :-> '[o] -- | Applicable for wrappers over Lorentz code. class MapLorentzInstr instr -- | Modify all the code under given entity. mapLorentzInstr :: MapLorentzInstr instr => (forall (i :: [Type]) (o :: [Type]). () => (i :-> o) -> i :-> o) -> instr -> instr -- | Constraint applied to a whole parameter type. type NiceParameterFull cp = (Typeable cp, ParameterDeclaresEntrypoints cp) -- | Universal entrypoint calling. parameterEntrypointCallCustom :: forall cp (mname :: Maybe Symbol). ParameterDeclaresEntrypoints cp => EntrypointRef mname -> EntrypointCall cp (GetEntrypointArgCustom cp mname) eprName :: forall (mname :: Maybe Symbol). EntrypointRef mname -> EpName -- | Call root entrypoint safely. sepcCallRootChecked :: (NiceParameter cp, ForbidExplicitDefaultEntrypoint cp) => SomeEntrypointCall cp -- | Call the default entrypoint. parameterEntrypointCallDefault :: ParameterDeclaresEntrypoints cp => EntrypointCall cp (GetDefaultEntrypointArg cp) -- | Prepare call to given entrypoint. -- -- This does not treat calls to default entrypoint in a special way. To -- call default entrypoint properly use -- parameterEntrypointCallDefault. parameterEntrypointCall :: forall cp (name :: Symbol). ParameterDeclaresEntrypoints cp => Label name -> EntrypointCall cp (GetEntrypointArg cp name) -- | Derive annotations for given parameter. parameterEntrypointsToNotes :: ParameterDeclaresEntrypoints cp => ParamNotes (ToT cp) -- | Get entrypoint argument by name. type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type -- | Name and argument of each entrypoint. This may include intermediate -- ones, even root if necessary. -- -- Touching this type family is costly (O(N^2)), don't use it -- often. -- -- Note [order of entrypoints children]: If this contains entrypoints -- referring to indermediate nodes (not leaves) in or tree, then -- each such entrypoint should be mentioned eariler than all of its -- children. type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)] -- | Defines a generalized way to declare entrypoints for various parameter -- types. -- -- When defining instances of this typeclass, set concrete deriv -- argument and leave variable cp argument. Also keep in mind, -- that in presence of explicit default entrypoint, all other Or -- arms should be callable, though you can put this burden on user if -- very necessary. -- -- Methods of this typeclass aim to better type-safety when making up an -- implementation and they may be not too convenient to use; users should -- exploit their counterparts. class EntrypointsDerivation (deriv :: k) cp where { -- | Name and argument of each entrypoint. This may include intermediate -- ones, even root if necessary. -- -- Touching this type family is costly (O(N^2)), don't use it -- often. -- -- Note [order of entrypoints children]: If this contains entrypoints -- referring to indermediate nodes (not leaves) in or tree, then -- each such entrypoint should be mentioned eariler than all of its -- children. type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)]; -- | Get entrypoint argument by name. type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type; } -- | Construct parameter annotations corresponding to expected entrypoints -- set. -- -- This method is implementation detail, for actual notes construction -- use parameterEntrypointsToNotes. epdNotes :: EntrypointsDerivation deriv cp => (Notes (ToT cp), RootAnn) -- | Construct entrypoint caller. -- -- This does not treat calls to default entrypoint in a special way. -- -- This method is implementation detail, for actual entrypoint lookup use -- parameterEntrypointCall. epdCall :: forall (name :: Symbol). (EntrypointsDerivation deriv cp, ParameterScope (ToT cp)) => Label name -> EpConstructionRes (ToT cp) (Eval (EpdLookupEntrypoint deriv cp name)) -- | Description of how each of the entrypoints is constructed. epdDescs :: EntrypointsDerivation deriv cp => Rec EpCallingDesc (EpdAllEntrypoints deriv cp) -- | Ensure that all declared entrypoints are unique. type RequireAllUniqueEntrypoints cp = RequireAllUniqueEntrypoints' ParameterEntrypointsDerivation cp cp type family ParameterEntrypointsDerivation cp -- | Which entrypoints given parameter declares. -- -- Note that usually this function should not be used as constraint, use -- ParameterDeclaresEntrypoints for this purpose. class (EntrypointsDerivation ParameterEntrypointsDerivation cp cp, RequireAllUniqueEntrypoints cp) => ParameterHasEntrypoints cp where { type family ParameterEntrypointsDerivation cp; } -- | Parameter declares some entrypoints. -- -- This is a version of ParameterHasEntrypoints which we actually -- use in constraints. When given type is a sum type or newtype, we refer -- to ParameterHasEntrypoints instance, otherwise this instance is -- not necessary. type ParameterDeclaresEntrypoints cp = (If CanHaveEntrypoints cp ParameterHasEntrypoints cp (), NiceParameter cp, EntrypointsDerivation GetParameterEpDerivation cp cp) -- | Get all entrypoints declared for parameter. type family AllParameterEntrypoints cp :: [(Symbol, Type)] -- | Lookup for entrypoint type by name. -- -- Does not treat default entrypoints in a special way. type family LookupParameterEntrypoint cp :: Symbol -> Exp Maybe Type -- | Get type of entrypoint with given name, fail if not found. type GetEntrypointArg cp (name :: Symbol) = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type TError 'Text "Entrypoint not found: " :<>: 'ShowType name :$$: 'Text "In contract parameter `" :<>: 'ShowType cp :<>: 'Text "`" :: Type -> Type LookupParameterEntrypoint cp name -- | Get type of entrypoint with given name, fail if not found. type GetDefaultEntrypointArg cp = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type Pure cp LookupParameterEntrypoint cp DefaultEpName -- | Ensure that there is no explicit "default" entrypoint. type ForbidExplicitDefaultEntrypoint cp = Eval LiftM3 UnMaybe :: Exp Constraint -> Type -> Exp Constraint -> Maybe Type -> Constraint -> Type Pure Pure () TError 'Text "Parameter used here must have no explicit \"default\" entrypoint" :$$: 'Text "In parameter type `" :<>: 'ShowType cp :<>: 'Text "`" :: Type -> Exp Constraint -> Type LookupParameterEntrypoint cp DefaultEpName -- | Similar to ForbidExplicitDefaultEntrypoint, but in a version -- which the compiler can work with (and which produces errors confusing -- for users :/) type NoExplicitDefaultEntrypoint cp = Eval LookupParameterEntrypoint cp DefaultEpName ~ 'Nothing :: Maybe Type -- | Which entrypoint to call. -- -- We intentionally distinguish default and non-default cases because -- this makes API more details-agnostic. data EntrypointRef (mname :: Maybe Symbol) -- | Call the default entrypoint, or root if no explicit default is -- assigned. [CallDefault] :: EntrypointRef ('Nothing :: Maybe Symbol) -- | Call the given entrypoint; calling default is not treated specially. -- You have to provide entrypoint name via passing it as type argument. -- -- Unfortunatelly, here we cannot accept a label because in most cases -- our entrypoints begin from capital letter (being derived from -- constructor name), while labels must start from a lower-case letter, -- and there is no way to make a conversion at type-level. [Call] :: forall (name :: Symbol). NiceEntrypointName name => EntrypointRef ('Just name) -- | Universal entrypoint lookup. type family GetEntrypointArgCustom cp (mname :: Maybe Symbol) -- | When we call a Lorentz contract we should pass entrypoint name and -- corresponding argument. Ideally we want to statically check that -- parameter has entrypoint with given name and argument. Constraint -- defined by this type class holds for contract with parameter -- cp that have entrypoint matching name with type -- arg. -- -- In order to check this property statically, we need to know entrypoint -- name in compile time, EntrypointRef type serves this purpose. -- If entrypoint name is not known, one can use TrustEpName -- wrapper to take responsibility for presence of this entrypoint. -- -- If you want to call a function which has this constraint, you have two -- options: 1. Pass contract parameter cp using type -- application, pass EntrypointRef as a value and pass entrypoint -- argument. Type system will check that cp has an entrypoint -- with given reference and type. 2. Pass EpName wrapped into -- TrustEpName and entrypoint argument. In this case passing -- contract parameter is not necessary, you do not even have to know it. class HasEntrypointArg (cp :: k) name arg -- | Data returned by this method may look somewhat arbitrary. -- EpName is obviously needed because name can be -- EntrypointRef or TrustEpName. Dict is returned -- because in EntrypointRef case we get this evidence for free and -- don't want to use it. We seem to always need it anyway. useHasEntrypointArg :: HasEntrypointArg cp name arg => name -> (Dict (ParameterScope (ToT arg)), EpName) -- | HasEntrypointArg constraint specialized to default entrypoint. type HasDefEntrypointArg (cp :: k) defEpName defArg = (defEpName ~ EntrypointRef 'Nothing :: Maybe Symbol, HasEntrypointArg cp defEpName defArg) -- | This wrapper allows to pass untyped EpName and bypass checking -- that entrypoint with given name and type exists. newtype TrustEpName TrustEpName :: EpName -> TrustEpName -- | Checks that the given parameter consists of some specific entrypoint. -- Similar as HasEntrypointArg but ensures that the argument -- matches the following datatype. type HasEntrypointOfType param (con :: Symbol) exp = (GetEntrypointArgCustom param 'Just con ~ exp, ParameterDeclaresEntrypoints param) type (n :: Symbol) :> ty = 'NamedEp n ty infixr 0 :> -- | Check that the given entrypoint has some fields inside. This interface -- allows for an abstraction of contract parameter so that it requires -- some *minimal* specification, but not a concrete one. type family ParameterContainsEntrypoints param (fields :: [NamedEp]) -- | No entrypoints declared, parameter type will serve as argument type of -- the only existing entrypoint (default one). data EpdNone nicePrintedValueEvi :: NicePrintedValue a :- PrintedValScope (ToT a) niceUnpackedValueEvi :: NiceUnpackedValue a :- UnpackedValScope (ToT a) nicePackedValueEvi :: NicePackedValue a :- PackedValScope (ToT a) niceConstantEvi :: NiceConstant a :- ConstantScope (ToT a) niceStorageEvi :: NiceStorage a :- StorageScope (ToT a) niceParameterEvi :: NiceParameter a :- ParameterScope (ToT a) -- | Gathers constraints, commonly required for values. class (IsoValue a, Typeable a) => KnownValue a -- | Ensure given type does not contain "operation". class (IsoValue a, ForbidOp ToT a) => NoOperation a class (IsoValue a, ForbidContract ToT a) => NoContractType a class (IsoValue a, ForbidBigMap ToT a) => NoBigMap a class (IsoValue a, HasNoNestedBigMaps ToT a) => CanHaveBigMap a -- | Constraint applied to any part of parameter type. -- -- Note that you don't usually apply this constraint to the whole -- parameter, consider using NiceParameterFull in such case. -- -- Using this type is justified e.g. when calling another contract, there -- you usually supply an entrypoint argument, not the whole parameter. type NiceParameter a = (KnownValue a, ProperParameterBetterErrors ToT a) type NiceStorage a = (HasAnnotation a, KnownValue a, ProperStorageBetterErrors ToT a) type NiceConstant a = (KnownValue a, ProperConstantBetterErrors ToT a) type NicePackedValue a = (KnownValue a, ProperPackedValBetterErrors ToT a) type NiceUnpackedValue a = (KnownValue a, ProperUnpackedValBetterErrors ToT a) type NiceFullPackedValue a = (NicePackedValue a, NiceUnpackedValue a) type NicePrintedValue a = (KnownValue a, ProperPrintedValBetterErrors ToT a) type NiceComparable n = (KnownValue n, Comparable ToT n) -- | This class defines the type and field annotations for a given type. -- Right now the type annotations come from names in a named field, and -- field annotations are generated from the record fields. class HasAnnotation a -- | A special type which wraps over a primitive type and states that it -- has entrypoints (one). -- -- Assuming that any type can have entrypoints makes use of Lorentz -- entrypoints too annoying, so for declaring entrypoints for not sum -- types we require an explicit wrapper. newtype ShouldHaveEntrypoints a ShouldHaveEntrypoints :: a -> ShouldHaveEntrypoints a [unHasEntrypoints] :: ShouldHaveEntrypoints a -> a -- | In this strategy the desired depths of contructors (in the type tree) -- and fields (in each constructor's tree) are provided manually and -- simply checked against the number of actual constructors and fields. withDepths :: [CstrDepth] -> GenericStrategy -- | Strategy to make right-balanced instances (both in constructors and -- fields). rightBalanced :: GenericStrategy -- | Strategy to make left-balanced instances (both in constructors and -- fields). leftBalanced :: GenericStrategy -- | Strategy to make fully right-leaning instances (both in constructors -- and fields). rightComb :: GenericStrategy -- | Strategy to make fully left-leaning instances (both in constructors -- and fields). leftComb :: GenericStrategy -- | Helper for making a constructor depth. -- -- Note that this is only intended to be more readable than directly -- using a tuple with withDepths and for the ability to be used in -- places where RebindableSyntax overrides the number literal -- resolution. cstr :: forall (n :: Nat). KnownNat n => [Natural] -> CstrDepth -- | Helper for making a field depth. -- -- Note that this is only intended to be more readable than directly -- using a tuple with withDepths and for the ability to be used in -- places where RebindableSyntax overrides the number literal -- resolution. fld :: forall (n :: Nat). KnownNat n => Natural customGeneric :: String -> GenericStrategy -> Q [Dec] -- | A piece of markdown document. -- -- This is opposed to Text type, which in turn is not supposed to -- contain markup elements. type Markdown = Builder -- | Proxy for a label type that includes the KnownSymbol constraint data Label (name :: Symbol) [Label] :: forall (name :: Symbol). KnownSymbol name => Label name -- | Entrypoint name. -- -- There are two properties we care about: -- --
    --
  1. Special treatment of the default entrypoint name. -- default is prohibited in the CONTRACT instruction -- and in values of address and contract types. -- However, it is not prohibited in the SELF instruction. Hence, -- the value inside EpName can be "default", so -- that we can distinguish SELF and SELF %default. It -- is important to distinguish them because their binary representation -- that is inserted into blockchain is different. For example, -- typechecking SELF %default consumes more gas than -- SELF. In this module, we provide several smart constructors -- with different handling of default, please use the -- appropriate one for your use case.
  2. --
  3. The set of permitted characters. Intuitively, an entrypoint name -- should be valid only if it is a valid annotation (because entrypoints -- are defined using field annotations). However, it is not enforced in -- Tezos. It is not clear whether this behavior is intended. There is an -- upstream issue which received bug label, so probably -- it is considered a bug. Currently we treat it as a bug and deviate -- from upstream implementation by probiting entrypoint names that are -- not valid annotations. If Tezos developers fix it soon, we will be -- happy. If they don't, we should (maybe temporarily) remove this -- limitation from our code. There is an issue in our repo as -- well.
  4. --
data EpName -- | This is a bidirectional pattern that can be used for two purposes: -- --
    --
  1. Construct an EpName referring to the default -- entrypoint.
  2. --
  3. Use it in pattern-matching or in equality comparison to check -- whether EpName refers to the default entrypoint. This is -- trickier because there are two possible EpName values referring -- to the default entrypoints. DefEpName will match only the most -- common one (no entrypoint). However, there is a special case: -- SELF instruction can have explicit %default -- reference. For this reason, it is recommended to use -- isDefEpName instead. Pattern-matching on DefEpName is -- still permitted for backwards compatibility and for the cases when you -- are sure that EpName does not come from the SELF -- instruction.
  4. --
pattern DefEpName :: EpName -- | Michelson string value. -- -- This is basically a mere text with limits imposed by the language: -- https://tezos.gitlab.io/whitedoc/michelson.html#constants -- Although, this document seems to be not fully correct, and thus we -- applied constraints deduced empirically. -- -- You construct an item of this type using one of the following ways: -- -- -- --
--   >>> [mt|Some text|]
--   MTextUnsafe { unMText = "Some text" }
--   
-- -- data MText -- | QuasyQuoter for constructing Michelson strings. -- -- Validity of result will be checked at compile time. Note: -- -- mt :: QuasiQuoter -- | Blake2b_160 hash of a public key. data KeyHash -- | Cryptographic signatures used by Tezos. Constructors correspond to -- PublicKey constructors. -- -- Tezos distinguishes signatures for different curves. For instance, -- ed25519 signatures and secp256k1 signatures are printed differently -- (have different prefix). However, signatures are packed without -- information about the curve. For this purpose there is a generic -- signature which only stores bytes and doesn't carry information about -- the curve. Apparently unpacking from bytes always produces such -- signature. Unpacking from string produces a signature with curve -- information. data Signature -- | Public cryptographic key used by Tezos. There are three cryptographic -- curves each represented by its own constructor. data PublicKey -- | Identifier of a network (babylonnet, mainnet, test network or other). -- Evaluated as hash of the genesis block. -- -- The only operation supported for this type is packing. Use case: -- multisig contract, for instance, now includes chain ID into signed -- data "in order to add extra replay protection between the main chain -- and the test chain". data ChainId -- | Time in the real world. Use the functions below to convert it to/from -- Unix time in seconds. data Timestamp -- | Mutez is a wrapper over integer data type. 1 mutez is 1 token (μTz). data Mutez -- | Safely create Mutez. -- -- This is recommended way to create Mutez from a numeric -- literal; you can't construct all valid Mutez values using -- this function but for small values it works neat. -- -- Warnings displayed when trying to construct invalid Natural or -- Word literal are hardcoded for these types in GHC -- implementation, so we can only exploit these existing rules. toMutez :: Word32 -> Mutez zeroMutez :: Mutez oneMutez :: Mutez timestampFromSeconds :: Integer -> Timestamp timestampFromUTCTime :: UTCTime -> Timestamp -- | Quote a value of type Timestamp in -- yyyy-mm-ddThh:mm:ss[.sss]Z format. -- --
--   >>> formatTimestamp [timestampQuote| 2019-02-21T16:54:12.2344523Z |]
--   "2019-02-21T16:54:12Z"
--   
-- -- Inspired by 'time-quote' library. timestampQuote :: QuasiQuoter -- | Data type corresponding to address structure in Tezos. data Address mkUType :: forall (x :: T). SingI x => Notes x -> Type -- | Address with optional entrypoint name attached to it. TODO: come up -- with better name? data EpAddress EpAddress :: Address -> EpName -> EpAddress -- | Address itself [eaAddress] :: EpAddress -> Address -- | Entrypoint name (might be empty) [eaEntrypoint] :: EpAddress -> EpName -- | Keeps documentation gathered for some piece of contract code. -- -- Used for building documentation of a contract. data ContractDoc ContractDoc :: DocBlock -> DocBlock -> Set SomeDocDefinitionItem -> Set DocItemId -> ContractDoc -- | All inlined doc items. [cdContents] :: ContractDoc -> DocBlock -- | Definitions used in document. -- -- Usually you put some large and repetitive descriptions here. This -- differs from the document content in that it contains sections which -- are always at top-level, disregard the nesting. -- -- All doc items which define docItemId method go here, and only -- they. [cdDefinitions] :: ContractDoc -> DocBlock -- | We remember all already declared entries to avoid cyclic dependencies -- in documentation items discovery. [cdDefinitionsSet] :: ContractDoc -> Set SomeDocDefinitionItem -- | We remember all already used identifiers. (Documentation naturally -- should not declare multiple items with the same identifier because -- that would make references to the respective anchors ambiguous). [cdDefinitionIds] :: ContractDoc -> Set DocItemId -- | A part of documentation to be grouped. Essentially incapsulates -- DocBlock. newtype SubDoc SubDoc :: DocBlock -> SubDoc -- | Several doc items of the same type. data DocSection DocSection :: (NonEmpty $ DocElem d) -> DocSection -- | A doc item which we store, along with related information. data DocElem d DocElem :: d -> Maybe SubDoc -> DocElem d -- | Doc item itself. [deItem] :: DocElem d -> d -- | Subdocumentation, if given item is a group. [deSub] :: DocElem d -> Maybe SubDoc -- | Hides some documentation item which is put to "definitions" section. data SomeDocDefinitionItem [SomeDocDefinitionItem] :: forall d. (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => d -> SomeDocDefinitionItem -- | Hides some documentation item. data SomeDocItem [SomeDocItem] :: forall d. DocItem d => d -> SomeDocItem -- | How to render section name. data DocSectionNameStyle -- | Suitable for block name. DocSectionNameBig :: DocSectionNameStyle -- | Suitable for subsection title within block. DocSectionNameSmall :: DocSectionNameStyle data DocItemRef (p :: DocItemPlacementKind) (r :: DocItemReferencedKind) [DocItemRef] :: DocItemId -> DocItemRef 'DocItemInDefinitions 'True [DocItemRefInlined] :: DocItemId -> DocItemRef 'DocItemInlined 'True [DocItemNoRef] :: DocItemRef 'DocItemInlined 'False -- | Where do we place given doc item. data DocItemPlacementKind -- | Placed in the document content itself. DocItemInlined :: DocItemPlacementKind -- | Placed in dedicated definitions section; can later be referenced. DocItemInDefinitions :: DocItemPlacementKind -- | Position of all doc items of some type. newtype DocItemPos DocItemPos :: (Natural, Text) -> DocItemPos -- | Some unique identifier of a doc item. -- -- All doc items which should be refer-able need to have this identifier. newtype DocItemId DocItemId :: Text -> DocItemId -- | A piece of documentation describing one property of a thing, be it a -- name or description of a contract, or an error throwable by given -- endpoint. -- -- Items of the same type appear close to each other in a rendered -- documentation and form a section. -- -- Doc items are later injected into a contract code via a dedicated -- nop-like instruction. Normally doc items which belong to one section -- appear in resulting doc in the same order in which they appeared in -- the contract. -- -- While documentation framework grows, this typeclass acquires more and -- more methods for fine tuning of existing rendering logic because we -- don't want to break backward compatibility, hope one day we will make -- everything concise :( E.g. all rendering and reording stuff could be -- merged in one method, and we could have several template -- implementations for it which would allow user to specify only stuff -- relevant to his case. class (Typeable d, DOrd d) => DocItem d where { -- | Defines where given doc item should be put. There are two options: 1. -- Inline right here (default behaviour); 2. Put into definitions -- section. -- -- Note that we require all doc items with "in definitions" placement to -- have Eq and Ord instances which comply the following -- law: if two documentation items describe the same entity or property, -- they should be considered equal. type family DocItemPlacement d :: DocItemPlacementKind; type family DocItemReferenced d :: DocItemReferencedKind; type DocItemPlacement d = 'DocItemInlined; type DocItemReferenced d = 'False; } -- | Position of this item in the resulting documentation; the smaller the -- value, the higher the section with this element will be placed. If the -- position is the same as other doc items, they will be placed base on -- their name, alphabetically. -- -- Documentation structure is not necessarily flat. If some doc item -- consolidates a whole documentation block within it, this block will -- have its own placement of items independent from outer parts of the -- doc. docItemPos :: DocItem d => Natural -- | When multiple items of the same type belong to one section, how this -- section will be called. -- -- If not provided, section will contain just untitled content. docItemSectionName :: DocItem d => Maybe Text -- | Description of a section. -- -- Can be used to mention some common things about all elements of this -- section. Markdown syntax is permitted here. docItemSectionDescription :: DocItem d => Maybe Markdown -- | How to render section name. -- -- Takes effect only if section name is set. docItemSectionNameStyle :: DocItem d => DocSectionNameStyle -- | Defines a function which constructs an unique identifier of given doc -- item, if it has been decided to put the doc item into definitions -- section. -- -- Identifier should be unique both among doc items of the same type and -- items of other types. Thus, consider using "typeId-contentId" pattern. docItemRef :: DocItem d => d -> DocItemRef (DocItemPlacement d) (DocItemReferenced d) -- | Render given doc item to Markdown, preferably one line, optionally -- with header. -- -- Accepts the smallest allowed level of header. (Using smaller value -- than provided one will interfere with existing headers thus delivering -- mess). docItemToMarkdown :: DocItem d => HeaderLevel -> d -> Markdown -- | Render table of contents entry for given doc item to Markdown. docItemToToc :: DocItem d => HeaderLevel -> d -> Markdown -- | All doc items which this doc item refers to. -- -- They will automatically be put to definitions as soon as given doc -- item is detected. docItemDependencies :: DocItem d => d -> [SomeDocDefinitionItem] -- | This function accepts doc items put under the same section in the -- order in which they appeared in the contract and returns their new -- desired order. It's also fine to use this function for filtering or -- merging doc items. -- -- Default implementation * leaves inlined items as is; * for items put -- to definitions, lexicographically sorts them by their id. docItemsOrder :: DocItem d => [d] -> [d] -- | Defines where given doc item should be put. There are two options: 1. -- Inline right here (default behaviour); 2. Put into definitions -- section. -- -- Note that we require all doc items with "in definitions" placement to -- have Eq and Ord instances which comply the following -- law: if two documentation items describe the same entity or property, -- they should be considered equal. type family DocItemPlacement d :: DocItemPlacementKind type family DocItemReferenced d :: DocItemReferencedKind -- | Generate DToc entry anchor from docItemRef. mdTocFromRef :: (DocItem d, DocItemReferenced d ~ 'True) => HeaderLevel -> Markdown -> d -> Markdown -- | Get doc item position at term-level. docItemPosition :: DocItem d => DocItemPos -- | Make a reference to doc item in definitions. docDefinitionRef :: (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => Markdown -> d -> Markdown -- | Render documentation for SubDoc. subDocToMarkdown :: HeaderLevel -> SubDoc -> Markdown -- | A hand-made anchor. data DAnchor DAnchor :: Anchor -> DAnchor -- | Comment in the doc (mostly used for licenses) data DComment DComment :: Text -> DComment -- | Repository settings for DGitRevision. newtype GitRepoSettings GitRepoSettings :: (Text -> Text) -> GitRepoSettings -- | By commit sha make up a url to that commit in remote repository. [grsMkGitRevision] :: GitRepoSettings -> Text -> Text data DGitRevision DGitRevisionKnown :: DGitRevisionInfo -> DGitRevision DGitRevisionUnknown :: DGitRevision -- | Description of something. data DDescription DDescription :: Markdown -> DDescription -- | A function which groups a piece of doc under one doc item. type DocGrouping = SubDoc -> SomeDocItem -- | Render given contract documentation to markdown document. contractDocToMarkdown :: ContractDoc -> LText morleyRepoSettings :: GitRepoSettings -- | Make DGitRevision. -- --
--   >>> :t $mkDGitRevision
--   GitRepoSettings -> DGitRevision
--   
mkDGitRevision :: ExpQ type Operation = Operation' Instr type Value = Value' Instr newtype BigMap k v BigMap :: Map k v -> BigMap k v [unBigMap] :: BigMap k v -> Map k v -- | Since Contract name is used to designate contract code, lets -- call analogy of TContract type as follows. -- -- Note that type argument always designates an argument of entrypoint. -- If a contract has explicit default entrypoint (and no root -- entrypoint), ContractRef referring to it can never have the -- entire parameter as its type argument. data ContractRef arg ContractRef :: Address -> SomeEntrypointCall arg -> ContractRef arg [crAddress] :: ContractRef arg -> Address [crEntrypoint] :: ContractRef arg -> SomeEntrypointCall arg type WellTypedIsoValue a = (WellTyped ToT a, IsoValue a) type SomeEntrypointCall arg = SomeEntrypointCallT ToT arg type EntrypointCall param arg = EntrypointCallT ToT param ToT arg -- | Isomorphism between Michelson values and plain Haskell types. -- -- Default implementation of this typeclass converts ADTs to Michelson -- "pair"s and "or"s. class WellTypedToT a => IsoValue a where { -- | Type function that converts a regular Haskell type into a T -- type. type family ToT a :: T; type ToT a = GValueType Rep a; } -- | Converts a Haskell structure into Value representation. toVal :: IsoValue a => a -> Value (ToT a) -- | Converts a Value into Haskell type. fromVal :: IsoValue a => Value (ToT a) -> a -- | Type function that converts a regular Haskell type into a T -- type. type family ToT a :: T -- | Replace type argument of ContractAddr with isomorphic one. coerceContractRef :: ToT a ~ ToT b => ContractRef a -> ContractRef b -- | Constraint for instrConstruct and gInstrConstructStack. type InstrConstructC dt = (GenericIsoValue dt, GInstrConstruct Rep dt) -- | Types of all fields in a datatype. type ConstructorFieldTypes dt = GFieldTypes Rep dt -- | Require this type to be homomorphic. class IsHomomorphic (a :: k) -- | Require two types to be built from the same type constructor. -- -- E.g. HaveCommonTypeCtor (Maybe Integer) (Maybe Natural) is -- defined, while HaveCmmonTypeCtor (Maybe Integer) [Integer] is -- not. class HaveCommonTypeCtor (a :: k) (b :: k1) -- | Doc element with description of a type. data DType [DType] :: forall a. TypeHasDoc a => Proxy a -> DType -- | Data hides some type implementing TypeHasDoc. data SomeTypeWithDoc [SomeTypeWithDoc] :: forall td. TypeHasDoc td => Proxy td -> SomeTypeWithDoc -- | Description for a Haskell type appearing in documentation. class (Typeable a, SingI TypeDocFieldDescriptions a, FieldDescriptionsValid TypeDocFieldDescriptions a a) => TypeHasDoc a where { -- | Description of constructors and fields of a. -- -- See FieldDescriptions documentation for an example of usage. -- -- Descriptions will be checked at compile time to make sure that only -- existing constructors and fields are referenced. -- -- For that check to work instance Generic a is required -- whenever TypeDocFieldDescriptions is not empty. -- -- For implementation of the check see FieldDescriptionsValid type -- family. type family TypeDocFieldDescriptions a :: FieldDescriptions; type TypeDocFieldDescriptions a = '[] :: [(Symbol, (Maybe Symbol, [(Symbol, Symbol)]))]; } -- | Name of type as it appears in definitions section. -- -- Each type must have its own unique name because it will be used in -- identifier for references. -- -- Default definition derives name from Generics. If it does not fit, -- consider defining this function manually. (We tried using Data -- for this, but it produces names including module names which is not do -- we want). typeDocName :: TypeHasDoc a => Proxy a -> Text -- | Explanation of a type. Markdown formatting is allowed. typeDocMdDescription :: TypeHasDoc a => Markdown -- | How reference to this type is rendered, in Markdown. -- -- Examples: -- -- -- -- Consider using one of the following functions as default -- implementation; which one to use depends on number of type arguments -- in your type: -- -- -- -- If none of them fits your purposes precisely, consider using -- customTypeDocMdReference. typeDocMdReference :: TypeHasDoc a => Proxy a -> WithinParens -> Markdown -- | All types which this type directly contains. -- -- Used in automatic types discovery. typeDocDependencies :: TypeHasDoc a => Proxy a -> [SomeDocDefinitionItem] -- | For complex types - their immediate Haskell representation. -- -- For primitive types set this to Nothing. -- -- For homomorphic types use homomorphicTypeDocHaskellRep -- implementation. -- -- For polymorhpic types consider using concreteTypeDocHaskellRep -- as implementation. -- -- Modifier haskellRepNoFields can be used to hide names of -- fields, beneficial for newtypes. -- -- Another modifier called haskellRepStripFieldPrefix can be used -- for datatypes to leave only meaningful part of name in every field. typeDocHaskellRep :: TypeHasDoc a => TypeDocHaskellRep a -- | Final michelson representation of a type. -- -- For homomorphic types use homomorphicTypeDocMichelsonRep -- implementation. -- -- For polymorhpic types consider using -- concreteTypeDocMichelsonRep as implementation. typeDocMichelsonRep :: TypeHasDoc a => TypeDocMichelsonRep a -- | Description of constructors and fields of a. -- -- See FieldDescriptions documentation for an example of usage. -- -- Descriptions will be checked at compile time to make sure that only -- existing constructors and fields are referenced. -- -- For that check to work instance Generic a is required -- whenever TypeDocFieldDescriptions is not empty. -- -- For implementation of the check see FieldDescriptionsValid type -- family. type family TypeDocFieldDescriptions a :: FieldDescriptions -- | Create a DType in form suitable for putting to -- typeDocDependencies. dTypeDep :: TypeHasDoc t => SomeDocDefinitionItem -- | Render a reference to a type which consists of type constructor (you -- have to provide name of this type constructor and documentation for -- the whole type) and zero or more type arguments. customTypeDocMdReference :: (Text, DType) -> [DType] -> WithinParens -> Markdown -- | Derive typeDocMdReference, for homomorphic types only. homomorphicTypeDocMdReference :: (Typeable t, TypeHasDoc t, IsHomomorphic t) => Proxy t -> WithinParens -> Markdown -- | Derive typeDocMdReference, for polymorphic type with one type -- argument, like Maybe Integer. poly1TypeDocMdReference :: forall (t :: Type -> Type) r a. (r ~ t a, Typeable t, Each '[TypeHasDoc] '[r, a], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown -- | Derive typeDocMdReference, for polymorphic type with two type -- arguments, like Lambda Integer Natural. poly2TypeDocMdReference :: forall (t :: Type -> Type -> Type) r a b. (r ~ t a b, Typeable t, Each '[TypeHasDoc] '[r, a, b], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown -- | Implement typeDocDependencies via getting all immediate fields -- of a datatype. -- -- Note: this will not include phantom types, I'm not sure yet how this -- scenario should be handled (@martoon). genericTypeDocDependencies :: (Generic a, GTypeHasDoc (Rep a)) => Proxy a -> [SomeDocDefinitionItem] -- | Implement typeDocHaskellRep for a homomorphic type. -- -- Note that it does not require your type to be of IsHomomorphic -- instance, which can be useful for some polymorhpic types which, for -- documentation purposes, we want to consider homomorphic. -- -- Example: Operation is in fact polymorhpic, but we don't want -- this fact to be reflected in the documentation. homomorphicTypeDocHaskellRep :: (Generic a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep a -- | Implement typeDocHaskellRep on example of given concrete type. -- -- This is a best effort attempt to implement typeDocHaskellRep -- for polymorhpic types, as soon as there is no simple way to preserve -- type variables when automatically deriving Haskell representation of a -- type. concreteTypeDocHaskellRep :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a), HaveCommonTypeCtor b a) => TypeDocHaskellRep b -- | Version of concreteTypeDocHaskellRep which does not ensure -- whether the type for which representation is built is any similar to -- the original type which you implement a TypeHasDoc instance -- for. concreteTypeDocHaskellRepUnsafe :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep b -- | Erase fields from Haskell datatype representation. -- -- Use this when rendering fields names is undesired. haskellRepNoFields :: TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Add field name for newtype. -- -- Since newtype field is automatically erased. Use this -- function to add the desired field name. haskellAddNewtypeField :: Text -> TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Cut fields prefixes which we use according to the style guide. -- -- E.g. cmMyField field will be transformed to myField. haskellRepStripFieldPrefix :: HasCallStack => TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Implement typeDocMichelsonRep for homomorphic type. homomorphicTypeDocMichelsonRep :: SingI (ToT a) => TypeDocMichelsonRep a -- | Implement typeDocMichelsonRep on example of given concrete -- type. -- -- This function exists for the same reason as -- concreteTypeDocHaskellRep. concreteTypeDocMichelsonRep :: forall k a (b :: k). (Typeable a, SingI (ToT a), HaveCommonTypeCtor b a) => TypeDocMichelsonRep b -- | Version of concreteTypeDocHaskellRepUnsafe which does not -- ensure whether the type for which representation is built is any -- similar to the original type which you implement a TypeHasDoc -- instance for. concreteTypeDocMichelsonRepUnsafe :: forall k a (b :: k). (Typeable a, SingI (ToT a)) => TypeDocMichelsonRep b arg :: forall (name :: Symbol) a. Name name -> (name :! a) -> a argDef :: forall (name :: Symbol) a. Name name -> a -> (name :? a) -> a argF :: forall (name :: Symbol) f a. Name name -> NamedF f a name -> f a type (name :: Symbol) :! a = NamedF Identity a name type (name :: Symbol) :? a = NamedF Maybe a name data Rec (a :: u -> Type) (b :: [u]) [RNil] :: forall u (a :: u -> Type). Rec a ('[] :: [u]) [:&] :: forall u (a :: u -> Type) (r :: u) (rs :: [u]). !a r -> !Rec a rs -> Rec a (r : rs) withDict :: HasDict c e => e -> (c => r) -> r class Default a def :: Default a => a -- | This module contains the core of Indigo language: the -- IndigoState monad, a datatype that represents its state. It -- also includes some convenient functions to work with the state in -- IndigoM, to provide rebindable syntax. -- -- The IndigoState monad implements the functionality of a -- symbolic interpreter. During its execution Lorentz code is being -- generated. module Indigo.Internal.State -- | IndigoState monad. It's basically Control.Monad.Indexed.State , -- however this package is not in the used lts and it doesn't compile. -- -- It takes as input a MetaData (for the initial state) and -- returns a GenCode (for the resulting state and the generated -- Lorentz code). -- -- IndigoState has to be used to write backend typed Lorentz code from -- the corresponding frontend constructions. newtype IndigoState inp out a IndigoState :: (MetaData inp -> GenCode inp out a) -> IndigoState inp out a [runIndigoState] :: IndigoState inp out a -> MetaData inp -> GenCode inp out a usingIndigoState :: MetaData inp -> IndigoState inp out a -> GenCode inp out a -- | Bind for rebindable syntax. -- -- It's basically like the bind for the State monad, but it also -- composes the generated code from m a and a -> m -- b. (>>=) :: forall inp out out1 a b. IndigoState inp out a -> (a -> IndigoState out out1 b) -> IndigoState inp out1 b (=<<) :: (a -> IndigoState out out1 b) -> IndigoState inp out a -> IndigoState inp out1 b -- | Then for rebindable syntax. (>>) :: IndigoState inp out a -> IndigoState out out1 b -> IndigoState inp out1 b -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
--    ($)  ::              (a -> b) ->   a ->   b
--   (<$>) :: Functor f => (a -> b) -> f a -> f b
--   
-- -- Whereas $ is function application, <$> is function -- application lifted over a Functor. -- --

Examples

-- -- Convert from a Maybe Int to a Maybe -- String using show: -- --
--   >>> show <$> Nothing
--   Nothing
--   
--   >>> show <$> Just 3
--   Just "3"
--   
-- -- Convert from an Either Int Int to an -- Either Int String using show: -- --
--   >>> show <$> Left 17
--   Left 17
--   
--   >>> show <$> Right 17
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> (*2) <$> [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> even <$> (2,2)
--   (2,True)
--   
(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | Return for rebindable syntax. return :: a -> IndigoState inp inp a -- | Get current MetaData. iget :: IndigoState inp inp (MetaData inp) -- | Put new GenCode. iput :: GenCode inp out a -> IndigoState inp out a -- | Reference id to a stack cell data RefId -- | Stack element of the symbolic interpreter. -- -- It holds either a reference index that refers to this element or just -- NoRef, indicating that there are no references to this element. data StkEl a [NoRef] :: KnownValue a => StkEl a [Ref] :: KnownValue a => RefId -> StkEl a -- | Stack of the symbolic interpreter. type StackVars (stk :: [Type]) = Rec StkEl stk -- | Resulting state of IndigoM. data GenCode inp out a GenCode :: ~a -> ~MetaData out -> (inp :-> out) -> (out :-> inp) -> GenCode inp out a -- | Interpreter output value [gcOut] :: GenCode inp out a -> ~a -- | Interpreter meta data. [gcMeta] :: GenCode inp out a -> ~MetaData out -- | Generated Lorentz code. [gcCode] :: GenCode inp out a -> inp :-> out -- | Clearing Lorentz code. [gcClear] :: GenCode inp out a -> out :-> inp -- | Initial state of IndigoState. data MetaData stk MetaData :: StackVars stk -> RefId -> MetaData stk -- | Stack of the symbolic interpreter. [mdStack] :: MetaData stk -> StackVars stk -- | Number of allocated variables. [mdRefCount] :: MetaData stk -> RefId emptyMetadata :: MetaData '[] -- | Produces the generated Lorentz code that cleans after itself, leaving -- the same stack as the input one cleanGenCode :: GenCode inp out a -> inp :-> inp type DefaultStack stk = Default (MetaData stk) instance GHC.Base.Functor (Indigo.Internal.State.IndigoState inp out) instance GHC.Base.Functor (Indigo.Internal.State.GenCode inp out) instance GHC.Num.Num Indigo.Internal.State.RefId instance GHC.Real.Real Indigo.Internal.State.RefId instance GHC.Classes.Ord Indigo.Internal.State.RefId instance GHC.Classes.Eq Indigo.Internal.State.RefId instance GHC.Generics.Generic Indigo.Internal.State.RefId instance GHC.Show.Show Indigo.Internal.State.RefId instance Data.Default.Class.Default (Indigo.Internal.State.MetaData '[]) instance (Lorentz.Constraints.Scopes.KnownValue x, Data.Default.Class.Default (Indigo.Internal.State.MetaData xs)) => Data.Default.Class.Default (Indigo.Internal.State.MetaData (x : xs)) instance Data.Type.Equality.TestEquality Indigo.Internal.State.StkEl module Indigo.Internal.Object -- | A object that can be either stored in the single stack cell or split -- into fields. Fields are identified by their names. -- -- f is a functor to be applied to each of field names. data IndigoObjectF f a -- | Value stored on the stack, it might be either complex product type, -- like (a, b), Storage, etc, or sum type like Either, or -- primitive like Int, Operation, etc. -- -- Laziness of RefId is needed here to make possible to put -- error in a variable. This is used as a workaround in -- Indigo.Compilation.Lambda. [Cell] :: KnownValue a => ~RefId -> IndigoObjectF f a -- | Decomposed product type, which is NOT stored as one cell on the stack. [Decomposed] :: ComplexObjectC a => Rec f (ConstructorFieldNames a) -> IndigoObjectF f a -- | Auxiliary datatype to define a variable. Keeps field name as type -- param data NamedFieldVar a name [NamedFieldVar] :: IsObject (GetFieldType a name) => {unFieldVar :: Var (GetFieldType a name)} -> NamedFieldVar a name -- | Like NamedFieldVar, but this one doesn't keep name of a field data TypedFieldVar a [TypedFieldVar] :: IsObject a => Var a -> TypedFieldVar a type FieldTypes a = MapGFT a (ConstructorFieldNames a) -- | Variable exposed to a user. -- -- Var represents the tree of fields. Each field is Var -- itself: either a value on the stack or Rec of its direct -- fields. type Var a = IndigoObjectF (NamedFieldVar a) a -- | Convert a list of fields from name-based list to type-based one namedToTypedRec :: forall a f g. (forall name. f name -> g (GetFieldType a name)) -> Rec f (ConstructorFieldNames a) -> Rec g (FieldTypes a) -- | Convert a list of fields from type-based list to named-based one typedToNamedRec :: forall a f g. KnownList (ConstructorFieldNames a) => (forall name. f (GetFieldType a name) -> g name) -> Rec f (FieldTypes a) -> Rec g (ConstructorFieldNames a) namedToTypedFieldVar :: forall a name. NamedFieldVar a name -> TypedFieldVar (GetFieldType a name) typedToNamedFieldVar :: forall a name. TypedFieldVar (GetFieldType a name) -> NamedFieldVar a name class IsObject' (TypeDecision a) a => IsObject a complexObjectDict :: forall a. IsObject a => Maybe (Dict (ComplexObjectC a)) type ComplexObjectC a = (ToDeconstructC a, ToConstructC a, AllConstrained IsObject (FieldTypes a)) castFieldConstructors :: forall a st. CastFieldConstructors (FieldTypes a) (ConstructorFieldTypes a) => Rec (FieldConstructor st) (FieldTypes a) -> Rec (FieldConstructor st) (ConstructorFieldTypes a) -- | Given a MetaData and a Peano singleton for a depth, it -- puts a new Var at that depth (0-indexed) and returns it with -- the updated MetaData. -- -- If there is a Var there already it is used and the -- MetaData not changed. withVarAt :: (KnownValue a, a ~ At n inp, RequireLongerThan inp n) => MetaData inp -> Sing n -> (MetaData inp, Var a) -- | Create a variable referencing the element on top of the stack. makeTopVar :: KnownValue x => IndigoState (x & inp) (x & inp) (Var x) -- | Push a new stack element with a reference to it. Return the variable -- referencing this element. pushRefMd :: KnownValue x => MetaData stk -> (Var x, MetaData (x & stk)) -- | Push a new stack element without a reference to it. pushNoRefMd :: KnownValue a => MetaData inp -> MetaData (a & inp) -- | Remove the top element of the stack. It's supposed that no variable -- refers to this element. popNoRefMd :: MetaData (a & inp) -> MetaData inp type Ops = [Operation] -- | Allows to get a variable with operations type HasSideEffects = Given (Var Ops) -- | Return a variable which refers to a stack cell with operations operationsVar :: HasSideEffects => Var Ops -- | Allows to get a variable with storage type HasStorage st = Given (Var st) -- | Return a variable which refers to a stack cell with storage storageVar :: HasStorage st => Var st instance Indigo.Internal.Object.IsObject' (Indigo.Internal.Object.TypeDecision a) a => Indigo.Internal.Object.IsObject a instance Lorentz.Constraints.Scopes.KnownValue a => Indigo.Internal.Object.IsObject' 'Indigo.Internal.Object.PrimitiveD a instance Lorentz.Constraints.Scopes.KnownValue a => Indigo.Internal.Object.IsObject' 'Indigo.Internal.Object.SumTypeD a instance Indigo.Internal.Object.ComplexObjectC a => Indigo.Internal.Object.IsObject' 'Indigo.Internal.Object.ProductTypeD a -- | This module contains the logic to lookup Vars in a stack and -- the actions to manipulate it. -- -- For efficiency, actions are implemented using Lorentz macros. To do so -- every necessary constraint is checked at runtime. module Indigo.Internal.Lookup -- | Puts a copy of the value for the given Var on top of the -- stack varActionGet :: forall a stk. KnownValue a => RefId -> StackVars stk -> stk :-> (a & stk) -- | Sets the value for the given Var to the topmost value on the -- stack varActionSet :: forall a stk. KnownValue a => RefId -> StackVars stk -> (a & stk) :-> stk -- | Updates the value for the given Var with the topmost value on -- the stack using the given binary instruction. varActionUpdate :: forall a b stk. (KnownValue a, KnownValue b) => RefId -> StackVars stk -> ('[b, a] :-> '[a]) -> (b : stk) :-> stk -- | Given a stack with a list of Operations on its bottom, updates -- it by appending the Operation on the top. varActionOperation :: HasSideEffects => StackVars stk -> (Operation : stk) :-> stk rtake :: Sing n -> Rec any s -> Rec any (Take n s) rdrop :: Sing n -> Rec any s -> Rec any (Drop n s) instance Data.Type.Equality.TestEquality Indigo.Internal.Lookup.TVal -- | This module serves the purpose of listing hiding rules of -- Prelude that conflicts with Indigo exported functions. module Indigo.Prelude -- | Append two lists, i.e., -- --
--   [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
--   [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
--   
-- -- If the first list is not finite, the result is the first list. (++) :: [a] -> [a] -> [a] infixr 5 ++ -- | The value of seq a b is bottom if a is bottom, and -- otherwise equal to b. In other words, it evaluates the first -- argument a to weak head normal form (WHNF). seq is -- usually introduced to improve performance by avoiding unneeded -- laziness. -- -- A note on evaluation order: the expression seq a b does -- not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq -- returns a value. In particular, this means that b may be -- evaluated before a. If you need to guarantee a specific order -- of evaluation, you must use the function pseq from the -- "parallel" package. seq :: a -> b -> b infixr 0 `seq` -- | O(n). filter, applied to a predicate and a list, returns -- the list of those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
-- --
--   >>> filter odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | O(min(m,n)). zip takes two lists and returns a list of -- corresponding pairs. -- --
--   zip [1, 2] ['a', 'b'] = [(1, 'a'), (2, 'b')]
--   
-- -- If one input list is short, excess elements of the longer list are -- discarded: -- --
--   zip [1] ['a', 'b'] = [(1, 'a')]
--   zip [1, 2] ['a'] = [(1, 'a')]
--   
-- -- zip is right-lazy: -- --
--   zip [] _|_ = []
--   zip _|_ [] = _|_
--   
-- -- zip is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zip :: [a] -> [b] -> [(a, b)] -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
--   f x | x < 0     = ...
--       | otherwise = ...
--   
otherwise :: Bool -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
--   f $ g $ h x  =  f (g (h x))
--   
-- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is levity-polymorphic in its result -- type, so that foo $ True where foo :: Bool -> -- Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b -- | Conditional failure of Alternative computations. Defined by -- --
--   guard True  = pure ()
--   guard False = empty
--   
-- --

Examples

-- -- Common uses of guard include conditionally signaling an error -- in an error monad and conditionally rejecting the current choice in an -- Alternative-based parser. -- -- As an example of signaling an error in the error monad Maybe, -- consider a safe division function safeDiv x y that returns -- Nothing when the denominator y is zero and -- Just (x `div` y) otherwise. For example: -- --
--   >>> safeDiv 4 0
--   Nothing
--   >>> safeDiv 4 2
--   Just 2
--   
-- -- A definition of safeDiv using guards, but not guard: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y | y /= 0    = Just (x `div` y)
--               | otherwise = Nothing
--   
-- -- A definition of safeDiv using guard and Monad -- do-notation: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y = do
--     guard (y /= 0)
--     return (x `div` y)
--   
guard :: Alternative f => Bool -> f () -- | The join function is the conventional monad join operator. It -- is used to remove one level of monadic structure, projecting its bound -- argument into the outer level. -- --

Examples

-- -- A common use of join is to run an IO computation -- returned from an STM transaction, since STM transactions -- can't perform IO directly. Recall that -- --
--   atomically :: STM a -> IO a
--   
-- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
--   atomically :: STM (IO b) -> IO (IO b)
--   join       :: IO (IO b)  -> IO b
--   
-- -- we can compose them as -- --
--   join . atomically :: STM (IO b) -> IO b
--   
-- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- -- -- --
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y >= fromEnum x = maxBound
--             | otherwise                = minBound
--   
class Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- -- enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..] with [n,n'..] = -- enumFromThen n n', a possible implementation being -- enumFromThen n n' = n : n' : worker (f x) (f x n'), -- worker s v = v : worker s (s v), x = fromEnum n' - -- fromEnum n and f n y | n > 0 = f (n - 1) (succ y) | n < -- 0 = f (n + 1) (pred y) | otherwise = y For example: -- -- enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m] with [n..m] = -- enumFromTo n m, a possible implementation being enumFromTo n -- m | n <= m = n : enumFromTo (succ n) m | otherwise = []. For -- example: -- -- enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m] with [n,n'..m] -- = enumFromThenTo n n' m, a possible implementation being -- enumFromThenTo n n' m = worker (f x) (c x) n m, x = -- fromEnum n' - fromEnum n, c x = bool (>=) ((x -- 0) f n y | n > 0 = f (n - 1) (succ y) | n < 0 = f (n + -- 1) (pred y) | otherwise = y and worker s c v m | c v m = v : -- worker s c (s v) m | otherwise = [] For example: -- -- enumFromThenTo :: Enum a => a -> a -> a -> [a] -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- The Haskell Report defines no laws for Eq. However, == -- is customarily expected to implement an equivalence relationship where -- two values comparing equal are indistinguishable by "public" -- functions, with a "public" function being one not allowing to see -- implementation details. For example, for a type representing -- non-normalised natural numbers modulo 100, a "public" function doesn't -- make the difference between 1 and 201. It is expected to have the -- following properties: -- -- -- -- Minimal complete definition: either == or /=. class Eq a -- | Trigonometric and hyperbolic functions and related functions. -- -- The Haskell Report defines no laws for Floating. However, -- (+), (*) and exp are -- customarily expected to define an exponential field and have the -- following properties: -- -- class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a infixr 8 ** -- | Fractional numbers, supporting real division. -- -- The Haskell Report defines no laws for Fractional. However, -- (+) and (*) are customarily expected -- to define a division ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- Fractional implement a field. However, all instances in -- base do. class Num a => Fractional a -- | Reciprocal fraction. recip :: Fractional a => a -> a -- | Conversion from a Rational (that is Ratio -- Integer). A floating literal stands for an application of -- fromRational to a value of type Rational, so such -- literals have type (Fractional a) => a. fromRational :: Fractional a => Rational -> a -- | Integral numbers, supporting integer division. -- -- The Haskell Report defines no laws for Integral. However, -- Integral instances are customarily expected to define a -- Euclidean domain and have the following properties for the -- div/mod and quot/rem pairs, given suitable -- Euclidean functions f and g: -- -- -- -- An example of a suitable Euclidean function, for Integer's -- instance, is abs. class (Real a, Enum a) => Integral a -- | integer division truncated toward zero quot :: Integral a => a -> a -> a -- | integer remainder, satisfying -- --
--   (x `quot` y)*y + (x `rem` y) == x
--   
rem :: Integral a => a -> a -> a -- | simultaneous quot and rem quotRem :: Integral a => a -> a -> (a, a) -- | simultaneous div and mod divMod :: Integral a => a -> a -> (a, a) -- | conversion to Integer toInteger :: Integral a => a -> Integer infixl 7 `quot` infixl 7 `rem` -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: Type -> Type) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> (a -> m b) -> m b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. (>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a infixl 1 >>= infixl 1 >> -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. class Functor (f :: Type -> Type) fmap :: Functor f => (a -> b) -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | Basic numeric class. -- -- The Haskell Report defines no laws for Num. However, -- (+) and (*) are customarily expected -- to define a ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- both Num and Ord implement an ordered ring. Indeed, in -- base only Integer and Rational do. class Num a -- | Unary negation. negate :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | The Ord class is used for totally ordered datatypes. -- -- Instances of Ord can be derived for any user-defined datatype -- whose constituent types are in Ord. The declared order of the -- constructors in the data declaration determines the ordering in -- derived Ord instances. The Ordering datatype allows a -- single comparison to determine the precise ordering of two objects. -- -- The Haskell Report defines no laws for Ord. However, -- <= is customarily expected to implement a non-strict partial -- order and have the following properties: -- -- -- -- Note that the following operator interactions are expected to hold: -- --
    --
  1. x >= y = y <= x
  2. --
  3. x < y = x <= y && x /= y
  4. --
  5. x > y = y < x
  6. --
  7. x < y = compare x y == LT
  8. --
  9. x > y = compare x y == GT
  10. --
  11. x == y = compare x y == EQ
  12. --
  13. min x y == if x <= y then x else y = True
  14. --
  15. max x y == if x >= y then x else y = True
  16. --
-- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a -- | Parsing of Strings, producing values. -- -- Derived instances of Read make the following assumptions, which -- derived instances of Show obey: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readsPrec d r =  readParen (d > app_prec)
--                            (\r -> [(Leaf m,t) |
--                                    ("Leaf",s) <- lex r,
--                                    (m,t) <- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d > up_prec)
--                            (\r -> [(u:^:v,w) |
--                                    (u,s) <- readsPrec (up_prec+1) r,
--                                    (":^:",t) <- lex s,
--                                    (v,w) <- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   
-- -- Note that right-associativity of :^: is unused. -- -- The derived instance in GHC is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" <- lexP
--                                    m <- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u <- step readPrec
--                                    Symbol ":^:" <- lexP
--                                    v <- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   
-- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
--   instance Read T where
--     readPrec     = ...
--     readListPrec = readListPrecDefault
--   
class Read a class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- -- -- -- The default definitions of the ceiling, floor, -- truncate and round functions are in terms of -- properFraction. properFraction :: (RealFrac a, Integral b) => a -> (b, a) -- | truncate x returns the integer nearest x -- between zero and x truncate :: (RealFrac a, Integral b) => a -> b -- | round x returns the nearest integer to x; the -- even integer if x is equidistant between two integers round :: (RealFrac a, Integral b) => a -> b -- | ceiling x returns the least integer not less than -- x ceiling :: (RealFrac a, Integral b) => a -> b -- | floor x returns the greatest integer not greater than -- x floor :: (RealFrac a, Integral b) => a -> b -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Show is equivalent to -- --
--   instance (Show a) => Show (Tree a) where
--   
--          showsPrec d (Leaf m) = showParen (d > app_prec) $
--               showString "Leaf " . showsPrec (app_prec+1) m
--            where app_prec = 10
--   
--          showsPrec d (u :^: v) = showParen (d > up_prec) $
--               showsPrec (up_prec+1) u .
--               showString " :^: "      .
--               showsPrec (up_prec+1) v
--            where up_prec = 5
--   
-- -- Note that right-associativity of :^: is ignored. For example, -- -- class Show a -- | The class Typeable allows a concrete representation of a type -- to be calculated. class Typeable (a :: k) -- | When a value is bound in do-notation, the pattern on the left -- hand side of <- might not match. In this case, this class -- provides a function to recover. -- -- A Monad without a MonadFail instance may only be used in -- conjunction with pattern that always match, such as newtypes, tuples, -- data types with only a single data constructor, and irrefutable -- patterns (~pat). -- -- Instances of MonadFail should satisfy the following law: -- fail s should be a left zero for >>=, -- --
--   fail s >>= f  =  fail s
--   
-- -- If your Monad is also MonadPlus, a popular definition is -- --
--   fail _ = mzero
--   
class Monad m => MonadFail (m :: Type -> Type) fail :: MonadFail m => String -> m a -- | Class for string-like datastructures; used by the overloaded string -- extension (-XOverloadedStrings in GHC). class IsString a fromString :: IsString a => String -> a -- | A functor with application, providing operations to -- -- -- -- A minimal complete definition must include implementations of -- pure and of either <*> or liftA2. If it -- defines both, then they must behave the same as their default -- definitions: -- --
--   (<*>) = liftA2 id
--   
-- --
--   liftA2 f x y = f <$> x <*> y
--   
-- -- Further, any definition must satisfy the following: -- -- -- -- The other methods have the following default definitions, which may be -- overridden with equivalent specialized implementations: -- -- -- -- As a consequence of these laws, the Functor instance for -- f will satisfy -- -- -- -- It may be useful to note that supposing -- --
--   forall x y. p (q x y) = f x . g y
--   
-- -- it follows from the above that -- --
--   liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v
--   
-- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: Type -> Type) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: Applicative f => f (a -> b) -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. (*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <*> infixl 4 *> infixl 4 <* -- | Data structures that can be folded. -- -- For example, given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Foldable Tree where
--      foldMap f Empty = mempty
--      foldMap f (Leaf x) = f x
--      foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r
--   
-- -- This is suitable even for abstract types, as the monoid is assumed to -- satisfy the monoid laws. Alternatively, one could define -- foldr: -- --
--   instance Foldable Tree where
--      foldr f z Empty = z
--      foldr f z (Leaf x) = f x z
--      foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l
--   
-- -- Foldable instances are expected to satisfy the following -- laws: -- --
--   foldr f z t = appEndo (foldMap (Endo . f) t ) z
--   
-- --
--   foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
--   
-- --
--   fold = foldMap id
--   
-- --
--   length = getSum . foldMap (Sum . const  1)
--   
-- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
--   sum = getSum . foldMap Sum
--   
-- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
--   foldMap f = fold . fmap f
--   
-- -- which implies that -- --
--   foldMap f . fmap g = foldMap (f . g)
--   
class Foldable (t :: Type -> Type) -- | Functors representing data structures that can be traversed from left -- to right. -- -- A definition of traverse must satisfy the following laws: -- -- -- -- A definition of sequenceA must satisfy the following laws: -- -- -- -- where an applicative transformation is a function -- --
--   t :: (Applicative f, Applicative g) => f a -> g a
--   
-- -- preserving the Applicative operations, i.e. -- --
--   t (pure x) = pure x
--   t (f <*> x) = t f <*> t x
--   
-- -- and the identity functor Identity and composition functors -- Compose are from Data.Functor.Identity and -- Data.Functor.Compose. -- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to Functor, e.g. given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Traversable Tree where
--      traverse f Empty = pure Empty
--      traverse f (Leaf x) = Leaf <$> f x
--      traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
--   
-- -- This is suitable even for abstract types, as the laws for -- <*> imply a form of associativity. -- -- The superclass instances should satisfy the following: -- -- class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) -- | Evaluate each action in the structure from left to right, and collect -- the results. For a version that ignores the results see -- sequenceA_. sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class Generic a -- | This class gives the integer associated with a type-level natural. -- There are instances of the class for every concrete literal: 0, 1, 2, -- etc. class KnownNat (n :: Nat) class IsLabel (x :: Symbol) a fromLabel :: IsLabel x a => a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the following: -- -- class Semigroup a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in O(1) by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. stimes :: (Semigroup a, Integral b) => b -> a -> a -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = (<>) since -- base-4.11.0.0. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. mconcat :: Monoid a => [a] -> a data Bool False :: Bool True :: Bool -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data Char -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double D# :: Double# -> Double -- | Single-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- single-precision type. data Float F# :: Float# -> Float -- | A fixed-precision integer type with at least the range [-2^29 .. -- 2^29-1]. The exact range for a given implementation can be -- determined by using minBound and maxBound from the -- Bounded class. data Int -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | Invariant: Jn# and Jp# are used iff value doesn't fit in -- S# -- -- Useful properties resulting from the invariants: -- -- data Integer -- | Type representing arbitrary-precision non-negative integers. -- --
--   >>> 2^100 :: Natural
--   1267650600228229401496703205376
--   
-- -- Operations whose result would be negative throw -- (Underflow :: ArithException), -- --
--   >>> -1 :: Natural
--   *** Exception: arithmetic underflow
--   
data Natural -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | Rational numbers, with numerator and denominator of some -- Integral type. -- -- Note that Ratio's instances inherit the deficiencies from the -- type parameter's. For example, Ratio Natural's Num -- instance has similar problems to Natural's. data Ratio a (:%) :: !a -> !a -> Ratio a -- | Arbitrary-precision rational numbers, represented as a ratio of two -- Integer values. A rational number may be constructed using the -- % operator. type Rational = Ratio Integer -- | A value of type IO a is a computation which, when -- performed, does some I/O before returning a value of type a. -- -- There is really only one way to "perform" an I/O action: bind it to -- Main.main in your program. When your program is run, the I/O -- will be performed. It isn't possible to perform I/O from an arbitrary -- function, unless that function is itself in the IO monad and -- called at some point, directly or indirectly, from Main.main. -- -- IO is a monad, so IO actions can be combined using -- either the do-notation or the >> and >>= -- operations from the Monad class. data IO a -- | A Word is an unsigned integral type, with the same size as -- Int. data Word -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 -- | A value of type Ptr a represents a pointer to an -- object, or an array of objects, which may be marshalled to or from -- Haskell values of type a. -- -- The type a will often be an instance of class Storable -- which provides the marshalling operations. However this is not -- essential, and you can provide your own operations to access the -- pointer. For example you might write small foreign functions to get or -- set the fields of a C struct. data Ptr a -- | A value of type FunPtr a is a pointer to a function -- callable from foreign code. The type a will normally be a -- foreign type, a function type with zero or more arguments where -- -- -- -- A value of type FunPtr a may be a pointer to a foreign -- function, either returned by another foreign function or imported with -- a a static address import like -- --
--   foreign import ccall "stdlib.h &free"
--     p_free :: FunPtr (Ptr a -> IO ())
--   
-- -- or a pointer to a Haskell function created using a wrapper stub -- declared to produce a FunPtr of the correct type. For example: -- --
--   type Compare = Int -> Int -> Bool
--   foreign import ccall "wrapper"
--     mkCompare :: Compare -> IO (FunPtr Compare)
--   
-- -- Calls to wrapper stubs like mkCompare allocate storage, which -- should be released with freeHaskellFunPtr when no longer -- required. -- -- To convert FunPtr values to corresponding Haskell functions, -- one can define a dynamic stub for the specific foreign type, -- e.g. -- --
--   type IntFunction = CInt -> IO ()
--   foreign import ccall "dynamic"
--     mkFun :: FunPtr IntFunction -> IntFunction
--   
data FunPtr a -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --

Examples

-- -- The type Either String Int is the type -- of values which can be either a String or an Int. The -- Left constructor can be used only on Strings, and the -- Right constructor can be used only on Ints: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> s
--   Left "foo"
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> n
--   Right 3
--   
--   >>> :type s
--   s :: Either String Int
--   
--   >>> :type n
--   n :: Either String Int
--   
-- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> fmap (*2) s
--   Left "foo"
--   
--   >>> fmap (*2) n
--   Right 6
--   
-- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
--   >>> import Data.Char ( digitToInt, isDigit )
--   
--   >>> :{
--       let parseEither :: Char -> Either String Int
--           parseEither c
--             | isDigit c = Right (digitToInt c)
--             | otherwise = Left "parse error"
--   
--   >>> :}
--   
-- -- The following should work, since both '1' and '2' -- can be parsed as Ints. -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither '1'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Right 3
--   
-- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither 'm'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Left "parse error"
--   
data Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The kind of constraints, like Show a data Constraint -- | Comparison of type-level naturals, as a function. type family CmpNat (a :: Nat) (b :: Nat) :: Ordering -- | Coercible is a two-parameter class that has instances for -- types a and b if the compiler can infer that they -- have the same representation. This class does not have regular -- instances; instead they are created on-the-fly during type-checking. -- Trying to manually declare an instance of Coercible is an -- error. -- -- Nevertheless one can pretend that the following three kinds of -- instances exist. First, as a trivial base-case: -- --
--   instance Coercible a a
--   
-- -- Furthermore, for every type constructor there is an instance that -- allows to coerce under the type constructor. For example, let -- D be a prototypical type constructor (data or -- newtype) with three type arguments, which have roles -- nominal, representational resp. phantom. -- Then there is an instance of the form -- --
--   instance Coercible b b' => Coercible (D a b c) (D a b' c')
--   
-- -- Note that the nominal type arguments are equal, the -- representational type arguments can differ, but need to have -- a Coercible instance themself, and the phantom type -- arguments can be changed arbitrarily. -- -- The third kind of instance exists for every newtype NT = MkNT -- T and comes in two variants, namely -- --
--   instance Coercible a T => Coercible a NT
--   
-- --
--   instance Coercible T b => Coercible NT b
--   
-- -- This instance is only usable if the constructor MkNT is in -- scope. -- -- If, as a library author of a type constructor like Set a, you -- want to prevent a user of your module to write coerce :: Set T -- -> Set NT, you need to set the role of Set's type -- parameter to nominal, by writing -- --
--   type role Set nominal
--   
-- -- For more details about this feature, please refer to Safe -- Coercions by Joachim Breitner, Richard A. Eisenberg, Simon Peyton -- Jones and Stephanie Weirich. class a ~R# b => Coercible (a :: k) (b :: k) -- | CallStacks are a lightweight method of obtaining a partial -- call-stack at any point in the program. -- -- A function can request its call-site with the HasCallStack -- constraint. For example, we can define -- --
--   putStrLnWithCallStack :: HasCallStack => String -> IO ()
--   
-- -- as a variant of putStrLn that will get its call-site and -- print it, along with the string given as argument. We can access the -- call-stack inside putStrLnWithCallStack with -- callStack. -- --
--   putStrLnWithCallStack :: HasCallStack => String -> IO ()
--   putStrLnWithCallStack msg = do
--     putStrLn msg
--     putStrLn (prettyCallStack callStack)
--   
-- -- Thus, if we call putStrLnWithCallStack we will get a -- formatted call-stack alongside our string. -- --
--   >>> putStrLnWithCallStack "hello"
--   hello
--   CallStack (from HasCallStack):
--     putStrLnWithCallStack, called at <interactive>:2:1 in interactive:Ghci1
--   
-- -- GHC solves HasCallStack constraints in three steps: -- --
    --
  1. If there is a CallStack in scope -- i.e. the enclosing -- function has a HasCallStack constraint -- GHC will append the -- new call-site to the existing CallStack.
  2. --
  3. If there is no CallStack in scope -- e.g. in the GHCi -- session above -- and the enclosing definition does not have an -- explicit type signature, GHC will infer a HasCallStack -- constraint for the enclosing definition (subject to the monomorphism -- restriction).
  4. --
  5. If there is no CallStack in scope and the enclosing -- definition has an explicit type signature, GHC will solve the -- HasCallStack constraint for the singleton CallStack -- containing just the current call-site.
  6. --
-- -- CallStacks do not interact with the RTS and do not require -- compilation with -prof. On the other hand, as they are built -- up explicitly via the HasCallStack constraints, they will -- generally not contain as much information as the simulated call-stacks -- maintained by the RTS. -- -- A CallStack is a [(String, SrcLoc)]. The -- String is the name of function that was called, the -- SrcLoc is the call-site. The list is ordered with the most -- recently called function at the head. -- -- NOTE: The intrepid user may notice that HasCallStack is just an -- alias for an implicit parameter ?callStack :: CallStack. This -- is an implementation detail and should not be considered part -- of the CallStack API, we may decide to change the -- implementation in the future. data CallStack -- | Haskell defines operations to read and write characters from and to -- files, represented by values of type Handle. Each value of -- this type is a handle: a record used by the Haskell run-time -- system to manage I/O with file system objects. A handle has at -- least the following properties: -- -- -- -- Most handles will also have a current I/O position indicating where -- the next input or output operation will occur. A handle is -- readable if it manages only input or both input and output; -- likewise, it is writable if it manages only output or both -- input and output. A handle is open when first allocated. Once -- it is closed it can no longer be used for either input or output, -- though an implementation cannot re-use its storage while references -- remain to it. Handles are in the Show and Eq classes. -- The string produced by showing a handle is system dependent; it should -- include enough information to identify the handle for debugging. A -- handle is equal according to == only to itself; no attempt is -- made to compare the internal state of different handles for equality. data Handle -- | Right-to-left composition of functors. The composition of applicative -- functors is always applicative, but the composition of monads is not -- always a monad. newtype Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) Compose :: f (g a) -> Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) [getCompose] :: Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) -> f (g a) infixr 9 `Compose` infixr 9 `Compose` -- | If Void is uninhabited then any Functor that holds only -- values of type Void is holding no values. vacuous :: Functor f => f Void -> f a -- | Since Void values logically don't exist, this witnesses the -- logical reasoning tool of "ex falso quodlibet". -- --
--   >>> let x :: Either Void Int; x = Right 5
--   
--   >>> :{
--   case x of
--       Right r -> r
--       Left l  -> absurd l
--   :}
--   5
--   
absurd :: Void -> a -- | Uninhabited data type data Void -- | Repeat a value n times. -- --
--   mtimesDefault n a = a <> a <> ... <> a  -- using <> (n-1) times
--   
-- -- Implemented using stimes and mempty. -- -- This is a suitable definition for an mtimes member of -- Monoid. mtimesDefault :: (Integral b, Monoid a) => b -> a -> a -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | Provide a Semigroup for an arbitrary Monoid. -- -- NOTE: This is not needed anymore since Semigroup became -- a superclass of Monoid in base-4.11 and this newtype be -- deprecated at some point in the future. data WrappedMonoid m -- | Option is effectively Maybe with a better instance of -- Monoid, built off of an underlying Semigroup instead of -- an underlying Monoid. -- -- Ideally, this type would not exist at all and we would just fix the -- Monoid instance of Maybe. -- -- In GHC 8.4 and higher, the Monoid instance for Maybe has -- been corrected to lift a Semigroup instance instead of a -- Monoid instance. Consequently, this type is no longer useful. -- It will be marked deprecated in GHC 8.8 and removed in GHC 8.10. newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | The sortWith function sorts a list of elements using the user -- supplied function to project something out of each element sortWith :: Ord b => (a -> b) -> [a] -> [a] -- | A bifunctor is a type constructor that takes two type arguments and is -- a functor in both arguments. That is, unlike with -- Functor, a type constructor such as Either does not need -- to be partially applied for a Bifunctor instance, and the -- methods in this class permit mapping functions over the Left -- value or the Right value, or both at the same time. -- -- Formally, the class Bifunctor represents a bifunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where both the first and second -- arguments are covariant. -- -- You can define a Bifunctor by either defining bimap or -- by defining both first and second. -- -- If you supply bimap, you should ensure that: -- --
--   bimap id idid
--   
-- -- If you supply first and second, ensure: -- --
--   first idid
--   second idid
--   
-- -- If you supply both, you should also ensure: -- --
--   bimap f g ≡ first f . second g
--   
-- -- These ensure by parametricity: -- --
--   bimap  (f . g) (h . i) ≡ bimap f h . bimap g i
--   first  (f . g) ≡ first  f . first  g
--   second (f . g) ≡ second f . second g
--   
class Bifunctor (p :: Type -> Type -> Type) -- | Map over both arguments at the same time. -- --
--   bimap f g ≡ first f . second g
--   
-- --

Examples

-- --
--   >>> bimap toUpper (+1) ('j', 3)
--   ('J',4)
--   
-- --
--   >>> bimap toUpper (+1) (Left 'j')
--   Left 'J'
--   
-- --
--   >>> bimap toUpper (+1) (Right 3)
--   Right 4
--   
bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d -- | Map covariantly over the first argument. -- --
--   first f ≡ bimap f id
--   
-- --

Examples

-- --
--   >>> first toUpper ('j', 3)
--   ('J',3)
--   
-- --
--   >>> first toUpper (Left 'j')
--   Left 'J'
--   
first :: Bifunctor p => (a -> b) -> p a c -> p b c -- | Map covariantly over the second argument. -- --
--   secondbimap id
--   
-- --

Examples

-- --
--   >>> second (+1) ('j', 3)
--   ('j',4)
--   
-- --
--   >>> second (+1) (Right 3)
--   Right 4
--   
second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | Extract everything except the last element of the stream. init :: NonEmpty a -> [a] -- | Extract the last element of the stream. last :: NonEmpty a -> a -- | Extract the possibly-empty tail of the stream. tail :: NonEmpty a -> [a] -- | Extract the first element of the stream. head :: NonEmpty a -> a -- | nonEmpty efficiently turns a normal list into a NonEmpty -- stream, producing Nothing if the input is empty. nonEmpty :: [a] -> Maybe (NonEmpty a) -- | Get a string representation of the current execution stack state. showStackTrace :: IO (Maybe String) -- | Get a trace of the current execution stack state. -- -- Returns Nothing if stack trace support isn't available on -- host machine. getStackTrace :: IO (Maybe [Location]) -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | Direct MonadPlus equivalent of filter. -- --

Examples

-- -- The filter function is just mfilter specialized to the -- list monad: -- --
--   filter = ( mfilter :: (a -> Bool) -> [a] -> [a] )
--   
-- -- An example using mfilter with the Maybe monad: -- --
--   >>> mfilter odd (Just 1)
--   Just 1
--   >>> mfilter odd (Just 2)
--   Nothing
--   
mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | The foldM function is analogous to foldl, except that -- its result is encapsulated in a monad. Note that foldM works -- from left-to-right over the list arguments. This could be an issue -- where (>>) and the `folded function' are not -- commutative. -- --
--   foldM f a1 [x1, x2, ..., xm]
--   
--   ==
--   
--   do
--     a2 <- f a1 x1
--     a3 <- f a2 x2
--     ...
--     f am xm
--   
-- -- If right-to-left evaluation is required, the input list should be -- reversed. -- -- Note: foldM is the same as foldlM foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | The mapAndUnzipM function maps its first argument over a list, -- returning the result as a pair of lists. This function is mainly used -- with complicated data structures or a state monad. mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c]) -- | Repeat an action indefinitely. -- --

Examples

-- -- A common use of forever is to process input from network -- sockets, Handles, and channels (e.g. MVar and -- Chan). -- -- For example, here is how we might implement an echo server, -- using forever both to listen for client connections on a -- network socket and to echo client input on client connection handles: -- --
--   echoServer :: Socket -> IO ()
--   echoServer socket = forever $ do
--     client <- accept socket
--     forkFinally (echo client) (\_ -> hClose client)
--     where
--       echo :: Handle -> IO ()
--       echo client = forever $
--         hGetLine client >>= hPutStrLn client
--   
forever :: Applicative f => f a -> f b -- | Right-to-left composition of Kleisli arrows. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
--   (.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
--   (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
--   
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 <=< -- | Left-to-right composition of Kleisli arrows. (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element of -- a structure, passing an accumulating parameter from left to right, and -- returning a final value of this accumulator together with the new -- structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | One or none. optional :: Alternative f => f a -> f (Maybe a) -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | Fanout: send the input to both argument arrows and combine their -- output. -- -- The default definition may be overridden with a more efficient version -- if desired. (&&&) :: Arrow a => a b c -> a b c' -> a b (c, c') infixr 3 &&& -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | A handle managing output to the Haskell program's standard error -- channel. stderr :: Handle -- | A handle managing input from the Haskell program's standard input -- channel. stdin :: Handle -- | Perform some computation without adding new entries to the -- CallStack. withFrozenCallStack :: HasCallStack => (HasCallStack => a) -> a -- | Return the current CallStack. -- -- Does *not* include the call-site of callStack. callStack :: HasCallStack => CallStack -- | Write the supplied value into a TVar. writeTVar :: TVar a -> a -> STM () -- | Return the current value stored in a TVar. readTVar :: TVar a -> STM a -- | Create a new TVar holding a value supplied newTVar :: a -> STM (TVar a) -- | A monad supporting atomic memory transactions. data STM a -- | Shared memory locations that support atomic memory transactions. data TVar a -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | A mutable variable in the IO monad data IORef a -- | File and directory names are values of type String, whose -- precise meaning is operating system dependent. Files can be opened, -- yielding a handle which can then be used to operate on the contents of -- that file. type FilePath = String -- | Pretty print a CallStack. prettyCallStack :: CallStack -> String -- | Pretty print a SrcLoc. prettySrcLoc :: SrcLoc -> String -- | Any type that you wish to throw or catch as an exception must be an -- instance of the Exception class. The simplest case is a new -- exception type directly below the root: -- --
--   data MyException = ThisException | ThatException
--       deriving Show
--   
--   instance Exception MyException
--   
-- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
--   *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
--   Caught ThisException
--   
-- -- In more complicated examples, you may wish to define a whole hierarchy -- of exceptions: -- --
--   ---------------------------------------------------------------------
--   -- Make the root exception type for all the exceptions in a compiler
--   
--   data SomeCompilerException = forall e . Exception e => SomeCompilerException e
--   
--   instance Show SomeCompilerException where
--       show (SomeCompilerException e) = show e
--   
--   instance Exception SomeCompilerException
--   
--   compilerExceptionToException :: Exception e => e -> SomeException
--   compilerExceptionToException = toException . SomeCompilerException
--   
--   compilerExceptionFromException :: Exception e => SomeException -> Maybe e
--   compilerExceptionFromException x = do
--       SomeCompilerException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make a subhierarchy for exceptions in the frontend of the compiler
--   
--   data SomeFrontendException = forall e . Exception e => SomeFrontendException e
--   
--   instance Show SomeFrontendException where
--       show (SomeFrontendException e) = show e
--   
--   instance Exception SomeFrontendException where
--       toException = compilerExceptionToException
--       fromException = compilerExceptionFromException
--   
--   frontendExceptionToException :: Exception e => e -> SomeException
--   frontendExceptionToException = toException . SomeFrontendException
--   
--   frontendExceptionFromException :: Exception e => SomeException -> Maybe e
--   frontendExceptionFromException x = do
--       SomeFrontendException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make an exception type for a particular frontend compiler exception
--   
--   data MismatchedParentheses = MismatchedParentheses
--       deriving Show
--   
--   instance Exception MismatchedParentheses where
--       toException   = frontendExceptionToException
--       fromException = frontendExceptionFromException
--   
-- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
--   *** Exception: MismatchedParentheses
--   
class (Typeable e, Show e) => Exception e toException :: Exception e => e -> SomeException fromException :: Exception e => SomeException -> Maybe e -- | Render this exception value in a human-friendly manner. -- -- Default implementation: show. displayException :: Exception e => e -> String -- | The Const functor. newtype Const a (b :: k) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | The least element of a non-empty structure with respect to the given -- comparison function. minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | Maybe monoid returning the leftmost non-Nothing value. -- -- First a is isomorphic to Alt Maybe -- a, but precedes it historically. -- --
--   >>> getFirst (First (Just "hello") <> First Nothing <> First (Just "world"))
--   Just "hello"
--   
-- -- Use of this type is discouraged. Note the following equivalence: -- --
--   Data.Monoid.First x === Maybe (Data.Semigroup.First x)
--   
-- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
--   >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world"))
--   Just "world"
--   
-- -- Use of this type is discouraged. Note the following equivalence: -- --
--   Data.Monoid.Last x === Maybe (Data.Semigroup.Last x)
--   
-- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n). stimesIdempotent :: Integral b => b -> a -> a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
--   >>> getDual (mappend (Dual "Hello") (Dual "World"))
--   "WorldHello"
--   
newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | The monoid of endomorphisms under composition. -- --
--   >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--   
--   >>> appEndo computation "Haskell"
--   "Hello, Haskell!"
--   
newtype Endo a Endo :: (a -> a) -> Endo a [appEndo] :: Endo a -> a -> a -- | Boolean monoid under conjunction (&&). -- --
--   >>> getAll (All True <> mempty <> All False)
--   False
--   
-- --
--   >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8]))
--   False
--   
newtype All All :: Bool -> All [getAll] :: All -> Bool -- | Boolean monoid under disjunction (||). -- --
--   >>> getAny (Any True <> mempty <> Any False)
--   True
--   
-- --
--   >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8]))
--   True
--   
newtype Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | Monoid under addition. -- --
--   >>> getSum (Sum 1 <> Sum 2 <> mempty)
--   3
--   
newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
--   >>> getProduct (Product 3 <> Product 4 <> mempty)
--   12
--   
newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | Monoid under <|>. newtype Alt (f :: k -> Type) (a :: k) Alt :: f a -> Alt (f :: k -> Type) (a :: k) [getAlt] :: Alt (f :: k -> Type) (a :: k) -> f a -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: forall (n :: Nat) proxy. KnownNat n => proxy n -> Natural -- | This type represents unknown type-level natural numbers. data SomeNat SomeNat :: Proxy n -> SomeNat -- | The unfoldr function is a `dual' to foldr: while -- foldr reduces a list to a summary value, unfoldr builds -- a list from a seed value. The function takes the element and returns -- Nothing if it is done producing the list or returns Just -- (a,b), in which case, a is a prepended to the list -- and b is used as the next element in a recursive call. For -- example, -- --
--   iterate f == unfoldr (\x -> Just (x, f x))
--   
-- -- In some cases, unfoldr can undo a foldr operation: -- --
--   unfoldr f' (foldr f z xs) == xs
--   
-- -- if the following holds: -- --
--   f' (f x y) = Just (x,y)
--   f' z       = Nothing
--   
-- -- A simple use of unfoldr: -- --
--   >>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
--   [10,9,8,7,6,5,4,3,2,1]
--   
unfoldr :: (b -> Maybe (a, b)) -> b -> [a] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
--   >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | The sortBy function is the non-overloaded version of -- sort. -- --
--   >>> sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortBy :: (a -> a -> Ordering) -> [a] -> [a] -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
--   >>> sort [1,6,4,3,2,5]
--   [1,2,3,4,5,6]
--   
sort :: Ord a => [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
--   >>> permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   
permutations :: [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
--   >>> subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   
subsequences :: [a] -> [[a]] -- | O(n). The tails function returns all final segments of -- the argument, longest first. For example, -- --
--   >>> tails "abc"
--   ["abc","bc","c",""]
--   
-- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: [a] -> [[a]] -- | The inits function returns all initial segments of the -- argument, shortest first. For example, -- --
--   >>> inits "abc"
--   ["","a","ab","abc"]
--   
-- -- Note that inits has the following strictness property: -- inits (xs ++ _|_) = inits xs ++ _|_ -- -- In particular, inits _|_ = [] : _|_ inits :: [a] -> [[a]] -- | The group function takes a list and returns a list of lists -- such that the concatenation of the result is equal to the argument. -- Moreover, each sublist in the result contains only equal elements. For -- example, -- --
--   >>> group "Mississippi"
--   ["M","i","ss","i","ss","i","pp","i"]
--   
-- -- It is a special case of groupBy, which allows the programmer to -- supply their own equality test. group :: Eq a => [a] -> [[a]] -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericDrop function is an overloaded version of -- drop, which accepts any Integral value as the number of -- elements to drop. genericDrop :: Integral i => i -> [a] -> [a] -- | The genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | O(n). The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The transpose function transposes the rows and columns of its -- argument. For example, -- --
--   >>> transpose [[1,2,3],[4,5,6]]
--   [[1,4],[2,5],[3,6]]
--   
-- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
--   >>> transpose [[10,11],[20],[],[30,31,32]]
--   [[10,20,30],[11,31],[32]]
--   
transpose :: [[a]] -> [[a]] -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
--   >>> intercalate ", " ["Lorem", "ipsum", "dolor"]
--   "Lorem, ipsum, dolor"
--   
intercalate :: [a] -> [[a]] -> [a] -- | O(n). The intersperse function takes an element and a -- list and `intersperses' that element between the elements of the list. -- For example, -- --
--   >>> intersperse ',' "abcde"
--   "a,b,c,d,e"
--   
intersperse :: a -> [a] -> [a] -- | O(min(m,n)). The isPrefixOf function takes two lists and -- returns True iff the first list is a prefix of the second. -- --
--   >>> "Hello" `isPrefixOf` "Hello World!"
--   True
--   
-- --
--   >>> "Hello" `isPrefixOf` "Wello Horld!"
--   False
--   
isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. -- --
--   >>> readMaybe "123" :: Maybe Int
--   Just 123
--   
-- --
--   >>> readMaybe "hello" :: Maybe Int
--   Nothing
--   
readMaybe :: Read a => String -> Maybe a -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | Return True if the given value is a Right-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> isRight (Left "foo")
--   False
--   
--   >>> isRight (Right 3)
--   True
--   
-- -- Assuming a Left value signifies some sort of error, we can use -- isRight to write a very simple reporting function that only -- outputs "SUCCESS" when a computation has succeeded. -- -- This example shows how isRight might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
--   >>> import Control.Monad ( when )
--   
--   >>> let report e = when (isRight e) $ putStrLn "SUCCESS"
--   
--   >>> report (Left "parse error")
--   
--   >>> report (Right 1)
--   SUCCESS
--   
isRight :: Either a b -> Bool -- | Return True if the given value is a Left-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> isLeft (Left "foo")
--   True
--   
--   >>> isLeft (Right 3)
--   False
--   
-- -- Assuming a Left value signifies some sort of error, we can use -- isLeft to write a very simple error-reporting function that -- does absolutely nothing in the case of success, and outputs "ERROR" if -- any error occurred. -- -- This example shows how isLeft might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
--   >>> import Control.Monad ( when )
--   
--   >>> let report e = when (isLeft e) $ putStrLn "ERROR"
--   
--   >>> report (Right 1)
--   
--   >>> report (Left "parse error")
--   ERROR
--   
isLeft :: Either a b -> Bool -- | Partitions a list of Either into two lists. All the Left -- elements are extracted, in order, to the first component of the -- output. Similarly the Right elements are extracted to the -- second component of the output. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list
--   (["foo","bar","baz"],[3,7])
--   
-- -- The pair returned by partitionEithers x should be the -- same pair as (lefts x, rights x): -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list == (lefts list, rights list)
--   True
--   
partitionEithers :: [Either a b] -> ([a], [b]) -- | Extracts from a list of Either all the Right elements. -- All the Right elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> rights list
--   [3,7]
--   
rights :: [Either a b] -> [b] -- | Extracts from a list of Either all the Left elements. -- All the Left elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> lefts list
--   ["foo","bar","baz"]
--   
lefts :: [Either a b] -> [a] -- | Case analysis for the Either type. If the value is -- Left a, apply the first function to a; if it -- is Right b, apply the second function to b. -- --

Examples

-- -- We create two values of type Either String -- Int, one using the Left constructor and another -- using the Right constructor. Then we apply "either" the -- length function (if we have a String) or the "times-two" -- function (if we have an Int): -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> either length (*2) s
--   3
--   
--   >>> either length (*2) n
--   6
--   
either :: (a -> c) -> (b -> c) -> Either a b -> c -- |
--   comparing p x y = compare (p x) (p y)
--   
-- -- Useful combinator for use in conjunction with the xxxBy -- family of functions from Data.List, for example: -- --
--   ... sortBy (comparing fst) ...
--   
comparing :: Ord a => (b -> a) -> b -> b -> Ordering -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). If a has -- an Ord instance associated with it then comparing two -- values thus wrapped will give you the opposite of their normal sort -- order. This is particularly useful when sorting in generalised list -- comprehensions, as in: then sortWith by Down x newtype Down a Down :: a -> Down a -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the undefined :: a idiom. -- --
--   >>> Proxy :: Proxy (Void, Int -> Int)
--   Proxy
--   
-- -- Proxy can even hold types of higher kinds, -- --
--   >>> Proxy :: Proxy Either
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy Functor
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy complicatedStructure
--   Proxy
--   
data Proxy (t :: k) Proxy :: Proxy (t :: k) -- | See openFile data IOMode ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Swap bytes in Word16. byteSwap16 :: Word16 -> Word16 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFrom :: (Integral a, Bounded a) => a -> [a] gcdWord' :: Word -> Word -> Word gcdInt' :: Int -> Int -> Int -- | lcm x y is the smallest positive integer that both -- x and y divide. lcm :: Integral a => a -> a -> a -- | gcd x y is the non-negative factor of both x -- and y of which every common factor of x and -- y is also a factor; for example gcd 4 2 = 2, -- gcd (-4) 6 = 2, gcd 0 4 = 4. -- gcd 0 0 = 0. (That is, the common divisor -- that is "greatest" in the divisibility preordering.) -- -- Note: Since for signed fixed-width integer types, abs -- minBound < 0, the result may be negative if one of the -- arguments is minBound (and necessarily is if the other -- is 0 or minBound) for such types. gcd :: Integral a => a -> a -> a (^^%^^) :: Integral a => Rational -> a -> Rational (^%^) :: Integral a => Rational -> a -> Rational -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ odd :: Integral a => a -> Bool even :: Integral a => a -> Bool numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThen :: Fractional a => a -> a -> [a] numericEnumFrom :: Fractional a => a -> [a] -- | Extract the denominator of the ratio in reduced form: the numerator -- and denominator have no common factor and the denominator is positive. denominator :: Ratio a -> a -- | Extract the numerator of the ratio in reduced form: the numerator and -- denominator have no common factor and the denominator is positive. numerator :: Ratio a -> a -- | reduce is a subsidiary function used only in this module. It -- normalises a ratio by dividing both numerator and denominator by their -- greatest common divisor. reduce :: Integral a => a -> a -> Ratio a notANumber :: Rational infinity :: Rational ratioPrec1 :: Int ratioPrec :: Int underflowError :: a overflowError :: a ratioZeroDenominatorError :: a divZeroError :: a boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. unzip3 :: [(a, b, c)] -> ([a], [b], [c]) -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. unzip :: [(a, b)] -> ([a], [b]) -- | O(min(m,n)). zipWith generalises zip by zipping -- with the function given as the first argument, instead of a tupling -- function. For example, zipWith (+) is applied to two -- lists to produce the list of corresponding sums: -- --
--   >>> zipWith (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   zipWith f [] _|_ = []
--   
-- -- zipWith is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. It is capable of list fusion, but it is restricted to -- its first list argument and its resulting list. zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: [a] -> [a] -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
--   break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
--   break (< 9) [1,2,3] == ([],[1,2,3])
--   break (> 9) [1,2,3] == ([1,2,3],[])
--   
-- -- break p is equivalent to span (not . -- p). break :: (a -> Bool) -> [a] -> ([a], [a]) -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
--   splitAt 6 "Hello World!" == ("Hello ","World!")
--   splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
--   splitAt 1 [1,2,3] == ([1],[2,3])
--   splitAt 3 [1,2,3] == ([1,2,3],[])
--   splitAt 4 [1,2,3] == ([1,2,3],[])
--   splitAt 0 [1,2,3] == ([],[1,2,3])
--   splitAt (-1) [1,2,3] == ([],[1,2,3])
--   
-- -- It is equivalent to (take n xs, drop n xs) when -- n is not _|_ (splitAt _|_ xs = _|_). -- splitAt is an instance of the more general -- genericSplitAt, in which n may be of any integral -- type. splitAt :: Int -> [a] -> ([a], [a]) -- | drop n xs returns the suffix of xs after the -- first n elements, or [] if n > length -- xs: -- --
--   drop 6 "Hello World!" == "World!"
--   drop 3 [1,2,3,4,5] == [4,5]
--   drop 3 [1,2] == []
--   drop 3 [] == []
--   drop (-1) [1,2] == [1,2]
--   drop 0 [1,2] == [1,2]
--   
-- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: Int -> [a] -> [a] -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n > length xs: -- --
--   take 5 "Hello World!" == "Hello"
--   take 3 [1,2,3,4,5] == [1,2,3]
--   take 3 [1,2] == [1,2]
--   take 3 [] == []
--   take (-1) [1,2] == []
--   take 0 [1,2] == []
--   
-- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs: -- --
--   dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
--   dropWhile (< 9) [1,2,3] == []
--   dropWhile (< 0) [1,2,3] == [1,2,3]
--   
dropWhile :: (a -> Bool) -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p: -- --
--   takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
--   takeWhile (< 9) [1,2,3] == [1,2,3]
--   takeWhile (< 0) [1,2,3] == []
--   
takeWhile :: (a -> Bool) -> [a] -> [a] -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. cycle :: [a] -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. replicate :: Int -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. repeat :: a -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
--   iterate f x == [x, f x, f (f x), ...]
--   
-- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See -- iterate' for a strict variant of this function. iterate :: (a -> a) -> a -> [a] -- | O(n). scanr is the right-to-left dual of scanl. -- Note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
scanr :: (a -> b -> b) -> b -> [a] -> [b] -- | O(n). scanl is similar to foldl, but returns a -- list of successive reduced values from the left: -- --
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   
-- -- Note that -- --
--   last (scanl f z xs) == foldl f z xs.
--   
scanl :: (b -> a -> b) -> b -> [a] -> [b] -- | The mapMaybe function is a version of map which can -- throw out elements. In particular, the functional argument returns -- something of type Maybe b. If this is Nothing, -- no element is added on to the result list. If it is Just -- b, then b is included in the result list. -- --

Examples

-- -- Using mapMaybe f x is a shortcut for -- catMaybes $ map f x in most cases: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> let readMaybeInt = readMaybe :: String -> Maybe Int
--   
--   >>> mapMaybe readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
--   >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
-- -- If we map the Just constructor, the entire list should be -- returned: -- --
--   >>> mapMaybe Just [1,2,3]
--   [1,2,3]
--   
mapMaybe :: (a -> Maybe b) -> [a] -> [b] -- | The catMaybes function takes a list of Maybes and -- returns a list of all the Just values. -- --

Examples

-- -- Basic usage: -- --
--   >>> catMaybes [Just 1, Nothing, Just 3]
--   [1,3]
--   
-- -- When constructing a list of Maybe values, catMaybes can -- be used to return all of the "success" results (if the list is the -- result of a map, then mapMaybe would be more -- appropriate): -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [Just 1,Nothing,Just 3]
--   
--   >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [1,3]
--   
catMaybes :: [Maybe a] -> [a] -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --

Examples

-- -- Basic usage: -- --
--   >>> listToMaybe []
--   Nothing
--   
-- --
--   >>> listToMaybe [9]
--   Just 9
--   
-- --
--   >>> listToMaybe [1,2,3]
--   Just 1
--   
-- -- Composing maybeToList with listToMaybe should be the -- identity on singleton/empty lists: -- --
--   >>> maybeToList $ listToMaybe [5]
--   [5]
--   
--   >>> maybeToList $ listToMaybe []
--   []
--   
-- -- But not on lists with more than one element: -- --
--   >>> maybeToList $ listToMaybe [1,2,3]
--   [1]
--   
listToMaybe :: [a] -> Maybe a -- | The maybeToList function returns an empty list when given -- Nothing or a singleton list when given Just. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: Maybe a -> [a] -- | The fromMaybe function takes a default value and and -- Maybe value. If the Maybe is Nothing, it returns -- the default values; otherwise, it returns the value contained in the -- Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: a -> Maybe a -> a -- | The isNothing function returns True iff its argument is -- Nothing. -- --

Examples

-- -- Basic usage: -- --
--   >>> isNothing (Just 3)
--   False
--   
-- --
--   >>> isNothing (Just ())
--   False
--   
-- --
--   >>> isNothing Nothing
--   True
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isNothing (Just Nothing)
--   False
--   
isNothing :: Maybe a -> Bool -- | The isJust function returns True iff its argument is of -- the form Just _. -- --

Examples

-- -- Basic usage: -- --
--   >>> isJust (Just 3)
--   True
--   
-- --
--   >>> isJust (Just ())
--   True
--   
-- --
--   >>> isJust Nothing
--   False
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isJust (Just Nothing)
--   True
--   
isJust :: Maybe a -> Bool -- | The maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybe False odd (Just 3)
--   True
--   
-- --
--   >>> maybe False odd Nothing
--   False
--   
-- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> maybe 0 (*2) (readMaybe "5")
--   10
--   
--   >>> maybe 0 (*2) (readMaybe "")
--   0
--   
-- -- Apply show to a Maybe Int. If we have Just n, -- we want to show the underlying Int n. But if we have -- Nothing, we return the empty string instead of (for example) -- "Nothing": -- --
--   >>> maybe "" show (Just 5)
--   "5"
--   
--   >>> maybe "" show Nothing
--   ""
--   
maybe :: b -> (a -> b) -> Maybe a -> b -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --

Examples

-- -- Basic usage: -- --
--   >>> bool "foo" "bar" True
--   "bar"
--   
--   >>> bool "foo" "bar" False
--   "foo"
--   
-- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
--   >>> let p = True; x = "bar"; y = "foo"
--   
--   >>> bool x y p == if p then y else x
--   True
--   
--   >>> let p = False
--   
--   >>> bool x y p == if p then y else x
--   True
--   
bool :: a -> a -> Bool -> a -- | & is a reverse application operator. This provides -- notational convenience. Its precedence is one higher than that of the -- forward application operator $, which allows & to be -- nested in $. -- --
--   >>> 5 & (+1) & show
--   "6"
--   
(&) :: a -> (a -> b) -> b infixl 1 & -- | on b u x y runs the binary function b -- on the results of applying unary function u to two -- arguments x and y. From the opposite perspective, it -- transforms two inputs and combines the outputs. -- --
--   ((+) `on` f) x y = f x + f y
--   
-- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- -- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 `on` -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix argument, hence the recursion is reintroduced. fix :: (a -> a) -> a -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --

Examples

-- -- Replace the contents of a Maybe Int with unit: -- --
--   >>> void Nothing
--   Nothing
--   
--   >>> void (Just 3)
--   Just ()
--   
-- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int (): -- --
--   >>> void (Left 8675309)
--   Left 8675309
--   
--   >>> void (Right 8675309)
--   Right ()
--   
-- -- Replace every element of a list with unit: -- --
--   >>> void [1,2,3]
--   [(),(),()]
--   
-- -- Replace the second element of a pair with unit: -- --
--   >>> void (1,2)
--   (1,())
--   
-- -- Discard the result of an IO action: -- --
--   >>> mapM print [1,2]
--   1
--   2
--   [(),()]
--   
--   >>> void $ mapM print [1,2]
--   1
--   2
--   
void :: Functor f => f a -> f () -- | Flipped version of <$. -- --

Examples

-- -- Replace the contents of a Maybe Int with a -- constant String: -- --
--   >>> Nothing $> "foo"
--   Nothing
--   
--   >>> Just 90210 $> "foo"
--   Just "foo"
--   
-- -- Replace the contents of an Either Int -- Int with a constant String, resulting in an -- Either Int String: -- --
--   >>> Left 8675309 $> "foo"
--   Left 8675309
--   
--   >>> Right 8675309 $> "foo"
--   Right "foo"
--   
-- -- Replace each element of a list with a constant String: -- --
--   >>> [1,2,3] $> "foo"
--   ["foo","foo","foo"]
--   
-- -- Replace the second element of a pair with a constant String: -- --
--   >>> (1,2) $> "foo"
--   (1,"foo")
--   
($>) :: Functor f => f a -> b -> f b infixl 4 $> -- | Flipped version of <$>. -- --
--   (<&>) = flip fmap
--   
-- --

Examples

-- -- Apply (+1) to a list, a Just and a Right: -- --
--   >>> Just 2 <&> (+1)
--   Just 3
--   
-- --
--   >>> [1,2,3] <&> (+1)
--   [2,3,4]
--   
-- --
--   >>> Right 3 <&> (+1)
--   Right 4
--   
(<&>) :: Functor f => f a -> (a -> b) -> f b infixl 1 <&> -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
--    ($)  ::              (a -> b) ->   a ->   b
--   (<$>) :: Functor f => (a -> b) -> f a -> f b
--   
-- -- Whereas $ is function application, <$> is function -- application lifted over a Functor. -- --

Examples

-- -- Convert from a Maybe Int to a Maybe -- String using show: -- --
--   >>> show <$> Nothing
--   Nothing
--   
--   >>> show <$> Just 3
--   Just "3"
--   
-- -- Convert from an Either Int Int to an -- Either Int String using show: -- --
--   >>> show <$> Left 17
--   Left 17
--   
--   >>> show <$> Right 17
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> (*2) <$> [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> even <$> (2,2)
--   (2,True)
--   
(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | Swap the components of a pair. swap :: (a, b) -> (b, a) -- | uncurry converts a curried function to a function on pairs. -- --

Examples

-- --
--   >>> uncurry (+) (1,2)
--   3
--   
-- --
--   >>> uncurry ($) (show, 1)
--   "1"
--   
-- --
--   >>> map (uncurry max) [(1,2), (3,4), (6,8)]
--   [2,4,8]
--   
uncurry :: (a -> b -> c) -> (a, b) -> c -- | curry converts an uncurried function to a curried function. -- --

Examples

-- --
--   >>> curry fst 1 2
--   1
--   
curry :: ((a, b) -> c) -> a -> b -> c -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a box, which may be empty or full. data MVar a -- | the same as flip (-). -- -- Because - is treated specially in the Haskell grammar, -- (- e) is not a section, but an application of -- prefix negation. However, (subtract -- exp) is equivalent to the disallowed section. subtract :: Num a => a -> a -> a -- | Returns a [String] representing the current call stack. This -- can be useful for debugging. -- -- The implementation uses the call-stack simulation maintained by the -- profiler, so it only works if the program was compiled with -- -prof and contains suitable SCC annotations (e.g. by using -- -fprof-auto). Otherwise, the list returned is likely to be -- empty or uninformative. currentCallStack :: IO [String] -- | asTypeOf is a type-restricted version of const. It is -- usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- second. asTypeOf :: a -> a -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c -- | Function composition. (.) :: (b -> c) -> (a -> b) -> a -> c infixr 9 . -- | const x is a unary function which evaluates to x for -- all inputs. -- --
--   >>> const 42 "hello"
--   42
--   
-- --
--   >>> map (const 42) [0..3]
--   [42,42,42,42]
--   
const :: a -> b -> a -- | Identity function. -- --
--   id x = x
--   
id :: a -> a maxInt :: Int minInt :: Int -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
--   return f `ap` x1 `ap` ... `ap` xn
--   
-- -- is equivalent to -- --
--   liftMn f x1 x2 ... xn
--   
ap :: Monad m => m (a -> b) -> m a -> m b -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
--   liftM2 (+) [0,1] [0,2] = [0,2,1,3]
--   liftM2 (+) (Just 1) Nothing = Nothing
--   
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | Lift a ternary function to actions. liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | Zero or more. many :: Alternative f => f a -> f [a] infixl 3 <|> -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) -- | The identity of mplus. It should also satisfy the equations -- --
--   mzero >>= f  =  mzero
--   v >> mzero   =  mzero
--   
-- -- The default definition is -- --
--   mzero = empty
--   
mzero :: MonadPlus m => m a -- | An associative operation. The default definition is -- --
--   mplus = (<|>)
--   
mplus :: MonadPlus m => m a -> m a -> m a -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | Extract a list of call-sites from the CallStack. -- -- The list is ordered by most recent call. getCallStack :: CallStack -> [([Char], SrcLoc)] -- | Request a CallStack. -- -- NOTE: The implicit parameter ?callStack :: CallStack is an -- implementation detail and should not be considered part of the -- CallStack API, we may decide to change the implementation in -- the future. type HasCallStack = ?callStack :: CallStack -- | This is a valid definition of stimes for an idempotent -- Monoid. -- -- When mappend x x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n) stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | The SomeException type is the root of the exception type -- hierarchy. When an exception of type e is thrown, behind the -- scenes it is encapsulated in a SomeException. data SomeException SomeException :: e -> SomeException -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data ByteString -- | A map of integers to values a. data IntMap a -- | A set of integers. data IntSet -- | A Map from keys k to values a. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data Map k a -- | General-purpose finite sequences. data Seq a -- | A set of values a. data Set a -- | a variant of deepseq that is useful in some circumstances: -- --
--   force x = x `deepseq` x
--   
-- -- force x fully evaluates x, and then returns it. Note -- that force x only performs evaluation when the value of -- force x itself is demanded, so essentially it turns shallow -- evaluation into deep evaluation. -- -- force can be conveniently used in combination with -- ViewPatterns: -- --
--   {-# LANGUAGE BangPatterns, ViewPatterns #-}
--   import Control.DeepSeq
--   
--   someFun :: ComplexData -> SomeResult
--   someFun (force -> !arg) = {- 'arg' will be fully evaluated -}
--   
-- -- Another useful application is to combine force with -- evaluate in order to force deep evaluation relative to other -- IO operations: -- --
--   import Control.Exception (evaluate)
--   import Control.DeepSeq
--   
--   main = do
--     result <- evaluate $ force $ pureComputation
--     {- 'result' will be fully evaluated at this point -}
--     return ()
--   
-- -- Finally, here's an exception safe variant of the readFile' -- example: -- --
--   readFile' :: FilePath -> IO String
--   readFile' fn = bracket (openFile fn ReadMode) hClose $ \h ->
--                          evaluate . force =<< hGetContents h
--   
force :: NFData a => a -> a -- | the deep analogue of $!. In the expression f $!! x, -- x is fully evaluated before the function f is -- applied to it. ($!!) :: NFData a => (a -> b) -> a -> b infixr 0 $!! -- | deepseq: fully evaluates the first argument, before returning -- the second. -- -- The name deepseq is used to illustrate the relationship to -- seq: where seq is shallow in the sense that it only -- evaluates the top level of its argument, deepseq traverses the -- entire data structure evaluating it completely. -- -- deepseq can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also -- useful in conjunction with parallel Strategies (see the -- parallel package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in any -- order or in parallel. To impose an actual order on evaluation, use -- pseq from Control.Parallel in the parallel -- package. deepseq :: NFData a => a -> b -> b -- | A class of types that can be fully evaluated. class NFData a -- | rnf should reduce its argument to normal form (that is, fully -- evaluate all sub-components), and then return (). -- --

Generic NFData deriving

-- -- Starting with GHC 7.2, you can automatically derive instances for -- types possessing a Generic instance. -- -- Note: Generic1 can be auto-derived starting with GHC 7.4 -- --
--   {-# LANGUAGE DeriveGeneric #-}
--   
--   import GHC.Generics (Generic, Generic1)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1)
--   
--   instance NFData a => NFData (Foo a)
--   instance NFData1 Foo
--   
--   data Colour = Red | Green | Blue
--                 deriving Generic
--   
--   instance NFData Colour
--   
-- -- Starting with GHC 7.10, the example above can be written more -- concisely by enabling the new DeriveAnyClass extension: -- --
--   {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
--   
--   import GHC.Generics (Generic)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1, NFData, NFData1)
--   
--   data Colour = Red | Green | Blue
--                 deriving (Generic, NFData)
--   
-- --

Compatibility with previous deepseq versions

-- -- Prior to version 1.4.0.0, the default implementation of the rnf -- method was defined as -- --
--   rnf a = seq a ()
--   
-- -- However, starting with deepseq-1.4.0.0, the default -- implementation is based on DefaultSignatures allowing for -- more accurate auto-derived NFData instances. If you need the -- previously used exact default rnf method implementation -- semantics, use -- --
--   instance NFData Colour where rnf x = seq x ()
--   
-- -- or alternatively -- --
--   instance NFData Colour where rnf = rwhnf
--   
-- -- or -- --
--   {-# LANGUAGE BangPatterns #-}
--   instance NFData Colour where rnf !_ = ()
--   
rnf :: NFData a => a -> () -- | A space efficient, packed, unboxed Unicode text type. data Text -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: forall (m :: Type -> Type) e a. Functor m => e -> MaybeT m a -> ExceptT e m a -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: forall (m :: Type -> Type) e a. Functor m => ExceptT e m a -> MaybeT m a -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | Function type for handling a coding error. It is supplied with two -- inputs: -- -- -- -- If the handler returns a value wrapped with Just, that value -- will be used in the output as the replacement for the invalid input. -- If it returns Nothing, no value will be used in the output. -- -- Should the handler need to abort processing, it should use -- error or throw an exception (preferably a -- UnicodeException). It may use the description provided to -- construct a more helpful error report. type OnError a b = String -> Maybe a -> Maybe b -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Decode a ByteString containing UTF-8 encoded text. -- -- NOTE: The replacement character returned by -- OnDecodeError MUST be within the BMP plane; surrogate code -- points will automatically be remapped to the replacement char -- U+FFFD (since 0.11.3.0), whereas code points beyond -- the BMP will throw an error (since 1.2.3.1); For earlier -- versions of text using those unsupported code points would -- result in undefined behavior. decodeUtf8With :: OnDecodeError -> ByteString -> Text -- | Decode a ByteString containing UTF-8 encoded text. -- -- If the input contains any invalid UTF-8 data, the relevant exception -- will be returned, otherwise the decoded text. decodeUtf8' :: ByteString -> Either UnicodeException Text -- | O(n) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [Text] -- | O(n) Breaks a Text up into a list of Texts at -- newline Chars. The resulting strings do not contain newlines. lines :: Text -> [Text] -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [Text] -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Convert a lazy Text into a strict Text. toStrict :: Text -> Text -- | O(c) Convert a strict Text into a lazy Text. fromStrict :: Text -> Text -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execStateT :: Monad m => StateT s m a -> s -> m s -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalStateT :: Monad m => StateT s m a -> s -> m a -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: (s -> s) -> State s a -> State s a -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: State s a -> s -> s -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalState :: State s a -> s -> a -- | Unwrap a state monad computation as a function. (The inverse of -- state.) runState :: State s a -> s -> (a, s) -- | A state monad parameterized by the type s of the state to -- carry. -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. type State s = StateT s Identity -- | A state transformer monad parameterized by: -- -- -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. newtype StateT s (m :: Type -> Type) a StateT :: (s -> m (a, s)) -> StateT s (m :: Type -> Type) a [runStateT] :: StateT s (m :: Type -> Type) a -> s -> m (a, s) -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e a) -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | The trivial monad transformer, which maps a monad to an equivalent -- monad. data IdentityT (f :: k -> Type) (a :: k) -- | The class of monad transformers. Instances should satisfy the -- following laws, which state that lift is a monad -- transformation: -- -- class MonadTrans (t :: Type -> Type -> Type -> Type) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a -- | The parameterizable reader monad. -- -- Computations are functions of a shared environment. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. type Reader r = ReaderT r Identity -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. newtype ReaderT r (m :: Type -> Type) a ReaderT :: (r -> m a) -> ReaderT r (m :: Type -> Type) a [runReaderT] :: ReaderT r (m :: Type -> Type) a -> r -> m a -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: Type -> Type) | m -> s -- | Replace the state inside the monad. put :: MonadState s m => s -> m () -- | Embed a simple state action into the monad. state :: MonadState s m => (s -> (a, s)) -> m a -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: Type -> Type) | m -> r -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | Executes a computation in a modified environment. local :: MonadReader r m => (r -> r) -> m a -> m a -- | Retrieves a function of the current environment. reader :: MonadReader r m => (r -> a) -> m a -- | Retrieves a function of the current environment. asks :: MonadReader r m => (r -> a) -> m a -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => (s -> a) -> m a -- | Monadic state transformer. -- -- Maps an old state to a new state inside a state monad. The old state -- is thrown away. -- --
--   Main> :t modify ((+1) :: Int -> Int)
--   modify (...) :: (MonadState Int a) => a ()
--   
-- -- This says that modify (+1) acts over any Monad that is a -- member of the MonadState class, with an Int state. modify :: MonadState s m => (s -> s) -> m () -- | A monad transformer that adds exceptions to other monads. -- -- ExceptT constructs a monad parameterized over two things: -- -- -- -- The return function yields a computation that produces the -- given value, while >>= sequences two subcomputations, -- exiting on the first exception. newtype ExceptT e (m :: Type -> Type) a ExceptT :: m (Either e a) -> ExceptT e (m :: Type -> Type) a -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype MaybeT (m :: Type -> Type) a MaybeT :: m (Maybe a) -> MaybeT (m :: Type -> Type) a [runMaybeT] :: MaybeT (m :: Type -> Type) a -> m (Maybe a) (.~) :: ASetter s t a b -> b -> s -> t (^..) :: s -> Getting (Endo [a]) s a -> [a] over :: ASetter s t a b -> (a -> b) -> s -> t set :: ASetter s t a b -> b -> s -> t preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a) preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a) use :: MonadState s m => Getting a s a -> m a view :: MonadReader s m => Getting a s a -> m a bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c bracket_ :: MonadMask m => m a -> m b -> m c -> m c catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a catchAny :: MonadCatch m => m a -> (SomeException -> m a) -> m a finally :: MonadMask m => m a -> m b -> m a handleAny :: MonadCatch m => (SomeException -> m a) -> m a -> m a onException :: MonadMask m => m a -> m b -> m a throwM :: (MonadThrow m, Exception e) => e -> m a try :: (MonadCatch m, Exception e) => m a -> m (Either e a) tryAny :: MonadCatch m => m a -> m (Either SomeException a) pass :: Applicative f => f () ($!) :: (a -> b) -> a -> b guardM :: MonadPlus m => m Bool -> m () ifM :: Monad m => m Bool -> m a -> m a -> m a unlessM :: Monad m => m Bool -> m () -> m () whenM :: Monad m => m Bool -> m () -> m () asum :: (Container t, Alternative f, Element t ~ f a) => t -> f a flipfoldl' :: (Container t, Element t ~ a) => (a -> b -> b) -> b -> t -> b forM_ :: (Container t, Monad m) => t -> (Element t -> m b) -> m () for_ :: (Container t, Applicative f) => t -> (Element t -> f b) -> f () mapM_ :: (Container t, Monad m) => (Element t -> m b) -> t -> m () product :: (Container t, Num (Element t)) => t -> Element t sequenceA_ :: (Container t, Applicative f, Element t ~ f a) => t -> f () sequence_ :: (Container t, Monad m, Element t ~ m a) => t -> m () sum :: (Container t, Num (Element t)) => t -> Element t traverse_ :: (Container t, Applicative f) => (Element t -> f b) -> t -> f () error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => Text -> a trace :: Text -> a -> a traceId :: Text -> Text traceIdWith :: (a -> Text) -> a -> a traceM :: Monad m => Text -> m () traceShow :: Show a => a -> b -> b traceShowId :: Show a => a -> a traceShowIdWith :: Show s => (a -> s) -> a -> a traceShowM :: (Show a, Monad m) => a -> m () undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a evaluateNF :: (NFData a, MonadIO m) => a -> m a evaluateNF_ :: (NFData a, MonadIO m) => a -> m () evaluateWHNF :: MonadIO m => a -> m a evaluateWHNF_ :: MonadIO m => a -> m () pattern Exc :: Exception e => e -> SomeException bug :: (HasCallStack, Exception e) => e -> a note :: MonadError e m => e -> Maybe a -> m a (<<$>>) :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b) map :: Functor f => (a -> b) -> f a -> f b atomically :: MonadIO m => STM a -> m a newEmptyMVar :: MonadIO m => m (MVar a) newMVar :: MonadIO m => a -> m (MVar a) newTVarIO :: MonadIO m => a -> m (TVar a) putMVar :: MonadIO m => MVar a -> a -> m () readMVar :: MonadIO m => MVar a -> m a readTVarIO :: MonadIO m => TVar a -> m a swapMVar :: MonadIO m => MVar a -> a -> m a takeMVar :: MonadIO m => MVar a -> m a tryPutMVar :: MonadIO m => MVar a -> a -> m Bool tryReadMVar :: MonadIO m => MVar a -> m (Maybe a) tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) die :: MonadIO m => String -> m a exitFailure :: MonadIO m => m a exitSuccess :: MonadIO m => m a exitWith :: MonadIO m => ExitCode -> m a appendFile :: MonadIO m => FilePath -> Text -> m () getLine :: MonadIO m => m Text hClose :: MonadIO m => Handle -> m () openFile :: MonadIO m => FilePath -> IOMode -> m Handle withFile :: (MonadIO m, MonadMask m) => FilePath -> IOMode -> (Handle -> m a) -> m a atomicModifyIORef :: MonadIO m => IORef a -> (a -> (a, b)) -> m b atomicModifyIORef' :: MonadIO m => IORef a -> (a -> (a, b)) -> m b atomicWriteIORef :: MonadIO m => IORef a -> a -> m () modifyIORef :: MonadIO m => IORef a -> (a -> a) -> m () modifyIORef' :: MonadIO m => IORef a -> (a -> a) -> m () newIORef :: MonadIO m => a -> m (IORef a) readIORef :: MonadIO m => IORef a -> m a writeIORef :: MonadIO m => IORef a -> a -> m () uncons :: [a] -> Maybe (a, [a]) whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f () whenNotNullM :: Monad m => m [a] -> (NonEmpty a -> m ()) -> m () allM :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool andM :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool anyM :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool concatForM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => l a -> (a -> f m) -> f m concatMapM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => (a -> f m) -> l a -> f m orM :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool fromLeft :: a -> Either a b -> a fromRight :: b -> Either a b -> b leftToMaybe :: Either l r -> Maybe l maybeToLeft :: r -> Maybe l -> Either l r maybeToRight :: l -> Maybe r -> Either l r rightToMaybe :: Either l r -> Maybe r whenLeftM :: Monad m => m (Either l r) -> (l -> m ()) -> m () whenRightM :: Monad m => m (Either l r) -> (r -> m ()) -> m () whenJust :: Applicative f => Maybe a -> (a -> f ()) -> f () whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () whenNothing :: Applicative f => Maybe a -> f a -> f a whenNothingM :: Monad m => m (Maybe a) -> m a -> m a whenNothingM_ :: Monad m => m (Maybe a) -> m () -> m () whenNothing_ :: Applicative f => Maybe a -> f () -> f () evaluatingState :: s -> State s a -> a evaluatingStateT :: Functor f => s -> StateT s f a -> f a executingState :: s -> State s a -> s executingStateT :: Functor f => s -> StateT s f a -> f s usingReader :: r -> Reader r a -> a usingReaderT :: r -> ReaderT r m a -> m a usingState :: s -> State s a -> (a, s) usingStateT :: s -> StateT s m a -> m (a, s) maybeToMonoid :: Monoid m => Maybe m -> m hashNub :: (Eq a, Hashable a) => [a] -> [a] ordNub :: Ord a => [a] -> [a] sortNub :: Ord a => [a] -> [a] unstableNub :: (Eq a, Hashable a) => [a] -> [a] hPrint :: (MonadIO m, Show a) => Handle -> a -> m () hPutStr :: (Print a, MonadIO m) => Handle -> a -> m () hPutStrLn :: (Print a, MonadIO m) => Handle -> a -> m () print :: forall a m. (MonadIO m, Show a) => a -> m () putLText :: MonadIO m => Text -> m () putLTextLn :: MonadIO m => Text -> m () putStr :: (Print a, MonadIO m) => a -> m () putStrLn :: (Print a, MonadIO m) => a -> m () putText :: MonadIO m => Text -> m () putTextLn :: MonadIO m => Text -> m () readEither :: (ToString a, Read b) => a -> Either Text b show :: forall b a. (Show a, IsString b) => a -> b class MonadThrow m => MonadCatch (m :: Type -> Type) class MonadCatch m => MonadMask (m :: Type -> Type) mask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b uninterruptibleMask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b generalBracket :: MonadMask m => m a -> (a -> ExitCase b -> m c) -> (a -> m b) -> m (b, c) class Monad m => MonadThrow (m :: Type -> Type) class Hashable a hashWithSalt :: Hashable a => Int -> a -> Int _1 :: Field1 s t a b => Lens s t a b _2 :: Field2 s t a b => Lens s t a b _3 :: Field3 s t a b => Lens s t a b _4 :: Field4 s t a b => Lens s t a b _5 :: Field5 s t a b => Lens s t a b type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t type Lens' s a = Lens s s a a type Traversal s t a b = forall (f :: Type -> Type). Applicative f => a -> f b -> s -> f t type Traversal' s a = Traversal s s a a class Container t where { type family Element t; type Element t = ElementDefault t; } toList :: Container t => t -> [Element t] null :: Container t => t -> Bool foldr :: Container t => (Element t -> b -> b) -> b -> t -> b foldl :: Container t => (b -> Element t -> b) -> b -> t -> b foldl' :: Container t => (b -> Element t -> b) -> b -> t -> b length :: Container t => t -> Int elem :: Container t => Element t -> t -> Bool maximum :: Container t => t -> Element t minimum :: Container t => t -> Element t foldMap :: (Container t, Monoid m) => (Element t -> m) -> t -> m fold :: Container t => t -> Element t foldr' :: Container t => (Element t -> b -> b) -> b -> t -> b foldr1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t foldl1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t notElem :: Container t => Element t -> t -> Bool all :: Container t => (Element t -> Bool) -> t -> Bool any :: Container t => (Element t -> Bool) -> t -> Bool find :: Container t => (Element t -> Bool) -> t -> Maybe (Element t) safeHead :: Container t => t -> Maybe (Element t) type family Element t class One x where { type family OneItem x; } one :: One x => OneItem x -> x type family OneItem x class ToPairs t toPairs :: ToPairs t => t -> [(Key t, Val t)] keys :: ToPairs t => t -> [Key t] elems :: ToPairs t => t -> [Val t] data Undefined Undefined :: Undefined data Bug Bug :: SomeException -> CallStack -> Bug class Print a class ConvertUtf8 a b encodeUtf8 :: ConvertUtf8 a b => a -> b decodeUtf8 :: ConvertUtf8 a b => b -> a decodeUtf8Strict :: ConvertUtf8 a b => b -> Either UnicodeException a type LByteString = ByteString type LText = Text class ToLText a toLText :: ToLText a => a -> Text class ToString a toString :: ToString a => a -> String class ToText a toText :: ToText a => a -> Text type (f :: k1 -> k) $ (a :: k1) = f a type family Each (c :: [k -> Constraint]) (as :: [k]) type With (a :: [k -> Constraint]) (b :: k) = a <+> b class SuperComposition a b c | a b -> c (...) :: SuperComposition a b c => a -> b -> c data HashMap k v data HashSet a data Vector a module Indigo.Internal.SIS -- | IndigoState with hidden output stack, necessary to generate -- typed Lorentz code from untyped Indigo frontend. newtype SomeIndigoState inp a SomeIndigoState :: (MetaData inp -> SomeGenCode inp a) -> SomeIndigoState inp a [unSIS] :: SomeIndigoState inp a -> MetaData inp -> SomeGenCode inp a -- | Gen code with hidden output stack data SomeGenCode inp a [SomeGenCode] :: GenCode inp out a -> SomeGenCode inp a -- | return for SomeIndigoState returnSIS :: a -> SomeIndigoState inp a -- | Like bind, but the input type of the second parameter is determined by -- the output of the first one. bindSIS :: SomeIndigoState inp a -> (forall someOut. a -> SomeIndigoState someOut b) -> SomeIndigoState inp b -- | Convert IndigoState to SomeIndigoState toSIS :: IndigoState inp out a -> SomeIndigoState inp a -- | To run SomeIndigoState you need to pass an handler of -- GenCode with any output stack. runSIS :: SomeIndigoState inp a -> MetaData inp -> (forall out. GenCode inp out a -> r) -> r -- | Call an action with IndigoState stored in -- SomeIndigoState. -- -- This function is kinda dummy because it passes IndigoState to the -- function which produces a GenCode independently on passed MetaData to -- it. It has to be used with only functions which pass MetaData in the -- same way. This function is needed to pass SomeIndigoState in -- contravariant positions of statements like if, case, -- while, forEach, etc. Alternative solution would be -- abstracting out IndigoState and SomeIndigoState with typeclass class -- CodeGenerator m where runCodeGen :: m inp a -> MetaData inp -> -- (forall out . GenCode inp out a -> r) -> r and passing -- CodeGenerator m in contravariant positions instead of IndigoState. withSIS :: SomeIndigoState inp a -> (forall out. IndigoState inp out a -> SomeIndigoState inp b) -> SomeIndigoState inp b -- | The same as withSIS but converting a function with one -- argument, also dummy. withSIS1 :: KnownValue x => (Var x -> SomeIndigoState (x & inp) a) -> (forall out. (Var x -> IndigoState (x & inp) out a) -> SomeIndigoState inp b) -> SomeIndigoState inp b -- | The same as withSIS1 but converting a function with 2 -- arguments, also dummy. withSIS2 :: (KnownValue x, KnownValue y) => (Var x -> Var y -> SomeIndigoState (x & (y & inp)) a) -> (forall out. (Var x -> Var y -> IndigoState (x & (y & inp)) out a) -> SomeIndigoState inp b) -> SomeIndigoState inp b instance GHC.Base.Functor (Indigo.Internal.SIS.SomeIndigoState inp) instance GHC.Base.Functor (Indigo.Internal.SIS.SomeGenCode inp) -- | This module contains a datatype representing a lens to a field, -- helpers to compose new lens, and type class like StoreHasField -- returning a lens. module Indigo.Internal.Field -- | Constraint to access/assign field stored in Rec type AccessFieldC a name = RElem name (ConstructorFieldNames a) (RIndex name (ConstructorFieldNames a)) -- | Get a field from list of fields fetchField :: forall a name f proxy. AccessFieldC a name => proxy name -> Rec f (ConstructorFieldNames a) -> f name -- | Assign a field to a value assignField :: forall a name f proxy. AccessFieldC a name => proxy name -> f name -> Rec f (ConstructorFieldNames a) -> Rec f (ConstructorFieldNames a) -- | Lens to a field. obj.f1.f2.f3 is represented as list names of -- [f1, f2, f3]. -- -- dt is a type of source object (type of obj in example above) -- fname is a name of target field ("f3" in example -- above) ftype is a type of target field -- -- However, a lens contains not only name of field but for each field it -- contains operations to get and set target field. data FieldLens dt fname ftype [TargetField] :: (InstrGetFieldC dt fname, InstrSetFieldC dt fname, GetFieldType dt fname ~ targetFType, AccessFieldC dt fname) => Label fname -> StoreFieldOps dt targetFName targetFType -> FieldLens dt targetFName targetFType [DeeperField] :: (AccessFieldC dt fname, InstrSetFieldC dt fname, HasField (GetFieldType dt fname) targetFName targetFType) => Label fname -> StoreFieldOps dt targetFName targetFType -> FieldLens dt targetFName targetFType -- | Access to StoreFieldOps flSFO :: FieldLens dt fname ftype -> StoreFieldOps dt fname ftype -- | Class like StoreHasField type class but holding a lens to a -- field. class (KnownValue ftype, KnownValue dt) => HasField dt fname ftype | dt fname -> ftype fieldLens :: HasField dt fname ftype => FieldLens dt fname ftype -- | Build a lens to deeper field of an object. fieldLensDeeper :: forall dt targetName targetType fname. (AccessFieldC dt fname, HasFieldOfType dt fname (GetFieldType dt fname), HasField (GetFieldType dt fname) targetName targetType) => Label fname -> FieldLens dt targetName targetType -- | Build a lens to a direct field of an object. fieldLensADT :: forall dt targetFName targetFType fname. (InstrGetFieldC dt fname, InstrSetFieldC dt fname, GetFieldType dt fname ~ targetFType, AccessFieldC dt fname) => Label fname -> FieldLens dt targetFName targetFType instance (Michelson.Typed.Haskell.Instr.Product.InstrSetFieldC dt fname, Michelson.Typed.Haskell.Instr.Product.InstrGetFieldC dt fname, Michelson.Typed.Haskell.Instr.Product.GetFieldType dt fname GHC.Types.~ ftype, Indigo.Internal.Field.AccessFieldC dt fname, GHC.TypeLits.KnownSymbol fname, Lorentz.Constraints.Scopes.KnownValue ftype, Lorentz.Constraints.Scopes.KnownValue dt) => Indigo.Internal.Field.HasField dt fname ftype -- | Expr data type and its generalizations module Indigo.Internal.Expr.Types data Expr a [C] :: NiceConstant a => a -> Expr a [V] :: KnownValue a => Var a -> Expr a [ObjMan] :: ObjectManipulation a -> Expr a [Cast] :: KnownValue a => Expr a -> Expr a [Size] :: SizeOpHs c => Expr c -> Expr Natural [Update] :: (UpdOpHs c, KnownValue c) => Expr c -> Expr (UpdOpKeyHs c) -> Expr (UpdOpParamsHs c) -> Expr c [Add] :: (ArithOpHs Add n m, KnownValue (ArithResHs Add n m)) => Expr n -> Expr m -> Expr (ArithResHs Add n m) [Sub] :: (ArithOpHs Sub n m, KnownValue (ArithResHs Sub n m)) => Expr n -> Expr m -> Expr (ArithResHs Sub n m) [Mul] :: (ArithOpHs Mul n m, KnownValue (ArithResHs Mul n m)) => Expr n -> Expr m -> Expr (ArithResHs Mul n m) [Div] :: (EDivOpHs n m, KnownValue (EDivOpResHs n m)) => Expr n -> Expr m -> Expr (EDivOpResHs n m) [Mod] :: (EDivOpHs n m, KnownValue (EModOpResHs n m)) => Expr n -> Expr m -> Expr (EModOpResHs n m) [Abs] :: (UnaryArithOpHs Abs n, KnownValue (UnaryArithResHs Abs n)) => Expr n -> Expr (UnaryArithResHs Abs n) [Neg] :: (UnaryArithOpHs Neg n, KnownValue (UnaryArithResHs Neg n)) => Expr n -> Expr (UnaryArithResHs Neg n) [Lsl] :: (ArithOpHs Lsl n m, KnownValue (ArithResHs Lsl n m)) => Expr n -> Expr m -> Expr (ArithResHs Lsl n m) [Lsr] :: (ArithOpHs Lsr n m, KnownValue (ArithResHs Lsr n m)) => Expr n -> Expr m -> Expr (ArithResHs Lsr n m) [Eq'] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Neq] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Le] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Lt] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Ge] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Gt] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Or] :: (ArithOpHs Or n m, KnownValue (ArithResHs Or n m)) => Expr n -> Expr m -> Expr (ArithResHs Or n m) [Xor] :: (ArithOpHs Xor n m, KnownValue (ArithResHs Xor n m)) => Expr n -> Expr m -> Expr (ArithResHs Xor n m) [And] :: (ArithOpHs And n m, KnownValue (ArithResHs And n m)) => Expr n -> Expr m -> Expr (ArithResHs And n m) [Not] :: (UnaryArithOpHs Not n, KnownValue (UnaryArithResHs Not n)) => Expr n -> Expr (UnaryArithResHs Not n) [Int'] :: Expr Natural -> Expr Integer [IsNat] :: Expr Integer -> Expr (Maybe Natural) [Coerce] :: (Castable_ a b, KnownValue b) => Expr a -> Expr b [ForcedCoerce] :: (MichelsonCoercible a b, KnownValue b) => Expr a -> Expr b [Fst] :: KnownValue n => Expr (n, m) -> Expr n [Snd] :: KnownValue m => Expr (n, m) -> Expr m [Pair] :: KnownValue (n, m) => Expr n -> Expr m -> Expr (n, m) [Some] :: KnownValue (Maybe t) => Expr t -> Expr (Maybe t) [None] :: KnownValue t => Expr (Maybe t) [Right'] :: (KnownValue y, KnownValue (Either y x)) => Expr x -> Expr (Either y x) [Left'] :: (KnownValue x, KnownValue (Either y x)) => Expr y -> Expr (Either y x) [Mem] :: MemOpHs c => Expr (MemOpKeyHs c) -> Expr c -> Expr Bool [UGet] :: (HasUStore name key value store, KnownValue value) => Label name -> Expr key -> Expr (UStore store) -> Expr (Maybe value) [UInsertNew] :: (HasUStore name key value store, IsError err, KnownValue (UStore store)) => Label name -> err -> Expr key -> Expr value -> Expr (UStore store) -> Expr (UStore store) [UInsert] :: (HasUStore name key value store, KnownValue (UStore store)) => Label name -> Expr key -> Expr value -> Expr (UStore store) -> Expr (UStore store) [UMem] :: (HasUStore name key val store, KnownValue val) => Label name -> Expr key -> Expr (UStore store) -> Expr Bool [UUpdate] :: (HasUStore name key val store, KnownValue (UStore store)) => Label name -> Expr key -> Expr (Maybe val) -> Expr (UStore store) -> Expr (UStore store) [UDelete] :: (HasUStore name key val store, KnownValue (UStore store)) => Label name -> Expr key -> Expr (UStore store) -> Expr (UStore store) [Wrap] :: (InstrWrapOneC dt name, KnownValue dt) => Label name -> Expr (CtorOnlyField name dt) -> Expr dt [Unwrap] :: (InstrUnwrapC dt name, KnownValue (CtorOnlyField name dt)) => Label name -> Expr dt -> Expr (CtorOnlyField name dt) [Construct] :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt [ConstructWithoutNamed] :: ComplexObjectC dt => Rec Expr (FieldTypes dt) -> Expr dt [Name] :: KnownValue (name :! t) => Label name -> Expr t -> Expr (name :! t) [UnName] :: KnownValue t => Label name -> Expr (name :! t) -> Expr t [EmptySet] :: (NiceComparable key, KnownValue (Set key)) => Expr (Set key) [Get] :: (GetOpHs c, KnownValue (Maybe (GetOpValHs c)), KnownValue (GetOpValHs c)) => Expr (GetOpKeyHs c) -> Expr c -> Expr (Maybe (GetOpValHs c)) [EmptyMap] :: (KnownValue value, NiceComparable key, KnownValue (Map key value)) => Expr (Map key value) [EmptyBigMap] :: (KnownValue value, NiceComparable key, KnownValue (BigMap key value)) => Expr (BigMap key value) [Pack] :: NicePackedValue a => Expr a -> Expr ByteString [Unpack] :: NiceUnpackedValue a => Expr ByteString -> Expr (Maybe a) [Cons] :: KnownValue (List a) => Expr a -> Expr (List a) -> Expr (List a) [Nil] :: KnownValue a => Expr (List a) [Concat] :: (ConcatOpHs c, KnownValue c) => Expr c -> Expr c -> Expr c [Concat'] :: (ConcatOpHs c, KnownValue c) => Expr (List c) -> Expr c [Slice] :: (SliceOpHs c, KnownValue c) => Expr Natural -> Expr Natural -> Expr c -> Expr (Maybe c) [Contract] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, ToTAddress p addr, ToT addr ~ ToT Address) => Expr addr -> Expr (Maybe (ContractRef p)) [Self] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p) => Expr (ContractRef p) [ContractAddress] :: Expr (ContractRef p) -> Expr Address [ContractCallingUnsafe] :: NiceParameter arg => EpName -> Expr Address -> Expr (Maybe (ContractRef arg)) [RunFutureContract] :: NiceParameter p => Expr (FutureContract p) -> Expr (Maybe (ContractRef p)) [ImplicitAccount] :: Expr KeyHash -> Expr (ContractRef ()) [ConvertEpAddressToContract] :: NiceParameter p => Expr EpAddress -> Expr (Maybe (ContractRef p)) [MakeView] :: KnownValue (View a r) => Expr a -> Expr (ContractRef r) -> Expr (View a r) [MakeVoid] :: KnownValue (Void_ a b) => Expr a -> Expr (Lambda b b) -> Expr (Void_ a b) [CheckSignature] :: Expr PublicKey -> Expr Signature -> Expr ByteString -> Expr Bool [Sha256] :: Expr ByteString -> Expr ByteString [Sha512] :: Expr ByteString -> Expr ByteString [Blake2b] :: Expr ByteString -> Expr ByteString [HashKey] :: Expr PublicKey -> Expr KeyHash [ChainId] :: Expr ChainId [Now] :: Expr Timestamp [Amount] :: Expr Mutez [Balance] :: Expr Mutez [Sender] :: Expr Address [Exec] :: KnownValue b => Expr a -> Expr (Lambda a b) -> Expr b [NonZero] :: (NonZero n, KnownValue (Maybe n)) => Expr n -> Expr (Maybe n) type IsExpr op n = (ToExpr op, ExprType op ~ n, KnownValue n) class ToExpr' (Decide x) x => ToExpr x type ExprType a = ExprType' (Decide a) a type (:~>) op n = IsExpr op n toExpr :: forall a. ToExpr a => a -> Expr (ExprType a) type IsArithExpr exN exM a n m = (exN :~> n, exM :~> m, ArithOpHs a n m, KnownValue (ArithResHs a n m)) type IsUnaryArithExpr exN a n = (exN :~> n, UnaryArithOpHs a n, KnownValue (UnaryArithResHs a n)) type IsConcatExpr exN1 exN2 n = (exN1 :~> n, exN2 :~> n, ConcatOpHs n) type IsConcatListExpr exN n = (exN :~> List n, ConcatOpHs n, KnownValue n) type IsDivExpr exN exM n m = (exN :~> n, exM :~> m, EDivOpHs n m, KnownValue (EDivOpResHs n m)) type IsModExpr exN exM n m = (exN :~> n, exM :~> m, EDivOpHs n m, KnownValue (EModOpResHs n m)) type IsGetExpr exKey exMap map = (exKey :~> GetOpKeyHs map, exMap :~> map, GetOpHs map, KnownValue (GetOpValHs map)) type IsMemExpr exKey exN n = (exKey :~> MemOpKeyHs n, exN :~> n, MemOpHs n) type IsSizeExpr exN n = (exN :~> n, SizeOpHs n) type IsSliceExpr exN n = (exN :~> n, SliceOpHs n) type IsUpdExpr exKey exVal exMap map = (exKey :~> UpdOpKeyHs map, exVal :~> UpdOpParamsHs map, exMap :~> map, UpdOpHs map) -- | Datatype describing access to an inner fields of object, like -- object !. field1 !. field2 ~. (field3, value3) ~. (field4, -- value4) data ObjectManipulation a [Object] :: Expr a -> ObjectManipulation a [ToField] :: HasField dt fname ftype => ObjectManipulation dt -> Label fname -> ObjectManipulation ftype [SetField] :: HasField dt fname ftype => ObjectManipulation dt -> Label fname -> Expr ftype -> ObjectManipulation dt type ObjectExpr a = IndigoObjectF (NamedFieldExpr a) a -- | Auxiliary datatype where each field refers to an expression the field -- equals to. It's not recursive one. data NamedFieldExpr a name [NamedFieldExpr] :: {unNamedFieldExpr :: Expr (GetFieldType a name)} -> NamedFieldExpr a name instance Indigo.Internal.Expr.Types.ToExpr' (Indigo.Internal.Expr.Types.Decide x) x => Indigo.Internal.Expr.Types.ToExpr x instance Lorentz.Constraints.Scopes.KnownValue a => Indigo.Internal.Expr.Types.ToExpr' 'Indigo.Internal.Expr.Types.VarD (Indigo.Internal.Object.Var a) instance Lorentz.Constraints.Scopes.NiceConstant a => Indigo.Internal.Expr.Types.ToExpr' 'Indigo.Internal.Expr.Types.ValD a instance Indigo.Internal.Expr.Types.ToExpr' 'Indigo.Internal.Expr.Types.ObjManD (Indigo.Internal.Expr.Types.ObjectManipulation a) instance Indigo.Internal.Expr.Types.ToExpr' 'Indigo.Internal.Expr.Types.ExprD (Indigo.Internal.Expr.Types.Expr a) -- | Expr compilation module Indigo.Internal.Expr.Compilation compileExpr :: forall a inp. Expr a -> IndigoState inp (a & inp) () -- | ObjManipulationRes represents a postponed compilation of -- ObjectManipulation datatype. When ObjectManipulation is -- being compiled we are trying to put off the generation of code for -- work with an object because we can just go to a deeper field without -- its "materialization" onto stack. data ObjManipulationRes inp a [StillObject] :: ObjectExpr a -> ObjManipulationRes inp a [OnStack] :: IndigoState inp (a & inp) () -> ObjManipulationRes inp a -- | This function might look cumbersome but it basically either goes -- deeper to an inner field or generates Lorentz code. runObjectManipulation :: ObjectManipulation x -> ObjManipulationRes inp x nullaryOp :: KnownValue res => (inp :-> (res : inp)) -> IndigoState inp (res : inp) () unaryOp :: KnownValue res => Expr n -> ((n & inp) :-> (res & inp)) -> IndigoState inp (res & inp) () binaryOp :: KnownValue res => Expr n -> Expr m -> ((n & (m & inp)) :-> (res & inp)) -> IndigoState inp (res & inp) () ternaryOp :: KnownValue res => Expr n -> Expr m -> Expr l -> ((n & (m & (l & inp))) :-> (res & inp)) -> IndigoState inp (res & inp) () nullaryOpFlat :: (inp :-> inp) -> IndigoState inp inp () unaryOpFlat :: Expr n -> ((n & inp) :-> inp) -> IndigoState inp inp () binaryOpFlat :: Expr n -> Expr m -> ((n & (m & inp)) :-> inp) -> IndigoState inp inp () ternaryOpFlat :: Expr n -> Expr m -> Expr l -> ((n & (m & (l & inp))) :-> inp) -> IndigoState inp inp () -- | All the basic Expressions used in Indigo code. -- -- Note: infix operators acting on structure follow a naming convention: -- --
    --
  1. the last character identifies the structure -- type:
  2. --
  3. the preceding characters identify the action:
  4. --
-- -- The only exception to this convention is (.:) (for cons) module Indigo.Internal.Expr.Symbolic constExpr :: NiceConstant a => a -> Expr a -- | Create an expression holding a variable. varExpr :: KnownValue a => Var a -> Expr a cast :: ex :~> a => ex -> Expr a add :: IsArithExpr exN exM Add n m => exN -> exM -> Expr (ArithResHs Add n m) sub :: IsArithExpr exN exM Sub n m => exN -> exM -> Expr (ArithResHs Sub n m) mul :: IsArithExpr exN exM Mul n m => exN -> exM -> Expr (ArithResHs Mul n m) div :: IsDivExpr exN exM n m => exN -> exM -> Expr (EDivOpResHs n m) mod :: IsModExpr exN exM n m => exN -> exM -> Expr (EModOpResHs n m) neg :: IsUnaryArithExpr exN Neg n => exN -> Expr (UnaryArithResHs Neg n) abs :: IsUnaryArithExpr exN Abs n => exN -> Expr (UnaryArithResHs Abs n) (+) :: IsArithExpr exN exM Add n m => exN -> exM -> Expr (ArithResHs Add n m) infixl 6 + (-) :: IsArithExpr exN exM Sub n m => exN -> exM -> Expr (ArithResHs Sub n m) infixl 6 - (*) :: IsArithExpr exN exM Mul n m => exN -> exM -> Expr (ArithResHs Mul n m) infixl 7 * (/) :: IsDivExpr exN exM n m => exN -> exM -> Expr (EDivOpResHs n m) infixl 7 / (%) :: IsModExpr exN exM n m => exN -> exM -> Expr (EModOpResHs n m) infixl 7 % eq :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool neq :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool lt :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool gt :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool le :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool ge :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (==) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 == (/=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 /= (<) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 < (>) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 > (<=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 <= (>=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 >= isNat :: ex :~> Integer => ex -> Expr (Maybe Natural) toInt :: ex :~> Natural => ex -> Expr Integer nonZero :: (ex :~> n, NonZero n, KnownValue (Maybe n)) => ex -> Expr (Maybe n) -- | Convert between types that have the same Michelson representation and -- an explicit permission for that in the face of CanCastTo -- constraint. coerce :: forall b a ex. (Castable_ a b, KnownValue b, ex :~> a) => ex -> Expr b -- | Convert between expressions of types that have the same Michelson -- representation. forcedCoerce :: forall b a ex. (MichelsonCoercible a b, KnownValue b, ex :~> a) => ex -> Expr b lsl :: IsArithExpr exN exM Lsl n m => exN -> exM -> Expr (ArithResHs Lsl n m) lsr :: IsArithExpr exN exM Lsr n m => exN -> exM -> Expr (ArithResHs Lsr n m) and :: IsArithExpr exN exM And n m => exN -> exM -> Expr (ArithResHs And n m) or :: IsArithExpr exN exM Or n m => exN -> exM -> Expr (ArithResHs Or n m) xor :: IsArithExpr exN exM Xor n m => exN -> exM -> Expr (ArithResHs Xor n m) not :: IsUnaryArithExpr exN Not n => exN -> Expr (UnaryArithResHs Not n) (<<<) :: IsArithExpr exN exM Lsl n m => exN -> exM -> Expr (ArithResHs Lsl n m) infixl 8 <<< (>>>) :: IsArithExpr exN exM Lsr n m => exN -> exM -> Expr (ArithResHs Lsr n m) infixl 8 >>> (&&) :: IsArithExpr exN exM And n m => exN -> exM -> Expr (ArithResHs And n m) infixr 3 && (||) :: IsArithExpr exN exM Or n m => exN -> exM -> Expr (ArithResHs Or n m) infixr 2 || (^) :: IsArithExpr exN exM Xor n m => exN -> exM -> Expr (ArithResHs Xor n m) infixr 2 ^ pack :: (ex :~> a, NicePackedValue a) => ex -> Expr ByteString unpack :: (NiceUnpackedValue a, exb :~> ByteString) => exb -> Expr (Maybe a) pair :: (ex1 :~> n, ex2 :~> m, KnownValue (n, m)) => ex1 -> ex2 -> Expr (n, m) car :: (op :~> (n, m), KnownValue n) => op -> Expr n cdr :: (op :~> (n, m), KnownValue m) => op -> Expr m fst :: (op :~> (n, m), KnownValue n) => op -> Expr n snd :: (op :~> (n, m), KnownValue m) => op -> Expr m some :: (ex :~> t, KnownValue (Maybe t)) => ex -> Expr (Maybe t) none :: KnownValue t => Expr (Maybe t) right :: (ex :~> x, KnownValue y, KnownValue (Either y x)) => ex -> Expr (Either y x) left :: (ex :~> y, KnownValue x, KnownValue (Either y x)) => ex -> Expr (Either y x) slice :: (an :~> Natural, bn :~> Natural, IsSliceExpr ex c) => (an, bn) -> ex -> Expr (Maybe c) concat :: IsConcatExpr exN1 exN2 n => exN1 -> exN2 -> Expr n (<>) :: IsConcatExpr exN1 exN2 n => exN1 -> exN2 -> Expr n infixr 6 <> concatAll :: IsConcatListExpr exN n => exN -> Expr n nil :: KnownValue a => Expr (List a) cons :: (ex1 :~> a, ex2 :~> List a) => ex1 -> ex2 -> Expr (List a) (.:) :: (ex1 :~> a, ex2 :~> List a) => ex1 -> ex2 -> Expr (List a) infixr 5 .: get :: IsGetExpr exKey exMap map => exKey -> exMap -> Expr (Maybe (GetOpValHs map)) update :: IsUpdExpr exKey exVal exMap map => (exKey, exVal) -> exMap -> Expr map insert :: (ExprInsertable c insParam, ex :~> c) => insParam -> ex -> Expr c remove :: (ExprRemovable c, exStruct :~> c, exKey :~> UpdOpKeyHs c) => exKey -> exStruct -> Expr c mem :: IsMemExpr exKey exN n => exKey -> exN -> Expr Bool size :: IsSizeExpr exN n => exN -> Expr Natural (#:) :: IsGetExpr exKey exMap map => exMap -> exKey -> Expr (Maybe (GetOpValHs map)) infixl 8 #: (!:) :: IsUpdExpr exKey exVal exMap map => exMap -> (exKey, exVal) -> Expr map infixl 8 !: (+:) :: (ExprInsertable c exParam, exStructure :~> c) => exStructure -> exParam -> Expr c infixl 8 +: (-:) :: (ExprRemovable c, exStruct :~> c, exKey :~> UpdOpKeyHs c) => exStruct -> exKey -> Expr c infixl 8 -: (?:) :: IsMemExpr exKey exN n => exN -> exKey -> Expr Bool infixl 8 ?: empty :: (ExprMagma c, NiceComparable (UpdOpKeyHs c), KnownValue c) => Expr c emptyBigMap :: (KnownValue value, NiceComparable key, KnownValue (BigMap key value)) => Expr (BigMap key value) emptyMap :: (KnownValue value, NiceComparable key, KnownValue (Map key value)) => Expr (Map key value) emptySet :: (NiceComparable key, KnownValue (Set key)) => Expr (Set key) uGet :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr (Maybe value) uUpdate :: (HasUStore name key value store, exKey :~> key, exVal :~> Maybe value, exStore :~> UStore store) => exStore -> (Label name, exKey, exVal) -> Expr (UStore store) uInsert :: (HasUStore name key value store, exKey :~> key, exVal :~> value, exStore :~> UStore store) => exStore -> (Label name, exKey, exVal) -> Expr (UStore store) uInsertNew :: (HasUStore name key value store, IsError err, exKey :~> key, exVal :~> value, exStore :~> UStore store) => exStore -> (Label name, err, exKey, exVal) -> Expr (UStore store) uDelete :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr (UStore store) uMem :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr Bool (#@) :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr (Maybe value) infixr 8 #@ (!@) :: (HasUStore name key value store, exKey :~> key, exVal :~> Maybe value, exStore :~> UStore store) => exStore -> (Label name, exKey, exVal) -> Expr (UStore store) infixl 8 !@ (+@) :: (HasUStore name key value store, exKey :~> key, exVal :~> value, exStore :~> UStore store) => exStore -> (Label name, exKey, exVal) -> Expr (UStore store) infixr 8 +@ (++@) :: (HasUStore name key value store, IsError err, exKey :~> key, exVal :~> value, exStore :~> UStore store) => exStore -> (Label name, err, exKey, exVal) -> Expr (UStore store) infixr 8 ++@ (-@) :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr (UStore store) infixl 8 -@ (?@) :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr Bool infixl 8 ?@ wrap :: (InstrWrapOneC dt name, exField :~> CtorOnlyField name dt, KnownValue dt) => Label name -> exField -> Expr dt unwrap :: (InstrUnwrapC dt name, exDt :~> dt, KnownValue (CtorOnlyField name dt)) => Label name -> exDt -> Expr (CtorOnlyField name dt) (!!) :: (HasField dt name ftype, exDt :~> dt, exFld :~> ftype) => exDt -> (Label name, exFld) -> Expr dt infixl 8 !! (#!) :: (HasField dt name ftype, exDt :~> dt) => exDt -> Label name -> Expr ftype infixl 8 #! name :: (ex :~> t, KnownValue (name :! t)) => Label name -> ex -> Expr (name :! t) unName :: (ex :~> (name :! t), KnownValue t) => Label name -> ex -> Expr t (!~) :: (ex :~> t, KnownValue (name :! t)) => ex -> Label name -> Expr (name :! t) infixl 8 !~ (#~) :: (ex :~> (name :! t), KnownValue t) => ex -> Label name -> Expr t infixl 8 #~ construct :: (InstrConstructC dt, KnownValue dt, RMap (ConstructorFieldTypes dt), fields ~ Rec Expr (ConstructorFieldTypes dt), RecFromTuple fields) => IsoRecTuple fields -> Expr dt constructRec :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt contract :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, ToTAddress p addr, ToT addr ~ ToT Address, exAddr :~> addr) => exAddr -> Expr (Maybe (ContractRef p)) self :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p) => Expr (ContractRef p) contractAddress :: exc :~> ContractRef p => exc -> Expr Address contractCallingUnsafe :: (NiceParameter arg, exAddr :~> Address) => EpName -> exAddr -> Expr (Maybe (ContractRef arg)) contractCallingString :: (NiceParameter arg, exAddr :~> Address) => MText -> exAddr -> Expr (Maybe (ContractRef arg)) runFutureContract :: (NiceParameter p, conExpr :~> FutureContract p) => conExpr -> Expr (Maybe (ContractRef p)) implicitAccount :: exkh :~> KeyHash => exkh -> Expr (ContractRef ()) convertEpAddressToContract :: (NiceParameter p, epExpr :~> EpAddress) => epExpr -> Expr (Maybe (ContractRef p)) makeView :: (KnownValue (View a r), exa :~> a, exCRef :~> ContractRef r) => exa -> exCRef -> Expr (View a r) makeVoid :: (KnownValue (Void_ a b), exa :~> a, exCRef :~> Lambda b b) => exa -> exCRef -> Expr (Void_ a b) now :: Expr Timestamp amount :: Expr Mutez sender :: Expr Address blake2b :: hashExpr :~> ByteString => hashExpr -> Expr ByteString sha256 :: hashExpr :~> ByteString => hashExpr -> Expr ByteString sha512 :: hashExpr :~> ByteString => hashExpr -> Expr ByteString hashKey :: keyExpr :~> PublicKey => keyExpr -> Expr KeyHash chainId :: Expr ChainId balance :: Expr Mutez checkSignature :: (pkExpr :~> PublicKey, sigExpr :~> Signature, hashExpr :~> ByteString) => pkExpr -> sigExpr -> hashExpr -> Expr Bool instance (Lorentz.Constraints.Scopes.NiceComparable k, Lorentz.Constraints.Scopes.KnownValue v) => Indigo.Internal.Expr.Symbolic.ExprRemovable (Michelson.Typed.Haskell.Value.BigMap k v) instance (Lorentz.Constraints.Scopes.NiceComparable k, Lorentz.Constraints.Scopes.KnownValue v) => Indigo.Internal.Expr.Symbolic.ExprRemovable (Data.Map.Internal.Map k v) instance Lorentz.Constraints.Scopes.NiceComparable a => Indigo.Internal.Expr.Symbolic.ExprRemovable (Data.Set.Internal.Set a) instance (Lorentz.Constraints.Scopes.NiceComparable k, exKey Indigo.Internal.Expr.Types.:~> k, exValue Indigo.Internal.Expr.Types.:~> v) => Indigo.Internal.Expr.Symbolic.ExprInsertable (Michelson.Typed.Haskell.Value.BigMap k v) (exKey, exValue) instance (Lorentz.Constraints.Scopes.NiceComparable k, exKey Indigo.Internal.Expr.Types.:~> k, exValue Indigo.Internal.Expr.Types.:~> v) => Indigo.Internal.Expr.Symbolic.ExprInsertable (Data.Map.Internal.Map k v) (exKey, exValue) instance (Lorentz.Constraints.Scopes.NiceComparable a, exKey Indigo.Internal.Expr.Types.:~> a) => Indigo.Internal.Expr.Symbolic.ExprInsertable (Data.Set.Internal.Set a) exKey instance Lorentz.Constraints.Scopes.KnownValue v => Indigo.Internal.Expr.Symbolic.ExprMagma (Michelson.Typed.Haskell.Value.BigMap k v) instance Lorentz.Constraints.Scopes.KnownValue v => Indigo.Internal.Expr.Symbolic.ExprMagma (Data.Map.Internal.Map k v) instance Indigo.Internal.Expr.Symbolic.ExprMagma (Data.Set.Internal.Set k) -- | Decompose a complex value into its fields to be used in -- setVar. Also functionality to generate code to deconstruct -- storage into primitive fields the storage consists of and to construct -- it back. module Indigo.Internal.Expr.Decompose -- | Decompose an expression to list of its direct fields. decomposeExpr :: ComplexObjectC a => Expr a -> ExprDecomposition inp a -- | For given element on stack, generate code which decomposes it to list -- of its deep non-decomposable fields. Clean up code of -- SomeIndigoState composes the value back. deepDecomposeCompose :: forall a inp. IsObject a => SomeIndigoState (a & inp) (Var a) -- | Datatype representing decomposition of Expr. data ExprDecomposition inp a [ExprFields] :: Rec Expr (FieldTypes a) -> ExprDecomposition inp a [Deconstructed] :: IndigoState inp (FieldTypes a ++ inp) () -> ExprDecomposition inp a class IsObject' (TypeDecision a) a => IsObject a -- | Expressions supported in Indigo language and their compilation -- to Lorentz code. -- -- This module contains only basic building blocks that can be used to -- implement anything else. Other modules provide high level language -- constructions and standard functions. module Indigo.Internal.Expr module Indigo.Internal -- | Backend of the statements to create and modify variables module Indigo.Backend.Var -- | Create a new variable with passed expression as an initial value. newVar :: KnownValue x => Expr x -> IndigoState inp (x & inp) (Var x) -- | Set the variable to a new value. -- -- If a variable is a cell on the stack, we just compile passed -- expression and replace variable cell on stack. If a variable is -- decomposed, we decompose passed expression and call setVar -- recursively from its fields. setVar :: forall a inp. Var a -> Expr a -> IndigoState inp inp () -- | Set the field (direct or indirect) of a complex object. setField :: forall dt fname ftype inp. (IsObject dt, IsObject ftype, HasField dt fname ftype) => Var dt -> Label fname -> Expr ftype -> IndigoState inp inp () -- | Call binary operator with constant argument to update variable -- in-place. updateVar :: (IsObject x, KnownValue y) => ([y, x] :-> '[x]) -> Var x -> Expr y -> IndigoState inp inp () -- | Machinery that provides the ability to return values from Indigo -- statements (like if, case, while, etc). You -- are allowed to return unit, one expression or a tuple of expressions. -- For instance: -- --
--   (a, b) <- if flag
--             then do
--                    anotherFlag <- newVar True
--                    return (5 +. var, anotherFlag ||. True)
--             else return (0, anotherVar)
--   
-- -- is a valid construction. Pay attention to the fact that 5 +. -- var has the type Expr Integer, but 0 is just an -- Integer and anotherFlag ||. True has type Expr -- Bool, but anotherVar has type Var Bool; -- and this code will compile anyway. This is done intentionally to avoid -- the burden of manually converting values to expressions (or -- variables). So you can write the same constructions as in a regular -- language. module Indigo.Backend.Scope -- | To avoid overlapping instances we need to somehow distinguish single -- values from tuples, because the instances: -- --
--   instance Something a
--   instance Something (a, b)
--   
-- -- overlap and adding {-# OVERLAPPING #-} doesn't rescue in some -- cases, especially for type families defined in Something. data BranchRetKind -- | If value is unit (don't return anything) Unit :: BranchRetKind -- | If it's a single value (not tuple) SingleVal :: BranchRetKind -- | If it's tuple (we don't care how many elements are in) Tuple :: BranchRetKind type ScopeCodeGen ret = ScopeCodeGen' (ClassifyReturnValue ret) ret -- | Type class which unions all related management of computations in a -- scope, like in if branch, in case body, etc. -- -- Particularly, it takes care of the computation of expressions -- returning from a scope to leave it safely. Basically, this type class -- encapsulates the generation of Lorentz code that looks like: -- --
--   branch_code #
--     -- we get some arbitrary type of a stack here, lets call it xs
--   compute_returning_expressions #
--     -- we get type of stack [e1, e2, ... ek] ++ xs
--   cleanup_xs_to_inp
--     -- we get [e1, e2, e3, ..., ek] ++ inp
--   
class ReturnableValue' retKind ret => ScopeCodeGen' (retKind :: BranchRetKind) (ret :: Type) -- | Produces an Indigo computation that puts on the stack the evaluated -- returned expressions from the leaving scope. compileScopeReturn' :: ScopeCodeGen' retKind ret => ret -> IndigoState xs (RetOutStack' retKind ret ++ xs) () -- | Drop the stack cells that were produced in the leaving scope, apart -- from ones corresponding to the returning expressions. liftClear' :: ScopeCodeGen' retKind ret => (xs :-> inp) -> (RetOutStack' retKind ret ++ xs) :-> (RetOutStack' retKind ret ++ inp) -- | Generate gcClear for the whole statement genGcClear' :: ScopeCodeGen' retKind ret => (RetOutStack' retKind ret ++ inp) :-> inp type ReturnableValue ret = ReturnableValue' (ClassifyReturnValue ret) ret -- | Class for values that can be returned from Indigo statements. They -- include () and tuples. class ReturnableValue' (retKind :: BranchRetKind) (ret :: Type) where { -- | Type family reflecting the top elements of stack produced by a -- statement returning the value. type family RetOutStack' retKind ret :: [Type]; -- | Type family reflecting the returning value from a statement. type family RetVars' retKind ret :: Type; -- | Tuple looking like (Expr x, Expr y, ..) that corresponds to -- expressions returning from the scope. 'RetVars'' and 'RetExprs'' are -- twin types because the former just adds Var over each -- expression of the latter. type family RetExprs' retKind ret :: Type; } -- | Allocate variables referring to result of the statement. allocateVars' :: ReturnableValue' retKind ret => (forall inpt x. KnownValue x => MetaData inpt -> (Var x, MetaData (x & inpt))) -> MetaData inp -> (RetVars' retKind ret, MetaData (RetOutStack' retKind ret ++ inp)) type RetOutStack ret = RetOutStack' (ClassifyReturnValue ret) ret type RetVars ret = RetVars' (ClassifyReturnValue ret) ret type RetExprs ret = RetExprs' (ClassifyReturnValue ret) ret -- | This type family returns a promoted value of type BranchRetKind -- or causes a compilation error if a tuple with too many elements is -- used. type family ClassifyReturnValue (ret :: Type) -- | Specific version of 'liftClear'' liftClear :: forall ret inp xs. ScopeCodeGen ret => (xs :-> inp) -> (RetOutStack ret ++ xs) :-> (RetOutStack ret ++ inp) -- | Concatenate a scoped code, generation of returning expressions, and -- clean up of redundant cells from the stack. compileScope :: forall ret inp xs. ScopeCodeGen ret => GenCode inp xs ret -> inp :-> (RetOutStack ret ++ inp) -- | Specific version of 'allocateVars'' allocateVars :: forall ret inp. ReturnableValue ret => (forall inpt x. KnownValue x => MetaData inpt -> (Var x, MetaData (x & inpt))) -> MetaData inp -> (RetVars ret, MetaData (RetOutStack ret ++ inp)) -- | Push a variables in MetaData, referring to the generated -- expressions, and generate gcClear for the whole statement. finalizeStatement :: forall ret inp. ScopeCodeGen ret => MetaData inp -> (inp :-> (RetOutStack ret ++ inp)) -> GenCode inp (RetOutStack ret ++ inp) (RetVars ret) instance Indigo.Backend.Scope.KnownValueExpr single => Indigo.Backend.Scope.ReturnableValue' 'Indigo.Backend.Scope.SingleVal single instance Indigo.Backend.Scope.KnownValueExpr single => Indigo.Backend.Scope.ScopeCodeGen' 'Indigo.Backend.Scope.SingleVal single instance (Indigo.Backend.Scope.KnownValueExpr x, Indigo.Backend.Scope.KnownValueExpr y) => Indigo.Backend.Scope.ReturnableValue' 'Indigo.Backend.Scope.Tuple (x, y) instance (Indigo.Backend.Scope.KnownValueExpr x, Indigo.Backend.Scope.KnownValueExpr y) => Indigo.Backend.Scope.ScopeCodeGen' 'Indigo.Backend.Scope.Tuple (x, y) instance (Indigo.Backend.Scope.KnownValueExpr x, Indigo.Backend.Scope.KnownValueExpr y, Indigo.Backend.Scope.KnownValueExpr z) => Indigo.Backend.Scope.ReturnableValue' 'Indigo.Backend.Scope.Tuple (x, y, z) instance (Indigo.Backend.Scope.KnownValueExpr x, Indigo.Backend.Scope.KnownValueExpr y, Indigo.Backend.Scope.KnownValueExpr z) => Indigo.Backend.Scope.ScopeCodeGen' 'Indigo.Backend.Scope.Tuple (x, y, z) instance Indigo.Backend.Scope.ScopeCodeGen' 'Indigo.Backend.Scope.Unit () instance Indigo.Backend.Scope.ReturnableValue' 'Indigo.Backend.Scope.Unit () -- | This module implements the ability to put Indigo computations on the -- stack as a lambda and execute them. module Indigo.Backend.Lambda type LambdaPure1 arg res = Lambda1Generic '[] arg res -- | Create a lambda, that takes only one argument, from the given -- computation. The lambda is not allowed to modify storage and emit -- operations. createLambdaPure1 :: forall res arg inp out. CreateLambdaPure1C arg res => LambdaCreator '[] arg res inp out type CreateLambdaPure1C arg res = CreateLambda1CGeneric '[] arg res -- | Execute a lambda, which accepts only one argument, on passed -- expression. executeLambdaPure1 :: forall res arg inp. ExecuteLambdaPure1C arg res => LambdaExecutor '[] arg res inp type ExecuteLambdaPure1C arg res = ExecuteLambda1CGeneric '[] arg res initMetaDataPure :: KnownValue arg => (Var arg, MetaData '[arg]) type Lambda1 st arg res = Lambda1Generic '[st] arg res -- | Create a lambda, that takes only one argument, from the given -- computation. The lambda is not allowed to emit operations. createLambda1 :: forall st res arg inp out. CreateLambda1C st arg res => LambdaCreator '[st] arg res inp out type CreateLambda1C st arg res = (KnownValue st, CreateLambda1CGeneric '[st] arg res) -- | Execute a lambda that accepts only one argument on the given -- expression. executeLambda1 :: forall st res arg inp. ExecuteLambda1C st arg res => LambdaExecutor '[st] arg res inp type ExecuteLambda1C st arg res = (IsObject st, HasStorage st, ExecuteLambda1CGeneric '[st] arg res) initMetaData :: (KnownValue arg, KnownValue st) => (Var arg, MetaData '[arg, st]) type LambdaEff1 st arg res = Lambda1Generic '[st, Ops] arg res -- | Create a lambda, that takes only one argument, from the given -- computation, and return a variable referring to this lambda. The -- lambda is allowed to modify storage and emit operations. createLambdaEff1 :: forall st res arg inp out. CreateLambdaEff1C st arg res => LambdaCreator '[st, Ops] arg res inp out type CreateLambdaEff1C st arg res = (KnownValue st, CreateLambda1CGeneric '[st, Ops] arg res) -- | Execute a lambda that accepts only one argument on the given -- expression. Also updates the storage and operations with the values -- returned from the lambda. executeLambdaEff1 :: forall st res arg inp. ExecuteLambdaEff1C st arg res => LambdaExecutor '[st, Ops] arg res inp type ExecuteLambdaEff1C st arg res = (HasStorage st, HasSideEffects, IsObject st, ExecuteLambda1CGeneric '[st, Ops] arg res) initMetaDataEff :: (KnownValue arg, KnownValue st) => (Var arg, MetaData '[arg, st, Ops]) type Lambda1Generic extra arg res = (arg & extra) :-> (RetOutStack res ++ extra) type LambdaExecutor extra arg res inp = Var (Lambda1Generic extra arg res) -> Expr arg -> IndigoState inp (RetOutStack res ++ inp) (RetVars res) type LambdaCreator extra arg res inp out = (Var arg -> IndigoState (arg & extra) out res) -> IndigoState inp (Lambda1Generic extra arg res & inp) (Var (Lambda1Generic extra arg res)) -- | Conditional statements of Indigo language. module Indigo.Backend.Conditional -- | If statement. All variables created inside its branches will be -- released after the execution leaves the scope in which they were -- created. if_ :: forall inp xs ys a b. IfConstraint a b => Expr Bool -> IndigoState inp xs a -> IndigoState inp ys b -> IndigoState inp (RetOutStack a ++ inp) (RetVars a) -- | If which works like case for Maybe. ifSome :: forall inp xs ys x a b. (IfConstraint a b, KnownValue x) => Expr (Maybe x) -> (Var x -> IndigoState (x & inp) xs a) -> IndigoState inp ys b -> IndigoState inp (RetOutStack a ++ inp) (RetVars a) -- | If which works like case for Either. ifRight :: forall inp xs ys x y a b. (IfConstraint a b, KnownValue x, KnownValue y) => Expr (Either y x) -> (Var x -> IndigoState (x & inp) xs a) -> (Var y -> IndigoState (y & inp) ys b) -> IndigoState inp (RetOutStack a ++ inp) (RetVars a) ifCons :: forall inp xs ys x a b. (IfConstraint a b, KnownValue x) => Expr (List x) -> (Var x -> Var (List x) -> IndigoState (x & (List x & inp)) xs a) -> IndigoState inp ys b -> IndigoState inp (RetOutStack a ++ inp) (RetVars a) type IfConstraint a b = (ScopeCodeGen a, ScopeCodeGen b, CompareBranchesResults (RetExprs a) (RetExprs b), RetVars a ~ RetVars b, RetOutStack a ~ RetOutStack b) -- | Error related statements of Indigo language. module Indigo.Backend.Error failWith :: KnownValue a => Expr a -> IndigoState s t r failUsing_ :: IsError x => x -> IndigoState s t r failCustom :: forall tag err s t r. (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err) => Label tag -> Expr err -> IndigoState s t r failCustom_ :: forall tag s t r notVoidErrorMsg. (RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag) => Label tag -> IndigoState s t r failUnexpected_ :: MText -> IndigoState s t r assert :: forall s x. IsError x => x -> Expr Bool -> IndigoState s s () assertSome :: forall x s err. (IsError err, KnownValue x) => err -> Expr (Maybe x) -> IndigoState s s () assertNone :: forall x s err. (IsError err, KnownValue x) => err -> Expr (Maybe x) -> IndigoState s s () assertRight :: forall x y s err. (IsError err, KnownValue x, KnownValue y) => err -> Expr (Either y x) -> IndigoState s s () assertLeft :: forall x y s err. (IsError err, KnownValue x, KnownValue y) => err -> Expr (Either y x) -> IndigoState s s () assertCustom :: forall tag err s. (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err) => Label tag -> Expr err -> Expr Bool -> IndigoState s s () assertCustom_ :: forall tag s notVoidErrorMsg. (RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag) => Label tag -> Expr Bool -> IndigoState s s () -- | High level statements of Indigo language. module Indigo.Backend.Case -- | A case statement for indigo. See examples for a sample usage. caseRec :: forall dt inp ret clauses. CaseCommon dt ret clauses => Expr dt -> clauses -> IndigoState inp (RetOutStack ret ++ inp) (RetVars ret) -- | case_ for pattern-matching on parameter. entryCaseRec :: forall dt entrypointKind inp ret clauses. (CaseCommon dt ret clauses, DocumentEntrypoints entrypointKind dt) => Proxy entrypointKind -> Expr dt -> clauses -> IndigoState inp (RetOutStack ret ++ inp) (RetVars ret) -- | entryCase_ for contracts with flat parameter. entryCaseSimpleRec :: forall cp inp ret clauses. (CaseCommon cp ret clauses, DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp) => Expr cp -> clauses -> IndigoState inp (RetOutStack ret ++ inp) (RetVars ret) -- | This type is analogous to the CaseClauseL type but instead of -- wrapping a Lorentz instruction, this wraps an Indigo value with the -- same input/output types. data IndigoCaseClauseL ret (param :: CaseClauseParam) type CaseCommonF f dt ret clauses = (InstrCaseC dt, RMap (CaseClauses dt), clauses ~ Rec (f ret) (CaseClauses dt), ScopeCodeGen ret) type CaseCommon dt ret clauses = CaseCommonF IndigoCaseClauseL dt ret clauses data IndigoAnyOut x ret IndigoAnyOut :: (forall inp. SomeIndigoState (x : inp) retBranch) -> IndigoAnyOut x ret instance (name GHC.Types.~ GHC.TypeLits.AppendSymbol "c" ctor, Lorentz.Constraints.Scopes.KnownValue x) => Lorentz.ADT.CaseArrow name (Indigo.Internal.Object.Var x -> Indigo.Backend.Case.IndigoAnyOut x ret) (Indigo.Backend.Case.IndigoCaseClauseL ret ('Michelson.Typed.Haskell.Instr.Sum.CaseClauseParam ctor ('Michelson.Typed.Haskell.Instr.Sum.OneField x))) -- | Strictly typed statements of Indigo language. module Indigo.Backend -- | For statements to iterate over container. forEach :: (IterOpHs a, KnownValue (IterOpElHs a)) => Expr a -> (Var (IterOpElHs a) -> IndigoState (IterOpElHs a & inp) xs ()) -> IndigoState inp inp () -- | While statement. The same rule about releasing. while :: Expr Bool -> IndigoState inp xs () -> IndigoState inp inp () whileLeft :: (KnownValue l, KnownValue r) => Expr (Either l r) -> (Var l -> IndigoState (l & inp) xs ()) -> IndigoState inp (r & inp) (Var r) selfCalling :: forall p inp mname. (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname)) => EntrypointRef mname -> IndigoState inp (ContractRef (GetEntrypointArgCustom p mname) & inp) (Var (ContractRef (GetEntrypointArgCustom p mname))) contractCalling :: forall cp inp epRef epArg addr. (HasEntrypointArg cp epRef epArg, ToTAddress cp addr, ToT addr ~ ToT Address, KnownValue epArg) => epRef -> Expr addr -> IndigoState inp (Maybe (ContractRef epArg) & inp) (Var (Maybe (ContractRef epArg))) -- | Put a document item. doc :: DocItem di => di -> IndigoState s s () -- | Group documentation built in the given piece of code into block -- dedicated to one thing, e.g. to one entrypoint. docGroup :: DocGrouping -> IndigoState i o () -> IndigoState i o () -- | Insert documentation of the contract storage type. The type should be -- passed using type applications. docStorage :: forall storage s. TypeHasDoc storage => IndigoState s s () -- | Give a name to given contract. Apply it to the whole contract code. contractName :: Text -> IndigoState i o () -> IndigoState i o () -- | Indigo version for the function of the same name from Lorentz. finalizeParamCallingDoc :: (NiceParameterFull cp, RequireSumType cp, HasCallStack) => (Var cp -> IndigoState (cp & inp) out x) -> Expr cp -> IndigoState inp out x -- | Attach general info to given contract. contractGeneral :: IndigoState i o () -> IndigoState i o () -- | Attach default general info to the contract documentation. contractGeneralDefault :: IndigoState s s () transferTokens :: (NiceParameter p, HasSideEffects) => Expr p -> Expr Mutez -> Expr (ContractRef p) -> IndigoState inp inp () setDelegate :: HasSideEffects => Expr (Maybe KeyHash) -> IndigoState inp inp () -- | Takes an arbitrary IndigoM and wraps it into an -- IndigoFunction producing a local scope for its execution. -- Once it executed, all non-returned variables are cleaned up so that -- the stack has only returned variables at the top. This also can be -- interpreted as if True then f else nop. -- -- Note, that by default we do not define scope inside indigo functions, -- meaning that once we want to create a new variable or return it from a -- function we need to do it inside scope $ instr construction, -- for example: -- --
--   f :: IndigoFunction s Natural
--   f = scope $ do
--     *[s]*
--     res <- newVar (0 :: Natural)
--     *[Natural, s]*
--     scope $ do
--       _n <- newVar (1 :: Integer)
--       *[Integer, Natural, s]
--       res += 4
--     *[Natural, s]*
--     return res
--     *[s]*
--   
scope :: forall a inp out. ScopeCodeGen a => IndigoState inp out a -> IndigoState inp (RetOutStack a ++ inp) (RetVars a) -- | Add a comment comment :: CommentType -> IndigoState i i () -- | StatementF functor datatype for Freer monad module Indigo.Frontend.Statement -- | StatementF functor for Freer monad. -- -- The constructors correspond to every Indigo statement that has -- expressions (Expr x) in its signature. -- -- The ones that don't take expressions are compiled directly to -- IndigoState (and kept in LiftIndigoState), because they -- won't be taken into consideration by an optimizer anyway. -- -- One more detail about StatementF is that it takes a -- cont type parameter, which is basically IndigoM -- (freer monad), to avoid cyclic dependencies. cont is needed -- to support statements which have recursive structure (like: -- if, while, case, etc). data StatementF (freer :: Type -> Type) a -- | Direct injection of IndigoState of statements which are not going to -- be analyzed by optimizer. [LiftIndigoState] :: (forall inp. SomeIndigoState inp a) -> StatementF freer a [NewVar] :: KnownValue x => Expr x -> StatementF freer (Var x) [SetVar] :: Var x -> Expr x -> StatementF freer () [VarModification] :: (IsObject x, KnownValue y) => ([y, x] :-> '[x]) -> Var x -> Expr y -> StatementF freer () [SetField] :: (IsObject dt, IsObject ftype, HasField dt fname ftype) => Var dt -> Label fname -> Expr ftype -> StatementF cont () -- | Pure lambda [LambdaPure1Call] :: (ExecuteLambdaPure1C arg res, CreateLambdaPure1C arg res, Typeable res) => String -> (Var arg -> freer res) -> Expr arg -> StatementF freer (RetVars res) -- | Default lambda which can modify storage [Lambda1Call] :: (ExecuteLambda1C st arg res, CreateLambda1C st arg res, Typeable res) => Proxy st -> String -> (Var arg -> freer res) -> Expr arg -> StatementF freer (RetVars res) -- | Lambda which can modify storage and emit operations [LambdaEff1Call] :: (ExecuteLambdaEff1C st arg res, CreateLambdaEff1C st arg res, Typeable res) => Proxy st -> String -> (Var arg -> freer res) -> Expr arg -> StatementF freer (RetVars res) [Scope] :: ScopeCodeGen a => freer a -> StatementF freer (RetVars a) [If] :: IfConstraint a b => Expr Bool -> freer a -> freer b -> StatementF freer (RetVars a) [IfSome] :: (IfConstraint a b, KnownValue x) => Expr (Maybe x) -> (Var x -> freer a) -> freer b -> StatementF freer (RetVars a) [IfRight] :: (IfConstraint a b, KnownValue x, KnownValue y) => Expr (Either y x) -> (Var x -> freer a) -> (Var y -> freer b) -> StatementF freer (RetVars a) [IfCons] :: (IfConstraint a b, KnownValue x) => Expr (List x) -> (Var x -> Var (List x) -> freer a) -> freer b -> StatementF freer (RetVars a) [Case] :: CaseCommonF (IndigoMCaseClauseL freer) dt ret clauses => Expr dt -> clauses -> StatementF freer (RetVars ret) [EntryCase] :: (CaseCommonF (IndigoMCaseClauseL freer) dt ret clauses, DocumentEntrypoints entrypointKind dt) => Proxy entrypointKind -> Expr dt -> clauses -> StatementF freer (RetVars ret) [EntryCaseSimple] :: (CaseCommonF (IndigoMCaseClauseL freer) cp ret clauses, DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp) => Expr cp -> clauses -> StatementF freer (RetVars ret) [While] :: Expr Bool -> freer () -> StatementF freer () [WhileLeft] :: (KnownValue x, KnownValue y) => Expr (Either y x) -> (Var y -> freer ()) -> StatementF freer (Var x) [ForEach] :: (IterOpHs a, KnownValue (IterOpElHs a)) => Expr a -> (Var (IterOpElHs a) -> freer ()) -> StatementF freer () [ContractName] :: Text -> freer () -> StatementF freer () [DocGroup] :: DocGrouping -> freer () -> StatementF freer () [ContractGeneral] :: freer () -> StatementF freer () [FinalizeParamCallingDoc] :: (NiceParameterFull cp, RequireSumType cp, HasCallStack) => (Var cp -> freer x) -> Expr cp -> StatementF freer x [TransferTokens] :: (NiceParameter p, HasSideEffects) => Expr p -> Expr Mutez -> Expr (ContractRef p) -> StatementF freer () [SetDelegate] :: HasSideEffects => Expr (Maybe KeyHash) -> StatementF freer () [CreateContract] :: (IsObject st, NiceStorage st, NiceParameterFull param, HasSideEffects) => Contract param st -> Expr (Maybe KeyHash) -> Expr Mutez -> Expr st -> StatementF freer (Var Address) [ContractCalling] :: (HasEntrypointArg cp epRef epArg, ToTAddress cp addr, ToT addr ~ ToT Address, KnownValue epArg) => Proxy cp -> epRef -> Expr addr -> StatementF freer (Var (Maybe (ContractRef epArg))) [FailWith] :: KnownValue a => Expr a -> StatementF freer r [Assert] :: IsError x => x -> Expr Bool -> StatementF freer () [FailCustom] :: (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err) => Label tag -> Expr err -> StatementF freer r type IfConstraint a b = (ScopeCodeGen a, ScopeCodeGen b, CompareBranchesResults (RetExprs a) (RetExprs b), RetVars a ~ RetVars b, RetOutStack a ~ RetOutStack b) -- | Analogous datatype as IndigoCaseClauseL from Indigo.Backend.Case data IndigoMCaseClauseL freer ret (param :: CaseClauseParam) [OneFieldIndigoMCaseClauseL] :: (CaseArrow name (Var x -> IndigoAnyOut x ret) (IndigoCaseClauseL ret ('CaseClauseParam ctor ('OneField x))), name ~ AppendSymbol "c" ctor, KnownValue x, ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr) => Label name -> (Var x -> freer retBr) -> IndigoMCaseClauseL freer ret ('CaseClauseParam ctor ('OneField x)) type CaseCommonF f dt ret clauses = (InstrCaseC dt, RMap (CaseClauses dt), clauses ~ Rec (f ret) (CaseClauses dt), ScopeCodeGen ret) module Indigo.Frontend.Program -- | Monad for writing your contracts in. newtype IndigoM a IndigoM :: Program (StatementF IndigoM) a -> IndigoM a [unIndigoM] :: IndigoM a -> Program (StatementF IndigoM) a -- | This is freer monad (in other words operational monad). -- -- It preserves the structure of the computation performed over it, -- including return and bind operations. This was -- introduced to be able to iterate over Indigo code and optimize/analyze -- it. -- -- You can read a clearer description of this construction in "The Book -- of Monads" by Alejandro Serrano. There is a chapter about free monads, -- specifically about Freer you can read at page 259. There is -- "operational" package which contains transformer of this monad and -- auxiliary functions but it's not used because we are using only some -- basics of it. data Program instr a [Done] :: a -> Program instr a [Instr] :: instr a -> Program instr a [Bind] :: Program instr a -> (a -> Program instr b) -> Program instr b -- | Traverse over Freer structure and interpret it interpretProgram :: Monad m => (forall x. instr x -> m x) -> Program instr a -> m a instance GHC.Base.Monad Indigo.Frontend.Program.IndigoM instance GHC.Base.Applicative Indigo.Frontend.Program.IndigoM instance GHC.Base.Functor Indigo.Frontend.Program.IndigoM instance GHC.Base.Functor (Indigo.Frontend.Program.Program instr) instance GHC.Base.Applicative (Indigo.Frontend.Program.Program instr) instance GHC.Base.Monad (Indigo.Frontend.Program.Program instr) module Indigo.Compilation.Params -- | Type of a function with n Var arguments and -- IndigoM a result. -- -- Note that the arguments are the first n elements of the -- inp stack in inverse order, for example: IndigoWithParams -- ('S ('S 'Z)) '[a, b, c] x is the same as: Var b -> Var a -- -> IndigoM x type family IndigoWithParams n inp a -- | Typeable and stack size constraint for the parameters of an -- IndigoWithParams. type family AreIndigoParams n stk :: Constraint -- | Converts an IndigoWithParams to its form without input -- Vars, alongside the MetaData to use it with. If there is -- an Ops to the bottom of the stack it also assigns a Var -- to it. fromIndigoWithParams :: forall inp n a. (AreIndigoParams n inp, KnownValue a) => IndigoWithParams n inp a -> MetaData inp -> Sing n -> (IndigoM a, MetaData inp) module Indigo.Compilation.Lambda data CompiledLambda [CompiledLambda] :: (Typeable arg, Typeable res, Typeable extra) => {_clProxyRes :: Proxy res, _clName :: String, _clVarLam :: Var (Lambda1Generic extra arg res)} -> CompiledLambda data Lambda1Def [LambdaPure1Def] :: (Typeable res, CreateLambdaPure1C arg res) => {_ldProxy :: Proxy (_stUnit, arg, res), _ldName :: String, _ldBody :: Var arg -> IndigoM res} -> Lambda1Def [Lambda1Def] :: (Typeable res, CreateLambda1C st arg res) => {_ldProxy :: Proxy (st, arg, res), _ldName :: String, _ldBody :: Var arg -> IndigoM res} -> Lambda1Def [LambdaEff1Def] :: (Typeable res, CreateLambdaEff1C st arg res) => {_ldProxy :: Proxy (st, arg, res), _ldName :: String, _ldBody :: Var arg -> IndigoM res} -> Lambda1Def -- | Collect all used lambdas in a computation (which might be either a -- contract body or another function body), which are called at least -- twice. Only outer functions will be gathered, for instance, if we call -- lambda func1 from func0, only func0 will be taken. collectLambdas :: forall a. IndigoM a -> Set Lambda1Def instance GHC.Classes.Eq Indigo.Compilation.Lambda.Lambda1Def instance GHC.Classes.Ord Indigo.Compilation.Lambda.Lambda1Def -- | This module contains everything related to compilation from Indigo to -- Lorentz, including plain Indigo code, as well as Indigo contracts. module Indigo.Compilation -- | Compile Indigo code to Lorentz. -- -- Note: it is necessary to specify the number of parameters (using the -- first type variable) of the Indigo function. Also, these should be on -- the top of the input stack in inverse order (see -- IndigoWithParams). compileIndigo :: forall n inp a. (SingI (ToPeano n), Default (MetaData inp), AreIndigoParams (ToPeano n) inp, KnownValue a) => IndigoWithParams (ToPeano n) inp a -> inp :-> inp -- | Type of a function with n Var arguments and -- IndigoM a result. -- -- Note that the arguments are the first n elements of the -- inp stack in inverse order, for example: IndigoWithParams -- ('S ('S 'Z)) '[a, b, c] x is the same as: Var b -> Var a -- -> IndigoM x type family IndigoWithParams n inp a -- | Type of a contract that can be compiled to Lorentz with -- compileIndigoContract. type IndigoContract param st = (HasStorage st, HasSideEffects) => Var param -> IndigoM () -- | Compile Indigo code to Lorentz contract. Drop elements from the stack -- to return only [Operation] and storage. compileIndigoContract :: forall param st. (KnownValue param, IsObject st) => IndigoContract param st -> ContractCode param st type Ops = [Operation] -- | Allows to get a variable with operations type HasSideEffects = Given (Var Ops) -- | Return a variable which refers to a stack cell with operations operationsVar :: HasSideEffects => Var Ops -- | Allows to get a variable with storage type HasStorage st = Given (Var st) -- | Return a variable which refers to a stack cell with storage storageVar :: HasStorage st => Var st -- | Duplication of Backend functions, but without input and output stack. module Indigo.Frontend.Language -- | Create a new variable with the result of the given expression as its -- initial value. new :: IsExpr ex x => ex -> IndigoM (Var x) -- | Set the given variable to the result of the given expression. setVar :: IsExpr ex x => Var x -> ex -> IndigoM () setField :: (ex :~> ftype, IsObject dt, IsObject ftype, HasField dt fname ftype) => Var dt -> Label fname -> ex -> IndigoM () (+=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Add n m, ArithResHs Add n m ~ m) => Var m -> ex1 -> IndigoM () (-=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Sub n m, ArithResHs Sub n m ~ m) => Var m -> ex1 -> IndigoM () (*=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Mul n m, ArithResHs Mul n m ~ m) => Var m -> ex1 -> IndigoM () (<<<=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsl n m, ArithResHs Lsl n m ~ m) => Var m -> ex1 -> IndigoM () (>>>=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsr n m, ArithResHs Lsr n m ~ m) => Var m -> ex1 -> IndigoM () (&&=) :: (IsExpr ex1 n, IsObject m, ArithOpHs And n m, ArithResHs And n m ~ m) => Var m -> ex1 -> IndigoM () (||=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Or n m, ArithResHs Or n m ~ m) => Var m -> ex1 -> IndigoM () (^=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Xor n m, ArithResHs Xor n m ~ m) => Var m -> ex1 -> IndigoM () (=:) :: IsExpr ex x => Var x -> ex -> IndigoM () infixr 0 =: -- | Get a field from the storage, returns a variable. -- -- Note that the storage type almost always needs to be specified. getStorageField :: forall store ftype fname. (HasStorage store, HasField store fname ftype) => Label fname -> IndigoM (Var ftype) -- | Sets a storage field to a new value. setStorageField :: forall store name ftype ex. (HasStorage store, ex :~> ftype, IsObject store, IsObject ftype, HasField store name ftype) => Label name -> ex -> IndigoM () -- | Updates a storage field by using an updating IndigoM. updateStorageField :: forall store ftype fname fex. (HasStorage store, fex :~> ftype, HasField store fname ftype, IsObject store, IsObject ftype) => Label fname -> (Var ftype -> IndigoM fex) -> IndigoM () if_ :: forall a b ex. (IfConstraint a b, ex :~> Bool) => ex -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Run the instruction when the condition is met, do nothing otherwise. when :: exc :~> Bool => exc -> IndigoM () -> IndigoM () -- | Reverse of when. unless :: exc :~> Bool => exc -> IndigoM () -> IndigoM () ifSome :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b) => ex -> (Var x -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) ifNone :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b) => ex -> IndigoM b -> (Var x -> IndigoM a) -> IndigoM (RetVars a) -- | Run the instruction when the given expression returns Just a -- value, do nothing otherwise. whenSome :: forall x exa. (KnownValue x, exa :~> Maybe x) => exa -> (Var x -> IndigoM ()) -> IndigoM () -- | Run the instruction when the given expression returns Nothing, -- do nothing otherwise. whenNone :: forall x exa. (KnownValue x, exa :~> Maybe x) => exa -> IndigoM () -> IndigoM () ifRight :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b) => ex -> (Var x -> IndigoM a) -> (Var y -> IndigoM b) -> IndigoM (RetVars a) ifLeft :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b) => ex -> (Var y -> IndigoM b) -> (Var x -> IndigoM a) -> IndigoM (RetVars a) whenRight :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x) => ex -> (Var x -> IndigoM ()) -> IndigoM () whenLeft :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x) => ex -> (Var y -> IndigoM ()) -> IndigoM () ifCons :: forall x a b ex. (KnownValue x, ex :~> List x, IfConstraint a b) => ex -> (Var x -> Var (List x) -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) -- | caseRec for tuples. case_ :: forall dt guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, RecFromTuple clauses, guard :~> dt) => guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | A case statement for indigo. See examples for a sample usage. caseRec :: forall dt guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, guard :~> dt) => guard -> clauses -> IndigoM (RetVars ret) -- | entryCaseRec for tuples. entryCase :: forall dt entrypointKind guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, RecFromTuple clauses, DocumentEntrypoints entrypointKind dt, guard :~> dt) => Proxy entrypointKind -> guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | caseRec for pattern-matching on parameter. entryCaseRec :: forall dt entrypointKind guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, DocumentEntrypoints entrypointKind dt, guard :~> dt) => Proxy entrypointKind -> guard -> clauses -> IndigoM (RetVars ret) entryCaseSimple :: forall cp guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) cp ret clauses, RecFromTuple clauses, DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp, guard :~> cp) => guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | An alias for #= kept only for backward compatibility. -- | Deprecated: use #= instead (//->) :: (CaseArrow name (Var x -> IndigoAnyOut x ret) (IndigoCaseClauseL ret ('CaseClauseParam ctor ('OneField x))), ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr, KnownValue x, name ~ AppendSymbol "c" ctor) => Label name -> (Var x -> IndigoM retBr) -> IndigoMCaseClauseL IndigoM ret ('CaseClauseParam ctor ('OneField x)) infixr 0 //-> -- | Use this instead of /->. -- -- This operator is like /-> but wraps a body into -- IndigoAnyOut, which is needed for two reasons: to allow having -- any output stack and to allow returning not exactly the same values. -- -- It has the added benefit of not being an arrow, so in case the body of -- the clause is a lambda there won't be several. (#=) :: (CaseArrow name (Var x -> IndigoAnyOut x ret) (IndigoCaseClauseL ret ('CaseClauseParam ctor ('OneField x))), ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr, KnownValue x, name ~ AppendSymbol "c" ctor) => Label name -> (Var x -> IndigoM retBr) -> IndigoMCaseClauseL IndigoM ret ('CaseClauseParam ctor ('OneField x)) infixr 0 #= scope :: forall a. ScopeCodeGen a => IndigoM a -> IndigoFunction a -- | Alias for scope we use in the tutorial. defFunction :: forall a. ScopeCodeGen a => IndigoM a -> IndigoFunction a -- | A more specific version of defFunction meant to more easily -- create IndigoContracts. -- -- Used in the tutorial. The HasSideEffects constraint is -- specified to avoid the warning for redundant constraints. defContract :: (HasSideEffects => IndigoM ()) -> HasSideEffects => IndigoProcedure -- | Like defNamedEffLambda1 but doesn't modify storage and doesn't make -- side effects. defNamedPureLambda1 :: forall argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambdaPure1C (ExprType argExpr) res, CreateLambdaPure1C (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | Like defNamedEffLambda1 but doesn't make side effects. defNamedLambda1 :: forall st argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambda1C st (ExprType argExpr) res, CreateLambda1C st (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | Like defNamedLambda1 but doesn't take an argument. defNamedLambda0 :: forall st res. (Typeable res, ExecuteLambda1C st () res, CreateLambda1C st () res) => String -> IndigoM res -> IndigoM (RetVars res) -- | Family of defNamed*LambdaN functions put an Indigo -- computation on the stack to later call it avoiding code duplication. -- defNamed*LambdaN takes a computation with N arguments. This -- family of functions add some overhead to contract byte size for every -- call of the function, therefore, DON'T use defNamed*LambdaN -- if: * Your computation is pretty small. It would be cheaper just to -- inline it, so use defFunction. * Your computation is called -- only once, in this case also use defFunction. -- -- Also, pay attention that defNamed*LambdaN accepts a string -- that is a name of the passed computation. Be careful and make sure -- that all declared computations have different names. Later the name -- will be removed. -- -- Pay attention, that lambda argument will be evaluated to variable -- before lambda calling. -- -- TODO Approach with lambda names has critical pitfall: in case if a -- function takes Label name, lambda body won't be regenerated -- for every different label. So be carefully, this will be fixed in a -- following issue. defNamedEffLambda1 :: forall st argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambdaEff1C st (ExprType argExpr) res, CreateLambdaEff1C st (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | While statement. while :: forall ex. ex :~> Bool => ex -> IndigoM () -> IndigoM () whileLeft :: forall x y ex. (ex :~> Either y x, KnownValue y, KnownValue x) => ex -> (Var y -> IndigoM ()) -> IndigoM (Var x) -- | For statements to iterate over a container. forEach :: forall a e. (IterOpHs a, KnownValue (IterOpElHs a), e :~> a) => e -> (Var (IterOpElHs a) -> IndigoM ()) -> IndigoM () selfCalling :: forall p mname. (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname)) => EntrypointRef mname -> IndigoM (Var (ContractRef (GetEntrypointArgCustom p mname))) contractCalling :: forall cp epRef epArg addr exAddr. (HasEntrypointArg cp epRef epArg, ToTAddress cp addr, ToT addr ~ ToT Address, exAddr :~> addr, KnownValue epArg) => epRef -> exAddr -> IndigoM (Var (Maybe (ContractRef epArg))) -- | Put a document item. doc :: DocItem di => di -> IndigoM () -- | Group documentation built in the given piece of code into a block -- dedicated to one thing, e.g. to one entrypoint. docGroup :: DocGrouping -> IndigoM () -> IndigoM () -- | Insert documentation of the contract's storage type. The type should -- be passed using type applications. docStorage :: forall storage. TypeHasDoc storage => IndigoM () -- | Give a name to the given contract. Apply it to the whole contract -- code. contractName :: Text -> IndigoM () -> IndigoM () -- | Attach general info to the given contract. contractGeneral :: IndigoM () -> IndigoM () -- | Attach default general info to the contract documentation. contractGeneralDefault :: IndigoM () -- | Indigo version for the homonym Lorentz function. finalizeParamCallingDoc :: forall param x. (ToExpr param, NiceParameterFull (ExprType param), RequireSumType (ExprType param), HasCallStack) => (Var (ExprType param) -> IndigoM x) -> param -> IndigoM x -- | Put a DAnchor doc item. anchor :: Text -> IndigoM () -- | Put a DDescription doc item. description :: Markdown -> IndigoM () -- | Put a DEntrypointExample doc item. example :: forall a. NiceParameter a => a -> IndigoM () transferTokens :: (IsExpr exp p, IsExpr exm Mutez, IsExpr exc (ContractRef p), NiceParameter p, HasSideEffects) => exp -> exm -> exc -> IndigoM () setDelegate :: (HasSideEffects, IsExpr ex (Maybe KeyHash)) => ex -> IndigoM () -- | Create contract using default compilation options for Lorentz -- compiler. -- -- See Lorentz.Run. createContract :: (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorage st, NiceParameterFull param, HasSideEffects) => (HasStorage st => Var param -> IndigoM ()) -> exk -> exm -> exs -> IndigoM (Var Address) -- | Create contract from raw Lorentz Contract. createLorentzContract :: (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorage st, NiceParameterFull param, HasSideEffects) => Contract param st -> exk -> exm -> exs -> IndigoM (Var Address) failWith :: forall r a ex. IsExpr ex a => ex -> IndigoM r assert :: forall x ex. (IsError x, IsExpr ex Bool) => x -> ex -> IndigoM () failCustom :: forall r tag err ex. (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err, ex :~> err) => Label tag -> ex -> IndigoM r failCustom_ :: forall r tag notVoidErrorMsg. (RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag) => Label tag -> IndigoM r failUnexpected_ :: MText -> IndigoM r assertCustom :: forall tag err errEx ex. (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err, IsExpr errEx err, IsExpr ex Bool) => Label tag -> errEx -> ex -> IndigoM () assertCustom_ :: forall tag notVoidErrorMsg ex. (RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag, IsExpr ex Bool) => Label tag -> ex -> IndigoM () -- | Add a comment in a generated Michelson code comment :: CommentType -> IndigoM () -- | Add a comment in a generated Michelson code justComment :: Text -> IndigoM () -- | Add a comment before and after the given Indigo function code. The -- first argument is the name of the function. commentAroundFun :: Text -> IndigoM a -> IndigoM a -- | Add a comment before and after the given Indigo statement code. The -- first argument is the name of the statement. commentAroundStmt :: Text -> IndigoM a -> IndigoM a -- | Utility type for an IndigoM that adds one element to the stack -- and returns a variable pointing at it. type IndigoFunction ret = IndigoM (RetVars ret) -- | Utility type for an IndigoM that does not modify the stack -- (only the values in it) and returns nothing. type IndigoProcedure = IndigoM () type IndigoEntrypoint param = param -> IndigoProcedure liftIndigoState :: (forall inp. SomeIndigoState inp a) -> IndigoM a module Indigo.Frontend -- | Module containing pretty-printing of Indigo contracts module Indigo.Print -- | Pretty-print an Indigo contract into Michelson code. printIndigoContract :: forall param st. (IsObject st, NiceParameterFull param, NiceStorage st) => Bool -> IndigoContract param st -> LText -- | Generate an Indigo contract documentation. renderIndigoDoc :: forall param st. (IsObject st, NiceParameterFull param) => IndigoContract param st -> LText -- | Prints the pretty-printed Michelson code of an Indigo contract to the -- standard output. -- -- This is intended to be easy to use for newcomers. printAsMichelson :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorage st, MonadIO m) => IndigoContract param st -> m () -- | Saves the pretty-printed Michelson code of an Indigo contract to the -- given file. -- -- This is intended to be easy to use for newcomers. saveAsMichelson :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorage st, MonadIO m, MonadMask m) => IndigoContract param st -> FilePath -> m () -- | Print the generated documentation to the standard output. printDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, MonadIO m) => IndigoContract param st -> m () -- | Save the generated documentation to the given file. saveDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, MonadIO m, MonadMask m) => IndigoContract param st -> FilePath -> m () -- | Reimplementation of some syntax sugar -- -- You need the following module pragmas to make it work smoothly: -- --
--   {-# LANGUAGE NoApplicativeDo, RebindableSyntax #-}
--   {-# OPTIONS_GHC -Wno-unused-do-bind #-}
--   
module Indigo.Rebinded -- | Defines semantics of if ... then ... else ... construction -- for Indigo where the predicate is a generic exa for which -- IsExpr exa Bool holds ifThenElse :: (IfConstraint a b, IsExpr exa Bool) => exa -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Defines numerical literals resolution for Indigo. -- -- It is implemented with an additional NumType argument that -- disambiguates the resulting type. This allows, for example, 1 -- int to be resolved to 1 :: Integer. fromInteger :: Integer -> NumType n t -> t -- | Numerical literal disambiguation value for a Natural, see -- fromInteger. nat :: NumType 'Nat Natural -- | Numerical literal disambiguation value for an Integer, see -- fromInteger. int :: NumType 'Int Integer -- | Numerical literal disambiguation value for a Mutez, see -- fromInteger. mutez :: NumType 'Mtz Mutez class IsLabel (x :: Symbol) a fromLabel :: IsLabel x a => a -- | Standard library for Indigo. -- -- As opposed to Expr and Language modules, this module contains quite -- standard things that are not present in vanilla Michelson and are not -- typically found in imperative high level languages. module Indigo.Lib -- | Indigo version of the view macro. It takes a function from -- view argument to view result and a View structure that -- typically comes from a top-level case. view_ :: forall arg r viewExpr exr. (KnownValue arg, NiceParameter r, viewExpr :~> View arg r, exr :~> r, HasSideEffects) => (Expr arg -> IndigoM exr) -> viewExpr -> IndigoM () -- | Indigo version of the void macro. void_ :: forall a b voidExpr exb. (KnownValue a, IsError (VoidResult b), NiceConstant b, voidExpr :~> Void_ a b, exb :~> b) => (Expr a -> IndigoM exb) -> voidExpr -> IndigoM () -- | Flipped version of view_ that is present due to the common -- appearance of flip view parameter $ instr construction. -- -- Semantically we "project" the given parameter inside the body of the -- View construction. project :: forall arg r viewExpr exr. (KnownValue arg, NiceParameter r, viewExpr :~> View arg r, exr :~> r, HasSideEffects) => viewExpr -> (Expr arg -> IndigoM exr) -> IndigoM () -- | Flipped version of void_ that is present due to the common -- appearance of flip void_ parameter $ instr construction. projectVoid :: forall a b voidExpr exb. (KnownValue a, IsError (VoidResult b), NiceConstant b, voidExpr :~> Void_ a b, exb :~> b) => voidExpr -> (Expr a -> IndigoM exb) -> IndigoM () -- | If the first value is greater than the second one, it returns their -- difference. If the values are equal, it returns Nothing. -- Otherwise it fails using the supplied function. subGt0 :: (ex1 :~> Natural, ex2 :~> Natural) => ex1 -> ex2 -> IndigoM () -> IndigoFunction (Maybe Natural) module Indigo -- | Append two lists, i.e., -- --
--   [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
--   [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
--   
-- -- If the first list is not finite, the result is the first list. (++) :: [a] -> [a] -> [a] infixr 5 ++ -- | The value of seq a b is bottom if a is bottom, and -- otherwise equal to b. In other words, it evaluates the first -- argument a to weak head normal form (WHNF). seq is -- usually introduced to improve performance by avoiding unneeded -- laziness. -- -- A note on evaluation order: the expression seq a b does -- not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq -- returns a value. In particular, this means that b may be -- evaluated before a. If you need to guarantee a specific order -- of evaluation, you must use the function pseq from the -- "parallel" package. seq :: a -> b -> b infixr 0 `seq` -- | O(n). filter, applied to a predicate and a list, returns -- the list of those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
-- --
--   >>> filter odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | O(min(m,n)). zip takes two lists and returns a list of -- corresponding pairs. -- --
--   zip [1, 2] ['a', 'b'] = [(1, 'a'), (2, 'b')]
--   
-- -- If one input list is short, excess elements of the longer list are -- discarded: -- --
--   zip [1] ['a', 'b'] = [(1, 'a')]
--   zip [1, 2] ['a'] = [(1, 'a')]
--   
-- -- zip is right-lazy: -- --
--   zip [] _|_ = []
--   zip _|_ [] = _|_
--   
-- -- zip is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zip :: [a] -> [b] -> [(a, b)] -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
--   f x | x < 0     = ...
--       | otherwise = ...
--   
otherwise :: Bool -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
--   f $ g $ h x  =  f (g (h x))
--   
-- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is levity-polymorphic in its result -- type, so that foo $ True where foo :: Bool -> -- Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b -- | Conditional failure of Alternative computations. Defined by -- --
--   guard True  = pure ()
--   guard False = empty
--   
-- --

Examples

-- -- Common uses of guard include conditionally signaling an error -- in an error monad and conditionally rejecting the current choice in an -- Alternative-based parser. -- -- As an example of signaling an error in the error monad Maybe, -- consider a safe division function safeDiv x y that returns -- Nothing when the denominator y is zero and -- Just (x `div` y) otherwise. For example: -- --
--   >>> safeDiv 4 0
--   Nothing
--   >>> safeDiv 4 2
--   Just 2
--   
-- -- A definition of safeDiv using guards, but not guard: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y | y /= 0    = Just (x `div` y)
--               | otherwise = Nothing
--   
-- -- A definition of safeDiv using guard and Monad -- do-notation: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y = do
--     guard (y /= 0)
--     return (x `div` y)
--   
guard :: Alternative f => Bool -> f () -- | The join function is the conventional monad join operator. It -- is used to remove one level of monadic structure, projecting its bound -- argument into the outer level. -- --

Examples

-- -- A common use of join is to run an IO computation -- returned from an STM transaction, since STM transactions -- can't perform IO directly. Recall that -- --
--   atomically :: STM a -> IO a
--   
-- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
--   atomically :: STM (IO b) -> IO (IO b)
--   join       :: IO (IO b)  -> IO b
--   
-- -- we can compose them as -- --
--   join . atomically :: STM (IO b) -> IO b
--   
-- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- -- -- --
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y >= fromEnum x = maxBound
--             | otherwise                = minBound
--   
class Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- -- enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..] with [n,n'..] = -- enumFromThen n n', a possible implementation being -- enumFromThen n n' = n : n' : worker (f x) (f x n'), -- worker s v = v : worker s (s v), x = fromEnum n' - -- fromEnum n and f n y | n > 0 = f (n - 1) (succ y) | n < -- 0 = f (n + 1) (pred y) | otherwise = y For example: -- -- enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m] with [n..m] = -- enumFromTo n m, a possible implementation being enumFromTo n -- m | n <= m = n : enumFromTo (succ n) m | otherwise = []. For -- example: -- -- enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m] with [n,n'..m] -- = enumFromThenTo n n' m, a possible implementation being -- enumFromThenTo n n' m = worker (f x) (c x) n m, x = -- fromEnum n' - fromEnum n, c x = bool (>=) ((x -- 0) f n y | n > 0 = f (n - 1) (succ y) | n < 0 = f (n + -- 1) (pred y) | otherwise = y and worker s c v m | c v m = v : -- worker s c (s v) m | otherwise = [] For example: -- -- enumFromThenTo :: Enum a => a -> a -> a -> [a] -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- The Haskell Report defines no laws for Eq. However, == -- is customarily expected to implement an equivalence relationship where -- two values comparing equal are indistinguishable by "public" -- functions, with a "public" function being one not allowing to see -- implementation details. For example, for a type representing -- non-normalised natural numbers modulo 100, a "public" function doesn't -- make the difference between 1 and 201. It is expected to have the -- following properties: -- -- -- -- Minimal complete definition: either == or /=. class Eq a -- | Trigonometric and hyperbolic functions and related functions. -- -- The Haskell Report defines no laws for Floating. However, -- (+), (*) and exp are -- customarily expected to define an exponential field and have the -- following properties: -- -- class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a infixr 8 ** -- | Fractional numbers, supporting real division. -- -- The Haskell Report defines no laws for Fractional. However, -- (+) and (*) are customarily expected -- to define a division ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- Fractional implement a field. However, all instances in -- base do. class Num a => Fractional a -- | Reciprocal fraction. recip :: Fractional a => a -> a -- | Conversion from a Rational (that is Ratio -- Integer). A floating literal stands for an application of -- fromRational to a value of type Rational, so such -- literals have type (Fractional a) => a. fromRational :: Fractional a => Rational -> a -- | Integral numbers, supporting integer division. -- -- The Haskell Report defines no laws for Integral. However, -- Integral instances are customarily expected to define a -- Euclidean domain and have the following properties for the -- div/mod and quot/rem pairs, given suitable -- Euclidean functions f and g: -- -- -- -- An example of a suitable Euclidean function, for Integer's -- instance, is abs. class (Real a, Enum a) => Integral a -- | integer division truncated toward zero quot :: Integral a => a -> a -> a -- | integer remainder, satisfying -- --
--   (x `quot` y)*y + (x `rem` y) == x
--   
rem :: Integral a => a -> a -> a -- | simultaneous quot and rem quotRem :: Integral a => a -> a -> (a, a) -- | simultaneous div and mod divMod :: Integral a => a -> a -> (a, a) -- | conversion to Integer toInteger :: Integral a => a -> Integer infixl 7 `quot` infixl 7 `rem` -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: Type -> Type) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> (a -> m b) -> m b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. (>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a infixl 1 >>= infixl 1 >> -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. class Functor (f :: Type -> Type) fmap :: Functor f => (a -> b) -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | Basic numeric class. -- -- The Haskell Report defines no laws for Num. However, -- (+) and (*) are customarily expected -- to define a ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- both Num and Ord implement an ordered ring. Indeed, in -- base only Integer and Rational do. class Num a -- | Unary negation. negate :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | The Ord class is used for totally ordered datatypes. -- -- Instances of Ord can be derived for any user-defined datatype -- whose constituent types are in Ord. The declared order of the -- constructors in the data declaration determines the ordering in -- derived Ord instances. The Ordering datatype allows a -- single comparison to determine the precise ordering of two objects. -- -- The Haskell Report defines no laws for Ord. However, -- <= is customarily expected to implement a non-strict partial -- order and have the following properties: -- -- -- -- Note that the following operator interactions are expected to hold: -- --
    --
  1. x >= y = y <= x
  2. --
  3. x < y = x <= y && x /= y
  4. --
  5. x > y = y < x
  6. --
  7. x < y = compare x y == LT
  8. --
  9. x > y = compare x y == GT
  10. --
  11. x == y = compare x y == EQ
  12. --
  13. min x y == if x <= y then x else y = True
  14. --
  15. max x y == if x >= y then x else y = True
  16. --
-- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a -- | Parsing of Strings, producing values. -- -- Derived instances of Read make the following assumptions, which -- derived instances of Show obey: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readsPrec d r =  readParen (d > app_prec)
--                            (\r -> [(Leaf m,t) |
--                                    ("Leaf",s) <- lex r,
--                                    (m,t) <- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d > up_prec)
--                            (\r -> [(u:^:v,w) |
--                                    (u,s) <- readsPrec (up_prec+1) r,
--                                    (":^:",t) <- lex s,
--                                    (v,w) <- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   
-- -- Note that right-associativity of :^: is unused. -- -- The derived instance in GHC is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" <- lexP
--                                    m <- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u <- step readPrec
--                                    Symbol ":^:" <- lexP
--                                    v <- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   
-- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
--   instance Read T where
--     readPrec     = ...
--     readListPrec = readListPrecDefault
--   
class Read a class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- -- -- -- The default definitions of the ceiling, floor, -- truncate and round functions are in terms of -- properFraction. properFraction :: (RealFrac a, Integral b) => a -> (b, a) -- | truncate x returns the integer nearest x -- between zero and x truncate :: (RealFrac a, Integral b) => a -> b -- | round x returns the nearest integer to x; the -- even integer if x is equidistant between two integers round :: (RealFrac a, Integral b) => a -> b -- | ceiling x returns the least integer not less than -- x ceiling :: (RealFrac a, Integral b) => a -> b -- | floor x returns the greatest integer not greater than -- x floor :: (RealFrac a, Integral b) => a -> b -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Show is equivalent to -- --
--   instance (Show a) => Show (Tree a) where
--   
--          showsPrec d (Leaf m) = showParen (d > app_prec) $
--               showString "Leaf " . showsPrec (app_prec+1) m
--            where app_prec = 10
--   
--          showsPrec d (u :^: v) = showParen (d > up_prec) $
--               showsPrec (up_prec+1) u .
--               showString " :^: "      .
--               showsPrec (up_prec+1) v
--            where up_prec = 5
--   
-- -- Note that right-associativity of :^: is ignored. For example, -- -- class Show a -- | The class Typeable allows a concrete representation of a type -- to be calculated. class Typeable (a :: k) -- | When a value is bound in do-notation, the pattern on the left -- hand side of <- might not match. In this case, this class -- provides a function to recover. -- -- A Monad without a MonadFail instance may only be used in -- conjunction with pattern that always match, such as newtypes, tuples, -- data types with only a single data constructor, and irrefutable -- patterns (~pat). -- -- Instances of MonadFail should satisfy the following law: -- fail s should be a left zero for >>=, -- --
--   fail s >>= f  =  fail s
--   
-- -- If your Monad is also MonadPlus, a popular definition is -- --
--   fail _ = mzero
--   
class Monad m => MonadFail (m :: Type -> Type) fail :: MonadFail m => String -> m a -- | Class for string-like datastructures; used by the overloaded string -- extension (-XOverloadedStrings in GHC). class IsString a fromString :: IsString a => String -> a -- | A functor with application, providing operations to -- -- -- -- A minimal complete definition must include implementations of -- pure and of either <*> or liftA2. If it -- defines both, then they must behave the same as their default -- definitions: -- --
--   (<*>) = liftA2 id
--   
-- --
--   liftA2 f x y = f <$> x <*> y
--   
-- -- Further, any definition must satisfy the following: -- -- -- -- The other methods have the following default definitions, which may be -- overridden with equivalent specialized implementations: -- -- -- -- As a consequence of these laws, the Functor instance for -- f will satisfy -- -- -- -- It may be useful to note that supposing -- --
--   forall x y. p (q x y) = f x . g y
--   
-- -- it follows from the above that -- --
--   liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v
--   
-- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: Type -> Type) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: Applicative f => f (a -> b) -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. (*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <*> infixl 4 *> infixl 4 <* -- | Data structures that can be folded. -- -- For example, given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Foldable Tree where
--      foldMap f Empty = mempty
--      foldMap f (Leaf x) = f x
--      foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r
--   
-- -- This is suitable even for abstract types, as the monoid is assumed to -- satisfy the monoid laws. Alternatively, one could define -- foldr: -- --
--   instance Foldable Tree where
--      foldr f z Empty = z
--      foldr f z (Leaf x) = f x z
--      foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l
--   
-- -- Foldable instances are expected to satisfy the following -- laws: -- --
--   foldr f z t = appEndo (foldMap (Endo . f) t ) z
--   
-- --
--   foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
--   
-- --
--   fold = foldMap id
--   
-- --
--   length = getSum . foldMap (Sum . const  1)
--   
-- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
--   sum = getSum . foldMap Sum
--   
-- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
--   foldMap f = fold . fmap f
--   
-- -- which implies that -- --
--   foldMap f . fmap g = foldMap (f . g)
--   
class Foldable (t :: Type -> Type) -- | Functors representing data structures that can be traversed from left -- to right. -- -- A definition of traverse must satisfy the following laws: -- -- -- -- A definition of sequenceA must satisfy the following laws: -- -- -- -- where an applicative transformation is a function -- --
--   t :: (Applicative f, Applicative g) => f a -> g a
--   
-- -- preserving the Applicative operations, i.e. -- --
--   t (pure x) = pure x
--   t (f <*> x) = t f <*> t x
--   
-- -- and the identity functor Identity and composition functors -- Compose are from Data.Functor.Identity and -- Data.Functor.Compose. -- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to Functor, e.g. given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Traversable Tree where
--      traverse f Empty = pure Empty
--      traverse f (Leaf x) = Leaf <$> f x
--      traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
--   
-- -- This is suitable even for abstract types, as the laws for -- <*> imply a form of associativity. -- -- The superclass instances should satisfy the following: -- -- class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) -- | Evaluate each action in the structure from left to right, and collect -- the results. For a version that ignores the results see -- sequenceA_. sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class Generic a -- | This class gives the integer associated with a type-level natural. -- There are instances of the class for every concrete literal: 0, 1, 2, -- etc. class KnownNat (n :: Nat) class IsLabel (x :: Symbol) a fromLabel :: IsLabel x a => a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the following: -- -- class Semigroup a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in O(1) by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. stimes :: (Semigroup a, Integral b) => b -> a -> a -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = (<>) since -- base-4.11.0.0. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. mconcat :: Monoid a => [a] -> a data Bool False :: Bool True :: Bool -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data Char -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double D# :: Double# -> Double -- | Single-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- single-precision type. data Float F# :: Float# -> Float -- | A fixed-precision integer type with at least the range [-2^29 .. -- 2^29-1]. The exact range for a given implementation can be -- determined by using minBound and maxBound from the -- Bounded class. data Int -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | Invariant: Jn# and Jp# are used iff value doesn't fit in -- S# -- -- Useful properties resulting from the invariants: -- -- data Integer -- | Type representing arbitrary-precision non-negative integers. -- --
--   >>> 2^100 :: Natural
--   1267650600228229401496703205376
--   
-- -- Operations whose result would be negative throw -- (Underflow :: ArithException), -- --
--   >>> -1 :: Natural
--   *** Exception: arithmetic underflow
--   
data Natural -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | Rational numbers, with numerator and denominator of some -- Integral type. -- -- Note that Ratio's instances inherit the deficiencies from the -- type parameter's. For example, Ratio Natural's Num -- instance has similar problems to Natural's. data Ratio a (:%) :: !a -> !a -> Ratio a -- | Arbitrary-precision rational numbers, represented as a ratio of two -- Integer values. A rational number may be constructed using the -- % operator. type Rational = Ratio Integer -- | A value of type IO a is a computation which, when -- performed, does some I/O before returning a value of type a. -- -- There is really only one way to "perform" an I/O action: bind it to -- Main.main in your program. When your program is run, the I/O -- will be performed. It isn't possible to perform I/O from an arbitrary -- function, unless that function is itself in the IO monad and -- called at some point, directly or indirectly, from Main.main. -- -- IO is a monad, so IO actions can be combined using -- either the do-notation or the >> and >>= -- operations from the Monad class. data IO a -- | A Word is an unsigned integral type, with the same size as -- Int. data Word -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 -- | A value of type Ptr a represents a pointer to an -- object, or an array of objects, which may be marshalled to or from -- Haskell values of type a. -- -- The type a will often be an instance of class Storable -- which provides the marshalling operations. However this is not -- essential, and you can provide your own operations to access the -- pointer. For example you might write small foreign functions to get or -- set the fields of a C struct. data Ptr a -- | A value of type FunPtr a is a pointer to a function -- callable from foreign code. The type a will normally be a -- foreign type, a function type with zero or more arguments where -- -- -- -- A value of type FunPtr a may be a pointer to a foreign -- function, either returned by another foreign function or imported with -- a a static address import like -- --
--   foreign import ccall "stdlib.h &free"
--     p_free :: FunPtr (Ptr a -> IO ())
--   
-- -- or a pointer to a Haskell function created using a wrapper stub -- declared to produce a FunPtr of the correct type. For example: -- --
--   type Compare = Int -> Int -> Bool
--   foreign import ccall "wrapper"
--     mkCompare :: Compare -> IO (FunPtr Compare)
--   
-- -- Calls to wrapper stubs like mkCompare allocate storage, which -- should be released with freeHaskellFunPtr when no longer -- required. -- -- To convert FunPtr values to corresponding Haskell functions, -- one can define a dynamic stub for the specific foreign type, -- e.g. -- --
--   type IntFunction = CInt -> IO ()
--   foreign import ccall "dynamic"
--     mkFun :: FunPtr IntFunction -> IntFunction
--   
data FunPtr a -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --

Examples

-- -- The type Either String Int is the type -- of values which can be either a String or an Int. The -- Left constructor can be used only on Strings, and the -- Right constructor can be used only on Ints: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> s
--   Left "foo"
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> n
--   Right 3
--   
--   >>> :type s
--   s :: Either String Int
--   
--   >>> :type n
--   n :: Either String Int
--   
-- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> fmap (*2) s
--   Left "foo"
--   
--   >>> fmap (*2) n
--   Right 6
--   
-- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
--   >>> import Data.Char ( digitToInt, isDigit )
--   
--   >>> :{
--       let parseEither :: Char -> Either String Int
--           parseEither c
--             | isDigit c = Right (digitToInt c)
--             | otherwise = Left "parse error"
--   
--   >>> :}
--   
-- -- The following should work, since both '1' and '2' -- can be parsed as Ints. -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither '1'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Right 3
--   
-- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither 'm'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Left "parse error"
--   
data Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The kind of constraints, like Show a data Constraint -- | Comparison of type-level naturals, as a function. type family CmpNat (a :: Nat) (b :: Nat) :: Ordering -- | Coercible is a two-parameter class that has instances for -- types a and b if the compiler can infer that they -- have the same representation. This class does not have regular -- instances; instead they are created on-the-fly during type-checking. -- Trying to manually declare an instance of Coercible is an -- error. -- -- Nevertheless one can pretend that the following three kinds of -- instances exist. First, as a trivial base-case: -- --
--   instance Coercible a a
--   
-- -- Furthermore, for every type constructor there is an instance that -- allows to coerce under the type constructor. For example, let -- D be a prototypical type constructor (data or -- newtype) with three type arguments, which have roles -- nominal, representational resp. phantom. -- Then there is an instance of the form -- --
--   instance Coercible b b' => Coercible (D a b c) (D a b' c')
--   
-- -- Note that the nominal type arguments are equal, the -- representational type arguments can differ, but need to have -- a Coercible instance themself, and the phantom type -- arguments can be changed arbitrarily. -- -- The third kind of instance exists for every newtype NT = MkNT -- T and comes in two variants, namely -- --
--   instance Coercible a T => Coercible a NT
--   
-- --
--   instance Coercible T b => Coercible NT b
--   
-- -- This instance is only usable if the constructor MkNT is in -- scope. -- -- If, as a library author of a type constructor like Set a, you -- want to prevent a user of your module to write coerce :: Set T -- -> Set NT, you need to set the role of Set's type -- parameter to nominal, by writing -- --
--   type role Set nominal
--   
-- -- For more details about this feature, please refer to Safe -- Coercions by Joachim Breitner, Richard A. Eisenberg, Simon Peyton -- Jones and Stephanie Weirich. class a ~R# b => Coercible (a :: k) (b :: k) -- | CallStacks are a lightweight method of obtaining a partial -- call-stack at any point in the program. -- -- A function can request its call-site with the HasCallStack -- constraint. For example, we can define -- --
--   putStrLnWithCallStack :: HasCallStack => String -> IO ()
--   
-- -- as a variant of putStrLn that will get its call-site and -- print it, along with the string given as argument. We can access the -- call-stack inside putStrLnWithCallStack with -- callStack. -- --
--   putStrLnWithCallStack :: HasCallStack => String -> IO ()
--   putStrLnWithCallStack msg = do
--     putStrLn msg
--     putStrLn (prettyCallStack callStack)
--   
-- -- Thus, if we call putStrLnWithCallStack we will get a -- formatted call-stack alongside our string. -- --
--   >>> putStrLnWithCallStack "hello"
--   hello
--   CallStack (from HasCallStack):
--     putStrLnWithCallStack, called at <interactive>:2:1 in interactive:Ghci1
--   
-- -- GHC solves HasCallStack constraints in three steps: -- --
    --
  1. If there is a CallStack in scope -- i.e. the enclosing -- function has a HasCallStack constraint -- GHC will append the -- new call-site to the existing CallStack.
  2. --
  3. If there is no CallStack in scope -- e.g. in the GHCi -- session above -- and the enclosing definition does not have an -- explicit type signature, GHC will infer a HasCallStack -- constraint for the enclosing definition (subject to the monomorphism -- restriction).
  4. --
  5. If there is no CallStack in scope and the enclosing -- definition has an explicit type signature, GHC will solve the -- HasCallStack constraint for the singleton CallStack -- containing just the current call-site.
  6. --
-- -- CallStacks do not interact with the RTS and do not require -- compilation with -prof. On the other hand, as they are built -- up explicitly via the HasCallStack constraints, they will -- generally not contain as much information as the simulated call-stacks -- maintained by the RTS. -- -- A CallStack is a [(String, SrcLoc)]. The -- String is the name of function that was called, the -- SrcLoc is the call-site. The list is ordered with the most -- recently called function at the head. -- -- NOTE: The intrepid user may notice that HasCallStack is just an -- alias for an implicit parameter ?callStack :: CallStack. This -- is an implementation detail and should not be considered part -- of the CallStack API, we may decide to change the -- implementation in the future. data CallStack -- | Haskell defines operations to read and write characters from and to -- files, represented by values of type Handle. Each value of -- this type is a handle: a record used by the Haskell run-time -- system to manage I/O with file system objects. A handle has at -- least the following properties: -- -- -- -- Most handles will also have a current I/O position indicating where -- the next input or output operation will occur. A handle is -- readable if it manages only input or both input and output; -- likewise, it is writable if it manages only output or both -- input and output. A handle is open when first allocated. Once -- it is closed it can no longer be used for either input or output, -- though an implementation cannot re-use its storage while references -- remain to it. Handles are in the Show and Eq classes. -- The string produced by showing a handle is system dependent; it should -- include enough information to identify the handle for debugging. A -- handle is equal according to == only to itself; no attempt is -- made to compare the internal state of different handles for equality. data Handle -- | Right-to-left composition of functors. The composition of applicative -- functors is always applicative, but the composition of monads is not -- always a monad. newtype Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) Compose :: f (g a) -> Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) [getCompose] :: Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) -> f (g a) infixr 9 `Compose` infixr 9 `Compose` -- | If Void is uninhabited then any Functor that holds only -- values of type Void is holding no values. vacuous :: Functor f => f Void -> f a -- | Since Void values logically don't exist, this witnesses the -- logical reasoning tool of "ex falso quodlibet". -- --
--   >>> let x :: Either Void Int; x = Right 5
--   
--   >>> :{
--   case x of
--       Right r -> r
--       Left l  -> absurd l
--   :}
--   5
--   
absurd :: Void -> a -- | Uninhabited data type data Void -- | Repeat a value n times. -- --
--   mtimesDefault n a = a <> a <> ... <> a  -- using <> (n-1) times
--   
-- -- Implemented using stimes and mempty. -- -- This is a suitable definition for an mtimes member of -- Monoid. mtimesDefault :: (Integral b, Monoid a) => b -> a -> a -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | Provide a Semigroup for an arbitrary Monoid. -- -- NOTE: This is not needed anymore since Semigroup became -- a superclass of Monoid in base-4.11 and this newtype be -- deprecated at some point in the future. data WrappedMonoid m -- | Option is effectively Maybe with a better instance of -- Monoid, built off of an underlying Semigroup instead of -- an underlying Monoid. -- -- Ideally, this type would not exist at all and we would just fix the -- Monoid instance of Maybe. -- -- In GHC 8.4 and higher, the Monoid instance for Maybe has -- been corrected to lift a Semigroup instance instead of a -- Monoid instance. Consequently, this type is no longer useful. -- It will be marked deprecated in GHC 8.8 and removed in GHC 8.10. newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | The sortWith function sorts a list of elements using the user -- supplied function to project something out of each element sortWith :: Ord b => (a -> b) -> [a] -> [a] -- | A bifunctor is a type constructor that takes two type arguments and is -- a functor in both arguments. That is, unlike with -- Functor, a type constructor such as Either does not need -- to be partially applied for a Bifunctor instance, and the -- methods in this class permit mapping functions over the Left -- value or the Right value, or both at the same time. -- -- Formally, the class Bifunctor represents a bifunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where both the first and second -- arguments are covariant. -- -- You can define a Bifunctor by either defining bimap or -- by defining both first and second. -- -- If you supply bimap, you should ensure that: -- --
--   bimap id idid
--   
-- -- If you supply first and second, ensure: -- --
--   first idid
--   second idid
--   
-- -- If you supply both, you should also ensure: -- --
--   bimap f g ≡ first f . second g
--   
-- -- These ensure by parametricity: -- --
--   bimap  (f . g) (h . i) ≡ bimap f h . bimap g i
--   first  (f . g) ≡ first  f . first  g
--   second (f . g) ≡ second f . second g
--   
class Bifunctor (p :: Type -> Type -> Type) -- | Map over both arguments at the same time. -- --
--   bimap f g ≡ first f . second g
--   
-- --

Examples

-- --
--   >>> bimap toUpper (+1) ('j', 3)
--   ('J',4)
--   
-- --
--   >>> bimap toUpper (+1) (Left 'j')
--   Left 'J'
--   
-- --
--   >>> bimap toUpper (+1) (Right 3)
--   Right 4
--   
bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d -- | Map covariantly over the first argument. -- --
--   first f ≡ bimap f id
--   
-- --

Examples

-- --
--   >>> first toUpper ('j', 3)
--   ('J',3)
--   
-- --
--   >>> first toUpper (Left 'j')
--   Left 'J'
--   
first :: Bifunctor p => (a -> b) -> p a c -> p b c -- | Map covariantly over the second argument. -- --
--   secondbimap id
--   
-- --

Examples

-- --
--   >>> second (+1) ('j', 3)
--   ('j',4)
--   
-- --
--   >>> second (+1) (Right 3)
--   Right 4
--   
second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | Extract everything except the last element of the stream. init :: NonEmpty a -> [a] -- | Extract the last element of the stream. last :: NonEmpty a -> a -- | Extract the possibly-empty tail of the stream. tail :: NonEmpty a -> [a] -- | Extract the first element of the stream. head :: NonEmpty a -> a -- | nonEmpty efficiently turns a normal list into a NonEmpty -- stream, producing Nothing if the input is empty. nonEmpty :: [a] -> Maybe (NonEmpty a) -- | Get a string representation of the current execution stack state. showStackTrace :: IO (Maybe String) -- | Get a trace of the current execution stack state. -- -- Returns Nothing if stack trace support isn't available on -- host machine. getStackTrace :: IO (Maybe [Location]) -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | Direct MonadPlus equivalent of filter. -- --

Examples

-- -- The filter function is just mfilter specialized to the -- list monad: -- --
--   filter = ( mfilter :: (a -> Bool) -> [a] -> [a] )
--   
-- -- An example using mfilter with the Maybe monad: -- --
--   >>> mfilter odd (Just 1)
--   Just 1
--   >>> mfilter odd (Just 2)
--   Nothing
--   
mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | The foldM function is analogous to foldl, except that -- its result is encapsulated in a monad. Note that foldM works -- from left-to-right over the list arguments. This could be an issue -- where (>>) and the `folded function' are not -- commutative. -- --
--   foldM f a1 [x1, x2, ..., xm]
--   
--   ==
--   
--   do
--     a2 <- f a1 x1
--     a3 <- f a2 x2
--     ...
--     f am xm
--   
-- -- If right-to-left evaluation is required, the input list should be -- reversed. -- -- Note: foldM is the same as foldlM foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | The mapAndUnzipM function maps its first argument over a list, -- returning the result as a pair of lists. This function is mainly used -- with complicated data structures or a state monad. mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c]) -- | Repeat an action indefinitely. -- --

Examples

-- -- A common use of forever is to process input from network -- sockets, Handles, and channels (e.g. MVar and -- Chan). -- -- For example, here is how we might implement an echo server, -- using forever both to listen for client connections on a -- network socket and to echo client input on client connection handles: -- --
--   echoServer :: Socket -> IO ()
--   echoServer socket = forever $ do
--     client <- accept socket
--     forkFinally (echo client) (\_ -> hClose client)
--     where
--       echo :: Handle -> IO ()
--       echo client = forever $
--         hGetLine client >>= hPutStrLn client
--   
forever :: Applicative f => f a -> f b -- | Right-to-left composition of Kleisli arrows. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
--   (.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
--   (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
--   
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 <=< -- | Left-to-right composition of Kleisli arrows. (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element of -- a structure, passing an accumulating parameter from left to right, and -- returning a final value of this accumulator together with the new -- structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | One or none. optional :: Alternative f => f a -> f (Maybe a) -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | Fanout: send the input to both argument arrows and combine their -- output. -- -- The default definition may be overridden with a more efficient version -- if desired. (&&&) :: Arrow a => a b c -> a b c' -> a b (c, c') infixr 3 &&& -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | A handle managing output to the Haskell program's standard error -- channel. stderr :: Handle -- | A handle managing input from the Haskell program's standard input -- channel. stdin :: Handle -- | Perform some computation without adding new entries to the -- CallStack. withFrozenCallStack :: HasCallStack => (HasCallStack => a) -> a -- | Return the current CallStack. -- -- Does *not* include the call-site of callStack. callStack :: HasCallStack => CallStack -- | Write the supplied value into a TVar. writeTVar :: TVar a -> a -> STM () -- | Return the current value stored in a TVar. readTVar :: TVar a -> STM a -- | Create a new TVar holding a value supplied newTVar :: a -> STM (TVar a) -- | A monad supporting atomic memory transactions. data STM a -- | Shared memory locations that support atomic memory transactions. data TVar a -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | A mutable variable in the IO monad data IORef a -- | File and directory names are values of type String, whose -- precise meaning is operating system dependent. Files can be opened, -- yielding a handle which can then be used to operate on the contents of -- that file. type FilePath = String -- | Pretty print a CallStack. prettyCallStack :: CallStack -> String -- | Pretty print a SrcLoc. prettySrcLoc :: SrcLoc -> String -- | Any type that you wish to throw or catch as an exception must be an -- instance of the Exception class. The simplest case is a new -- exception type directly below the root: -- --
--   data MyException = ThisException | ThatException
--       deriving Show
--   
--   instance Exception MyException
--   
-- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
--   *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
--   Caught ThisException
--   
-- -- In more complicated examples, you may wish to define a whole hierarchy -- of exceptions: -- --
--   ---------------------------------------------------------------------
--   -- Make the root exception type for all the exceptions in a compiler
--   
--   data SomeCompilerException = forall e . Exception e => SomeCompilerException e
--   
--   instance Show SomeCompilerException where
--       show (SomeCompilerException e) = show e
--   
--   instance Exception SomeCompilerException
--   
--   compilerExceptionToException :: Exception e => e -> SomeException
--   compilerExceptionToException = toException . SomeCompilerException
--   
--   compilerExceptionFromException :: Exception e => SomeException -> Maybe e
--   compilerExceptionFromException x = do
--       SomeCompilerException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make a subhierarchy for exceptions in the frontend of the compiler
--   
--   data SomeFrontendException = forall e . Exception e => SomeFrontendException e
--   
--   instance Show SomeFrontendException where
--       show (SomeFrontendException e) = show e
--   
--   instance Exception SomeFrontendException where
--       toException = compilerExceptionToException
--       fromException = compilerExceptionFromException
--   
--   frontendExceptionToException :: Exception e => e -> SomeException
--   frontendExceptionToException = toException . SomeFrontendException
--   
--   frontendExceptionFromException :: Exception e => SomeException -> Maybe e
--   frontendExceptionFromException x = do
--       SomeFrontendException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make an exception type for a particular frontend compiler exception
--   
--   data MismatchedParentheses = MismatchedParentheses
--       deriving Show
--   
--   instance Exception MismatchedParentheses where
--       toException   = frontendExceptionToException
--       fromException = frontendExceptionFromException
--   
-- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
--   *** Exception: MismatchedParentheses
--   
class (Typeable e, Show e) => Exception e toException :: Exception e => e -> SomeException fromException :: Exception e => SomeException -> Maybe e -- | Render this exception value in a human-friendly manner. -- -- Default implementation: show. displayException :: Exception e => e -> String -- | The Const functor. newtype Const a (b :: k) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | The least element of a non-empty structure with respect to the given -- comparison function. minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | Maybe monoid returning the leftmost non-Nothing value. -- -- First a is isomorphic to Alt Maybe -- a, but precedes it historically. -- --
--   >>> getFirst (First (Just "hello") <> First Nothing <> First (Just "world"))
--   Just "hello"
--   
-- -- Use of this type is discouraged. Note the following equivalence: -- --
--   Data.Monoid.First x === Maybe (Data.Semigroup.First x)
--   
-- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
--   >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world"))
--   Just "world"
--   
-- -- Use of this type is discouraged. Note the following equivalence: -- --
--   Data.Monoid.Last x === Maybe (Data.Semigroup.Last x)
--   
-- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n). stimesIdempotent :: Integral b => b -> a -> a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
--   >>> getDual (mappend (Dual "Hello") (Dual "World"))
--   "WorldHello"
--   
newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | The monoid of endomorphisms under composition. -- --
--   >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--   
--   >>> appEndo computation "Haskell"
--   "Hello, Haskell!"
--   
newtype Endo a Endo :: (a -> a) -> Endo a [appEndo] :: Endo a -> a -> a -- | Boolean monoid under conjunction (&&). -- --
--   >>> getAll (All True <> mempty <> All False)
--   False
--   
-- --
--   >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8]))
--   False
--   
newtype All All :: Bool -> All [getAll] :: All -> Bool -- | Boolean monoid under disjunction (||). -- --
--   >>> getAny (Any True <> mempty <> Any False)
--   True
--   
-- --
--   >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8]))
--   True
--   
newtype Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | Monoid under addition. -- --
--   >>> getSum (Sum 1 <> Sum 2 <> mempty)
--   3
--   
newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
--   >>> getProduct (Product 3 <> Product 4 <> mempty)
--   12
--   
newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | Monoid under <|>. newtype Alt (f :: k -> Type) (a :: k) Alt :: f a -> Alt (f :: k -> Type) (a :: k) [getAlt] :: Alt (f :: k -> Type) (a :: k) -> f a -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: forall (n :: Nat) proxy. KnownNat n => proxy n -> Natural -- | This type represents unknown type-level natural numbers. data SomeNat SomeNat :: Proxy n -> SomeNat -- | The unfoldr function is a `dual' to foldr: while -- foldr reduces a list to a summary value, unfoldr builds -- a list from a seed value. The function takes the element and returns -- Nothing if it is done producing the list or returns Just -- (a,b), in which case, a is a prepended to the list -- and b is used as the next element in a recursive call. For -- example, -- --
--   iterate f == unfoldr (\x -> Just (x, f x))
--   
-- -- In some cases, unfoldr can undo a foldr operation: -- --
--   unfoldr f' (foldr f z xs) == xs
--   
-- -- if the following holds: -- --
--   f' (f x y) = Just (x,y)
--   f' z       = Nothing
--   
-- -- A simple use of unfoldr: -- --
--   >>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
--   [10,9,8,7,6,5,4,3,2,1]
--   
unfoldr :: (b -> Maybe (a, b)) -> b -> [a] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
--   >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | The sortBy function is the non-overloaded version of -- sort. -- --
--   >>> sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortBy :: (a -> a -> Ordering) -> [a] -> [a] -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
--   >>> sort [1,6,4,3,2,5]
--   [1,2,3,4,5,6]
--   
sort :: Ord a => [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
--   >>> permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   
permutations :: [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
--   >>> subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   
subsequences :: [a] -> [[a]] -- | O(n). The tails function returns all final segments of -- the argument, longest first. For example, -- --
--   >>> tails "abc"
--   ["abc","bc","c",""]
--   
-- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: [a] -> [[a]] -- | The inits function returns all initial segments of the -- argument, shortest first. For example, -- --
--   >>> inits "abc"
--   ["","a","ab","abc"]
--   
-- -- Note that inits has the following strictness property: -- inits (xs ++ _|_) = inits xs ++ _|_ -- -- In particular, inits _|_ = [] : _|_ inits :: [a] -> [[a]] -- | The group function takes a list and returns a list of lists -- such that the concatenation of the result is equal to the argument. -- Moreover, each sublist in the result contains only equal elements. For -- example, -- --
--   >>> group "Mississippi"
--   ["M","i","ss","i","ss","i","pp","i"]
--   
-- -- It is a special case of groupBy, which allows the programmer to -- supply their own equality test. group :: Eq a => [a] -> [[a]] -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericDrop function is an overloaded version of -- drop, which accepts any Integral value as the number of -- elements to drop. genericDrop :: Integral i => i -> [a] -> [a] -- | The genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | O(n). The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The transpose function transposes the rows and columns of its -- argument. For example, -- --
--   >>> transpose [[1,2,3],[4,5,6]]
--   [[1,4],[2,5],[3,6]]
--   
-- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
--   >>> transpose [[10,11],[20],[],[30,31,32]]
--   [[10,20,30],[11,31],[32]]
--   
transpose :: [[a]] -> [[a]] -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
--   >>> intercalate ", " ["Lorem", "ipsum", "dolor"]
--   "Lorem, ipsum, dolor"
--   
intercalate :: [a] -> [[a]] -> [a] -- | O(n). The intersperse function takes an element and a -- list and `intersperses' that element between the elements of the list. -- For example, -- --
--   >>> intersperse ',' "abcde"
--   "a,b,c,d,e"
--   
intersperse :: a -> [a] -> [a] -- | O(min(m,n)). The isPrefixOf function takes two lists and -- returns True iff the first list is a prefix of the second. -- --
--   >>> "Hello" `isPrefixOf` "Hello World!"
--   True
--   
-- --
--   >>> "Hello" `isPrefixOf` "Wello Horld!"
--   False
--   
isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. -- --
--   >>> readMaybe "123" :: Maybe Int
--   Just 123
--   
-- --
--   >>> readMaybe "hello" :: Maybe Int
--   Nothing
--   
readMaybe :: Read a => String -> Maybe a -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | Return True if the given value is a Right-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> isRight (Left "foo")
--   False
--   
--   >>> isRight (Right 3)
--   True
--   
-- -- Assuming a Left value signifies some sort of error, we can use -- isRight to write a very simple reporting function that only -- outputs "SUCCESS" when a computation has succeeded. -- -- This example shows how isRight might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
--   >>> import Control.Monad ( when )
--   
--   >>> let report e = when (isRight e) $ putStrLn "SUCCESS"
--   
--   >>> report (Left "parse error")
--   
--   >>> report (Right 1)
--   SUCCESS
--   
isRight :: Either a b -> Bool -- | Return True if the given value is a Left-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> isLeft (Left "foo")
--   True
--   
--   >>> isLeft (Right 3)
--   False
--   
-- -- Assuming a Left value signifies some sort of error, we can use -- isLeft to write a very simple error-reporting function that -- does absolutely nothing in the case of success, and outputs "ERROR" if -- any error occurred. -- -- This example shows how isLeft might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
--   >>> import Control.Monad ( when )
--   
--   >>> let report e = when (isLeft e) $ putStrLn "ERROR"
--   
--   >>> report (Right 1)
--   
--   >>> report (Left "parse error")
--   ERROR
--   
isLeft :: Either a b -> Bool -- | Partitions a list of Either into two lists. All the Left -- elements are extracted, in order, to the first component of the -- output. Similarly the Right elements are extracted to the -- second component of the output. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list
--   (["foo","bar","baz"],[3,7])
--   
-- -- The pair returned by partitionEithers x should be the -- same pair as (lefts x, rights x): -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list == (lefts list, rights list)
--   True
--   
partitionEithers :: [Either a b] -> ([a], [b]) -- | Extracts from a list of Either all the Right elements. -- All the Right elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> rights list
--   [3,7]
--   
rights :: [Either a b] -> [b] -- | Extracts from a list of Either all the Left elements. -- All the Left elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> lefts list
--   ["foo","bar","baz"]
--   
lefts :: [Either a b] -> [a] -- | Case analysis for the Either type. If the value is -- Left a, apply the first function to a; if it -- is Right b, apply the second function to b. -- --

Examples

-- -- We create two values of type Either String -- Int, one using the Left constructor and another -- using the Right constructor. Then we apply "either" the -- length function (if we have a String) or the "times-two" -- function (if we have an Int): -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> either length (*2) s
--   3
--   
--   >>> either length (*2) n
--   6
--   
either :: (a -> c) -> (b -> c) -> Either a b -> c -- |
--   comparing p x y = compare (p x) (p y)
--   
-- -- Useful combinator for use in conjunction with the xxxBy -- family of functions from Data.List, for example: -- --
--   ... sortBy (comparing fst) ...
--   
comparing :: Ord a => (b -> a) -> b -> b -> Ordering -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). If a has -- an Ord instance associated with it then comparing two -- values thus wrapped will give you the opposite of their normal sort -- order. This is particularly useful when sorting in generalised list -- comprehensions, as in: then sortWith by Down x newtype Down a Down :: a -> Down a -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the undefined :: a idiom. -- --
--   >>> Proxy :: Proxy (Void, Int -> Int)
--   Proxy
--   
-- -- Proxy can even hold types of higher kinds, -- --
--   >>> Proxy :: Proxy Either
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy Functor
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy complicatedStructure
--   Proxy
--   
data Proxy (t :: k) Proxy :: Proxy (t :: k) -- | See openFile data IOMode ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Swap bytes in Word16. byteSwap16 :: Word16 -> Word16 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFrom :: (Integral a, Bounded a) => a -> [a] gcdWord' :: Word -> Word -> Word gcdInt' :: Int -> Int -> Int -- | lcm x y is the smallest positive integer that both -- x and y divide. lcm :: Integral a => a -> a -> a -- | gcd x y is the non-negative factor of both x -- and y of which every common factor of x and -- y is also a factor; for example gcd 4 2 = 2, -- gcd (-4) 6 = 2, gcd 0 4 = 4. -- gcd 0 0 = 0. (That is, the common divisor -- that is "greatest" in the divisibility preordering.) -- -- Note: Since for signed fixed-width integer types, abs -- minBound < 0, the result may be negative if one of the -- arguments is minBound (and necessarily is if the other -- is 0 or minBound) for such types. gcd :: Integral a => a -> a -> a (^^%^^) :: Integral a => Rational -> a -> Rational (^%^) :: Integral a => Rational -> a -> Rational -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ odd :: Integral a => a -> Bool even :: Integral a => a -> Bool numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThen :: Fractional a => a -> a -> [a] numericEnumFrom :: Fractional a => a -> [a] -- | Extract the denominator of the ratio in reduced form: the numerator -- and denominator have no common factor and the denominator is positive. denominator :: Ratio a -> a -- | Extract the numerator of the ratio in reduced form: the numerator and -- denominator have no common factor and the denominator is positive. numerator :: Ratio a -> a -- | reduce is a subsidiary function used only in this module. It -- normalises a ratio by dividing both numerator and denominator by their -- greatest common divisor. reduce :: Integral a => a -> a -> Ratio a notANumber :: Rational infinity :: Rational ratioPrec1 :: Int ratioPrec :: Int underflowError :: a overflowError :: a ratioZeroDenominatorError :: a divZeroError :: a boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. unzip3 :: [(a, b, c)] -> ([a], [b], [c]) -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. unzip :: [(a, b)] -> ([a], [b]) -- | O(min(m,n)). zipWith generalises zip by zipping -- with the function given as the first argument, instead of a tupling -- function. For example, zipWith (+) is applied to two -- lists to produce the list of corresponding sums: -- --
--   >>> zipWith (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   zipWith f [] _|_ = []
--   
-- -- zipWith is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. It is capable of list fusion, but it is restricted to -- its first list argument and its resulting list. zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: [a] -> [a] -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
--   break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
--   break (< 9) [1,2,3] == ([],[1,2,3])
--   break (> 9) [1,2,3] == ([1,2,3],[])
--   
-- -- break p is equivalent to span (not . -- p). break :: (a -> Bool) -> [a] -> ([a], [a]) -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
--   splitAt 6 "Hello World!" == ("Hello ","World!")
--   splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
--   splitAt 1 [1,2,3] == ([1],[2,3])
--   splitAt 3 [1,2,3] == ([1,2,3],[])
--   splitAt 4 [1,2,3] == ([1,2,3],[])
--   splitAt 0 [1,2,3] == ([],[1,2,3])
--   splitAt (-1) [1,2,3] == ([],[1,2,3])
--   
-- -- It is equivalent to (take n xs, drop n xs) when -- n is not _|_ (splitAt _|_ xs = _|_). -- splitAt is an instance of the more general -- genericSplitAt, in which n may be of any integral -- type. splitAt :: Int -> [a] -> ([a], [a]) -- | drop n xs returns the suffix of xs after the -- first n elements, or [] if n > length -- xs: -- --
--   drop 6 "Hello World!" == "World!"
--   drop 3 [1,2,3,4,5] == [4,5]
--   drop 3 [1,2] == []
--   drop 3 [] == []
--   drop (-1) [1,2] == [1,2]
--   drop 0 [1,2] == [1,2]
--   
-- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: Int -> [a] -> [a] -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n > length xs: -- --
--   take 5 "Hello World!" == "Hello"
--   take 3 [1,2,3,4,5] == [1,2,3]
--   take 3 [1,2] == [1,2]
--   take 3 [] == []
--   take (-1) [1,2] == []
--   take 0 [1,2] == []
--   
-- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs: -- --
--   dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
--   dropWhile (< 9) [1,2,3] == []
--   dropWhile (< 0) [1,2,3] == [1,2,3]
--   
dropWhile :: (a -> Bool) -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p: -- --
--   takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
--   takeWhile (< 9) [1,2,3] == [1,2,3]
--   takeWhile (< 0) [1,2,3] == []
--   
takeWhile :: (a -> Bool) -> [a] -> [a] -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. cycle :: [a] -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. replicate :: Int -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. repeat :: a -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
--   iterate f x == [x, f x, f (f x), ...]
--   
-- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See -- iterate' for a strict variant of this function. iterate :: (a -> a) -> a -> [a] -- | O(n). scanr is the right-to-left dual of scanl. -- Note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
scanr :: (a -> b -> b) -> b -> [a] -> [b] -- | O(n). scanl is similar to foldl, but returns a -- list of successive reduced values from the left: -- --
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   
-- -- Note that -- --
--   last (scanl f z xs) == foldl f z xs.
--   
scanl :: (b -> a -> b) -> b -> [a] -> [b] -- | The mapMaybe function is a version of map which can -- throw out elements. In particular, the functional argument returns -- something of type Maybe b. If this is Nothing, -- no element is added on to the result list. If it is Just -- b, then b is included in the result list. -- --

Examples

-- -- Using mapMaybe f x is a shortcut for -- catMaybes $ map f x in most cases: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> let readMaybeInt = readMaybe :: String -> Maybe Int
--   
--   >>> mapMaybe readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
--   >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
-- -- If we map the Just constructor, the entire list should be -- returned: -- --
--   >>> mapMaybe Just [1,2,3]
--   [1,2,3]
--   
mapMaybe :: (a -> Maybe b) -> [a] -> [b] -- | The catMaybes function takes a list of Maybes and -- returns a list of all the Just values. -- --

Examples

-- -- Basic usage: -- --
--   >>> catMaybes [Just 1, Nothing, Just 3]
--   [1,3]
--   
-- -- When constructing a list of Maybe values, catMaybes can -- be used to return all of the "success" results (if the list is the -- result of a map, then mapMaybe would be more -- appropriate): -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [Just 1,Nothing,Just 3]
--   
--   >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [1,3]
--   
catMaybes :: [Maybe a] -> [a] -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --

Examples

-- -- Basic usage: -- --
--   >>> listToMaybe []
--   Nothing
--   
-- --
--   >>> listToMaybe [9]
--   Just 9
--   
-- --
--   >>> listToMaybe [1,2,3]
--   Just 1
--   
-- -- Composing maybeToList with listToMaybe should be the -- identity on singleton/empty lists: -- --
--   >>> maybeToList $ listToMaybe [5]
--   [5]
--   
--   >>> maybeToList $ listToMaybe []
--   []
--   
-- -- But not on lists with more than one element: -- --
--   >>> maybeToList $ listToMaybe [1,2,3]
--   [1]
--   
listToMaybe :: [a] -> Maybe a -- | The maybeToList function returns an empty list when given -- Nothing or a singleton list when given Just. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: Maybe a -> [a] -- | The fromMaybe function takes a default value and and -- Maybe value. If the Maybe is Nothing, it returns -- the default values; otherwise, it returns the value contained in the -- Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: a -> Maybe a -> a -- | The isNothing function returns True iff its argument is -- Nothing. -- --

Examples

-- -- Basic usage: -- --
--   >>> isNothing (Just 3)
--   False
--   
-- --
--   >>> isNothing (Just ())
--   False
--   
-- --
--   >>> isNothing Nothing
--   True
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isNothing (Just Nothing)
--   False
--   
isNothing :: Maybe a -> Bool -- | The isJust function returns True iff its argument is of -- the form Just _. -- --

Examples

-- -- Basic usage: -- --
--   >>> isJust (Just 3)
--   True
--   
-- --
--   >>> isJust (Just ())
--   True
--   
-- --
--   >>> isJust Nothing
--   False
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isJust (Just Nothing)
--   True
--   
isJust :: Maybe a -> Bool -- | The maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybe False odd (Just 3)
--   True
--   
-- --
--   >>> maybe False odd Nothing
--   False
--   
-- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> maybe 0 (*2) (readMaybe "5")
--   10
--   
--   >>> maybe 0 (*2) (readMaybe "")
--   0
--   
-- -- Apply show to a Maybe Int. If we have Just n, -- we want to show the underlying Int n. But if we have -- Nothing, we return the empty string instead of (for example) -- "Nothing": -- --
--   >>> maybe "" show (Just 5)
--   "5"
--   
--   >>> maybe "" show Nothing
--   ""
--   
maybe :: b -> (a -> b) -> Maybe a -> b -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --

Examples

-- -- Basic usage: -- --
--   >>> bool "foo" "bar" True
--   "bar"
--   
--   >>> bool "foo" "bar" False
--   "foo"
--   
-- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
--   >>> let p = True; x = "bar"; y = "foo"
--   
--   >>> bool x y p == if p then y else x
--   True
--   
--   >>> let p = False
--   
--   >>> bool x y p == if p then y else x
--   True
--   
bool :: a -> a -> Bool -> a -- | & is a reverse application operator. This provides -- notational convenience. Its precedence is one higher than that of the -- forward application operator $, which allows & to be -- nested in $. -- --
--   >>> 5 & (+1) & show
--   "6"
--   
(&) :: a -> (a -> b) -> b infixl 1 & -- | on b u x y runs the binary function b -- on the results of applying unary function u to two -- arguments x and y. From the opposite perspective, it -- transforms two inputs and combines the outputs. -- --
--   ((+) `on` f) x y = f x + f y
--   
-- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- -- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 `on` -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix argument, hence the recursion is reintroduced. fix :: (a -> a) -> a -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --

Examples

-- -- Replace the contents of a Maybe Int with unit: -- --
--   >>> void Nothing
--   Nothing
--   
--   >>> void (Just 3)
--   Just ()
--   
-- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int (): -- --
--   >>> void (Left 8675309)
--   Left 8675309
--   
--   >>> void (Right 8675309)
--   Right ()
--   
-- -- Replace every element of a list with unit: -- --
--   >>> void [1,2,3]
--   [(),(),()]
--   
-- -- Replace the second element of a pair with unit: -- --
--   >>> void (1,2)
--   (1,())
--   
-- -- Discard the result of an IO action: -- --
--   >>> mapM print [1,2]
--   1
--   2
--   [(),()]
--   
--   >>> void $ mapM print [1,2]
--   1
--   2
--   
void :: Functor f => f a -> f () -- | Flipped version of <$. -- --

Examples

-- -- Replace the contents of a Maybe Int with a -- constant String: -- --
--   >>> Nothing $> "foo"
--   Nothing
--   
--   >>> Just 90210 $> "foo"
--   Just "foo"
--   
-- -- Replace the contents of an Either Int -- Int with a constant String, resulting in an -- Either Int String: -- --
--   >>> Left 8675309 $> "foo"
--   Left 8675309
--   
--   >>> Right 8675309 $> "foo"
--   Right "foo"
--   
-- -- Replace each element of a list with a constant String: -- --
--   >>> [1,2,3] $> "foo"
--   ["foo","foo","foo"]
--   
-- -- Replace the second element of a pair with a constant String: -- --
--   >>> (1,2) $> "foo"
--   (1,"foo")
--   
($>) :: Functor f => f a -> b -> f b infixl 4 $> -- | Flipped version of <$>. -- --
--   (<&>) = flip fmap
--   
-- --

Examples

-- -- Apply (+1) to a list, a Just and a Right: -- --
--   >>> Just 2 <&> (+1)
--   Just 3
--   
-- --
--   >>> [1,2,3] <&> (+1)
--   [2,3,4]
--   
-- --
--   >>> Right 3 <&> (+1)
--   Right 4
--   
(<&>) :: Functor f => f a -> (a -> b) -> f b infixl 1 <&> -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
--    ($)  ::              (a -> b) ->   a ->   b
--   (<$>) :: Functor f => (a -> b) -> f a -> f b
--   
-- -- Whereas $ is function application, <$> is function -- application lifted over a Functor. -- --

Examples

-- -- Convert from a Maybe Int to a Maybe -- String using show: -- --
--   >>> show <$> Nothing
--   Nothing
--   
--   >>> show <$> Just 3
--   Just "3"
--   
-- -- Convert from an Either Int Int to an -- Either Int String using show: -- --
--   >>> show <$> Left 17
--   Left 17
--   
--   >>> show <$> Right 17
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> (*2) <$> [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> even <$> (2,2)
--   (2,True)
--   
(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | Swap the components of a pair. swap :: (a, b) -> (b, a) -- | uncurry converts a curried function to a function on pairs. -- --

Examples

-- --
--   >>> uncurry (+) (1,2)
--   3
--   
-- --
--   >>> uncurry ($) (show, 1)
--   "1"
--   
-- --
--   >>> map (uncurry max) [(1,2), (3,4), (6,8)]
--   [2,4,8]
--   
uncurry :: (a -> b -> c) -> (a, b) -> c -- | curry converts an uncurried function to a curried function. -- --

Examples

-- --
--   >>> curry fst 1 2
--   1
--   
curry :: ((a, b) -> c) -> a -> b -> c -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a box, which may be empty or full. data MVar a -- | the same as flip (-). -- -- Because - is treated specially in the Haskell grammar, -- (- e) is not a section, but an application of -- prefix negation. However, (subtract -- exp) is equivalent to the disallowed section. subtract :: Num a => a -> a -> a -- | Returns a [String] representing the current call stack. This -- can be useful for debugging. -- -- The implementation uses the call-stack simulation maintained by the -- profiler, so it only works if the program was compiled with -- -prof and contains suitable SCC annotations (e.g. by using -- -fprof-auto). Otherwise, the list returned is likely to be -- empty or uninformative. currentCallStack :: IO [String] -- | asTypeOf is a type-restricted version of const. It is -- usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- second. asTypeOf :: a -> a -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c -- | Function composition. (.) :: (b -> c) -> (a -> b) -> a -> c infixr 9 . -- | const x is a unary function which evaluates to x for -- all inputs. -- --
--   >>> const 42 "hello"
--   42
--   
-- --
--   >>> map (const 42) [0..3]
--   [42,42,42,42]
--   
const :: a -> b -> a -- | Identity function. -- --
--   id x = x
--   
id :: a -> a maxInt :: Int minInt :: Int -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
--   return f `ap` x1 `ap` ... `ap` xn
--   
-- -- is equivalent to -- --
--   liftMn f x1 x2 ... xn
--   
ap :: Monad m => m (a -> b) -> m a -> m b -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
--   liftM2 (+) [0,1] [0,2] = [0,2,1,3]
--   liftM2 (+) (Just 1) Nothing = Nothing
--   
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | Lift a ternary function to actions. liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | Zero or more. many :: Alternative f => f a -> f [a] infixl 3 <|> -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) -- | The identity of mplus. It should also satisfy the equations -- --
--   mzero >>= f  =  mzero
--   v >> mzero   =  mzero
--   
-- -- The default definition is -- --
--   mzero = empty
--   
mzero :: MonadPlus m => m a -- | An associative operation. The default definition is -- --
--   mplus = (<|>)
--   
mplus :: MonadPlus m => m a -> m a -> m a -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | Extract a list of call-sites from the CallStack. -- -- The list is ordered by most recent call. getCallStack :: CallStack -> [([Char], SrcLoc)] -- | Request a CallStack. -- -- NOTE: The implicit parameter ?callStack :: CallStack is an -- implementation detail and should not be considered part of the -- CallStack API, we may decide to change the implementation in -- the future. type HasCallStack = ?callStack :: CallStack -- | This is a valid definition of stimes for an idempotent -- Monoid. -- -- When mappend x x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n) stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | The SomeException type is the root of the exception type -- hierarchy. When an exception of type e is thrown, behind the -- scenes it is encapsulated in a SomeException. data SomeException SomeException :: e -> SomeException -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data ByteString -- | A map of integers to values a. data IntMap a -- | A set of integers. data IntSet -- | A Map from keys k to values a. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data Map k a -- | General-purpose finite sequences. data Seq a -- | A set of values a. data Set a -- | a variant of deepseq that is useful in some circumstances: -- --
--   force x = x `deepseq` x
--   
-- -- force x fully evaluates x, and then returns it. Note -- that force x only performs evaluation when the value of -- force x itself is demanded, so essentially it turns shallow -- evaluation into deep evaluation. -- -- force can be conveniently used in combination with -- ViewPatterns: -- --
--   {-# LANGUAGE BangPatterns, ViewPatterns #-}
--   import Control.DeepSeq
--   
--   someFun :: ComplexData -> SomeResult
--   someFun (force -> !arg) = {- 'arg' will be fully evaluated -}
--   
-- -- Another useful application is to combine force with -- evaluate in order to force deep evaluation relative to other -- IO operations: -- --
--   import Control.Exception (evaluate)
--   import Control.DeepSeq
--   
--   main = do
--     result <- evaluate $ force $ pureComputation
--     {- 'result' will be fully evaluated at this point -}
--     return ()
--   
-- -- Finally, here's an exception safe variant of the readFile' -- example: -- --
--   readFile' :: FilePath -> IO String
--   readFile' fn = bracket (openFile fn ReadMode) hClose $ \h ->
--                          evaluate . force =<< hGetContents h
--   
force :: NFData a => a -> a -- | the deep analogue of $!. In the expression f $!! x, -- x is fully evaluated before the function f is -- applied to it. ($!!) :: NFData a => (a -> b) -> a -> b infixr 0 $!! -- | deepseq: fully evaluates the first argument, before returning -- the second. -- -- The name deepseq is used to illustrate the relationship to -- seq: where seq is shallow in the sense that it only -- evaluates the top level of its argument, deepseq traverses the -- entire data structure evaluating it completely. -- -- deepseq can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also -- useful in conjunction with parallel Strategies (see the -- parallel package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in any -- order or in parallel. To impose an actual order on evaluation, use -- pseq from Control.Parallel in the parallel -- package. deepseq :: NFData a => a -> b -> b -- | A class of types that can be fully evaluated. class NFData a -- | rnf should reduce its argument to normal form (that is, fully -- evaluate all sub-components), and then return (). -- --

Generic NFData deriving

-- -- Starting with GHC 7.2, you can automatically derive instances for -- types possessing a Generic instance. -- -- Note: Generic1 can be auto-derived starting with GHC 7.4 -- --
--   {-# LANGUAGE DeriveGeneric #-}
--   
--   import GHC.Generics (Generic, Generic1)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1)
--   
--   instance NFData a => NFData (Foo a)
--   instance NFData1 Foo
--   
--   data Colour = Red | Green | Blue
--                 deriving Generic
--   
--   instance NFData Colour
--   
-- -- Starting with GHC 7.10, the example above can be written more -- concisely by enabling the new DeriveAnyClass extension: -- --
--   {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
--   
--   import GHC.Generics (Generic)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1, NFData, NFData1)
--   
--   data Colour = Red | Green | Blue
--                 deriving (Generic, NFData)
--   
-- --

Compatibility with previous deepseq versions

-- -- Prior to version 1.4.0.0, the default implementation of the rnf -- method was defined as -- --
--   rnf a = seq a ()
--   
-- -- However, starting with deepseq-1.4.0.0, the default -- implementation is based on DefaultSignatures allowing for -- more accurate auto-derived NFData instances. If you need the -- previously used exact default rnf method implementation -- semantics, use -- --
--   instance NFData Colour where rnf x = seq x ()
--   
-- -- or alternatively -- --
--   instance NFData Colour where rnf = rwhnf
--   
-- -- or -- --
--   {-# LANGUAGE BangPatterns #-}
--   instance NFData Colour where rnf !_ = ()
--   
rnf :: NFData a => a -> () -- | Note that calling given entrypoints involves constructing -- UParam. pbsUParam :: forall (ctorName :: Symbol). KnownSymbol ctorName => ParamBuildingStep -- | Make up UParam from ADT sum. -- -- Entry points template will consist of (constructorName, -- constructorFieldType) pairs. Each constructor is expected to have -- exactly one field. uparamFromAdt :: UParamLinearize up => up -> UParam (UParamLinearized up) -- | Like caseUParam, but accepts a tuple of clauses, not a -- Rec. caseUParamT :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]) clauses. (clauses ~ Rec (CaseClauseU inp out) entries, RecFromTuple clauses, CaseUParam entries) => IsoRecTuple clauses -> UParamFallback inp out -> (UParam entries : inp) :-> out -- | Pattern-match on given UParam entries. -- -- You have to provide all case branches and a fallback action on case -- when entrypoint is not found. caseUParam :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]). (CaseUParam entries, RequireUniqueEntrypoints entries) => Rec (CaseClauseU inp out) entries -> UParamFallback inp out -> (UParam entries : inp) :-> out -- | Default implementation for UParamFallback, simply reports an -- error. uparamFallbackFail :: forall (inp :: [Type]) (out :: [Type]). UParamFallback inp out -- | Helper instruction which extracts content of UParam. unwrapUParam :: forall (entries :: [EntrypointKind]) (s :: [Type]). (UParam entries : s) :-> ((MText, ByteString) : s) -- | Construct a UParam safely. mkUParam :: forall a (name :: Symbol) (entries :: [EntrypointKind]). (NicePackedValue a, LookupEntrypoint name entries ~ a, RequireUniqueEntrypoints entries) => Label name -> a -> UParam entries -- | An entrypoint is described by two types: its name and type of -- argument. type EntrypointKind = (Symbol, Type) -- | A convenient alias for type-level name-something pair. type (n :: Symbol) ?: (a :: k) = '(n, a) -- | Encapsulates parameter for one of entry points. It keeps entrypoint -- name and corresponding argument serialized. -- -- In Haskell world, we keep an invariant of that contained value relates -- to one of entry points from entries list. newtype UParam (entries :: [EntrypointKind]) UParamUnsafe :: (MText, ByteString) -> UParam (entries :: [EntrypointKind]) -- | Pseudo value for UParam type variable. type SomeInterface = '[ '("SomeEntrypoints", Void)] -- | Homomorphic version of UParam, forgets the exact interface. type UParam_ = UParam SomeInterface -- | Get type of entrypoint argument by its name. type family LookupEntrypoint (name :: Symbol) (entries :: [EntrypointKind]) -- | Ensure that given entry points do no contain duplicated names. type family RequireUniqueEntrypoints (entries :: [EntrypointKind]) -- | This type can store any value that satisfies a certain constraint. data ConstrainedSome (c :: Type -> Constraint) [ConstrainedSome] :: forall (c :: Type -> Constraint) a. c a => a -> ConstrainedSome c -- | This class is needed to implement unpackUParam. class UnpackUParam (c :: Type -> Constraint) (entries :: [EntrypointKind]) -- | Turn UParam into a Haskell value. Since we don't know its type -- in compile time, we have to erase it using ConstrainedSome. The -- user of this function can require arbitrary constraint to hold -- (depending on how they want to use the result). unpackUParam :: UnpackUParam c entries => UParam entries -> Either EntrypointLookupError (MText, ConstrainedSome c) data EntrypointLookupError NoSuchEntrypoint :: MText -> EntrypointLookupError ArgumentUnpackFailed :: EntrypointLookupError -- | Implementations of some entry points. -- -- Note that this thing inherits properties of Rec, e.g. you can -- Data.Vinyl.Core.rappend implementations for two entrypoint -- sets when assembling scattered parts of a contract. type EntrypointsImpl (inp :: [Type]) (out :: [Type]) (entries :: [EntrypointKind]) = Rec CaseClauseU inp out entries -- | An action invoked when user-provided entrypoint is not found. type UParamFallback (inp :: [Type]) (out :: [Type]) = (MText, ByteString) : inp :-> out -- | Make up a "case" over entry points. class CaseUParam (entries :: [EntrypointKind]) -- | Constraint required by uparamFromAdt. type UParamLinearize p = (Generic p, GUParamLinearize Rep p) -- | Entry points template derived from given ADT sum. type UParamLinearized p = GUParamLinearized Rep p entryCaseSimple_ :: forall cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp & inp) :-> out -- | Whether finalizeParamCallingDoc has already been applied to -- these steps. areFinalizedParamBuildingSteps :: [ParamBuildingStep] -> Bool -- | Wrapper for documenting single entrypoint which parameter isn't going -- to be unwrapped from some datatype. -- -- entryCase unwraps a datatype, however, sometimes we want to -- have entrypoint parameter to be not wrapped into some datatype. documentEntrypoint :: forall kind (epName :: Symbol) param (s :: [Type]) (out :: [Type]). (KnownSymbol epName, DocItem (DEntrypoint kind), TypeHasDoc param, HasAnnotation param, KnownValue param) => ((param & s) :-> out) -> (param & s) :-> out -- | Go over contract code and update every occurrence of -- DEntrypointArg documentation item, adding the given step to its -- "how to build parameter" description. clarifyParamBuildingSteps :: forall (inp :: [Type]) (out :: [Type]). ParamBuildingStep -> (inp :-> out) -> inp :-> out mkDEntrypointArgSimple :: (KnownValue t, HasAnnotation t, TypeHasDoc t) => DEntrypointArg mkDEpUType :: (KnownValue t, HasAnnotation t) => Type emptyDEpArg :: DEntrypointArg constructDEpArg :: (TypeHasDoc arg, HasAnnotation arg, KnownValue arg) => DEntrypointArg -- | Make a ParamBuildingStep that tells about wrapping an argument -- into a constructor with given name and uses given ParamBuilder -- as description of Michelson part. mkPbsWrapIn :: Text -> ParamBuilder -> ParamBuildingStep -- | Default implementation of docItemToMarkdown for entry points. diEntrypointToMarkdown :: HeaderLevel -> DEntrypoint level -> Markdown -- | Gathers information about single entrypoint. -- -- We assume that entry points might be of different kinds, which is -- designated by phantom type parameter. For instance, you may want to -- have several groups of entry points corresponding to various parts of -- a contract - specifying different kind type argument for each -- of those groups will allow you defining different DocItem -- instances with appropriate custom descriptions for them. data DEntrypoint kind DEntrypoint :: Text -> SubDoc -> DEntrypoint kind [depName] :: DEntrypoint kind -> Text [depSub] :: DEntrypoint kind -> SubDoc -- | Default value for DEntrypoint type argument. data PlainEntrypointsKind data DEntrypointReference DEntrypointReference :: Text -> Anchor -> DEntrypointReference -- | When describing the way of parameter construction - piece of -- incremental builder for this description. newtype ParamBuilder ParamBuilder :: (Markdown -> Markdown) -> ParamBuilder -- | Argument stands for previously constructed parameter piece, and -- returned value - a piece constructed after our step. [unParamBuilder] :: ParamBuilder -> Markdown -> Markdown data ParamBuildingDesc ParamBuildingDesc :: Markdown -> ParamBuilder -> ParamBuilder -> ParamBuildingDesc -- | Plain english description of this step. [pbdEnglish] :: ParamBuildingDesc -> Markdown -- | How to construct parameter in Haskell code. [pbdHaskell] :: ParamBuildingDesc -> ParamBuilder -- | How to construct parameter working on raw Michelson. [pbdMichelson] :: ParamBuildingDesc -> ParamBuilder -- | Describes a parameter building step. -- -- This can be wrapping into (Haskell) constructor, or a more complex -- transformation. data ParamBuildingStep -- | Wraps something into constructor with given name. Constructor should -- be the one which corresponds to an entrypoint defined via field -- annotation, for more complex cases use PbsCustom. PbsWrapIn :: Text -> ParamBuildingDesc -> ParamBuildingStep -- | Directly call an entrypoint marked with a field annotation. PbsCallEntrypoint :: EpName -> ParamBuildingStep -- | Other action. PbsCustom :: ParamBuildingDesc -> ParamBuildingStep -- | This entrypoint cannot be called, which is possible when an explicit -- default entrypoint is present. This is not a true entrypoint but just -- some intermediate node in or tree and neither it nor any of -- its parents are marked with a field annotation. -- -- It contains dummy ParamBuildingSteps which were assigned before -- entrypoints were taken into account. PbsUncallable :: [ParamBuildingStep] -> ParamBuildingStep -- | Describes argument of an entrypoint. data DEntrypointArg DEntrypointArg :: Maybe DType -> [ParamBuildingStep] -> Type -> DEntrypointArg -- | Argument of the entrypoint. Pass Nothing if no argument is -- required. [epaArg] :: DEntrypointArg -> Maybe DType -- | Describes a way to lift an entrypoint argument into full parameter -- which can be passed to the contract. -- -- Steps are supposed to be applied in the order opposite to one in which -- they are given. E.g. suppose that an entrypoint is called as Run -- (Service1 arg); then the first step (actual last) should describe -- wrapping into Run constructor, and the second step (actual -- first) should be about wrapping into Service1 constructor. [epaBuilding] :: DEntrypointArg -> [ParamBuildingStep] -- | Untyped representation of entrypoint, used for printing its michelson -- type representation. [epaType] :: DEntrypointArg -> Type -- | Pick a type documentation from CtorField. class KnownSymbol con => DeriveCtorFieldDoc (con :: Symbol) (cf :: CtorField) deriveCtorFieldDoc :: DeriveCtorFieldDoc con cf => DEntrypointArg -- | Constraint for documentEntrypoints. type DocumentEntrypoints kind a = (Generic a, GDocumentEntrypoints kind Rep a) -- | Provides arror for convenient entrypoint documentation class EntryArrow (kind :: k) (name :: Symbol) body -- | Lift entrypoint implementation. -- -- Entrypoint names should go with "e" prefix. (#->) :: EntryArrow kind name body => (Label name, Proxy kind) -> body -> body type family RequireFlatParamEps cp type family RequireFlatEpDerivation (cp :: t) deriv -- | Utility to create EntrypointsFields from an entrypoint name -- (epName) and an EntrypointLambda implementation. Note -- that you need to merge multiple of these (with <>) if -- your field contains more than one entrypoint lambda. mkStoreEp :: forall (epName :: Symbol) epParam epStore. Label epName -> EntrypointLambda epParam epStore -> EntrypointsField epParam epStore composeStoreEntrypointOps :: forall (nameInStore :: Symbol) store substore (epName :: Symbol) epParam epStore. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreEntrypointOps substore epName epParam epStore -> StoreEntrypointOps store epName epParam epStore -- | Chain implementations of field and submap operations. composeStoreSubmapOps :: forall (nameInStore :: Symbol) store substore (mname :: Symbol) key value. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreSubmapOps substore mname key value -> StoreSubmapOps store mname key value -- | Chain two implementations of field operations. -- -- Suits for a case when your store does not contain its fields directly -- rather has a nested structure. composeStoreFieldOps :: forall (nameInStore :: Symbol) store substore (nameInSubstore :: Symbol) field. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreFieldOps substore nameInSubstore field -> StoreFieldOps store nameInSubstore field -- | Pretend that given StoreEntrypointOps implementation is made up -- for entrypoint with name desiredName, not its actual name. -- Logic of the implementation remains the same. -- -- See also storeSubmapOpsReferTo. storeEntrypointOpsReferTo :: forall (epName :: Symbol) store epParam epStore (desiredName :: Symbol). Label epName -> StoreEntrypointOps store epName epParam epStore -> StoreEntrypointOps store desiredName epParam epStore -- | Pretend that given StoreFieldOps implementation is made up for -- field with name desiredName, not its actual name. Logic of -- the implementation remains the same. -- -- See also storeSubmapOpsReferTo. storeFieldOpsReferTo :: forall (name :: Symbol) storage field (desiredName :: Symbol). Label name -> StoreFieldOps storage name field -> StoreFieldOps storage desiredName field -- | Pretend that given StoreSubmapOps implementation is made up for -- submap with name desiredName, not its actual name. Logic of -- the implementation remains the same. -- -- Use case: imagine that your code requires access to submap named -- X, but in your storage that submap is called Y. Then -- you implement the instance which makes X refer to Y: -- --
--   instance StoreHasSubmap Store X Key Value where
--     storeSubmapOps = storeSubmapOpsReferTo #Y storeSubmapOpsForY
--   
storeSubmapOpsReferTo :: forall (name :: Symbol) storage key value (desiredName :: Symbol). Label name -> StoreSubmapOps storage name key value -> StoreSubmapOps storage desiredName key value -- | Implementation of StoreHasEntrypoint for a data type which has -- an instance of StoreHasEntrypoint inside. For instance, it can -- be used for top-level storage. storeEntrypointOpsDeeper :: forall store (nameInStore :: Symbol) substore (epName :: Symbol) epParam epStore. (HasFieldOfType store nameInStore substore, StoreHasEntrypoint substore epName epParam epStore) => Label nameInStore -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasSubmap for a data type which has an -- instance of StoreHasSubmap inside. For instance, it can be used -- for top-level storage. storeSubmapOpsDeeper :: forall storage (bigMapPartName :: Symbol) fields (mname :: Symbol) key value. (HasFieldOfType storage bigMapPartName fields, StoreHasSubmap fields mname key value) => Label bigMapPartName -> StoreSubmapOps storage mname key value -- | Implementation of StoreHasField for a data type which has an -- instance of StoreHasField inside. For instance, it can be used -- for top-level storage. storeFieldOpsDeeper :: forall storage (fieldsPartName :: Symbol) fields (fname :: Symbol) ftype. (HasFieldOfType storage fieldsPartName fields, StoreHasField fields fname ftype) => Label fieldsPartName -> StoreFieldOps storage fname ftype -- | Implementation of StoreHasEntrypoint for a datatype that has a -- StoreHasSubmap that contains the entrypoint and a -- StoreHasField for the field such entrypoint operates on. storeEntrypointOpsSubmapField :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (StoreHasSubmap store epmName MText (EntrypointLambda epParam epStore), StoreHasField store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasEntrypoint for a datatype that has a -- StoreHasField for an EntrypointsField that contains the -- entrypoint and a StoreHasField for the field such entrypoint -- operates on. storeEntrypointOpsFields :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (StoreHasField store epmName (EntrypointsField epParam epStore), StoreHasField store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasEntrypoint for a datatype keeping a -- pack of fields, among which one has contains the entrypoint and -- another is what such entrypoint operates on. storeEntrypointOpsADT :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (HasFieldOfType store epmName (EntrypointsField epParam epStore), HasFieldOfType store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasField for case of datatype keeping a -- pack of fields. storeFieldOpsADT :: forall dt (fname :: Symbol) ftype. HasFieldOfType dt fname ftype => StoreFieldOps dt fname ftype -- | Update the sub-storage that the entrypoint operates on. stSetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epStore : (store : s)) :-> (store : s) -- | Get the sub-storage that the entrypoint operates on, preserving the -- storage itself on the stack. stGetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : (store : s)) -- | Pick the sub-storage that the entrypoint operates on. stToEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : s) -- | Stores the entrypoint lambda in the storage. Fails if already set. stSetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) -- | Get stored entrypoint lambda, preserving the storage itself on the -- stack. stGetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : (store : s)) -- | Pick stored entrypoint lambda. stToEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) -- | Extracts and executes the epName entrypoint lambda from -- storage, returing the updated full storage (store) and the -- produced Operations. stEntrypoint :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epParam : (store : s)) :-> (([Operation], store) : s) -- | Add a value in storage, but fail if it will overwrite some existing -- entry. stInsertNew :: forall store (mname :: Symbol) key value (s :: [Type]). StoreHasSubmap store mname key value => Label mname -> (forall (s0 :: [Type]) (any :: [Type]). () => (key : s0) :-> any) -> (key : (value : (store : s))) :-> (store : s) -- | Add a value in storage. stInsert :: forall store (mname :: Symbol) key value (s :: [Type]). StoreHasSubmap store mname key value => Label mname -> (key : (value : (store : s))) :-> (store : s) -- | Delete a value in storage. stDelete :: forall store (mname :: Symbol) key value (s :: [Type]). (StoreHasSubmap store mname key value, KnownValue value) => Label mname -> (key : (store : s)) :-> (store : s) -- | Update a value in storage. stUpdate :: forall store (mname :: Symbol) key value (s :: [Type]). StoreHasSubmap store mname key value => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s) -- | Get value in storage. stGet :: forall store (mname :: Symbol) key value (s :: [Type]). (StoreHasSubmap store mname key value, KnownValue value) => Label mname -> (key : (store : s)) :-> (Maybe value : s) -- | Check value presence in storage. stMem :: forall store (mname :: Symbol) key value (s :: [Type]). StoreHasSubmap store mname key value => Label mname -> (key : (store : s)) :-> (Bool : s) -- | Update storage field. stSetField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (ftype : (store : s)) :-> (store : s) -- | Get storage field, preserving the storage itself on stack. stGetField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (store : s) :-> (ftype : (store : s)) -- | Pick storage field. stToField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (store : s) :-> (ftype : s) -- | Datatype containing the full implementation of StoreHasField -- typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreFieldOps store (fname :: Symbol) ftype StoreFieldOps :: (forall (s :: [Type]). () => Label fname -> (store : s) :-> (ftype : s)) -> (forall (s :: [Type]). () => Label fname -> (ftype : (store : s)) :-> (store : s)) -> StoreFieldOps store (fname :: Symbol) ftype [sopToField] :: StoreFieldOps store (fname :: Symbol) ftype -> forall (s :: [Type]). () => Label fname -> (store : s) :-> (ftype : s) [sopSetField] :: StoreFieldOps store (fname :: Symbol) ftype -> forall (s :: [Type]). () => Label fname -> (ftype : (store : s)) :-> (store : s) -- | Provides operations on fields for storage. class StoreHasField store (fname :: Symbol) ftype | store fname -> ftype storeFieldOps :: StoreHasField store fname ftype => StoreFieldOps store fname ftype -- | Datatype containing the full implementation of StoreHasSubmap -- typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreSubmapOps store (mname :: Symbol) key value StoreSubmapOps :: (forall (s :: [Type]). () => Label mname -> (key : (store : s)) :-> (Bool : s)) -> (forall (s :: [Type]). KnownValue value => Label mname -> (key : (store : s)) :-> (Maybe value : s)) -> (forall (s :: [Type]). () => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s)) -> (forall (s :: [Type]). () => Maybe (Label mname -> (key : (store : s)) :-> (store : s))) -> (forall (s :: [Type]). () => Maybe (Label mname -> (key : (value : (store : s))) :-> (store : s))) -> StoreSubmapOps store (mname :: Symbol) key value [sopMem] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Label mname -> (key : (store : s)) :-> (Bool : s) [sopGet] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). KnownValue value => Label mname -> (key : (store : s)) :-> (Maybe value : s) [sopUpdate] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s) [sopDelete] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Maybe (Label mname -> (key : (store : s)) :-> (store : s)) [sopInsert] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Maybe (Label mname -> (key : (value : (store : s))) :-> (store : s)) -- | Provides operations on submaps of storage. class StoreHasSubmap store (mname :: Symbol) key value | store mname -> key value storeSubmapOps :: StoreHasSubmap store mname key value => StoreSubmapOps store mname key value -- | Type synonym for a Lambda that can be used as an entrypoint type EntrypointLambda param store = Lambda (param, store) ([Operation], store) -- | Type synonym of a BigMap mapping MText (entrypoint -- names) to EntrypointLambda. -- -- This is useful when defining instances of StoreHasEntrypoint as -- a storage field containing one or more entrypoints (lambdas) of the -- same type. type EntrypointsField param store = BigMap MText EntrypointLambda param store -- | Datatype containing the full implementation of -- StoreHasEntrypoint typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreEntrypointOps store (epName :: Symbol) epParam epStore StoreEntrypointOps :: (forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s)) -> (forall (s :: [Type]). () => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s)) -> (forall (s :: [Type]). () => Label epName -> (store : s) :-> (epStore : s)) -> (forall (s :: [Type]). () => Label epName -> (epStore : (store : s)) :-> (store : s)) -> StoreEntrypointOps store (epName :: Symbol) epParam epStore [sopToEpLambda] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) [sopSetEpLambda] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) [sopToEpStore] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (store : s) :-> (epStore : s) [sopSetEpStore] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (epStore : (store : s)) :-> (store : s) -- | Provides operations on stored entrypoints. -- -- store is the storage containing both the entrypoint -- epName (note: it has to be in a BigMap to take -- advantage of lazy evaluation) and the epStore field this -- operates on. class StoreHasEntrypoint store (epName :: Symbol) epParam epStore | store epName -> epParam epStore storeEpOps :: StoreHasEntrypoint store epName epParam epStore => StoreEntrypointOps store epName epParam epStore -- | Indicates a submap with given key and value types. data (k2 :: k) ~> (v :: k1) infix 9 ~> -- | Indicates a stored entrypoint with the given param and -- store types. data (param :: k) ::-> (store :: k1) infix 9 ::-> -- | Concise way to write down constraints with expected content of a -- storage. -- -- Use it like follows: -- --
--   type StorageConstraint store = StorageContains store
--     [ "fieldInt" := Int
--     , "fieldNat" := Nat
--     , "epsToNat" := Int ::-> Nat
--     , "balances" := Address ~> Int
--     ]
--   
type family StorageContains store (content :: [NamedField]) -- | Unwrap a constructor with the given name. Useful for sum types. unwrapUnsafe_ :: forall dt (name :: Symbol) (st :: [Type]). InstrUnwrapC dt name => Label name -> (dt & st) :-> (CtorOnlyField name dt : st) -- | Wrap entry in single-field constructor. Useful for sum types. wrapOne :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapOneC dt name => Label name -> (CtorOnlyField name dt : st) :-> (dt & st) -- | Wrap entry in constructor. Useful for sum types. wrap_ :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapC dt name => Label name -> AppendCtorField (GetCtorField dt name) st :-> (dt & st) -- | Lift an instruction to field constructor. fieldCtor :: forall (st :: [Type]) f. HasCallStack => (st :-> (f & st)) -> FieldConstructor st f -- | Decompose a complex object into its fields deconstruct :: forall dt (fields :: [Type]) (st :: [Type]). (InstrDeconstructC dt, KnownList fields, ToTs fields ~ ToTs (ConstructorFieldTypes dt)) => (dt & st) :-> (fields ++ st) -- | Construct an object from fields on the stack. constructStack :: forall dt (fields :: [Type]) (st :: [Type]). (InstrConstructC dt, ToTs fields ~ ToTs (ConstructorFieldTypes dt), KnownList fields) => (fields ++ st) :-> (dt & st) -- | Apply given modifier to a datatype field. modifyField :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, InstrSetFieldC dt name) => Label name -> (forall (st0 :: [Type]). () => (GetFieldType dt name : st0) :-> (GetFieldType dt name : st0)) -> (dt & st) :-> (dt & st) -- | Like getField, but leaves field named. getFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> ((name :! GetFieldType dt name) & (dt : st)) -- | Extract a field of a datatype, leaving the original datatype on stack. getField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> (GetFieldType dt name & (dt : st)) -- | Like toField, but leaves field named. toFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> ((name :! GetFieldType dt name) & st) -- | Extract a field of a datatype replacing the value of this datatype -- with the extracted field. -- -- For this and the following functions you have to specify field name -- which is either record name or name attached with (:!) -- operator. toField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> (GetFieldType dt name & st) -- | Like HasField, but allows constrainting field type. type HasFieldOfType dt (fname :: Symbol) fieldTy = (HasField dt fname, GetFieldType dt fname ~ fieldTy) -- | A pair of field name and type. data NamedField NamedField :: Symbol -> Type -> NamedField type (n :: Symbol) := ty = 'NamedField n ty infixr 0 := -- | Shortcut for multiple HasFieldOfType constraints. type family HasFieldsOfType dt (fs :: [NamedField]) -- | Lorentz analogy of CaseClause, it works on plain Type -- types. data CaseClauseL (inp :: [Type]) (out :: [Type]) (param :: CaseClauseParam) [CaseClauseL] :: forall (x :: CtorField) (inp :: [Type]) (out :: [Type]) (ctor :: Symbol). (AppendCtorField x inp :-> out) -> CaseClauseL inp out ('CaseClauseParam ctor x) -- | Provides "case" arrow which works on different wrappers for clauses. class CaseArrow (name :: Symbol) body clause | clause -> name, clause -> body -- | Lift an instruction to case clause. -- -- You should write out constructor name corresponding to the clause -- explicitly. Prefix constructor name with "c" letter, otherwise your -- label will not be recognized by Haskell parser. Passing constructor -- name can be circumvented but doing so is not recomended as mentioning -- contructor name improves readability and allows avoiding some -- mistakes. (/->) :: CaseArrow name body clause => Label name -> body -> clause infixr 0 /-> type CaseTC dt (out :: [Type]) (inp :: [Type]) clauses = (InstrCaseC dt, RMap CaseClauses dt, RecFromTuple clauses, clauses ~ Rec CaseClauseL inp out CaseClauses dt) -- | Handlers for most common errors defined in Lorentz. baseErrorDocHandlers :: [NumericErrorDocHandler] -- | Handler for VoidResult. voidResultDocHandler :: NumericErrorDocHandler -- | Handler for all CustomErrors. customErrorDocHandler :: NumericErrorDocHandler -- | Extended version of applyErrorTagToErrorsDoc which accepts -- error handlers. -- -- In most cases that function should be enough for your purposes, but it -- uses a fixed set of base handlers which may be not enough in case when -- you define your own errors. In this case define and pass all the -- necessary handlers to this function. -- -- It fails with error if some of the errors used in the contract -- cannot be handled with given handlers. applyErrorTagToErrorsDocWith :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [NumericErrorDocHandler] -> ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Modify documentation generated for given code so that all -- CustomError mention not their textual error tag rather -- respective numeric one from the given map. -- -- If some documented error is not present in the map, it remains -- unmodified. This function may fail with error if contract uses -- some uncommon errors, see applyErrorTagToErrorsDocWith for -- details. applyErrorTagToErrorsDoc :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Adds a section which explains error tag mapping. data DDescribeErrorTagMap DDescribeErrorTagMap :: Text -> DDescribeErrorTagMap -- | Describes where the error tag map is defined in Haskell code. [detmSrcLoc] :: DDescribeErrorTagMap -> Text -- | Errors for NumericErrorDocHandler data NumericErrorDocHandlerError -- | Handler which changes documentation for one particular error type. data NumericErrorDocHandler -- | Some error with a numeric tag attached. data NumericErrorWrapper (numTag :: Nat) err -- | Make migration script which initializes UStore from scratch. fillUStore :: UStoreTraversable FillUStoreTW template => template -> UStoreMigration () template -- | Like ustoreDecompose, but requires all entries from -- UStore to be recognized. ustoreDecomposeFull :: UStoreTraversable DecomposeUStoreTW template => UStore template -> Either Text template -- | Decompose UStore into separate big_maps and fields. -- -- Since this function needs to UNPACK content of -- UStore to actual keys and values, you have to provide -- UnpackEnv. -- -- Along with resulting value, you get a list of UStore entries -- which were not recognized as belonging to any submap or field -- according to UStore's template - this should be empty unless -- UStore invariants were violated. ustoreDecompose :: UStoreTraversable DecomposeUStoreTW template => UStore template -> Either Text (UStoreContent, template) -- | Make UStore from separate big_maps and fields. mkUStore :: UStoreTraversable MkUStoreTW template => template -> UStore template -- | Declares handlers for UStore creation from template. data MkUStoreTW -- | Declares handlers for UStore conversion to template. data DecomposeUStoreTW -- | Declares handlers for UStore filling via lambda. data FillUStoreTW -- | Get the old version of storage. -- -- This can be applied only in the beginning of migration. -- -- In fact this function is not very useful, all required operations -- should be available for MUStore, but leaving it here just in -- case. mustoreToOld :: forall (touched :: [Symbol]) oldTemplate newTemplate (remDiff :: [DiffItem]) (s :: [Type]). RequireBeInitial touched => (MUStore oldTemplate newTemplate remDiff touched : s) :-> (UStore oldTemplate : s) -- | Modify field which should stay in new version of storage. This does -- not affect remaining diff. migrateModifyField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (s :: [Type]). (HasUField field fieldTy oldTempl, HasUField field fieldTy newTempl) => Label field -> (fieldTy : (MUStore oldTempl newTempl diff touched : s)) :-> (MUStore oldTempl newTempl diff touched : s) -- | Remove field and write new one in place of it. -- -- This is semantically equivalent to dip (migrateRemoveField label) -- >> migrateAddField label, but is cheaper. migrateOverwriteField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy oldFieldTy (marker :: UStoreMarkerType) (oldMarker :: UStoreMarkerType) (newDiff :: [DiffItem]) (newDiff0 :: [DiffItem]) (s :: [Type]). ('(UStoreFieldExt oldMarker oldFieldTy, newDiff0) ~ CoverDiff 'DcRemove field diff, '(UStoreFieldExt marker fieldTy, newDiff) ~ CoverDiff 'DcAdd field newDiff0, HasUField field fieldTy newTempl) => Label field -> (fieldTy : (MUStore oldTempl newTempl diff touched : s)) :-> (MUStore oldTempl newTempl newDiff (field : touched) : s) -- | Get and remove a field from old version of UStore. -- -- You probably want to use this more often than plain -- migrateRemoveField. migrateExtractField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (newDiff :: [DiffItem]) (marker :: UStoreMarkerType) (s :: [Type]). ('(UStoreFieldExt marker fieldTy, newDiff) ~ CoverDiff 'DcRemove field diff, HasUField field fieldTy oldTempl, RequireUntouched field (IsElem field touched)) => Label field -> (MUStore oldTempl newTempl diff touched : s) :-> (fieldTy : (MUStore oldTempl newTempl newDiff (field : touched) : s)) -- | Remove a field which should not be present in new version of storage. -- This covers one removal from the diff. -- -- In fact, this action could be performed automatically, but since -- removal is a destructive operation, being explicit about it seems like -- a good thing. migrateRemoveField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (newDiff :: [DiffItem]) (marker :: UStoreMarkerType) (s :: [Type]). ('(UStoreFieldExt marker fieldTy, newDiff) ~ CoverDiff 'DcRemove field diff, HasUField field fieldTy oldTempl) => Label field -> (MUStore oldTempl newTempl diff touched : s) :-> (MUStore oldTempl newTempl newDiff (field : touched) : s) -- | Add a field which was not present before. This covers one addition -- from the diff and any removals of field with given name. -- -- This function cannot overwrite existing field with the same name, if -- this is necessary use migrateOverwriteField which would declare -- removal explicitly. migrateAddField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (newDiff :: [DiffItem]) (marker :: UStoreMarkerType) (s :: [Type]). ('(UStoreFieldExt marker fieldTy, newDiff) ~ CoverDiff 'DcAdd field diff, HasUField field fieldTy newTempl) => Label field -> (fieldTy : (MUStore oldTempl newTempl diff touched : s)) :-> (MUStore oldTempl newTempl newDiff (field : touched) : s) -- | Get a field present in old version of UStore. migrateGetField :: forall (field :: Symbol) oldTempl newTempl (diff :: [DiffItem]) (touched :: [Symbol]) fieldTy (s :: [Type]). (HasUField field fieldTy oldTempl, RequireUntouched field (IsElem field touched)) => Label field -> (MUStore oldTempl newTempl diff touched : s) :-> (fieldTy : (MUStore oldTempl newTempl diff touched : s)) -- | Like setField, but for UStore. ustoreSetField :: forall store (name :: Symbol) (s :: [Type]). FieldAccessC store name => Label name -> (GetUStoreField store name : (UStore store : s)) :-> (UStore store : s) -- | Like getField, but for UStore. -- -- This may fail only if UStore was made up incorrectly during -- contract initialization. ustoreGetField :: forall store (name :: Symbol) (s :: [Type]). FieldAccessC store name => Label name -> (UStore store : s) :-> (GetUStoreField store name : (UStore store : s)) -- | Like toField, but for UStore. -- -- This may fail only if UStore was made up incorrectly during -- contract initialization. ustoreToField :: forall store (name :: Symbol) (s :: [Type]). FieldAccessC store name => Label name -> (UStore store : s) :-> (GetUStoreField store name : s) ustoreDelete :: forall store (name :: Symbol) (s :: [Type]). KeyAccessC store name => Label name -> (GetUStoreKey store name : (UStore store : s)) :-> (UStore store : s) -- | Insert a key-value pair, but fail if it will overwrite some existing -- entry. ustoreInsertNew :: forall store (name :: Symbol) (s :: [Type]). (KeyAccessC store name, ValueAccessC store name) => Label name -> (forall (s0 :: [Type]) (any :: [Type]). () => (GetUStoreKey store name : s0) :-> any) -> (GetUStoreKey store name : (GetUStoreValue store name : (UStore store : s))) :-> (UStore store : s) ustoreInsert :: forall store (name :: Symbol) (s :: [Type]). (KeyAccessC store name, ValueAccessC store name) => Label name -> (GetUStoreKey store name : (GetUStoreValue store name : (UStore store : s))) :-> (UStore store : s) ustoreUpdate :: forall store (name :: Symbol) (s :: [Type]). (KeyAccessC store name, ValueAccessC store name) => Label name -> (GetUStoreKey store name : (Maybe (GetUStoreValue store name) : (UStore store : s))) :-> (UStore store : s) ustoreGet :: forall store (name :: Symbol) (s :: [Type]). (KeyAccessC store name, ValueAccessC store name) => Label name -> (GetUStoreKey store name : (UStore store : s)) :-> (Maybe (GetUStoreValue store name) : s) ustoreMem :: forall store (name :: Symbol) (s :: [Type]). KeyAccessC store name => Label name -> (GetUStoreKey store name : (UStore store : s)) :-> (Bool : s) -- | This constraint can be used if a function needs to work with -- big store, but needs to know only about some submap(s) of it. -- -- It can use all UStore operations for a particular name, key and value -- without knowing whole template. type HasUStore (name :: Symbol) key value store = (KeyAccessC store name, ValueAccessC store name, GetUStoreKey store name ~ key, GetUStoreValue store name ~ value) -- | This constraint can be used if a function needs to work with -- big store, but needs to know only about some field of it. type HasUField (name :: Symbol) ty store = (FieldAccessC store name, GetUStoreField store name ~ ty) -- | Write down all sensisble constraints which given store -- satisfies and apply them to constrained. -- -- This store should have |~> and UStoreField fields in -- its immediate fields, no deep inspection is performed. type HasUStoreForAllIn store constrained = (Generic store, GHasStoreForAllIn constrained Rep store) voidResultTag :: MText -- | view type synonym as described in A1. data View a r -- | void type synonym as described in A1. data Void_ a b -- | Newtype over void result type used in tests to distinguish successful -- void result from other errors. -- -- Usage example: lExpectFailWith (== VoidResult roleMaster)` -- -- This error is special - it can contain arguments of different types -- depending on entrypoint which raises it. data VoidResult r -- | Unlift an UStore to a smaller UStore which is part of -- the former. -- -- This function is not intended for use in migrations, only in normal -- entry points. -- -- Surprisingly, despite smaller UStore may have extra entries, -- this function is safe when used in contract code. Truly, all getters -- and setters are still safe to use. Also, there is no way for the -- resulting small UStore to leak outside of the contract since -- the only place where big_map can appear is contract storage, -- so this small UStore can be either dropped or lifted back via -- liftUStore to appear as part of the new contract's state. -- -- When this function is run as part of standalone instructions sequence, -- not as part of contract code (e.g. in tests), you may get an -- UStore with entries not inherent to it. unliftUStore :: forall template (name :: Symbol) (s :: [Type]). Generic template => Label name -> (UStore template : s) :-> (UStore (GetFieldType template name) : s) -- | Lift an UStore to another UStore which contains all the -- entries of the former under given field. -- -- This function is not intended for use in migrations, only in normal -- entry points. -- -- Note that this function ensures that template of resulting store does -- not contain inner nested templates with duplicated fields, otherwise -- UStore invariants could get broken. liftUStore :: forall template (name :: Symbol) (s :: [Type]). (Generic template, RequireAllUniqueFields template) => Label name -> (UStore (GetFieldType template name) : s) :-> (UStore template : s) -- | Get migration script in case of simple (non-batched) migration. migrationToScript :: UStoreMigration os ns -> MigrationScript os ns -- | Get migration script in case of simple (non-batched) migration. migrationToScriptI :: UStoreMigration os ns -> Identity (MigrationScript os ns) -- | Safe way to create migration scripts for UStore. -- -- You have to supply a code which would transform MUStore, -- coverring required diff step-by-step. All basic instructions work, -- also use migrate* functions from this module to operate with -- MUStore. -- -- This method produces a whole migration, it cannot be splitted in -- batches. In case if your migration is too big to be applied within a -- single transaction, use mkUStoreBatchedMigration. mkUStoreMigration :: forall oldTempl newTempl (_1 :: [Symbol]). Lambda (MUStore oldTempl newTempl (BuildDiff oldTempl newTempl) ('[] :: [Symbol])) (MUStore oldTempl newTempl ('[] :: [DiffItem]) _1) -> UStoreMigration oldTempl newTempl -- | Turn Migration into a whole piece of code for transforming -- storage. -- -- This is not want you'd want to use for contract deployment because of -- gas and operation size limits that Tezos applies to transactions. migrationToLambda :: UStoreMigration oldTemplate newTemplate -> Lambda (UStore oldTemplate) (UStore newTemplate) -- | Keeps information about migration between UStores with two -- given templates. data UStoreMigration oldTempl newTempl -- | Code of migration for UStore. -- -- Invariant: preferably should fit into op size / gas limits (quite -- obvious). Often this stands for exactly one stage of migration (one -- Tezos transaction). newtype MigrationScript oldStore newStore MigrationScript :: Lambda UStore_ UStore_ -> MigrationScript oldStore newStore [unMigrationScript] :: MigrationScript oldStore newStore -> Lambda UStore_ UStore_ type MigrationScript_ = MigrationScript SomeUTemplate SomeUTemplate -- | Information for UStore template required for documentation. -- -- You only need to instantiate this for templates used directly in -- UStore, nested subtemplates do not need this instance. class Typeable template => UStoreTemplateHasDoc template -- | UStore template name as it appears in documentation. -- -- Should be only 1 word. ustoreTemplateDocName :: UStoreTemplateHasDoc template => Text -- | Description of template. ustoreTemplateDocDescription :: UStoreTemplateHasDoc template => Markdown -- | Description of template entries. ustoreTemplateDocContents :: UStoreTemplateHasDoc template => Markdown ustoreTemplateDocDependencies :: UStoreTemplateHasDoc template => [SomeTypeWithDoc] -- | Instantiated for documented UStore markers. class KnownUStoreMarker marker => UStoreMarkerHasDoc (marker :: UStoreMarkerType) -- | Specifies key encoding. -- -- You accept description of field name, and should return how is it -- encoded as key of big_map bytes bytes. ustoreMarkerKeyEncoding :: UStoreMarkerHasDoc marker => Text -> Text -- | Constraint for UStore traversal. type UStoreTraversable way a = (Generic a, GUStoreTraversable way Rep a, UStoreTraversalWay way) -- | Gathers multple fields and BigMaps under one object. -- -- Type argument of this datatype stands for a "store template" - a -- datatype with one constructor and multiple fields, each containing an -- object of type UStoreField or |~> and corresponding -- to single virtual field or BigMap respectively. It's also -- possible to parameterize it with a larger type which is a product of -- types satisfying the above property. data UStore a -- | Describes one virtual big map in the storage. newtype k |~> v UStoreSubMap :: Map k v -> (|~>) k v [unUStoreSubMap] :: (|~>) k v -> Map k v -- | Describes plain field in the storage. newtype UStoreFieldExt (m :: UStoreMarkerType) v UStoreField :: v -> UStoreFieldExt (m :: UStoreMarkerType) v [unUStoreField] :: UStoreFieldExt (m :: UStoreMarkerType) v -> v -- | Specific kind used to designate markers for UStoreFieldExt. -- -- We suggest that fields may serve different purposes and so annotated -- with special markers accordingly, which influences translation to -- Michelson. See example below. -- -- This Haskell kind is implemented like that because we want markers to -- differ from all other types in kind; herewith UStoreMarkerType -- is still an open kind (has potentially infinite number of -- inhabitants). type UStoreMarkerType = UStoreMarker -> Type -- | Just a plain field used as data. type UStoreField = UStoreFieldExt UMarkerPlainField -- | Display type-level information about UStore field with given marker -- and field value type. Used for error messages. type family ShowUStoreField (marker :: UStoreMarkerType) v :: ErrorMessage -- | Allows to specify format of key under which fields of this type are -- stored. Useful to avoid collisions. class KnownUStoreMarker (marker :: UStoreMarkerType) where { -- | Display type-level information about UStore field with given marker -- and field value type. Used for error messages. type family ShowUStoreField (marker :: UStoreMarkerType) v :: ErrorMessage; type ShowUStoreField (marker :: UStoreMarkerType) v = 'Text "field of type " :<>: 'ShowType v; } -- | By field name derive key under which field should be stored. mkFieldMarkerUKey :: KnownUStoreMarker marker => MText -> ByteString -- | Get type of submap key. type GetUStoreKey store (name :: Symbol) = MSKey GetUStore name store -- | Get type of submap value. type GetUStoreValue store (name :: Symbol) = MSValue GetUStore name store -- | Get type of plain field. This ignores marker with field type. type GetUStoreField store (name :: Symbol) = FSValue GetUStore name store -- | Get kind of field. type GetUStoreFieldMarker store (name :: Symbol) = FSMarker GetUStore name store -- | Collect all fields with the given marker. type PickMarkedFields (marker :: UStoreMarkerType) template = GPickMarkedFields marker Rep template -- | Implementation of castDummy for types composed from smaller -- types. It helps to ensure that all necessary constraints are requested -- in instance head. castDummyG :: (Generic a, Generic b, GCanCastTo (Rep a) (Rep b)) => Proxy a -> Proxy b -> () -- | Locally provide bidirectional CanCastTo instance. allowCheckedCoerce :: forall k1 k2 (a :: k1) (b :: k2). Dict (CanCastTo a b, CanCastTo b a) -- | Locally provide given CanCastTo instance. allowCheckedCoerceTo :: forall k1 k2 (b :: k1) (a :: k2). Dict (CanCastTo a b) -- | Pretends that the top item of the stack was coerced. checkedCoercing_ :: forall a b (s :: [Type]). Coercible_ a b => ((b : s) :-> (b : s)) -> (a : s) :-> (a : s) -- | Coerce between types which have an explicit permission for that in the -- face of CanCastTo constraint. checkedCoerce_ :: forall a b (s :: [Type]). Castable_ a b => (a : s) :-> (b : s) -- | Coercion in Haskell world which respects CanCastTo. checkedCoerce :: (CanCastTo a b, Coercible a b) => a -> b -- | Unpack named value. fromNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (NamedF Identity a name : s) :-> (a : s) -- | Lift given value to a named value. toNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (a : s) :-> (NamedF Identity a name : s) -- | Specialized version of coerce_ to unwrap a haskell newtype. coerceUnwrap :: forall a (s :: [Type]). Wrappable a => (a : s) :-> (Unwrappable a : s) -- | Specialized version of coerce_ to wrap into a haskell -- newtype. coerceWrap :: forall a (s :: [Type]). Wrappable a => (Unwrappable a : s) :-> (a : s) fakeCoercing :: forall (s1 :: [Type]) (s2 :: [Type]) (s1' :: [Type]) (s2' :: [Type]). (s1 :-> s2) -> s1' :-> s2' -- | Convert between two stacks via failing. fakeCoerce :: forall (s1 :: [Type]) (s2 :: [Type]). s1 :-> s2 gForcedCoerce_ :: forall k t (a :: k) (b :: k) (s :: [Type]). MichelsonCoercible (t a) (t b) => (t a : s) :-> (t b : s) -- | Convert between values of types that have the same representation. -- -- This function is not safe in a sense that this allows breaking -- invariants of casted type (example: UStore) or may stop -- compile on code changes (example: coercion of pair to a datatype with -- two fields will break if new field is added). Still, produced -- Michelson code will always be valid. -- -- Prefer using one of more specific functions from this module. forcedCoerce_ :: forall a b (s :: [Type]). MichelsonCoercible a b => (a & s) :-> (b & s) -- | Whether two types have the same Michelson representation. type MichelsonCoercible a b = ToT a ~ ToT b -- | Explicitly allowed coercions. -- -- a CanCastTo b proclaims that a can be casted -- to b without violating any invariants of b. -- -- This relation is reflexive; it may be symmetric or not. It -- tends to be composable: casting complex types usually requires -- permission to cast their respective parts; for such types consider -- using castDummyG as implementation of the method of this -- typeclass. -- -- For cases when a cast from a to b requires some -- validation, consider rather making a dedicated function which performs -- the necessary checks and then calls forcedCoerce. class CanCastTo (a :: k) (b :: k1) -- | An optional method which helps passing -Wredundant-constraints check. -- Also, you can set specific implementation for it with specific sanity -- checks. castDummy :: CanCastTo a b => Proxy a -> Proxy b -> () -- | Coercion from a to b is permitted and safe. type Castable_ a b = (MichelsonCoercible a b, CanCastTo a b) -- | Coercions between a to b are permitted and safe. type Coercible_ a b = (MichelsonCoercible a b, CanCastTo a b, CanCastTo b a) -- | If you apply numeric error representation in your contract, -- errorToVal will stop working because it doesn't know about this -- transformation. This function takes this transformation into account. -- If a string is used as a tag, but it is not found in the passed map, -- we conservatively preserve that string (because this whole approach is -- rather a heuristic). errorToValNumeric :: IsError e => ErrorTagMap -> e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r -- | If you apply numeric error representation in your contract, -- errorFromVal will stop working because it doesn't know about -- this transformation. This function takes this transformation into -- account. If a number is used as a tag, but it is not found in the -- passed map, we conservatively preserve that number (because this whole -- approach is rather a heuristic). errorFromValNumeric :: forall (t :: T) e. (KnownT t, IsError e) => ErrorTagMap -> Value t -> Either Text e -- | This function implements the simplest scenario of using this module's -- functionality: 1. Gather all error tags from a single instruction. 2. -- Turn them into error conversion map. 3. Apply this conversion. useNumericErrors :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> (inp :-> out, ErrorTagMap) -- | Similar to applyErrorTagMap, but for case when you have -- excluded some tags from map via excludeErrorTags. Needed, -- because both excludeErrorTags and this function do not tolerate -- unknown errors in contract code (for your safety). applyErrorTagMapWithExclusions :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> ErrorTagExclusions -> (inp :-> out) -> inp :-> out -- | For each typical FAILWITH that uses a string to represent error -- tag this function changes error tag to be a number using the supplied -- conversion map. It assumes that supplied map contains all such strings -- (and will error out if it does not). It will always be the case if you -- gather all error tags using gatherErrorTags and build -- ErrorTagMap from them using addNewErrorTags. applyErrorTagMap :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Remove some error tags from map. This way you say to remain these -- string tags intact, while others will be converted to numbers when -- this map is applied. -- -- Note that later you have to apply this map using -- applyErrorTagMapWithExclusions, otherwise an error would be -- raised. excludeErrorTags :: HasCallStack => ErrorTagExclusions -> ErrorTagMap -> ErrorTagMap -- | Build ErrorTagMap from a set of textual tags. buildErrorTagMap :: HashSet MText -> ErrorTagMap -- | Add more error tags to an existing ErrorTagMap. It is useful -- when your contract consists of multiple parts (e. g. in case of -- contract upgrade), you have existing map for some part and want to add -- tags from another part to it. You can pass empty map as existing one -- if you just want to build ErrorTagMap from a set of textual -- tags. See buildErrorTagMap. addNewErrorTags :: ErrorTagMap -> HashSet MText -> ErrorTagMap -- | Find all textual error tags that are used in typical FAILWITH -- patterns within given instruction. Map them to natural numbers. gatherErrorTags :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> HashSet MText -- | This is a bidirectional map with correspondence between numeric and -- textual error tags. type ErrorTagMap = Bimap Natural MText -- | Tags excluded from map. type ErrorTagExclusions = HashSet MText -- | QuasiQuote that helps generating TypeHasDoc instance. -- -- Usage: -- --
--   [typeDoc| <type> <description> |]
--   [typeDoc| Storage "This is storage description"  |]
--   
-- -- See this tutorial which includes this quasiquote. typeDoc :: QuasiQuoter -- | QuasiQuote that helps generating CustomErrorHasDoc instance. -- -- Usage: -- --
--   [errorDoc| <error-name> <error-type> <error-description> |]
--   [errorDoc| "errorName" exception "Error description" |]
--   
-- -- See this tutorial which includes this quasiquote. errorDoc :: QuasiQuoter -- | QuasiQuote that helps generating ParameterHasEntrypoints -- instance. -- -- Usage: -- --
--   [entrypointDoc| Parameter <parameter-type> <optional-root-annotation> |]
--   [entrypointDoc| Parameter plain |]
--   [entrypointDoc| Parameter plain "root"|]
--   
-- -- See this tutorial which includes this quasiquote. entrypointDoc :: QuasiQuoter -- | Implementation of typeDocMdDescription (of TypeHasDoc -- typeclass) for Haskell types which sole purpose is to be error. typeDocMdDescriptionReferToError :: IsError e => Markdown errorTagToText :: forall (tag :: Symbol). KnownSymbol tag => Text -- | Demote error tag to term level. errorTagToMText :: forall (tag :: Symbol). Label tag -> MText -- | Description of error representation in Haskell. customErrorDocHaskellRepGeneral :: forall (tag :: Symbol). (SingI (ToT (ErrorArg tag)), IsError (CustomError tag), TypeHasDoc (ErrorArg tag), CustomErrorHasDoc tag) => Text -> Proxy tag -> Markdown -- | Fail, providing a reference to the place in the code where this -- function is called. -- -- Like error in Haskell code, this instruction is for internal -- errors only. failUnexpected :: forall (s :: [Type]) (t :: [Type]). MText -> s :-> t -- | Fail with the given Haskell value. failUsing :: forall e (s :: [Type]) (t :: [Type]). IsError e => e -> s :-> t -- | Implementation of errorFromVal via IsoValue. isoErrorFromVal :: forall (t :: T) e. (Typeable t, Typeable (ToT e), IsoValue e) => Value t -> Either Text e -- | Implementation of errorToVal via IsoValue. isoErrorToVal :: (KnownError e, IsoValue e) => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r type ErrorScope (t :: T) = (Typeable t, ConstantScope t) -- | Haskell type representing error. class (Typeable e, ErrorHasDoc e) => IsError e -- | Converts a Haskell error into Value representation. errorToVal :: IsError e => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r -- | Converts a Value into Haskell error. errorFromVal :: forall (t :: T). (IsError e, KnownT t) => Value t -> Either Text e -- | Constraints which we require in a particular instance. You are not -- oblidged to often instantiate this correctly, it is only useful for -- some utilities. type family ErrorRequirements e class Typeable e => ErrorHasDoc e where { -- | Constraints which we require in a particular instance. You are not -- oblidged to often instantiate this correctly, it is only useful for -- some utilities. type family ErrorRequirements e; type ErrorRequirements e = (); } -- | Name of error as it appears in the corresponding section title. errorDocName :: ErrorHasDoc e => Text -- | What should happen for this error to be raised. errorDocMdCause :: ErrorHasDoc e => Markdown -- | Brief version of errorDocMdCause. -- -- This will appear along with the error when mentioned in entrypoint -- description. By default, the first sentence of the full description is -- used. errorDocMdCauseInEntrypoint :: ErrorHasDoc e => Markdown -- | How this error is represented in Haskell. errorDocHaskellRep :: ErrorHasDoc e => Markdown -- | Error class. errorDocClass :: ErrorHasDoc e => ErrorClass -- | Which definitions documentation for this error mentions. errorDocDependencies :: ErrorHasDoc e => [SomeDocDefinitionItem] -- | Captured constraints which we require in a particular instance. This -- is a way to encode a bidirectional instance in the nowaday Haskell, -- for class MyConstraint => ErrorHasDoc MyType instance it -- lets deducing MyConstraint by ErrorHasDoc MyType. -- -- You are not oblidged to always instantiate, it is only useful for some -- utilities which otherwise would not compile. errorDocRequirements :: ErrorHasDoc e => Dict (ErrorRequirements e) -- | Use this type as replacement for () when you really -- want to leave error cause unspecified. data UnspecifiedError UnspecifiedError :: UnspecifiedError -- | Type wrapper for an IsError. data SomeError SomeError :: e -> SomeError -- | Declares a custom error, defining error name - error argument -- relation. -- -- If your error is supposed to carry no argument, then provide -- (). -- -- Note that this relation is defined globally rather than on -- per-contract basis, so define errors accordingly. If your error has -- argument specific to your contract, call it such that error name -- reflects its belonging to this contract. -- -- This is the basic [error format]. type family ErrorArg (tag :: Symbol) -- | Material custom error. -- -- Use this in pattern matches against error (e.g. in tests). data CustomError (tag :: Symbol) CustomError :: Label tag -> ErrorArg tag -> CustomError (tag :: Symbol) [ceTag] :: CustomError (tag :: Symbol) -> Label tag [ceArg] :: CustomError (tag :: Symbol) -> ErrorArg tag type RequireNoArgError (tag :: Symbol) (msg :: ErrorMessage) = (TypeErrorUnless ErrorArg tag == () msg, msg ~ 'Text "Expected no-arg error, but given error requires argument of type " :<>: 'ShowType ErrorArg tag) -- | Error class on how the error should be handled by the client. data ErrorClass -- | Normal expected error. Examples: "insufficient balance", "wallet does -- not exist". ErrClassActionException :: ErrorClass -- | Invalid argument passed to entrypoint. Examples: your entrypoint -- accepts an enum represented as nat, and unknown value is -- provided. This includes more complex cases which involve multiple -- entrypoints. E.g. API provides iterator interface, middleware should -- care about using it hiding complex details and exposing a simpler API -- to user; then an attempt to request non-existing element would also -- correspond to an error from this class. ErrClassBadArgument :: ErrorClass -- | Unexpected error. Most likely it means that there is a bug in the -- contract or the contract has been deployed incorrectly. ErrClassContractInternal :: ErrorClass -- | It's possible to leave error class unspecified. ErrClassUnknown :: ErrorClass class (KnownSymbol tag, TypeHasDoc ErrorArg tag, IsError CustomError tag) => CustomErrorHasDoc (tag :: Symbol) -- | What should happen for this error to be raised. customErrDocMdCause :: CustomErrorHasDoc tag => Markdown -- | Brief version of customErrDocMdCause. This will appear along -- with the error when mentioned in entrypoint description. -- -- By default, the first sentence of the full description is used. customErrDocMdCauseInEntrypoint :: CustomErrorHasDoc tag => Markdown -- | Error class. -- -- By default this returns "unknown error" class; though you should -- provide explicit implementation in order to avoid a warning. customErrClass :: CustomErrorHasDoc tag => ErrorClass -- | Clarification of error argument meaning. -- -- Provide when it's not obvious, e.g. argument is not named with -- :!. -- -- NOTE: This should not be an entire sentence, rather just the -- semantic backbone. -- -- Bad: * Error argument stands for the previous value of -- approval. -- -- Good: * the previous value of approval * pair, first -- argument of which is one thing, and the second is another customErrArgumentSemantics :: CustomErrorHasDoc tag => Maybe Markdown -- | Mentions that contract uses given error. data DError [DError] :: forall e. ErrorHasDoc e => Proxy e -> DError -- | Documentation for custom errors. -- -- Mentions that entrypoint throws given error. data DThrows [DThrows] :: forall e. ErrorHasDoc e => Proxy e -> DThrows mkDEntrypointExample :: NiceParameter a => a -> DEntrypointExample -- | Leave only instructions related to documentation. -- -- This function is useful when your method executes a lambda coming from -- outside, but you know its properties and want to propagate its -- documentation to your contract code. cutLorentzNonDoc :: forall (inp :: [Type]) (out :: [Type]) (s :: [Type]). (inp :-> out) -> s :-> s renderLorentzDocWithGitRev :: forall (inp :: [Type]) (out :: [Type]). DGitRevision -> (inp :-> out) -> LText renderLorentzDoc :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> LText buildLorentzDocWithGitRev :: forall (inp :: [Type]) (out :: [Type]). DGitRevision -> (inp :-> out) -> ContractDoc buildLorentzDoc :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> ContractDoc -- | Modify the example value of an entrypoint data DEntrypointExample DEntrypointExample :: Value t -> DEntrypointExample -- | Remove element with the given type from the stack. dropT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). (DipT inp a inp dinp dout out, dinp ~ (a : dout)) => inp :-> out -- | Dip repeatedly until element of the given type is on top of the stack. -- -- If stack contains multiple entries of this type, compile error is -- raised. dipT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). DipT inp a inp dinp dout out => (dinp :-> dout) -> inp :-> out -- | Duplicate an element of stack referring it by type. -- -- If stack contains multiple entries of this type, compile error is -- raised. dupT :: forall a (st :: [Type]). DupT st a st => st :-> (a : st) class NonZero t -- | Pretty-print a Lorentz contract into Michelson code. printLorentzContract :: (NiceParameterFull cp, NiceStorage st) => Bool -> Contract cp st -> LText -- | Pretty-print a Haskell value as Michelson one. printLorentzValue :: NicePrintedValue v => Bool -> v -> LText -- | Lorentz version of analyzer. analyzeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> AnalyzerRes -- | Like interpretLorentzInstr, but works on lambda rather than -- arbitrary instruction. interpretLorentzLambda :: (IsoValue inp, IsoValue out) => ContractEnv -> Lambda inp out -> inp -> Either MichelsonFailed out -- | Interpret a Lorentz instruction, for test purposes. Note that this -- does not run the optimizer. interpretLorentzInstr :: forall (inp :: [Type]) (out :: [Type]). (IsoValuesStack inp, IsoValuesStack out) => ContractEnv -> (inp :-> out) -> Rec Identity inp -> Either MichelsonFailed (Rec Identity out) -- | Compile a whole contract to Michelson. -- -- Note that compiled contract can be ill-typed in terms of Michelson -- code when some of the compilation options are used (e.g. when -- ccoDisableInitialCast is True, resulted contract can -- be ill-typed). However, compilation with -- defaultContractCompilationOptions should be valid. compileLorentzContract :: (NiceParameterFull cp, NiceStorage st) => Contract cp st -> Contract (ToT cp) (ToT st) -- | Compile contract with defaultCompilationOptions and -- cDisableInitialCast set to False. defaultContract :: ContractCode cp st -> Contract cp st -- | Compile Lorentz code, optionally running the optimizer, string and -- byte transformers. compileLorentzWithOptions :: forall (inp :: [Type]) (out :: [Type]). CompilationOptions -> (inp :-> out) -> Instr (ToTs inp) (ToTs out) -- | For use outside of Lorentz. Will use defaultCompilationOptions. compileLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) -- | Runs Michelson optimizer with default config and does not touch -- strings and bytes. defaultCompilationOptions :: CompilationOptions -- | Options to control Lorentz to Michelson compilation. data CompilationOptions CompilationOptions :: Maybe OptimizerConf -> (Bool, MText -> MText) -> (Bool, ByteString -> ByteString) -> CompilationOptions -- | Config for Michelson optimizer. [coOptimizerConf] :: CompilationOptions -> Maybe OptimizerConf -- | Function to transform strings with. See -- transformStringsLorentz. [coStringTransformer] :: CompilationOptions -> (Bool, MText -> MText) -- | Function to transform byte strings with. See -- transformBytesLorentz. [coBytesTransformer] :: CompilationOptions -> (Bool, ByteString -> ByteString) -- | Wrap parameter into this to locally assign a way to derive entrypoints -- for it. newtype ParameterWrapper deriv cp ParameterWrapper :: cp -> ParameterWrapper deriv cp [unParameterWraper] :: ParameterWrapper deriv cp -> cp type family Unwrappable s -- | Wrappable is similar to lens Wrapped class without the -- method. It provides type family that is mainly used as constraint when -- unwrapping Lorentz instruction into a Haskell newtype and vice versa. class ToT s ~ ToT Unwrappable s => Wrappable s where { type family Unwrappable s; type Unwrappable s = GUnwrappable Rep s; } type family ArithResHs aop n m -- | Lifted ArithOp. class (ArithOp aop ToT n ToT m, NiceComparable n, NiceComparable m, ToT ArithResHs aop n m ~ ArithRes aop ToT n ToT m) => ArithOpHs aop n m where { type family ArithResHs aop n m; } type family UnaryArithResHs aop n -- | Lifted UnaryArithOp. class (UnaryArithOp aop ToT n, NiceComparable n, ToT UnaryArithResHs aop n ~ UnaryArithRes aop ToT n) => UnaryArithOpHs aop n where { type family UnaryArithResHs aop n; } -- | Implementation of ParameterHasEntrypoints which fits for case -- when your contract exposes multiple entrypoints via having sum type as -- its parameter. -- -- In particular, each constructor would produce a homonymous entrypoint -- with argument type equal to type of constructor field (each -- constructor should have only one field). Constructor called -- Default will designate the default entrypoint. data EpdPlain -- | Extension of EpdPlain on parameters being defined as several -- nested datatypes. -- -- In particular, this will traverse sum types recursively, stopping at -- Michelson primitives (like Natural) and constructors with -- number of fields different from one. -- -- It does not assign names to intermediate nodes of Or tree, only -- to the very leaves. -- -- If some entrypoint arguments have custom IsoValue instance, -- this derivation way will not work. As a workaround, you can wrap your -- argument into some primitive (e.g. :!). data EpdRecursive -- | Extension of EpdPlain on parameters being defined as several -- nested datatypes. -- -- In particular, it will traverse the immediate sum type, and require -- another ParameterHasEntrypoints for the inner complex -- datatypes. Only those inner types are considered which are the only -- fields in their respective constructors. Inner types should not -- themselves declare default entrypoint, we enforce this for better -- modularity. Each top-level constructor will be treated as entrypoint -- even if it contains a complex datatype within, in such case that would -- be an entrypoint corresponding to intermediate node in or -- tree. -- -- Comparing to EpdRecursive this gives you more control over -- where and how entrypoints will be derived. data EpdDelegate -- | Extension of EpdPlain, EpdRecursive, and -- EpdDelegate which allow specifying root annotation for the -- parameters. data EpdWithRoot (r :: Symbol) (epd :: k) type List = [] type family MemOpKeyHs c -- | Lifted MemOpKey. class (MemOp ToT c, ToT MemOpKeyHs c ~ MemOpKey ToT c) => MemOpHs c where { type family MemOpKeyHs c; } -- | A useful property which holds for reasonable MapOp instances. -- -- It's a separate thing from MapOpHs because it mentions -- b type parameter. type family IsoMapOpRes c b type family MapOpResHs c :: Type -> Type type family MapOpInpHs c -- | Lifted MapOp. class (MapOp ToT c, ToT MapOpInpHs c ~ MapOpInp ToT c, ToT MapOpResHs c () ~ MapOpRes ToT c ToT ()) => MapOpHs c where { type family MapOpInpHs c; type family MapOpResHs c :: Type -> Type; } type family IterOpElHs c -- | Lifted IterOp. class (IterOp ToT c, ToT IterOpElHs c ~ IterOpEl ToT c) => IterOpHs c where { type family IterOpElHs c; } -- | Lifted SizeOp. -- -- This could be just a constraint alias, but to avoid T types -- appearance in error messages we make a full type class with concrete -- instances. class SizeOp ToT c => SizeOpHs c type family UpdOpParamsHs c type family UpdOpKeyHs c -- | Lifted UpdOp. class (UpdOp ToT c, ToT UpdOpKeyHs c ~ UpdOpKey ToT c, ToT UpdOpParamsHs c ~ UpdOpParams ToT c) => UpdOpHs c where { type family UpdOpKeyHs c; type family UpdOpParamsHs c; } type family GetOpValHs c type family GetOpKeyHs c -- | Lifted GetOp. class (GetOp ToT c, ToT GetOpKeyHs c ~ GetOpKey ToT c, ToT GetOpValHs c ~ GetOpVal ToT c) => GetOpHs c where { type family GetOpKeyHs c; type family GetOpValHs c; } -- | Lifted ConcatOp. class ConcatOp ToT c => ConcatOpHs c -- | Lifted SliceOp. class SliceOp ToT c => SliceOpHs c type family EModOpResHs n m type family EDivOpResHs n m -- | Lifted EDivOp. class (EDivOp ToT n ToT m, NiceComparable n, NiceComparable m, ToT EDivOpResHs n m ~ EDivOpRes ToT n ToT m, ToT EModOpResHs n m ~ EModOpRes ToT n ToT m) => EDivOpHs n m where { type family EDivOpResHs n m; type family EModOpResHs n m; } -- | Similar to valueToScriptExpr, but for values encoded as -- Expressions. This is only used in tests. expressionToScriptExpr :: Expression -> ByteString -- | This function transforms Lorentz values into script_expr. -- -- script_expr is used in RPC as an argument in entrypoint -- designed for getting value by key from the big_map in Babylon. In -- order to convert value to the script_expr we have to pack it, -- take blake2b hash and add specific expr prefix. Take a look -- at -- https://gitlab.com/tezos/tezos/blob/6e25ae8eb385d9975a30388c7a7aa2a9a65bf184/src/proto_005_PsBabyM1/lib_protocol/script_expr_hash.ml -- and -- https://gitlab.com/tezos/tezos/blob/6e25ae8eb385d9975a30388c7a7aa2a9a65bf184/src/proto_005_PsBabyM1/lib_protocol/contract_services.ml#L136 -- for more information. valueToScriptExpr :: NicePackedValue t => t -> ByteString lEncodeValue :: NicePrintedValue a => a -> ByteString lUnpackValue :: NiceUnpackedValue a => ByteString -> Either UnpackError a lPackValue :: NicePackedValue a => a -> ByteString stackType :: forall (s :: [Type]). s :-> s testAssert :: forall (out :: [Type]) (inp :: [Type]). (Typeable (ToTs out), HasCallStack) => Text -> PrintComment (ToTs inp) -> (inp :-> (Bool & out)) -> inp :-> inp printComment :: forall (s :: [Type]). PrintComment (ToTs s) -> s :-> s stackRef :: forall (gn :: Nat) (st :: [T]) (n :: Peano). (n ~ ToPeano gn, SingI n, KnownPeano n, RequireLongerThan st n) => PrintComment st convertContractRef :: forall cp contract2 contract1. (ToContractRef cp contract1, FromContractRef cp contract2) => contract1 -> contract2 -- | Specification of callTAddress to call the default entrypoint. callingDefTAddress :: NiceParameterFull cp => TAddress cp -> ContractRef (GetDefaultEntrypointArg cp) -- | Turn TAddress to ContractRef in Haskell world. -- -- This is an analogy of address to contract convertion -- in Michelson world, thus you have to supply an entrypoint (or call the -- default one explicitly). callingTAddress :: forall cp (mname :: Maybe Symbol). NiceParameterFull cp => TAddress cp -> EntrypointRef mname -> ContractRef (GetEntrypointArgCustom cp mname) -- | Address which remembers the parameter type of the contract it refers -- to. -- -- It differs from Michelson's contract type because it cannot -- contain entrypoint, and it always refers to entire contract parameter -- even if this contract has explicit default entrypoint. newtype TAddress (p :: k) TAddress :: Address -> TAddress (p :: k) [unTAddress] :: TAddress (p :: k) -> Address -- | Address associated with value of contract arg type. -- -- Places where ContractRef can appear are now severely limited, -- this type gives you type-safety of ContractRef but still can be -- used everywhere. This type is not a full-featured one rather a helper; -- in particular, once pushing it on stack, you cannot return it back to -- Haskell world. -- -- Note that it refers to an entrypoint of the contract, not just the -- contract as a whole. In this sense this type differs from -- TAddress. -- -- Unlike with ContractRef, having this type you still cannot be -- sure that the referred contract exists and need to perform a lookup -- before calling it. newtype FutureContract arg FutureContract :: ContractRef arg -> FutureContract arg [unFutureContract] :: FutureContract arg -> ContractRef arg -- | Convert something to Address in Haskell world. -- -- Use this when you want to access state of the contract and are not -- interested in calling it. class ToAddress a toAddress :: ToAddress a => a -> Address -- | Convert something referring to a contract (not specific entrypoint) to -- TAddress in Haskell world. class ToTAddress cp a toTAddress :: ToTAddress cp a => a -> TAddress cp -- | Convert something to ContractRef in Haskell world. class ToContractRef cp contract toContractRef :: ToContractRef cp contract => contract -> ContractRef cp -- | Convert something from ContractAddr in Haskell world. class FromContractRef cp contract fromContractRef :: FromContractRef cp contract => ContractRef cp -> contract -- | Single entrypoint of a contract. -- -- Note that we cannot make it return [[Operation], store] -- because such entrypoint should've been followed by pair, and -- this is not possible if entrypoint implementation ends with -- failWith. type Entrypoint param store = '[param, store] :-> ContractOut store -- | Version of Entrypoint which accepts no argument. type Entrypoint_ store = '[store] :-> ContractOut store optimizeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> inp :-> out optimizeLorentzWithConf :: forall (inp :: [Type]) (out :: [Type]). OptimizerConf -> (inp :-> out) -> inp :-> out -- | Lorentz version of transformBytes. transformBytesLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (ByteString -> ByteString) -> (inp :-> out) -> inp :-> out -- | Lorentz version of transformStrings. transformStringsLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (MText -> MText) -> (inp :-> out) -> inp :-> out -- | Parse textual representation of a Michelson value and turn it into -- corresponding Haskell value. -- -- Note: it won't work in some complex cases, e. g. if there is a lambda -- which uses an instruction which depends on current contract's type. -- Obviously it can not work, because we don't have any information about -- a contract to which this value belongs (there is no such contract at -- all). parseLorentzValue :: KnownValue v => Text -> Either ParseLorentzError v -- | Version of # which performs some optimizations immediately. (##) :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]). (a :-> b) -> (b :-> c) -> a :-> c (#) :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]). (a :-> b) -> (b :-> c) -> a :-> c infixl 8 # -- | Wrap Lorentz instruction with variable annotations, annots -- list has to be non-empty, otherwise this function raises an error. iWithVarAnnotations :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [Text] -> (inp :-> out) -> inp :-> out iForceNotFail :: forall (i :: [Type]) (o :: [Type]). (i :-> o) -> i :-> o iMapAnyCode :: forall (i1 :: [Type]) (i2 :: [Type]) (o :: [Type]). (forall (o' :: [T]). () => Instr (ToTs i1) o' -> Instr (ToTs i2) o') -> (i1 :-> o) -> i2 :-> o iNonFailingCode :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> Instr (ToTs inp) (ToTs out) iAnyCode :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) iGenericIf :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]) (s :: [Type]). (forall (s' :: [T]). () => Instr (ToTs a) s' -> Instr (ToTs b) s' -> Instr (ToTs c) s') -> (a :-> s) -> (b :-> s) -> c :-> s pattern I :: Instr (ToTs inp) (ToTs out) -> inp :-> out pattern FI :: (forall (out' :: [T]). () => Instr (ToTs inp) out') -> inp :-> out -- | Alias for instruction which hides inner types representation via -- T. newtype (inp :: [Type]) :-> (out :: [Type]) LorentzInstr :: RemFail Instr (ToTs inp) (ToTs out) -> (:->) (inp :: [Type]) (out :: [Type]) [unLorentzInstr] :: (:->) (inp :: [Type]) (out :: [Type]) -> RemFail Instr (ToTs inp) (ToTs out) infixr 1 :-> -- | Alias for :->, seems to make signatures more readable -- sometimes. -- -- Let's someday decide which one of these two should remain. type (%>) = (:->) infixr 1 %> type ContractOut st = '[([Operation], st)] type ContractCode cp st = '[(cp, st)] :-> ContractOut st data SomeContractCode [SomeContractCode] :: forall cp st. (NiceParameterFull cp, NiceStorage st) => ContractCode cp st -> SomeContractCode type a & (b :: [Type]) = a : b infixr 2 & type Lambda i o = '[i] :-> '[o] -- | Applicable for wrappers over Lorentz code. class MapLorentzInstr instr -- | Modify all the code under given entity. mapLorentzInstr :: MapLorentzInstr instr => (forall (i :: [Type]) (o :: [Type]). () => (i :-> o) -> i :-> o) -> instr -> instr -- | Constraint applied to a whole parameter type. type NiceParameterFull cp = (Typeable cp, ParameterDeclaresEntrypoints cp) -- | Universal entrypoint calling. parameterEntrypointCallCustom :: forall cp (mname :: Maybe Symbol). ParameterDeclaresEntrypoints cp => EntrypointRef mname -> EntrypointCall cp (GetEntrypointArgCustom cp mname) eprName :: forall (mname :: Maybe Symbol). EntrypointRef mname -> EpName -- | Call root entrypoint safely. sepcCallRootChecked :: (NiceParameter cp, ForbidExplicitDefaultEntrypoint cp) => SomeEntrypointCall cp -- | Call the default entrypoint. parameterEntrypointCallDefault :: ParameterDeclaresEntrypoints cp => EntrypointCall cp (GetDefaultEntrypointArg cp) -- | Prepare call to given entrypoint. -- -- This does not treat calls to default entrypoint in a special way. To -- call default entrypoint properly use -- parameterEntrypointCallDefault. parameterEntrypointCall :: forall cp (name :: Symbol). ParameterDeclaresEntrypoints cp => Label name -> EntrypointCall cp (GetEntrypointArg cp name) -- | Derive annotations for given parameter. parameterEntrypointsToNotes :: ParameterDeclaresEntrypoints cp => ParamNotes (ToT cp) -- | Get entrypoint argument by name. type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type -- | Name and argument of each entrypoint. This may include intermediate -- ones, even root if necessary. -- -- Touching this type family is costly (O(N^2)), don't use it -- often. -- -- Note [order of entrypoints children]: If this contains entrypoints -- referring to indermediate nodes (not leaves) in or tree, then -- each such entrypoint should be mentioned eariler than all of its -- children. type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)] -- | Defines a generalized way to declare entrypoints for various parameter -- types. -- -- When defining instances of this typeclass, set concrete deriv -- argument and leave variable cp argument. Also keep in mind, -- that in presence of explicit default entrypoint, all other Or -- arms should be callable, though you can put this burden on user if -- very necessary. -- -- Methods of this typeclass aim to better type-safety when making up an -- implementation and they may be not too convenient to use; users should -- exploit their counterparts. class EntrypointsDerivation (deriv :: k) cp where { -- | Name and argument of each entrypoint. This may include intermediate -- ones, even root if necessary. -- -- Touching this type family is costly (O(N^2)), don't use it -- often. -- -- Note [order of entrypoints children]: If this contains entrypoints -- referring to indermediate nodes (not leaves) in or tree, then -- each such entrypoint should be mentioned eariler than all of its -- children. type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)]; -- | Get entrypoint argument by name. type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type; } -- | Construct parameter annotations corresponding to expected entrypoints -- set. -- -- This method is implementation detail, for actual notes construction -- use parameterEntrypointsToNotes. epdNotes :: EntrypointsDerivation deriv cp => (Notes (ToT cp), RootAnn) -- | Construct entrypoint caller. -- -- This does not treat calls to default entrypoint in a special way. -- -- This method is implementation detail, for actual entrypoint lookup use -- parameterEntrypointCall. epdCall :: forall (name :: Symbol). (EntrypointsDerivation deriv cp, ParameterScope (ToT cp)) => Label name -> EpConstructionRes (ToT cp) (Eval (EpdLookupEntrypoint deriv cp name)) -- | Description of how each of the entrypoints is constructed. epdDescs :: EntrypointsDerivation deriv cp => Rec EpCallingDesc (EpdAllEntrypoints deriv cp) -- | Ensure that all declared entrypoints are unique. type RequireAllUniqueEntrypoints cp = RequireAllUniqueEntrypoints' ParameterEntrypointsDerivation cp cp type family ParameterEntrypointsDerivation cp -- | Which entrypoints given parameter declares. -- -- Note that usually this function should not be used as constraint, use -- ParameterDeclaresEntrypoints for this purpose. class (EntrypointsDerivation ParameterEntrypointsDerivation cp cp, RequireAllUniqueEntrypoints cp) => ParameterHasEntrypoints cp where { type family ParameterEntrypointsDerivation cp; } -- | Parameter declares some entrypoints. -- -- This is a version of ParameterHasEntrypoints which we actually -- use in constraints. When given type is a sum type or newtype, we refer -- to ParameterHasEntrypoints instance, otherwise this instance is -- not necessary. type ParameterDeclaresEntrypoints cp = (If CanHaveEntrypoints cp ParameterHasEntrypoints cp (), NiceParameter cp, EntrypointsDerivation GetParameterEpDerivation cp cp) -- | Get all entrypoints declared for parameter. type family AllParameterEntrypoints cp :: [(Symbol, Type)] -- | Lookup for entrypoint type by name. -- -- Does not treat default entrypoints in a special way. type family LookupParameterEntrypoint cp :: Symbol -> Exp Maybe Type -- | Get type of entrypoint with given name, fail if not found. type GetEntrypointArg cp (name :: Symbol) = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type TError 'Text "Entrypoint not found: " :<>: 'ShowType name :$$: 'Text "In contract parameter `" :<>: 'ShowType cp :<>: 'Text "`" :: Type -> Type LookupParameterEntrypoint cp name -- | Get type of entrypoint with given name, fail if not found. type GetDefaultEntrypointArg cp = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type Pure cp LookupParameterEntrypoint cp DefaultEpName -- | Ensure that there is no explicit "default" entrypoint. type ForbidExplicitDefaultEntrypoint cp = Eval LiftM3 UnMaybe :: Exp Constraint -> Type -> Exp Constraint -> Maybe Type -> Constraint -> Type Pure Pure () TError 'Text "Parameter used here must have no explicit \"default\" entrypoint" :$$: 'Text "In parameter type `" :<>: 'ShowType cp :<>: 'Text "`" :: Type -> Exp Constraint -> Type LookupParameterEntrypoint cp DefaultEpName -- | Similar to ForbidExplicitDefaultEntrypoint, but in a version -- which the compiler can work with (and which produces errors confusing -- for users :/) type NoExplicitDefaultEntrypoint cp = Eval LookupParameterEntrypoint cp DefaultEpName ~ 'Nothing :: Maybe Type -- | Which entrypoint to call. -- -- We intentionally distinguish default and non-default cases because -- this makes API more details-agnostic. data EntrypointRef (mname :: Maybe Symbol) -- | Call the default entrypoint, or root if no explicit default is -- assigned. [CallDefault] :: EntrypointRef ('Nothing :: Maybe Symbol) -- | Call the given entrypoint; calling default is not treated specially. -- You have to provide entrypoint name via passing it as type argument. -- -- Unfortunatelly, here we cannot accept a label because in most cases -- our entrypoints begin from capital letter (being derived from -- constructor name), while labels must start from a lower-case letter, -- and there is no way to make a conversion at type-level. [Call] :: forall (name :: Symbol). NiceEntrypointName name => EntrypointRef ('Just name) -- | Universal entrypoint lookup. type family GetEntrypointArgCustom cp (mname :: Maybe Symbol) -- | When we call a Lorentz contract we should pass entrypoint name and -- corresponding argument. Ideally we want to statically check that -- parameter has entrypoint with given name and argument. Constraint -- defined by this type class holds for contract with parameter -- cp that have entrypoint matching name with type -- arg. -- -- In order to check this property statically, we need to know entrypoint -- name in compile time, EntrypointRef type serves this purpose. -- If entrypoint name is not known, one can use TrustEpName -- wrapper to take responsibility for presence of this entrypoint. -- -- If you want to call a function which has this constraint, you have two -- options: 1. Pass contract parameter cp using type -- application, pass EntrypointRef as a value and pass entrypoint -- argument. Type system will check that cp has an entrypoint -- with given reference and type. 2. Pass EpName wrapped into -- TrustEpName and entrypoint argument. In this case passing -- contract parameter is not necessary, you do not even have to know it. class HasEntrypointArg (cp :: k) name arg -- | Data returned by this method may look somewhat arbitrary. -- EpName is obviously needed because name can be -- EntrypointRef or TrustEpName. Dict is returned -- because in EntrypointRef case we get this evidence for free and -- don't want to use it. We seem to always need it anyway. useHasEntrypointArg :: HasEntrypointArg cp name arg => name -> (Dict (ParameterScope (ToT arg)), EpName) -- | HasEntrypointArg constraint specialized to default entrypoint. type HasDefEntrypointArg (cp :: k) defEpName defArg = (defEpName ~ EntrypointRef 'Nothing :: Maybe Symbol, HasEntrypointArg cp defEpName defArg) -- | This wrapper allows to pass untyped EpName and bypass checking -- that entrypoint with given name and type exists. newtype TrustEpName TrustEpName :: EpName -> TrustEpName -- | Checks that the given parameter consists of some specific entrypoint. -- Similar as HasEntrypointArg but ensures that the argument -- matches the following datatype. type HasEntrypointOfType param (con :: Symbol) exp = (GetEntrypointArgCustom param 'Just con ~ exp, ParameterDeclaresEntrypoints param) type (n :: Symbol) :> ty = 'NamedEp n ty infixr 0 :> -- | Check that the given entrypoint has some fields inside. This interface -- allows for an abstraction of contract parameter so that it requires -- some *minimal* specification, but not a concrete one. type family ParameterContainsEntrypoints param (fields :: [NamedEp]) -- | No entrypoints declared, parameter type will serve as argument type of -- the only existing entrypoint (default one). data EpdNone nicePrintedValueEvi :: NicePrintedValue a :- PrintedValScope (ToT a) niceUnpackedValueEvi :: NiceUnpackedValue a :- UnpackedValScope (ToT a) nicePackedValueEvi :: NicePackedValue a :- PackedValScope (ToT a) niceConstantEvi :: NiceConstant a :- ConstantScope (ToT a) niceStorageEvi :: NiceStorage a :- StorageScope (ToT a) niceParameterEvi :: NiceParameter a :- ParameterScope (ToT a) -- | Gathers constraints, commonly required for values. class (IsoValue a, Typeable a) => KnownValue a -- | Ensure given type does not contain "operation". class (IsoValue a, ForbidOp ToT a) => NoOperation a class (IsoValue a, ForbidContract ToT a) => NoContractType a class (IsoValue a, ForbidBigMap ToT a) => NoBigMap a class (IsoValue a, HasNoNestedBigMaps ToT a) => CanHaveBigMap a -- | Constraint applied to any part of parameter type. -- -- Note that you don't usually apply this constraint to the whole -- parameter, consider using NiceParameterFull in such case. -- -- Using this type is justified e.g. when calling another contract, there -- you usually supply an entrypoint argument, not the whole parameter. type NiceParameter a = (KnownValue a, ProperParameterBetterErrors ToT a) type NiceStorage a = (HasAnnotation a, KnownValue a, ProperStorageBetterErrors ToT a) type NiceConstant a = (KnownValue a, ProperConstantBetterErrors ToT a) type NicePackedValue a = (KnownValue a, ProperPackedValBetterErrors ToT a) type NiceUnpackedValue a = (KnownValue a, ProperUnpackedValBetterErrors ToT a) type NiceFullPackedValue a = (NicePackedValue a, NiceUnpackedValue a) type NicePrintedValue a = (KnownValue a, ProperPrintedValBetterErrors ToT a) type NiceComparable n = (KnownValue n, Comparable ToT n) -- | This class defines the type and field annotations for a given type. -- Right now the type annotations come from names in a named field, and -- field annotations are generated from the record fields. class HasAnnotation a -- | A special type which wraps over a primitive type and states that it -- has entrypoints (one). -- -- Assuming that any type can have entrypoints makes use of Lorentz -- entrypoints too annoying, so for declaring entrypoints for not sum -- types we require an explicit wrapper. newtype ShouldHaveEntrypoints a ShouldHaveEntrypoints :: a -> ShouldHaveEntrypoints a [unHasEntrypoints] :: ShouldHaveEntrypoints a -> a -- | In this strategy the desired depths of contructors (in the type tree) -- and fields (in each constructor's tree) are provided manually and -- simply checked against the number of actual constructors and fields. withDepths :: [CstrDepth] -> GenericStrategy -- | Strategy to make right-balanced instances (both in constructors and -- fields). rightBalanced :: GenericStrategy -- | Strategy to make left-balanced instances (both in constructors and -- fields). leftBalanced :: GenericStrategy -- | Strategy to make fully right-leaning instances (both in constructors -- and fields). rightComb :: GenericStrategy -- | Strategy to make fully left-leaning instances (both in constructors -- and fields). leftComb :: GenericStrategy -- | Helper for making a constructor depth. -- -- Note that this is only intended to be more readable than directly -- using a tuple with withDepths and for the ability to be used in -- places where RebindableSyntax overrides the number literal -- resolution. cstr :: forall (n :: Nat). KnownNat n => [Natural] -> CstrDepth -- | Helper for making a field depth. -- -- Note that this is only intended to be more readable than directly -- using a tuple with withDepths and for the ability to be used in -- places where RebindableSyntax overrides the number literal -- resolution. fld :: forall (n :: Nat). KnownNat n => Natural customGeneric :: String -> GenericStrategy -> Q [Dec] -- | A piece of markdown document. -- -- This is opposed to Text type, which in turn is not supposed to -- contain markup elements. type Markdown = Builder -- | Proxy for a label type that includes the KnownSymbol constraint data Label (name :: Symbol) [Label] :: forall (name :: Symbol). KnownSymbol name => Label name -- | Entrypoint name. -- -- There are two properties we care about: -- --
    --
  1. Special treatment of the default entrypoint name. -- default is prohibited in the CONTRACT instruction -- and in values of address and contract types. -- However, it is not prohibited in the SELF instruction. Hence, -- the value inside EpName can be "default", so -- that we can distinguish SELF and SELF %default. It -- is important to distinguish them because their binary representation -- that is inserted into blockchain is different. For example, -- typechecking SELF %default consumes more gas than -- SELF. In this module, we provide several smart constructors -- with different handling of default, please use the -- appropriate one for your use case.
  2. --
  3. The set of permitted characters. Intuitively, an entrypoint name -- should be valid only if it is a valid annotation (because entrypoints -- are defined using field annotations). However, it is not enforced in -- Tezos. It is not clear whether this behavior is intended. There is an -- upstream issue which received bug label, so probably -- it is considered a bug. Currently we treat it as a bug and deviate -- from upstream implementation by probiting entrypoint names that are -- not valid annotations. If Tezos developers fix it soon, we will be -- happy. If they don't, we should (maybe temporarily) remove this -- limitation from our code. There is an issue in our repo as -- well.
  4. --
data EpName -- | This is a bidirectional pattern that can be used for two purposes: -- --
    --
  1. Construct an EpName referring to the default -- entrypoint.
  2. --
  3. Use it in pattern-matching or in equality comparison to check -- whether EpName refers to the default entrypoint. This is -- trickier because there are two possible EpName values referring -- to the default entrypoints. DefEpName will match only the most -- common one (no entrypoint). However, there is a special case: -- SELF instruction can have explicit %default -- reference. For this reason, it is recommended to use -- isDefEpName instead. Pattern-matching on DefEpName is -- still permitted for backwards compatibility and for the cases when you -- are sure that EpName does not come from the SELF -- instruction.
  4. --
pattern DefEpName :: EpName -- | Michelson string value. -- -- This is basically a mere text with limits imposed by the language: -- https://tezos.gitlab.io/whitedoc/michelson.html#constants -- Although, this document seems to be not fully correct, and thus we -- applied constraints deduced empirically. -- -- You construct an item of this type using one of the following ways: -- -- -- --
--   >>> [mt|Some text|]
--   MTextUnsafe { unMText = "Some text" }
--   
-- -- data MText -- | QuasyQuoter for constructing Michelson strings. -- -- Validity of result will be checked at compile time. Note: -- -- mt :: QuasiQuoter -- | Blake2b_160 hash of a public key. data KeyHash -- | Cryptographic signatures used by Tezos. Constructors correspond to -- PublicKey constructors. -- -- Tezos distinguishes signatures for different curves. For instance, -- ed25519 signatures and secp256k1 signatures are printed differently -- (have different prefix). However, signatures are packed without -- information about the curve. For this purpose there is a generic -- signature which only stores bytes and doesn't carry information about -- the curve. Apparently unpacking from bytes always produces such -- signature. Unpacking from string produces a signature with curve -- information. data Signature -- | Public cryptographic key used by Tezos. There are three cryptographic -- curves each represented by its own constructor. data PublicKey -- | Identifier of a network (babylonnet, mainnet, test network or other). -- Evaluated as hash of the genesis block. -- -- The only operation supported for this type is packing. Use case: -- multisig contract, for instance, now includes chain ID into signed -- data "in order to add extra replay protection between the main chain -- and the test chain". data ChainId -- | Time in the real world. Use the functions below to convert it to/from -- Unix time in seconds. data Timestamp -- | Mutez is a wrapper over integer data type. 1 mutez is 1 token (μTz). data Mutez -- | Safely create Mutez. -- -- This is recommended way to create Mutez from a numeric -- literal; you can't construct all valid Mutez values using -- this function but for small values it works neat. -- -- Warnings displayed when trying to construct invalid Natural or -- Word literal are hardcoded for these types in GHC -- implementation, so we can only exploit these existing rules. toMutez :: Word32 -> Mutez zeroMutez :: Mutez oneMutez :: Mutez timestampFromSeconds :: Integer -> Timestamp timestampFromUTCTime :: UTCTime -> Timestamp -- | Quote a value of type Timestamp in -- yyyy-mm-ddThh:mm:ss[.sss]Z format. -- --
--   >>> formatTimestamp [timestampQuote| 2019-02-21T16:54:12.2344523Z |]
--   "2019-02-21T16:54:12Z"
--   
-- -- Inspired by 'time-quote' library. timestampQuote :: QuasiQuoter -- | Data type corresponding to address structure in Tezos. data Address mkUType :: forall (x :: T). SingI x => Notes x -> Type -- | Address with optional entrypoint name attached to it. TODO: come up -- with better name? data EpAddress EpAddress :: Address -> EpName -> EpAddress -- | Address itself [eaAddress] :: EpAddress -> Address -- | Entrypoint name (might be empty) [eaEntrypoint] :: EpAddress -> EpName -- | Keeps documentation gathered for some piece of contract code. -- -- Used for building documentation of a contract. data ContractDoc ContractDoc :: DocBlock -> DocBlock -> Set SomeDocDefinitionItem -> Set DocItemId -> ContractDoc -- | All inlined doc items. [cdContents] :: ContractDoc -> DocBlock -- | Definitions used in document. -- -- Usually you put some large and repetitive descriptions here. This -- differs from the document content in that it contains sections which -- are always at top-level, disregard the nesting. -- -- All doc items which define docItemId method go here, and only -- they. [cdDefinitions] :: ContractDoc -> DocBlock -- | We remember all already declared entries to avoid cyclic dependencies -- in documentation items discovery. [cdDefinitionsSet] :: ContractDoc -> Set SomeDocDefinitionItem -- | We remember all already used identifiers. (Documentation naturally -- should not declare multiple items with the same identifier because -- that would make references to the respective anchors ambiguous). [cdDefinitionIds] :: ContractDoc -> Set DocItemId -- | A part of documentation to be grouped. Essentially incapsulates -- DocBlock. newtype SubDoc SubDoc :: DocBlock -> SubDoc -- | Several doc items of the same type. data DocSection DocSection :: (NonEmpty $ DocElem d) -> DocSection -- | A doc item which we store, along with related information. data DocElem d DocElem :: d -> Maybe SubDoc -> DocElem d -- | Doc item itself. [deItem] :: DocElem d -> d -- | Subdocumentation, if given item is a group. [deSub] :: DocElem d -> Maybe SubDoc -- | Hides some documentation item which is put to "definitions" section. data SomeDocDefinitionItem [SomeDocDefinitionItem] :: forall d. (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => d -> SomeDocDefinitionItem -- | Hides some documentation item. data SomeDocItem [SomeDocItem] :: forall d. DocItem d => d -> SomeDocItem -- | How to render section name. data DocSectionNameStyle -- | Suitable for block name. DocSectionNameBig :: DocSectionNameStyle -- | Suitable for subsection title within block. DocSectionNameSmall :: DocSectionNameStyle data DocItemRef (p :: DocItemPlacementKind) (r :: DocItemReferencedKind) [DocItemRef] :: DocItemId -> DocItemRef 'DocItemInDefinitions 'True [DocItemRefInlined] :: DocItemId -> DocItemRef 'DocItemInlined 'True [DocItemNoRef] :: DocItemRef 'DocItemInlined 'False -- | Where do we place given doc item. data DocItemPlacementKind -- | Placed in the document content itself. DocItemInlined :: DocItemPlacementKind -- | Placed in dedicated definitions section; can later be referenced. DocItemInDefinitions :: DocItemPlacementKind -- | Position of all doc items of some type. newtype DocItemPos DocItemPos :: (Natural, Text) -> DocItemPos -- | Some unique identifier of a doc item. -- -- All doc items which should be refer-able need to have this identifier. newtype DocItemId DocItemId :: Text -> DocItemId -- | A piece of documentation describing one property of a thing, be it a -- name or description of a contract, or an error throwable by given -- endpoint. -- -- Items of the same type appear close to each other in a rendered -- documentation and form a section. -- -- Doc items are later injected into a contract code via a dedicated -- nop-like instruction. Normally doc items which belong to one section -- appear in resulting doc in the same order in which they appeared in -- the contract. -- -- While documentation framework grows, this typeclass acquires more and -- more methods for fine tuning of existing rendering logic because we -- don't want to break backward compatibility, hope one day we will make -- everything concise :( E.g. all rendering and reording stuff could be -- merged in one method, and we could have several template -- implementations for it which would allow user to specify only stuff -- relevant to his case. class (Typeable d, DOrd d) => DocItem d where { -- | Defines where given doc item should be put. There are two options: 1. -- Inline right here (default behaviour); 2. Put into definitions -- section. -- -- Note that we require all doc items with "in definitions" placement to -- have Eq and Ord instances which comply the following -- law: if two documentation items describe the same entity or property, -- they should be considered equal. type family DocItemPlacement d :: DocItemPlacementKind; type family DocItemReferenced d :: DocItemReferencedKind; type DocItemPlacement d = 'DocItemInlined; type DocItemReferenced d = 'False; } -- | Position of this item in the resulting documentation; the smaller the -- value, the higher the section with this element will be placed. If the -- position is the same as other doc items, they will be placed base on -- their name, alphabetically. -- -- Documentation structure is not necessarily flat. If some doc item -- consolidates a whole documentation block within it, this block will -- have its own placement of items independent from outer parts of the -- doc. docItemPos :: DocItem d => Natural -- | When multiple items of the same type belong to one section, how this -- section will be called. -- -- If not provided, section will contain just untitled content. docItemSectionName :: DocItem d => Maybe Text -- | Description of a section. -- -- Can be used to mention some common things about all elements of this -- section. Markdown syntax is permitted here. docItemSectionDescription :: DocItem d => Maybe Markdown -- | How to render section name. -- -- Takes effect only if section name is set. docItemSectionNameStyle :: DocItem d => DocSectionNameStyle -- | Defines a function which constructs an unique identifier of given doc -- item, if it has been decided to put the doc item into definitions -- section. -- -- Identifier should be unique both among doc items of the same type and -- items of other types. Thus, consider using "typeId-contentId" pattern. docItemRef :: DocItem d => d -> DocItemRef (DocItemPlacement d) (DocItemReferenced d) -- | Render given doc item to Markdown, preferably one line, optionally -- with header. -- -- Accepts the smallest allowed level of header. (Using smaller value -- than provided one will interfere with existing headers thus delivering -- mess). docItemToMarkdown :: DocItem d => HeaderLevel -> d -> Markdown -- | Render table of contents entry for given doc item to Markdown. docItemToToc :: DocItem d => HeaderLevel -> d -> Markdown -- | All doc items which this doc item refers to. -- -- They will automatically be put to definitions as soon as given doc -- item is detected. docItemDependencies :: DocItem d => d -> [SomeDocDefinitionItem] -- | This function accepts doc items put under the same section in the -- order in which they appeared in the contract and returns their new -- desired order. It's also fine to use this function for filtering or -- merging doc items. -- -- Default implementation * leaves inlined items as is; * for items put -- to definitions, lexicographically sorts them by their id. docItemsOrder :: DocItem d => [d] -> [d] -- | Defines where given doc item should be put. There are two options: 1. -- Inline right here (default behaviour); 2. Put into definitions -- section. -- -- Note that we require all doc items with "in definitions" placement to -- have Eq and Ord instances which comply the following -- law: if two documentation items describe the same entity or property, -- they should be considered equal. type family DocItemPlacement d :: DocItemPlacementKind type family DocItemReferenced d :: DocItemReferencedKind -- | Generate DToc entry anchor from docItemRef. mdTocFromRef :: (DocItem d, DocItemReferenced d ~ 'True) => HeaderLevel -> Markdown -> d -> Markdown -- | Get doc item position at term-level. docItemPosition :: DocItem d => DocItemPos -- | Make a reference to doc item in definitions. docDefinitionRef :: (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => Markdown -> d -> Markdown -- | Render documentation for SubDoc. subDocToMarkdown :: HeaderLevel -> SubDoc -> Markdown -- | A hand-made anchor. data DAnchor DAnchor :: Anchor -> DAnchor -- | Comment in the doc (mostly used for licenses) data DComment DComment :: Text -> DComment -- | Repository settings for DGitRevision. newtype GitRepoSettings GitRepoSettings :: (Text -> Text) -> GitRepoSettings -- | By commit sha make up a url to that commit in remote repository. [grsMkGitRevision] :: GitRepoSettings -> Text -> Text data DGitRevision DGitRevisionKnown :: DGitRevisionInfo -> DGitRevision DGitRevisionUnknown :: DGitRevision -- | Description of something. data DDescription DDescription :: Markdown -> DDescription -- | A function which groups a piece of doc under one doc item. type DocGrouping = SubDoc -> SomeDocItem -- | Render given contract documentation to markdown document. contractDocToMarkdown :: ContractDoc -> LText morleyRepoSettings :: GitRepoSettings -- | Make DGitRevision. -- --
--   >>> :t $mkDGitRevision
--   GitRepoSettings -> DGitRevision
--   
mkDGitRevision :: ExpQ type Operation = Operation' Instr type Value = Value' Instr newtype BigMap k v BigMap :: Map k v -> BigMap k v [unBigMap] :: BigMap k v -> Map k v -- | Since Contract name is used to designate contract code, lets -- call analogy of TContract type as follows. -- -- Note that type argument always designates an argument of entrypoint. -- If a contract has explicit default entrypoint (and no root -- entrypoint), ContractRef referring to it can never have the -- entire parameter as its type argument. data ContractRef arg ContractRef :: Address -> SomeEntrypointCall arg -> ContractRef arg [crAddress] :: ContractRef arg -> Address [crEntrypoint] :: ContractRef arg -> SomeEntrypointCall arg type WellTypedIsoValue a = (WellTyped ToT a, IsoValue a) type SomeEntrypointCall arg = SomeEntrypointCallT ToT arg type EntrypointCall param arg = EntrypointCallT ToT param ToT arg -- | Isomorphism between Michelson values and plain Haskell types. -- -- Default implementation of this typeclass converts ADTs to Michelson -- "pair"s and "or"s. class WellTypedToT a => IsoValue a where { -- | Type function that converts a regular Haskell type into a T -- type. type family ToT a :: T; type ToT a = GValueType Rep a; } -- | Converts a Haskell structure into Value representation. toVal :: IsoValue a => a -> Value (ToT a) -- | Converts a Value into Haskell type. fromVal :: IsoValue a => Value (ToT a) -> a -- | Type function that converts a regular Haskell type into a T -- type. type family ToT a :: T -- | Replace type argument of ContractAddr with isomorphic one. coerceContractRef :: ToT a ~ ToT b => ContractRef a -> ContractRef b -- | Constraint for instrConstruct and gInstrConstructStack. type InstrConstructC dt = (GenericIsoValue dt, GInstrConstruct Rep dt) -- | Types of all fields in a datatype. type ConstructorFieldTypes dt = GFieldTypes Rep dt -- | Require this type to be homomorphic. class IsHomomorphic (a :: k) -- | Require two types to be built from the same type constructor. -- -- E.g. HaveCommonTypeCtor (Maybe Integer) (Maybe Natural) is -- defined, while HaveCmmonTypeCtor (Maybe Integer) [Integer] is -- not. class HaveCommonTypeCtor (a :: k) (b :: k1) -- | Doc element with description of a type. data DType [DType] :: forall a. TypeHasDoc a => Proxy a -> DType -- | Data hides some type implementing TypeHasDoc. data SomeTypeWithDoc [SomeTypeWithDoc] :: forall td. TypeHasDoc td => Proxy td -> SomeTypeWithDoc -- | Description for a Haskell type appearing in documentation. class (Typeable a, SingI TypeDocFieldDescriptions a, FieldDescriptionsValid TypeDocFieldDescriptions a a) => TypeHasDoc a where { -- | Description of constructors and fields of a. -- -- See FieldDescriptions documentation for an example of usage. -- -- Descriptions will be checked at compile time to make sure that only -- existing constructors and fields are referenced. -- -- For that check to work instance Generic a is required -- whenever TypeDocFieldDescriptions is not empty. -- -- For implementation of the check see FieldDescriptionsValid type -- family. type family TypeDocFieldDescriptions a :: FieldDescriptions; type TypeDocFieldDescriptions a = '[] :: [(Symbol, (Maybe Symbol, [(Symbol, Symbol)]))]; } -- | Name of type as it appears in definitions section. -- -- Each type must have its own unique name because it will be used in -- identifier for references. -- -- Default definition derives name from Generics. If it does not fit, -- consider defining this function manually. (We tried using Data -- for this, but it produces names including module names which is not do -- we want). typeDocName :: TypeHasDoc a => Proxy a -> Text -- | Explanation of a type. Markdown formatting is allowed. typeDocMdDescription :: TypeHasDoc a => Markdown -- | How reference to this type is rendered, in Markdown. -- -- Examples: -- -- -- -- Consider using one of the following functions as default -- implementation; which one to use depends on number of type arguments -- in your type: -- -- -- -- If none of them fits your purposes precisely, consider using -- customTypeDocMdReference. typeDocMdReference :: TypeHasDoc a => Proxy a -> WithinParens -> Markdown -- | All types which this type directly contains. -- -- Used in automatic types discovery. typeDocDependencies :: TypeHasDoc a => Proxy a -> [SomeDocDefinitionItem] -- | For complex types - their immediate Haskell representation. -- -- For primitive types set this to Nothing. -- -- For homomorphic types use homomorphicTypeDocHaskellRep -- implementation. -- -- For polymorhpic types consider using concreteTypeDocHaskellRep -- as implementation. -- -- Modifier haskellRepNoFields can be used to hide names of -- fields, beneficial for newtypes. -- -- Another modifier called haskellRepStripFieldPrefix can be used -- for datatypes to leave only meaningful part of name in every field. typeDocHaskellRep :: TypeHasDoc a => TypeDocHaskellRep a -- | Final michelson representation of a type. -- -- For homomorphic types use homomorphicTypeDocMichelsonRep -- implementation. -- -- For polymorhpic types consider using -- concreteTypeDocMichelsonRep as implementation. typeDocMichelsonRep :: TypeHasDoc a => TypeDocMichelsonRep a -- | Description of constructors and fields of a. -- -- See FieldDescriptions documentation for an example of usage. -- -- Descriptions will be checked at compile time to make sure that only -- existing constructors and fields are referenced. -- -- For that check to work instance Generic a is required -- whenever TypeDocFieldDescriptions is not empty. -- -- For implementation of the check see FieldDescriptionsValid type -- family. type family TypeDocFieldDescriptions a :: FieldDescriptions -- | Create a DType in form suitable for putting to -- typeDocDependencies. dTypeDep :: TypeHasDoc t => SomeDocDefinitionItem -- | Render a reference to a type which consists of type constructor (you -- have to provide name of this type constructor and documentation for -- the whole type) and zero or more type arguments. customTypeDocMdReference :: (Text, DType) -> [DType] -> WithinParens -> Markdown -- | Derive typeDocMdReference, for homomorphic types only. homomorphicTypeDocMdReference :: (Typeable t, TypeHasDoc t, IsHomomorphic t) => Proxy t -> WithinParens -> Markdown -- | Derive typeDocMdReference, for polymorphic type with one type -- argument, like Maybe Integer. poly1TypeDocMdReference :: forall (t :: Type -> Type) r a. (r ~ t a, Typeable t, Each '[TypeHasDoc] '[r, a], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown -- | Derive typeDocMdReference, for polymorphic type with two type -- arguments, like Lambda Integer Natural. poly2TypeDocMdReference :: forall (t :: Type -> Type -> Type) r a b. (r ~ t a b, Typeable t, Each '[TypeHasDoc] '[r, a, b], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown -- | Implement typeDocDependencies via getting all immediate fields -- of a datatype. -- -- Note: this will not include phantom types, I'm not sure yet how this -- scenario should be handled (@martoon). genericTypeDocDependencies :: (Generic a, GTypeHasDoc (Rep a)) => Proxy a -> [SomeDocDefinitionItem] -- | Implement typeDocHaskellRep for a homomorphic type. -- -- Note that it does not require your type to be of IsHomomorphic -- instance, which can be useful for some polymorhpic types which, for -- documentation purposes, we want to consider homomorphic. -- -- Example: Operation is in fact polymorhpic, but we don't want -- this fact to be reflected in the documentation. homomorphicTypeDocHaskellRep :: (Generic a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep a -- | Implement typeDocHaskellRep on example of given concrete type. -- -- This is a best effort attempt to implement typeDocHaskellRep -- for polymorhpic types, as soon as there is no simple way to preserve -- type variables when automatically deriving Haskell representation of a -- type. concreteTypeDocHaskellRep :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a), HaveCommonTypeCtor b a) => TypeDocHaskellRep b -- | Version of concreteTypeDocHaskellRep which does not ensure -- whether the type for which representation is built is any similar to -- the original type which you implement a TypeHasDoc instance -- for. concreteTypeDocHaskellRepUnsafe :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep b -- | Erase fields from Haskell datatype representation. -- -- Use this when rendering fields names is undesired. haskellRepNoFields :: TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Add field name for newtype. -- -- Since newtype field is automatically erased. Use this -- function to add the desired field name. haskellAddNewtypeField :: Text -> TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Cut fields prefixes which we use according to the style guide. -- -- E.g. cmMyField field will be transformed to myField. haskellRepStripFieldPrefix :: HasCallStack => TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Implement typeDocMichelsonRep for homomorphic type. homomorphicTypeDocMichelsonRep :: SingI (ToT a) => TypeDocMichelsonRep a -- | Implement typeDocMichelsonRep on example of given concrete -- type. -- -- This function exists for the same reason as -- concreteTypeDocHaskellRep. concreteTypeDocMichelsonRep :: forall k a (b :: k). (Typeable a, SingI (ToT a), HaveCommonTypeCtor b a) => TypeDocMichelsonRep b -- | Version of concreteTypeDocHaskellRepUnsafe which does not -- ensure whether the type for which representation is built is any -- similar to the original type which you implement a TypeHasDoc -- instance for. concreteTypeDocMichelsonRepUnsafe :: forall k a (b :: k). (Typeable a, SingI (ToT a)) => TypeDocMichelsonRep b -- | A space efficient, packed, unboxed Unicode text type. data Text -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: forall (m :: Type -> Type) e a. Functor m => e -> MaybeT m a -> ExceptT e m a -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: forall (m :: Type -> Type) e a. Functor m => ExceptT e m a -> MaybeT m a -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | Function type for handling a coding error. It is supplied with two -- inputs: -- -- -- -- If the handler returns a value wrapped with Just, that value -- will be used in the output as the replacement for the invalid input. -- If it returns Nothing, no value will be used in the output. -- -- Should the handler need to abort processing, it should use -- error or throw an exception (preferably a -- UnicodeException). It may use the description provided to -- construct a more helpful error report. type OnError a b = String -> Maybe a -> Maybe b -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Decode a ByteString containing UTF-8 encoded text. -- -- NOTE: The replacement character returned by -- OnDecodeError MUST be within the BMP plane; surrogate code -- points will automatically be remapped to the replacement char -- U+FFFD (since 0.11.3.0), whereas code points beyond -- the BMP will throw an error (since 1.2.3.1); For earlier -- versions of text using those unsupported code points would -- result in undefined behavior. decodeUtf8With :: OnDecodeError -> ByteString -> Text -- | Decode a ByteString containing UTF-8 encoded text. -- -- If the input contains any invalid UTF-8 data, the relevant exception -- will be returned, otherwise the decoded text. decodeUtf8' :: ByteString -> Either UnicodeException Text -- | O(n) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [Text] -- | O(n) Breaks a Text up into a list of Texts at -- newline Chars. The resulting strings do not contain newlines. lines :: Text -> [Text] -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [Text] -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Convert a lazy Text into a strict Text. toStrict :: Text -> Text -- | O(c) Convert a strict Text into a lazy Text. fromStrict :: Text -> Text -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execStateT :: Monad m => StateT s m a -> s -> m s -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalStateT :: Monad m => StateT s m a -> s -> m a -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: (s -> s) -> State s a -> State s a -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: State s a -> s -> s -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalState :: State s a -> s -> a -- | Unwrap a state monad computation as a function. (The inverse of -- state.) runState :: State s a -> s -> (a, s) -- | A state monad parameterized by the type s of the state to -- carry. -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. type State s = StateT s Identity -- | A state transformer monad parameterized by: -- -- -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. newtype StateT s (m :: Type -> Type) a StateT :: (s -> m (a, s)) -> StateT s (m :: Type -> Type) a [runStateT] :: StateT s (m :: Type -> Type) a -> s -> m (a, s) -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e a) -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | The trivial monad transformer, which maps a monad to an equivalent -- monad. data IdentityT (f :: k -> Type) (a :: k) -- | The class of monad transformers. Instances should satisfy the -- following laws, which state that lift is a monad -- transformation: -- -- class MonadTrans (t :: Type -> Type -> Type -> Type) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a -- | The parameterizable reader monad. -- -- Computations are functions of a shared environment. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. type Reader r = ReaderT r Identity -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. newtype ReaderT r (m :: Type -> Type) a ReaderT :: (r -> m a) -> ReaderT r (m :: Type -> Type) a [runReaderT] :: ReaderT r (m :: Type -> Type) a -> r -> m a -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: Type -> Type) | m -> s -- | Replace the state inside the monad. put :: MonadState s m => s -> m () -- | Embed a simple state action into the monad. state :: MonadState s m => (s -> (a, s)) -> m a -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: Type -> Type) | m -> r -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | Executes a computation in a modified environment. local :: MonadReader r m => (r -> r) -> m a -> m a -- | Retrieves a function of the current environment. reader :: MonadReader r m => (r -> a) -> m a -- | Retrieves a function of the current environment. asks :: MonadReader r m => (r -> a) -> m a -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => (s -> a) -> m a -- | Monadic state transformer. -- -- Maps an old state to a new state inside a state monad. The old state -- is thrown away. -- --
--   Main> :t modify ((+1) :: Int -> Int)
--   modify (...) :: (MonadState Int a) => a ()
--   
-- -- This says that modify (+1) acts over any Monad that is a -- member of the MonadState class, with an Int state. modify :: MonadState s m => (s -> s) -> m () -- | A monad transformer that adds exceptions to other monads. -- -- ExceptT constructs a monad parameterized over two things: -- -- -- -- The return function yields a computation that produces the -- given value, while >>= sequences two subcomputations, -- exiting on the first exception. newtype ExceptT e (m :: Type -> Type) a ExceptT :: m (Either e a) -> ExceptT e (m :: Type -> Type) a -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype MaybeT (m :: Type -> Type) a MaybeT :: m (Maybe a) -> MaybeT (m :: Type -> Type) a [runMaybeT] :: MaybeT (m :: Type -> Type) a -> m (Maybe a) (.~) :: ASetter s t a b -> b -> s -> t (^..) :: s -> Getting (Endo [a]) s a -> [a] over :: ASetter s t a b -> (a -> b) -> s -> t set :: ASetter s t a b -> b -> s -> t preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a) preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a) use :: MonadState s m => Getting a s a -> m a view :: MonadReader s m => Getting a s a -> m a bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c bracket_ :: MonadMask m => m a -> m b -> m c -> m c catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a catchAny :: MonadCatch m => m a -> (SomeException -> m a) -> m a finally :: MonadMask m => m a -> m b -> m a handleAny :: MonadCatch m => (SomeException -> m a) -> m a -> m a onException :: MonadMask m => m a -> m b -> m a throwM :: (MonadThrow m, Exception e) => e -> m a try :: (MonadCatch m, Exception e) => m a -> m (Either e a) tryAny :: MonadCatch m => m a -> m (Either SomeException a) pass :: Applicative f => f () ($!) :: (a -> b) -> a -> b guardM :: MonadPlus m => m Bool -> m () ifM :: Monad m => m Bool -> m a -> m a -> m a unlessM :: Monad m => m Bool -> m () -> m () whenM :: Monad m => m Bool -> m () -> m () asum :: (Container t, Alternative f, Element t ~ f a) => t -> f a flipfoldl' :: (Container t, Element t ~ a) => (a -> b -> b) -> b -> t -> b forM_ :: (Container t, Monad m) => t -> (Element t -> m b) -> m () for_ :: (Container t, Applicative f) => t -> (Element t -> f b) -> f () mapM_ :: (Container t, Monad m) => (Element t -> m b) -> t -> m () product :: (Container t, Num (Element t)) => t -> Element t sequenceA_ :: (Container t, Applicative f, Element t ~ f a) => t -> f () sequence_ :: (Container t, Monad m, Element t ~ m a) => t -> m () sum :: (Container t, Num (Element t)) => t -> Element t traverse_ :: (Container t, Applicative f) => (Element t -> f b) -> t -> f () error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => Text -> a trace :: Text -> a -> a traceId :: Text -> Text traceIdWith :: (a -> Text) -> a -> a traceM :: Monad m => Text -> m () traceShow :: Show a => a -> b -> b traceShowId :: Show a => a -> a traceShowIdWith :: Show s => (a -> s) -> a -> a traceShowM :: (Show a, Monad m) => a -> m () undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a evaluateNF :: (NFData a, MonadIO m) => a -> m a evaluateNF_ :: (NFData a, MonadIO m) => a -> m () evaluateWHNF :: MonadIO m => a -> m a evaluateWHNF_ :: MonadIO m => a -> m () pattern Exc :: Exception e => e -> SomeException bug :: (HasCallStack, Exception e) => e -> a note :: MonadError e m => e -> Maybe a -> m a (<<$>>) :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b) map :: Functor f => (a -> b) -> f a -> f b atomically :: MonadIO m => STM a -> m a newEmptyMVar :: MonadIO m => m (MVar a) newMVar :: MonadIO m => a -> m (MVar a) newTVarIO :: MonadIO m => a -> m (TVar a) putMVar :: MonadIO m => MVar a -> a -> m () readMVar :: MonadIO m => MVar a -> m a readTVarIO :: MonadIO m => TVar a -> m a swapMVar :: MonadIO m => MVar a -> a -> m a takeMVar :: MonadIO m => MVar a -> m a tryPutMVar :: MonadIO m => MVar a -> a -> m Bool tryReadMVar :: MonadIO m => MVar a -> m (Maybe a) tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) die :: MonadIO m => String -> m a exitFailure :: MonadIO m => m a exitSuccess :: MonadIO m => m a exitWith :: MonadIO m => ExitCode -> m a appendFile :: MonadIO m => FilePath -> Text -> m () getLine :: MonadIO m => m Text hClose :: MonadIO m => Handle -> m () openFile :: MonadIO m => FilePath -> IOMode -> m Handle withFile :: (MonadIO m, MonadMask m) => FilePath -> IOMode -> (Handle -> m a) -> m a atomicModifyIORef :: MonadIO m => IORef a -> (a -> (a, b)) -> m b atomicModifyIORef' :: MonadIO m => IORef a -> (a -> (a, b)) -> m b atomicWriteIORef :: MonadIO m => IORef a -> a -> m () modifyIORef :: MonadIO m => IORef a -> (a -> a) -> m () modifyIORef' :: MonadIO m => IORef a -> (a -> a) -> m () newIORef :: MonadIO m => a -> m (IORef a) readIORef :: MonadIO m => IORef a -> m a writeIORef :: MonadIO m => IORef a -> a -> m () uncons :: [a] -> Maybe (a, [a]) whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f () whenNotNullM :: Monad m => m [a] -> (NonEmpty a -> m ()) -> m () allM :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool andM :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool anyM :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool concatForM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => l a -> (a -> f m) -> f m concatMapM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => (a -> f m) -> l a -> f m orM :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool fromLeft :: a -> Either a b -> a fromRight :: b -> Either a b -> b leftToMaybe :: Either l r -> Maybe l maybeToLeft :: r -> Maybe l -> Either l r maybeToRight :: l -> Maybe r -> Either l r rightToMaybe :: Either l r -> Maybe r whenLeftM :: Monad m => m (Either l r) -> (l -> m ()) -> m () whenRightM :: Monad m => m (Either l r) -> (r -> m ()) -> m () whenJust :: Applicative f => Maybe a -> (a -> f ()) -> f () whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () whenNothing :: Applicative f => Maybe a -> f a -> f a whenNothingM :: Monad m => m (Maybe a) -> m a -> m a whenNothingM_ :: Monad m => m (Maybe a) -> m () -> m () whenNothing_ :: Applicative f => Maybe a -> f () -> f () evaluatingState :: s -> State s a -> a evaluatingStateT :: Functor f => s -> StateT s f a -> f a executingState :: s -> State s a -> s executingStateT :: Functor f => s -> StateT s f a -> f s usingReader :: r -> Reader r a -> a usingReaderT :: r -> ReaderT r m a -> m a usingState :: s -> State s a -> (a, s) usingStateT :: s -> StateT s m a -> m (a, s) maybeToMonoid :: Monoid m => Maybe m -> m hashNub :: (Eq a, Hashable a) => [a] -> [a] ordNub :: Ord a => [a] -> [a] sortNub :: Ord a => [a] -> [a] unstableNub :: (Eq a, Hashable a) => [a] -> [a] hPrint :: (MonadIO m, Show a) => Handle -> a -> m () hPutStr :: (Print a, MonadIO m) => Handle -> a -> m () hPutStrLn :: (Print a, MonadIO m) => Handle -> a -> m () print :: forall a m. (MonadIO m, Show a) => a -> m () putLText :: MonadIO m => Text -> m () putLTextLn :: MonadIO m => Text -> m () putStr :: (Print a, MonadIO m) => a -> m () putStrLn :: (Print a, MonadIO m) => a -> m () putText :: MonadIO m => Text -> m () putTextLn :: MonadIO m => Text -> m () readEither :: (ToString a, Read b) => a -> Either Text b show :: forall b a. (Show a, IsString b) => a -> b class MonadThrow m => MonadCatch (m :: Type -> Type) class MonadCatch m => MonadMask (m :: Type -> Type) mask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b uninterruptibleMask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b generalBracket :: MonadMask m => m a -> (a -> ExitCase b -> m c) -> (a -> m b) -> m (b, c) class Monad m => MonadThrow (m :: Type -> Type) class Hashable a hashWithSalt :: Hashable a => Int -> a -> Int _1 :: Field1 s t a b => Lens s t a b _2 :: Field2 s t a b => Lens s t a b _3 :: Field3 s t a b => Lens s t a b _4 :: Field4 s t a b => Lens s t a b _5 :: Field5 s t a b => Lens s t a b type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t type Lens' s a = Lens s s a a type Traversal s t a b = forall (f :: Type -> Type). Applicative f => a -> f b -> s -> f t type Traversal' s a = Traversal s s a a class Container t where { type family Element t; type Element t = ElementDefault t; } toList :: Container t => t -> [Element t] null :: Container t => t -> Bool foldr :: Container t => (Element t -> b -> b) -> b -> t -> b foldl :: Container t => (b -> Element t -> b) -> b -> t -> b foldl' :: Container t => (b -> Element t -> b) -> b -> t -> b length :: Container t => t -> Int elem :: Container t => Element t -> t -> Bool maximum :: Container t => t -> Element t minimum :: Container t => t -> Element t foldMap :: (Container t, Monoid m) => (Element t -> m) -> t -> m fold :: Container t => t -> Element t foldr' :: Container t => (Element t -> b -> b) -> b -> t -> b foldr1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t foldl1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t notElem :: Container t => Element t -> t -> Bool all :: Container t => (Element t -> Bool) -> t -> Bool any :: Container t => (Element t -> Bool) -> t -> Bool find :: Container t => (Element t -> Bool) -> t -> Maybe (Element t) safeHead :: Container t => t -> Maybe (Element t) type family Element t class One x where { type family OneItem x; } one :: One x => OneItem x -> x type family OneItem x class ToPairs t toPairs :: ToPairs t => t -> [(Key t, Val t)] keys :: ToPairs t => t -> [Key t] elems :: ToPairs t => t -> [Val t] data Undefined Undefined :: Undefined data Bug Bug :: SomeException -> CallStack -> Bug class Print a class ConvertUtf8 a b encodeUtf8 :: ConvertUtf8 a b => a -> b decodeUtf8 :: ConvertUtf8 a b => b -> a decodeUtf8Strict :: ConvertUtf8 a b => b -> Either UnicodeException a type LByteString = ByteString type LText = Text class ToLText a toLText :: ToLText a => a -> Text class ToString a toString :: ToString a => a -> String class ToText a toText :: ToText a => a -> Text type (f :: k1 -> k) $ (a :: k1) = f a type family Each (c :: [k -> Constraint]) (as :: [k]) type With (a :: [k -> Constraint]) (b :: k) = a <+> b class SuperComposition a b c | a b -> c (...) :: SuperComposition a b c => a -> b -> c data HashMap k v data HashSet a data Vector a arg :: forall (name :: Symbol) a. Name name -> (name :! a) -> a argDef :: forall (name :: Symbol) a. Name name -> a -> (name :? a) -> a argF :: forall (name :: Symbol) f a. Name name -> NamedF f a name -> f a type (name :: Symbol) :! a = NamedF Identity a name type (name :: Symbol) :? a = NamedF Maybe a name data Rec (a :: u -> Type) (b :: [u]) [RNil] :: forall u (a :: u -> Type). Rec a ('[] :: [u]) [:&] :: forall u (a :: u -> Type) (r :: u) (rs :: [u]). !a r -> !Rec a rs -> Rec a (r : rs) withDict :: HasDict c e => e -> (c => r) -> r class Default a def :: Default a => a -- | Resulting state of IndigoM. data GenCode inp out a GenCode :: ~a -> ~MetaData out -> (inp :-> out) -> (out :-> inp) -> GenCode inp out a -- | Interpreter output value [gcOut] :: GenCode inp out a -> ~a -- | Interpreter meta data. [gcMeta] :: GenCode inp out a -> ~MetaData out -- | Generated Lorentz code. [gcCode] :: GenCode inp out a -> inp :-> out -- | Clearing Lorentz code. [gcClear] :: GenCode inp out a -> out :-> inp type DefaultStack stk = Default (MetaData stk) -- | Initial state of IndigoState. data MetaData stk MetaData :: StackVars stk -> RefId -> MetaData stk -- | Stack of the symbolic interpreter. [mdStack] :: MetaData stk -> StackVars stk -- | Number of allocated variables. [mdRefCount] :: MetaData stk -> RefId -- | Stack of the symbolic interpreter. type StackVars (stk :: [Type]) = Rec StkEl stk -- | Stack element of the symbolic interpreter. -- -- It holds either a reference index that refers to this element or just -- NoRef, indicating that there are no references to this element. data StkEl a [NoRef] :: KnownValue a => StkEl a [Ref] :: KnownValue a => RefId -> StkEl a -- | Reference id to a stack cell data RefId -- | IndigoState monad. It's basically Control.Monad.Indexed.State , -- however this package is not in the used lts and it doesn't compile. -- -- It takes as input a MetaData (for the initial state) and -- returns a GenCode (for the resulting state and the generated -- Lorentz code). -- -- IndigoState has to be used to write backend typed Lorentz code from -- the corresponding frontend constructions. newtype IndigoState inp out a IndigoState :: (MetaData inp -> GenCode inp out a) -> IndigoState inp out a [runIndigoState] :: IndigoState inp out a -> MetaData inp -> GenCode inp out a usingIndigoState :: MetaData inp -> IndigoState inp out a -> GenCode inp out a -- | Get current MetaData. iget :: IndigoState inp inp (MetaData inp) -- | Put new GenCode. iput :: GenCode inp out a -> IndigoState inp out a emptyMetadata :: MetaData '[] -- | Produces the generated Lorentz code that cleans after itself, leaving -- the same stack as the input one cleanGenCode :: GenCode inp out a -> inp :-> inp -- | Allows to get a variable with storage type HasStorage st = Given (Var st) -- | Allows to get a variable with operations type HasSideEffects = Given (Var Ops) type Ops = [Operation] type ComplexObjectC a = (ToDeconstructC a, ToConstructC a, AllConstrained IsObject (FieldTypes a)) type FieldTypes a = MapGFT a (ConstructorFieldNames a) class IsObject' (TypeDecision a) a => IsObject a -- | Like NamedFieldVar, but this one doesn't keep name of a field data TypedFieldVar a [TypedFieldVar] :: IsObject a => Var a -> TypedFieldVar a -- | Variable exposed to a user. -- -- Var represents the tree of fields. Each field is Var -- itself: either a value on the stack or Rec of its direct -- fields. type Var a = IndigoObjectF (NamedFieldVar a) a -- | Auxiliary datatype to define a variable. Keeps field name as type -- param data NamedFieldVar a name [NamedFieldVar] :: IsObject (GetFieldType a name) => {unFieldVar :: Var (GetFieldType a name)} -> NamedFieldVar a name -- | A object that can be either stored in the single stack cell or split -- into fields. Fields are identified by their names. -- -- f is a functor to be applied to each of field names. data IndigoObjectF f a -- | Value stored on the stack, it might be either complex product type, -- like (a, b), Storage, etc, or sum type like Either, or -- primitive like Int, Operation, etc. -- -- Laziness of RefId is needed here to make possible to put -- error in a variable. This is used as a workaround in -- Indigo.Compilation.Lambda. [Cell] :: KnownValue a => ~RefId -> IndigoObjectF f a -- | Decomposed product type, which is NOT stored as one cell on the stack. [Decomposed] :: ComplexObjectC a => Rec f (ConstructorFieldNames a) -> IndigoObjectF f a -- | Convert a list of fields from name-based list to type-based one namedToTypedRec :: forall a f g. (forall name. f name -> g (GetFieldType a name)) -> Rec f (ConstructorFieldNames a) -> Rec g (FieldTypes a) -- | Convert a list of fields from type-based list to named-based one typedToNamedRec :: forall a f g. KnownList (ConstructorFieldNames a) => (forall name. f (GetFieldType a name) -> g name) -> Rec f (FieldTypes a) -> Rec g (ConstructorFieldNames a) castFieldConstructors :: forall a st. CastFieldConstructors (FieldTypes a) (ConstructorFieldTypes a) => Rec (FieldConstructor st) (FieldTypes a) -> Rec (FieldConstructor st) (ConstructorFieldTypes a) namedToTypedFieldVar :: forall a name. NamedFieldVar a name -> TypedFieldVar (GetFieldType a name) typedToNamedFieldVar :: forall a name. TypedFieldVar (GetFieldType a name) -> NamedFieldVar a name complexObjectDict :: forall a. IsObject a => Maybe (Dict (ComplexObjectC a)) -- | Given a MetaData and a Peano singleton for a depth, it -- puts a new Var at that depth (0-indexed) and returns it with -- the updated MetaData. -- -- If there is a Var there already it is used and the -- MetaData not changed. withVarAt :: (KnownValue a, a ~ At n inp, RequireLongerThan inp n) => MetaData inp -> Sing n -> (MetaData inp, Var a) -- | Create a variable referencing the element on top of the stack. makeTopVar :: KnownValue x => IndigoState (x & inp) (x & inp) (Var x) -- | Push a new stack element with a reference to it. Return the variable -- referencing this element. pushRefMd :: KnownValue x => MetaData stk -> (Var x, MetaData (x & stk)) -- | Push a new stack element without a reference to it. pushNoRefMd :: KnownValue a => MetaData inp -> MetaData (a & inp) -- | Remove the top element of the stack. It's supposed that no variable -- refers to this element. popNoRefMd :: MetaData (a & inp) -> MetaData inp -- | Return a variable which refers to a stack cell with operations operationsVar :: HasSideEffects => Var Ops -- | Return a variable which refers to a stack cell with storage storageVar :: HasStorage st => Var st -- | Puts a copy of the value for the given Var on top of the -- stack varActionGet :: forall a stk. KnownValue a => RefId -> StackVars stk -> stk :-> (a & stk) -- | Sets the value for the given Var to the topmost value on the -- stack varActionSet :: forall a stk. KnownValue a => RefId -> StackVars stk -> (a & stk) :-> stk -- | Updates the value for the given Var with the topmost value on -- the stack using the given binary instruction. varActionUpdate :: forall a b stk. (KnownValue a, KnownValue b) => RefId -> StackVars stk -> ('[b, a] :-> '[a]) -> (b : stk) :-> stk -- | Given a stack with a list of Operations on its bottom, updates -- it by appending the Operation on the top. varActionOperation :: HasSideEffects => StackVars stk -> (Operation : stk) :-> stk rtake :: Sing n -> Rec any s -> Rec any (Take n s) rdrop :: Sing n -> Rec any s -> Rec any (Drop n s) -- | IndigoState with hidden output stack, necessary to generate -- typed Lorentz code from untyped Indigo frontend. newtype SomeIndigoState inp a SomeIndigoState :: (MetaData inp -> SomeGenCode inp a) -> SomeIndigoState inp a [unSIS] :: SomeIndigoState inp a -> MetaData inp -> SomeGenCode inp a -- | Gen code with hidden output stack data SomeGenCode inp a [SomeGenCode] :: GenCode inp out a -> SomeGenCode inp a -- | return for SomeIndigoState returnSIS :: a -> SomeIndigoState inp a -- | Like bind, but the input type of the second parameter is determined by -- the output of the first one. bindSIS :: SomeIndigoState inp a -> (forall someOut. a -> SomeIndigoState someOut b) -> SomeIndigoState inp b -- | To run SomeIndigoState you need to pass an handler of -- GenCode with any output stack. runSIS :: SomeIndigoState inp a -> MetaData inp -> (forall out. GenCode inp out a -> r) -> r -- | Convert IndigoState to SomeIndigoState toSIS :: IndigoState inp out a -> SomeIndigoState inp a -- | Call an action with IndigoState stored in -- SomeIndigoState. -- -- This function is kinda dummy because it passes IndigoState to the -- function which produces a GenCode independently on passed MetaData to -- it. It has to be used with only functions which pass MetaData in the -- same way. This function is needed to pass SomeIndigoState in -- contravariant positions of statements like if, case, -- while, forEach, etc. Alternative solution would be -- abstracting out IndigoState and SomeIndigoState with typeclass class -- CodeGenerator m where runCodeGen :: m inp a -> MetaData inp -> -- (forall out . GenCode inp out a -> r) -> r and passing -- CodeGenerator m in contravariant positions instead of IndigoState. withSIS :: SomeIndigoState inp a -> (forall out. IndigoState inp out a -> SomeIndigoState inp b) -> SomeIndigoState inp b -- | The same as withSIS but converting a function with one -- argument, also dummy. withSIS1 :: KnownValue x => (Var x -> SomeIndigoState (x & inp) a) -> (forall out. (Var x -> IndigoState (x & inp) out a) -> SomeIndigoState inp b) -> SomeIndigoState inp b -- | The same as withSIS1 but converting a function with 2 -- arguments, also dummy. withSIS2 :: (KnownValue x, KnownValue y) => (Var x -> Var y -> SomeIndigoState (x & (y & inp)) a) -> (forall out. (Var x -> Var y -> IndigoState (x & (y & inp)) out a) -> SomeIndigoState inp b) -> SomeIndigoState inp b -- | Class like StoreHasField type class but holding a lens to a -- field. class (KnownValue ftype, KnownValue dt) => HasField dt fname ftype | dt fname -> ftype fieldLens :: HasField dt fname ftype => FieldLens dt fname ftype -- | Lens to a field. obj.f1.f2.f3 is represented as list names of -- [f1, f2, f3]. -- -- dt is a type of source object (type of obj in example above) -- fname is a name of target field ("f3" in example -- above) ftype is a type of target field -- -- However, a lens contains not only name of field but for each field it -- contains operations to get and set target field. data FieldLens dt fname ftype [TargetField] :: (InstrGetFieldC dt fname, InstrSetFieldC dt fname, GetFieldType dt fname ~ targetFType, AccessFieldC dt fname) => Label fname -> StoreFieldOps dt targetFName targetFType -> FieldLens dt targetFName targetFType [DeeperField] :: (AccessFieldC dt fname, InstrSetFieldC dt fname, HasField (GetFieldType dt fname) targetFName targetFType) => Label fname -> StoreFieldOps dt targetFName targetFType -> FieldLens dt targetFName targetFType -- | Constraint to access/assign field stored in Rec type AccessFieldC a name = RElem name (ConstructorFieldNames a) (RIndex name (ConstructorFieldNames a)) -- | Get a field from list of fields fetchField :: forall a name f proxy. AccessFieldC a name => proxy name -> Rec f (ConstructorFieldNames a) -> f name -- | Assign a field to a value assignField :: forall a name f proxy. AccessFieldC a name => proxy name -> f name -> Rec f (ConstructorFieldNames a) -> Rec f (ConstructorFieldNames a) -- | Access to StoreFieldOps flSFO :: FieldLens dt fname ftype -> StoreFieldOps dt fname ftype -- | Build a lens to a direct field of an object. fieldLensADT :: forall dt targetFName targetFType fname. (InstrGetFieldC dt fname, InstrSetFieldC dt fname, GetFieldType dt fname ~ targetFType, AccessFieldC dt fname) => Label fname -> FieldLens dt targetFName targetFType -- | Build a lens to deeper field of an object. fieldLensDeeper :: forall dt targetName targetType fname. (AccessFieldC dt fname, HasFieldOfType dt fname (GetFieldType dt fname), HasField (GetFieldType dt fname) targetName targetType) => Label fname -> FieldLens dt targetName targetType type IsSizeExpr exN n = (exN :~> n, SizeOpHs n) type IsMemExpr exKey exN n = (exKey :~> MemOpKeyHs n, exN :~> n, MemOpHs n) type IsUpdExpr exKey exVal exMap map = (exKey :~> UpdOpKeyHs map, exVal :~> UpdOpParamsHs map, exMap :~> map, UpdOpHs map) type IsGetExpr exKey exMap map = (exKey :~> GetOpKeyHs map, exMap :~> map, GetOpHs map, KnownValue (GetOpValHs map)) type IsSliceExpr exN n = (exN :~> n, SliceOpHs n) type IsConcatListExpr exN n = (exN :~> List n, ConcatOpHs n, KnownValue n) type IsConcatExpr exN1 exN2 n = (exN1 :~> n, exN2 :~> n, ConcatOpHs n) type IsModExpr exN exM n m = (exN :~> n, exM :~> m, EDivOpHs n m, KnownValue (EModOpResHs n m)) type IsDivExpr exN exM n m = (exN :~> n, exM :~> m, EDivOpHs n m, KnownValue (EDivOpResHs n m)) type IsArithExpr exN exM a n m = (exN :~> n, exM :~> m, ArithOpHs a n m, KnownValue (ArithResHs a n m)) type IsUnaryArithExpr exN a n = (exN :~> n, UnaryArithOpHs a n, KnownValue (UnaryArithResHs a n)) class ToExpr' (Decide x) x => ToExpr x type ExprType a = ExprType' (Decide a) a type (:~>) op n = IsExpr op n type IsExpr op n = (ToExpr op, ExprType op ~ n, KnownValue n) type ObjectExpr a = IndigoObjectF (NamedFieldExpr a) a -- | Auxiliary datatype where each field refers to an expression the field -- equals to. It's not recursive one. data NamedFieldExpr a name [NamedFieldExpr] :: {unNamedFieldExpr :: Expr (GetFieldType a name)} -> NamedFieldExpr a name -- | Datatype describing access to an inner fields of object, like -- object !. field1 !. field2 ~. (field3, value3) ~. (field4, -- value4) data ObjectManipulation a [Object] :: Expr a -> ObjectManipulation a [ToField] :: HasField dt fname ftype => ObjectManipulation dt -> Label fname -> ObjectManipulation ftype [SetField] :: HasField dt fname ftype => ObjectManipulation dt -> Label fname -> Expr ftype -> ObjectManipulation dt data Expr a [C] :: NiceConstant a => a -> Expr a [V] :: KnownValue a => Var a -> Expr a [ObjMan] :: ObjectManipulation a -> Expr a [Cast] :: KnownValue a => Expr a -> Expr a [Size] :: SizeOpHs c => Expr c -> Expr Natural [Update] :: (UpdOpHs c, KnownValue c) => Expr c -> Expr (UpdOpKeyHs c) -> Expr (UpdOpParamsHs c) -> Expr c [Add] :: (ArithOpHs Add n m, KnownValue (ArithResHs Add n m)) => Expr n -> Expr m -> Expr (ArithResHs Add n m) [Sub] :: (ArithOpHs Sub n m, KnownValue (ArithResHs Sub n m)) => Expr n -> Expr m -> Expr (ArithResHs Sub n m) [Mul] :: (ArithOpHs Mul n m, KnownValue (ArithResHs Mul n m)) => Expr n -> Expr m -> Expr (ArithResHs Mul n m) [Div] :: (EDivOpHs n m, KnownValue (EDivOpResHs n m)) => Expr n -> Expr m -> Expr (EDivOpResHs n m) [Mod] :: (EDivOpHs n m, KnownValue (EModOpResHs n m)) => Expr n -> Expr m -> Expr (EModOpResHs n m) [Abs] :: (UnaryArithOpHs Abs n, KnownValue (UnaryArithResHs Abs n)) => Expr n -> Expr (UnaryArithResHs Abs n) [Neg] :: (UnaryArithOpHs Neg n, KnownValue (UnaryArithResHs Neg n)) => Expr n -> Expr (UnaryArithResHs Neg n) [Lsl] :: (ArithOpHs Lsl n m, KnownValue (ArithResHs Lsl n m)) => Expr n -> Expr m -> Expr (ArithResHs Lsl n m) [Lsr] :: (ArithOpHs Lsr n m, KnownValue (ArithResHs Lsr n m)) => Expr n -> Expr m -> Expr (ArithResHs Lsr n m) [Eq'] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Neq] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Le] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Lt] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Ge] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Gt] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Or] :: (ArithOpHs Or n m, KnownValue (ArithResHs Or n m)) => Expr n -> Expr m -> Expr (ArithResHs Or n m) [Xor] :: (ArithOpHs Xor n m, KnownValue (ArithResHs Xor n m)) => Expr n -> Expr m -> Expr (ArithResHs Xor n m) [And] :: (ArithOpHs And n m, KnownValue (ArithResHs And n m)) => Expr n -> Expr m -> Expr (ArithResHs And n m) [Not] :: (UnaryArithOpHs Not n, KnownValue (UnaryArithResHs Not n)) => Expr n -> Expr (UnaryArithResHs Not n) [Int'] :: Expr Natural -> Expr Integer [IsNat] :: Expr Integer -> Expr (Maybe Natural) [Coerce] :: (Castable_ a b, KnownValue b) => Expr a -> Expr b [ForcedCoerce] :: (MichelsonCoercible a b, KnownValue b) => Expr a -> Expr b [Fst] :: KnownValue n => Expr (n, m) -> Expr n [Snd] :: KnownValue m => Expr (n, m) -> Expr m [Pair] :: KnownValue (n, m) => Expr n -> Expr m -> Expr (n, m) [Some] :: KnownValue (Maybe t) => Expr t -> Expr (Maybe t) [None] :: KnownValue t => Expr (Maybe t) [Right'] :: (KnownValue y, KnownValue (Either y x)) => Expr x -> Expr (Either y x) [Left'] :: (KnownValue x, KnownValue (Either y x)) => Expr y -> Expr (Either y x) [Mem] :: MemOpHs c => Expr (MemOpKeyHs c) -> Expr c -> Expr Bool [UGet] :: (HasUStore name key value store, KnownValue value) => Label name -> Expr key -> Expr (UStore store) -> Expr (Maybe value) [UInsertNew] :: (HasUStore name key value store, IsError err, KnownValue (UStore store)) => Label name -> err -> Expr key -> Expr value -> Expr (UStore store) -> Expr (UStore store) [UInsert] :: (HasUStore name key value store, KnownValue (UStore store)) => Label name -> Expr key -> Expr value -> Expr (UStore store) -> Expr (UStore store) [UMem] :: (HasUStore name key val store, KnownValue val) => Label name -> Expr key -> Expr (UStore store) -> Expr Bool [UUpdate] :: (HasUStore name key val store, KnownValue (UStore store)) => Label name -> Expr key -> Expr (Maybe val) -> Expr (UStore store) -> Expr (UStore store) [UDelete] :: (HasUStore name key val store, KnownValue (UStore store)) => Label name -> Expr key -> Expr (UStore store) -> Expr (UStore store) [Wrap] :: (InstrWrapOneC dt name, KnownValue dt) => Label name -> Expr (CtorOnlyField name dt) -> Expr dt [Unwrap] :: (InstrUnwrapC dt name, KnownValue (CtorOnlyField name dt)) => Label name -> Expr dt -> Expr (CtorOnlyField name dt) [Construct] :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt [ConstructWithoutNamed] :: ComplexObjectC dt => Rec Expr (FieldTypes dt) -> Expr dt [Name] :: KnownValue (name :! t) => Label name -> Expr t -> Expr (name :! t) [UnName] :: KnownValue t => Label name -> Expr (name :! t) -> Expr t [EmptySet] :: (NiceComparable key, KnownValue (Set key)) => Expr (Set key) [Get] :: (GetOpHs c, KnownValue (Maybe (GetOpValHs c)), KnownValue (GetOpValHs c)) => Expr (GetOpKeyHs c) -> Expr c -> Expr (Maybe (GetOpValHs c)) [EmptyMap] :: (KnownValue value, NiceComparable key, KnownValue (Map key value)) => Expr (Map key value) [EmptyBigMap] :: (KnownValue value, NiceComparable key, KnownValue (BigMap key value)) => Expr (BigMap key value) [Pack] :: NicePackedValue a => Expr a -> Expr ByteString [Unpack] :: NiceUnpackedValue a => Expr ByteString -> Expr (Maybe a) [Cons] :: KnownValue (List a) => Expr a -> Expr (List a) -> Expr (List a) [Nil] :: KnownValue a => Expr (List a) [Concat] :: (ConcatOpHs c, KnownValue c) => Expr c -> Expr c -> Expr c [Concat'] :: (ConcatOpHs c, KnownValue c) => Expr (List c) -> Expr c [Slice] :: (SliceOpHs c, KnownValue c) => Expr Natural -> Expr Natural -> Expr c -> Expr (Maybe c) [Contract] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, ToTAddress p addr, ToT addr ~ ToT Address) => Expr addr -> Expr (Maybe (ContractRef p)) [Self] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p) => Expr (ContractRef p) [ContractAddress] :: Expr (ContractRef p) -> Expr Address [ContractCallingUnsafe] :: NiceParameter arg => EpName -> Expr Address -> Expr (Maybe (ContractRef arg)) [RunFutureContract] :: NiceParameter p => Expr (FutureContract p) -> Expr (Maybe (ContractRef p)) [ImplicitAccount] :: Expr KeyHash -> Expr (ContractRef ()) [ConvertEpAddressToContract] :: NiceParameter p => Expr EpAddress -> Expr (Maybe (ContractRef p)) [MakeView] :: KnownValue (View a r) => Expr a -> Expr (ContractRef r) -> Expr (View a r) [MakeVoid] :: KnownValue (Void_ a b) => Expr a -> Expr (Lambda b b) -> Expr (Void_ a b) [CheckSignature] :: Expr PublicKey -> Expr Signature -> Expr ByteString -> Expr Bool [Sha256] :: Expr ByteString -> Expr ByteString [Sha512] :: Expr ByteString -> Expr ByteString [Blake2b] :: Expr ByteString -> Expr ByteString [HashKey] :: Expr PublicKey -> Expr KeyHash [ChainId] :: Expr ChainId [Now] :: Expr Timestamp [Amount] :: Expr Mutez [Balance] :: Expr Mutez [Sender] :: Expr Address [Exec] :: KnownValue b => Expr a -> Expr (Lambda a b) -> Expr b [NonZero] :: (NonZero n, KnownValue (Maybe n)) => Expr n -> Expr (Maybe n) toExpr :: forall a. ToExpr a => a -> Expr (ExprType a) -- | ObjManipulationRes represents a postponed compilation of -- ObjectManipulation datatype. When ObjectManipulation is -- being compiled we are trying to put off the generation of code for -- work with an object because we can just go to a deeper field without -- its "materialization" onto stack. data ObjManipulationRes inp a [StillObject] :: ObjectExpr a -> ObjManipulationRes inp a [OnStack] :: IndigoState inp (a & inp) () -> ObjManipulationRes inp a compileExpr :: forall a inp. Expr a -> IndigoState inp (a & inp) () -- | This function might look cumbersome but it basically either goes -- deeper to an inner field or generates Lorentz code. runObjectManipulation :: ObjectManipulation x -> ObjManipulationRes inp x ternaryOp :: KnownValue res => Expr n -> Expr m -> Expr l -> ((n & (m & (l & inp))) :-> (res & inp)) -> IndigoState inp (res & inp) () binaryOp :: KnownValue res => Expr n -> Expr m -> ((n & (m & inp)) :-> (res & inp)) -> IndigoState inp (res & inp) () unaryOp :: KnownValue res => Expr n -> ((n & inp) :-> (res & inp)) -> IndigoState inp (res & inp) () nullaryOp :: KnownValue res => (inp :-> (res : inp)) -> IndigoState inp (res : inp) () ternaryOpFlat :: Expr n -> Expr m -> Expr l -> ((n & (m & (l & inp))) :-> inp) -> IndigoState inp inp () binaryOpFlat :: Expr n -> Expr m -> ((n & (m & inp)) :-> inp) -> IndigoState inp inp () unaryOpFlat :: Expr n -> ((n & inp) :-> inp) -> IndigoState inp inp () nullaryOpFlat :: (inp :-> inp) -> IndigoState inp inp () remove :: (ExprRemovable c, exStruct :~> c, exKey :~> UpdOpKeyHs c) => exKey -> exStruct -> Expr c insert :: (ExprInsertable c insParam, ex :~> c) => insParam -> ex -> Expr c empty :: (ExprMagma c, NiceComparable (UpdOpKeyHs c), KnownValue c) => Expr c constExpr :: NiceConstant a => a -> Expr a -- | Create an expression holding a variable. varExpr :: KnownValue a => Var a -> Expr a cast :: ex :~> a => ex -> Expr a add :: IsArithExpr exN exM Add n m => exN -> exM -> Expr (ArithResHs Add n m) (+) :: IsArithExpr exN exM Add n m => exN -> exM -> Expr (ArithResHs Add n m) infixl 6 + sub :: IsArithExpr exN exM Sub n m => exN -> exM -> Expr (ArithResHs Sub n m) (-) :: IsArithExpr exN exM Sub n m => exN -> exM -> Expr (ArithResHs Sub n m) infixl 6 - mul :: IsArithExpr exN exM Mul n m => exN -> exM -> Expr (ArithResHs Mul n m) (*) :: IsArithExpr exN exM Mul n m => exN -> exM -> Expr (ArithResHs Mul n m) infixl 7 * div :: IsDivExpr exN exM n m => exN -> exM -> Expr (EDivOpResHs n m) (/) :: IsDivExpr exN exM n m => exN -> exM -> Expr (EDivOpResHs n m) infixl 7 / mod :: IsModExpr exN exM n m => exN -> exM -> Expr (EModOpResHs n m) (%) :: IsModExpr exN exM n m => exN -> exM -> Expr (EModOpResHs n m) infixl 7 % abs :: IsUnaryArithExpr exN Abs n => exN -> Expr (UnaryArithResHs Abs n) neg :: IsUnaryArithExpr exN Neg n => exN -> Expr (UnaryArithResHs Neg n) eq :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (==) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 == neq :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (/=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 /= lt :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (<) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 < gt :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (>) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 > le :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (<=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 <= ge :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (>=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 >= isNat :: ex :~> Integer => ex -> Expr (Maybe Natural) toInt :: ex :~> Natural => ex -> Expr Integer nonZero :: (ex :~> n, NonZero n, KnownValue (Maybe n)) => ex -> Expr (Maybe n) -- | Convert between types that have the same Michelson representation and -- an explicit permission for that in the face of CanCastTo -- constraint. coerce :: forall b a ex. (Castable_ a b, KnownValue b, ex :~> a) => ex -> Expr b -- | Convert between expressions of types that have the same Michelson -- representation. forcedCoerce :: forall b a ex. (MichelsonCoercible a b, KnownValue b, ex :~> a) => ex -> Expr b lsl :: IsArithExpr exN exM Lsl n m => exN -> exM -> Expr (ArithResHs Lsl n m) (<<<) :: IsArithExpr exN exM Lsl n m => exN -> exM -> Expr (ArithResHs Lsl n m) infixl 8 <<< lsr :: IsArithExpr exN exM Lsr n m => exN -> exM -> Expr (ArithResHs Lsr n m) (>>>) :: IsArithExpr exN exM Lsr n m => exN -> exM -> Expr (ArithResHs Lsr n m) infixl 8 >>> or :: IsArithExpr exN exM Or n m => exN -> exM -> Expr (ArithResHs Or n m) (||) :: IsArithExpr exN exM Or n m => exN -> exM -> Expr (ArithResHs Or n m) infixr 2 || and :: IsArithExpr exN exM And n m => exN -> exM -> Expr (ArithResHs And n m) (&&) :: IsArithExpr exN exM And n m => exN -> exM -> Expr (ArithResHs And n m) infixr 3 && xor :: IsArithExpr exN exM Xor n m => exN -> exM -> Expr (ArithResHs Xor n m) (^) :: IsArithExpr exN exM Xor n m => exN -> exM -> Expr (ArithResHs Xor n m) infixr 2 ^ not :: IsUnaryArithExpr exN Not n => exN -> Expr (UnaryArithResHs Not n) pack :: (ex :~> a, NicePackedValue a) => ex -> Expr ByteString unpack :: (NiceUnpackedValue a, exb :~> ByteString) => exb -> Expr (Maybe a) pair :: (ex1 :~> n, ex2 :~> m, KnownValue (n, m)) => ex1 -> ex2 -> Expr (n, m) car :: (op :~> (n, m), KnownValue n) => op -> Expr n fst :: (op :~> (n, m), KnownValue n) => op -> Expr n cdr :: (op :~> (n, m), KnownValue m) => op -> Expr m snd :: (op :~> (n, m), KnownValue m) => op -> Expr m some :: (ex :~> t, KnownValue (Maybe t)) => ex -> Expr (Maybe t) none :: KnownValue t => Expr (Maybe t) right :: (ex :~> x, KnownValue y, KnownValue (Either y x)) => ex -> Expr (Either y x) left :: (ex :~> y, KnownValue x, KnownValue (Either y x)) => ex -> Expr (Either y x) slice :: (an :~> Natural, bn :~> Natural, IsSliceExpr ex c) => (an, bn) -> ex -> Expr (Maybe c) concat :: IsConcatExpr exN1 exN2 n => exN1 -> exN2 -> Expr n (<>) :: IsConcatExpr exN1 exN2 n => exN1 -> exN2 -> Expr n infixr 6 <> cons :: (ex1 :~> a, ex2 :~> List a) => ex1 -> ex2 -> Expr (List a) (.:) :: (ex1 :~> a, ex2 :~> List a) => ex1 -> ex2 -> Expr (List a) infixr 5 .: concatAll :: IsConcatListExpr exN n => exN -> Expr n nil :: KnownValue a => Expr (List a) get :: IsGetExpr exKey exMap map => exKey -> exMap -> Expr (Maybe (GetOpValHs map)) update :: IsUpdExpr exKey exVal exMap map => (exKey, exVal) -> exMap -> Expr map mem :: IsMemExpr exKey exN n => exKey -> exN -> Expr Bool size :: IsSizeExpr exN n => exN -> Expr Natural (#:) :: IsGetExpr exKey exMap map => exMap -> exKey -> Expr (Maybe (GetOpValHs map)) infixl 8 #: (!:) :: IsUpdExpr exKey exVal exMap map => exMap -> (exKey, exVal) -> Expr map infixl 8 !: (+:) :: (ExprInsertable c exParam, exStructure :~> c) => exStructure -> exParam -> Expr c infixl 8 +: (-:) :: (ExprRemovable c, exStruct :~> c, exKey :~> UpdOpKeyHs c) => exStruct -> exKey -> Expr c infixl 8 -: (?:) :: IsMemExpr exKey exN n => exN -> exKey -> Expr Bool infixl 8 ?: emptyBigMap :: (KnownValue value, NiceComparable key, KnownValue (BigMap key value)) => Expr (BigMap key value) emptyMap :: (KnownValue value, NiceComparable key, KnownValue (Map key value)) => Expr (Map key value) emptySet :: (NiceComparable key, KnownValue (Set key)) => Expr (Set key) uGet :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr (Maybe value) (#@) :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr (Maybe value) infixr 8 #@ uUpdate :: (HasUStore name key value store, exKey :~> key, exVal :~> Maybe value, exStore :~> UStore store) => exStore -> (Label name, exKey, exVal) -> Expr (UStore store) (!@) :: (HasUStore name key value store, exKey :~> key, exVal :~> Maybe value, exStore :~> UStore store) => exStore -> (Label name, exKey, exVal) -> Expr (UStore store) infixl 8 !@ uInsert :: (HasUStore name key value store, exKey :~> key, exVal :~> value, exStore :~> UStore store) => exStore -> (Label name, exKey, exVal) -> Expr (UStore store) (+@) :: (HasUStore name key value store, exKey :~> key, exVal :~> value, exStore :~> UStore store) => exStore -> (Label name, exKey, exVal) -> Expr (UStore store) infixr 8 +@ uInsertNew :: (HasUStore name key value store, IsError err, exKey :~> key, exVal :~> value, exStore :~> UStore store) => exStore -> (Label name, err, exKey, exVal) -> Expr (UStore store) (++@) :: (HasUStore name key value store, IsError err, exKey :~> key, exVal :~> value, exStore :~> UStore store) => exStore -> (Label name, err, exKey, exVal) -> Expr (UStore store) infixr 8 ++@ uDelete :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr (UStore store) (-@) :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr (UStore store) infixl 8 -@ uMem :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr Bool (?@) :: (HasUStore name key value store, exKey :~> key, exStore :~> UStore store) => exStore -> (Label name, exKey) -> Expr Bool infixl 8 ?@ wrap :: (InstrWrapOneC dt name, exField :~> CtorOnlyField name dt, KnownValue dt) => Label name -> exField -> Expr dt unwrap :: (InstrUnwrapC dt name, exDt :~> dt, KnownValue (CtorOnlyField name dt)) => Label name -> exDt -> Expr (CtorOnlyField name dt) (#!) :: (HasField dt name ftype, exDt :~> dt) => exDt -> Label name -> Expr ftype infixl 8 #! (!!) :: (HasField dt name ftype, exDt :~> dt, exFld :~> ftype) => exDt -> (Label name, exFld) -> Expr dt infixl 8 !! name :: (ex :~> t, KnownValue (name :! t)) => Label name -> ex -> Expr (name :! t) unName :: (ex :~> (name :! t), KnownValue t) => Label name -> ex -> Expr t (!~) :: (ex :~> t, KnownValue (name :! t)) => ex -> Label name -> Expr (name :! t) infixl 8 !~ (#~) :: (ex :~> (name :! t), KnownValue t) => ex -> Label name -> Expr t infixl 8 #~ construct :: (InstrConstructC dt, KnownValue dt, RMap (ConstructorFieldTypes dt), fields ~ Rec Expr (ConstructorFieldTypes dt), RecFromTuple fields) => IsoRecTuple fields -> Expr dt constructRec :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt contract :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, ToTAddress p addr, ToT addr ~ ToT Address, exAddr :~> addr) => exAddr -> Expr (Maybe (ContractRef p)) self :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p) => Expr (ContractRef p) contractAddress :: exc :~> ContractRef p => exc -> Expr Address contractCallingUnsafe :: (NiceParameter arg, exAddr :~> Address) => EpName -> exAddr -> Expr (Maybe (ContractRef arg)) contractCallingString :: (NiceParameter arg, exAddr :~> Address) => MText -> exAddr -> Expr (Maybe (ContractRef arg)) runFutureContract :: (NiceParameter p, conExpr :~> FutureContract p) => conExpr -> Expr (Maybe (ContractRef p)) implicitAccount :: exkh :~> KeyHash => exkh -> Expr (ContractRef ()) convertEpAddressToContract :: (NiceParameter p, epExpr :~> EpAddress) => epExpr -> Expr (Maybe (ContractRef p)) makeView :: (KnownValue (View a r), exa :~> a, exCRef :~> ContractRef r) => exa -> exCRef -> Expr (View a r) makeVoid :: (KnownValue (Void_ a b), exa :~> a, exCRef :~> Lambda b b) => exa -> exCRef -> Expr (Void_ a b) now :: Expr Timestamp amount :: Expr Mutez sender :: Expr Address checkSignature :: (pkExpr :~> PublicKey, sigExpr :~> Signature, hashExpr :~> ByteString) => pkExpr -> sigExpr -> hashExpr -> Expr Bool sha256 :: hashExpr :~> ByteString => hashExpr -> Expr ByteString sha512 :: hashExpr :~> ByteString => hashExpr -> Expr ByteString blake2b :: hashExpr :~> ByteString => hashExpr -> Expr ByteString hashKey :: keyExpr :~> PublicKey => keyExpr -> Expr KeyHash chainId :: Expr ChainId balance :: Expr Mutez -- | Datatype representing decomposition of Expr. data ExprDecomposition inp a [ExprFields] :: Rec Expr (FieldTypes a) -> ExprDecomposition inp a [Deconstructed] :: IndigoState inp (FieldTypes a ++ inp) () -> ExprDecomposition inp a -- | Decompose an expression to list of its direct fields. decomposeExpr :: ComplexObjectC a => Expr a -> ExprDecomposition inp a -- | For given element on stack, generate code which decomposes it to list -- of its deep non-decomposable fields. Clean up code of -- SomeIndigoState composes the value back. deepDecomposeCompose :: forall a inp. IsObject a => SomeIndigoState (a & inp) (Var a) -- | Monad for writing your contracts in. newtype IndigoM a IndigoM :: Program (StatementF IndigoM) a -> IndigoM a [unIndigoM] :: IndigoM a -> Program (StatementF IndigoM) a -- | This is freer monad (in other words operational monad). -- -- It preserves the structure of the computation performed over it, -- including return and bind operations. This was -- introduced to be able to iterate over Indigo code and optimize/analyze -- it. -- -- You can read a clearer description of this construction in "The Book -- of Monads" by Alejandro Serrano. There is a chapter about free monads, -- specifically about Freer you can read at page 259. There is -- "operational" package which contains transformer of this monad and -- auxiliary functions but it's not used because we are using only some -- basics of it. data Program instr a [Done] :: a -> Program instr a [Instr] :: instr a -> Program instr a [Bind] :: Program instr a -> (a -> Program instr b) -> Program instr b -- | Traverse over Freer structure and interpret it interpretProgram :: Monad m => (forall x. instr x -> m x) -> Program instr a -> m a -- | Type of a function with n Var arguments and -- IndigoM a result. -- -- Note that the arguments are the first n elements of the -- inp stack in inverse order, for example: IndigoWithParams -- ('S ('S 'Z)) '[a, b, c] x is the same as: Var b -> Var a -- -> IndigoM x type family IndigoWithParams n inp a -- | Type of a contract that can be compiled to Lorentz with -- compileIndigoContract. type IndigoContract param st = (HasStorage st, HasSideEffects) => Var param -> IndigoM () -- | Compile Indigo code to Lorentz. -- -- Note: it is necessary to specify the number of parameters (using the -- first type variable) of the Indigo function. Also, these should be on -- the top of the input stack in inverse order (see -- IndigoWithParams). compileIndigo :: forall n inp a. (SingI (ToPeano n), Default (MetaData inp), AreIndigoParams (ToPeano n) inp, KnownValue a) => IndigoWithParams (ToPeano n) inp a -> inp :-> inp -- | Compile Indigo code to Lorentz contract. Drop elements from the stack -- to return only [Operation] and storage. compileIndigoContract :: forall param st. (KnownValue param, IsObject st) => IndigoContract param st -> ContractCode param st type IndigoEntrypoint param = param -> IndigoProcedure -- | Utility type for an IndigoM that does not modify the stack -- (only the values in it) and returns nothing. type IndigoProcedure = IndigoM () -- | Utility type for an IndigoM that adds one element to the stack -- and returns a variable pointing at it. type IndigoFunction ret = IndigoM (RetVars ret) liftIndigoState :: (forall inp. SomeIndigoState inp a) -> IndigoM a -- | Create a new variable with the result of the given expression as its -- initial value. new :: IsExpr ex x => ex -> IndigoM (Var x) -- | Set the given variable to the result of the given expression. setVar :: IsExpr ex x => Var x -> ex -> IndigoM () (=:) :: IsExpr ex x => Var x -> ex -> IndigoM () infixr 0 =: setField :: (ex :~> ftype, IsObject dt, IsObject ftype, HasField dt fname ftype) => Var dt -> Label fname -> ex -> IndigoM () (+=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Add n m, ArithResHs Add n m ~ m) => Var m -> ex1 -> IndigoM () (-=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Sub n m, ArithResHs Sub n m ~ m) => Var m -> ex1 -> IndigoM () (*=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Mul n m, ArithResHs Mul n m ~ m) => Var m -> ex1 -> IndigoM () (||=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Or n m, ArithResHs Or n m ~ m) => Var m -> ex1 -> IndigoM () (&&=) :: (IsExpr ex1 n, IsObject m, ArithOpHs And n m, ArithResHs And n m ~ m) => Var m -> ex1 -> IndigoM () (^=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Xor n m, ArithResHs Xor n m ~ m) => Var m -> ex1 -> IndigoM () (<<<=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsl n m, ArithResHs Lsl n m ~ m) => Var m -> ex1 -> IndigoM () (>>>=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsr n m, ArithResHs Lsr n m ~ m) => Var m -> ex1 -> IndigoM () -- | Sets a storage field to a new value. setStorageField :: forall store name ftype ex. (HasStorage store, ex :~> ftype, IsObject store, IsObject ftype, HasField store name ftype) => Label name -> ex -> IndigoM () -- | Updates a storage field by using an updating IndigoM. updateStorageField :: forall store ftype fname fex. (HasStorage store, fex :~> ftype, HasField store fname ftype, IsObject store, IsObject ftype) => Label fname -> (Var ftype -> IndigoM fex) -> IndigoM () -- | Get a field from the storage, returns a variable. -- -- Note that the storage type almost always needs to be specified. getStorageField :: forall store ftype fname. (HasStorage store, HasField store fname ftype) => Label fname -> IndigoM (Var ftype) if_ :: forall a b ex. (IfConstraint a b, ex :~> Bool) => ex -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Run the instruction when the condition is met, do nothing otherwise. when :: exc :~> Bool => exc -> IndigoM () -> IndigoM () -- | Reverse of when. unless :: exc :~> Bool => exc -> IndigoM () -> IndigoM () ifSome :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b) => ex -> (Var x -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) ifNone :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b) => ex -> IndigoM b -> (Var x -> IndigoM a) -> IndigoM (RetVars a) -- | Run the instruction when the given expression returns Just a -- value, do nothing otherwise. whenSome :: forall x exa. (KnownValue x, exa :~> Maybe x) => exa -> (Var x -> IndigoM ()) -> IndigoM () -- | Run the instruction when the given expression returns Nothing, -- do nothing otherwise. whenNone :: forall x exa. (KnownValue x, exa :~> Maybe x) => exa -> IndigoM () -> IndigoM () ifRight :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b) => ex -> (Var x -> IndigoM a) -> (Var y -> IndigoM b) -> IndigoM (RetVars a) ifLeft :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b) => ex -> (Var y -> IndigoM b) -> (Var x -> IndigoM a) -> IndigoM (RetVars a) whenRight :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x) => ex -> (Var x -> IndigoM ()) -> IndigoM () whenLeft :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x) => ex -> (Var y -> IndigoM ()) -> IndigoM () ifCons :: forall x a b ex. (KnownValue x, ex :~> List x, IfConstraint a b) => ex -> (Var x -> Var (List x) -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) -- | A case statement for indigo. See examples for a sample usage. caseRec :: forall dt guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, guard :~> dt) => guard -> clauses -> IndigoM (RetVars ret) -- | caseRec for tuples. case_ :: forall dt guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, RecFromTuple clauses, guard :~> dt) => guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | caseRec for pattern-matching on parameter. entryCaseRec :: forall dt entrypointKind guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, DocumentEntrypoints entrypointKind dt, guard :~> dt) => Proxy entrypointKind -> guard -> clauses -> IndigoM (RetVars ret) -- | entryCaseRec for tuples. entryCase :: forall dt entrypointKind guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, RecFromTuple clauses, DocumentEntrypoints entrypointKind dt, guard :~> dt) => Proxy entrypointKind -> guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) entryCaseSimple :: forall cp guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) cp ret clauses, RecFromTuple clauses, DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp, guard :~> cp) => guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | An alias for #= kept only for backward compatibility. -- | Deprecated: use #= instead (//->) :: (CaseArrow name (Var x -> IndigoAnyOut x ret) (IndigoCaseClauseL ret ('CaseClauseParam ctor ('OneField x))), ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr, KnownValue x, name ~ AppendSymbol "c" ctor) => Label name -> (Var x -> IndigoM retBr) -> IndigoMCaseClauseL IndigoM ret ('CaseClauseParam ctor ('OneField x)) infixr 0 //-> -- | Use this instead of /->. -- -- This operator is like /-> but wraps a body into -- IndigoAnyOut, which is needed for two reasons: to allow having -- any output stack and to allow returning not exactly the same values. -- -- It has the added benefit of not being an arrow, so in case the body of -- the clause is a lambda there won't be several. (#=) :: (CaseArrow name (Var x -> IndigoAnyOut x ret) (IndigoCaseClauseL ret ('CaseClauseParam ctor ('OneField x))), ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr, KnownValue x, name ~ AppendSymbol "c" ctor) => Label name -> (Var x -> IndigoM retBr) -> IndigoMCaseClauseL IndigoM ret ('CaseClauseParam ctor ('OneField x)) infixr 0 #= scope :: forall a. ScopeCodeGen a => IndigoM a -> IndigoFunction a -- | Alias for scope we use in the tutorial. defFunction :: forall a. ScopeCodeGen a => IndigoM a -> IndigoFunction a -- | A more specific version of defFunction meant to more easily -- create IndigoContracts. -- -- Used in the tutorial. The HasSideEffects constraint is -- specified to avoid the warning for redundant constraints. defContract :: (HasSideEffects => IndigoM ()) -> HasSideEffects => IndigoProcedure -- | Family of defNamed*LambdaN functions put an Indigo -- computation on the stack to later call it avoiding code duplication. -- defNamed*LambdaN takes a computation with N arguments. This -- family of functions add some overhead to contract byte size for every -- call of the function, therefore, DON'T use defNamed*LambdaN -- if: * Your computation is pretty small. It would be cheaper just to -- inline it, so use defFunction. * Your computation is called -- only once, in this case also use defFunction. -- -- Also, pay attention that defNamed*LambdaN accepts a string -- that is a name of the passed computation. Be careful and make sure -- that all declared computations have different names. Later the name -- will be removed. -- -- Pay attention, that lambda argument will be evaluated to variable -- before lambda calling. -- -- TODO Approach with lambda names has critical pitfall: in case if a -- function takes Label name, lambda body won't be regenerated -- for every different label. So be carefully, this will be fixed in a -- following issue. defNamedEffLambda1 :: forall st argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambdaEff1C st (ExprType argExpr) res, CreateLambdaEff1C st (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | Like defNamedEffLambda1 but doesn't make side effects. defNamedLambda1 :: forall st argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambda1C st (ExprType argExpr) res, CreateLambda1C st (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | Like defNamedLambda1 but doesn't take an argument. defNamedLambda0 :: forall st res. (Typeable res, ExecuteLambda1C st () res, CreateLambda1C st () res) => String -> IndigoM res -> IndigoM (RetVars res) -- | Like defNamedEffLambda1 but doesn't modify storage and doesn't make -- side effects. defNamedPureLambda1 :: forall argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambdaPure1C (ExprType argExpr) res, CreateLambdaPure1C (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | While statement. while :: forall ex. ex :~> Bool => ex -> IndigoM () -> IndigoM () whileLeft :: forall x y ex. (ex :~> Either y x, KnownValue y, KnownValue x) => ex -> (Var y -> IndigoM ()) -> IndigoM (Var x) -- | For statements to iterate over a container. forEach :: forall a e. (IterOpHs a, KnownValue (IterOpElHs a), e :~> a) => e -> (Var (IterOpElHs a) -> IndigoM ()) -> IndigoM () -- | Put a document item. doc :: DocItem di => di -> IndigoM () -- | Group documentation built in the given piece of code into a block -- dedicated to one thing, e.g. to one entrypoint. docGroup :: DocGrouping -> IndigoM () -> IndigoM () -- | Insert documentation of the contract's storage type. The type should -- be passed using type applications. docStorage :: forall storage. TypeHasDoc storage => IndigoM () -- | Give a name to the given contract. Apply it to the whole contract -- code. contractName :: Text -> IndigoM () -> IndigoM () -- | Attach general info to the given contract. contractGeneral :: IndigoM () -> IndigoM () -- | Attach default general info to the contract documentation. contractGeneralDefault :: IndigoM () -- | Indigo version for the homonym Lorentz function. finalizeParamCallingDoc :: forall param x. (ToExpr param, NiceParameterFull (ExprType param), RequireSumType (ExprType param), HasCallStack) => (Var (ExprType param) -> IndigoM x) -> param -> IndigoM x -- | Put a DDescription doc item. description :: Markdown -> IndigoM () -- | Put a DAnchor doc item. anchor :: Text -> IndigoM () -- | Put a DEntrypointExample doc item. example :: forall a. NiceParameter a => a -> IndigoM () selfCalling :: forall p mname. (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname)) => EntrypointRef mname -> IndigoM (Var (ContractRef (GetEntrypointArgCustom p mname))) contractCalling :: forall cp epRef epArg addr exAddr. (HasEntrypointArg cp epRef epArg, ToTAddress cp addr, ToT addr ~ ToT Address, exAddr :~> addr, KnownValue epArg) => epRef -> exAddr -> IndigoM (Var (Maybe (ContractRef epArg))) transferTokens :: (IsExpr exp p, IsExpr exm Mutez, IsExpr exc (ContractRef p), NiceParameter p, HasSideEffects) => exp -> exm -> exc -> IndigoM () setDelegate :: (HasSideEffects, IsExpr ex (Maybe KeyHash)) => ex -> IndigoM () -- | Create contract using default compilation options for Lorentz -- compiler. -- -- See Lorentz.Run. createContract :: (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorage st, NiceParameterFull param, HasSideEffects) => (HasStorage st => Var param -> IndigoM ()) -> exk -> exm -> exs -> IndigoM (Var Address) -- | Create contract from raw Lorentz Contract. createLorentzContract :: (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorage st, NiceParameterFull param, HasSideEffects) => Contract param st -> exk -> exm -> exs -> IndigoM (Var Address) assert :: forall x ex. (IsError x, IsExpr ex Bool) => x -> ex -> IndigoM () failWith :: forall r a ex. IsExpr ex a => ex -> IndigoM r failCustom :: forall r tag err ex. (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err, ex :~> err) => Label tag -> ex -> IndigoM r failCustom_ :: forall r tag notVoidErrorMsg. (RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag) => Label tag -> IndigoM r failUnexpected_ :: MText -> IndigoM r assertCustom :: forall tag err errEx ex. (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err, IsExpr errEx err, IsExpr ex Bool) => Label tag -> errEx -> ex -> IndigoM () assertCustom_ :: forall tag notVoidErrorMsg ex. (RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag, IsExpr ex Bool) => Label tag -> ex -> IndigoM () -- | Add a comment in a generated Michelson code justComment :: Text -> IndigoM () -- | Add a comment in a generated Michelson code comment :: CommentType -> IndigoM () -- | Add a comment before and after the given Indigo function code. The -- first argument is the name of the function. commentAroundFun :: Text -> IndigoM a -> IndigoM a -- | Add a comment before and after the given Indigo statement code. The -- first argument is the name of the statement. commentAroundStmt :: Text -> IndigoM a -> IndigoM a -- | Pretty-print an Indigo contract into Michelson code. printIndigoContract :: forall param st. (IsObject st, NiceParameterFull param, NiceStorage st) => Bool -> IndigoContract param st -> LText -- | Generate an Indigo contract documentation. renderIndigoDoc :: forall param st. (IsObject st, NiceParameterFull param) => IndigoContract param st -> LText -- | Prints the pretty-printed Michelson code of an Indigo contract to the -- standard output. -- -- This is intended to be easy to use for newcomers. printAsMichelson :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorage st, MonadIO m) => IndigoContract param st -> m () -- | Saves the pretty-printed Michelson code of an Indigo contract to the -- given file. -- -- This is intended to be easy to use for newcomers. saveAsMichelson :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorage st, MonadIO m, MonadMask m) => IndigoContract param st -> FilePath -> m () -- | Print the generated documentation to the standard output. printDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, MonadIO m) => IndigoContract param st -> m () -- | Save the generated documentation to the given file. saveDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, MonadIO m, MonadMask m) => IndigoContract param st -> FilePath -> m () -- | Defines semantics of if ... then ... else ... construction -- for Indigo where the predicate is a generic exa for which -- IsExpr exa Bool holds ifThenElse :: (IfConstraint a b, IsExpr exa Bool) => exa -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Numerical literal disambiguation value for a Natural, see -- fromInteger. nat :: NumType 'Nat Natural -- | Numerical literal disambiguation value for an Integer, see -- fromInteger. int :: NumType 'Int Integer -- | Numerical literal disambiguation value for a Mutez, see -- fromInteger. mutez :: NumType 'Mtz Mutez -- | Defines numerical literals resolution for Indigo. -- -- It is implemented with an additional NumType argument that -- disambiguates the resulting type. This allows, for example, 1 -- int to be resolved to 1 :: Integer. fromInteger :: Integer -> NumType n t -> t -- | Indigo version of the view macro. It takes a function from -- view argument to view result and a View structure that -- typically comes from a top-level case. view_ :: forall arg r viewExpr exr. (KnownValue arg, NiceParameter r, viewExpr :~> View arg r, exr :~> r, HasSideEffects) => (Expr arg -> IndigoM exr) -> viewExpr -> IndigoM () -- | Flipped version of view_ that is present due to the common -- appearance of flip view parameter $ instr construction. -- -- Semantically we "project" the given parameter inside the body of the -- View construction. project :: forall arg r viewExpr exr. (KnownValue arg, NiceParameter r, viewExpr :~> View arg r, exr :~> r, HasSideEffects) => viewExpr -> (Expr arg -> IndigoM exr) -> IndigoM () -- | Indigo version of the void macro. void_ :: forall a b voidExpr exb. (KnownValue a, IsError (VoidResult b), NiceConstant b, voidExpr :~> Void_ a b, exb :~> b) => (Expr a -> IndigoM exb) -> voidExpr -> IndigoM () -- | Flipped version of void_ that is present due to the common -- appearance of flip void_ parameter $ instr construction. projectVoid :: forall a b voidExpr exb. (KnownValue a, IsError (VoidResult b), NiceConstant b, voidExpr :~> Void_ a b, exb :~> b) => voidExpr -> (Expr a -> IndigoM exb) -> IndigoM () -- | If the first value is greater than the second one, it returns their -- difference. If the values are equal, it returns Nothing. -- Otherwise it fails using the supplied function. subGt0 :: (ex1 :~> Natural, ex2 :~> Natural) => ex1 -> ex2 -> IndigoM () -> IndigoFunction (Maybe Natural)