code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Module4.Task28 where import Prelude hiding (lookup) import qualified Data.List as L class MapLike m where empty :: m k v lookup :: Ord k => k -> m k v -> Maybe v insert :: Ord k => k -> v -> m k v -> m k v delete :: Ord k => k -> m k v -> m k v fromList :: Ord k => [(k,v)] -> m k v fromList [] = empty fromList ((k,v):xs) = insert k v (fromList xs) newtype ListMap k v = ListMap { getListMap :: [(k,v)] } deriving (Eq,Show) instance MapLike ListMap where empty = ListMap [] lookup _ (ListMap []) = Nothing lookup key (ListMap ((k,v):xs)) | k == key = Just v | otherwise = lookup key (ListMap xs) insert key newValue (ListMap []) = ListMap [(key, newValue)] insert key newValue (ListMap ((k,v):xs)) | k == key = ListMap ((k,newValue):xs) | otherwise = let (ListMap t) = insert key newValue (ListMap xs) in ListMap ((k,v):t) delete key l@(ListMap []) = l delete key (ListMap ((k,v):xs)) | k == key = ListMap xs | otherwise = let (ListMap t) = delete key (ListMap xs) in ListMap ((k,v):t)
dstarcev/stepic-haskell
src/Module4/Task28.hs
bsd-3-clause
1,139
0
13
343
603
310
293
31
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Operation ( OperationT , Permission(..) , requirePermission , runOperation ) where import Prelude hiding (null, filter) import Data.Set import Data.Text (Text) import Control.Monad.Trans import Control.Monad.Reader import Control.Monad.State import Control.Monad.Except import Control.Applicative import Control.Monad.Writer.Strict import qualified Database.Persist as DB import Control.Lens import Types import DBTypes import Models data Permission = EditUser UserID | EditTenant TenantID | ViewUser UserID deriving (Eq,Ord,Show) data PermissionError = Requires (Set Permission) newtype OperationT m a = Op { unsafeRunOp :: WriterT (Set Permission) m a } deriving (Functor, Applicative, Monad, Alternative, MonadPlus, Foldable, MonadFix, MonadTrans, MonadIO) deriving instance (MonadReader r m) => MonadReader r (OperationT m) deriving instance (MonadState s m) => MonadState s (OperationT m) deriving instance (MonadError e m) => MonadError e (OperationT m) requirePermission :: Monad m => Permission -> OperationT m () requirePermission = Op . tell . singleton runOperation :: OperationT App a -> User -> ExceptT PermissionError App a runOperation op u@(UserB{_userRole=role}) = do (a,s) <- lift $ runWriterT $ unsafeRunOp op let go s (EditUserDetails) = fromList <$> filterM (\case (EditUser uid) -> hasTenant uid (_userTenantID u) _ -> return False) (toList s) go s (EditTenantDetails) = fromList <$> filterM (\case (EditTenant tid) -> return $ tid == (_userTenantID u) _ -> return False) (toList s) go s _ = return s s' <- lift $ foldM go s (roleCapabilities role) if null s' then return a else throwError $ Requires s' hasTenant :: UserID -> TenantID -> App Bool hasTenant uid tid = runDb $ do tid' <- fmap _dBUserTenantID <$> DB.get uid case tid' of Nothing -> return False Just tid' -> return (tid == tid')
meditans/haskell-webapps
ServantPersistent/src/Operation.hs
mit
2,398
0
18
618
703
374
329
62
6
-- -- -- ----------------- -- Exercise 8.23. ----------------- -- -- -- module E'8'23 where --
pascal-knodel/haskell-craft
_/links/E'8'23.hs
mit
102
0
2
22
14
13
1
1
0
{-# OPTIONS -Wall #-} -- add a few padding cell to the array and see if the performance improves
nushio3/Paraiso
Language/Paraiso/Annotation/Padding.hs
bsd-3-clause
98
0
2
20
4
3
1
1
0
module Robots3.Exact where import Robots3.Data import Autolib.Set import Control.Monad ( guard ) import Data.List ( tails ) clusters :: Set Position -> [ Set Position ] clusters ps = fixpoint cmeet $ do p <- setToList ps ; return $ unitSet p cmeet :: [ Set Position ] -> [ Set Position ] cmeet [] = [] cmeet [c] = [c] cmeet ( c : ds ) = let ds' :: [ Set Position ] ds' = cmeet ds news = do d <- ds' let new :: [ Position ] new = do x <- setToList c y <- setToList d guard $ same_line x y interval_rectangle x y return $ case new of [] -> Left d _ -> Right (d, mkSet new ) combined :: [ Position ] combined = setToList c ++ do Right (d, new) <- news setToList new ++ setToList d solitary :: [ Set Position ] solitary = do Left old <- news return old in if null combined then c : ds' else mkSet combined : solitary exact_hull_points :: Set Position -> Set Position exact_hull_points ps = fixpoint meet ps fixpoint f x = let y = f x in if x == y then x else fixpoint f y meet ps = mkSet $ do (p,q) <- all_pairs ps if same_line p q then interval_rectangle p q else [p,q] all_pairs ps = do p : qs <- tails $ setToList $ ps q <- qs return (p,q)
florianpilz/autotool
src/Robots3/Exact.hs
gpl-2.0
1,325
22
14
432
568
283
285
49
3
----------------------------------------------------------------------------- -- Strict State Thread module -- -- This library provides support for strict state threads, as described -- in the PLDI '94 paper by John Launchbury and Simon Peyton Jones. -- In addition to the monad ST, it also provides mutable variables STRef -- and mutable arrays STArray. -- -- Suitable for use with Hugs 98. ----------------------------------------------------------------------------- module Hugs.ST ( ST(..) , runST , unsafeRunST , RealWorld , stToIO , unsafeIOToST , unsafeSTToIO , STRef -- instance Eq (STRef s a) , newSTRef , readSTRef , writeSTRef , STArray -- instance Eq (STArray s ix elt) , newSTArray , boundsSTArray , readSTArray , writeSTArray , thawSTArray , freezeSTArray , unsafeFreezeSTArray , unsafeReadSTArray , unsafeWriteSTArray ) where import Hugs.Prelude(IO(..)) import Hugs.Array(Array,Ix(index,rangeSize),bounds,elems) import Hugs.IOExts(unsafePerformIO, unsafeCoerce) import Control.Monad ----------------------------------------------------------------------------- -- The ST representation generalizes that of IO (cf. Hugs.Prelude), -- so it can use IO primitives that manipulate local state. newtype ST s a = ST (forall r. (a -> r) -> r) data RealWorld = RealWorld primitive thenStrictST "primbindIO" :: ST s a -> (a -> ST s b) -> ST s b primitive returnST "primretIO" :: a -> ST s a unST :: ST s a -> (a -> r) -> r unST (ST f) = f runST :: (forall s. ST s a) -> a runST m = unST m id unsafeRunST :: ST s a -> a unsafeRunST m = unST m id stToIO :: ST RealWorld a -> IO a stToIO (ST f) = IO f unsafeIOToST :: IO a -> ST s a unsafeIOToST = unsafePerformIO . liftM returnST unsafeSTToIO :: ST s a -> IO a unsafeSTToIO = stToIO . unsafeCoerce instance Functor (ST s) where fmap = liftM instance Monad (ST s) where (>>=) = thenStrictST return = returnST ----------------------------------------------------------------------------- data STRef s a -- implemented as an internal primitive primitive newSTRef "newRef" :: a -> ST s (STRef s a) primitive readSTRef "getRef" :: STRef s a -> ST s a primitive writeSTRef "setRef" :: STRef s a -> a -> ST s () primitive eqSTRef "eqRef" :: STRef s a -> STRef s a -> Bool instance Eq (STRef s a) where (==) = eqSTRef ----------------------------------------------------------------------------- data STArray s ix elt -- implemented as an internal primitive newSTArray :: Ix ix => (ix,ix) -> elt -> ST s (STArray s ix elt) boundsSTArray :: Ix ix => STArray s ix elt -> (ix, ix) readSTArray :: Ix ix => STArray s ix elt -> ix -> ST s elt writeSTArray :: Ix ix => STArray s ix elt -> ix -> elt -> ST s () thawSTArray :: Ix ix => Array ix elt -> ST s (STArray s ix elt) freezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt) unsafeFreezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt) unsafeReadSTArray :: Ix i => STArray s i e -> Int -> ST s e unsafeReadSTArray = primReadArr unsafeWriteSTArray :: Ix i => STArray s i e -> Int -> e -> ST s () unsafeWriteSTArray = primWriteArr newSTArray bs e = primNewArr bs (rangeSize bs) e boundsSTArray a = primBounds a readSTArray a i = unsafeReadSTArray a (index (boundsSTArray a) i) writeSTArray a i e = unsafeWriteSTArray a (index (boundsSTArray a) i) e thawSTArray arr = do stArr <- newSTArray (bounds arr) err sequence_ (zipWith (unsafeWriteSTArray stArr) [0..] (elems arr)) return stArr where err = error "thawArray: element not overwritten" -- shouldnae happen freezeSTArray a = primFreeze a unsafeFreezeSTArray = freezeSTArray -- not as fast as GHC instance Eq (STArray s ix elt) where (==) = eqSTArray primitive primNewArr "IONewArr" :: (a,a) -> Int -> b -> ST s (STArray s a b) primitive primReadArr "IOReadArr" :: STArray s a b -> Int -> ST s b primitive primWriteArr "IOWriteArr" :: STArray s a b -> Int -> b -> ST s () primitive primFreeze "IOFreeze" :: STArray s a b -> ST s (Array a b) primitive primBounds "IOBounds" :: STArray s a b -> (a,a) primitive eqSTArray "IOArrEq" :: STArray s a b -> STArray s a b -> Bool -----------------------------------------------------------------------------
kaoskorobase/mescaline
resources/hugs/packages/hugsbase/Hugs/ST.hs
gpl-3.0
4,589
43
12
1,169
1,353
713
640
-1
-1
module Main where import System.Environment (getArgs) import System.Random (randomIO) import System.Random.MWC (Gen, initialize, uniformR) import System.Directory (getHomeDirectory, createDirectoryIfMissing) import System.FilePath ((</>)) import Control.Monad (liftM, unless) import Control.Monad.Primitive import Data.Word (Word32) import qualified Data.Vector as V import qualified Data.Vector.Unboxed as UV import qualified Data.Vector.Unboxed.Mutable as MV import Data.Vector.Unboxed.Mutable (MVector, write) import Data.Vector.Unboxed (Vector, (!), freeze) import Codec.Picture import FractalArt.SimpleCommandParser import FractalArt.ForeignFunctions type Position = (Int, Int) type Size = (Int, Int) type Color = (Float, Float, Float) type Grid m = MVector m (Bool, Color) aOutputDir, aFileName :: Arg String aOutputDir = Arg "output" 'o' return aFileName = Arg "file" 'f' return aWidth, aHeight :: Arg Int aWidth = Arg "width" 'w' (return . read) aHeight = Arg "height" 'h' (return . read) fNoSetWallpaper :: Flag fNoSetWallpaper = Flag "no-bg" 'n' main :: IO () main = do args <- getArgs home <- getHomeDirectory let workingDir = parseArg aOutputDir args `def` (home </> ".fractalart") let imageFile = parseArg aFileName args `def` (workingDir </> "wallpaper.bmp") createDirectoryIfMissing False workingDir putStrLn $ "Working in: " ++ workingDir size@(width, height) <- do (w,h) <- getScreenSize let nw = parseArg aWidth args `def` w let nh = parseArg aHeight args `def` h return (nw, nh) putStrLn $ "Screen Resolution: " ++ show size seed <- randomIO :: IO Word32 gen <- initialize (V.singleton seed) startPosition <- do x <- uniformR (0, width - 1) gen y <- uniformR (0, height - 1) gen return (x, y) putStrLn "Generating Image..." -- Generate and force evaluation grid <- runBG startPosition size gen putStrLn $ "Saving To: " ++ imageFile -- Create an immutable copy of the grid frozen <- freeze grid let bitmap = UV.map snd frozen writeBitmap imageFile $ createImage size bitmap unless (parseFlag fNoSetWallpaper args) (setWallpaper imageFile) putStrLn "Done" -- | Create an image from a vector of colors createImage :: Size -> Vector Color -> Image PixelRGB8 createImage (width, height) grid = generateImage colorAt width height where colorAt x y = toPixel $ grid ! toIndex (width, height) (x, y) toPixel (r, g, b) = PixelRGB8 (toByte r) (toByte g) (toByte b) toByte f = floor(f * 255) -- | Generate the wallpaper runBG :: PrimMonad m => Position -> Size -> Gen (PrimState m) -> m (Grid (PrimState m)) runBG pos@(x, y) size@(w, h) gen = do grid <- startGrid mapM_ (iter pos size gen grid) [1..iterations] return grid where startGrid = do grid <- MV.replicate (w * h) (False, (0, 0, 0)) col <- startColor write grid (toIndex size pos) (True, col) return grid startColor = do hue <- uniformR (0, 360) gen --sat <- uniform gen return $ hsv hue 0.6 1 iterations = maximum [x, w - 1 - x, y, h - 1 - y] iter :: PrimMonad m => Position -> Size -> Gen (PrimState m) -> Grid (PrimState m) -> Int -> m () iter pos size gen grid n = mapM_ f next where f p = do col <- nextColor grid size gen p write grid (toIndex size p) (True, col) next = filter (isInside size) $ ringAt pos n nextColor :: PrimMonad m => Grid (PrimState m) -> Size -> Gen (PrimState m) -> Position -> m Color nextColor grid size gen pos = do c <- colors i <- uniformR (0, length c - 1) gen m <- modColor (mkRange $ length c) (c !! i) return . clampColor $ m where colors = liftM (map snd . filter isValid) . mapM (MV.read grid . toIndex size) . filter (isInside size) $ ringAt pos 1 mkRange l = 0.006 * 4 / fromIntegral l modColor range (r, g, b) = do mr <- uniformR (-range, range) gen mg <- uniformR (-range, range) gen mb <- uniformR (-range, range) gen return (r + mr, g + mg, b + mb) foldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a foldM' _ z [] = return z foldM' f z (x:xs) = do z' <- f z x z' `seq` foldM' f z' xs hsv :: Float -> Float -> Float -> Color hsv h s v = case hId of 0 -> (v, t, p) 1 -> (q, v, p) 2 -> (p, v, t) 3 -> (p, q, v) 4 -> (t, p, v) 5 -> (v, p, q) _ -> error $ "invalid hue: " ++ show h where hId :: Int hId = floor (h / 60) `mod` 6 f = h / 60 - fromIntegral hId p = v * (1 - s) q = v * (1 - s * f) t = v * (1 - s * (1 - f)) clampColor :: Color -> Color clampColor (r, g, b) = (f r, f g, f b) where f = min 1 . max 0 ringAt :: Position -> Int -> [Position] ringAt (x, y) l = sides ++ top ++ bottom where top = [(n + x, l + y) | n <- [-l .. l]] bottom = [(n + x, -l + y) | n <- [-l .. l]] sides = concat [[(l + x, n + y), (-l + x, n + y)] | n <- [1 - l .. l - 1]] toIndex :: Size -> Position -> Int toIndex (w, _) (x, y) = y * w + x isValid :: (Bool, a) -> Bool isValid = fst isInside :: Size -> Position -> Bool isInside (w, h) (x, y) = inside' x w && inside' y h where inside' n s = (n < s) && (n >= 0)
TomSmeets/FractalArt
src/Main.hs
mit
5,455
0
14
1,577
2,354
1,241
1,113
131
7
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeOperators #-} module T13910 where import Data.Kind import Data.Type.Equality data family Sing (a :: k) class SingKind k where type Demote k = (r :: *) | r -> k fromSing :: Sing (a :: k) -> Demote k toSing :: Demote k -> SomeSing k data SomeSing k where SomeSing :: Sing (a :: k) -> SomeSing k withSomeSing :: forall k r . SingKind k => Demote k -> (forall (a :: k). Sing a -> r) -> r withSomeSing x f = case toSing x of SomeSing x' -> f x' data TyFun :: * -> * -> * type a ~> b = TyFun a b -> * infixr 0 ~> type family Apply (f :: k1 ~> k2) (x :: k1) :: k2 type a @@ b = Apply a b infixl 9 @@ data FunArrow = (:->) | (:~>) class FunType (arr :: FunArrow) where type Fun (k1 :: Type) arr (k2 :: Type) :: Type class FunType arr => AppType (arr :: FunArrow) where type App k1 arr k2 (f :: Fun k1 arr k2) (x :: k1) :: k2 type FunApp arr = (FunType arr, AppType arr) instance FunType (:->) where type Fun k1 (:->) k2 = k1 -> k2 $(return []) -- This is only necessary for GHC 8.0 -- GHC 8.2 is smarter instance AppType (:->) where type App k1 (:->) k2 (f :: k1 -> k2) x = f x instance FunType (:~>) where type Fun k1 (:~>) k2 = k1 ~> k2 $(return []) instance AppType (:~>) where type App k1 (:~>) k2 (f :: k1 ~> k2) x = f @@ x infixr 0 -?> type (-?>) (k1 :: Type) (k2 :: Type) (arr :: FunArrow) = Fun k1 arr k2 data instance Sing (z :: a :~: b) where SRefl :: Sing Refl instance SingKind (a :~: b) where type Demote (a :~: b) = a :~: b fromSing SRefl = Refl toSing Refl = SomeSing SRefl (~>:~:) :: forall (k :: Type) (a :: k) (b :: k) (r :: a :~: b) (p :: forall (y :: k). a :~: y ~> Type). Sing r -> p @@ Refl -> p @@ r (~>:~:) SRefl pRefl = pRefl type WhyReplacePoly (arr :: FunArrow) (from :: t) (p :: (t -?> Type) arr) (y :: t) (e :: from :~: y) = App t arr Type p y data WhyReplacePolySym (arr :: FunArrow) (from :: t) (p :: (t -?> Type) arr) :: forall (y :: t). from :~: y ~> Type type instance Apply (WhyReplacePolySym arr from p :: from :~: y ~> Type) x = WhyReplacePoly arr from p y x replace :: forall (t :: Type) (from :: t) (to :: t) (p :: t -> Type). p from -> from :~: to -> p to replace = replacePoly @(:->) replaceTyFun :: forall (t :: Type) (from :: t) (to :: t) (p :: t ~> Type). p @@ from -> from :~: to -> p @@ to replaceTyFun = replacePoly @(:~>) @_ @_ @_ @p replacePoly :: forall (arr :: FunArrow) (t :: Type) (from :: t) (to :: t) (p :: (t -?> Type) arr). FunApp arr => App t arr Type p from -> from :~: to -> App t arr Type p to replacePoly from eq = withSomeSing eq $ \(singEq :: Sing r) -> (~>:~:) @t @from @to @r @(WhyReplacePolySym arr from p) singEq from type WhyLeibnizPoly (arr :: FunArrow) (f :: (t -?> Type) arr) (a :: t) (z :: t) = App t arr Type f a -> App t arr Type f z data WhyLeibnizPolySym (arr :: FunArrow) (f :: (t -?> Type) arr) (a :: t) :: t ~> Type type instance Apply (WhyLeibnizPolySym arr f a) z = WhyLeibnizPoly arr f a z leibnizPoly :: forall (arr :: FunArrow) (t :: Type) (f :: (t -?> Type) arr) (a :: t) (b :: t). FunApp arr => a :~: b -> App t arr Type f a -> App t arr Type f b leibnizPoly = replaceTyFun @t @a @b @(WhyLeibnizPolySym arr f a) id leibniz :: forall (t :: Type) (f :: t -> Type) (a :: t) (b :: t). a :~: b -> f a -> f b leibniz = replaceTyFun @t @a @b @(WhyLeibnizPolySym (:->) f a) id -- The line above is what you get if you inline the definition of leibnizPoly. -- It causes a panic, however. -- -- An equivalent implementation is commented out below, which does *not* -- cause GHC to panic. -- -- leibniz = leibnizPoly @(:->) leibnizTyFun :: forall (t :: Type) (f :: t ~> Type) (a :: t) (b :: t). a :~: b -> f @@ a -> f @@ b leibnizTyFun = leibnizPoly @(:~>) @_ @f
ezyang/ghc
testsuite/tests/dependent/should_compile/T13910.hs
bsd-3-clause
4,433
93
19
1,313
1,732
994
738
-1
-1
{-# LANGUAGE BangPatterns, CPP, ForeignFunctionInterface, MagicHash, Rank2Types, RecordWildCards, UnboxedTuples, UnliftedFFITypes #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- | -- Module : Data.Text.Array -- Copyright : (c) 2009, 2010, 2011 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Packed, unboxed, heap-resident arrays. Suitable for performance -- critical use, both in terms of large data quantities and high -- speed. -- -- This module is intended to be imported @qualified@, to avoid name -- clashes with "Prelude" functions, e.g. -- -- > import qualified Data.Text.Array as A -- -- The names in this module resemble those in the 'Data.Array' family -- of modules, but are shorter due to the assumption of qualifid -- naming. module Data.Text.Array ( -- * Types Array(Array, aBA) , MArray(MArray, maBA) -- * Functions , copyM , copyI , empty , equal #if defined(ASSERTS) , length #endif , run , run2 , toList , unsafeFreeze , unsafeIndex , new , unsafeWrite ) where #if defined(ASSERTS) -- This fugly hack is brought by GHC's apparent reluctance to deal -- with MagicHash and UnboxedTuples when inferring types. Eek! # define CHECK_BOUNDS(_func_,_len_,_k_) \ if (_k_) < 0 || (_k_) >= (_len_) then error ("Data.Text.Array." ++ (_func_) ++ ": bounds error, offset " ++ show (_k_) ++ ", length " ++ show (_len_)) else #else # define CHECK_BOUNDS(_func_,_len_,_k_) #endif #include "MachDeps.h" #if defined(ASSERTS) import Control.Exception (assert) #endif #if __GLASGOW_HASKELL__ >= 702 import Control.Monad.ST.Unsafe (unsafeIOToST) #else import Control.Monad.ST (unsafeIOToST) #endif import Data.Bits ((.&.), xor) import Data.Text.Internal.Unsafe (inlinePerformIO) import Data.Text.Internal.Unsafe.Shift (shiftL, shiftR) #if __GLASGOW_HASKELL__ >= 703 import Foreign.C.Types (CInt(CInt), CSize(CSize)) #else import Foreign.C.Types (CInt, CSize) #endif import GHC.Base (ByteArray#, MutableByteArray#, Int(..), indexWord16Array#, newByteArray#, unsafeCoerce#, writeWord16Array#) import GHC.ST (ST(..), runST) import GHC.Word (Word16(..)) import Prelude hiding (length, read) -- | Immutable array type. data Array = Array { aBA :: ByteArray# #if defined(ASSERTS) , aLen :: {-# UNPACK #-} !Int -- length (in units of Word16, not bytes) #endif } -- | Mutable array type, for use in the ST monad. data MArray s = MArray { maBA :: MutableByteArray# s #if defined(ASSERTS) , maLen :: {-# UNPACK #-} !Int -- length (in units of Word16, not bytes) #endif } #if defined(ASSERTS) -- | Operations supported by all arrays. class IArray a where -- | Return the length of an array. length :: a -> Int instance IArray Array where length = aLen {-# INLINE length #-} instance IArray (MArray s) where length = maLen {-# INLINE length #-} #endif -- | Create an uninitialized mutable array. new :: forall s. Int -> ST s (MArray s) new n | n < 0 || n .&. highBit /= 0 = array_size_error | otherwise = ST $ \s1# -> case newByteArray# len# s1# of (# s2#, marr# #) -> (# s2#, MArray marr# #if defined(ASSERTS) n #endif #) where !(I# len#) = bytesInArray n highBit = maxBound `xor` (maxBound `shiftR` 1) {-# INLINE new #-} array_size_error :: a array_size_error = error "Data.Text.Array.new: size overflow" -- | Freeze a mutable array. Do not mutate the 'MArray' afterwards! unsafeFreeze :: MArray s -> ST s Array unsafeFreeze MArray{..} = ST $ \s# -> (# s#, Array (unsafeCoerce# maBA) #if defined(ASSERTS) maLen #endif #) {-# INLINE unsafeFreeze #-} -- | Indicate how many bytes would be used for an array of the given -- size. bytesInArray :: Int -> Int bytesInArray n = n `shiftL` 1 {-# INLINE bytesInArray #-} -- | Unchecked read of an immutable array. May return garbage or -- crash on an out-of-bounds access. unsafeIndex :: Array -> Int -> Word16 unsafeIndex Array{..} i@(I# i#) = CHECK_BOUNDS("unsafeIndex",aLen,i) case indexWord16Array# aBA i# of r# -> (W16# r#) {-# INLINE unsafeIndex #-} -- | Unchecked write of a mutable array. May return garbage or crash -- on an out-of-bounds access. unsafeWrite :: MArray s -> Int -> Word16 -> ST s () unsafeWrite MArray{..} i@(I# i#) (W16# e#) = ST $ \s1# -> CHECK_BOUNDS("unsafeWrite",maLen,i) case writeWord16Array# maBA i# e# s1# of s2# -> (# s2#, () #) {-# INLINE unsafeWrite #-} -- | Convert an immutable array to a list. toList :: Array -> Int -> Int -> [Word16] toList ary off len = loop 0 where loop i | i < len = unsafeIndex ary (off+i) : loop (i+1) | otherwise = [] -- | An empty immutable array. empty :: Array empty = runST (new 0 >>= unsafeFreeze) -- | Run an action in the ST monad and return an immutable array of -- its result. run :: (forall s. ST s (MArray s)) -> Array run k = runST (k >>= unsafeFreeze) -- | Run an action in the ST monad and return an immutable array of -- its result paired with whatever else the action returns. run2 :: (forall s. ST s (MArray s, a)) -> (Array, a) run2 k = runST (do (marr,b) <- k arr <- unsafeFreeze marr return (arr,b)) {-# INLINE run2 #-} -- | Copy some elements of a mutable array. copyM :: MArray s -- ^ Destination -> Int -- ^ Destination offset -> MArray s -- ^ Source -> Int -- ^ Source offset -> Int -- ^ Count -> ST s () copyM dest didx src sidx count | count <= 0 = return () | otherwise = #if defined(ASSERTS) assert (sidx + count <= length src) . assert (didx + count <= length dest) . #endif unsafeIOToST $ memcpyM (maBA dest) (fromIntegral didx) (maBA src) (fromIntegral sidx) (fromIntegral count) {-# INLINE copyM #-} -- | Copy some elements of an immutable array. copyI :: MArray s -- ^ Destination -> Int -- ^ Destination offset -> Array -- ^ Source -> Int -- ^ Source offset -> Int -- ^ First offset in destination /not/ to -- copy (i.e. /not/ length) -> ST s () copyI dest i0 src j0 top | i0 >= top = return () | otherwise = unsafeIOToST $ memcpyI (maBA dest) (fromIntegral i0) (aBA src) (fromIntegral j0) (fromIntegral (top-i0)) {-# INLINE copyI #-} -- | Compare portions of two arrays for equality. No bounds checking -- is performed. equal :: Array -- ^ First -> Int -- ^ Offset into first -> Array -- ^ Second -> Int -- ^ Offset into second -> Int -- ^ Count -> Bool equal arrA offA arrB offB count = inlinePerformIO $ do i <- memcmp (aBA arrA) (fromIntegral offA) (aBA arrB) (fromIntegral offB) (fromIntegral count) return $! i == 0 {-# INLINE equal #-} foreign import ccall unsafe "_hs_text_memcpy" memcpyI :: MutableByteArray# s -> CSize -> ByteArray# -> CSize -> CSize -> IO () foreign import ccall unsafe "_hs_text_memcmp" memcmp :: ByteArray# -> CSize -> ByteArray# -> CSize -> CSize -> IO CInt foreign import ccall unsafe "_hs_text_memcpy" memcpyM :: MutableByteArray# s -> CSize -> MutableByteArray# s -> CSize -> CSize -> IO ()
beni55/text
Data/Text/Array.hs
bsd-2-clause
7,801
0
12
2,199
1,612
904
708
-1
-1
{-# LANGUAGE OverloadedStrings #-} module RFC2616 ( Header(..) , Request(..) , Response(..) , request , response ) where import Control.Applicative import Data.Attoparsec.ByteString as P import Data.Attoparsec.ByteString.Char8 (char8, endOfLine, isDigit_w8) import Data.ByteString (ByteString) import Data.Word (Word8) import Data.Attoparsec.ByteString.Char8 (isEndOfLine, isHorizontalSpace) isToken :: Word8 -> Bool isToken w = w <= 127 && notInClass "\0-\31()<>@,;:\\\"/[]?={} \t" w skipSpaces :: Parser () skipSpaces = satisfy isHorizontalSpace *> skipWhile isHorizontalSpace data Request = Request { requestMethod :: ByteString , requestUri :: ByteString , requestVersion :: ByteString } deriving (Eq, Ord, Show) httpVersion :: Parser ByteString httpVersion = "HTTP/" *> P.takeWhile (\c -> isDigit_w8 c || c == 46) requestLine :: Parser Request requestLine = Request <$> (takeWhile1 isToken <* char8 ' ') <*> (takeWhile1 (/=32) <* char8 ' ') <*> (httpVersion <* endOfLine) data Header = Header { headerName :: ByteString , headerValue :: [ByteString] } deriving (Eq, Ord, Show) messageHeader :: Parser Header messageHeader = Header <$> (P.takeWhile isToken <* char8 ':' <* skipWhile isHorizontalSpace) <*> ((:) <$> (takeTill isEndOfLine <* endOfLine) <*> (many $ skipSpaces *> takeTill isEndOfLine <* endOfLine)) request :: Parser (Request, [Header]) request = (,) <$> requestLine <*> many messageHeader <* endOfLine data Response = Response { responseVersion :: ByteString , responseCode :: ByteString , responseMsg :: ByteString } deriving (Eq, Ord, Show) responseLine :: Parser Response responseLine = Response <$> (httpVersion <* char8 ' ') <*> (P.takeWhile isDigit_w8 <* char8 ' ') <*> (takeTill isEndOfLine <* endOfLine) response :: Parser (Response, [Header]) response = (,) <$> responseLine <*> many messageHeader <* endOfLine
beni55/attoparsec
examples/RFC2616.hs
bsd-3-clause
2,052
0
11
467
605
337
268
51
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="fa-IR"> <title>Highlighter</title> <maps> <homeID>highlighter</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/highlighter/src/main/javahelp/help_fa_IR/helpset_fa_IR.hs
apache-2.0
964
77
66
155
404
205
199
-1
-1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- Stg to C--: heap management functions -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module StgCmmHeap ( getVirtHp, setVirtHp, setRealHp, getHpRelOffset, entryHeapCheck, altHeapCheck, noEscapeHeapCheck, altHeapCheckReturnsTo, heapStackCheckGen, entryHeapCheck', mkStaticClosureFields, mkStaticClosure, allocDynClosure, allocDynClosureCmm, allocHeapClosure, emitSetDynHdr ) where #include "HsVersions.h" import StgSyn import CLabel import StgCmmLayout import StgCmmUtils import StgCmmMonad import StgCmmProf (profDynAlloc, dynProfHdr, staticProfHdr) import StgCmmTicky import StgCmmClosure import StgCmmEnv import MkGraph import Hoopl import SMRep import Cmm import CmmUtils import CostCentre import IdInfo( CafInfo(..), mayHaveCafRefs ) import Id ( Id ) import Module import DynFlags import FastString( mkFastString, fsLit ) import Panic( sorry ) #if __GLASGOW_HASKELL__ >= 709 import Prelude hiding ((<*>)) #endif import Control.Monad (when) import Data.Maybe (isJust) ----------------------------------------------------------- -- Initialise dynamic heap objects ----------------------------------------------------------- allocDynClosure :: Maybe Id -> CmmInfoTable -> LambdaFormInfo -> CmmExpr -- Cost Centre to stick in the object -> CmmExpr -- Cost Centre to blame for this alloc -- (usually the same; sometimes "OVERHEAD") -> [(NonVoid StgArg, VirtualHpOffset)] -- Offsets from start of object -- ie Info ptr has offset zero. -- No void args in here -> FCode CmmExpr -- returns Hp+n allocDynClosureCmm :: Maybe Id -> CmmInfoTable -> LambdaFormInfo -> CmmExpr -> CmmExpr -> [(CmmExpr, ByteOff)] -> FCode CmmExpr -- returns Hp+n -- allocDynClosure allocates the thing in the heap, -- and modifies the virtual Hp to account for this. -- The second return value is the graph that sets the value of the -- returned LocalReg, which should point to the closure after executing -- the graph. -- allocDynClosure returns an (Hp+8) CmmExpr, and hence the result is -- only valid until Hp is changed. The caller should assign the -- result to a LocalReg if it is required to remain live. -- -- The reason we don't assign it to a LocalReg here is that the caller -- is often about to call regIdInfo, which immediately assigns the -- result of allocDynClosure to a new temp in order to add the tag. -- So by not generating a LocalReg here we avoid a common source of -- new temporaries and save some compile time. This can be quite -- significant - see test T4801. allocDynClosure mb_id info_tbl lf_info use_cc _blame_cc args_w_offsets = do let (args, offsets) = unzip args_w_offsets cmm_args <- mapM getArgAmode args -- No void args allocDynClosureCmm mb_id info_tbl lf_info use_cc _blame_cc (zip cmm_args offsets) allocDynClosureCmm mb_id info_tbl lf_info use_cc _blame_cc amodes_w_offsets = do -- SAY WHAT WE ARE ABOUT TO DO let rep = cit_rep info_tbl tickyDynAlloc mb_id rep lf_info let info_ptr = CmmLit (CmmLabel (cit_lbl info_tbl)) allocHeapClosure rep info_ptr use_cc amodes_w_offsets -- | Low-level heap object allocation. allocHeapClosure :: SMRep -- ^ representation of the object -> CmmExpr -- ^ info pointer -> CmmExpr -- ^ cost centre -> [(CmmExpr,ByteOff)] -- ^ payload -> FCode CmmExpr -- ^ returns the address of the object allocHeapClosure rep info_ptr use_cc payload = do profDynAlloc rep use_cc virt_hp <- getVirtHp -- Find the offset of the info-ptr word let info_offset = virt_hp + 1 -- info_offset is the VirtualHpOffset of the first -- word of the new object -- Remember, virtHp points to last allocated word, -- ie 1 *before* the info-ptr word of new object. base <- getHpRelOffset info_offset emitComment $ mkFastString "allocHeapClosure" emitSetDynHdr base info_ptr use_cc -- Fill in the fields hpStore base payload -- Bump the virtual heap pointer dflags <- getDynFlags setVirtHp (virt_hp + heapClosureSizeW dflags rep) return base emitSetDynHdr :: CmmExpr -> CmmExpr -> CmmExpr -> FCode () emitSetDynHdr base info_ptr ccs = do dflags <- getDynFlags hpStore base (zip (header dflags) [0, wORD_SIZE dflags ..]) where header :: DynFlags -> [CmmExpr] header dflags = [info_ptr] ++ dynProfHdr dflags ccs -- ToDof: Parallel stuff -- No ticky header -- Store the item (expr,off) in base[off] hpStore :: CmmExpr -> [(CmmExpr, ByteOff)] -> FCode () hpStore base vals = do dflags <- getDynFlags sequence_ $ [ emitStore (cmmOffsetB dflags base off) val | (val,off) <- vals ] ----------------------------------------------------------- -- Layout of static closures ----------------------------------------------------------- -- Make a static closure, adding on any extra padding needed for CAFs, -- and adding a static link field if necessary. mkStaticClosureFields :: DynFlags -> CmmInfoTable -> CostCentreStack -> CafInfo -> [CmmLit] -- Payload -> [CmmLit] -- The full closure mkStaticClosureFields dflags info_tbl ccs caf_refs payload = mkStaticClosure dflags info_lbl ccs payload padding static_link_field saved_info_field where info_lbl = cit_lbl info_tbl -- CAFs must have consistent layout, regardless of whether they -- are actually updatable or not. The layout of a CAF is: -- -- 3 saved_info -- 2 static_link -- 1 indirectee -- 0 info ptr -- -- the static_link and saved_info fields must always be in the -- same place. So we use isThunkRep rather than closureUpdReqd -- here: is_caf = isThunkRep (cit_rep info_tbl) padding | is_caf && null payload = [mkIntCLit dflags 0] | otherwise = [] static_link_field | is_caf || staticClosureNeedsLink (mayHaveCafRefs caf_refs) info_tbl = [static_link_value] | otherwise = [] saved_info_field | is_caf = [mkIntCLit dflags 0] | otherwise = [] -- For a static constructor which has NoCafRefs, we set the -- static link field to a non-zero value so the garbage -- collector will ignore it. static_link_value | mayHaveCafRefs caf_refs = mkIntCLit dflags 0 | otherwise = mkIntCLit dflags 3 -- No CAF refs -- See Note [STATIC_LINK fields] -- in rts/sm/Storage.h mkStaticClosure :: DynFlags -> CLabel -> CostCentreStack -> [CmmLit] -> [CmmLit] -> [CmmLit] -> [CmmLit] -> [CmmLit] mkStaticClosure dflags info_lbl ccs payload padding static_link_field saved_info_field = [CmmLabel info_lbl] ++ staticProfHdr dflags ccs ++ concatMap (padLitToWord dflags) payload ++ padding ++ static_link_field ++ saved_info_field -- JD: Simon had ellided this padding, but without it the C back end asserts -- failure. Maybe it's a bad assertion, and this padding is indeed unnecessary? padLitToWord :: DynFlags -> CmmLit -> [CmmLit] padLitToWord dflags lit = lit : padding pad_length where width = typeWidth (cmmLitType dflags lit) pad_length = wORD_SIZE dflags - widthInBytes width :: Int padding n | n <= 0 = [] | n `rem` 2 /= 0 = CmmInt 0 W8 : padding (n-1) | n `rem` 4 /= 0 = CmmInt 0 W16 : padding (n-2) | n `rem` 8 /= 0 = CmmInt 0 W32 : padding (n-4) | otherwise = CmmInt 0 W64 : padding (n-8) ----------------------------------------------------------- -- Heap overflow checking ----------------------------------------------------------- {- Note [Heap checks] ~~~~~~~~~~~~~~~~~~ Heap checks come in various forms. We provide the following entry points to the runtime system, all of which use the native C-- entry convention. * gc() performs garbage collection and returns nothing to its caller * A series of canned entry points like r = gc_1p( r ) where r is a pointer. This performs gc, and then returns its argument r to its caller. * A series of canned entry points like gcfun_2p( f, x, y ) where f is a function closure of arity 2 This performs garbage collection, keeping alive the three argument ptrs, and then tail-calls f(x,y) These are used in the following circumstances * entryHeapCheck: Function entry (a) With a canned GC entry sequence f( f_clo, x:ptr, y:ptr ) { Hp = Hp+8 if Hp > HpLim goto L ... L: HpAlloc = 8 jump gcfun_2p( f_clo, x, y ) } Note the tail call to the garbage collector; it should do no register shuffling (b) No canned sequence f( f_clo, x:ptr, y:ptr, ...etc... ) { T: Hp = Hp+8 if Hp > HpLim goto L ... L: HpAlloc = 8 call gc() -- Needs an info table goto T } * altHeapCheck: Immediately following an eval Started as case f x y of r { (p,q) -> rhs } (a) With a canned sequence for the results of f (which is the very common case since all boxed cases return just one pointer ... r = f( x, y ) K: -- K needs an info table Hp = Hp+8 if Hp > HpLim goto L ...code for rhs... L: r = gc_1p( r ) goto K } Here, the info table needed by the call to gc_1p should be the *same* as the one for the call to f; the C-- optimiser spots this sharing opportunity) (b) No canned sequence for results of f Note second info table ... (r1,r2,r3) = call f( x, y ) K: Hp = Hp+8 if Hp > HpLim goto L ...code for rhs... L: call gc() -- Extra info table here goto K * generalHeapCheck: Anywhere else e.g. entry to thunk case branch *not* following eval, or let-no-escape Exactly the same as the previous case: K: -- K needs an info table Hp = Hp+8 if Hp > HpLim goto L ... L: call gc() goto K -} -------------------------------------------------------------- -- A heap/stack check at a function or thunk entry point. entryHeapCheck :: ClosureInfo -> Maybe LocalReg -- Function (closure environment) -> Int -- Arity -- not same as len args b/c of voids -> [LocalReg] -- Non-void args (empty for thunk) -> FCode () -> FCode () entryHeapCheck cl_info nodeSet arity args code = entryHeapCheck' is_fastf node arity args code where node = case nodeSet of Just r -> CmmReg (CmmLocal r) Nothing -> CmmLit (CmmLabel $ staticClosureLabel cl_info) is_fastf = case closureFunInfo cl_info of Just (_, ArgGen _) -> False _otherwise -> True -- | lower-level version for CmmParse entryHeapCheck' :: Bool -- is a known function pattern -> CmmExpr -- expression for the closure pointer -> Int -- Arity -- not same as len args b/c of voids -> [LocalReg] -- Non-void args (empty for thunk) -> FCode () -> FCode () entryHeapCheck' is_fastf node arity args code = do dflags <- getDynFlags let is_thunk = arity == 0 args' = map (CmmReg . CmmLocal) args stg_gc_fun = CmmReg (CmmGlobal GCFun) stg_gc_enter1 = CmmReg (CmmGlobal GCEnter1) {- Thunks: jump stg_gc_enter_1 Function (fast): call (NativeNode) stg_gc_fun(fun, args) Function (slow): call (slow) stg_gc_fun(fun, args) -} gc_call upd | is_thunk = mkJump dflags NativeNodeCall stg_gc_enter1 [node] upd | is_fastf = mkJump dflags NativeNodeCall stg_gc_fun (node : args') upd | otherwise = mkJump dflags Slow stg_gc_fun (node : args') upd updfr_sz <- getUpdFrameOff loop_id <- newLabelC emitLabel loop_id heapCheck True True (gc_call updfr_sz <*> mkBranch loop_id) code -- ------------------------------------------------------------ -- A heap/stack check in a case alternative -- If there are multiple alts and we need to GC, but don't have a -- continuation already (the scrut was simple), then we should -- pre-generate the continuation. (if there are multiple alts it is -- always a canned GC point). -- altHeapCheck: -- If we have a return continuation, -- then if it is a canned GC pattern, -- then we do mkJumpReturnsTo -- else we do a normal call to stg_gc_noregs -- else if it is a canned GC pattern, -- then generate the continuation and do mkCallReturnsTo -- else we do a normal call to stg_gc_noregs altHeapCheck :: [LocalReg] -> FCode a -> FCode a altHeapCheck regs code = altOrNoEscapeHeapCheck False regs code altOrNoEscapeHeapCheck :: Bool -> [LocalReg] -> FCode a -> FCode a altOrNoEscapeHeapCheck checkYield regs code = do dflags <- getDynFlags case cannedGCEntryPoint dflags regs of Nothing -> genericGC checkYield code Just gc -> do lret <- newLabelC let (off, _, copyin) = copyInOflow dflags NativeReturn (Young lret) regs [] lcont <- newLabelC tscope <- getTickScope emitOutOfLine lret (copyin <*> mkBranch lcont, tscope) emitLabel lcont cannedGCReturnsTo checkYield False gc regs lret off code altHeapCheckReturnsTo :: [LocalReg] -> Label -> ByteOff -> FCode a -> FCode a altHeapCheckReturnsTo regs lret off code = do dflags <- getDynFlags case cannedGCEntryPoint dflags regs of Nothing -> genericGC False code Just gc -> cannedGCReturnsTo False True gc regs lret off code -- noEscapeHeapCheck is implemented identically to altHeapCheck (which -- is more efficient), but cannot be optimized away in the non-allocating -- case because it may occur in a loop noEscapeHeapCheck :: [LocalReg] -> FCode a -> FCode a noEscapeHeapCheck regs code = altOrNoEscapeHeapCheck True regs code cannedGCReturnsTo :: Bool -> Bool -> CmmExpr -> [LocalReg] -> Label -> ByteOff -> FCode a -> FCode a cannedGCReturnsTo checkYield cont_on_stack gc regs lret off code = do dflags <- getDynFlags updfr_sz <- getUpdFrameOff heapCheck False checkYield (gc_call dflags gc updfr_sz) code where reg_exprs = map (CmmReg . CmmLocal) regs -- Note [stg_gc arguments] -- NB. we use the NativeReturn convention for passing arguments -- to the canned heap-check routines, because we are in a case -- alternative and hence the [LocalReg] was passed to us in the -- NativeReturn convention. gc_call dflags label sp | cont_on_stack = mkJumpReturnsTo dflags label NativeReturn reg_exprs lret off sp | otherwise = mkCallReturnsTo dflags label NativeReturn reg_exprs lret off sp [] genericGC :: Bool -> FCode a -> FCode a genericGC checkYield code = do updfr_sz <- getUpdFrameOff lretry <- newLabelC emitLabel lretry call <- mkCall generic_gc (GC, GC) [] [] updfr_sz [] heapCheck False checkYield (call <*> mkBranch lretry) code cannedGCEntryPoint :: DynFlags -> [LocalReg] -> Maybe CmmExpr cannedGCEntryPoint dflags regs = case map localRegType regs of [] -> Just (mkGcLabel "stg_gc_noregs") [ty] | isGcPtrType ty -> Just (mkGcLabel "stg_gc_unpt_r1") | isFloatType ty -> case width of W32 -> Just (mkGcLabel "stg_gc_f1") W64 -> Just (mkGcLabel "stg_gc_d1") _ -> Nothing | width == wordWidth dflags -> Just (mkGcLabel "stg_gc_unbx_r1") | width == W64 -> Just (mkGcLabel "stg_gc_l1") | otherwise -> Nothing where width = typeWidth ty [ty1,ty2] | isGcPtrType ty1 && isGcPtrType ty2 -> Just (mkGcLabel "stg_gc_pp") [ty1,ty2,ty3] | isGcPtrType ty1 && isGcPtrType ty2 && isGcPtrType ty3 -> Just (mkGcLabel "stg_gc_ppp") [ty1,ty2,ty3,ty4] | isGcPtrType ty1 && isGcPtrType ty2 && isGcPtrType ty3 && isGcPtrType ty4 -> Just (mkGcLabel "stg_gc_pppp") _otherwise -> Nothing -- Note [stg_gc arguments] -- It might seem that we could avoid passing the arguments to the -- stg_gc function, because they are already in the right registers. -- While this is usually the case, it isn't always. Sometimes the -- code generator has cleverly avoided the eval in a case, e.g. in -- ffi/should_run/4221.hs we found -- -- case a_r1mb of z -- FunPtr x y -> ... -- -- where a_r1mb is bound a top-level constructor, and is known to be -- evaluated. The codegen just assigns x, y and z, and continues; -- R1 is never assigned. -- -- So we'll have to rely on optimisations to eliminatethese -- assignments where possible. -- | The generic GC procedure; no params, no results generic_gc :: CmmExpr generic_gc = mkGcLabel "stg_gc_noregs" -- | Create a CLabel for calling a garbage collector entry point mkGcLabel :: String -> CmmExpr mkGcLabel s = CmmLit (CmmLabel (mkCmmCodeLabel rtsUnitId (fsLit s))) ------------------------------- heapCheck :: Bool -> Bool -> CmmAGraph -> FCode a -> FCode a heapCheck checkStack checkYield do_gc code = getHeapUsage $ \ hpHw -> -- Emit heap checks, but be sure to do it lazily so -- that the conditionals on hpHw don't cause a black hole do { dflags <- getDynFlags ; let mb_alloc_bytes | hpHw > mBLOCK_SIZE = sorry $ unlines [" Trying to allocate more than "++show mBLOCK_SIZE++" bytes.", "", "This is currently not possible due to a limitation of GHC's code generator.", "See http://hackage.haskell.org/trac/ghc/ticket/4505 for details.", "Suggestion: read data from a file instead of having large static data", "structures in code."] | hpHw > 0 = Just (mkIntExpr dflags (hpHw * (wORD_SIZE dflags))) | otherwise = Nothing where mBLOCK_SIZE = bLOCKS_PER_MBLOCK dflags * bLOCK_SIZE_W dflags stk_hwm | checkStack = Just (CmmLit CmmHighStackMark) | otherwise = Nothing ; codeOnly $ do_checks stk_hwm checkYield mb_alloc_bytes do_gc ; tickyAllocHeap True hpHw ; setRealHp hpHw ; code } heapStackCheckGen :: Maybe CmmExpr -> Maybe CmmExpr -> FCode () heapStackCheckGen stk_hwm mb_bytes = do updfr_sz <- getUpdFrameOff lretry <- newLabelC emitLabel lretry call <- mkCall generic_gc (GC, GC) [] [] updfr_sz [] do_checks stk_hwm False mb_bytes (call <*> mkBranch lretry) -- Note [Single stack check] -- ~~~~~~~~~~~~~~~~~~~~~~~~~ -- When compiling a function we can determine how much stack space it -- will use. We therefore need to perform only a single stack check at -- the beginning of a function to see if we have enough stack space. -- -- The check boils down to comparing Sp-N with SpLim, where N is the -- amount of stack space needed (see Note [Stack usage] below). *BUT* -- at this stage of the pipeline we are not supposed to refer to Sp -- itself, because the stack is not yet manifest, so we don't quite -- know where Sp pointing. -- So instead of referring directly to Sp - as we used to do in the -- past - the code generator uses (old + 0) in the stack check. That -- is the address of the first word of the old area, so if we add N -- we'll get the address of highest used word. -- -- This makes the check robust. For example, while we need to perform -- only one stack check for each function, we could in theory place -- more stack checks later in the function. They would be redundant, -- but not incorrect (in a sense that they should not change program -- behaviour). We need to make sure however that a stack check -- inserted after incrementing the stack pointer checks for a -- respectively smaller stack space. This would not be the case if the -- code generator produced direct references to Sp. By referencing -- (old + 0) we make sure that we always check for a correct amount of -- stack: when converting (old + 0) to Sp the stack layout phase takes -- into account changes already made to stack pointer. The idea for -- this change came from observations made while debugging #8275. -- Note [Stack usage] -- ~~~~~~~~~~~~~~~~~~ -- At the moment we convert from STG to Cmm we don't know N, the -- number of bytes of stack that the function will use, so we use a -- special late-bound CmmLit, namely -- CmmHighStackMark -- to stand for the number of bytes needed. When the stack is made -- manifest, the number of bytes needed is calculated, and used to -- replace occurrences of CmmHighStackMark -- -- The (Maybe CmmExpr) passed to do_checks is usually -- Just (CmmLit CmmHighStackMark) -- but can also (in certain hand-written RTS functions) -- Just (CmmLit 8) or some other fixed valuet -- If it is Nothing, we don't generate a stack check at all. do_checks :: Maybe CmmExpr -- Should we check the stack? -- See Note [Stack usage] -> Bool -- Should we check for preemption? -> Maybe CmmExpr -- Heap headroom (bytes) -> CmmAGraph -- What to do on failure -> FCode () do_checks mb_stk_hwm checkYield mb_alloc_lit do_gc = do dflags <- getDynFlags gc_id <- newLabelC let Just alloc_lit = mb_alloc_lit bump_hp = cmmOffsetExprB dflags (CmmReg hpReg) alloc_lit -- Sp overflow if ((old + 0) - CmmHighStack < SpLim) -- At the beginning of a function old + 0 = Sp -- See Note [Single stack check] sp_oflo sp_hwm = CmmMachOp (mo_wordULt dflags) [CmmMachOp (MO_Sub (typeWidth (cmmRegType dflags spReg))) [CmmStackSlot Old 0, sp_hwm], CmmReg spLimReg] -- Hp overflow if (Hp > HpLim) -- (Hp has been incremented by now) -- HpLim points to the LAST WORD of valid allocation space. hp_oflo = CmmMachOp (mo_wordUGt dflags) [CmmReg hpReg, CmmReg (CmmGlobal HpLim)] alloc_n = mkAssign (CmmGlobal HpAlloc) alloc_lit case mb_stk_hwm of Nothing -> return () Just stk_hwm -> tickyStackCheck >> (emit =<< mkCmmIfGoto (sp_oflo stk_hwm) gc_id) -- Emit new label that might potentially be a header -- of a self-recursive tail call. -- See Note [Self-recursive loop header]. self_loop_info <- getSelfLoop case self_loop_info of Just (_, loop_header_id, _) | checkYield && isJust mb_stk_hwm -> emitLabel loop_header_id _otherwise -> return () if (isJust mb_alloc_lit) then do tickyHeapCheck emitAssign hpReg bump_hp emit =<< mkCmmIfThen hp_oflo (alloc_n <*> mkBranch gc_id) else do when (checkYield && not (gopt Opt_OmitYields dflags)) $ do -- Yielding if HpLim == 0 let yielding = CmmMachOp (mo_wordEq dflags) [CmmReg (CmmGlobal HpLim), CmmLit (zeroCLit dflags)] emit =<< mkCmmIfGoto yielding gc_id tscope <- getTickScope emitOutOfLine gc_id (do_gc, tscope) -- this is expected to jump back somewhere -- Test for stack pointer exhaustion, then -- bump heap pointer, and test for heap exhaustion -- Note that we don't move the heap pointer unless the -- stack check succeeds. Otherwise we might end up -- with slop at the end of the current block, which can -- confuse the LDV profiler. -- Note [Self-recursive loop header] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- Self-recursive loop header is required by loopification optimization (See -- Note [Self-recursive tail calls] in StgCmmExpr). We emit it if: -- -- 1. There is information about self-loop in the FCode environment. We don't -- check the binder (first component of the self_loop_info) because we are -- certain that if the self-loop info is present then we are compiling the -- binder body. Reason: the only possible way to get here with the -- self_loop_info present is from closureCodeBody. -- -- 2. checkYield && isJust mb_stk_hwm. checkYield tells us that it is possible -- to preempt the heap check (see #367 for motivation behind this check). It -- is True for heap checks placed at the entry to a function and -- let-no-escape heap checks but false for other heap checks (eg. in case -- alternatives or created from hand-written high-level Cmm). The second -- check (isJust mb_stk_hwm) is true for heap checks at the entry to a -- function and some heap checks created in hand-written Cmm. Otherwise it -- is Nothing. In other words the only situation when both conditions are -- true is when compiling stack and heap checks at the entry to a -- function. This is the only situation when we want to emit a self-loop -- label.
GaloisInc/halvm-ghc
compiler/codeGen/StgCmmHeap.hs
bsd-3-clause
26,199
0
20
7,461
3,813
1,978
1,835
307
8
-- Test for #2188 module TH_scope where f g = [d| f :: Int f = g g :: Int g = 4 |]
sdiehl/ghc
testsuite/tests/quotes/TH_scope.hs
bsd-3-clause
115
0
5
56
17
12
5
-1
-1
module DoIn1 where --A definition can be removed if it is not used by other declarations. --Where a definition is removed, it's type signature should also be removed. --In this Example: remove the defintion 'k' io s = do let k = reverse s s <- getLine let q =(s ++ s) putStr q putStr "foo"
mpickering/HaRe
old/testing/removeDef/DoIn1.hs
bsd-3-clause
342
0
11
108
62
30
32
10
1
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-} {-# LANGUAGE EmptyCase, LambdaCase #-} {-# LANGUAGE TypeFamilies, UndecidableInstances #-} -- Check some type families and type synonyms module EmptyCase003 where type family A (a :: *) :: * -- Conservatively considered non-exhaustive (A a missing), -- since A a does not reduce to anything. f1 :: A a -> a -> b f1 = \case data Void type family B (a :: *) :: * type instance B a = Void -- Exhaustive f2 :: B a -> b f2 = \case type family C (a :: *) :: * type instance C Int = Char type instance C Bool = Void -- Non-exhaustive (C a missing, no info about `a`) f3 :: C a -> a -> b f3 = \case -- Non-exhaustive (_ :: Char missing): C Int rewrites -- to Char (which is trivially inhabited) f4 :: C Int -> a f4 = \case -- Exhaustive: C Bool rewrites to Void f5 :: C Bool -> a f5 = \case -- type family D (a :: *) :: * -- type instance D x = D x -- non-terminating -- -- -- Exhaustive but *impossible* to detect that, since rewriting -- -- D Int does not terminate (the checker should loop). -- f6 :: D Int -> a -- f6 = \case data Zero data Succ n type TenC n = Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ n))))))))) type Ten = TenC Zero type Hundred = TenC (TenC (TenC (TenC (TenC (TenC (TenC (TenC (TenC (TenC Zero))))))))) type family E (n :: *) (a :: *) :: * type instance E Zero b = b type instance E (Succ n) b = E n b -- Exhaustive (10 rewrites) f7 :: E Ten Void -> b f7 = \case -- Exhaustive (100 rewrites) f8 :: E Hundred Void -> b f8 = \case type family Add (a :: *) (b :: *) :: * type instance Add Zero m = m type instance Add (Succ n) m = Succ (Add n m) type family Mult (a :: *) (b :: *) :: * type instance Mult Zero m = Zero type instance Mult (Succ n) m = Add m (Mult n m) type Five = Succ (Succ (Succ (Succ (Succ Zero)))) type Four = Succ (Succ (Succ (Succ Zero))) -- Exhaustive (80 rewrites) f9 :: E (Mult Four (Mult Four Five)) Void -> a f9 = \case -- This gets killed on my dell -- -- -- Exhaustive (390625 rewrites) -- f10 :: E (Mult (Mult (Mult Five Five) -- (Mult Five Five)) -- (Mult (Mult Five Five) -- (Mult Five Five))) -- Void -> a -- f10 = \case
ezyang/ghc
testsuite/tests/pmcheck/should_compile/EmptyCase003.hs
bsd-3-clause
2,278
0
23
599
674
393
281
-1
-1
module Data.Time ( module Data.Time.Calendar, module Data.Time.Clock, module Data.Time.LocalTime, module Data.Time.Format ) where import Data.Time.Calendar import Data.Time.Clock import Data.Time.LocalTime import Data.Time.Format
beni55/haste-compiler
libraries/time/lib/Data/Time.hs
bsd-3-clause
235
8
5
26
68
45
23
10
0
module PackageTests.BuildDeps.TargetSpecificDeps1.Check where import Test.Tasty.HUnit import PackageTests.PackageTester import System.FilePath import Data.List import qualified Control.Exception as E import Text.Regex.Posix suite :: SuiteConfig -> Assertion suite config = do let spec = PackageSpec { directory = "PackageTests" </> "BuildDeps" </> "TargetSpecificDeps1" , configOpts = [] , distPref = Nothing } result <- cabal_build config spec do assertEqual "cabal build should fail - see test-log.txt" False (successful result) assertBool "error should be in MyLibrary.hs" $ "MyLibrary.hs:" `isInfixOf` outputText result assertBool "error should be \"Could not find module `System.Time\"" $ (intercalate " " $ lines $ outputText result) =~ "Could not find module.*System.Time" `E.catch` \exc -> do putStrLn $ "Cabal result was "++show result E.throwIO (exc :: E.SomeException)
trskop/cabal
Cabal/tests/PackageTests/BuildDeps/TargetSpecificDeps1/Check.hs
bsd-3-clause
1,026
0
15
260
223
118
105
24
1
{-# LANGUAGE ImplicitParams #-} module T8474 where data D = D Int deriving Show -- In 7.7 this took exponential time! slow_to_compile :: IO () slow_to_compile = do tst1 <- return 1 let ?tst1 = tst1 {- let ?tst2 = tst1 let ?tst3 = tst1 let ?tst4 = tst1 let ?tst5 = tst1 let ?tst6 = tst1 let ?tst7 = tst1 -} print $ D ?tst1
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/typecheck/should_compile/T8474.hs
bsd-3-clause
343
0
9
87
63
33
30
8
1
{-# LANGUAGE GADTs #-} module API.WebMoney.Internal.Query where import Data.Text (Text) data QueryBestRates where QueryBestRates :: QueryBestRates data QueryExchanges where QueryExchanges :: { queryExchType :: !Int } -> QueryExchanges data QueryList where QueryList :: { listWMID :: !Text , listType :: !Int , listQueryID :: !(Maybe Text) , listCapitallerWMID :: !(Maybe Text) } -> QueryList QueryCounterList :: { listWMID :: !Text , listType :: !Int , listQueryID :: !(Maybe Text) , listCapitallerWMID :: !(Maybe Text) } -> QueryList data QueryTransDel where QueryTransDel :: { transDelWMID :: !Text , transDelOperID :: !Text , transDelCapitallerWMID :: !(Maybe Text) } -> QueryTransDel data QueryTransChange where QueryTransChange :: { transChangeWMID :: !Text , transChangeOperID :: !Text , transChangeCursType :: !Bool , transChangeCursAmount :: !Double , transChangeCapitallerWMID :: !(Maybe Text) } -> QueryTransChange data QueryTransUnion where QueryTransUnion :: { transUnionWMID :: !Text , transUnionOperID :: !Text , transUnionNewOperID :: !Text , transUnionCapitallerWMID :: !(Maybe Text) } -> QueryTransUnion data QueryTransNew where QueryTransNew :: { transNewWMID :: !Text , transNewInPurse :: !Text , transNewOutPurse :: !Text , transNewInAmount :: !Double , transNewOutAmount :: !Double , transNewCapitallerWMID :: !(Maybe Text) } -> QueryTransNew data QueryTransPurchase where QueryTransPurchase :: { transPurchaseWMID :: !Text , transPurchaseSourceID :: !Text , transPurchaseDestID :: !Text , transPurchaseDestStamp :: !(Maybe Text) , transPurchaseCapitallerWMID :: !(Maybe Text) } -> QueryTransPurchase type HourStat = Int type DayStat = (Int, Maybe HourStat) type MonthStat = (Int, Maybe DayStat) type WeekStat = Int type YearStat = (Int, Maybe MonthStat, Maybe WeekStat) type YearWeekStat = (Int, Maybe MonthStat, WeekStat) data QueryStats where QueryMonthStats :: { statsExchType :: !Int , statsDate :: !(Maybe YearStat) } -> QueryStats QueryWeekStats :: { statsExchType :: !Int , statsYearDate :: !YearStat } -> QueryStats QueryDayStats :: { statsExchType :: !Int , statsYearDate :: !YearStat } -> QueryStats QueryHourStats :: { statsExchType :: !Int , statsYearWeekDate :: !YearWeekStat } -> QueryStats data QueryNewCounterList where QueryNewCounterList :: { listNewWMID :: !Text , listNewQueryID :: !Text , listNewCapitallerWMID :: !(Maybe Text) } -> QueryNewCounterList
triplepointfive/wmexchanger
src/API/WebMoney/Internal/Query.hs
mit
3,170
0
10
1,101
622
368
254
153
0
module Rebase.GHC.GHCi ( module GHC.GHCi ) where import GHC.GHCi
nikita-volkov/rebase
library/Rebase/GHC/GHCi.hs
mit
68
0
5
12
20
13
7
4
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} module Text.Greek.Grammar where import Control.Lens (makeLenses) import Data.Text (Text) data Source = Source { _author :: Text , _title :: Text , _year :: Int } makeLenses ''Source data Part = Section Text | Page Int data Citation = Citation Source Part data Cited a = Cited { _citations :: [Citation] , _item :: a } makeLenses ''Cited instance Functor Cited where fmap f (Cited cs i) = Cited cs (f i) instance Applicative Cited where pure a = Cited [] a (Cited cs f) <*> (Cited cs' a) = Cited (cs ++ cs') (f a) (§) :: Source -> Text -> a -> Cited a s § t = Cited [Citation s . Section $ t] (§§) :: Source -> [Text] -> a -> Cited a s §§ ts = Cited (Citation s . Section <$> ts) mounce :: Source mounce = Source "William D. Mounce" "The Morphology of Biblical Greek" 1994 brooksWinbery :: Source brooksWinbery = Source "James A. Brooks, Carlton L. Winbery" "A Morphology of New Testament Greek" 1994 smyth :: Source smyth = Source "Herbert Weird Smyth, Gordon M. Messing" "Greek Grammar" 1956 -- revised by Messing; Copyright 1920 Smyth; Copyright 1956, renewed 1984
scott-fleischman/greek-grammar
haskell/greek-grammar/src/Text/Greek/Grammar.hs
mit
1,208
0
9
249
383
204
179
34
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE QuasiQuotes #-} module Graphics.Urho3D.Graphics.View( View , SharedView , viewContext ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Cpp as C import Graphics.Urho3D.Graphics.Internal.View import Data.Monoid import Graphics.Urho3D.Container.Ptr import Graphics.Urho3D.Core.Context C.context (C.cppCtx <> viewCntx <> sharedViewPtrCntx <> contextContext ) C.include "<Urho3D/Graphics/View.h>" C.using "namespace Urho3D" viewContext :: C.Context viewContext = viewCntx <> sharedViewPtrCntx sharedPtr "View"
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/Graphics/View.hs
mit
617
0
10
86
130
78
52
-1
-1
mystery x s = concat $ replicate (round (sqrt x)) s
rtoal/ple
haskell/mystery.hs
mit
58
0
10
17
32
15
17
2
1
module Main where {-# LANGUAGE ScopedTypeVariables #-} import Data.Maybe import Graphics.UI.WX hiding (Event) import Reactive.Banana import Reactive.Banana.WX import AI.HNN.FF.Network import Numeric.LinearAlgebra import Data.List.Split import Data.List (replicate) main :: IO () main = start gui gui :: IO () gui = do f <- frame [ text := "Neural Network" ] lEpocs <- staticText f [ text := "Epocs"] lMiddleLayers <- staticText f [ text := "Middle & output layers"] lLearningRate <- staticText f [ text := "Learning rate"] iEpocs <- textCtrlRich f [ text := "1000" ] iMiddleLayers <- textCtrlRich f [ text := "2,2,1"] iLearningRate <- textCtrlRich f [ text := "0.8"] bStart <- button f [ text := "Start" ] bQuit <- button f [ text := "Quit" ] set bStart [ on command := parseInputAndTrain f iEpocs iMiddleLayers iLearningRate] set bQuit [ on command := close f] set f [ layout := column 25 [ widget lEpocs, widget iEpocs, widget lMiddleLayers, widget iMiddleLayers, widget lLearningRate, widget iLearningRate, widget bStart, widget bQuit ] ] parseInputAndTrain :: (Paint w, Textual w1, Textual w2, Textual w3) => w -> w1 -> w2 -> w3 -> IO () parseInputAndTrain f iEpocs iMiddleLayers iLearningRate = do epocsString <- get iEpocs text middleLayersString <- get iMiddleLayers text learningRateString <- get iLearningRate text let epocs = read epocsString :: Int let middleLayersSplited = splitOn "," middleLayersString let middleLayer = map (\s -> read s :: Int) middleLayersSplited let learningRate = read learningRateString :: Double trainNeuralNetwork epocs 2 middleLayer 1 learningRate trainNeuralNetwork :: Int -> Int -> [Int] -> Int -> Double -> IO() trainNeuralNetwork epocs firstLayer middleLayers outputLayer learningRate = do xys <- readFile "xy.txt" zs <- readFile "z.txt" let list1 = parse xys let list2 = parse zs let list11 = map fromList list1 let list22 = map fromList list2 let samples2 = zip list11 list22 putStrLn "1------------------" n <- createNetwork firstLayer middleLayers outputLayer :: IO (Network Double) mapM_ (putStrLn . show) samples2 mapM_ (putStrLn . show . output n tanh . fst) samples2 putStrLn "2------------------" let n' = trainNTimes epocs learningRate tanh tanh' n samples2 mapM_ (putStrLn . show . output n' tanh . fst) samples2 parse :: String -> [[Double]] parse a = map (map read . words) (lines a) oneList :: [a] -> [b] -> [(a, b)] oneList [] _ = [] oneList (x:xs) (y:ys) = (x, y) : oneList xs ys samples :: Samples Double samples = [ (fromList [0, 0], fromList [0]) , (fromList [0, 1], fromList [1]) , (fromList [1, 0], fromList [1]) , (fromList [1, 1], fromList [0]) ]
tomymehdi/ai-haskell
final/Experiments.hs
mit
2,998
10
16
807
1,075
531
544
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} module Main where import Protolude import Data.Sequence (Seq) import qualified Data.Sequence as S build :: Int -> Seq Int build n = S.fromList [1 .. n] part1 :: Int -> Int part1 = rec . build where rec xs | S.null xs = -1 | length xs <= 2 = S.index xs 0 | otherwise = rec $ S.drop 2 xs S.>< S.take 1 xs testInput :: Int testInput = 5 input :: Int input = 3014387 testPart1 :: Bool testPart1 = 3 == part1 testInput part2 :: Int -> Int part2 = rec . build where rec xs | S.null xs = -1 | length xs <= 2 = S.index xs 0 | otherwise = rec ws where ws = zs S.|> z (z S.:< zs) = S.viewl ys ys = S.take n xs S.>< S.drop (n + 1) xs n = length xs `div` 2 testPart2 :: Bool testPart2 = 2 == part2 testInput main :: IO () main = do print testPart1 print . part1 $ input print testPart2 print . part2 $ input
genos/online_problems
advent_of_code_2016/day19/src/Main.hs
mit
1,030
0
12
380
412
207
205
35
1
-- The highest profit wins! -- http://www.codewars.com/kata/559590633066759614000063 module Codewars.Kata.MinMax where minMax :: (Ord a) => [a] -> (a, a) minMax xs = (minimum xs, maximum xs)
gafiatulin/codewars
src/7 kyu/MinMax.hs
mit
193
0
7
28
56
33
23
3
1
{-| Module : Data.Algorithm.PPattern Structription : Short Structription Copyright : (c) anonymous, 2016-1017, 2016-2017 License : MIT Maintainer : [email protected] Stability : experimental Pattern matching for Permutations. -} module Data.Algorithm.PPattern ( -- * Searching with default ConflictSelection search , occursIn , avoids , contains -- * Searching with conflict selection strategy , searchWithConflictSelectionStrategy , searchLeftmostConflictFirst , searchLeftmostHorizontalConflictFirst , searchLeftmostVerticalConflictFirst , searchRightmostConflictFirst , searchRightmostHorizontalConflictFirst , searchRightmostVerticalConflictFirst ) where import qualified Data.Maybe as Maybe import qualified Data.Algorithm.PPattern.Perm as Perm import qualified Data.Algorithm.PPattern.Search as Search import qualified Data.Algorithm.PPattern.Search.ConflictSelection as ConflictSelection import qualified Data.Algorithm.PPattern.Search.Occurrence as Occurrence {-| Alias for function 'search'. -} occursIn :: Perm.Perm -> Perm.Perm -> Bool p `occursIn` q = Maybe.isJust $ search p q {-| Return True if there does not exist an order-isomorphic occurrence of 'p' into 'q'. -} avoids :: Perm.Perm -> Perm.Perm -> Bool q `avoids` p = not $ p `occursIn` q {-| Return True if there exists an order-isomorphic occurrence of 'p' into 'q'. -} contains :: Perm.Perm -> Perm.Perm -> Bool q `contains` p = p `occursIn` q {-| Search for an order-isomorphic occurrence of 'p' into 'q' according to a given ConflictSelection. -} searchWithConflictSelectionStrategy :: Perm.Perm -> Perm.Perm -> ConflictSelection.Strategy -> Maybe Occurrence.Occurrence searchWithConflictSelectionStrategy = Search.search {-| Search for an order-isomorphic occurrence of 'p' into 'q' using the default conflict resolution strategy. -} search :: Perm.Perm -> Perm.Perm -> Maybe Occurrence.Occurrence search p q = searchWithConflictSelectionStrategy p q ConflictSelection.DefaultStrategy {-| Search for an order-isomorphic occurrence of 'p' into 'q' according to the leftmost conflict ConflictSelection. -} searchLeftmostConflictFirst :: Perm.Perm -> Perm.Perm -> Maybe Occurrence.Occurrence searchLeftmostConflictFirst p q = searchWithConflictSelectionStrategy p q ConflictSelection.LeftmostConflictFirst {-| Search for an order-isomorphic occurrence of 'p' into 'q'. Resolve conflicts according to a given strategy. -} searchLeftmostHorizontalConflictFirst :: Perm.Perm -> Perm.Perm -> Maybe Occurrence.Occurrence searchLeftmostHorizontalConflictFirst p q = searchWithConflictSelectionStrategy p q ConflictSelection.LeftmostHorizontalConflictFirst {-| Search for an order-isomorphic occurrence of 'p' into 'q' according to the rightmost order conflict first strategy. -} searchRightmostHorizontalConflictFirst :: Perm.Perm -> Perm.Perm -> Maybe Occurrence.Occurrence searchRightmostHorizontalConflictFirst p q = searchWithConflictSelectionStrategy p q ConflictSelection.LeftmostVerticalConflictFirst {-| Search for an order-isomorphic occurrence of 'p' into 'q' according to the rightmost conflict strategy. -} searchRightmostConflictFirst :: Perm.Perm -> Perm.Perm -> Maybe Occurrence.Occurrence searchRightmostConflictFirst p q = searchWithConflictSelectionStrategy p q ConflictSelection.RightmostConflictFirst {-| Search for an order-isomorphic occurrence of 'p' into 'q' according to the leftmost value conflict first strategy. -} searchLeftmostVerticalConflictFirst :: Perm.Perm -> Perm.Perm -> Maybe Occurrence.Occurrence p `searchLeftmostVerticalConflictFirst` q = searchWithConflictSelectionStrategy p q ConflictSelection.RightmostHorizontalConflictFirst {-| Search for an order-isomorphic occurrence of 'p' into 'q' according to the rightmost value conflict first strategy. -} searchRightmostVerticalConflictFirst :: Perm.Perm -> Perm.Perm -> Maybe Occurrence.Occurrence searchRightmostVerticalConflictFirst p q = searchWithConflictSelectionStrategy p q ConflictSelection.RightmostVerticalConflictFirst
vialette/ppattern
src/Data/Algorithm/PPattern.hs
mit
4,246
0
9
700
548
305
243
40
1
{-#LANGUAGE DeriveDataTypeable #-} {-#LANGUAGE BangPatterns#-} module Control.Concurrent.HEP.Mailbox ( newMBox , sendMBox , receiveMBox , receiveMBoxAfter , receiveMBoxAfterTMVar )where import Control.Concurrent.HEP.Types import Control.Concurrent.STM import Control.Concurrent import System.Timeout newMBox:: IO (MBox a) newMBox = do !a <- atomically $! newTQueue -- newTChan return $! LocalMBox a sendMBox:: MBox m-> m -> IO () sendMBox (LocalMBox !mbox) !m = do atomically $! writeTQueue mbox m --yield receiveMBoxAfterTMVar:: TMVar (Maybe a) -> TimeoutType-> MBox a-> IO (Maybe a) receiveMBoxAfterTMVar !tmvar !tm (LocalMBox !mbox) = do -- timeout (tm * 1000) $! receiveMBox mbox --yield atomically $! readTMVar tmvar `orElse` ( readTQueue mbox >>= (return . Just)) receiveMBoxAfter:: TimeoutType-> MBox a-> IO (Maybe a) receiveMBoxAfter !tm !mbox = timeout (tm * 1000) $! receiveMBox mbox receiveMBox:: MBox a-> IO a receiveMBox (LocalMBox !mbox) = do --yield atomically $! readTQueue mbox
dambaev/hep
src/Control/Concurrent/HEP/Mailbox.hs
mit
1,081
0
11
221
333
168
165
28
1
import System.Random (randomRIO) import Control.Monad pick :: [a] -> IO a pick xs = randomRIO (0, length xs - 1) >>= return . (xs !!) firstPart :: [[Char]] firstPart = ["lazy", "stupid", "insecure", "idiotic", "slimy", "slutty", "smelly", "pompous", "communist", "dicknose", "pie-eating", "racist", "elitist", "trashy", "drug-loving", "butterface", "tone deaf", "ugly", "creepy"] secondPart :: [[Char]] secondPart = ["douche", "ass", "turd", "rectum", "butt", "cock","shit","crotch","bitch","prick","slut","taint","fuck","dick","boner","shart","nut","sphincter"] thirdPart :: [[Char]] thirdPart = ["pilot","canoe","captain","pirate","hammer","knob","box","jockey","nazi","waffle","goblin","blossum","biscuit","clown","socket","monster","hound","dragon","balloon"] makeInsult :: IO [Char] makeInsult = do fp <- pick firstPart sp <- pick secondPart tp <- pick thirdPart return $ fp ++ " " ++ sp ++ " " ++ tp main = do insult <- makeInsult putStrLn $ "You are a " ++ insult ++ "!"
Joss-Steward/Auto-Insulter
insultGenerator.hs
mit
1,022
0
11
159
379
223
156
19
1
{-# htermination min :: Float -> Float -> Float #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_min_6.hs
mit
52
0
2
10
3
2
1
1
0
module Compiler.Syntax.Type ( module Compiler.Syntax.Type.Position , module Compiler.Syntax.Type.Token ) where import Compiler.Syntax.Type.Position import Compiler.Syntax.Type.Token
banacorn/mini-pascal
src/Compiler/Syntax/Type.hs
mit
201
0
5
33
39
28
11
5
0
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} module HsObjRaw (PolyObjCore(..), HsObj(..), objType, formObjOfType, formObjSimple, transformObjTypes, transformObjTypes', resolveToType, alignTypes, applyMono, apply, makeMonomorphic, tryMakeMonomorphic, doIO) where --import Debug.Trace import Control.Arrow import Control.Monad --import Control.Monad.Trans.Class import Data.Typeable (Typeable, typeOf) import Data.Monoid import Data.Maybe import Data.List import Data.Text (Text) import Data.Map.Strict (Map) import qualified Data.Text as T import qualified Data.Map.Strict as Map import qualified Data.Text.Read import qualified Unsafe.Coerce import HyphenBase import HyphenKinds import HyphenTyCon import HsType import HyphenUnify import PythonBase -- | This module defines the HsObj type, which in a run-time -- representation of a Haskell object of some (possibly polymorphic) -- type. It is different to Data.Dynamic mostly in that it supports a -- representation of polymorphic objects; it is also different in that -- it integrates with HsType (our preferred representation of Haskell -- types, which can represent polymorphic types and which stores more -- information about the type constructors therein contained) rather -- than the standard library representation of Haskell types (which -- cannot represent polymorphism, and which stores less information -- about type constructors, for example loosing information about -- their kinds). -- -- When we say that we 'represent' polymorphic objects, this is a -- little misleading. We simply represent them in terms of how they -- can be built out of 'fundamental' polymorphic objects (names that -- can be imported from modules) using the fundamental operation of -- function application; for 'fundamental' polymorphic objects, we -- just store some code that can be passed to ghci to refer to the -- object in question, which allows us to generate code to pick up a -- monomorphic realization. For this reason, what we do is quite -- inefficient if you work at length with polymorphic objects; this is -- why the documentation for hyphen explains that for anything where -- efficiency matters, you should make all your objects monomorphic as -- early as possible. -- -- A monomorphic HsObj is simple: it just consists of its monomorphic -- type and an Any which points to the object in question. A -- Polymorphic object is more complicated. It consists of a *core*, -- which represents a 'fundamental' polymorphic object (i.e. one -- importable from somewhere) and which is itself concretely -- represented as an abstract function which takes an HsType (which -- had better be both monomorphic and a specialization of the -- polymorphic type of the underlying polymorphic HsObj) and returns -- an HsObj (a specialization of the Polymorphic HsObj to the given -- type) in the PythonM monad. (This, in turn, is internally -- implemented by using the 'stored piece of code' mentioned above.) -- In simple cases, the HsObj consists only of the core; in more -- complicated cases, there may be a sequence of other HsObjs that we -- need to function-apply the core to before we get the encoded -- object. We keep track of the type of the core and the type of the -- final HsObj. -- -- Occasionally, we pass around HsObjs which claim to be polymorphic -- but whose type si monomorphic. These are allowed, but only as -- intermediates; the actual HsObjs that we wrap and expose as Python -- objects should never be like that... data PolyObjCore = PolyObjCore {resolvePolyObjCoreToType :: HsType -> PythonM HsObj} data HsObj = MonoObj HsType Any | PolyObj { polyObjFinalType :: HsType, polyObjCoreType :: HsType, polyObjCore :: PolyObjCore, polyObjAppliedTo :: [HsObj] } -- | Debug representation of HsObjs debugDumpHsObj :: HsObj -> Text debugDumpHsObj (MonoObj hst _) = bracket $ T.unwords [T.pack "MonoObj", typeName hst] debugDumpHsObj (PolyObj ft ct _ ato) = bracket $ T.unwords [ T.pack "PolyObj", bracket $ typeName ft, bracket $ typeName ct, T.concat ( T.pack "[" : intersperse (T.pack ", ") (map debugDumpHsObj ato) ++ [T.pack "]"])] -- | Fetch the type of an HsObj objType :: HsObj -> HsType objType (MonoObj t _) = t objType (PolyObj {polyObjFinalType=t}) = t -- | form an HsObj given the desired type; *takes on trust that it will -- be applied to something of the type specified; in other words, not -- type safe*! formObjOfType :: HsType -> a -> IO HsObj formObjOfType ty = return . MonoObj ty . Unsafe.Coerce.unsafeCoerce -- | form an HsObj; only correct if the type of the object in question -- is simple (a single type constructor of arity 0) formObjSimple :: (Typeable a) => a -> IO HsObj formObjSimple ob = formObjOfType (hsTypeFromSimpleTypeRep $ typeOf ob) ob -- | Same as transformObjTypes below, but skip the final step (which -- is replacing a polymorphic representation with a monomorphic one if -- the type has become monomorphic). transformObjTypes' :: Map Var HsType -> HsObj -> HsObj transformObjTypes' d = go where go (PolyObj ft ct c ato) = PolyObj (f ft) (f ct) c (map go ato) go mo@(MonoObj _ _) = mo f = transformType d -- | Specialize the type of an HsObj by substituting the given types for -- the type-variables it contains. transformObjTypes :: Map Var HsType -> HsObj -> PythonM HsObj transformObjTypes d = tryMakeMonomorphic . transformObjTypes' d -- | Resolve the HsObj given to the Type given; raises python TypeError -- if this is not possible. resolveToType :: HsType -> HsObj -> PythonM HsObj resolveToType ty obj = do let unify_result = unify [mapVars (T.append $ T.pack "o_") $ objType obj, mapVars (T.append $ T.pack "r_") ty] (_, substRaw) <- maybe ( pyTypeErr' $ "Incompatible types: cannot resolve object of type\n\t" ++ T.unpack (typeName $ objType obj) ++ "\nto type\n\t" ++ T.unpack (typeName ty)) return unify_result let subst = Map.mapKeys (Var . T.drop 2 . getVar) . fst . Map.split (Var $ T.pack "q") $ substRaw transformObjTypes subst obj -- | The pseudo-variable '...', which, while it is only a -- pseudo-variable (it wouldn't be legal in Haskell) is useful in -- various operations below. ellipsisVar :: Var ellipsisVar = Var $ T.pack $ "..." ------------- simplifyFVs :: Map Var Kind -> Map Text Text simplifyFVs = Map.fromList . concatMap finalize . Map.toList . fmap rationalize . Map.fromListWith (++) . map process . Map.keys where process :: Var -> (Text, [(Int, Var)]) process orig = let (prefix, rest) = separateVarPrefix orig (core, number) = separateVarNumber rest in (core, [(number, orig)]) rationalize :: [(Int, Var)] -> [(Int, Var)] rationalize = rationalizeFrom 0 [] . sort rationalizeFrom _ [] [] = [] rationalizeFrom nextFree (ov:vs) [] = (nextFree, ov) : rationalizeFrom (nextFree+1) vs [] rationalizeFrom nextFree [] ((i, v):ivs) | i >= nextFree = (i, v) : rationalizeFrom (i+1) [] ivs | otherwise = rationalizeFrom nextFree [v] ivs rationalizeFrom nextFree allvs@(ov:vs) allivs@((i, v):ivs) | i > nextFree = (nextFree, ov) : rationalizeFrom (nextFree+1) vs allivs | otherwise = (i, v) : rationalizeFrom (nextFree+1) allvs ivs finalize :: (Text, [(Int, Var)]) -> [(Text, Text)] finalize (core, lst) = map doOne lst where doOne (i, Var orig) = (orig, T.concat [core, T.pack $ "_" ++ show i]) separateVarNumber :: Var -> (Text, Int) separateVarNumber v | v == ellipsisVar = (T.pack "a", 0) --special case | T.null prePart = (getVar v, 0) | otherwise = case Data.Text.Read.decimal endPart of Right (num', remainder) -> if T.null remainder then (prePart, num') else (getVar v, 0) _ -> (getVar v, 0) where (prePart_, endPart) = T.breakOnEnd (T.pack "_") (getVar v) prePart = if T.null prePart_ then (T.pack "X*X") else T.init prePart_ separateVarPrefix :: Var -> (Text, Var) separateVarPrefix t = case T.findIndex (=='_') (getVar t) of Nothing -> (T.empty, t) Just pos -> second Var $ T.splitAt (pos+1) (getVar t) -- | Given an HsObj which we'd like to apply to a list of other HsObjs in -- turn, see if it's possible to specialize the types of all the HsObjs -- concerned to make the application type check. If so, return HsObjs -- with types suitably specialized (but without reducing them to -- monomorphic objs if their type has become monomorphic). Otherwise, -- return a friendly error message. alignTypes :: (HsObj, [HsObj]) -> Either ErrMsg (HsObj, [HsObj], HsType) alignTypes (o1, os) = do let (t1, ts) = (objType o1, map objType os) _ <- breakFnType t1 let argPrefixes = [T.pack $ "a" ++ show i ++ "_" | i <- [1..]] ts' = zipWith (mapVars . T.append) argPrefixes ts wantedFnType = foldr fnHsType (mkHsType (Right (ellipsisVar, Kind [])) []) ts' unify_result = unify [mapVars (T.append $ T.pack "res_") t1, wantedFnType] (totalTypeRaw, substRaw) <- maybe (report $ "Type mismatch in application. Based on types of arguments, " ++ "function applied should have a type like\n\t" ++ T.unpack (typeName wantedFnType) ++ "\nBut actual function applied has type\n\t" ++ T.unpack (typeName t1)) Right unify_result let simplifySubst = simplifyFVs $ typeFreeVars totalTypeRaw totalType = mapVars (simplifySubst Map.!) totalTypeRaw fullSubstRaw = Map.union substRaw $ Map.fromList [ (v, mkHsType (Right (v, k)) []) | (v, k) <- Map.toList (typeFreeVars totalTypeRaw)] subst = mapVars (simplifySubst Map.!) <$> fullSubstRaw resultType = fromMaybe (error "alignTypes: internal err") $ Map.lookup ellipsisVar subst substsByPref = cleaveMap separateVarPrefix subst substsFor x = Map.findWithDefault Map.empty x substsByPref o1' = transformObjTypes' (substsFor $ T.pack "res_") o1 os' = zipWith transformObjTypes' (map substsFor argPrefixes) os when (typeFreeVars resultType /= typeFreeVars totalType) ( report $ "Ambiguous application: You tried to apply an object of type \n\t" ++ T.unpack (typeName t1) ++ "\nto objects of type \n\t[" ++ intercalate ", " (map (T.unpack . typeName) ts) ++ "].\nAfter resolving type variables, this " ++ "amounts to applying an object of type\n\t" ++ T.unpack (typeName $ objType o1') ++ "\n to objects of type\n\t[" ++ intercalate ", " (map (T.unpack . typeName . objType) os') ++ "].\nThe variables " ++ show (map (getVar . fst) . Map.toAscList $ Map.difference (typeFreeVars totalType) (typeFreeVars resultType)) ++ " are present in the input but not the result and cannot be resolved.\n") -- ++ (show . typeName $ totalTypeRaw) ++ "\n" -- ++ show (fmap typeName $ substRaw)) return (o1', os', resultType) ------------- -- Helper function, the 'real word' of applyMono applyMono' :: (HsType, Any) -> (HsType, Any) -> (HsType, Any) applyMono' (fn_type, ptr_fn) (arg_type, ptr_arg) = let (ty_fr, ty_to) = breakFnTypeUnsafe fn_type in if ty_fr /= arg_type then error ("applyMono: expected arg type\n\t" ++ T.unpack (typeName ty_fr) ++ "\ngot:\n\t" ++ T.unpack (typeName arg_type)) else (ty_to, (Unsafe.Coerce.unsafeCoerce ptr_fn) ptr_arg) -- | Apply a monomorphic object to another monomorphic object. Checks -- types. Barfs if the objects are, in fact, not monomorphic. applyMono :: HsObj -> HsObj -> HsObj applyMono (MonoObj ty1 obj1) (MonoObj ty2 obj2) = uncurry MonoObj $ applyMono' (ty1, obj1) (ty2, obj2) -- | Apply an HsObj to a sequence of other HsObjs. Return a result in the -- PythonM. Raise a nice Python TypeError if there's a type error. apply :: HsObj -> [HsObj] -> PythonM HsObj apply fn_orig args_orig = do (fn, args, resultType) <- promoteErr $ alignTypes (fn_orig, args_orig) case fn of PolyObj {} -> tryMakeMonomorphic $ (fn {polyObjFinalType =resultType, polyObjAppliedTo =polyObjAppliedTo fn ++ args}) MonoObj _ _ -> do args' <- mapM makeMonomorphicUnsafe args return $ foldl applyMono fn args' -- | Given an HsObj whose type is monomorphic (but which may itself be -- implemented, cheatingly, as a polymorphic obj), turn it into a real -- monomorphic HsObj if it wasn't one already; otherwise return Nothing. makeMonomorphic :: HsObj -> PythonM (Maybe HsObj) makeMonomorphic m@(MonoObj _ _) = return $ return m makeMonomorphic obj@(PolyObj {}) | isMonoType (polyObjFinalType obj) = do appliedToMono <- mapM makeMonomorphicUnsafe (polyObjAppliedTo obj) coreMono <- resolvePolyObjCoreToType (polyObjCore obj) (polyObjCoreType obj) return . Just $ foldl applyMono coreMono appliedToMono makeMonomorphic _ = return Nothing -- | Like makeMonomorphic, but barfs if it cannot make the HsObj monomorphic. makeMonomorphicUnsafe obj = do res <- makeMonomorphic obj case res of Just res' -> return res' Nothing -> pyTypeErr' ( "makeMonomorphicUnsafe:not monomorphic: " ++ (T.unpack $ debugDumpHsObj obj)) -- | Like makeMonomorphic, but returns the original Obj unchanged if -- it can't make it monomorphic. tryMakeMonomorphic :: HsObj -> PythonM HsObj tryMakeMonomorphic o = fromMaybe o <$> makeMonomorphic o -- | Given an HsObj which we hope represents an IO action, return an IO -- action that does the represented action and returns another HsObj -- with the return value. If presented with an HsObj which doesn't -- represent an IO action, we produce a nice error message. doIO :: HsObj -> Either ErrMsg (IO HsObj) doIO (MonoObj ty ptr) = do unless (typeHead ty == Left ioTyCon) ( report $ "Attempt to perform IO action, but instead of an action an object " ++ "of type " ++ (T.unpack $ typeName ty) ++ " was supplied.") let [ioRetType] = typeTail ty return $ do ioRet <- (Unsafe.Coerce.unsafeCoerce ptr :: IO Any) return $ MonoObj ioRetType ioRet doIO obj@(PolyObj {}) = report $ "IO action to perform must have monomorphic type, not " ++ ( T.unpack . typeName $ objType obj)
tbarnetlamb/hyphen
hyphen/lowlevel_src/HsObjRaw.hs
gpl-2.0
14,714
0
23
3,292
3,331
1,772
1,559
184
4
import Probability import Data.Frame generate size = do let w = [0.35, 0.4, 0.25] mu = [0.0, 2.0, 5.0] sigma = [0.5, 0.5, 1.0] xs <- iid size $ mixture w [ normal m s | (m,s) <- zip mu sigma ] return ["xs" %=% xs] main_generate = generate 1000 model xs = do let n_components = 3 w <- symmetric_dirichlet n_components 1.0 mu <- sort <$> iid n_components (cauchy 0.0 1.0) tau <- iid n_components (gamma 1.0 1.0) let loggers = [ "dists" %=% zip w (zip mu tau) ] let n_points = length xs xs ~> iid n_points (mixture w [ normal m s | (m, s) <- zip mu tau]) return loggers main = do frame <- readTable "x.csv" let xs = frame $$ ("x",AsDouble) mcmc $ model xs
bredelings/BAli-Phy
tests/prob_prog/examples.3/mixture_model/Main.hs
gpl-2.0
715
0
14
194
341
167
174
22
1
--------------------------------------------------------------------------- -- This file is part of grammata. -- -- grammata is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- grammata is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with grammata. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- | Module : Grammata.Language.Expression -- Description : Grammata abstract syntax tree and parser for arithmetical expressions. -- Maintainer : [email protected] -- Stability : stable -- Portability : portable -- Copyright : (c) Sascha Rechenberger, 2014, 2015 -- License : GPL-3 -- -- [Arithmetical expression grammar, parametrized over @VALUE@] -- -- > EXPRESSION ::= DISJ { || DISJ}* -- > -- > DISJ ::= CONJ { && CONJ}* -- > -- > CONJ ::= COMP {{ == | != | <= | >= | < | > } COMP}* -- > -- > COMP ::= SUM {{ + | - } SUM}* -- > -- > SUM ::= FAC {{ * | / } FAC}* -- > -- > FAC ::= ( EXPRESSION ) -- > | { - | ! } EXPRESSION -- > | IDENT{(EXPRESSION { , EXPRESSION}*)}? -- > | VALUE -- > | remind --------------------------------------------------------------------------- module Grammata.Language.Expression ( -- * Expression AST Expression (..), -- * Parser parseExpression, -- * Auxiliaries Op, foldExpression, ParseExprVal (..) ) where import Data.List (intercalate) import Data.Char (isAlphaNum) import Data.Word import Control.Applicative (Applicative (pure, (<*>)), (*>), (<*), (<|>), (<$>)) import Text.Parsec (try, alphaNum, chainl1, choice, string, oneOf, many1, many, between, lower, char, sepBy, spaces, (<?>), parse, digit) import Text.Parsec.String (Parser) import Debug.Trace import Test.QuickCheck -- | Operators reperesented as strings. type Op = String -- | AST @EXPRESSION@; parametrized over the constant values. data Expression ast = Const ast | BinOp (Expression ast) Op (Expression ast) | UnOp Op (Expression ast) | Func Op [Expression ast] | Remind deriving(Eq) instance Show ast => Show (Expression ast) where show (Const ast) = show ast show (BinOp e1 op e2) = "(" ++ show e1 ++ " " ++ op ++ " " ++ show e2 ++ ")" show (UnOp op e) = "(" ++ op ++ show e ++ ")" show (Func op es) = op ++ if null es then "" else "(" ++ intercalate ", " (map show es) ++ ")" show (Remind) = "remind" instance Functor Expression where fmap f = foldExpression (Const . f) BinOp UnOp Func Remind instance Applicative Expression where pure = Const treeF <*> Const x = fmap (\f -> f x) treeF treeF <*> treeA = foldExpression (\x -> treeF <*> pure x) BinOp UnOp Func Remind treeA -- | Fold function for arithmetical parseExpressions. foldExpression :: () => (ast -> result) -- ^ Const ast -> (result -> Op -> result -> result) -- ^ BinOp (Expression ast) Op (Expression ast) -> (Op -> result -> result) -- ^ UnOp Op (Expression ast) -> (Op -> [result] -> result) -- ^ Func Op [Expression ast] -> result -- ^ Remind -> Expression ast -- ^ Expression to fold. -> result -- ^ Folded parseExpression. foldExpression const binop unop func rem = fold where fold (Const ast) = const ast fold (BinOp e1 op e2) = binop (fold e1) op (fold e2) fold (UnOp op e) = unop op (fold e) fold (Func op es) = func op (map fold es) fold (Remind) = rem -- | Interface for parametrized parsing of arithmetical expressions. class Eq value => ParseExprVal value where parseExprVal :: Parser value token :: String -> Parser String token t = spaces >> string t >> spaces >> return t infixr 5 <<< (<<<) :: [String] -> Parser (Expression value) -> Parser (Expression value) ops <<< parser = do e1 <- parser others <- many . try $ do op <- choice . map (try . token) $ ops e2 <- parser return (op, e2) return $ case others of [] -> e1 es -> foldl (\e1 (op, e2) -> BinOp e1 op e2) e1 es infixr 5 >>> (>>>) :: [String] -> Parser (Expression value) -> Parser (Expression value) ops >>> parser = do others <- many . try $ do e <- parser op <- choice . map (try . token) $ ops return (e, op) e1 <- parser return $ case others of [] -> e1 es -> foldr (\(e2,op) e1 -> BinOp e2 op e1) e1 es -- | Parses @EXPRESSION@. parseExpression :: ParseExprVal value => Parser (Expression value) parseExpression = ["||"] <<< ["&&"] <<< ["==", "!=", "<=", ">=", "<", ">"] <<< ["+", "-"] <<< ["*", "/"] <<< [":"] >>> expr where expr = UnOp <$> ((:[]) <$> between spaces spaces (oneOf "-!.%")) <*> expr <|> try (token "remind") *> pure Remind <|> Const <$> try parseExprVal <|> Func <$> ((:) <$> lower <*> many alphaNum) <*> ((try (token "(") *> sepBy parseExpression (token ",") <* token ")") <|> pure []) <|> try (token "(") *> parseExpression <* token ")" -- QuickCheck for parsing instance ParseExprVal Word where parseExprVal = read <$> many1 digit instance Arbitrary a => Arbitrary (Expression a) where arbitrary = do dice <- choose (0,3) :: Gen Int case dice of 0 -> Const <$> arbitrary 1 -> BinOp <$> arbitrary <*> elements ["+", "-", "*", "/", "==", "!=", "<=", ">=", "<", ">", "||", "&&"] <*> arbitrary 2 -> UnOp <$> elements ["-", "!"] <*> arbitrary 3 -> do f <- choose ('a','z') fs <- listOf . elements . filter isAlphaNum $ ['0'..'z'] args <- listOf arbitrary return $ Func (f:fs) args parses_correctly :: Expression Word -> Bool parses_correctly x = case p (show x) of Left msg -> False Right x' -> x == x' p = parse (parseExpression :: Parser (Expression Word)) "" -- check :: IO () check = quickCheckWith stdArgs{maxSize = 10} parses_correctly
SRechenberger/grammata
src/Grammata/Language/Expression.hs
gpl-3.0
7,273
0
23
2,386
1,832
986
846
100
5
{-# LANGUAGE PatternGuards #-} {-# LANGUAGE QuasiQuotes #-} -- Copyright : (c) 2019 Robert Künnemann -- License : GPL v3 (see LICENSE) -- -- Maintainer : Robert Künnemann <[email protected]> -- Portability : GHC only -- -- Translation rules for local progress: processes must reduce unless they are of form !P or in(..) -- -- The theory behind this is quite involved, it is described in the following paper: -- -- Michael Backes, Jannik Dreier, Steve Kremer and Robert Künnemann. "A Novel -- Approach for Reasoning about Liveness in Cryptographic Protocols and its -- Application to Fair Exchange". EuroS&P 2017 -- module Sapic.ProgressTranslation ( progressTrans , progressTransNull , progressTransAct , progressTransComb , progressInit , progressRestr ) where import qualified Data.List as List import Data.Set hiding (map) import Data.Typeable import qualified Text.RawString.QQ as QQ import Control.Monad.Catch import Theory import Theory.Sapic import Sapic.Facts import Sapic.ProgressFunction import Sapic.Basetranslation -- | Adds event @ProgressFrom@ to any rule with a state fact (not semi-state -- fact) on the rhs, if the followup position (as marked in the state) is in -- @domPF@, i.e., the domain of the progress function. addProgressFrom :: Set [Int] -> [Int] -> ([TransFact], [TransAction], [TransFact],a) -> ([TransFact], [TransAction], [TransFact],a) addProgressFrom domPF child (l,a,r,res) | any isNonSemiState r , child `member` domPF = (Fr(varProgress child):l , ProgressFrom child:a , map (addVarToState $ varProgress child) r , res) | otherwise = (l,a,r,res) -- | Initial rules for progress: adds @ProgressFrom@ to the previous set of -- init rules, if [] in @domPF@, the domain of the progress function. Updates -- the initial ~x accordingly. progressInit :: (MonadCatch m, Show ann1, Typeable ann1) => AnProcess ann1 -> ([AnnotatedRule ann2], Set LVar) -> m ([AnnotatedRule ann2], Set LVar) progressInit anP (initrules,initTx) = do domPF <- pfFrom anP -- invPF <- pfInv anP return (initrules' domPF, initTx' domPF `union` initTx) where initTx' domPF = if [] `member` domPF then singleton $ varProgress [] else empty initrules' domPF = map (mapAct $ addProgressFrom domPF []) initrules -- | Helper function: add progress variable for @lhsP pos@ to @tx@ if if is in -- the dom(progress function) extendVars :: Set ProcessPosition -> [Int] -> Set LVar -> Set LVar extendVars domPF pos tx | lhsP pos `member` domPF = varProgress (lhsP pos) `insert` tx | otherwise = tx -- | Add ProgressTo and ProgressFrom events to a rule: ProgressFrom for the -- position itself, and ProgressTo for one of the children. addProgressItems :: Set [Int] -> ([Int] -> Maybe ProcessPosition) -> [Int] -> ([TransFact], [TransAction], [TransFact], a) -> ([TransFact], [TransAction], [TransFact], a) addProgressItems domPF invPF pos =addProgressFrom domPF (lhsP pos) -- can only start from ! or in, which have no rhs position . addProgressTo invPF (lhsP pos) . addProgressTo invPF (rhsP pos) -- | Add ProgressTo events: -- (corresponds to step2 (child[12] p) in Firsttranslation.ml) -- If one of the direct childen of anrule is in the range of the pf it has an -- inverse. We thus add ProgressTo to each such rule that has the *old* state in -- the premise (we don't want to move into Semistates too early). ProgressTo is -- annotated with the inverse of the child's position, for verification speedup. -- addProgressTo :: Foldable t => -- ([Int] -> Maybe ProcessPosition) -- -> [Int] -- -> ([] TransFact, [TransAction], c, d) -- -> (t TransFact, [TransAction], c,d ) addProgressTo :: Foldable t => ([Int] -> Maybe ProcessPosition) -> [Int] -> (a, [TransAction], t TransFact, d) -> (a, [TransAction], t TransFact, d) addProgressTo invPF child (l,a,r,res) -- | any isState l -- , (Just posFrom) <- invPF child = (l,ProgressTo child posFrom:a,r,res) | any isTargetState r , (Just posFrom) <- invPF child = (l,ProgressTo child posFrom:a,r,res) | otherwise = (l,a,r,res) where isTargetState (State kind nextPos _) = nextPos == child && (kind == PState || kind == LState) isTargetState _ = False -- | Null Processes are translated without any modification progressTransNull :: p1 -> p2 -> p2 progressTransNull _ tNull = tNull -- | Add ProgressTo or -From to rules generated on an action. progressTransAct :: (MonadCatch m, Show ann, Typeable ann) => AnProcess ann -> TransFAct (m TranslationResultAct) -> TransFAct (m TranslationResultAct) progressTransAct anP tAct ac an pos tx = do (rs0,tx1) <- tAct ac an pos tx domPF <- pfFrom anP invPF <- pfInv anP return (map (addProgressItems domPF invPF pos) rs0,extendVars domPF pos tx1) -- | Add ProgressTo or -From to rules generated on a combinator. progressTransComb :: (MonadCatch m, Show ann, Typeable ann) => AnProcess ann -> TransFComb (m TranslationResultComb) -> TransFComb (m TranslationResultComb) progressTransComb anP tComb comb an pos tx = do (rs0,tx1,tx2) <- tComb comb an pos tx domPF <- pfFrom anP invPF <- pfInv anP return (map (addProgressItems domPF invPF pos) rs0 ,extendVars domPF pos tx1 ,extendVars domPF pos tx2) -- | Overall translation is a triple of the other translations. progressTrans :: (Show ann, Typeable ann, MonadCatch m2, MonadCatch m3) => AnProcess ann -> (TransFNull (m1 TranslationResultNull), TransFAct (m2 TranslationResultAct), TransFComb (m3 TranslationResultComb)) -> (TransFNull (m1 TranslationResultNull), TransFAct (m2 TranslationResultAct), TransFComb (m3 TranslationResultComb)) progressTrans anP (tN,tA,tC) = ( progressTransNull anP tN , progressTransAct anP tA , progressTransComb anP tC) resProgressInit :: String resProgressInit = [QQ.r|restriction progressInit: "Ex #t . Init()@t" |] -- | Add restrictions for all transitions that have to take place according to the progress function. progressRestr :: (MonadThrow m, MonadCatch m, Show ann, Typeable ann) => AnProcess ann -> [SyntacticRestriction] -> m [SyntacticRestriction] progressRestr anP restrictions = do domPF <- pfFrom anP -- set of "from" positions initL <- toEx resProgressInit lss_to <- mapM restriction (toList domPF) -- list of set of sets of "to" positions return $ restrictions ++ concat lss_to ++ [initL] where restriction pos = do -- produce restriction to go to one of the tos once pos is reached toss <- pf anP pos mapM (\tos -> return $ Restriction (name tos) (formula tos)) (toList toss) where name tos = "Progress_" ++ prettyPosition pos ++ "_to_" ++ List.intercalate "_or_" (map prettyPosition $ toList tos) formula tos = hinted forall pvar $ hinted forall t1var $ antecedent .==>. conclusion tos pvar = msgVarProgress pos t1var = LVar "t" LSortNode 1 t2var = LVar "t" LSortNode 2 antecedent = Ato $ Action (varTerm $ Free t1var) $ actionToFactFormula (ProgressFrom pos) conclusion tos = bigOr $ map progressTo $ toList tos bigOr [to] = to bigOr (to:tos) = to .||. bigOr tos bigOr [] = TF False -- This case should never occur progressTo to = hinted exists t2var $ Ato $ Action (varTerm $ Free t2var) $ actionToFactFormula $ ProgressTo to pos
tamarin-prover/tamarin-prover
lib/sapic/src/Sapic/ProgressTranslation.hs
gpl-3.0
8,504
0
15
2,584
1,894
1,003
891
112
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CloudWatchLogs.DeleteLogGroup -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Deletes the log group with the specified name and permanently deletes all -- the archived log events associated with it. -- -- <http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteLogGroup.html> module Network.AWS.CloudWatchLogs.DeleteLogGroup ( -- * Request DeleteLogGroup -- ** Request constructor , deleteLogGroup -- ** Request lenses , dlgLogGroupName -- * Response , DeleteLogGroupResponse -- ** Response constructor , deleteLogGroupResponse ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CloudWatchLogs.Types import qualified GHC.Exts newtype DeleteLogGroup = DeleteLogGroup { _dlgLogGroupName :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DeleteLogGroup' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dlgLogGroupName' @::@ 'Text' -- deleteLogGroup :: Text -- ^ 'dlgLogGroupName' -> DeleteLogGroup deleteLogGroup p1 = DeleteLogGroup { _dlgLogGroupName = p1 } dlgLogGroupName :: Lens' DeleteLogGroup Text dlgLogGroupName = lens _dlgLogGroupName (\s a -> s { _dlgLogGroupName = a }) data DeleteLogGroupResponse = DeleteLogGroupResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'DeleteLogGroupResponse' constructor. deleteLogGroupResponse :: DeleteLogGroupResponse deleteLogGroupResponse = DeleteLogGroupResponse instance ToPath DeleteLogGroup where toPath = const "/" instance ToQuery DeleteLogGroup where toQuery = const mempty instance ToHeaders DeleteLogGroup instance ToJSON DeleteLogGroup where toJSON DeleteLogGroup{..} = object [ "logGroupName" .= _dlgLogGroupName ] instance AWSRequest DeleteLogGroup where type Sv DeleteLogGroup = CloudWatchLogs type Rs DeleteLogGroup = DeleteLogGroupResponse request = post "DeleteLogGroup" response = nullResponse DeleteLogGroupResponse
dysinger/amazonka
amazonka-cloudwatch-logs/gen/Network/AWS/CloudWatchLogs/DeleteLogGroup.hs
mpl-2.0
3,002
0
9
640
345
210
135
47
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.RegionHealthChecks.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves the list of HealthCheck resources available to the specified -- project. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionHealthChecks.list@. module Network.Google.Resource.Compute.RegionHealthChecks.List ( -- * REST Resource RegionHealthChecksListResource -- * Creating a Request , regionHealthChecksList , RegionHealthChecksList -- * Request Lenses , rhclReturnPartialSuccess , rhclOrderBy , rhclProject , rhclFilter , rhclRegion , rhclPageToken , rhclMaxResults ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionHealthChecks.list@ method which the -- 'RegionHealthChecksList' request conforms to. type RegionHealthChecksListResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "healthChecks" :> QueryParam "returnPartialSuccess" Bool :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] HealthCheckList -- | Retrieves the list of HealthCheck resources available to the specified -- project. -- -- /See:/ 'regionHealthChecksList' smart constructor. data RegionHealthChecksList = RegionHealthChecksList' { _rhclReturnPartialSuccess :: !(Maybe Bool) , _rhclOrderBy :: !(Maybe Text) , _rhclProject :: !Text , _rhclFilter :: !(Maybe Text) , _rhclRegion :: !Text , _rhclPageToken :: !(Maybe Text) , _rhclMaxResults :: !(Textual Word32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionHealthChecksList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rhclReturnPartialSuccess' -- -- * 'rhclOrderBy' -- -- * 'rhclProject' -- -- * 'rhclFilter' -- -- * 'rhclRegion' -- -- * 'rhclPageToken' -- -- * 'rhclMaxResults' regionHealthChecksList :: Text -- ^ 'rhclProject' -> Text -- ^ 'rhclRegion' -> RegionHealthChecksList regionHealthChecksList pRhclProject_ pRhclRegion_ = RegionHealthChecksList' { _rhclReturnPartialSuccess = Nothing , _rhclOrderBy = Nothing , _rhclProject = pRhclProject_ , _rhclFilter = Nothing , _rhclRegion = pRhclRegion_ , _rhclPageToken = Nothing , _rhclMaxResults = 500 } -- | Opt-in for partial success behavior which provides partial results in -- case of failure. The default value is false. rhclReturnPartialSuccess :: Lens' RegionHealthChecksList (Maybe Bool) rhclReturnPartialSuccess = lens _rhclReturnPartialSuccess (\ s a -> s{_rhclReturnPartialSuccess = a}) -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the -- \`creationTimestamp\` field in reverse chronological order (newest -- result first). Use this to sort resources like operations so that the -- newest operation is returned first. Currently, only sorting by \`name\` -- or \`creationTimestamp desc\` is supported. rhclOrderBy :: Lens' RegionHealthChecksList (Maybe Text) rhclOrderBy = lens _rhclOrderBy (\ s a -> s{_rhclOrderBy = a}) -- | Project ID for this request. rhclProject :: Lens' RegionHealthChecksList Text rhclProject = lens _rhclProject (\ s a -> s{_rhclProject = a}) -- | A filter expression that filters resources listed in the response. The -- expression must specify the field name, a comparison operator, and the -- value that you want to use for filtering. The value must be a string, a -- number, or a boolean. The comparison operator must be either \`=\`, -- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute -- Engine instances, you can exclude instances named \`example-instance\` -- by specifying \`name != example-instance\`. You can also filter nested -- fields. For example, you could specify \`scheduling.automaticRestart = -- false\` to include instances only if they are not scheduled for -- automatic restarts. You can use filtering on nested fields to filter -- based on resource labels. To filter on multiple expressions, provide -- each separate expression within parentheses. For example: \`\`\` -- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\") -- \`\`\` By default, each expression is an \`AND\` expression. However, -- you can include \`AND\` and \`OR\` expressions explicitly. For example: -- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel -- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\` rhclFilter :: Lens' RegionHealthChecksList (Maybe Text) rhclFilter = lens _rhclFilter (\ s a -> s{_rhclFilter = a}) -- | Name of the region scoping this request. rhclRegion :: Lens' RegionHealthChecksList Text rhclRegion = lens _rhclRegion (\ s a -> s{_rhclRegion = a}) -- | Specifies a page token to use. Set \`pageToken\` to the -- \`nextPageToken\` returned by a previous list request to get the next -- page of results. rhclPageToken :: Lens' RegionHealthChecksList (Maybe Text) rhclPageToken = lens _rhclPageToken (\ s a -> s{_rhclPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than \`maxResults\`, Compute -- Engine returns a \`nextPageToken\` that can be used to get the next page -- of results in subsequent list requests. Acceptable values are \`0\` to -- \`500\`, inclusive. (Default: \`500\`) rhclMaxResults :: Lens' RegionHealthChecksList Word32 rhclMaxResults = lens _rhclMaxResults (\ s a -> s{_rhclMaxResults = a}) . _Coerce instance GoogleRequest RegionHealthChecksList where type Rs RegionHealthChecksList = HealthCheckList type Scopes RegionHealthChecksList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient RegionHealthChecksList'{..} = go _rhclProject _rhclRegion _rhclReturnPartialSuccess _rhclOrderBy _rhclFilter _rhclPageToken (Just _rhclMaxResults) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy RegionHealthChecksListResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionHealthChecks/List.hs
mpl-2.0
7,732
0
20
1,684
833
497
336
122
1
{-# LANGUAGE UndecidableInstances #-} module Monad.Ref ( MonadRef (..), modifyRef, RefT, runRefT ) where import Data.Functor ((<$>)) import Data.IORef (IORef, readIORef, writeIORef, newIORef) import Control.Monad.Trans.Reader (ReaderT, runReaderT) import Control.Monad.Lift.IO (MonadIO, liftIO) import Monad.Reader (MonadReader(..)) class (MonadIO m, Monad m, Functor m) => MonadRef s m | m -> s where getRef :: m s putRef :: s -> m () modifyRef :: (MonadRef s m) => (s -> s) -> m () modifyRef f = f <$> getRef >>= putRef instance (MonadIO m, MonadReader (IORef a) m, Functor m) => MonadRef a m where getRef = ask >>= liftIO . readIORef putRef s = do ref <- ask liftIO $ writeIORef ref s type RefT s m = ReaderT (IORef s) m runRefT :: (MonadIO m) => RefT s m a -> s -> m (a, s) runRefT m s = do ref <- liftIO $ newIORef s a <- runReaderT m ref s' <- liftIO $ readIORef ref return (a, s')
duncanburke/toliman-core
src/Monad/Ref.hs
mpl-2.0
930
0
9
204
406
220
186
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.HealthChecks.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves the list of HealthCheck resources available to the specified -- project. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.healthChecks.list@. module Network.Google.Resource.Compute.HealthChecks.List ( -- * REST Resource HealthChecksListResource -- * Creating a Request , healthChecksList , HealthChecksList -- * Request Lenses , hclOrderBy , hclProject , hclFilter , hclPageToken , hclMaxResults ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.healthChecks.list@ method which the -- 'HealthChecksList' request conforms to. type HealthChecksListResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "healthChecks" :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] HealthCheckList -- | Retrieves the list of HealthCheck resources available to the specified -- project. -- -- /See:/ 'healthChecksList' smart constructor. data HealthChecksList = HealthChecksList' { _hclOrderBy :: !(Maybe Text) , _hclProject :: !Text , _hclFilter :: !(Maybe Text) , _hclPageToken :: !(Maybe Text) , _hclMaxResults :: !(Textual Word32) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'HealthChecksList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'hclOrderBy' -- -- * 'hclProject' -- -- * 'hclFilter' -- -- * 'hclPageToken' -- -- * 'hclMaxResults' healthChecksList :: Text -- ^ 'hclProject' -> HealthChecksList healthChecksList pHclProject_ = HealthChecksList' { _hclOrderBy = Nothing , _hclProject = pHclProject_ , _hclFilter = Nothing , _hclPageToken = Nothing , _hclMaxResults = 500 } -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- orderBy=\"creationTimestamp desc\". This sorts results based on the -- creationTimestamp field in reverse chronological order (newest result -- first). Use this to sort resources like operations so that the newest -- operation is returned first. Currently, only sorting by name or -- creationTimestamp desc is supported. hclOrderBy :: Lens' HealthChecksList (Maybe Text) hclOrderBy = lens _hclOrderBy (\ s a -> s{_hclOrderBy = a}) -- | Project ID for this request. hclProject :: Lens' HealthChecksList Text hclProject = lens _hclProject (\ s a -> s{_hclProject = a}) -- | Sets a filter expression for filtering listed resources, in the form -- filter={expression}. Your {expression} must be in the format: field_name -- comparison_string literal_string. The field_name is the name of the -- field you want to compare. Only atomic field types are supported -- (string, number, boolean). The comparison_string must be either eq -- (equals) or ne (not equals). The literal_string is the string value to -- filter to. The literal value must be valid for the type of field you are -- filtering by (string, number, boolean). For string fields, the literal -- value is interpreted as a regular expression using RE2 syntax. The -- literal value must match the entire field. For example, to filter for -- instances that do not have a name of example-instance, you would use -- filter=name ne example-instance. You can filter on nested fields. For -- example, you could filter on instances that have set the -- scheduling.automaticRestart field to true. Use filtering on nested -- fields to take advantage of labels to organize and search for results -- based on label values. To filter on multiple expressions, provide each -- separate expression within parentheses. For example, -- (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple -- expressions are treated as AND expressions, meaning that resources must -- match all expressions to pass the filters. hclFilter :: Lens' HealthChecksList (Maybe Text) hclFilter = lens _hclFilter (\ s a -> s{_hclFilter = a}) -- | Specifies a page token to use. Set pageToken to the nextPageToken -- returned by a previous list request to get the next page of results. hclPageToken :: Lens' HealthChecksList (Maybe Text) hclPageToken = lens _hclPageToken (\ s a -> s{_hclPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than maxResults, Compute Engine -- returns a nextPageToken that can be used to get the next page of results -- in subsequent list requests. hclMaxResults :: Lens' HealthChecksList Word32 hclMaxResults = lens _hclMaxResults (\ s a -> s{_hclMaxResults = a}) . _Coerce instance GoogleRequest HealthChecksList where type Rs HealthChecksList = HealthCheckList type Scopes HealthChecksList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient HealthChecksList'{..} = go _hclProject _hclOrderBy _hclFilter _hclPageToken (Just _hclMaxResults) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy HealthChecksListResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/HealthChecks/List.hs
mpl-2.0
6,626
0
18
1,464
678
409
269
96
1
module Network.HighHock.Registry ( Registry , newRegistry , applyContainer , insertContainer , removeContainer , removeMissingContainers , insertMissingContainers , removeStoppedContainers ) where import qualified Data.Map.Strict as M import qualified Data.Text as T import qualified Control.Concurrent as CC import qualified Network.HighHock.Controller as C import Control.Monad (foldM, void) import Control.Exception (finally) import System.Log.Logger type Registry = M.Map T.Text C.Controller newRegistry :: Registry newRegistry = M.empty applyContainer :: (C.Controller -> IO a) -> T.Text -> Registry -> IO (Maybe a) applyContainer f id r = case M.lookup id r of Just c -> fmap Just $ f c Nothing -> return Nothing -- | Inserts a new container to be watched. If there is already an entry for the -- container, will stop it insertContainer :: (C.Controller -> IO ()) -> T.Text -> Registry -> IO Registry insertContainer act id r = do c <- C.newController applyContainer C.stop id r void $ CC.forkIO $ finally (act c) (C.stop c) infoM "insertContainer" ("Inserting " ++ T.unpack id) return $ M.insert id c r removeContainer :: T.Text -> Registry -> IO Registry removeContainer id r = do applyContainer C.stop id r infoM "removeContainer" ("Removing " ++ T.unpack id) return $ M.delete id r -- | Remove containers that are missing from the list of ids given. Stop also removeMissingContainers :: [T.Text] -> Registry -> IO Registry removeMissingContainers ids r = foldM (flip removeContainer) r missing where missing = filter (`notElem` ids) $ M.keys r -- | Add containers that are missing from the registry (and in the list of ids given) insertMissingContainers :: (T.Text -> C.Controller -> IO ()) -> [T.Text] -> Registry -> IO Registry insertMissingContainers fact ids r = foldM insert r missing where missing = filter (`notElem` M.keys r) ids insert r' i = insertContainer (fact i) i r' -- | Check the controller of each entry, and remove if stopped (any thread that -- finish will be stopped, due to our finally wrapper in the forkIO) removeStoppedContainers :: Registry -> IO Registry removeStoppedContainers r = dead >>= foldM (flip removeContainer) r where dead = M.foldlWithKey acc (return []) r acc :: IO [T.Text] -> T.Text -> C.Controller -> IO [T.Text] acc v id c = do v' <- v s <- C.isStopped c if s then return (id:v') else return v'
bluepeppers/highhockwho
src/Network/HighHock/Registry.hs
agpl-3.0
2,555
0
12
584
763
395
368
53
2
-- Implicit CAD. Copyright (C) 2011, Christopher Olah ([email protected]) -- Copyright (C) 2018, Julia Longtin ([email protected]) -- Released under the GNU AGPLV3+, see LICENSE -- be explicit about what we import. import Prelude (($), IO) -- our testing engine. import Test.Hspec(hspec, describe) -- the test forstatements. import ParserSpec.Statement(statementSpec) -- the test for expressions. import ParserSpec.Expr(exprSpec) main :: IO () main = hspec $ do -- run tests against the expression engine. describe "expressions" exprSpec -- and now, against the statement engine. describe "statements" statementSpec
krakrjak/ImplicitCAD
tests/Main.hs
agpl-3.0
630
0
8
97
91
54
37
8
1
module OwnTypesClasses ( Point(..) -- We could also opt not to export any value constructors for Shape by just writing Shape in the export statement. -- That way, someone importing our module could only make shapes by using the auxilliary functions baseCircle and baseRect. -- Data.Map uses that approach , Shape(..) , surface , nudge , baseCircle , baseRect ) where import qualified Data.Map as M data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) surface :: Shape -> Float surface (Circle _ r) = pi * r ^ 2 surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1) nudge :: Shape -> Float -> Float -> Shape nudge (Circle (Point x y) r) a b = Circle (Point (x+a) (y+b)) r nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b = Rectangle (Point (x1+a) (y1+b)) (Point (x2+a) (y2+b)) baseCircle :: Float -> Shape baseCircle r = Circle (Point 0 0) r baseRect :: Float -> Float -> Shape baseRect width height = Rectangle (Point 0 0) (Point width height) -- === Record syntax === -- data Person = Person { firstName :: String , lastName :: String , age :: Int , height :: Float , phoneNumber :: String , flavor :: String } deriving (Show) -- By using record syntax to create this data type, Haskell automatically made these functions: firstName, lastName, age, height, phoneNumber and flavor -- When making an instance of a record, we don't have to necessarily put the fields in the proper order, -- as long as we list all of them. But if we don't use record syntax, we have to specify them in order. data Car = Car String String Int deriving (Show) carExample = Car "Ford" "Mustang" 1967 -- Does not use record syntax, all assigned fields must be in definition order data Car2 a b c = Car2 { company :: a , model :: b , year :: c } deriving (Show) carExample2 = Car2 { model = "Mustang", company = "Ford", year = 1967} -- record syntax allows deviating from definition order -- === Type parameters === -- -- it's a very strong convention in Haskell to never add typeclass constraints in data declarations -- When declaring a data type, the part before the = is the type constructor -- and the constructors after it (possibly separated by |'s) are value constructors data Vector a = Vector a a a deriving (Show) vplus :: (Num t) => Vector t -> Vector t -> Vector t (Vector i j k) `vplus` (Vector l m n) = Vector (i+l) (j+m) (k+n) vectMult :: (Num t) => Vector t -> t -> Vector t (Vector i j k) `vectMult` m = Vector (i*m) (j*m) (k*m) scalarMult :: (Num t) => Vector t -> Vector t -> t (Vector i j k) `scalarMult` (Vector l m n) = i*l + j*m + k*n vectorOperationTest = Vector 2 9 3 `vectMult` (Vector 4 9 5 `scalarMult` Vector 9 2 4) -- === Derived instances === -- -- Haskell can automatically make our type an instance of any of the following typeclasses: Eq, Ord, Enum, Bounded, Show, Read data Human = Human { fName :: String , lName :: String } deriving (Eq, Show, Read) showTest :: Human -> [Char] showTest h = show h readTest :: [Char] -> Human readTest s = read s -- "Human {fName = \"Merlijn\", lName = \"Boogerd\"}" -- If we compare two values of the same type that were made using different constructors, -- the value which was made with a constructor that's defined first is considered smaller --data Bool = False | True deriving (Ord) boolTest :: Bool boolTest = True `compare` False == GT data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Ord, Show, Read, Bounded, Enum) dayTest :: Bool dayTest = [Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday] == ([minBound .. maxBound] :: [Day]) -- === Type synonyms === -- -- Type synonyms (and types generally) can only be used in the type portion of Haskell. -- We introduce type synonyms either to describe what some existing type represents in our functions (and thus our -- type declarations become better documentation) or when something has a long-ish type that's repeated a lot -- (like [(String,String)]) but represents something more specific in the context of our functions type PhoneNumber = String type Name = String type PhoneBook = [(Name,PhoneNumber)] inPhoneBook :: Name -> PhoneNumber -> PhoneBook -> Bool inPhoneBook name pnumber pbook = (name,pnumber) `elem` pbook -- type aliases can also take type parameters type AssocList k v = [(k,v)] -- we can partially apply type parameters and get new type constructors from them type IntMap = M.Map Int -- supplies a key type-parameter but misses the value type-parameter data LockerState = Taken | Free deriving (Show, Eq) type Code = String type LockerMap = M.Map Int (LockerState, Code) lockerLookup :: Int -> LockerMap -> Either String Code lockerLookup lockerNumber map = case M.lookup lockerNumber map of Nothing -> Left $ "Locker number " ++ show lockerNumber ++ " doesn't exist!" Just (state, code) -> if state /= Taken then Right code else Left $ "Locker " ++ show lockerNumber ++ " is already taken!" lockers :: LockerMap lockers = M.fromList [(100,(Taken,"ZD39I")) ,(101,(Free,"JAH3I")) ,(103,(Free,"IQSA9")) ,(105,(Free,"QOTSA")) ,(109,(Taken,"893JJ")) ,(110,(Taken,"99292")) ] -- === Recursive data structures === -- -- fixity declaration; *'s fixity is infixl 7 * and +'s fixity is infixl 6; both left-associative, * binds stronger than + infixr 5 :-: data List a = Empty | a :-: (List a) deriving (Show, Read, Eq, Ord) infixr 5 .++ (.++) :: List a -> List a -> List a Empty .++ ys = ys (x :-: xs) .++ ys = x :-: (xs .++ ys) -- pattern matching is actually about matching constructors data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) singleton :: a -> Tree a singleton x = Node x EmptyTree EmptyTree treeInsert :: (Ord a) => a -> Tree a -> Tree a treeInsert x EmptyTree = singleton x treeInsert x (Node a left right) | x == a = Node x left right | x < a = Node a (treeInsert x left) right | x > a = Node a left (treeInsert x right) -- checks whether the value of the first argument is contained in the tree treeElem :: (Ord a) => a -> Tree a -> Bool treeElem x EmptyTree = False treeElem x (Node a left right) | x == a = True | x < a = treeElem x left | x > a = treeElem x right treeInsertAll :: (Ord a) => Tree a -> [a] -> Tree a treeInsertAll = foldr treeInsert treeNumbers = [8,6,4,1,7,3,5] numericTree = treeInsertAll EmptyTree treeNumbers tenNotInTree = 10 `treeElem` numericTree == False sevenInTree = 7 `treeElem` numericTree -- === Typeclasses 102 === -- -- class is for defining new typeclasses and instance is for making our types instances data TrafficLight = Red | Yellow | Green instance Eq TrafficLight where Red == Red = True Green == Green = True Yellow == Yellow = True _ == _ = False -- Because == (in Eq class) is defined in terms of /= and vice versa, we only had to overwrite one of them -- in the instance declaration to create a "minimal complete definition" instance Show TrafficLight where show Red = "Red light" show Yellow = "Yellow light" show Green = "Green light" -- Self-assigned exercise: Create an ad hoc (join-semi-lattice-like) class and a parameterized instance for inclusive-or infixl 6 *** class LatticeLike a where (***) :: a -> a -> a -- least-upperbound data Ior a b = This a | That b | Both a b deriving (Show) instance (Ord a, Ord b) => LatticeLike (Ior a b) where This a1 *** This a2 = This $ max a1 a2 That b1 *** That b2 = That $ max b1 b2 Both a1 b1 *** Both a2 b2 = Both (max a1 a2) (max b1 b2) This a *** That b = Both a b This a1 *** Both a2 b = Both (max a1 a2) b That b1 *** Both a b2 = Both a (max b1 b2) first *** second = second *** first -- three more cases to be exhaustive, but they are just mirrored -- === Yes-No typeclass === -- class YesNo a where yesno :: a -> Bool -- emulating more flexible boolean semantics: values that represent non-emptiness evaluate to true, otherwise false instance YesNo Int where yesno 0 = False yesno _ = True instance YesNo [a] where -- this also includes Strings of course yesno [] = False yesno _ = True instance YesNo Bool where yesno = id instance YesNo (Maybe a) where yesno (Just _) = True yesno Nothing = False instance YesNo (Tree a) where yesno EmptyTree = False yesno _ = True instance YesNo TrafficLight where yesno Red = False yesno _ = True -- mimick if functionality using YesNo yesnoIf :: (YesNo y) => y -> a -> a -> a yesnoIf yesnoVal yesResult noResult = if yesno yesnoVal then yesResult else noResult -- === Functor Typeclass === -- instance Functor Tree where fmap f EmptyTree = EmptyTree fmap f (Node x leftsub rightsub) = Node (f x) (fmap f leftsub) (fmap f rightsub) instance Functor (Ior a) where fmap f (That b) = That $ f b fmap f (Both a b) = Both a $ f b fmap f (This a) = This a -- If we use fmap (\a -> a) (the identity function, which just returns its parameter) over some list, we expect to get back the same list as a result -- === Kinds and some type-foo === -- -- Types are little labels that values carry so that we can reason about the values. -- But types have their own little labels, called kinds; A kind is more or less the type of a type -- A * means that the type is a concrete type -- A concrete type is a type that doesn't take any type parameters and values can only have types that are concrete types -- We use :k on a type to get its kind, just like we can use :t on a value to get its type -- Type constructors are curried (just like functions), so we can partially apply them -- ghci> :k Either String -- Either String :: * -> * -- ghci> :k Either String Int -- Either String Int :: * class Tofu t where tofu :: j a -> t a j data Frank a b = Frank {frankField :: b a} deriving (Show) instance Tofu Frank where tofu x = Frank x data Barry t k p = Barry { yabba :: p, dabba :: t k } deriving (Show) instance Functor (Barry t k) where fmap f (Barry { yabba = p, dabba = q }) = Barry { yabba = f p, dabba = q }
mboogerd/hello-haskell
src/lyah/OwnTypesClasses.hs
apache-2.0
10,498
0
11
2,528
2,919
1,578
1,341
165
3
data ListItem a = Single a | Multiple Int a deriving (Show) decodeModified :: [ListItem a] -> [a] decodeModified [] = [] decodeModified (Single a : xs) = [a] ++ decodeModified xs decodeModified (Multiple n a : xs) = replicate n a ++ decodeModified xs
plilja/h99
p12.hs
apache-2.0
256
0
8
50
115
59
56
6
1
ans (t:n:_) | t == 1 = 6000 * n | t == 2 = 4000 * n | t == 3 = 3000 * n | t == 4 = 2000 * n main = do c <- getContents let i = map (map read) $ map words $ lines c :: [[Int]] o = map ans i mapM_ print o
a143753/AOJ
0277.hs
apache-2.0
227
0
14
86
156
74
82
10
1
{- Copyright 2010-2012 Cognimeta Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE TemplateHaskell, TypeFamilies #-} module Cgm.Data.Functor.Sum ( Sum(..) ) where import Cgm.Data.Structured newtype Sum a b e = Sum {getSum :: Either (a e) (b e)} deriveStructured ''Sum
Cognimeta/cognimeta-utils
src/Cgm/Data/Functor/Sum.hs
apache-2.0
796
0
9
152
66
41
25
6
0
module HaskHOL.Lib.IndDefs.PQ where import HaskHOL.Core import HaskHOL.Lib.IndDefs.Context -- Lift Parse Context and define quasi-quoter pcIndDefs :: ParseContext pcIndDefs = $(liftParseContext ctxtIndDefs) indDefs :: QuasiQuoter indDefs = baseQuoter ctxtIndDefs pcIndDefs
ecaustin/haskhol-deductive
src/HaskHOL/Lib/IndDefs/PQ.hs
bsd-2-clause
276
0
7
32
53
32
21
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} module RPG.Data.Gen.Portal ( portal ) where import Game.Sequoia.Color (yellow) import Game.Sequoia.Utils import RPG.Core import RPG.Scene portal :: ( Some r , Has (Loc -> IO ()) r , Has ((Prop -> Prop) -> IO ()) r , Has (Loc -> PropId -> B (Maybe Prop)) r ) => Loc -> Loc -> Eff r (Prop, Prop) portal dst1 dst2 = do (setLoc :: Loc -> IO ()) <- ask (movePlayer :: (Prop -> Prop) -> IO ()) <- ask (findProp :: Loc -> PropId -> B (Maybe Prop)) <- ask p1 <- portalGen p2 <- portalGen let id1 = maybe undefined id . view propKey . head $ tags p1 id2 = maybe undefined id . view propKey . head $ tags p2 f d i = tagging . set interaction . Just $ do pos <- fmap (maybe origin center) . sample $ findProp d i liftIO $ do setLoc d movePlayer $ teleport pos return ( f dst2 id2 p1 , f dst1 id1 p2 ) portalGen :: Some r => Eff r Prop portalGen = do idkey <- Just . PropId <$> int return . tagging (propKey .~ idkey) . traced yellow $ rect origin 40 40
isovector/rpg-gen
src/RPG/Data/Gen/Portal.hs
bsd-3-clause
1,302
0
18
473
496
245
251
37
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Diagrams.Swimunit.Base where import Diagrams.Prelude import Diagrams.Backend.SVG.CmdLine import Diagrams.Swimunit.Dotmatrix loglevel :: Int loglevel = debugll {-| 0 Fatal 1 Error 2 Warning 3 Info 4 Debug 5 Trace -} debugll :: Int debugll = 4 errordot :: Diagram B errordot = circle 1.0 errordotfont :: Dotfont errordotfont = dotfont_B6x9 {-| Constructs a rectangle with an error message passed as argument. A medium gray background should offer enough contrast for both light and dark themes. -} errord :: String -> Diagram B errord errmsg = ( dotmatrix errordot errordotfont errmsg # lc magenta # fc magenta <> rect 1.0 1.0 # lc magenta # fc gray ) {-| This defines an empty diagram which is used almost everytime when error occurs but the diagram should be rendered anyhow. Note that setting this to something visible may help debugging diagrams produced by swimunit. -} emptyd :: Diagram B emptyd = circle 0.0 -- ---- --
wherkendell/diagrams-contrib
src/Diagrams/Swimunit/Base.hs
bsd-3-clause
1,110
0
11
293
161
89
72
25
1
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE OverloadedStrings #-} module Reporting.Warning where import Data.Aeson ((.=)) import qualified Data.Aeson as Json import qualified Text.PrettyPrint as P import Text.PrettyPrint ((<+>)) import qualified AST.Module as Module import qualified AST.Type as Type import qualified Nitpick.Pattern as Pattern import qualified Reporting.Annotation as A import qualified Reporting.PrettyPrint as P import qualified Reporting.Report as Report -- ALL POSSIBLE WARNINGS data Warning = UnusedImport Module.Name | MissingTypeAnnotation String Type.Canonical | InexhaustivePatternMatch [Pattern.Pattern] | RedundantPatternMatch -- TO STRING toString :: P.Dealiaser -> String -> String -> A.Located Warning -> String toString dealiaser location source (A.A region warning) = Report.toString location region (toReport dealiaser warning) source print :: P.Dealiaser -> String -> String -> A.Located Warning -> IO () print dealiaser location source (A.A region warning) = Report.printWarning location region (toReport dealiaser warning) source toReport :: P.Dealiaser -> Warning -> Report.Report toReport dealiaser warning = case warning of UnusedImport moduleName -> Report.simple "unused import" ("Module `" ++ Module.nameToString moduleName ++ "` is unused.") "" MissingTypeAnnotation name inferredType -> Report.simple "missing type annotation" ("Top-level value `" ++ name ++ "` does not have a type annotation.") ( "The type annotation you want looks something like this:\n\n" ++ P.render (P.nest 4 typeDoc) ) where typeDoc = P.hang (P.text name <+> P.colon) 4 (P.pretty dealiaser False inferredType) InexhaustivePatternMatch unhandled -> Report.simple "missing pattern" "The following case expression does not handle all possible inputs." ( "The following patterns are not being handled:\n" ++ viewPatternList unhandled ++ "\n\n" ++ "If we get values like this, we have no choice but to crash! Normally this means\n" ++ "you just added a new tag to a union type, but sometimes it can be because there\n" ++ "is something very odd about the data you are modeling. In those rare cases, you\n" ++ "probably want to either:\n" ++ "\n" ++ " 1. Rethink the model. Maybe some cases are \"impossible\" but it is still\n" ++ " possible to construct such cases. Is there a way to model the values more\n" ++ " precisely such that \"impossible\" values truly are impossible?\n" ++ " 2. End the pattern match with a wildcard match that leads to an expression\n" ++ " like: Debug.crash \"If you are reading this, I have made a mistake!\"\n" ++ " Generally speaking, you do not want it to have to be this way." ) RedundantPatternMatch -> Report.simple "redundant pattern" "The following pattern is redundant." "Any value with this shape will be handled by a previous pattern." -- TO JSON toJson :: P.Dealiaser -> FilePath -> A.Located Warning -> Json.Value toJson dealiaser filePath (A.A region warning) = let (maybeRegion, additionalFields) = Report.toJson [] (toReport dealiaser warning) in Json.object $ [ "file" .= filePath , "region" .= maybe region id maybeRegion , "type" .= ("warning" :: String) ] ++ additionalFields -- PATTERN WARNINGS viewPatternList :: [Pattern.Pattern] -> String viewPatternList unhandledPatterns = let (showPatterns, rest) = splitAt 4 unhandledPatterns in concatMap ((++) "\n ") $ map Pattern.toString showPatterns ++ if null rest then [] else ["..."]
johnpmayer/elm-compiler
src/Reporting/Warning.hs
bsd-3-clause
3,971
0
23
1,072
745
398
347
84
4
-- | General import procedure. module HN.Model.Import where import HN.Model.Feeds import HN.Model.Soup import HN.Monads import HN.System import Snap.App -- | Import ALL THE THINGS. importEverything :: Model c s () importEverything = void $ do io $ hSetBuffering stdout NoBuffering forM_ [(importRedditHaskell,"importRedditHaskell") ,(importProggit,"importProggit") ,(importVimeo,"importVimeo") ,(importHaskellTwitter,"importHaskellTwitter") ,(importHaskellTips,"importTips") ,(importHackage,"importHackage") ,(importHaskellWiki,"importHaskellWiki") ,(importStackOverflow,"importStackOverflow") ,(importPlanetHaskell,"importPlanetHaskell") ,(importHaskellCafe,"importHaskellCafe") ,(importLibraries,"importLibraries") ,(importGhcDevs,"importGhcDevs") ,(importGooglePlus,"importGooglePlus") ,(importIrcQuotes,"importIrcQuotes") ,(importPastes,"importPastes") ,(importEvents,"importEvents")] $ \(m,op) -> do result <- m case result of Right{} -> return () Left e -> io $ print (op,e)
jwaldmann/haskellnews
src/HN/Model/Import.hs
bsd-3-clause
1,161
0
17
258
287
172
115
30
2
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 A ``lint'' pass to check for Core correctness -} {-# LANGUAGE CPP #-} module CoreLint ( lintCoreBindings, lintUnfolding, lintPassResult, lintInteractiveExpr, lintExpr, lintAnnots, -- ** Debug output endPass, endPassIO, dumpPassResult, CoreLint.dumpIfSet, ) where #include "HsVersions.h" import GhcPrelude import CoreSyn import CoreFVs import CoreUtils import CoreStats ( coreBindsStats ) import CoreMonad import Bag import Literal import DataCon import TysWiredIn import TysPrim import TcType ( isFloatingTy ) import Var import VarEnv import VarSet import Name import Id import IdInfo import PprCore import ErrUtils import Coercion import SrcLoc import Kind import Type import RepType import TyCoRep -- checks validity of types/coercions import TyCon import CoAxiom import BasicTypes import ErrUtils as Err import ListSetOps import PrelNames import Outputable import FastString import Util import InstEnv ( instanceDFunId ) import OptCoercion ( checkAxInstCo ) import UniqSupply import CoreArity ( typeArity ) import Demand ( splitStrictSig, isBotRes ) import HscTypes import DynFlags import Control.Monad import qualified Control.Monad.Fail as MonadFail import MonadUtils import Data.Foldable ( toList ) import Data.List.NonEmpty ( NonEmpty ) import Data.Maybe import Pair import qualified GHC.LanguageExtensions as LangExt {- Note [GHC Formalism] ~~~~~~~~~~~~~~~~~~~~ This file implements the type-checking algorithm for System FC, the "official" name of the Core language. Type safety of FC is heart of the claim that executables produced by GHC do not have segmentation faults. Thus, it is useful to be able to reason about System FC independently of reading the code. To this purpose, there is a document core-spec.pdf built in docs/core-spec that contains a formalism of the types and functions dealt with here. If you change just about anything in this file or you change other types/functions throughout the Core language (all signposted to this note), you should update that formalism. See docs/core-spec/README for more info about how to do so. Note [check vs lint] ~~~~~~~~~~~~~~~~~~~~ This file implements both a type checking algorithm and also general sanity checking. For example, the "sanity checking" checks for TyConApp on the left of an AppTy, which should never happen. These sanity checks don't really affect any notion of type soundness. Yet, it is convenient to do the sanity checks at the same time as the type checks. So, we use the following naming convention: - Functions that begin with 'lint'... are involved in type checking. These functions might also do some sanity checking. - Functions that begin with 'check'... are *not* involved in type checking. They exist only for sanity checking. Issues surrounding variable naming, shadowing, and such are considered *not* to be part of type checking, as the formalism omits these details. Summary of checks ~~~~~~~~~~~~~~~~~ Checks that a set of core bindings is well-formed. The PprStyle and String just control what we print in the event of an error. The Bool value indicates whether we have done any specialisation yet (in which case we do some extra checks). We check for (a) type errors (b) Out-of-scope type variables (c) Out-of-scope local variables (d) Ill-kinded types (e) Incorrect unsafe coercions If we have done specialisation the we check that there are (a) No top-level bindings of primitive (unboxed type) Outstanding issues: -- Things are *not* OK if: -- -- * Unsaturated type app before specialisation has been done; -- -- * Oversaturated type app after specialisation (eta reduction -- may well be happening...); Note [Linting function types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ As described in Note [Representation of function types], all saturated applications of funTyCon are represented with the FunTy constructor. We check this invariant in lintType. Note [Linting type lets] ~~~~~~~~~~~~~~~~~~~~~~~~ In the desugarer, it's very very convenient to be able to say (in effect) let a = Type Int in <body> That is, use a type let. See Note [Type let] in CoreSyn. However, when linting <body> we need to remember that a=Int, else we might reject a correct program. So we carry a type substitution (in this example [a -> Int]) and apply this substitution before comparing types. The functin lintInTy :: Type -> LintM (Type, Kind) returns a substituted type. When we encounter a binder (like x::a) we must apply the substitution to the type of the binding variable. lintBinders does this. For Ids, the type-substituted Id is added to the in_scope set (which itself is part of the TCvSubst we are carrying down), and when we find an occurrence of an Id, we fetch it from the in-scope set. Note [Bad unsafe coercion] ~~~~~~~~~~~~~~~~~~~~~~~~~~ For discussion see https://ghc.haskell.org/trac/ghc/wiki/BadUnsafeCoercions Linter introduces additional rules that checks improper coercion between different types, called bad coercions. Following coercions are forbidden: (a) coercions between boxed and unboxed values; (b) coercions between unlifted values of the different sizes, here active size is checked, i.e. size of the actual value but not the space allocated for value; (c) coercions between floating and integral boxed values, this check is not yet supported for unboxed tuples, as no semantics were specified for that; (d) coercions from / to vector type (e) If types are unboxed tuples then tuple (# A_1,..,A_n #) can be coerced to (# B_1,..,B_m #) if n=m and for each pair A_i, B_i rules (a-e) holds. Note [Join points] ~~~~~~~~~~~~~~~~~~ We check the rules listed in Note [Invariants on join points] in CoreSyn. The only one that causes any difficulty is the first: All occurrences must be tail calls. To this end, along with the in-scope set, we remember in le_joins the subset of in-scope Ids that are valid join ids. For example: join j x = ... in case e of A -> jump j y -- good B -> case (jump j z) of -- BAD C -> join h = jump j w in ... -- good D -> let x = jump j v in ... -- BAD A join point remains valid in case branches, so when checking the A branch, j is still valid. When we check the scrutinee of the inner case, however, we set le_joins to empty, and catch the error. Similarly, join points can occur free in RHSes of other join points but not the RHSes of value bindings (thunks and functions). ************************************************************************ * * Beginning and ending passes * * ************************************************************************ These functions are not CoreM monad stuff, but they probably ought to be, and it makes a convenient place for them. They print out stuff before and after core passes, and do Core Lint when necessary. -} endPass :: CoreToDo -> CoreProgram -> [CoreRule] -> CoreM () endPass pass binds rules = do { hsc_env <- getHscEnv ; print_unqual <- getPrintUnqualified ; liftIO $ endPassIO hsc_env print_unqual pass binds rules } endPassIO :: HscEnv -> PrintUnqualified -> CoreToDo -> CoreProgram -> [CoreRule] -> IO () -- Used by the IO-is CorePrep too endPassIO hsc_env print_unqual pass binds rules = do { dumpPassResult dflags print_unqual mb_flag (ppr pass) (pprPassDetails pass) binds rules ; lintPassResult hsc_env pass binds } where dflags = hsc_dflags hsc_env mb_flag = case coreDumpFlag pass of Just flag | dopt flag dflags -> Just flag | dopt Opt_D_verbose_core2core dflags -> Just flag _ -> Nothing dumpIfSet :: DynFlags -> Bool -> CoreToDo -> SDoc -> SDoc -> IO () dumpIfSet dflags dump_me pass extra_info doc = Err.dumpIfSet dflags dump_me (showSDoc dflags (ppr pass <+> extra_info)) doc dumpPassResult :: DynFlags -> PrintUnqualified -> Maybe DumpFlag -- Just df => show details in a file whose -- name is specified by df -> SDoc -- Header -> SDoc -- Extra info to appear after header -> CoreProgram -> [CoreRule] -> IO () dumpPassResult dflags unqual mb_flag hdr extra_info binds rules = do { forM_ mb_flag $ \flag -> Err.dumpSDoc dflags unqual flag (showSDoc dflags hdr) dump_doc -- Report result size -- This has the side effect of forcing the intermediate to be evaluated -- if it's not already forced by a -ddump flag. ; Err.debugTraceMsg dflags 2 size_doc } where size_doc = sep [text "Result size of" <+> hdr, nest 2 (equals <+> ppr (coreBindsStats binds))] dump_doc = vcat [ nest 2 extra_info , size_doc , blankLine , pprCoreBindingsWithSize binds , ppUnless (null rules) pp_rules ] pp_rules = vcat [ blankLine , text "------ Local rules for imported ids --------" , pprRules rules ] coreDumpFlag :: CoreToDo -> Maybe DumpFlag coreDumpFlag (CoreDoSimplify {}) = Just Opt_D_verbose_core2core coreDumpFlag (CoreDoPluginPass {}) = Just Opt_D_verbose_core2core coreDumpFlag CoreDoFloatInwards = Just Opt_D_verbose_core2core coreDumpFlag (CoreDoFloatOutwards {}) = Just Opt_D_verbose_core2core coreDumpFlag CoreLiberateCase = Just Opt_D_verbose_core2core coreDumpFlag CoreDoStaticArgs = Just Opt_D_verbose_core2core coreDumpFlag CoreDoCallArity = Just Opt_D_dump_call_arity coreDumpFlag CoreDoExitify = Just Opt_D_dump_exitify coreDumpFlag CoreDoStrictness = Just Opt_D_dump_stranal coreDumpFlag CoreDoWorkerWrapper = Just Opt_D_dump_worker_wrapper coreDumpFlag CoreDoSpecialising = Just Opt_D_dump_spec coreDumpFlag CoreDoSpecConstr = Just Opt_D_dump_spec coreDumpFlag CoreCSE = Just Opt_D_dump_cse coreDumpFlag CoreDoVectorisation = Just Opt_D_dump_vect coreDumpFlag CoreDesugar = Just Opt_D_dump_ds_preopt coreDumpFlag CoreDesugarOpt = Just Opt_D_dump_ds coreDumpFlag CoreTidy = Just Opt_D_dump_simpl coreDumpFlag CorePrep = Just Opt_D_dump_prep coreDumpFlag CoreOccurAnal = Just Opt_D_dump_occur_anal coreDumpFlag CoreDoPrintCore = Nothing coreDumpFlag (CoreDoRuleCheck {}) = Nothing coreDumpFlag CoreDoNothing = Nothing coreDumpFlag (CoreDoPasses {}) = Nothing {- ************************************************************************ * * Top-level interfaces * * ************************************************************************ -} lintPassResult :: HscEnv -> CoreToDo -> CoreProgram -> IO () lintPassResult hsc_env pass binds | not (gopt Opt_DoCoreLinting dflags) = return () | otherwise = do { let (warns, errs) = lintCoreBindings dflags pass (interactiveInScope hsc_env) binds ; Err.showPass dflags ("Core Linted result of " ++ showPpr dflags pass) ; displayLintResults dflags pass warns errs binds } where dflags = hsc_dflags hsc_env displayLintResults :: DynFlags -> CoreToDo -> Bag Err.MsgDoc -> Bag Err.MsgDoc -> CoreProgram -> IO () displayLintResults dflags pass warns errs binds | not (isEmptyBag errs) = do { putLogMsg dflags NoReason Err.SevDump noSrcSpan (defaultDumpStyle dflags) (vcat [ lint_banner "errors" (ppr pass), Err.pprMessageBag errs , text "*** Offending Program ***" , pprCoreBindings binds , text "*** End of Offense ***" ]) ; Err.ghcExit dflags 1 } | not (isEmptyBag warns) , not (hasNoDebugOutput dflags) , showLintWarnings pass -- If the Core linter encounters an error, output to stderr instead of -- stdout (#13342) = putLogMsg dflags NoReason Err.SevInfo noSrcSpan (defaultDumpStyle dflags) (lint_banner "warnings" (ppr pass) $$ Err.pprMessageBag (mapBag ($$ blankLine) warns)) | otherwise = return () where lint_banner :: String -> SDoc -> SDoc lint_banner string pass = text "*** Core Lint" <+> text string <+> text ": in result of" <+> pass <+> text "***" showLintWarnings :: CoreToDo -> Bool -- Disable Lint warnings on the first simplifier pass, because -- there may be some INLINE knots still tied, which is tiresomely noisy showLintWarnings (CoreDoSimplify _ (SimplMode { sm_phase = InitialPhase })) = False showLintWarnings _ = True lintInteractiveExpr :: String -> HscEnv -> CoreExpr -> IO () lintInteractiveExpr what hsc_env expr | not (gopt Opt_DoCoreLinting dflags) = return () | Just err <- lintExpr dflags (interactiveInScope hsc_env) expr = do { display_lint_err err ; Err.ghcExit dflags 1 } | otherwise = return () where dflags = hsc_dflags hsc_env display_lint_err err = do { putLogMsg dflags NoReason Err.SevDump noSrcSpan (defaultDumpStyle dflags) (vcat [ lint_banner "errors" (text what) , err , text "*** Offending Program ***" , pprCoreExpr expr , text "*** End of Offense ***" ]) ; Err.ghcExit dflags 1 } interactiveInScope :: HscEnv -> [Var] -- In GHCi we may lint expressions, or bindings arising from 'deriving' -- clauses, that mention variables bound in the interactive context. -- These are Local things (see Note [Interactively-bound Ids in GHCi] in HscTypes). -- So we have to tell Lint about them, lest it reports them as out of scope. -- -- We do this by find local-named things that may appear free in interactive -- context. This function is pretty revolting and quite possibly not quite right. -- When we are not in GHCi, the interactive context (hsc_IC hsc_env) is empty -- so this is a (cheap) no-op. -- -- See Trac #8215 for an example interactiveInScope hsc_env = tyvars ++ ids where -- C.f. TcRnDriver.setInteractiveContext, Desugar.deSugarExpr ictxt = hsc_IC hsc_env (cls_insts, _fam_insts) = ic_instances ictxt te1 = mkTypeEnvWithImplicits (ic_tythings ictxt) te = extendTypeEnvWithIds te1 (map instanceDFunId cls_insts) ids = typeEnvIds te tyvars = tyCoVarsOfTypesList $ map idType ids -- Why the type variables? How can the top level envt have free tyvars? -- I think it's because of the GHCi debugger, which can bind variables -- f :: [t] -> [t] -- where t is a RuntimeUnk (see TcType) lintCoreBindings :: DynFlags -> CoreToDo -> [Var] -> CoreProgram -> (Bag MsgDoc, Bag MsgDoc) -- Returns (warnings, errors) -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintCoreBindings dflags pass local_in_scope binds = initL dflags flags in_scope_set $ addLoc TopLevelBindings $ lintLetBndrs TopLevel binders $ -- Put all the top-level binders in scope at the start -- This is because transformation rules can bring something -- into use 'unexpectedly' do { checkL (null dups) (dupVars dups) ; checkL (null ext_dups) (dupExtVars ext_dups) ; mapM lint_bind binds } where in_scope_set = mkInScopeSet (mkVarSet local_in_scope) flags = LF { lf_check_global_ids = check_globals , lf_check_inline_loop_breakers = check_lbs , lf_check_static_ptrs = check_static_ptrs } -- See Note [Checking for global Ids] check_globals = case pass of CoreTidy -> False CorePrep -> False _ -> True -- See Note [Checking for INLINE loop breakers] check_lbs = case pass of CoreDesugar -> False CoreDesugarOpt -> False _ -> True -- See Note [Checking StaticPtrs] check_static_ptrs | not (xopt LangExt.StaticPointers dflags) = AllowAnywhere | otherwise = case pass of CoreDoFloatOutwards _ -> AllowAtTopLevel CoreTidy -> RejectEverywhere CorePrep -> AllowAtTopLevel _ -> AllowAnywhere binders = bindersOfBinds binds (_, dups) = removeDups compare binders -- dups_ext checks for names with different uniques -- but but the same External name M.n. We don't -- allow this at top level: -- M.n{r3} = ... -- M.n{r29} = ... -- because they both get the same linker symbol ext_dups = snd (removeDups ord_ext (map Var.varName binders)) ord_ext n1 n2 | Just m1 <- nameModule_maybe n1 , Just m2 <- nameModule_maybe n2 = compare (m1, nameOccName n1) (m2, nameOccName n2) | otherwise = LT -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lint_bind (Rec prs) = mapM_ (lintSingleBinding TopLevel Recursive) prs lint_bind (NonRec bndr rhs) = lintSingleBinding TopLevel NonRecursive (bndr,rhs) {- ************************************************************************ * * \subsection[lintUnfolding]{lintUnfolding} * * ************************************************************************ Note [Linting Unfoldings from Interfaces] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use this to check all top-level unfoldings that come in from interfaces (it is very painful to catch errors otherwise). We do not need to call lintUnfolding on unfoldings that are nested within top-level unfoldings; they are linted when we lint the top-level unfolding; hence the `TopLevelFlag` on `tcPragExpr` in TcIface. -} lintUnfolding :: DynFlags -> SrcLoc -> VarSet -- Treat these as in scope -> CoreExpr -> Maybe MsgDoc -- Nothing => OK lintUnfolding dflags locn vars expr | isEmptyBag errs = Nothing | otherwise = Just (pprMessageBag errs) where in_scope = mkInScopeSet vars (_warns, errs) = initL dflags defaultLintFlags in_scope linter linter = addLoc (ImportedUnfolding locn) $ lintCoreExpr expr lintExpr :: DynFlags -> [Var] -- Treat these as in scope -> CoreExpr -> Maybe MsgDoc -- Nothing => OK lintExpr dflags vars expr | isEmptyBag errs = Nothing | otherwise = Just (pprMessageBag errs) where in_scope = mkInScopeSet (mkVarSet vars) (_warns, errs) = initL dflags defaultLintFlags in_scope linter linter = addLoc TopLevelBindings $ lintCoreExpr expr {- ************************************************************************ * * \subsection[lintCoreBinding]{lintCoreBinding} * * ************************************************************************ Check a core binding, returning the list of variables bound. -} lintSingleBinding :: TopLevelFlag -> RecFlag -> (Id, CoreExpr) -> LintM () -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintSingleBinding top_lvl_flag rec_flag (binder,rhs) = addLoc (RhsOf binder) $ -- Check the rhs do { ty <- lintRhs binder rhs ; binder_ty <- applySubstTy (idType binder) ; ensureEqTys binder_ty ty (mkRhsMsg binder (text "RHS") ty) -- Check that it's not levity-polymorphic -- Do this first, because otherwise isUnliftedType panics -- Annoyingly, this duplicates the test in lintIdBdr, -- because for non-rec lets we call lintSingleBinding first ; checkL (isJoinId binder || not (isTypeLevPoly binder_ty)) (badBndrTyMsg binder (text "levity-polymorphic")) -- Check the let/app invariant -- See Note [CoreSyn let/app invariant] in CoreSyn ; checkL ( isJoinId binder || not (isUnliftedType binder_ty) || (isNonRec rec_flag && exprOkForSpeculation rhs) || exprIsLiteralString rhs) (badBndrTyMsg binder (text "unlifted")) -- Check that if the binder is top-level or recursive, it's not -- demanded. Primitive string literals are exempt as there is no -- computation to perform, see Note [CoreSyn top-level string literals]. ; checkL (not (isStrictId binder) || (isNonRec rec_flag && not (isTopLevel top_lvl_flag)) || exprIsLiteralString rhs) (mkStrictMsg binder) -- Check that if the binder is at the top level and has type Addr#, -- that it is a string literal, see -- Note [CoreSyn top-level string literals]. ; checkL (not (isTopLevel top_lvl_flag && binder_ty `eqType` addrPrimTy) || exprIsLiteralString rhs) (mkTopNonLitStrMsg binder) ; flags <- getLintFlags -- Check that a join-point binder has a valid type -- NB: lintIdBinder has checked that it is not top-level bound ; case isJoinId_maybe binder of Nothing -> return () Just arity -> checkL (isValidJoinPointType arity binder_ty) (mkInvalidJoinPointMsg binder binder_ty) ; when (lf_check_inline_loop_breakers flags && isStableUnfolding (realIdUnfolding binder) && isStrongLoopBreaker (idOccInfo binder) && isInlinePragma (idInlinePragma binder)) (addWarnL (text "INLINE binder is (non-rule) loop breaker:" <+> ppr binder)) -- Only non-rule loop breakers inhibit inlining -- Check whether arity and demand type are consistent (only if demand analysis -- already happened) -- -- Note (Apr 2014): this is actually ok. See Note [Demand analysis for trivial right-hand sides] -- in DmdAnal. After eta-expansion in CorePrep the rhs is no longer trivial. -- ; let dmdTy = idStrictness binder -- ; checkL (case dmdTy of -- StrictSig dmd_ty -> idArity binder >= dmdTypeDepth dmd_ty || exprIsTrivial rhs) -- (mkArityMsg binder) -- Check that the binder's arity is within the bounds imposed by -- the type and the strictness signature. See Note [exprArity invariant] -- and Note [Trimming arity] ; checkL (typeArity (idType binder) `lengthAtLeast` idArity binder) (text "idArity" <+> ppr (idArity binder) <+> text "exceeds typeArity" <+> ppr (length (typeArity (idType binder))) <> colon <+> ppr binder) ; case splitStrictSig (idStrictness binder) of (demands, result_info) | isBotRes result_info -> checkL (demands `lengthAtLeast` idArity binder) (text "idArity" <+> ppr (idArity binder) <+> text "exceeds arity imposed by the strictness signature" <+> ppr (idStrictness binder) <> colon <+> ppr binder) _ -> return () ; mapM_ (lintCoreRule binder binder_ty) (idCoreRules binder) ; addLoc (UnfoldingOf binder) $ lintIdUnfolding binder binder_ty (idUnfolding binder) } -- We should check the unfolding, if any, but this is tricky because -- the unfolding is a SimplifiableCoreExpr. Give up for now. -- | Checks the RHS of bindings. It only differs from 'lintCoreExpr' -- in that it doesn't reject occurrences of the function 'makeStatic' when they -- appear at the top level and @lf_check_static_ptrs == AllowAtTopLevel@, and -- for join points, it skips the outer lambdas that take arguments to the -- join point. -- -- See Note [Checking StaticPtrs]. lintRhs :: Id -> CoreExpr -> LintM OutType lintRhs bndr rhs | Just arity <- isJoinId_maybe bndr = lint_join_lams arity arity True rhs | AlwaysTailCalled arity <- tailCallInfo (idOccInfo bndr) = lint_join_lams arity arity False rhs where lint_join_lams 0 _ _ rhs = lintCoreExpr rhs lint_join_lams n tot enforce (Lam var expr) = addLoc (LambdaBodyOf var) $ lintBinder LambdaBind var $ \ var' -> do { body_ty <- lint_join_lams (n-1) tot enforce expr ; return $ mkLamType var' body_ty } lint_join_lams n tot True _other = failWithL $ mkBadJoinArityMsg bndr tot (tot-n) rhs lint_join_lams _ _ False rhs = markAllJoinsBad $ lintCoreExpr rhs -- Future join point, not yet eta-expanded -- Body is not a tail position -- Allow applications of the data constructor @StaticPtr@ at the top -- but produce errors otherwise. lintRhs _bndr rhs = fmap lf_check_static_ptrs getLintFlags >>= go where -- Allow occurrences of 'makeStatic' at the top-level but produce errors -- otherwise. go AllowAtTopLevel | (binders0, rhs') <- collectTyBinders rhs , Just (fun, t, info, e) <- collectMakeStaticArgs rhs' = markAllJoinsBad $ foldr -- imitate @lintCoreExpr (Lam ...)@ (\var loopBinders -> addLoc (LambdaBodyOf var) $ lintBinder LambdaBind var $ \var' -> do { body_ty <- loopBinders ; return $ mkLamType var' body_ty } ) -- imitate @lintCoreExpr (App ...)@ (do fun_ty <- lintCoreExpr fun addLoc (AnExpr rhs') $ lintCoreArgs fun_ty [Type t, info, e] ) binders0 go _ = markAllJoinsBad $ lintCoreExpr rhs lintIdUnfolding :: Id -> Type -> Unfolding -> LintM () lintIdUnfolding bndr bndr_ty (CoreUnfolding { uf_tmpl = rhs, uf_src = src }) | isStableSource src = do { ty <- lintRhs bndr rhs ; ensureEqTys bndr_ty ty (mkRhsMsg bndr (text "unfolding") ty) } lintIdUnfolding bndr bndr_ty (DFunUnfolding { df_con = con, df_bndrs = bndrs , df_args = args }) = do { ty <- lintBinders LambdaBind bndrs $ \ bndrs' -> do { res_ty <- lintCoreArgs (dataConRepType con) args ; return (mkLamTypes bndrs' res_ty) } ; ensureEqTys bndr_ty ty (mkRhsMsg bndr (text "dfun unfolding") ty) } lintIdUnfolding _ _ _ = return () -- Do not Lint unstable unfoldings, because that leads -- to exponential behaviour; c.f. CoreFVs.idUnfoldingVars {- Note [Checking for INLINE loop breakers] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's very suspicious if a strong loop breaker is marked INLINE. However, the desugarer generates instance methods with INLINE pragmas that form a mutually recursive group. Only after a round of simplification are they unravelled. So we suppress the test for the desugarer. ************************************************************************ * * \subsection[lintCoreExpr]{lintCoreExpr} * * ************************************************************************ -} -- For OutType, OutKind, the substitution has been applied, -- but has not been linted yet type LintedType = Type -- Substitution applied, and type is linted type LintedKind = Kind lintCoreExpr :: CoreExpr -> LintM OutType -- The returned type has the substitution from the monad -- already applied to it: -- lintCoreExpr e subst = exprType (subst e) -- -- The returned "type" can be a kind, if the expression is (Type ty) -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintCoreExpr (Var var) = lintVarOcc var 0 lintCoreExpr (Lit lit) = return (literalType lit) lintCoreExpr (Cast expr co) = do { expr_ty <- markAllJoinsBad $ lintCoreExpr expr ; co' <- applySubstCo co ; (_, k2, from_ty, to_ty, r) <- lintCoercion co' ; lintL (classifiesTypeWithValues k2) (text "Target of cast not # or *:" <+> ppr co) ; lintRole co' Representational r ; ensureEqTys from_ty expr_ty (mkCastErr expr co' from_ty expr_ty) ; return to_ty } lintCoreExpr (Tick tickish expr) = do case tickish of Breakpoint _ ids -> forM_ ids $ \id -> do checkDeadIdOcc id lookupIdInScope id _ -> return () markAllJoinsBadIf block_joins $ lintCoreExpr expr where block_joins = not (tickish `tickishScopesLike` SoftScope) -- TODO Consider whether this is the correct rule. It is consistent with -- the simplifier's behaviour - cost-centre-scoped ticks become part of -- the continuation, and thus they behave like part of an evaluation -- context, but soft-scoped and non-scoped ticks simply wrap the result -- (see Simplify.simplTick). lintCoreExpr (Let (NonRec tv (Type ty)) body) | isTyVar tv = -- See Note [Linting type lets] do { ty' <- applySubstTy ty ; lintTyBndr tv $ \ tv' -> do { addLoc (RhsOf tv) $ lintTyKind tv' ty' -- Now extend the substitution so we -- take advantage of it in the body ; extendSubstL tv ty' $ addLoc (BodyOfLetRec [tv]) $ lintCoreExpr body } } lintCoreExpr (Let (NonRec bndr rhs) body) | isId bndr = do { lintSingleBinding NotTopLevel NonRecursive (bndr,rhs) ; addLoc (BodyOfLetRec [bndr]) (lintIdBndr NotTopLevel LetBind bndr $ \_ -> addGoodJoins [bndr] $ lintCoreExpr body) } | otherwise = failWithL (mkLetErr bndr rhs) -- Not quite accurate lintCoreExpr e@(Let (Rec pairs) body) = lintLetBndrs NotTopLevel bndrs $ addGoodJoins bndrs $ do { -- Check that the list of pairs is non-empty checkL (not (null pairs)) (emptyRec e) -- Check that there are no duplicated binders ; checkL (null dups) (dupVars dups) -- Check that either all the binders are joins, or none ; checkL (all isJoinId bndrs || all (not . isJoinId) bndrs) $ mkInconsistentRecMsg bndrs ; mapM_ (lintSingleBinding NotTopLevel Recursive) pairs ; addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) } where bndrs = map fst pairs (_, dups) = removeDups compare bndrs lintCoreExpr e@(App _ _) = addLoc (AnExpr e) $ do { fun_ty <- lintCoreFun fun (length args) ; lintCoreArgs fun_ty args } where (fun, args) = collectArgs e lintCoreExpr (Lam var expr) = addLoc (LambdaBodyOf var) $ markAllJoinsBad $ lintBinder LambdaBind var $ \ var' -> do { body_ty <- lintCoreExpr expr ; return $ mkLamType var' body_ty } lintCoreExpr e@(Case scrut var alt_ty alts) = -- Check the scrutinee do { let scrut_diverges = exprIsBottom scrut ; scrut_ty <- markAllJoinsBad $ lintCoreExpr scrut ; (alt_ty, _) <- lintInTy alt_ty ; (var_ty, _) <- lintInTy (idType var) -- We used to try to check whether a case expression with no -- alternatives was legitimate, but this didn't work. -- See Note [No alternatives lint check] for details. -- See Note [Rules for floating-point comparisons] in PrelRules ; let isLitPat (LitAlt _, _ , _) = True isLitPat _ = False ; checkL (not $ isFloatingTy scrut_ty && any isLitPat alts) (ptext (sLit $ "Lint warning: Scrutinising floating-point " ++ "expression with literal pattern in case " ++ "analysis (see Trac #9238).") $$ text "scrut" <+> ppr scrut) ; case tyConAppTyCon_maybe (idType var) of Just tycon | debugIsOn , isAlgTyCon tycon , not (isAbstractTyCon tycon) , null (tyConDataCons tycon) , not scrut_diverges -> pprTrace "Lint warning: case binder's type has no constructors" (ppr var <+> ppr (idType var)) -- This can legitimately happen for type families $ return () _otherwise -> return () -- Don't use lintIdBndr on var, because unboxed tuple is legitimate ; subst <- getTCvSubst ; ensureEqTys var_ty scrut_ty (mkScrutMsg var var_ty scrut_ty subst) ; lintIdBndr NotTopLevel CaseBind var $ \_ -> do { -- Check the alternatives mapM_ (lintCoreAlt scrut_ty alt_ty) alts ; checkCaseAlts e scrut_ty alts ; return alt_ty } } -- This case can't happen; linting types in expressions gets routed through -- lintCoreArgs lintCoreExpr (Type ty) = failWithL (text "Type found as expression" <+> ppr ty) lintCoreExpr (Coercion co) = do { (k1, k2, ty1, ty2, role) <- lintInCo co ; return (mkHeteroCoercionType role k1 k2 ty1 ty2) } ---------------------- lintVarOcc :: Var -> Int -- Number of arguments (type or value) being passed -> LintM Type -- returns type of the *variable* lintVarOcc var nargs = do { checkL (isNonCoVarId var) (text "Non term variable" <+> ppr var) -- Cneck that the type of the occurrence is the same -- as the type of the binding site ; ty <- applySubstTy (idType var) ; var' <- lookupIdInScope var ; let ty' = idType var' ; ensureEqTys ty ty' $ mkBndrOccTypeMismatchMsg var' var ty' ty -- Check for a nested occurrence of the StaticPtr constructor. -- See Note [Checking StaticPtrs]. ; lf <- getLintFlags ; when (nargs /= 0 && lf_check_static_ptrs lf /= AllowAnywhere) $ checkL (idName var /= makeStaticName) $ text "Found makeStatic nested in an expression" ; checkDeadIdOcc var ; checkJoinOcc var nargs ; return (idType var') } lintCoreFun :: CoreExpr -> Int -- Number of arguments (type or val) being passed -> LintM Type -- Returns type of the *function* lintCoreFun (Var var) nargs = lintVarOcc var nargs lintCoreFun (Lam var body) nargs -- Act like lintCoreExpr of Lam, but *don't* call markAllJoinsBad; see -- Note [Beta redexes] | nargs /= 0 = addLoc (LambdaBodyOf var) $ lintBinder LambdaBind var $ \ var' -> do { body_ty <- lintCoreFun body (nargs - 1) ; return $ mkLamType var' body_ty } lintCoreFun expr nargs = markAllJoinsBadIf (nargs /= 0) $ lintCoreExpr expr ------------------ checkDeadIdOcc :: Id -> LintM () -- Occurrences of an Id should never be dead.... -- except when we are checking a case pattern checkDeadIdOcc id | isDeadOcc (idOccInfo id) = do { in_case <- inCasePat ; checkL in_case (text "Occurrence of a dead Id" <+> ppr id) } | otherwise = return () ------------------ checkJoinOcc :: Id -> JoinArity -> LintM () -- Check that if the occurrence is a JoinId, then so is the -- binding site, and it's a valid join Id checkJoinOcc var n_args | Just join_arity_occ <- isJoinId_maybe var = do { mb_join_arity_bndr <- lookupJoinId var ; case mb_join_arity_bndr of { Nothing -> -- Binder is not a join point addErrL (invalidJoinOcc var) ; Just join_arity_bndr -> do { checkL (join_arity_bndr == join_arity_occ) $ -- Arity differs at binding site and occurrence mkJoinBndrOccMismatchMsg var join_arity_bndr join_arity_occ ; checkL (n_args == join_arity_occ) $ -- Arity doesn't match #args mkBadJumpMsg var join_arity_occ n_args } } } | otherwise = return () {- Note [No alternatives lint check] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Case expressions with no alternatives are odd beasts, and it would seem like they would worth be looking at in the linter (cf Trac #10180). We used to check two things: * exprIsHNF is false: it would *seem* to be terribly wrong if the scrutinee was already in head normal form. * exprIsBottom is true: we should be able to see why GHC believes the scrutinee is diverging for sure. It was already known that the second test was not entirely reliable. Unfortunately (Trac #13990), the first test turned out not to be reliable either. Getting the checks right turns out to be somewhat complicated. For example, suppose we have (comment 8) data T a where TInt :: T Int absurdTBool :: T Bool -> a absurdTBool v = case v of data Foo = Foo !(T Bool) absurdFoo :: Foo -> a absurdFoo (Foo x) = absurdTBool x GHC initially accepts the empty case because of the GADT conditions. But then we inline absurdTBool, getting absurdFoo (Foo x) = case x of x is in normal form (because the Foo constructor is strict) but the case is empty. To avoid this problem, GHC would have to recognize that matching on Foo x is already absurd, which is not so easy. More generally, we don't really know all the ways that GHC can lose track of why an expression is bottom, so we shouldn't make too much fuss when that happens. Note [Beta redexes] ~~~~~~~~~~~~~~~~~~~ Consider: join j @x y z = ... in (\@x y z -> jump j @x y z) @t e1 e2 This is clearly ill-typed, since the jump is inside both an application and a lambda, either of which is enough to disqualify it as a tail call (see Note [Invariants on join points] in CoreSyn). However, strictly from a lambda-calculus perspective, the term doesn't go wrong---after the two beta reductions, the jump *is* a tail call and everything is fine. Why would we want to allow this when we have let? One reason is that a compound beta redex (that is, one with more than one argument) has different scoping rules: naively reducing the above example using lets will capture any free occurrence of y in e2. More fundamentally, type lets are tricky; many passes, such as Float Out, tacitly assume that the incoming program's type lets have all been dealt with by the simplifier. Thus we don't want to let-bind any types in, say, CoreSubst.simpleOptPgm, which in some circumstances can run immediately before Float Out. All that said, currently CoreSubst.simpleOptPgm is the only thing using this loophole, doing so to avoid re-traversing large functions (beta-reducing a type lambda without introducing a type let requires a substitution). TODO: Improve simpleOptPgm so that we can forget all this ever happened. ************************************************************************ * * \subsection[lintCoreArgs]{lintCoreArgs} * * ************************************************************************ The basic version of these functions checks that the argument is a subtype of the required type, as one would expect. -} lintCoreArgs :: OutType -> [CoreArg] -> LintM OutType lintCoreArgs fun_ty args = foldM lintCoreArg fun_ty args lintCoreArg :: OutType -> CoreArg -> LintM OutType lintCoreArg fun_ty (Type arg_ty) = do { checkL (not (isCoercionTy arg_ty)) (text "Unnecessary coercion-to-type injection:" <+> ppr arg_ty) ; arg_ty' <- applySubstTy arg_ty ; lintTyApp fun_ty arg_ty' } lintCoreArg fun_ty arg = do { arg_ty <- markAllJoinsBad $ lintCoreExpr arg -- See Note [Levity polymorphism invariants] in CoreSyn ; lintL (not (isTypeLevPoly arg_ty)) (text "Levity-polymorphic argument:" <+> (ppr arg <+> dcolon <+> parens (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty)))) -- check for levity polymorphism first, because otherwise isUnliftedType panics ; checkL (not (isUnliftedType arg_ty) || exprOkForSpeculation arg) (mkLetAppMsg arg) ; lintValApp arg fun_ty arg_ty } ----------------- lintAltBinders :: OutType -- Scrutinee type -> OutType -- Constructor type -> [OutVar] -- Binders -> LintM () -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintAltBinders scrut_ty con_ty [] = ensureEqTys con_ty scrut_ty (mkBadPatMsg con_ty scrut_ty) lintAltBinders scrut_ty con_ty (bndr:bndrs) | isTyVar bndr = do { con_ty' <- lintTyApp con_ty (mkTyVarTy bndr) ; lintAltBinders scrut_ty con_ty' bndrs } | otherwise = do { con_ty' <- lintValApp (Var bndr) con_ty (idType bndr) ; lintAltBinders scrut_ty con_ty' bndrs } ----------------- lintTyApp :: OutType -> OutType -> LintM OutType lintTyApp fun_ty arg_ty | Just (tv,body_ty) <- splitForAllTy_maybe fun_ty = do { lintTyKind tv arg_ty ; in_scope <- getInScope -- substTy needs the set of tyvars in scope to avoid generating -- uniques that are already in scope. -- See Note [The substitution invariant] in TyCoRep ; return (substTyWithInScope in_scope [tv] [arg_ty] body_ty) } | otherwise = failWithL (mkTyAppMsg fun_ty arg_ty) ----------------- lintValApp :: CoreExpr -> OutType -> OutType -> LintM OutType lintValApp arg fun_ty arg_ty | Just (arg,res) <- splitFunTy_maybe fun_ty = do { ensureEqTys arg arg_ty err1 ; return res } | otherwise = failWithL err2 where err1 = mkAppMsg fun_ty arg_ty arg err2 = mkNonFunAppMsg fun_ty arg_ty arg lintTyKind :: OutTyVar -> OutType -> LintM () -- Both args have had substitution applied -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintTyKind tyvar arg_ty -- Arg type might be boxed for a function with an uncommitted -- tyvar; notably this is used so that we can give -- error :: forall a:*. String -> a -- and then apply it to both boxed and unboxed types. = do { arg_kind <- lintType arg_ty ; unless (arg_kind `eqType` tyvar_kind) (addErrL (mkKindErrMsg tyvar arg_ty $$ (text "Linted Arg kind:" <+> ppr arg_kind))) } where tyvar_kind = tyVarKind tyvar {- ************************************************************************ * * \subsection[lintCoreAlts]{lintCoreAlts} * * ************************************************************************ -} checkCaseAlts :: CoreExpr -> OutType -> [CoreAlt] -> LintM () -- a) Check that the alts are non-empty -- b1) Check that the DEFAULT comes first, if it exists -- b2) Check that the others are in increasing order -- c) Check that there's a default for infinite types -- NB: Algebraic cases are not necessarily exhaustive, because -- the simplifier correctly eliminates case that can't -- possibly match. checkCaseAlts e ty alts = do { checkL (all non_deflt con_alts) (mkNonDefltMsg e) ; checkL (increasing_tag con_alts) (mkNonIncreasingAltsMsg e) -- For types Int#, Word# with an infinite (well, large!) number of -- possible values, there should usually be a DEFAULT case -- But (see Note [Empty case alternatives] in CoreSyn) it's ok to -- have *no* case alternatives. -- In effect, this is a kind of partial test. I suppose it's possible -- that we might *know* that 'x' was 1 or 2, in which case -- case x of { 1 -> e1; 2 -> e2 } -- would be fine. ; checkL (isJust maybe_deflt || not is_infinite_ty || null alts) (nonExhaustiveAltsMsg e) } where (con_alts, maybe_deflt) = findDefault alts -- Check that successive alternatives have increasing tags increasing_tag (alt1 : rest@( alt2 : _)) = alt1 `ltAlt` alt2 && increasing_tag rest increasing_tag _ = True non_deflt (DEFAULT, _, _) = False non_deflt _ = True is_infinite_ty = case tyConAppTyCon_maybe ty of Nothing -> False Just tycon -> isPrimTyCon tycon lintAltExpr :: CoreExpr -> OutType -> LintM () lintAltExpr expr ann_ty = do { actual_ty <- lintCoreExpr expr ; ensureEqTys actual_ty ann_ty (mkCaseAltMsg expr actual_ty ann_ty) } lintCoreAlt :: OutType -- Type of scrutinee -> OutType -- Type of the alternative -> CoreAlt -> LintM () -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintCoreAlt _ alt_ty (DEFAULT, args, rhs) = do { lintL (null args) (mkDefaultArgsMsg args) ; lintAltExpr rhs alt_ty } lintCoreAlt scrut_ty alt_ty (LitAlt lit, args, rhs) | litIsLifted lit = failWithL integerScrutinisedMsg | otherwise = do { lintL (null args) (mkDefaultArgsMsg args) ; ensureEqTys lit_ty scrut_ty (mkBadPatMsg lit_ty scrut_ty) ; lintAltExpr rhs alt_ty } where lit_ty = literalType lit lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs) | isNewTyCon (dataConTyCon con) = addErrL (mkNewTyDataConAltMsg scrut_ty alt) | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty = addLoc (CaseAlt alt) $ do { -- First instantiate the universally quantified -- type variables of the data constructor -- We've already check lintL (tycon == dataConTyCon con) (mkBadConMsg tycon con) ; let con_payload_ty = piResultTys (dataConRepType con) tycon_arg_tys -- And now bring the new binders into scope ; lintBinders CasePatBind args $ \ args' -> do { addLoc (CasePat alt) (lintAltBinders scrut_ty con_payload_ty args') ; lintAltExpr rhs alt_ty } } | otherwise -- Scrut-ty is wrong shape = addErrL (mkBadAltMsg scrut_ty alt) {- ************************************************************************ * * \subsection[lint-types]{Types} * * ************************************************************************ -} -- When we lint binders, we (one at a time and in order): -- 1. Lint var types or kinds (possibly substituting) -- 2. Add the binder to the in scope set, and if its a coercion var, -- we may extend the substitution to reflect its (possibly) new kind lintBinders :: BindingSite -> [Var] -> ([Var] -> LintM a) -> LintM a lintBinders _ [] linterF = linterF [] lintBinders site (var:vars) linterF = lintBinder site var $ \var' -> lintBinders site vars $ \ vars' -> linterF (var':vars') -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintBinder :: BindingSite -> Var -> (Var -> LintM a) -> LintM a lintBinder site var linterF | isTyVar var = lintTyBndr var linterF | isCoVar var = lintCoBndr var linterF | otherwise = lintIdBndr NotTopLevel site var linterF lintTyBndr :: InTyVar -> (OutTyVar -> LintM a) -> LintM a lintTyBndr tv thing_inside = do { subst <- getTCvSubst ; let (subst', tv') = substTyVarBndr subst tv ; lintKind (varType tv') ; updateTCvSubst subst' (thing_inside tv') } lintCoBndr :: InCoVar -> (OutCoVar -> LintM a) -> LintM a lintCoBndr cv thing_inside = do { subst <- getTCvSubst ; let (subst', cv') = substCoVarBndr subst cv ; lintKind (varType cv') ; lintL (isCoercionType (varType cv')) (text "CoVar with non-coercion type:" <+> pprTyVar cv) ; updateTCvSubst subst' (thing_inside cv') } lintLetBndrs :: TopLevelFlag -> [Var] -> LintM a -> LintM a lintLetBndrs top_lvl ids linterF = go ids where go [] = linterF go (id:ids) = lintIdBndr top_lvl LetBind id $ \_ -> go ids lintIdBndr :: TopLevelFlag -> BindingSite -> InVar -> (OutVar -> LintM a) -> LintM a -- Do substitution on the type of a binder and add the var with this -- new type to the in-scope set of the second argument -- ToDo: lint its rules lintIdBndr top_lvl bind_site id linterF = ASSERT2( isId id, ppr id ) do { flags <- getLintFlags ; checkL (not (lf_check_global_ids flags) || isLocalId id) (text "Non-local Id binder" <+> ppr id) -- See Note [Checking for global Ids] -- Check that if the binder is nested, it is not marked as exported ; checkL (not (isExportedId id) || is_top_lvl) (mkNonTopExportedMsg id) -- Check that if the binder is nested, it does not have an external name ; checkL (not (isExternalName (Var.varName id)) || is_top_lvl) (mkNonTopExternalNameMsg id) ; (ty, k) <- lintInTy (idType id) -- See Note [Levity polymorphism invariants] in CoreSyn ; lintL (isJoinId id || not (isKindLevPoly k)) (text "Levity-polymorphic binder:" <+> (ppr id <+> dcolon <+> parens (ppr ty <+> dcolon <+> ppr k))) -- Check that a join-id is a not-top-level let-binding ; when (isJoinId id) $ checkL (not is_top_lvl && is_let_bind) $ mkBadJoinBindMsg id ; let id' = setIdType id ty ; addInScopeVar id' $ (linterF id') } where is_top_lvl = isTopLevel top_lvl is_let_bind = case bind_site of LetBind -> True _ -> False {- %************************************************************************ %* * Types %* * %************************************************************************ -} lintInTy :: InType -> LintM (LintedType, LintedKind) -- Types only, not kinds -- Check the type, and apply the substitution to it -- See Note [Linting type lets] lintInTy ty = addLoc (InType ty) $ do { ty' <- applySubstTy ty ; k <- lintType ty' ; lintKind k ; return (ty', k) } checkTyCon :: TyCon -> LintM () checkTyCon tc = checkL (not (isTcTyCon tc)) (text "Found TcTyCon:" <+> ppr tc) ------------------- lintType :: OutType -> LintM LintedKind -- The returned Kind has itself been linted -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintType (TyVarTy tv) = do { checkL (isTyVar tv) (mkBadTyVarMsg tv) ; lintTyCoVarInScope tv ; return (tyVarKind tv) } -- We checked its kind when we added it to the envt lintType ty@(AppTy t1 t2) | TyConApp {} <- t1 = failWithL $ text "TyConApp to the left of AppTy:" <+> ppr ty | otherwise = do { k1 <- lintType t1 ; k2 <- lintType t2 ; lint_ty_app ty k1 [(t2,k2)] } lintType ty@(TyConApp tc tys) | Just ty' <- coreView ty = lintType ty' -- Expand type synonyms, so that we do not bogusly complain -- about un-saturated type synonyms -- We should never see a saturated application of funTyCon; such applications -- should be represented with the FunTy constructor. See Note [Linting -- function types] and Note [Representation of function types]. | isFunTyCon tc , tys `lengthIs` 4 = failWithL (hang (text "Saturated application of (->)") 2 (ppr ty)) | isTypeSynonymTyCon tc || isTypeFamilyTyCon tc -- Also type synonyms and type families , tys `lengthLessThan` tyConArity tc = failWithL (hang (text "Un-saturated type application") 2 (ppr ty)) | otherwise = do { checkTyCon tc ; ks <- mapM lintType tys ; lint_ty_app ty (tyConKind tc) (tys `zip` ks) } -- arrows can related *unlifted* kinds, so this has to be separate from -- a dependent forall. lintType ty@(FunTy t1 t2) = do { k1 <- lintType t1 ; k2 <- lintType t2 ; lintArrow (text "type or kind" <+> quotes (ppr ty)) k1 k2 } lintType t@(ForAllTy (TvBndr tv _vis) ty) = do { lintL (isTyVar tv) (text "Covar bound in type:" <+> ppr t) ; lintTyBndr tv $ \tv' -> do { k <- lintType ty ; lintL (not (tv' `elemVarSet` tyCoVarsOfType k)) (text "Variable escape in forall:" <+> ppr t) ; lintL (classifiesTypeWithValues k) (text "Non-* and non-# kind in forall:" <+> ppr t) ; return k }} lintType ty@(LitTy l) = lintTyLit l >> return (typeKind ty) lintType (CastTy ty co) = do { k1 <- lintType ty ; (k1', k2) <- lintStarCoercion co ; ensureEqTys k1 k1' (mkCastErr ty co k1' k1) ; return k2 } lintType (CoercionTy co) = do { (k1, k2, ty1, ty2, r) <- lintCoercion co ; return $ mkHeteroCoercionType r k1 k2 ty1 ty2 } lintKind :: OutKind -> LintM () -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintKind k = do { sk <- lintType k ; unless (classifiesTypeWithValues sk) (addErrL (hang (text "Ill-kinded kind:" <+> ppr k) 2 (text "has kind:" <+> ppr sk))) } -- confirms that a type is really * lintStar :: SDoc -> OutKind -> LintM () lintStar doc k = lintL (classifiesTypeWithValues k) (text "Non-*-like kind when *-like expected:" <+> ppr k $$ text "when checking" <+> doc) lintArrow :: SDoc -> LintedKind -> LintedKind -> LintM LintedKind -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintArrow what k1 k2 -- Eg lintArrow "type or kind `blah'" k1 k2 -- or lintarrow "coercion `blah'" k1 k2 = do { unless (classifiesTypeWithValues k1) (addErrL (msg (text "argument") k1)) ; unless (classifiesTypeWithValues k2) (addErrL (msg (text "result") k2)) ; return liftedTypeKind } where msg ar k = vcat [ hang (text "Ill-kinded" <+> ar) 2 (text "in" <+> what) , what <+> text "kind:" <+> ppr k ] lint_ty_app :: Type -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind lint_ty_app ty k tys = lint_app (text "type" <+> quotes (ppr ty)) k tys ---------------- lint_co_app :: Coercion -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind lint_co_app ty k tys = lint_app (text "coercion" <+> quotes (ppr ty)) k tys ---------------- lintTyLit :: TyLit -> LintM () lintTyLit (NumTyLit n) | n >= 0 = return () | otherwise = failWithL msg where msg = text "Negative type literal:" <+> integer n lintTyLit (StrTyLit _) = return () lint_app :: SDoc -> LintedKind -> [(LintedType,LintedKind)] -> LintM Kind -- (lint_app d fun_kind arg_tys) -- We have an application (f arg_ty1 .. arg_tyn), -- where f :: fun_kind -- Takes care of linting the OutTypes -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lint_app doc kfn kas = do { in_scope <- getInScope -- We need the in_scope set to satisfy the invariant in -- Note [The substitution invariant] in TyCoRep ; foldlM (go_app in_scope) kfn kas } where fail_msg extra = vcat [ hang (text "Kind application error in") 2 doc , nest 2 (text "Function kind =" <+> ppr kfn) , nest 2 (text "Arg kinds =" <+> ppr kas) , extra ] go_app in_scope kfn tka | Just kfn' <- coreView kfn = go_app in_scope kfn' tka go_app _ (FunTy kfa kfb) tka@(_,ka) = do { unless (ka `eqType` kfa) $ addErrL (fail_msg (text "Fun:" <+> (ppr kfa $$ ppr tka))) ; return kfb } go_app in_scope (ForAllTy (TvBndr kv _vis) kfn) tka@(ta,ka) = do { let kv_kind = tyVarKind kv ; unless (ka `eqType` kv_kind) $ addErrL (fail_msg (text "Forall:" <+> (ppr kv $$ ppr kv_kind $$ ppr tka))) ; return (substTyWithInScope in_scope [kv] [ta] kfn) } go_app _ kfn ka = failWithL (fail_msg (text "Not a fun:" <+> (ppr kfn $$ ppr ka))) {- ********************************************************************* * * Linting rules * * ********************************************************************* -} lintCoreRule :: OutVar -> OutType -> CoreRule -> LintM () lintCoreRule _ _ (BuiltinRule {}) = return () -- Don't bother lintCoreRule fun fun_ty rule@(Rule { ru_name = name, ru_bndrs = bndrs , ru_args = args, ru_rhs = rhs }) = lintBinders LambdaBind bndrs $ \ _ -> do { lhs_ty <- foldM lintCoreArg fun_ty args ; rhs_ty <- case isJoinId_maybe fun of Just join_arity -> do { checkL (args `lengthIs` join_arity) $ mkBadJoinPointRuleMsg fun join_arity rule -- See Note [Rules for join points] ; lintCoreExpr rhs } _ -> markAllJoinsBad $ lintCoreExpr rhs ; ensureEqTys lhs_ty rhs_ty $ (rule_doc <+> vcat [ text "lhs type:" <+> ppr lhs_ty , text "rhs type:" <+> ppr rhs_ty ]) ; let bad_bndrs = filter is_bad_bndr bndrs ; checkL (null bad_bndrs) (rule_doc <+> text "unbound" <+> ppr bad_bndrs) -- See Note [Linting rules] } where rule_doc = text "Rule" <+> doubleQuotes (ftext name) <> colon lhs_fvs = exprsFreeVars args rhs_fvs = exprFreeVars rhs is_bad_bndr :: Var -> Bool -- See Note [Unbound RULE binders] in Rules is_bad_bndr bndr = not (bndr `elemVarSet` lhs_fvs) && bndr `elemVarSet` rhs_fvs && isNothing (isReflCoVar_maybe bndr) {- Note [Linting rules] ~~~~~~~~~~~~~~~~~~~~~~~ It's very bad if simplifying a rule means that one of the template variables (ru_bndrs) that /is/ mentioned on the RHS becomes not-mentioned in the LHS (ru_args). How can that happen? Well, in Trac #10602, SpecConstr stupidly constructed a rule like forall x,c1,c2. f (x |> c1 |> c2) = .... But simplExpr collapses those coercions into one. (Indeed in Trac #10602, it collapsed to the identity and was removed altogether.) We don't have a great story for what to do here, but at least this check will nail it. NB (Trac #11643): it's possible that a variable listed in the binders becomes not-mentioned on both LHS and RHS. Here's a silly example: RULE forall x y. f (g x y) = g (x+1) (y-1) And suppose worker/wrapper decides that 'x' is Absent. Then we'll end up with RULE forall x y. f ($gw y) = $gw (x+1) This seems sufficiently obscure that there isn't enough payoff to try to trim the forall'd binder list. Note [Rules for join points] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A join point cannot be partially applied. However, the left-hand side of a rule for a join point is effectively a *pattern*, not a piece of code, so there's an argument to be made for allowing a situation like this: join $sj :: Int -> Int -> String $sj n m = ... j :: forall a. Eq a => a -> a -> String {-# RULES "SPEC j" jump j @ Int $dEq = jump $sj #-} j @a $dEq x y = ... Applying this rule can't turn a well-typed program into an ill-typed one, so conceivably we could allow it. But we can always eta-expand such an "undersaturated" rule (see 'CoreArity.etaExpandToJoinPointRule'), and in fact the simplifier would have to in order to deal with the RHS. So we take a conservative view and don't allow undersaturated rules for join points. See Note [Rules and join points] in OccurAnal for further discussion. -} {- ************************************************************************ * * Linting coercions * * ************************************************************************ -} lintInCo :: InCoercion -> LintM (LintedKind, LintedKind, LintedType, LintedType, Role) -- Check the coercion, and apply the substitution to it -- See Note [Linting type lets] lintInCo co = addLoc (InCo co) $ do { co' <- applySubstCo co ; lintCoercion co' } -- lints a coercion, confirming that its lh kind and its rh kind are both * -- also ensures that the role is Nominal lintStarCoercion :: OutCoercion -> LintM (LintedType, LintedType) lintStarCoercion g = do { (k1, k2, t1, t2, r) <- lintCoercion g ; lintStar (text "the kind of the left type in" <+> ppr g) k1 ; lintStar (text "the kind of the right type in" <+> ppr g) k2 ; lintRole g Nominal r ; return (t1, t2) } lintCoercion :: OutCoercion -> LintM (LintedKind, LintedKind, LintedType, LintedType, Role) -- Check the kind of a coercion term, returning the kind -- Post-condition: the returned OutTypes are lint-free -- -- If lintCoercion co = (k1, k2, s1, s2, r) -- then co :: s1 ~r s2 -- s1 :: k2 -- s2 :: k2 -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintCoercion (Refl r ty) = do { k <- lintType ty ; return (k, k, ty, ty, r) } lintCoercion co@(TyConAppCo r tc cos) | tc `hasKey` funTyConKey , [_rep1,_rep2,_co1,_co2] <- cos = do { failWithL (text "Saturated TyConAppCo (->):" <+> ppr co) } -- All saturated TyConAppCos should be FunCos | Just {} <- synTyConDefn_maybe tc = failWithL (text "Synonym in TyConAppCo:" <+> ppr co) | otherwise = do { checkTyCon tc ; (k's, ks, ss, ts, rs) <- mapAndUnzip5M lintCoercion cos ; k' <- lint_co_app co (tyConKind tc) (ss `zip` k's) ; k <- lint_co_app co (tyConKind tc) (ts `zip` ks) ; _ <- zipWith3M lintRole cos (tyConRolesX r tc) rs ; return (k', k, mkTyConApp tc ss, mkTyConApp tc ts, r) } lintCoercion co@(AppCo co1 co2) | TyConAppCo {} <- co1 = failWithL (text "TyConAppCo to the left of AppCo:" <+> ppr co) | Refl _ (TyConApp {}) <- co1 = failWithL (text "Refl (TyConApp ...) to the left of AppCo:" <+> ppr co) | otherwise = do { (k1, k2, s1, s2, r1) <- lintCoercion co1 ; (k'1, k'2, t1, t2, r2) <- lintCoercion co2 ; k3 <- lint_co_app co k1 [(t1,k'1)] ; k4 <- lint_co_app co k2 [(t2,k'2)] ; if r1 == Phantom then lintL (r2 == Phantom || r2 == Nominal) (text "Second argument in AppCo cannot be R:" $$ ppr co) else lintRole co Nominal r2 ; return (k3, k4, mkAppTy s1 t1, mkAppTy s2 t2, r1) } ---------- lintCoercion (ForAllCo tv1 kind_co co) = do { (_, k2) <- lintStarCoercion kind_co ; let tv2 = setTyVarKind tv1 k2 ; addInScopeVar tv1 $ do { ; (k3, k4, t1, t2, r) <- lintCoercion co ; in_scope <- getInScope ; let tyl = mkInvForAllTy tv1 t1 subst = mkTvSubst in_scope $ -- We need both the free vars of the `t2` and the -- free vars of the range of the substitution in -- scope. All the free vars of `t2` and `kind_co` should -- already be in `in_scope`, because they've been -- linted and `tv2` has the same unique as `tv1`. -- See Note [The substitution invariant] unitVarEnv tv1 (TyVarTy tv2 `mkCastTy` mkSymCo kind_co) tyr = mkInvForAllTy tv2 $ substTy subst t2 ; return (k3, k4, tyl, tyr, r) } } lintCoercion co@(FunCo r co1 co2) = do { (k1,k'1,s1,t1,r1) <- lintCoercion co1 ; (k2,k'2,s2,t2,r2) <- lintCoercion co2 ; k <- lintArrow (text "coercion" <+> quotes (ppr co)) k1 k2 ; k' <- lintArrow (text "coercion" <+> quotes (ppr co)) k'1 k'2 ; lintRole co1 r r1 ; lintRole co2 r r2 ; return (k, k', mkFunTy s1 s2, mkFunTy t1 t2, r) } lintCoercion (CoVarCo cv) | not (isCoVar cv) = failWithL (hang (text "Bad CoVarCo:" <+> ppr cv) 2 (text "With offending type:" <+> ppr (varType cv))) | otherwise = do { lintTyCoVarInScope cv ; cv' <- lookupIdInScope cv ; lintUnliftedCoVar cv ; return $ coVarKindsTypesRole cv' } -- See Note [Bad unsafe coercion] lintCoercion co@(UnivCo prov r ty1 ty2) = do { k1 <- lintType ty1 ; k2 <- lintType ty2 ; case prov of UnsafeCoerceProv -> return () -- no extra checks PhantomProv kco -> do { lintRole co Phantom r ; check_kinds kco k1 k2 } ProofIrrelProv kco -> do { lintL (isCoercionTy ty1) $ mkBadProofIrrelMsg ty1 co ; lintL (isCoercionTy ty2) $ mkBadProofIrrelMsg ty2 co ; check_kinds kco k1 k2 } PluginProv _ -> return () -- no extra checks ; when (r /= Phantom && classifiesTypeWithValues k1 && classifiesTypeWithValues k2) (checkTypes ty1 ty2) ; return (k1, k2, ty1, ty2, r) } where report s = hang (text $ "Unsafe coercion: " ++ s) 2 (vcat [ text "From:" <+> ppr ty1 , text " To:" <+> ppr ty2]) isUnBoxed :: PrimRep -> Bool isUnBoxed = not . isGcPtrRep -- see #9122 for discussion of these checks checkTypes t1 t2 = do { checkWarnL (not lev_poly1) (report "left-hand type is levity-polymorphic") ; checkWarnL (not lev_poly2) (report "right-hand type is levity-polymorphic") ; when (not (lev_poly1 || lev_poly2)) $ do { checkWarnL (reps1 `equalLength` reps2) (report "between values with different # of reps") ; zipWithM_ validateCoercion reps1 reps2 }} where lev_poly1 = isTypeLevPoly t1 lev_poly2 = isTypeLevPoly t2 -- don't look at these unless lev_poly1/2 are False -- Otherwise, we get #13458 reps1 = typePrimRep t1 reps2 = typePrimRep t2 validateCoercion :: PrimRep -> PrimRep -> LintM () validateCoercion rep1 rep2 = do { dflags <- getDynFlags ; checkWarnL (isUnBoxed rep1 == isUnBoxed rep2) (report "between unboxed and boxed value") ; checkWarnL (TyCon.primRepSizeB dflags rep1 == TyCon.primRepSizeB dflags rep2) (report "between unboxed values of different size") ; let fl = liftM2 (==) (TyCon.primRepIsFloat rep1) (TyCon.primRepIsFloat rep2) ; case fl of Nothing -> addWarnL (report "between vector types") Just False -> addWarnL (report "between float and integral values") _ -> return () } check_kinds kco k1 k2 = do { (k1', k2') <- lintStarCoercion kco ; ensureEqTys k1 k1' (mkBadUnivCoMsg CLeft co) ; ensureEqTys k2 k2' (mkBadUnivCoMsg CRight co) } lintCoercion (SymCo co) = do { (k1, k2, ty1, ty2, r) <- lintCoercion co ; return (k2, k1, ty2, ty1, r) } lintCoercion co@(TransCo co1 co2) = do { (k1a, _k1b, ty1a, ty1b, r1) <- lintCoercion co1 ; (_k2a, k2b, ty2a, ty2b, r2) <- lintCoercion co2 ; ensureEqTys ty1b ty2a (hang (text "Trans coercion mis-match:" <+> ppr co) 2 (vcat [ppr ty1a, ppr ty1b, ppr ty2a, ppr ty2b])) ; lintRole co r1 r2 ; return (k1a, k2b, ty1a, ty2b, r1) } lintCoercion the_co@(NthCo n co) = do { (_, _, s, t, r) <- lintCoercion co ; case (splitForAllTy_maybe s, splitForAllTy_maybe t) of { (Just (tv_s, _ty_s), Just (tv_t, _ty_t)) | n == 0 -> return (ks, kt, ts, tt, Nominal) where ts = tyVarKind tv_s tt = tyVarKind tv_t ks = typeKind ts kt = typeKind tt ; _ -> case (splitTyConApp_maybe s, splitTyConApp_maybe t) of { (Just (tc_s, tys_s), Just (tc_t, tys_t)) | tc_s == tc_t , isInjectiveTyCon tc_s r -- see Note [NthCo and newtypes] in TyCoRep , tys_s `equalLength` tys_t , tys_s `lengthExceeds` n -> return (ks, kt, ts, tt, tr) where ts = getNth tys_s n tt = getNth tys_t n tr = nthRole r tc_s n ks = typeKind ts kt = typeKind tt ; _ -> failWithL (hang (text "Bad getNth:") 2 (ppr the_co $$ ppr s $$ ppr t)) }}} lintCoercion the_co@(LRCo lr co) = do { (_,_,s,t,r) <- lintCoercion co ; lintRole co Nominal r ; case (splitAppTy_maybe s, splitAppTy_maybe t) of (Just s_pr, Just t_pr) -> return (ks_pick, kt_pick, s_pick, t_pick, Nominal) where s_pick = pickLR lr s_pr t_pick = pickLR lr t_pr ks_pick = typeKind s_pick kt_pick = typeKind t_pick _ -> failWithL (hang (text "Bad LRCo:") 2 (ppr the_co $$ ppr s $$ ppr t)) } lintCoercion (InstCo co arg) = do { (k3, k4, t1',t2', r) <- lintCoercion co ; (k1',k2',s1,s2, r') <- lintCoercion arg ; lintRole arg Nominal r' ; in_scope <- getInScope ; case (splitForAllTy_maybe t1', splitForAllTy_maybe t2') of (Just (tv1,t1), Just (tv2,t2)) | k1' `eqType` tyVarKind tv1 , k2' `eqType` tyVarKind tv2 -> return (k3, k4, substTyWithInScope in_scope [tv1] [s1] t1, substTyWithInScope in_scope [tv2] [s2] t2, r) | otherwise -> failWithL (text "Kind mis-match in inst coercion") _ -> failWithL (text "Bad argument of inst") } lintCoercion co@(AxiomInstCo con ind cos) = do { unless (0 <= ind && ind < numBranches (coAxiomBranches con)) (bad_ax (text "index out of range")) ; let CoAxBranch { cab_tvs = ktvs , cab_cvs = cvs , cab_roles = roles , cab_lhs = lhs , cab_rhs = rhs } = coAxiomNthBranch con ind ; unless (cos `equalLength` (ktvs ++ cvs)) $ bad_ax (text "lengths") ; subst <- getTCvSubst ; let empty_subst = zapTCvSubst subst ; (subst_l, subst_r) <- foldlM check_ki (empty_subst, empty_subst) (zip3 (ktvs ++ cvs) roles cos) ; let lhs' = substTys subst_l lhs rhs' = substTy subst_r rhs ; case checkAxInstCo co of Just bad_branch -> bad_ax $ text "inconsistent with" <+> pprCoAxBranch con bad_branch Nothing -> return () ; let s2 = mkTyConApp (coAxiomTyCon con) lhs' ; return (typeKind s2, typeKind rhs', s2, rhs', coAxiomRole con) } where bad_ax what = addErrL (hang (text "Bad axiom application" <+> parens what) 2 (ppr co)) check_ki (subst_l, subst_r) (ktv, role, arg) = do { (k', k'', s', t', r) <- lintCoercion arg ; lintRole arg role r ; let ktv_kind_l = substTy subst_l (tyVarKind ktv) ktv_kind_r = substTy subst_r (tyVarKind ktv) ; unless (k' `eqType` ktv_kind_l) (bad_ax (text "check_ki1" <+> vcat [ ppr co, ppr k', ppr ktv, ppr ktv_kind_l ] )) ; unless (k'' `eqType` ktv_kind_r) (bad_ax (text "check_ki2" <+> vcat [ ppr co, ppr k'', ppr ktv, ppr ktv_kind_r ] )) ; return (extendTCvSubst subst_l ktv s', extendTCvSubst subst_r ktv t') } lintCoercion (CoherenceCo co1 co2) = do { (_, k2, t1, t2, r) <- lintCoercion co1 ; let lhsty = mkCastTy t1 co2 ; k1' <- lintType lhsty ; return (k1', k2, lhsty, t2, r) } lintCoercion (KindCo co) = do { (k1, k2, _, _, _) <- lintCoercion co ; return (liftedTypeKind, liftedTypeKind, k1, k2, Nominal) } lintCoercion (SubCo co') = do { (k1,k2,s,t,r) <- lintCoercion co' ; lintRole co' Nominal r ; return (k1,k2,s,t,Representational) } lintCoercion this@(AxiomRuleCo co cs) = do { eqs <- mapM lintCoercion cs ; lintRoles 0 (coaxrAsmpRoles co) eqs ; case coaxrProves co [ Pair l r | (_,_,l,r,_) <- eqs ] of Nothing -> err "Malformed use of AxiomRuleCo" [ ppr this ] Just (Pair l r) -> return (typeKind l, typeKind r, l, r, coaxrRole co) } where err m xs = failWithL $ hang (text m) 2 $ vcat (text "Rule:" <+> ppr (coaxrName co) : xs) lintRoles n (e : es) ((_,_,_,_,r) : rs) | e == r = lintRoles (n+1) es rs | otherwise = err "Argument roles mismatch" [ text "In argument:" <+> int (n+1) , text "Expected:" <+> ppr e , text "Found:" <+> ppr r ] lintRoles _ [] [] = return () lintRoles n [] rs = err "Too many coercion arguments" [ text "Expected:" <+> int n , text "Provided:" <+> int (n + length rs) ] lintRoles n es [] = err "Not enough coercion arguments" [ text "Expected:" <+> int (n + length es) , text "Provided:" <+> int n ] lintCoercion (HoleCo h) = do { addErrL $ text "Unfilled coercion hole:" <+> ppr h ; lintCoercion (CoVarCo (coHoleCoVar h)) } ---------- lintUnliftedCoVar :: CoVar -> LintM () lintUnliftedCoVar cv = when (not (isUnliftedType (coVarKind cv))) $ failWithL (text "Bad lifted equality:" <+> ppr cv <+> dcolon <+> ppr (coVarKind cv)) {- ************************************************************************ * * \subsection[lint-monad]{The Lint monad} * * ************************************************************************ -} -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] data LintEnv = LE { le_flags :: LintFlags -- Linting the result of this pass , le_loc :: [LintLocInfo] -- Locations , le_subst :: TCvSubst -- Current type substitution; we also use this -- to keep track of all the variables in scope, -- both Ids and TyVars , le_joins :: IdSet -- Join points in scope that are valid -- A subset of teh InScopeSet in le_subst -- See Note [Join points] , le_dynflags :: DynFlags -- DynamicFlags } data LintFlags = LF { lf_check_global_ids :: Bool -- See Note [Checking for global Ids] , lf_check_inline_loop_breakers :: Bool -- See Note [Checking for INLINE loop breakers] , lf_check_static_ptrs :: StaticPtrCheck -- ^ See Note [Checking StaticPtrs] } -- See Note [Checking StaticPtrs] data StaticPtrCheck = AllowAnywhere -- ^ Allow 'makeStatic' to occur anywhere. | AllowAtTopLevel -- ^ Allow 'makeStatic' calls at the top-level only. | RejectEverywhere -- ^ Reject any 'makeStatic' occurrence. deriving Eq defaultLintFlags :: LintFlags defaultLintFlags = LF { lf_check_global_ids = False , lf_check_inline_loop_breakers = True , lf_check_static_ptrs = AllowAnywhere } newtype LintM a = LintM { unLintM :: LintEnv -> WarnsAndErrs -> -- Error and warning messages so far (Maybe a, WarnsAndErrs) } -- Result and messages (if any) type WarnsAndErrs = (Bag MsgDoc, Bag MsgDoc) {- Note [Checking for global Ids] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before CoreTidy, all locally-bound Ids must be LocalIds, even top-level ones. See Note [Exported LocalIds] and Trac #9857. Note [Checking StaticPtrs] ~~~~~~~~~~~~~~~~~~~~~~~~~~ See Note [Grand plan for static forms] in StaticPtrTable for an overview. Every occurrence of the function 'makeStatic' should be moved to the top level by the FloatOut pass. It's vital that we don't have nested 'makeStatic' occurrences after CorePrep, because we populate the Static Pointer Table from the top-level bindings. See SimplCore Note [Grand plan for static forms]. The linter checks that no occurrence is left behind, nested within an expression. The check is enabled only after the FloatOut, CorePrep, and CoreTidy passes and only if the module uses the StaticPointers language extension. Checking more often doesn't help since the condition doesn't hold until after the first FloatOut pass. Note [Type substitution] ~~~~~~~~~~~~~~~~~~~~~~~~ Why do we need a type substitution? Consider /\(a:*). \(x:a). /\(a:*). id a x This is ill typed, because (renaming variables) it is really /\(a:*). \(x:a). /\(b:*). id b x Hence, when checking an application, we can't naively compare x's type (at its binding site) with its expected type (at a use site). So we rename type binders as we go, maintaining a substitution. The same substitution also supports let-type, current expressed as (/\(a:*). body) ty Here we substitute 'ty' for 'a' in 'body', on the fly. -} instance Functor LintM where fmap = liftM instance Applicative LintM where pure x = LintM $ \ _ errs -> (Just x, errs) (<*>) = ap instance Monad LintM where fail = MonadFail.fail m >>= k = LintM (\ env errs -> let (res, errs') = unLintM m env errs in case res of Just r -> unLintM (k r) env errs' Nothing -> (Nothing, errs')) instance MonadFail.MonadFail LintM where fail err = failWithL (text err) instance HasDynFlags LintM where getDynFlags = LintM (\ e errs -> (Just (le_dynflags e), errs)) data LintLocInfo = RhsOf Id -- The variable bound | LambdaBodyOf Id -- The lambda-binder | UnfoldingOf Id -- Unfolding of a binder | BodyOfLetRec [Id] -- One of the binders | CaseAlt CoreAlt -- Case alternative | CasePat CoreAlt -- The *pattern* of the case alternative | AnExpr CoreExpr -- Some expression | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which) | TopLevelBindings | InType Type -- Inside a type | InCo Coercion -- Inside a coercion initL :: DynFlags -> LintFlags -> InScopeSet -> LintM a -> WarnsAndErrs -- Errors and warnings initL dflags flags in_scope m = case unLintM m env (emptyBag, emptyBag) of (_, errs) -> errs where env = LE { le_flags = flags , le_subst = mkEmptyTCvSubst in_scope , le_joins = emptyVarSet , le_loc = [] , le_dynflags = dflags } getLintFlags :: LintM LintFlags getLintFlags = LintM $ \ env errs -> (Just (le_flags env), errs) checkL :: Bool -> MsgDoc -> LintM () checkL True _ = return () checkL False msg = failWithL msg -- like checkL, but relevant to type checking lintL :: Bool -> MsgDoc -> LintM () lintL = checkL checkWarnL :: Bool -> MsgDoc -> LintM () checkWarnL True _ = return () checkWarnL False msg = addWarnL msg failWithL :: MsgDoc -> LintM a failWithL msg = LintM $ \ env (warns,errs) -> (Nothing, (warns, addMsg env errs msg)) addErrL :: MsgDoc -> LintM () addErrL msg = LintM $ \ env (warns,errs) -> (Just (), (warns, addMsg env errs msg)) addWarnL :: MsgDoc -> LintM () addWarnL msg = LintM $ \ env (warns,errs) -> (Just (), (addMsg env warns msg, errs)) addMsg :: LintEnv -> Bag MsgDoc -> MsgDoc -> Bag MsgDoc addMsg env msgs msg = ASSERT( notNull locs ) msgs `snocBag` mk_msg msg where locs = le_loc env (loc, cxt1) = dumpLoc (head locs) cxts = [snd (dumpLoc loc) | loc <- locs] context = ifPprDebug (vcat (reverse cxts) $$ cxt1 $$ text "Substitution:" <+> ppr (le_subst env)) cxt1 mk_msg msg = mkLocMessage SevWarning (mkSrcSpan loc loc) (context $$ msg) addLoc :: LintLocInfo -> LintM a -> LintM a addLoc extra_loc m = LintM $ \ env errs -> unLintM m (env { le_loc = extra_loc : le_loc env }) errs inCasePat :: LintM Bool -- A slight hack; see the unique call site inCasePat = LintM $ \ env errs -> (Just (is_case_pat env), errs) where is_case_pat (LE { le_loc = CasePat {} : _ }) = True is_case_pat _other = False addInScopeVar :: Var -> LintM a -> LintM a addInScopeVar var m = LintM $ \ env errs -> unLintM m (env { le_subst = extendTCvInScope (le_subst env) var , le_joins = delVarSet (le_joins env) var }) errs extendSubstL :: TyVar -> Type -> LintM a -> LintM a extendSubstL tv ty m = LintM $ \ env errs -> unLintM m (env { le_subst = Type.extendTvSubst (le_subst env) tv ty }) errs updateTCvSubst :: TCvSubst -> LintM a -> LintM a updateTCvSubst subst' m = LintM $ \ env errs -> unLintM m (env { le_subst = subst' }) errs markAllJoinsBad :: LintM a -> LintM a markAllJoinsBad m = LintM $ \ env errs -> unLintM m (env { le_joins = emptyVarSet }) errs markAllJoinsBadIf :: Bool -> LintM a -> LintM a markAllJoinsBadIf True m = markAllJoinsBad m markAllJoinsBadIf False m = m addGoodJoins :: [Var] -> LintM a -> LintM a addGoodJoins vars thing_inside | null join_ids = thing_inside | otherwise = LintM $ \ env errs -> unLintM thing_inside (add_joins env) errs where add_joins env = env { le_joins = le_joins env `extendVarSetList` join_ids } join_ids = filter isJoinId vars getValidJoins :: LintM IdSet getValidJoins = LintM (\ env errs -> (Just (le_joins env), errs)) getTCvSubst :: LintM TCvSubst getTCvSubst = LintM (\ env errs -> (Just (le_subst env), errs)) getInScope :: LintM InScopeSet getInScope = LintM (\ env errs -> (Just (getTCvInScope $ le_subst env), errs)) applySubstTy :: InType -> LintM OutType applySubstTy ty = do { subst <- getTCvSubst; return (substTy subst ty) } applySubstCo :: InCoercion -> LintM OutCoercion applySubstCo co = do { subst <- getTCvSubst; return (substCo subst co) } lookupIdInScope :: Id -> LintM Id lookupIdInScope id | not (mustHaveLocalBinding id) = return id -- An imported Id | otherwise = do { subst <- getTCvSubst ; case lookupInScope (getTCvInScope subst) id of Just v -> return v Nothing -> do { addErrL out_of_scope ; return id } } where out_of_scope = pprBndr LetBind id <+> text "is out of scope" lookupJoinId :: Id -> LintM (Maybe JoinArity) -- Look up an Id which should be a join point, valid here -- If so, return its arity, if not return Nothing lookupJoinId id = do { join_set <- getValidJoins ; case lookupVarSet join_set id of Just id' -> return (isJoinId_maybe id') Nothing -> return Nothing } lintTyCoVarInScope :: Var -> LintM () lintTyCoVarInScope v = lintInScope (text "is out of scope") v lintInScope :: SDoc -> Var -> LintM () lintInScope loc_msg var = do { subst <- getTCvSubst ; lintL (not (mustHaveLocalBinding var) || (var `isInScope` subst)) (hsep [pprBndr LetBind var, loc_msg]) } ensureEqTys :: OutType -> OutType -> MsgDoc -> LintM () -- check ty2 is subtype of ty1 (ie, has same structure but usage -- annotations need only be consistent, not equal) -- Assumes ty1,ty2 are have already had the substitution applied ensureEqTys ty1 ty2 msg = lintL (ty1 `eqType` ty2) msg lintRole :: Outputable thing => thing -- where the role appeared -> Role -- expected -> Role -- actual -> LintM () lintRole co r1 r2 = lintL (r1 == r2) (text "Role incompatibility: expected" <+> ppr r1 <> comma <+> text "got" <+> ppr r2 $$ text "in" <+> ppr co) {- ************************************************************************ * * \subsection{Error messages} * * ************************************************************************ -} dumpLoc :: LintLocInfo -> (SrcLoc, SDoc) dumpLoc (RhsOf v) = (getSrcLoc v, brackets (text "RHS of" <+> pp_binders [v])) dumpLoc (LambdaBodyOf b) = (getSrcLoc b, brackets (text "in body of lambda with binder" <+> pp_binder b)) dumpLoc (UnfoldingOf b) = (getSrcLoc b, brackets (text "in the unfolding of" <+> pp_binder b)) dumpLoc (BodyOfLetRec []) = (noSrcLoc, brackets (text "In body of a letrec with no binders")) dumpLoc (BodyOfLetRec bs@(_:_)) = ( getSrcLoc (head bs), brackets (text "in body of letrec with binders" <+> pp_binders bs)) dumpLoc (AnExpr e) = (noSrcLoc, text "In the expression:" <+> ppr e) dumpLoc (CaseAlt (con, args, _)) = (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> pp_binders args)) dumpLoc (CasePat (con, args, _)) = (noSrcLoc, text "In the pattern of a case alternative:" <+> parens (ppr con <+> pp_binders args)) dumpLoc (ImportedUnfolding locn) = (locn, brackets (text "in an imported unfolding")) dumpLoc TopLevelBindings = (noSrcLoc, Outputable.empty) dumpLoc (InType ty) = (noSrcLoc, text "In the type" <+> quotes (ppr ty)) dumpLoc (InCo co) = (noSrcLoc, text "In the coercion" <+> quotes (ppr co)) pp_binders :: [Var] -> SDoc pp_binders bs = sep (punctuate comma (map pp_binder bs)) pp_binder :: Var -> SDoc pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)] | otherwise = hsep [ppr b, dcolon, ppr (tyVarKind b)] ------------------------------------------------------ -- Messages for case expressions mkDefaultArgsMsg :: [Var] -> MsgDoc mkDefaultArgsMsg args = hang (text "DEFAULT case with binders") 4 (ppr args) mkCaseAltMsg :: CoreExpr -> Type -> Type -> MsgDoc mkCaseAltMsg e ty1 ty2 = hang (text "Type of case alternatives not the same as the annotation on case:") 4 (vcat [ text "Actual type:" <+> ppr ty1, text "Annotation on case:" <+> ppr ty2, text "Alt Rhs:" <+> ppr e ]) mkScrutMsg :: Id -> Type -> Type -> TCvSubst -> MsgDoc mkScrutMsg var var_ty scrut_ty subst = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var, text "Result binder type:" <+> ppr var_ty,--(idType var), text "Scrutinee type:" <+> ppr scrut_ty, hsep [text "Current TCv subst", ppr subst]] mkNonDefltMsg, mkNonIncreasingAltsMsg :: CoreExpr -> MsgDoc mkNonDefltMsg e = hang (text "Case expression with DEFAULT not at the beginning") 4 (ppr e) mkNonIncreasingAltsMsg e = hang (text "Case expression with badly-ordered alternatives") 4 (ppr e) nonExhaustiveAltsMsg :: CoreExpr -> MsgDoc nonExhaustiveAltsMsg e = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e) mkBadConMsg :: TyCon -> DataCon -> MsgDoc mkBadConMsg tycon datacon = vcat [ text "In a case alternative, data constructor isn't in scrutinee type:", text "Scrutinee type constructor:" <+> ppr tycon, text "Data con:" <+> ppr datacon ] mkBadPatMsg :: Type -> Type -> MsgDoc mkBadPatMsg con_result_ty scrut_ty = vcat [ text "In a case alternative, pattern result type doesn't match scrutinee type:", text "Pattern result type:" <+> ppr con_result_ty, text "Scrutinee type:" <+> ppr scrut_ty ] integerScrutinisedMsg :: MsgDoc integerScrutinisedMsg = text "In a LitAlt, the literal is lifted (probably Integer)" mkBadAltMsg :: Type -> CoreAlt -> MsgDoc mkBadAltMsg scrut_ty alt = vcat [ text "Data alternative when scrutinee is not a tycon application", text "Scrutinee type:" <+> ppr scrut_ty, text "Alternative:" <+> pprCoreAlt alt ] mkNewTyDataConAltMsg :: Type -> CoreAlt -> MsgDoc mkNewTyDataConAltMsg scrut_ty alt = vcat [ text "Data alternative for newtype datacon", text "Scrutinee type:" <+> ppr scrut_ty, text "Alternative:" <+> pprCoreAlt alt ] ------------------------------------------------------ -- Other error messages mkAppMsg :: Type -> Type -> CoreExpr -> MsgDoc mkAppMsg fun_ty arg_ty arg = vcat [text "Argument value doesn't match argument type:", hang (text "Fun type:") 4 (ppr fun_ty), hang (text "Arg type:") 4 (ppr arg_ty), hang (text "Arg:") 4 (ppr arg)] mkNonFunAppMsg :: Type -> Type -> CoreExpr -> MsgDoc mkNonFunAppMsg fun_ty arg_ty arg = vcat [text "Non-function type in function position", hang (text "Fun type:") 4 (ppr fun_ty), hang (text "Arg type:") 4 (ppr arg_ty), hang (text "Arg:") 4 (ppr arg)] mkLetErr :: TyVar -> CoreExpr -> MsgDoc mkLetErr bndr rhs = vcat [text "Bad `let' binding:", hang (text "Variable:") 4 (ppr bndr <+> dcolon <+> ppr (varType bndr)), hang (text "Rhs:") 4 (ppr rhs)] mkTyAppMsg :: Type -> Type -> MsgDoc mkTyAppMsg ty arg_ty = vcat [text "Illegal type application:", hang (text "Exp type:") 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)), hang (text "Arg type:") 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))] emptyRec :: CoreExpr -> MsgDoc emptyRec e = hang (text "Empty Rec binding:") 2 (ppr e) mkRhsMsg :: Id -> SDoc -> Type -> MsgDoc mkRhsMsg binder what ty = vcat [hsep [text "The type of this binder doesn't match the type of its" <+> what <> colon, ppr binder], hsep [text "Binder's type:", ppr (idType binder)], hsep [text "Rhs type:", ppr ty]] mkLetAppMsg :: CoreExpr -> MsgDoc mkLetAppMsg e = hang (text "This argument does not satisfy the let/app invariant:") 2 (ppr e) badBndrTyMsg :: Id -> SDoc -> MsgDoc badBndrTyMsg binder what = vcat [ text "The type of this binder is" <+> what <> colon <+> ppr binder , text "Binder's type:" <+> ppr (idType binder) ] mkStrictMsg :: Id -> MsgDoc mkStrictMsg binder = vcat [hsep [text "Recursive or top-level binder has strict demand info:", ppr binder], hsep [text "Binder's demand info:", ppr (idDemandInfo binder)] ] mkNonTopExportedMsg :: Id -> MsgDoc mkNonTopExportedMsg binder = hsep [text "Non-top-level binder is marked as exported:", ppr binder] mkNonTopExternalNameMsg :: Id -> MsgDoc mkNonTopExternalNameMsg binder = hsep [text "Non-top-level binder has an external name:", ppr binder] mkTopNonLitStrMsg :: Id -> MsgDoc mkTopNonLitStrMsg binder = hsep [text "Top-level Addr# binder has a non-literal rhs:", ppr binder] mkKindErrMsg :: TyVar -> Type -> MsgDoc mkKindErrMsg tyvar arg_ty = vcat [text "Kinds don't match in type application:", hang (text "Type variable:") 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)), hang (text "Arg type:") 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))] {- Not needed now mkArityMsg :: Id -> MsgDoc mkArityMsg binder = vcat [hsep [text "Demand type has", ppr (dmdTypeDepth dmd_ty), text "arguments, rhs has", ppr (idArity binder), text "arguments,", ppr binder], hsep [text "Binder's strictness signature:", ppr dmd_ty] ] where (StrictSig dmd_ty) = idStrictness binder -} mkCastErr :: Outputable casted => casted -> Coercion -> Type -> Type -> MsgDoc mkCastErr expr co from_ty expr_ty = vcat [text "From-type of Cast differs from type of enclosed expression", text "From-type:" <+> ppr from_ty, text "Type of enclosed expr:" <+> ppr expr_ty, text "Actual enclosed expr:" <+> ppr expr, text "Coercion used in cast:" <+> ppr co ] mkBadUnivCoMsg :: LeftOrRight -> Coercion -> SDoc mkBadUnivCoMsg lr co = text "Kind mismatch on the" <+> pprLeftOrRight lr <+> text "side of a UnivCo:" <+> ppr co mkBadProofIrrelMsg :: Type -> Coercion -> SDoc mkBadProofIrrelMsg ty co = hang (text "Found a non-coercion in a proof-irrelevance UnivCo:") 2 (vcat [ text "type:" <+> ppr ty , text "co:" <+> ppr co ]) mkBadTyVarMsg :: Var -> SDoc mkBadTyVarMsg tv = text "Non-tyvar used in TyVarTy:" <+> ppr tv <+> dcolon <+> ppr (varType tv) mkBadJoinBindMsg :: Var -> SDoc mkBadJoinBindMsg var = vcat [ text "Bad join point binding:" <+> ppr var , text "Join points can be bound only by a non-top-level let" ] mkInvalidJoinPointMsg :: Var -> Type -> SDoc mkInvalidJoinPointMsg var ty = hang (text "Join point has invalid type:") 2 (ppr var <+> dcolon <+> ppr ty) mkBadJoinArityMsg :: Var -> Int -> Int -> CoreExpr -> SDoc mkBadJoinArityMsg var ar nlams rhs = vcat [ text "Join point has too few lambdas", text "Join var:" <+> ppr var, text "Join arity:" <+> ppr ar, text "Number of lambdas:" <+> ppr nlams, text "Rhs = " <+> ppr rhs ] invalidJoinOcc :: Var -> SDoc invalidJoinOcc var = vcat [ text "Invalid occurrence of a join variable:" <+> ppr var , text "The binder is either not a join point, or not valid here" ] mkBadJumpMsg :: Var -> Int -> Int -> SDoc mkBadJumpMsg var ar nargs = vcat [ text "Join point invoked with wrong number of arguments", text "Join var:" <+> ppr var, text "Join arity:" <+> ppr ar, text "Number of arguments:" <+> int nargs ] mkInconsistentRecMsg :: [Var] -> SDoc mkInconsistentRecMsg bndrs = vcat [ text "Recursive let binders mix values and join points", text "Binders:" <+> hsep (map ppr_with_details bndrs) ] where ppr_with_details bndr = ppr bndr <> ppr (idDetails bndr) mkJoinBndrOccMismatchMsg :: Var -> JoinArity -> JoinArity -> SDoc mkJoinBndrOccMismatchMsg bndr join_arity_bndr join_arity_occ = vcat [ text "Mismatch in join point arity between binder and occurrence" , text "Var:" <+> ppr bndr , text "Arity at binding site:" <+> ppr join_arity_bndr , text "Arity at occurrence: " <+> ppr join_arity_occ ] mkBndrOccTypeMismatchMsg :: Var -> Var -> OutType -> OutType -> SDoc mkBndrOccTypeMismatchMsg bndr var bndr_ty var_ty = vcat [ text "Mismatch in type between binder and occurrence" , text "Var:" <+> ppr bndr , text "Binder type:" <+> ppr bndr_ty , text "Occurrence type:" <+> ppr var_ty , text " Before subst:" <+> ppr (idType var) ] mkBadJoinPointRuleMsg :: JoinId -> JoinArity -> CoreRule -> SDoc mkBadJoinPointRuleMsg bndr join_arity rule = vcat [ text "Join point has rule with wrong number of arguments" , text "Var:" <+> ppr bndr , text "Join arity:" <+> ppr join_arity , text "Rule:" <+> ppr rule ] pprLeftOrRight :: LeftOrRight -> MsgDoc pprLeftOrRight CLeft = text "left" pprLeftOrRight CRight = text "right" dupVars :: [NonEmpty Var] -> MsgDoc dupVars vars = hang (text "Duplicate variables brought into scope") 2 (ppr (map toList vars)) dupExtVars :: [NonEmpty Name] -> MsgDoc dupExtVars vars = hang (text "Duplicate top-level variables with the same qualified name") 2 (ppr (map toList vars)) {- ************************************************************************ * * \subsection{Annotation Linting} * * ************************************************************************ -} -- | This checks whether a pass correctly looks through debug -- annotations (@SourceNote@). This works a bit different from other -- consistency checks: We check this by running the given task twice, -- noting all differences between the results. lintAnnots :: SDoc -> (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts lintAnnots pname pass guts = do -- Run the pass as we normally would dflags <- getDynFlags when (gopt Opt_DoAnnotationLinting dflags) $ liftIO $ Err.showPass dflags "Annotation linting - first run" nguts <- pass guts -- If appropriate re-run it without debug annotations to make sure -- that they made no difference. when (gopt Opt_DoAnnotationLinting dflags) $ do liftIO $ Err.showPass dflags "Annotation linting - second run" nguts' <- withoutAnnots pass guts -- Finally compare the resulting bindings liftIO $ Err.showPass dflags "Annotation linting - comparison" let binds = flattenBinds $ mg_binds nguts binds' = flattenBinds $ mg_binds nguts' (diffs,_) = diffBinds True (mkRnEnv2 emptyInScopeSet) binds binds' when (not (null diffs)) $ CoreMonad.putMsg $ vcat [ lint_banner "warning" pname , text "Core changes with annotations:" , withPprStyle (defaultDumpStyle dflags) $ nest 2 $ vcat diffs ] -- Return actual new guts return nguts -- | Run the given pass without annotations. This means that we both -- set the debugLevel setting to 0 in the environment as well as all -- annotations from incoming modules. withoutAnnots :: (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts withoutAnnots pass guts = do -- Remove debug flag from environment. dflags <- getDynFlags let removeFlag env = env{ hsc_dflags = dflags{ debugLevel = 0} } withoutFlag corem = liftIO =<< runCoreM <$> fmap removeFlag getHscEnv <*> getRuleBase <*> getUniqueSupplyM <*> getModule <*> getVisibleOrphanMods <*> getPrintUnqualified <*> getSrcSpanM <*> pure corem -- Nuke existing ticks in module. -- TODO: Ticks in unfoldings. Maybe change unfolding so it removes -- them in absence of debugLevel > 0. let nukeTicks = stripTicksE (not . tickishIsCode) nukeAnnotsBind :: CoreBind -> CoreBind nukeAnnotsBind bind = case bind of Rec bs -> Rec $ map (\(b,e) -> (b, nukeTicks e)) bs NonRec b e -> NonRec b $ nukeTicks e nukeAnnotsMod mg@ModGuts{mg_binds=binds} = mg{mg_binds = map nukeAnnotsBind binds} -- Perform pass with all changes applied fmap fst $ withoutFlag $ pass (nukeAnnotsMod guts)
shlevy/ghc
compiler/coreSyn/CoreLint.hs
bsd-3-clause
100,043
361
21
28,972
19,709
10,343
9,366
-1
-1
{-| Module : Werewolf.Slack.Slack Copyright : (c) Henry J. Wylde, 2016 License : BSD3 Maintainer : [email protected] -} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module Werewolf.Slack.Slack ( -- * Slack notify, ) where import Control.Monad.Extra import Control.Monad.Reader import Control.Monad.State import Data.Aeson import Network.HTTP.Client import Network.HTTP.Types.Method import Werewolf.Slack.Options notify :: (MonadIO m, MonadReader Options m, MonadState Manager m) => Maybe String -> String -> m () notify mTo message = do manager <- get initialRequest <- asks optWebhookUrl >>= liftIO . parseRequest let request = initialRequest { method = methodPost, requestBody = body } whenM (asks optDebug) $ liftIO (print request) response <- liftIO $ httpLbs request manager whenM (asks optDebug) $ liftIO (print response) where body = RequestBodyLBS $ encode payload payload = object [ "channel" .= mTo , "text" .= message ]
hjwylde/werewolf-slack
app/Werewolf/Slack/Slack.hs
bsd-3-clause
1,124
0
11
268
266
142
124
24
1
module MidiRhythm.Midi ( toPresses, ) where import MidiRhythm.NotePress import qualified Sound.MIDI.File as MidiFile import qualified Sound.MIDI.Message.Channel as Channel import qualified Sound.MIDI.Message.Channel.Voice as Voice import qualified Sound.MIDI.File.Event as Event import Data.Foldable as Foldable import Control.Arrow import qualified Data.EventList.Relative.TimeBody as RelEvList import Data.EventList.Absolute.TimeBody import GHC.Exts import qualified Numeric.NonNegative.Wrapper as NonNeg data NoteEvent = NoteOff Pitch | NoteOn Pitch Velocity deriving Show pitch :: NoteEvent -> Pitch pitch (NoteOn p _) = p pitch (NoteOff p) = p eventToMaybeNoteEvent :: Event.T -> Maybe NoteEvent eventToMaybeNoteEvent ev = do (_, voiceEvent) <- Event.maybeVoice ev voiceEventToMaybeNoteEvent voiceEvent voiceEventToMaybeNoteEvent :: Voice.T -> Maybe NoteEvent voiceEventToMaybeNoteEvent (Voice.NoteOn p v) = Just (NoteOn (ourPitch p) (ourVelocity v)) voiceEventToMaybeNoteEvent (Voice.NoteOff p v) = Just (NoteOff (ourPitch p)) voiceEventToMaybeNoteEvent _ = Nothing ourPitch = Pitch . NonNeg.fromNumberUnsafe . Voice.fromPitch ourVelocity = Velocity . NonNeg.fromNumberUnsafe . Voice.fromVelocity type Hit = (ElapsedTime, Velocity) type PressesState = ([Press], Maybe Hit) type TimedNoteEvent = (ElapsedTime, NoteEvent) addPressOrSkip :: PressesState -> TimedNoteEvent -> PressesState addPressOrSkip state@(_, Just _) (t, NoteOn _ _) = state addPressOrSkip state@(_, Nothing) (t, NoteOff _) = state addPressOrSkip (presses, Just (prevT, vel)) (t, NoteOff _) = (Press prevT vel (t - prevT) : presses, Nothing) addPressOrSkip (presses, Nothing) (t, NoteOn _ vel) = (presses, Just (t, vel)) noteEventsToPresses :: [TimedNoteEvent] -> [Press] noteEventsToPresses = fst . foldl addPressOrSkip ([], Nothing) sliceByPitches = slice pitch . mapMaybe eventToMaybeNoteEvent . RelEvList.toAbsoluteEventList 0 pitchAndPressesToNotePresses (pitch, presses) = map (\(Press t vel dur) -> NotePress t vel dur pitch) presses toPresses :: MidiFile.Track -> [NotePress] toPresses = sortWith notePressTime . foldMap (pitchAndPressesToNotePresses . second ( noteEventsToPresses . map (first ElapsedTime) . toPairList)) . sliceByPitches
a10nik/midiRhythm
src/MidiRhythm/Midi.hs
bsd-3-clause
2,395
0
16
444
720
404
316
53
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Typechecking class declarations -} {-# LANGUAGE CPP #-} module TcClassDcl ( tcClassSigs, tcClassDecl2, findMethodBind, instantiateMethod, tcClassMinimalDef, HsSigFun, mkHsSigFun, lookupHsSig, emptyHsSigs, tcMkDeclCtxt, tcAddDeclCtxt, badMethodErr ) where #include "HsVersions.h" import HsSyn import TcEnv import TcPat( addInlinePrags ) import TcEvidence( idHsWrapper ) import TcBinds import TcUnify import TcHsType import TcMType import Type ( getClassPredTys_maybe ) import TcType import TcRnMonad import BuildTyCl( TcMethInfo ) import Class import Id import Name import NameEnv import NameSet import Var import Outputable import SrcLoc import Maybes import BasicTypes import Bag import FastString import BooleanFormula import Util import Control.Monad {- Dictionary handling ~~~~~~~~~~~~~~~~~~~ Every class implicitly declares a new data type, corresponding to dictionaries of that class. So, for example: class (D a) => C a where op1 :: a -> a op2 :: forall b. Ord b => a -> b -> b would implicitly declare data CDict a = CDict (D a) (a -> a) (forall b. Ord b => a -> b -> b) (We could use a record decl, but that means changing more of the existing apparatus. One step at at time!) For classes with just one superclass+method, we use a newtype decl instead: class C a where op :: forallb. a -> b -> b generates newtype CDict a = CDict (forall b. a -> b -> b) Now DictTy in Type is just a form of type synomym: DictTy c t = TyConTy CDict `AppTy` t Death to "ExpandingDicts". ************************************************************************ * * Type-checking the class op signatures * * ************************************************************************ -} tcClassSigs :: Name -- Name of the class -> [LSig Name] -> LHsBinds Name -> TcM ([TcMethInfo], -- Exactly one for each method NameEnv Type) -- Types of the generic-default methods tcClassSigs clas sigs def_methods = do { traceTc "tcClassSigs 1" (ppr clas) ; gen_dm_prs <- concat <$> mapM (addLocM tc_gen_sig) gen_sigs ; let gen_dm_env = mkNameEnv gen_dm_prs ; op_info <- concat <$> mapM (addLocM (tc_sig gen_dm_env)) vanilla_sigs ; let op_names = mkNameSet [ n | (n,_,_) <- op_info ] ; sequence_ [ failWithTc (badMethodErr clas n) | n <- dm_bind_names, not (n `elemNameSet` op_names) ] -- Value binding for non class-method (ie no TypeSig) ; sequence_ [ failWithTc (badGenericMethod clas n) | (n,_) <- gen_dm_prs, not (n `elem` dm_bind_names) ] -- Generic signature without value binding ; traceTc "tcClassSigs 2" (ppr clas) ; return (op_info, gen_dm_env) } where vanilla_sigs = [L loc (nm,ty) | L loc (TypeSig nm ty _) <- sigs] gen_sigs = [L loc (nm,ty) | L loc (GenericSig nm ty) <- sigs] dm_bind_names :: [Name] -- These ones have a value binding in the class decl dm_bind_names = [op | L _ (FunBind {fun_id = L _ op}) <- bagToList def_methods] tc_sig genop_env (op_names, op_hs_ty) = do { traceTc "ClsSig 1" (ppr op_names) ; op_ty <- tcClassSigType op_hs_ty -- Class tyvars already in scope ; traceTc "ClsSig 2" (ppr op_names) ; return [ (op_name, f op_name, op_ty) | L _ op_name <- op_names ] } where f nm | nm `elemNameEnv` genop_env = GenericDM | nm `elem` dm_bind_names = VanillaDM | otherwise = NoDM tc_gen_sig (op_names, gen_hs_ty) = do { gen_op_ty <- tcClassSigType gen_hs_ty ; return [ (op_name, gen_op_ty) | L _ op_name <- op_names ] } {- ************************************************************************ * * Class Declarations * * ************************************************************************ -} tcClassDecl2 :: LTyClDecl Name -- The class declaration -> TcM (LHsBinds Id) tcClassDecl2 (L loc (ClassDecl {tcdLName = class_name, tcdSigs = sigs, tcdMeths = default_binds})) = recoverM (return emptyLHsBinds) $ setSrcSpan loc $ do { clas <- tcLookupLocatedClass class_name -- We make a separate binding for each default method. -- At one time I used a single AbsBinds for all of them, thus -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... } -- But that desugars into -- ds = \d -> (..., ..., ...) -- dm1 = \d -> case ds d of (a,b,c) -> a -- And since ds is big, it doesn't get inlined, so we don't get good -- default methods. Better to make separate AbsBinds for each ; let (tyvars, _, _, op_items) = classBigSig clas prag_fn = mkPragFun sigs default_binds sig_fn = mkHsSigFun sigs clas_tyvars = snd (tcSuperSkolTyVars tyvars) pred = mkClassPred clas (mkTyVarTys clas_tyvars) ; this_dict <- newEvVar pred ; let tc_item (sel_id, dm_info) = case dm_info of DefMeth dm_name -> tc_dm sel_id dm_name False GenDefMeth dm_name -> tc_dm sel_id dm_name True -- For GenDefMeth, warn if the user specifies a signature -- with redundant constraints; but not for DefMeth, where -- the default method may well be 'error' or something NoDefMeth -> do { mapM_ (addLocM (badDmPrag sel_id)) (prag_fn (idName sel_id)) ; return emptyBag } tc_dm = tcDefMeth clas clas_tyvars this_dict default_binds sig_fn prag_fn ; dm_binds <- tcExtendTyVarEnv clas_tyvars $ mapM tc_item op_items ; return (unionManyBags dm_binds) } tcClassDecl2 d = pprPanic "tcClassDecl2" (ppr d) tcDefMeth :: Class -> [TyVar] -> EvVar -> LHsBinds Name -> HsSigFun -> PragFun -> Id -> Name -> Bool -> TcM (LHsBinds TcId) -- Generate code for polymorphic default methods only (hence DefMeth) -- (Generic default methods have turned into instance decls by now.) -- This is incompatible with Hugs, which expects a polymorphic -- default method for every class op, regardless of whether or not -- the programmer supplied an explicit default decl for the class. -- (If necessary we can fix that, but we don't have a convenient Id to hand.) tcDefMeth clas tyvars this_dict binds_in hs_sig_fn prag_fn sel_id dm_name warn_redundant | Just (L bind_loc dm_bind, bndr_loc) <- findMethodBind sel_name binds_in -- First look up the default method -- it should be there! = do { global_dm_id <- tcLookupId dm_name ; global_dm_id <- addInlinePrags global_dm_id prags ; local_dm_name <- setSrcSpan bndr_loc (newLocalName sel_name) -- Base the local_dm_name on the selector name, because -- type errors from tcInstanceMethodBody come from here ; spec_prags <- tcSpecPrags global_dm_id prags ; warnTc (not (null spec_prags)) (ptext (sLit "Ignoring SPECIALISE pragmas on default method") <+> quotes (ppr sel_name)) ; let hs_ty = lookupHsSig hs_sig_fn sel_name `orElse` pprPanic "tc_dm" (ppr sel_name) -- We need the HsType so that we can bring the right -- type variables into scope -- -- Eg. class C a where -- op :: forall b. Eq b => a -> [b] -> a -- gen_op :: a -> a -- generic gen_op :: D a => a -> a -- The "local_dm_ty" is precisely the type in the above -- type signatures, ie with no "forall a. C a =>" prefix local_dm_ty = instantiateMethod clas global_dm_id (mkTyVarTys tyvars) lm_bind = dm_bind { fun_id = L bind_loc local_dm_name } -- Substitute the local_meth_name for the binder -- NB: the binding is always a FunBind ; local_dm_sig <- instTcTySig hs_ty local_dm_ty Nothing [] local_dm_name ; let local_dm_sig' = local_dm_sig { sig_warn_redundant = warn_redundant } ; (ev_binds, (tc_bind, _, _)) <- checkConstraints (ClsSkol clas) tyvars [this_dict] $ tcPolyCheck NonRecursive no_prag_fn local_dm_sig' (L bind_loc lm_bind) ; let export = ABE { abe_poly = global_dm_id , abe_mono = sig_id local_dm_sig' , abe_wrap = idHsWrapper , abe_prags = IsDefaultMethod } full_bind = AbsBinds { abs_tvs = tyvars , abs_ev_vars = [this_dict] , abs_exports = [export] , abs_ev_binds = [ev_binds] , abs_binds = tc_bind } ; return (unitBag (L bind_loc full_bind)) } | otherwise = pprPanic "tcDefMeth" (ppr sel_id) where sel_name = idName sel_id prags = prag_fn sel_name no_prag_fn _ = [] -- No pragmas for local_meth_id; -- they are all for meth_id --------------- tcClassMinimalDef :: Name -> [LSig Name] -> [TcMethInfo] -> TcM ClassMinimalDef tcClassMinimalDef _clas sigs op_info = case findMinimalDef sigs of Nothing -> return defMindef Just mindef -> do -- Warn if the given mindef does not imply the default one -- That is, the given mindef should at least ensure that the -- class ops without default methods are required, since we -- have no way to fill them in otherwise whenIsJust (isUnsatisfied (mindef `impliesAtom`) defMindef) $ (\bf -> addWarnTc (warningMinimalDefIncomplete bf)) return mindef where -- By default require all methods without a default -- implementation whose names don't start with '_' defMindef :: ClassMinimalDef defMindef = mkAnd [ mkVar name | (name, NoDM, _) <- op_info , not (startsWithUnderscore (getOccName name)) ] instantiateMethod :: Class -> Id -> [TcType] -> TcType -- Take a class operation, say -- op :: forall ab. C a => forall c. Ix c => (b,c) -> a -- Instantiate it at [ty1,ty2] -- Return the "local method type": -- forall c. Ix x => (ty2,c) -> ty1 instantiateMethod clas sel_id inst_tys = ASSERT( ok_first_pred ) local_meth_ty where (sel_tyvars,sel_rho) = tcSplitForAllTys (idType sel_id) rho_ty = ASSERT( length sel_tyvars == length inst_tys ) substTyWith sel_tyvars inst_tys sel_rho (first_pred, local_meth_ty) = tcSplitPredFunTy_maybe rho_ty `orElse` pprPanic "tcInstanceMethod" (ppr sel_id) ok_first_pred = case getClassPredTys_maybe first_pred of Just (clas1, _tys) -> clas == clas1 Nothing -> False -- The first predicate should be of form (C a b) -- where C is the class in question --------------------------- type HsSigFun = NameEnv (LHsType Name) emptyHsSigs :: HsSigFun emptyHsSigs = emptyNameEnv mkHsSigFun :: [LSig Name] -> HsSigFun mkHsSigFun sigs = mkNameEnv [(n, hs_ty) | L _ (TypeSig ns hs_ty _) <- sigs , L _ n <- ns ] lookupHsSig :: HsSigFun -> Name -> Maybe (LHsType Name) lookupHsSig = lookupNameEnv --------------------------- findMethodBind :: Name -- Selector name -> LHsBinds Name -- A group of bindings -> Maybe (LHsBind Name, SrcSpan) -- Returns the binding, and the binding -- site of the method binder findMethodBind sel_name binds = foldlBag mplus Nothing (mapBag f binds) where f bind@(L _ (FunBind { fun_id = L bndr_loc op_name })) | op_name == sel_name = Just (bind, bndr_loc) f _other = Nothing --------------------------- findMinimalDef :: [LSig Name] -> Maybe ClassMinimalDef findMinimalDef = firstJusts . map toMinimalDef where toMinimalDef :: LSig Name -> Maybe ClassMinimalDef toMinimalDef (L _ (MinimalSig _ bf)) = Just (fmap unLoc bf) toMinimalDef _ = Nothing {- Note [Polymorphic methods] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider class Foo a where op :: forall b. Ord b => a -> b -> b -> b instance Foo c => Foo [c] where op = e When typechecking the binding 'op = e', we'll have a meth_id for op whose type is op :: forall c. Foo c => forall b. Ord b => [c] -> b -> b -> b So tcPolyBinds must be capable of dealing with nested polytypes; and so it is. See TcBinds.tcMonoBinds (with type-sig case). Note [Silly default-method bind] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we pass the default method binding to the type checker, it must look like op2 = e not $dmop2 = e otherwise the "$dm" stuff comes out error messages. But we want the "$dm" to come out in the interface file. So we typecheck the former, and wrap it in a let, thus $dmop2 = let op2 = e in op2 This makes the error messages right. ************************************************************************ * * Error messages * * ************************************************************************ -} tcMkDeclCtxt :: TyClDecl Name -> SDoc tcMkDeclCtxt decl = hsep [ptext (sLit "In the"), pprTyClDeclFlavour decl, ptext (sLit "declaration for"), quotes (ppr (tcdName decl))] tcAddDeclCtxt :: TyClDecl Name -> TcM a -> TcM a tcAddDeclCtxt decl thing_inside = addErrCtxt (tcMkDeclCtxt decl) thing_inside badMethodErr :: Outputable a => a -> Name -> SDoc badMethodErr clas op = hsep [ptext (sLit "Class"), quotes (ppr clas), ptext (sLit "does not have a method"), quotes (ppr op)] badGenericMethod :: Outputable a => a -> Name -> SDoc badGenericMethod clas op = hsep [ptext (sLit "Class"), quotes (ppr clas), ptext (sLit "has a generic-default signature without a binding"), quotes (ppr op)] {- badGenericInstanceType :: LHsBinds Name -> SDoc badGenericInstanceType binds = vcat [ptext (sLit "Illegal type pattern in the generic bindings"), nest 2 (ppr binds)] missingGenericInstances :: [Name] -> SDoc missingGenericInstances missing = ptext (sLit "Missing type patterns for") <+> pprQuotedList missing dupGenericInsts :: [(TyCon, InstInfo a)] -> SDoc dupGenericInsts tc_inst_infos = vcat [ptext (sLit "More than one type pattern for a single generic type constructor:"), nest 2 (vcat (map ppr_inst_ty tc_inst_infos)), ptext (sLit "All the type patterns for a generic type constructor must be identical") ] where ppr_inst_ty (_,inst) = ppr (simpleInstInfoTy inst) -} badDmPrag :: Id -> Sig Name -> TcM () badDmPrag sel_id prag = addErrTc (ptext (sLit "The") <+> hsSigDoc prag <+> ptext (sLit "for default method") <+> quotes (ppr sel_id) <+> ptext (sLit "lacks an accompanying binding")) warningMinimalDefIncomplete :: ClassMinimalDef -> SDoc warningMinimalDefIncomplete mindef = vcat [ ptext (sLit "The MINIMAL pragma does not require:") , nest 2 (pprBooleanFormulaNice mindef) , ptext (sLit "but there is no default implementation.") ]
green-haskell/ghc
compiler/typecheck/TcClassDcl.hs
bsd-3-clause
16,471
0
22
5,331
2,806
1,472
1,334
198
3
{-| Module : Idris.IBC Description : Core representations and code to generate IBC files. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.IBC (loadIBC, loadPkgIndex, writeIBC, writePkgIndex, hasValidIBCVersion, IBCPhase(..)) where import Idris.AbsSyntax import Idris.Core.Binary import Idris.Core.CaseTree import Idris.Core.Evaluate import Idris.Core.TT import Idris.DeepSeq import Idris.Delaborate import Idris.Docstrings (Docstring) import qualified Idris.Docstrings as D import Idris.Error import Idris.Imports import Idris.Output import IRTS.System (getIdrisLibDir) import Paths_idris import qualified Cheapskate.Types as CT import Codec.Archive.Zip import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict hiding (get, put) import qualified Control.Monad.State.Strict as ST import Data.Binary import Data.ByteString.Lazy as B hiding (elem, length, map) import Data.Functor import Data.List as L import Data.Maybe (catMaybes) import qualified Data.Set as S import qualified Data.Text as T import Data.Vector.Binary import Debug.Trace import System.Directory import System.FilePath ibcVersion :: Word16 ibcVersion = 160 -- | When IBC is being loaded - we'll load different things (and omit -- different structures/definitions) depending on which phase we're in. data IBCPhase = IBC_Building -- ^ when building the module tree | IBC_REPL Bool -- ^ when loading modules for the REPL Bool = True for top level module deriving (Show, Eq) data IBCFile = IBCFile { ver :: Word16 , sourcefile :: FilePath , ibc_reachablenames :: ![Name] , ibc_imports :: ![(Bool, FilePath)] , ibc_importdirs :: ![FilePath] , ibc_sourcedirs :: ![FilePath] , ibc_implicits :: ![(Name, [PArg])] , ibc_fixes :: ![FixDecl] , ibc_statics :: ![(Name, [Bool])] , ibc_interfaces :: ![(Name, InterfaceInfo)] , ibc_records :: ![(Name, RecordInfo)] , ibc_implementations :: ![(Bool, Bool, Name, Name)] , ibc_dsls :: ![(Name, DSL)] , ibc_datatypes :: ![(Name, TypeInfo)] , ibc_optimise :: ![(Name, OptInfo)] , ibc_syntax :: ![Syntax] , ibc_keywords :: ![String] , ibc_objs :: ![(Codegen, FilePath)] , ibc_libs :: ![(Codegen, String)] , ibc_cgflags :: ![(Codegen, String)] , ibc_dynamic_libs :: ![String] , ibc_hdrs :: ![(Codegen, String)] , ibc_totcheckfail :: ![(FC, String)] , ibc_flags :: ![(Name, [FnOpt])] , ibc_fninfo :: ![(Name, FnInfo)] , ibc_cg :: ![(Name, CGInfo)] , ibc_docstrings :: ![(Name, (Docstring D.DocTerm, [(Name, Docstring D.DocTerm)]))] , ibc_moduledocs :: ![(Name, Docstring D.DocTerm)] , ibc_transforms :: ![(Name, (Term, Term))] , ibc_errRev :: ![(Term, Term)] , ibc_errReduce :: ![Name] , ibc_coercions :: ![Name] , ibc_lineapps :: ![(FilePath, Int, PTerm)] , ibc_namehints :: ![(Name, Name)] , ibc_metainformation :: ![(Name, MetaInformation)] , ibc_errorhandlers :: ![Name] , ibc_function_errorhandlers :: ![(Name, Name, Name)] -- fn, arg, handler , ibc_metavars :: ![(Name, (Maybe Name, Int, [Name], Bool, Bool))] , ibc_patdefs :: ![(Name, ([([(Name, Term)], Term, Term)], [PTerm]))] , ibc_postulates :: ![Name] , ibc_externs :: ![(Name, Int)] , ibc_parsedSpan :: !(Maybe FC) , ibc_usage :: ![(Name, Int)] , ibc_exports :: ![Name] , ibc_autohints :: ![(Name, Name)] , ibc_deprecated :: ![(Name, String)] , ibc_defs :: ![(Name, Def)] , ibc_total :: ![(Name, Totality)] , ibc_injective :: ![(Name, Injectivity)] , ibc_access :: ![(Name, Accessibility)] , ibc_fragile :: ![(Name, String)] , ibc_constraints :: ![(FC, UConstraint)] } deriving Show {-! deriving instance Binary IBCFile !-} initIBC :: IBCFile initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] Nothing [] [] [] [] [] [] [] [] [] [] hasValidIBCVersion :: FilePath -> Idris Bool hasValidIBCVersion fp = do archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> return False Right archive -> do ver <- getEntry 0 "ver" archive return (ver == ibcVersion) loadIBC :: Bool -- ^ True = reexport, False = make everything private -> IBCPhase -> FilePath -> Idris () loadIBC reexport phase fp = do imps <- getImported case lookup fp imps of Nothing -> load True Just p -> if (not p && reexport) then load False else return () where load fullLoad = do logIBC 1 $ "Loading ibc " ++ fp ++ " " ++ show reexport archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> do ifail $ fp ++ " isn't loadable, it may have an old ibc format.\n" ++ "Please clean and rebuild it." Right archive -> do if fullLoad then process reexport phase archive fp else unhide phase archive addImported reexport fp -- | Load an entire package from its index file loadPkgIndex :: String -> Idris () loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir addImportDir (ddir </> pkg) fp <- findPkgIndex pkg loadIBC True IBC_Building fp makeEntry :: (Binary b) => String -> [b] -> Maybe Entry makeEntry name val = if L.null val then Nothing else Just $ toEntry name 0 (encode val) entries :: IBCFile -> [Entry] entries i = catMaybes [Just $ toEntry "ver" 0 (encode $ ver i), makeEntry "sourcefile" (sourcefile i), makeEntry "ibc_imports" (ibc_imports i), makeEntry "ibc_importdirs" (ibc_importdirs i), makeEntry "ibc_sourcedirs" (ibc_sourcedirs i), makeEntry "ibc_implicits" (ibc_implicits i), makeEntry "ibc_fixes" (ibc_fixes i), makeEntry "ibc_statics" (ibc_statics i), makeEntry "ibc_interfaces" (ibc_interfaces i), makeEntry "ibc_records" (ibc_records i), makeEntry "ibc_implementations" (ibc_implementations i), makeEntry "ibc_dsls" (ibc_dsls i), makeEntry "ibc_datatypes" (ibc_datatypes i), makeEntry "ibc_optimise" (ibc_optimise i), makeEntry "ibc_syntax" (ibc_syntax i), makeEntry "ibc_keywords" (ibc_keywords i), makeEntry "ibc_objs" (ibc_objs i), makeEntry "ibc_libs" (ibc_libs i), makeEntry "ibc_cgflags" (ibc_cgflags i), makeEntry "ibc_dynamic_libs" (ibc_dynamic_libs i), makeEntry "ibc_hdrs" (ibc_hdrs i), makeEntry "ibc_totcheckfail" (ibc_totcheckfail i), makeEntry "ibc_flags" (ibc_flags i), makeEntry "ibc_fninfo" (ibc_fninfo i), makeEntry "ibc_cg" (ibc_cg i), makeEntry "ibc_docstrings" (ibc_docstrings i), makeEntry "ibc_moduledocs" (ibc_moduledocs i), makeEntry "ibc_transforms" (ibc_transforms i), makeEntry "ibc_errRev" (ibc_errRev i), makeEntry "ibc_errReduce" (ibc_errReduce i), makeEntry "ibc_coercions" (ibc_coercions i), makeEntry "ibc_lineapps" (ibc_lineapps i), makeEntry "ibc_namehints" (ibc_namehints i), makeEntry "ibc_metainformation" (ibc_metainformation i), makeEntry "ibc_errorhandlers" (ibc_errorhandlers i), makeEntry "ibc_function_errorhandlers" (ibc_function_errorhandlers i), makeEntry "ibc_metavars" (ibc_metavars i), makeEntry "ibc_patdefs" (ibc_patdefs i), makeEntry "ibc_postulates" (ibc_postulates i), makeEntry "ibc_externs" (ibc_externs i), toEntry "ibc_parsedSpan" 0 . encode <$> ibc_parsedSpan i, makeEntry "ibc_usage" (ibc_usage i), makeEntry "ibc_exports" (ibc_exports i), makeEntry "ibc_autohints" (ibc_autohints i), makeEntry "ibc_deprecated" (ibc_deprecated i), makeEntry "ibc_defs" (ibc_defs i), makeEntry "ibc_total" (ibc_total i), makeEntry "ibc_injective" (ibc_injective i), makeEntry "ibc_access" (ibc_access i), makeEntry "ibc_fragile" (ibc_fragile i)] -- TODO: Put this back in shortly after minimising/pruning constraints -- makeEntry "ibc_constraints" (ibc_constraints i)] writeArchive :: FilePath -> IBCFile -> Idris () writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArchive (entries i) runIO $ B.writeFile fp (fromArchive a) writeIBC :: FilePath -> FilePath -> Idris () writeIBC src f = do logIBC 2 $ "Writing IBC for: " ++ show f iReport 2 $ "Writing IBC for: " ++ show f i <- getIState -- case (Data.List.map fst (idris_metavars i)) \\ primDefs of -- (_:_) -> ifail "Can't write ibc when there are unsolved metavariables" -- [] -> return () resetNameIdx ibcf <- mkIBC (ibc_write i) (initIBC { sourcefile = src }) idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 2 "Written") (\c -> do logIBC 2 $ "Failed " ++ pshow i c) return () -- | Write a package index containing all the imports in the current -- IState Used for ':search' of an entire package, to ensure -- everything is loaded. writePkgIndex :: FilePath -> Idris () writePkgIndex f = do i <- getIState let imps = map (\ (x, y) -> (True, x)) $ idris_imported i logIBC 2 $ "Writing package index " ++ show f ++ " including\n" ++ show (map snd imps) resetNameIdx let ibcf = initIBC { ibc_imports = imps } idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 2 "Written") (\c -> do logIBC 2 $ "Failed " ++ pshow i c) return () mkIBC :: [IBCWrite] -> IBCFile -> Idris IBCFile mkIBC [] f = return f mkIBC (i:is) f = do ist <- getIState logIBC 5 $ show i ++ " " ++ show (L.length is) f' <- ibc ist i f mkIBC is f' ibc :: IState -> IBCWrite -> IBCFile -> Idris IBCFile ibc i (IBCFix d) f = return f { ibc_fixes = d : ibc_fixes f } ibc i (IBCImp n) f = case lookupCtxtExact n (idris_implicits i) of Just v -> return f { ibc_implicits = (n,v): ibc_implicits f } _ -> ifail "IBC write failed" ibc i (IBCStatic n) f = case lookupCtxtExact n (idris_statics i) of Just v -> return f { ibc_statics = (n,v): ibc_statics f } _ -> ifail "IBC write failed" ibc i (IBCInterface n) f = case lookupCtxtExact n (idris_interfaces i) of Just v -> return f { ibc_interfaces = (n,v): ibc_interfaces f } _ -> ifail "IBC write failed" ibc i (IBCRecord n) f = case lookupCtxtExact n (idris_records i) of Just v -> return f { ibc_records = (n,v): ibc_records f } _ -> ifail "IBC write failed" ibc i (IBCImplementation int res n ins) f = return f { ibc_implementations = (int, res, n, ins) : ibc_implementations f } ibc i (IBCDSL n) f = case lookupCtxtExact n (idris_dsls i) of Just v -> return f { ibc_dsls = (n,v): ibc_dsls f } _ -> ifail "IBC write failed" ibc i (IBCData n) f = case lookupCtxtExact n (idris_datatypes i) of Just v -> return f { ibc_datatypes = (n,v): ibc_datatypes f } _ -> ifail "IBC write failed" ibc i (IBCOpt n) f = case lookupCtxtExact n (idris_optimisation i) of Just v -> return f { ibc_optimise = (n,v): ibc_optimise f } _ -> ifail "IBC write failed" ibc i (IBCSyntax n) f = return f { ibc_syntax = n : ibc_syntax f } ibc i (IBCKeyword n) f = return f { ibc_keywords = n : ibc_keywords f } ibc i (IBCImport n) f = return f { ibc_imports = n : ibc_imports f } ibc i (IBCImportDir n) f = return f { ibc_importdirs = n : ibc_importdirs f } ibc i (IBCSourceDir n) f = return f { ibc_sourcedirs = n : ibc_sourcedirs f } ibc i (IBCObj tgt n) f = return f { ibc_objs = (tgt, n) : ibc_objs f } ibc i (IBCLib tgt n) f = return f { ibc_libs = (tgt, n) : ibc_libs f } ibc i (IBCCGFlag tgt n) f = return f { ibc_cgflags = (tgt, n) : ibc_cgflags f } ibc i (IBCDyLib n) f = return f {ibc_dynamic_libs = n : ibc_dynamic_libs f } ibc i (IBCHeader tgt n) f = return f { ibc_hdrs = (tgt, n) : ibc_hdrs f } ibc i (IBCDef n) f = do f' <- case lookupDefExact n (tt_ctxt i) of Just v -> return f { ibc_defs = (n,v) : ibc_defs f } _ -> ifail "IBC write failed" case lookupCtxtExact n (idris_patdefs i) of Just v -> return f' { ibc_patdefs = (n,v) : ibc_patdefs f } _ -> return f' -- Not a pattern definition ibc i (IBCDoc n) f = case lookupCtxtExact n (idris_docstrings i) of Just v -> return f { ibc_docstrings = (n,v) : ibc_docstrings f } _ -> ifail "IBC write failed" ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of Just v -> return f { ibc_cg = (n,v) : ibc_cg f } _ -> ifail "IBC write failed" ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f } ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f } ibc i (IBCFlags n) f = case lookupCtxtExact n (idris_flags i) of Just a -> return f { ibc_flags = (n,a): ibc_flags f } _ -> ifail "IBC write failed" ibc i (IBCFnInfo n a) f = return f { ibc_fninfo = (n,a) : ibc_fninfo f } ibc i (IBCTotal n a) f = return f { ibc_total = (n,a) : ibc_total f } ibc i (IBCInjective n a) f = return f { ibc_injective = (n,a) : ibc_injective f } ibc i (IBCTrans n t) f = return f { ibc_transforms = (n, t) : ibc_transforms f } ibc i (IBCErrRev t) f = return f { ibc_errRev = t : ibc_errRev f } ibc i (IBCErrReduce t) f = return f { ibc_errReduce = t : ibc_errReduce f } ibc i (IBCLineApp fp l t) f = return f { ibc_lineapps = (fp,l,t) : ibc_lineapps f } ibc i (IBCNameHint (n, ty)) f = return f { ibc_namehints = (n, ty) : ibc_namehints f } ibc i (IBCMetaInformation n m) f = return f { ibc_metainformation = (n,m) : ibc_metainformation f } ibc i (IBCErrorHandler n) f = return f { ibc_errorhandlers = n : ibc_errorhandlers f } ibc i (IBCFunctionErrorHandler fn a n) f = return f { ibc_function_errorhandlers = (fn, a, n) : ibc_function_errorhandlers f } ibc i (IBCMetavar n) f = case lookup n (idris_metavars i) of Nothing -> return f Just t -> return f { ibc_metavars = (n, t) : ibc_metavars f } ibc i (IBCPostulate n) f = return f { ibc_postulates = n : ibc_postulates f } ibc i (IBCExtern n) f = return f { ibc_externs = n : ibc_externs f } ibc i (IBCTotCheckErr fc err) f = return f { ibc_totcheckfail = (fc, err) : ibc_totcheckfail f } ibc i (IBCParsedRegion fc) f = return f { ibc_parsedSpan = Just fc } ibc i (IBCModDocs n) f = case lookupCtxtExact n (idris_moduledocs i) of Just v -> return f { ibc_moduledocs = (n,v) : ibc_moduledocs f } _ -> ifail "IBC write failed" ibc i (IBCUsage n) f = return f { ibc_usage = n : ibc_usage f } ibc i (IBCExport n) f = return f { ibc_exports = n : ibc_exports f } ibc i (IBCAutoHint n h) f = return f { ibc_autohints = (n, h) : ibc_autohints f } ibc i (IBCDeprecate n r) f = return f { ibc_deprecated = (n, r) : ibc_deprecated f } ibc i (IBCFragile n r) f = return f { ibc_fragile = (n,r) : ibc_fragile f } ibc i (IBCConstraint fc u) f = return f { ibc_constraints = (fc, u) : ibc_constraints f } getEntry :: (Binary b, NFData b) => b -> FilePath -> Archive -> Idris b getEntry alt f a = case findEntryByPath f a of Nothing -> return alt Just e -> return $! (force . decode . fromEntry) e unhide :: IBCPhase -> Archive -> Idris () unhide phase ar = do processImports True phase ar processAccess True phase ar process :: Bool -- ^ Reexporting -> IBCPhase -> Archive -> FilePath -> Idris () process reexp phase archive fn = do ver <- getEntry 0 "ver" archive when (ver /= ibcVersion) $ do logIBC 2 "ibc out of date" let e = if ver < ibcVersion then "an earlier" else "a later" ldir <- runIO $ getIdrisLibDir let start = if ldir `L.isPrefixOf` fn then "This external module" else "This module" let end = case L.stripPrefix ldir fn of Nothing -> "Please clean and rebuild." Just ploc -> unwords ["Please reinstall:", L.head $ splitDirectories ploc] ifail $ unlines [ unwords ["Incompatible ibc version for:", show fn] , unwords [start , "was built with" , e , "version of Idris."] , end ] source <- getEntry "" "sourcefile" archive srcok <- runIO $ doesFileExist source when srcok $ timestampOlder source fn processImportDirs archive processSourceDirs archive processImports reexp phase archive processImplicits archive processInfix archive processStatics archive processInterfaces archive processRecords archive processImplementations archive processDSLs archive processDatatypes archive processOptimise archive processSyntax archive processKeywords archive processObjectFiles archive processLibs archive processCodegenFlags archive processDynamicLibs archive processHeaders archive processPatternDefs archive processFlags archive processFnInfo archive processTotalityCheckError archive processCallgraph archive processDocs archive processModuleDocs archive processCoercions archive processTransforms archive processErrRev archive processErrReduce archive processLineApps archive processNameHints archive processMetaInformation archive processErrorHandlers archive processFunctionErrorHandlers archive processMetaVars archive processPostulates archive processExterns archive processParsedSpan archive processUsage archive processExports archive processAutoHints archive processDeprecate archive processDefs archive processTotal archive processInjective archive processAccess reexp phase archive processFragile archive processConstraints archive timestampOlder :: FilePath -> FilePath -> Idris () timestampOlder src ibc = do srct <- runIO $ getModificationTime src ibct <- runIO $ getModificationTime ibc if (srct > ibct) then ifail $ unlines [ "Module needs reloading:" , unwords ["\tSRC :", show src] , unwords ["\tModified at:", show srct] , unwords ["\tIBC :", show ibc] , unwords ["\tModified at:", show ibct] ] else return () processPostulates :: Archive -> Idris () processPostulates ar = do ns <- getEntry [] "ibc_postulates" ar updateIState (\i -> i { idris_postulates = idris_postulates i `S.union` S.fromList ns }) processExterns :: Archive -> Idris () processExterns ar = do ns <- getEntry [] "ibc_externs" ar updateIState (\i -> i{ idris_externs = idris_externs i `S.union` S.fromList ns }) processParsedSpan :: Archive -> Idris () processParsedSpan ar = do fc <- getEntry Nothing "ibc_parsedSpan" ar updateIState (\i -> i { idris_parsedSpan = fc }) processUsage :: Archive -> Idris () processUsage ar = do ns <- getEntry [] "ibc_usage" ar updateIState (\i -> i { idris_erasureUsed = ns ++ idris_erasureUsed i }) processExports :: Archive -> Idris () processExports ar = do ns <- getEntry [] "ibc_exports" ar updateIState (\i -> i { idris_exports = ns ++ idris_exports i }) processAutoHints :: Archive -> Idris () processAutoHints ar = do ns <- getEntry [] "ibc_autohints" ar mapM_ (\(n,h) -> addAutoHint n h) ns processDeprecate :: Archive -> Idris () processDeprecate ar = do ns <- getEntry [] "ibc_deprecated" ar mapM_ (\(n,reason) -> addDeprecated n reason) ns processFragile :: Archive -> Idris () processFragile ar = do ns <- getEntry [] "ibc_fragile" ar mapM_ (\(n,reason) -> addFragile n reason) ns processConstraints :: Archive -> Idris () processConstraints ar = do cs <- getEntry [] "ibc_constraints" ar mapM_ (\ (fc, c) -> addConstraints fc (0, [c])) cs processImportDirs :: Archive -> Idris () processImportDirs ar = do fs <- getEntry [] "ibc_importdirs" ar mapM_ addImportDir fs processSourceDirs :: Archive -> Idris () processSourceDirs ar = do fs <- getEntry [] "ibc_sourcedirs" ar mapM_ addSourceDir fs processImports :: Bool -> IBCPhase -> Archive -> Idris () processImports reexp phase ar = do fs <- getEntry [] "ibc_imports" ar mapM_ (\(re, f) -> do i <- getIState ibcsd <- valIBCSubDir i ids <- allImportDirs fp <- findImport ids ibcsd f -- if (f `elem` imported i) -- then logLvl 1 $ "Already read " ++ f putIState (i { imported = f : imported i }) let phase' = case phase of IBC_REPL _ -> IBC_REPL False p -> p case fp of LIDR fn -> do logIBC 2 $ "Failed at " ++ fn ifail "Must be an ibc" IDR fn -> do logIBC 2 $ "Failed at " ++ fn ifail "Must be an ibc" IBC fn src -> loadIBC (reexp && re) phase' fn) fs processImplicits :: Archive -> Idris () processImplicits ar = do imps <- getEntry [] "ibc_implicits" ar mapM_ (\ (n, imp) -> do i <- getIState case lookupDefAccExact n False (tt_ctxt i) of Just (n, Hidden) -> return () Just (n, Private) -> return () _ -> putIState (i { idris_implicits = addDef n imp (idris_implicits i) })) imps processInfix :: Archive -> Idris () processInfix ar = do f <- getEntry [] "ibc_fixes" ar updateIState (\i -> i { idris_infixes = sort $ f ++ idris_infixes i }) processStatics :: Archive -> Idris () processStatics ar = do ss <- getEntry [] "ibc_statics" ar mapM_ (\ (n, s) -> updateIState (\i -> i { idris_statics = addDef n s (idris_statics i) })) ss processInterfaces :: Archive -> Idris () processInterfaces ar = do cs <- getEntry [] "ibc_interfaces" ar mapM_ (\ (n, c) -> do i <- getIState -- Don't lose implementations from previous IBCs, which -- could have loaded in any order let is = case lookupCtxtExact n (idris_interfaces i) of Just ci -> interface_implementations ci _ -> [] let c' = c { interface_implementations = interface_implementations c ++ is } putIState (i { idris_interfaces = addDef n c' (idris_interfaces i) })) cs processRecords :: Archive -> Idris () processRecords ar = do rs <- getEntry [] "ibc_records" ar mapM_ (\ (n, r) -> updateIState (\i -> i { idris_records = addDef n r (idris_records i) })) rs processImplementations :: Archive -> Idris () processImplementations ar = do cs <- getEntry [] "ibc_implementations" ar mapM_ (\ (i, res, n, ins) -> addImplementation i res n ins) cs processDSLs :: Archive -> Idris () processDSLs ar = do cs <- getEntry [] "ibc_dsls" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_dsls = addDef n c (idris_dsls i) })) cs processDatatypes :: Archive -> Idris () processDatatypes ar = do cs <- getEntry [] "ibc_datatypes" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_datatypes = addDef n c (idris_datatypes i) })) cs processOptimise :: Archive -> Idris () processOptimise ar = do cs <- getEntry [] "ibc_optimise" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_optimisation = addDef n c (idris_optimisation i) })) cs processSyntax :: Archive -> Idris () processSyntax ar = do s <- getEntry [] "ibc_syntax" ar updateIState (\i -> i { syntax_rules = updateSyntaxRules s (syntax_rules i) }) processKeywords :: Archive -> Idris () processKeywords ar = do k <- getEntry [] "ibc_keywords" ar updateIState (\i -> i { syntax_keywords = k ++ syntax_keywords i }) processObjectFiles :: Archive -> Idris () processObjectFiles ar = do os <- getEntry [] "ibc_objs" ar mapM_ (\ (cg, obj) -> do dirs <- allImportDirs o <- runIO $ findInPath dirs obj addObjectFile cg o) os processLibs :: Archive -> Idris () processLibs ar = do ls <- getEntry [] "ibc_libs" ar mapM_ (uncurry addLib) ls processCodegenFlags :: Archive -> Idris () processCodegenFlags ar = do ls <- getEntry [] "ibc_cgflags" ar mapM_ (uncurry addFlag) ls processDynamicLibs :: Archive -> Idris () processDynamicLibs ar = do ls <- getEntry [] "ibc_dynamic_libs" ar res <- mapM (addDyLib . return) ls mapM_ checkLoad res where checkLoad (Left _) = return () checkLoad (Right err) = ifail err processHeaders :: Archive -> Idris () processHeaders ar = do hs <- getEntry [] "ibc_hdrs" ar mapM_ (uncurry addHdr) hs processPatternDefs :: Archive -> Idris () processPatternDefs ar = do ds <- getEntry [] "ibc_patdefs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_patdefs = addDef n (force d) (idris_patdefs i) })) ds processDefs :: Archive -> Idris () processDefs ar = do ds <- getEntry [] "ibc_defs" ar mapM_ (\ (n, d) -> do d' <- updateDef d case d' of TyDecl _ _ -> return () _ -> do logIBC 2 $ "SOLVING " ++ show n solveDeferred emptyFC n updateIState (\i -> i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds where updateDef (CaseOp c t args o s cd) = do o' <- mapM updateOrig o cd' <- updateCD cd return $ CaseOp c t args o' s cd' updateDef t = return t updateOrig (Left t) = liftM Left (update t) updateOrig (Right (l, r)) = do l' <- update l r' <- update r return $ Right (l', r') updateCD (CaseDefs (cs, c) (rs, r)) = do c' <- updateSC c r' <- updateSC r return $ CaseDefs (cs, c') (rs, r') updateSC (Case t n alts) = do alts' <- mapM updateAlt alts return (Case t n alts') updateSC (ProjCase t alts) = do alts' <- mapM updateAlt alts return (ProjCase t alts') updateSC (STerm t) = do t' <- update t return (STerm t') updateSC c = return c updateAlt (ConCase n i ns t) = do t' <- updateSC t return (ConCase n i ns t') updateAlt (FnCase n ns t) = do t' <- updateSC t return (FnCase n ns t') updateAlt (ConstCase c t) = do t' <- updateSC t return (ConstCase c t') updateAlt (SucCase n t) = do t' <- updateSC t return (SucCase n t') updateAlt (DefaultCase t) = do t' <- updateSC t return (DefaultCase t') -- We get a lot of repetition in sub terms and can save a fair chunk -- of memory if we make sure they're shared. addTT looks for a term -- and returns it if it exists already, while also keeping stats of -- how many times a subterm is repeated. update t = do tm <- addTT t case tm of Nothing -> update' t Just t' -> return t' update' (P t n ty) = do n' <- getSymbol n return $ P t n' ty update' (App s f a) = liftM2 (App s) (update' f) (update' a) update' (Bind n b sc) = do b' <- updateB b sc' <- update sc return $ Bind n b' sc' where updateB (Let t v) = liftM2 Let (update' t) (update' v) updateB b = do ty' <- update' (binderTy b) return (b { binderTy = ty' }) update' (Proj t i) = do t' <- update' t return $ Proj t' i update' t = return t processDocs :: Archive -> Idris () processDocs ar = do ds <- getEntry [] "ibc_docstrings" ar mapM_ (\(n, a) -> addDocStr n (fst a) (snd a)) ds processModuleDocs :: Archive -> Idris () processModuleDocs ar = do ds <- getEntry [] "ibc_moduledocs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_moduledocs = addDef n d (idris_moduledocs i) })) ds processAccess :: Bool -- ^ Reexporting? -> IBCPhase -> Archive -> Idris () processAccess reexp phase ar = do ds <- getEntry [] "ibc_access" ar mapM_ (\ (n, a_in) -> do let a = if reexp then a_in else Hidden logIBC 3 $ "Setting " ++ show (a, n) ++ " to " ++ show a updateIState (\i -> i { tt_ctxt = setAccess n a (tt_ctxt i) }) if (not reexp) then do logIBC 2 $ "Not exporting " ++ show n setAccessibility n Hidden else logIBC 2 $ "Exporting " ++ show n -- Everything should be available at the REPL from -- things imported publicly when (phase == IBC_REPL True) $ setAccessibility n Public) ds processFlags :: Archive -> Idris () processFlags ar = do ds <- getEntry [] "ibc_flags" ar mapM_ (\ (n, a) -> setFlags n a) ds processFnInfo :: Archive -> Idris () processFnInfo ar = do ds <- getEntry [] "ibc_fninfo" ar mapM_ (\ (n, a) -> setFnInfo n a) ds processTotal :: Archive -> Idris () processTotal ar = do ds <- getEntry [] "ibc_total" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setTotal n a (tt_ctxt i) })) ds processInjective :: Archive -> Idris () processInjective ar = do ds <- getEntry [] "ibc_injective" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setInjective n a (tt_ctxt i) })) ds processTotalityCheckError :: Archive -> Idris () processTotalityCheckError ar = do es <- getEntry [] "ibc_totcheckfail" ar updateIState (\i -> i { idris_totcheckfail = idris_totcheckfail i ++ es }) processCallgraph :: Archive -> Idris () processCallgraph ar = do ds <- getEntry [] "ibc_cg" ar mapM_ (\ (n, a) -> addToCG n a) ds processCoercions :: Archive -> Idris () processCoercions ar = do ns <- getEntry [] "ibc_coercions" ar mapM_ (\ n -> addCoercion n) ns processTransforms :: Archive -> Idris () processTransforms ar = do ts <- getEntry [] "ibc_transforms" ar mapM_ (\ (n, t) -> addTrans n t) ts processErrRev :: Archive -> Idris () processErrRev ar = do ts <- getEntry [] "ibc_errRev" ar mapM_ addErrRev ts processErrReduce :: Archive -> Idris () processErrReduce ar = do ts <- getEntry [] "ibc_errReduce" ar mapM_ addErrReduce ts processLineApps :: Archive -> Idris () processLineApps ar = do ls <- getEntry [] "ibc_lineapps" ar mapM_ (\ (f, i, t) -> addInternalApp f i t) ls processNameHints :: Archive -> Idris () processNameHints ar = do ns <- getEntry [] "ibc_namehints" ar mapM_ (\ (n, ty) -> addNameHint n ty) ns processMetaInformation :: Archive -> Idris () processMetaInformation ar = do ds <- getEntry [] "ibc_metainformation" ar mapM_ (\ (n, m) -> updateIState (\i -> i { tt_ctxt = setMetaInformation n m (tt_ctxt i) })) ds processErrorHandlers :: Archive -> Idris () processErrorHandlers ar = do ns <- getEntry [] "ibc_errorhandlers" ar updateIState (\i -> i { idris_errorhandlers = idris_errorhandlers i ++ ns }) processFunctionErrorHandlers :: Archive -> Idris () processFunctionErrorHandlers ar = do ns <- getEntry [] "ibc_function_errorhandlers" ar mapM_ (\ (fn,arg,handler) -> addFunctionErrorHandlers fn arg [handler]) ns processMetaVars :: Archive -> Idris () processMetaVars ar = do ns <- getEntry [] "ibc_metavars" ar updateIState (\i -> i { idris_metavars = L.reverse ns ++ idris_metavars i }) ----- For Cheapskate and docstrings instance Binary a => Binary (D.Docstring a) where put (D.DocString opts lines) = do put opts ; put lines get = do opts <- get lines <- get return (D.DocString opts lines) instance Binary CT.Options where put (CT.Options x1 x2 x3 x4) = do put x1 ; put x2 ; put x3 ; put x4 get = do x1 <- get x2 <- get x3 <- get x4 <- get return (CT.Options x1 x2 x3 x4) instance Binary D.DocTerm where put D.Unchecked = putWord8 0 put (D.Checked t) = putWord8 1 >> put t put (D.Example t) = putWord8 2 >> put t put (D.Failing e) = putWord8 3 >> put e get = do i <- getWord8 case i of 0 -> return D.Unchecked 1 -> fmap D.Checked get 2 -> fmap D.Example get 3 -> fmap D.Failing get _ -> error "Corrupted binary data for DocTerm" instance Binary a => Binary (D.Block a) where put (D.Para lines) = do putWord8 0 ; put lines put (D.Header i lines) = do putWord8 1 ; put i ; put lines put (D.Blockquote bs) = do putWord8 2 ; put bs put (D.List b t xs) = do putWord8 3 ; put b ; put t ; put xs put (D.CodeBlock attr txt src) = do putWord8 4 ; put attr ; put txt ; put src put (D.HtmlBlock txt) = do putWord8 5 ; put txt put D.HRule = putWord8 6 get = do i <- getWord8 case i of 0 -> fmap D.Para get 1 -> liftM2 D.Header get get 2 -> fmap D.Blockquote get 3 -> liftM3 D.List get get get 4 -> liftM3 D.CodeBlock get get get 5 -> liftM D.HtmlBlock get 6 -> return D.HRule _ -> error "Corrupted binary data for Block" instance Binary a => Binary (D.Inline a) where put (D.Str txt) = do putWord8 0 ; put txt put D.Space = putWord8 1 put D.SoftBreak = putWord8 2 put D.LineBreak = putWord8 3 put (D.Emph xs) = putWord8 4 >> put xs put (D.Strong xs) = putWord8 5 >> put xs put (D.Code xs tm) = putWord8 6 >> put xs >> put tm put (D.Link a b c) = putWord8 7 >> put a >> put b >> put c put (D.Image a b c) = putWord8 8 >> put a >> put b >> put c put (D.Entity a) = putWord8 9 >> put a put (D.RawHtml x) = putWord8 10 >> put x get = do i <- getWord8 case i of 0 -> liftM D.Str get 1 -> return D.Space 2 -> return D.SoftBreak 3 -> return D.LineBreak 4 -> liftM D.Emph get 5 -> liftM D.Strong get 6 -> liftM2 D.Code get get 7 -> liftM3 D.Link get get get 8 -> liftM3 D.Image get get get 9 -> liftM D.Entity get 10 -> liftM D.RawHtml get _ -> error "Corrupted binary data for Inline" instance Binary CT.ListType where put (CT.Bullet c) = putWord8 0 >> put c put (CT.Numbered nw i) = putWord8 1 >> put nw >> put i get = do i <- getWord8 case i of 0 -> liftM CT.Bullet get 1 -> liftM2 CT.Numbered get get _ -> error "Corrupted binary data for ListType" instance Binary CT.CodeAttr where put (CT.CodeAttr a b) = put a >> put b get = liftM2 CT.CodeAttr get get instance Binary CT.NumWrapper where put (CT.PeriodFollowing) = putWord8 0 put (CT.ParenFollowing) = putWord8 1 get = do i <- getWord8 case i of 0 -> return CT.PeriodFollowing 1 -> return CT.ParenFollowing _ -> error "Corrupted binary data for NumWrapper" ----- Generated by 'derive' instance Binary SizeChange where put x = case x of Smaller -> putWord8 0 Same -> putWord8 1 Bigger -> putWord8 2 Unknown -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Smaller 1 -> return Same 2 -> return Bigger 3 -> return Unknown _ -> error "Corrupted binary data for SizeChange" instance Binary CGInfo where put (CGInfo x1 x2 x3 x4) = do put x1 -- put x3 -- Already used SCG info for totality check put x2 put x4 get = do x1 <- get x2 <- get x3 <- get return (CGInfo x1 x2 [] x3) instance Binary CaseType where put x = case x of Updatable -> putWord8 0 Shared -> putWord8 1 get = do i <- getWord8 case i of 0 -> return Updatable 1 -> return Shared _ -> error "Corrupted binary data for CaseType" instance Binary SC where put x = case x of Case x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 ProjCase x1 x2 -> do putWord8 1 put x1 put x2 STerm x1 -> do putWord8 2 put x1 UnmatchedCase x1 -> do putWord8 3 put x1 ImpossibleCase -> do putWord8 4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (Case x1 x2 x3) 1 -> do x1 <- get x2 <- get return (ProjCase x1 x2) 2 -> do x1 <- get return (STerm x1) 3 -> do x1 <- get return (UnmatchedCase x1) 4 -> return ImpossibleCase _ -> error "Corrupted binary data for SC" instance Binary CaseAlt where put x = {-# SCC "putCaseAlt" #-} case x of ConCase x1 x2 x3 x4 -> do putWord8 0 put x1 put x2 put x3 put x4 ConstCase x1 x2 -> do putWord8 1 put x1 put x2 DefaultCase x1 -> do putWord8 2 put x1 FnCase x1 x2 x3 -> do putWord8 3 put x1 put x2 put x3 SucCase x1 x2 -> do putWord8 4 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (ConCase x1 x2 x3 x4) 1 -> do x1 <- get x2 <- get return (ConstCase x1 x2) 2 -> do x1 <- get return (DefaultCase x1) 3 -> do x1 <- get x2 <- get x3 <- get return (FnCase x1 x2 x3) 4 -> do x1 <- get x2 <- get return (SucCase x1 x2) _ -> error "Corrupted binary data for CaseAlt" instance Binary CaseDefs where put (CaseDefs x1 x2) = do put x1 put x2 get = do x1 <- get x2 <- get return (CaseDefs x1 x2) instance Binary CaseInfo where put x@(CaseInfo x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (CaseInfo x1 x2 x3) instance Binary Def where put x = {-# SCC "putDef" #-} case x of Function x1 x2 -> do putWord8 0 put x1 put x2 TyDecl x1 x2 -> do putWord8 1 put x1 put x2 -- all primitives just get added at the start, don't write Operator x1 x2 x3 -> do return () -- no need to add/load original patterns, because they're not -- used again after totality checking CaseOp x1 x2 x3 _ _ x4 -> do putWord8 3 put x1 put x2 put x3 put x4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (Function x1 x2) 1 -> do x1 <- get x2 <- get return (TyDecl x1 x2) -- Operator isn't written, don't read 3 -> do x1 <- get x2 <- get x3 <- get -- x4 <- get -- x3 <- get always [] x5 <- get return (CaseOp x1 x2 x3 [] [] x5) _ -> error "Corrupted binary data for Def" instance Binary Accessibility where put x = case x of Public -> putWord8 0 Frozen -> putWord8 1 Private -> putWord8 2 Hidden -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Public 1 -> return Frozen 2 -> return Private 3 -> return Hidden _ -> error "Corrupted binary data for Accessibility" safeToEnum :: (Enum a, Bounded a, Integral int) => String -> int -> a safeToEnum label x' = result where x = fromIntegral x' result | x < fromEnum (minBound `asTypeOf` result) || x > fromEnum (maxBound `asTypeOf` result) = error $ label ++ ": corrupted binary representation in IBC" | otherwise = toEnum x instance Binary PReason where put x = case x of Other x1 -> do putWord8 0 put x1 Itself -> putWord8 1 NotCovering -> putWord8 2 NotPositive -> putWord8 3 Mutual x1 -> do putWord8 4 put x1 NotProductive -> putWord8 5 BelieveMe -> putWord8 6 UseUndef x1 -> do putWord8 7 put x1 ExternalIO -> putWord8 8 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Other x1) 1 -> return Itself 2 -> return NotCovering 3 -> return NotPositive 4 -> do x1 <- get return (Mutual x1) 5 -> return NotProductive 6 -> return BelieveMe 7 -> do x1 <- get return (UseUndef x1) 8 -> return ExternalIO _ -> error "Corrupted binary data for PReason" instance Binary Totality where put x = case x of Total x1 -> do putWord8 0 put x1 Partial x1 -> do putWord8 1 put x1 Unchecked -> do putWord8 2 Productive -> do putWord8 3 Generated -> do putWord8 4 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Total x1) 1 -> do x1 <- get return (Partial x1) 2 -> return Unchecked 3 -> return Productive 4 -> return Generated _ -> error "Corrupted binary data for Totality" instance Binary MetaInformation where put x = case x of EmptyMI -> do putWord8 0 DataMI x1 -> do putWord8 1 put x1 get = do i <- getWord8 case i of 0 -> return EmptyMI 1 -> do x1 <- get return (DataMI x1) _ -> error "Corrupted binary data for MetaInformation" instance Binary DataOpt where put x = case x of Codata -> putWord8 0 DefaultEliminator -> putWord8 1 DataErrRev -> putWord8 2 DefaultCaseFun -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Codata 1 -> return DefaultEliminator 2 -> return DataErrRev 3 -> return DefaultCaseFun _ -> error "Corrupted binary data for DataOpt" instance Binary FnOpt where put x = case x of Inlinable -> putWord8 0 TotalFn -> putWord8 1 Dictionary -> putWord8 2 AssertTotal -> putWord8 3 Specialise x -> do putWord8 4 put x AllGuarded -> putWord8 5 PartialFn -> putWord8 6 Implicit -> putWord8 7 Reflection -> putWord8 8 ErrorHandler -> putWord8 9 ErrorReverse -> putWord8 10 CoveringFn -> putWord8 11 NoImplicit -> putWord8 12 Constructor -> putWord8 13 CExport x1 -> do putWord8 14 put x1 AutoHint -> putWord8 15 PEGenerated -> putWord8 16 StaticFn -> putWord8 17 OverlappingDictionary -> putWord8 18 ErrorReduce -> putWord8 20 get = do i <- getWord8 case i of 0 -> return Inlinable 1 -> return TotalFn 2 -> return Dictionary 3 -> return AssertTotal 4 -> do x <- get return (Specialise x) 5 -> return AllGuarded 6 -> return PartialFn 7 -> return Implicit 8 -> return Reflection 9 -> return ErrorHandler 10 -> return ErrorReverse 11 -> return CoveringFn 12 -> return NoImplicit 13 -> return Constructor 14 -> do x1 <- get return $ CExport x1 15 -> return AutoHint 16 -> return PEGenerated 17 -> return StaticFn 18 -> return OverlappingDictionary 20 -> return ErrorReduce _ -> error "Corrupted binary data for FnOpt" instance Binary Fixity where put x = case x of Infixl x1 -> do putWord8 0 put x1 Infixr x1 -> do putWord8 1 put x1 InfixN x1 -> do putWord8 2 put x1 PrefixN x1 -> do putWord8 3 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Infixl x1) 1 -> do x1 <- get return (Infixr x1) 2 -> do x1 <- get return (InfixN x1) 3 -> do x1 <- get return (PrefixN x1) _ -> error "Corrupted binary data for Fixity" instance Binary FixDecl where put (Fix x1 x2) = do put x1 put x2 get = do x1 <- get x2 <- get return (Fix x1 x2) instance Binary ArgOpt where put x = case x of HideDisplay -> putWord8 0 InaccessibleArg -> putWord8 1 AlwaysShow -> putWord8 2 UnknownImp -> putWord8 3 get = do i <- getWord8 case i of 0 -> return HideDisplay 1 -> return InaccessibleArg 2 -> return AlwaysShow 3 -> return UnknownImp _ -> error "Corrupted binary data for Static" instance Binary Static where put x = case x of Static -> putWord8 0 Dynamic -> putWord8 1 get = do i <- getWord8 case i of 0 -> return Static 1 -> return Dynamic _ -> error "Corrupted binary data for Static" instance Binary Plicity where put x = case x of Imp x1 x2 x3 x4 _ x5 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 Exp x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 Constraint x1 x2 x3 -> do putWord8 2 put x1 put x2 put x3 TacImp x1 x2 x3 x4 -> do putWord8 3 put x1 put x2 put x3 put x4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (Imp x1 x2 x3 x4 False x5) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (Exp x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get return (Constraint x1 x2 x3) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (TacImp x1 x2 x3 x4) _ -> error "Corrupted binary data for Plicity" instance (Binary t) => Binary (PDecl' t) where put x = case x of PFix x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 PTy x1 x2 x3 x4 x5 x6 x7 x8 -> do putWord8 1 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 PClauses x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PData x1 x2 x3 x4 x5 x6 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 put x6 PParams x1 x2 x3 -> do putWord8 4 put x1 put x2 put x3 PNamespace x1 x2 x3 -> do putWord8 5 put x1 put x2 put x3 PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 -> do putWord8 6 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 PInterface x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 -> do putWord8 7 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 PImplementation x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 -> do putWord8 8 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 put x13 put x14 put x15 PDSL x1 x2 -> do putWord8 9 put x1 put x2 PCAF x1 x2 x3 -> do putWord8 10 put x1 put x2 put x3 PMutual x1 x2 -> do putWord8 11 put x1 put x2 PPostulate x1 x2 x3 x4 x5 x6 x7 x8 -> do putWord8 12 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 PSyntax x1 x2 -> do putWord8 13 put x1 put x2 PDirective x1 -> error "Cannot serialize PDirective" PProvider x1 x2 x3 x4 x5 x6 -> do putWord8 15 put x1 put x2 put x3 put x4 put x5 put x6 PTransform x1 x2 x3 x4 -> do putWord8 16 put x1 put x2 put x3 put x4 PRunElabDecl x1 x2 x3 -> do putWord8 17 put x1 put x2 put x3 POpenInterfaces x1 x2 x3 -> do putWord8 18 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (PFix x1 x2 x3) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (PTy x1 x2 x3 x4 x5 x6 x7 x8) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PClauses x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PData x1 x2 x3 x4 x5 x6) 4 -> do x1 <- get x2 <- get x3 <- get return (PParams x1 x2 x3) 5 -> do x1 <- get x2 <- get x3 <- get return (PNamespace x1 x2 x3) 6 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get return (PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 7 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get return (PInterface x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 8 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get x13 <- get x14 <- get x15 <- get return (PImplementation x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15) 9 -> do x1 <- get x2 <- get return (PDSL x1 x2) 10 -> do x1 <- get x2 <- get x3 <- get return (PCAF x1 x2 x3) 11 -> do x1 <- get x2 <- get return (PMutual x1 x2) 12 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (PPostulate x1 x2 x3 x4 x5 x6 x7 x8) 13 -> do x1 <- get x2 <- get return (PSyntax x1 x2) 14 -> do error "Cannot deserialize PDirective" 15 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PProvider x1 x2 x3 x4 x5 x6) 16 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PTransform x1 x2 x3 x4) 17 -> do x1 <- get x2 <- get x3 <- get return (PRunElabDecl x1 x2 x3) 18 -> do x1 <- get x2 <- get x3 <- get return (POpenInterfaces x1 x2 x3) _ -> error "Corrupted binary data for PDecl'" instance Binary t => Binary (ProvideWhat' t) where put (ProvTerm x1 x2) = do putWord8 0 put x1 put x2 put (ProvPostulate x1) = do putWord8 1 put x1 get = do y <- getWord8 case y of 0 -> do x1 <- get x2 <- get return (ProvTerm x1 x2) 1 -> do x1 <- get return (ProvPostulate x1) _ -> error "Corrupted binary data for ProvideWhat" instance Binary Using where put (UImplicit x1 x2) = do putWord8 0; put x1; put x2 put (UConstraint x1 x2) = do putWord8 1; put x1; put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get; x2 <- get; return (UImplicit x1 x2) 1 -> do x1 <- get; x2 <- get; return (UConstraint x1 x2) _ -> error "Corrupted binary data for Using" instance Binary SyntaxInfo where put (Syn x1 x2 x3 x4 _ _ x5 x6 x7 _ _ x8 _ _ _) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (Syn x1 x2 x3 x4 [] id x5 x6 x7 Nothing 0 x8 0 True True) instance (Binary t) => Binary (PClause' t) where put x = case x of PClause x1 x2 x3 x4 x5 x6 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 put x6 PWith x1 x2 x3 x4 x5 x6 x7 -> do putWord8 1 put x1 put x2 put x3 put x4 put x5 put x6 put x7 PClauseR x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PWithR x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PClause x1 x2 x3 x4 x5 x6) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get return (PWith x1 x2 x3 x4 x5 x6 x7) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PClauseR x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PWithR x1 x2 x3 x4 x5) _ -> error "Corrupted binary data for PClause'" instance (Binary t) => Binary (PData' t) where put x = case x of PDatadecl x1 x2 x3 x4 -> do putWord8 0 put x1 put x2 put x3 put x4 PLaterdecl x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PDatadecl x1 x2 x3 x4) 1 -> do x1 <- get x2 <- get x3 <- get return (PLaterdecl x1 x2 x3) _ -> error "Corrupted binary data for PData'" instance Binary PunInfo where put x = case x of TypeOrTerm -> putWord8 0 IsType -> putWord8 1 IsTerm -> putWord8 2 get = do i <- getWord8 case i of 0 -> return TypeOrTerm 1 -> return IsType 2 -> return IsTerm _ -> error "Corrupted binary data for PunInfo" instance Binary PTerm where put x = case x of PQuote x1 -> do putWord8 0 put x1 PRef x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 PInferRef x1 x2 x3 -> do putWord8 2 put x1 put x2 put x3 PPatvar x1 x2 -> do putWord8 3 put x1 put x2 PLam x1 x2 x3 x4 x5 -> do putWord8 4 put x1 put x2 put x3 put x4 put x5 PPi x1 x2 x3 x4 x5 -> do putWord8 5 put x1 put x2 put x3 put x4 put x5 PLet x1 x2 x3 x4 x5 x6 -> do putWord8 6 put x1 put x2 put x3 put x4 put x5 put x6 PTyped x1 x2 -> do putWord8 7 put x1 put x2 PAppImpl x1 x2 -> error "PAppImpl in final term" PApp x1 x2 x3 -> do putWord8 8 put x1 put x2 put x3 PAppBind x1 x2 x3 -> do putWord8 9 put x1 put x2 put x3 PMatchApp x1 x2 -> do putWord8 10 put x1 put x2 PCase x1 x2 x3 -> do putWord8 11 put x1 put x2 put x3 PTrue x1 x2 -> do putWord8 12 put x1 put x2 PResolveTC x1 -> do putWord8 15 put x1 PRewrite x1 x2 x3 x4 x5 -> do putWord8 17 put x1 put x2 put x3 put x4 put x5 PPair x1 x2 x3 x4 x5 -> do putWord8 18 put x1 put x2 put x3 put x4 put x5 PDPair x1 x2 x3 x4 x5 x6 -> do putWord8 19 put x1 put x2 put x3 put x4 put x5 put x6 PAlternative x1 x2 x3 -> do putWord8 20 put x1 put x2 put x3 PHidden x1 -> do putWord8 21 put x1 PType x1 -> do putWord8 22 put x1 PGoal x1 x2 x3 x4 -> do putWord8 23 put x1 put x2 put x3 put x4 PConstant x1 x2 -> do putWord8 24 put x1 put x2 Placeholder -> putWord8 25 PDoBlock x1 -> do putWord8 26 put x1 PIdiom x1 x2 -> do putWord8 27 put x1 put x2 PMetavar x1 x2 -> do putWord8 29 put x1 put x2 PProof x1 -> do putWord8 30 put x1 PTactics x1 -> do putWord8 31 put x1 PImpossible -> putWord8 33 PCoerced x1 -> do putWord8 34 put x1 PUnifyLog x1 -> do putWord8 35 put x1 PNoImplicits x1 -> do putWord8 36 put x1 PDisamb x1 x2 -> do putWord8 37 put x1 put x2 PUniverse x1 x2 -> do putWord8 38 put x1 put x2 PRunElab x1 x2 x3 -> do putWord8 39 put x1 put x2 put x3 PAs x1 x2 x3 -> do putWord8 40 put x1 put x2 put x3 PElabError x1 -> do putWord8 41 put x1 PQuasiquote x1 x2 -> do putWord8 42 put x1 put x2 PUnquote x1 -> do putWord8 43 put x1 PQuoteName x1 x2 x3 -> do putWord8 44 put x1 put x2 put x3 PIfThenElse x1 x2 x3 x4 -> do putWord8 45 put x1 put x2 put x3 put x4 PConstSugar x1 x2 -> do putWord8 46 put x1 put x2 PWithApp x1 x2 x3 -> do putWord8 47 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get return (PQuote x1) 1 -> do x1 <- get x2 <- get x3 <- get return (PRef x1 x2 x3) 2 -> do x1 <- get x2 <- get x3 <- get return (PInferRef x1 x2 x3) 3 -> do x1 <- get x2 <- get return (PPatvar x1 x2) 4 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PLam x1 x2 x3 x4 x5) 5 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PPi x1 x2 x3 x4 x5) 6 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PLet x1 x2 x3 x4 x5 x6) 7 -> do x1 <- get x2 <- get return (PTyped x1 x2) 8 -> do x1 <- get x2 <- get x3 <- get return (PApp x1 x2 x3) 9 -> do x1 <- get x2 <- get x3 <- get return (PAppBind x1 x2 x3) 10 -> do x1 <- get x2 <- get return (PMatchApp x1 x2) 11 -> do x1 <- get x2 <- get x3 <- get return (PCase x1 x2 x3) 12 -> do x1 <- get x2 <- get return (PTrue x1 x2) 15 -> do x1 <- get return (PResolveTC x1) 17 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PRewrite x1 x2 x3 x4 x5) 18 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PPair x1 x2 x3 x4 x5) 19 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PDPair x1 x2 x3 x4 x5 x6) 20 -> do x1 <- get x2 <- get x3 <- get return (PAlternative x1 x2 x3) 21 -> do x1 <- get return (PHidden x1) 22 -> do x1 <- get return (PType x1) 23 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PGoal x1 x2 x3 x4) 24 -> do x1 <- get x2 <- get return (PConstant x1 x2) 25 -> return Placeholder 26 -> do x1 <- get return (PDoBlock x1) 27 -> do x1 <- get x2 <- get return (PIdiom x1 x2) 29 -> do x1 <- get x2 <- get return (PMetavar x1 x2) 30 -> do x1 <- get return (PProof x1) 31 -> do x1 <- get return (PTactics x1) 33 -> return PImpossible 34 -> do x1 <- get return (PCoerced x1) 35 -> do x1 <- get return (PUnifyLog x1) 36 -> do x1 <- get return (PNoImplicits x1) 37 -> do x1 <- get x2 <- get return (PDisamb x1 x2) 38 -> do x1 <- get x2 <- get return (PUniverse x1 x2) 39 -> do x1 <- get x2 <- get x3 <- get return (PRunElab x1 x2 x3) 40 -> do x1 <- get x2 <- get x3 <- get return (PAs x1 x2 x3) 41 -> do x1 <- get return (PElabError x1) 42 -> do x1 <- get x2 <- get return (PQuasiquote x1 x2) 43 -> do x1 <- get return (PUnquote x1) 44 -> do x1 <- get x2 <- get x3 <- get return (PQuoteName x1 x2 x3) 45 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PIfThenElse x1 x2 x3 x4) 46 -> do x1 <- get x2 <- get return (PConstSugar x1 x2) 47 -> do x1 <- get x2 <- get x3 <- get return (PWithApp x1 x2 x3) _ -> error "Corrupted binary data for PTerm" instance Binary PAltType where put x = case x of ExactlyOne x1 -> do putWord8 0 put x1 FirstSuccess -> putWord8 1 TryImplicit -> putWord8 2 get = do i <- getWord8 case i of 0 -> do x1 <- get return (ExactlyOne x1) 1 -> return FirstSuccess 2 -> return TryImplicit _ -> error "Corrupted binary data for PAltType" instance (Binary t) => Binary (PTactic' t) where put x = case x of Intro x1 -> do putWord8 0 put x1 Focus x1 -> do putWord8 1 put x1 Refine x1 x2 -> do putWord8 2 put x1 put x2 Rewrite x1 -> do putWord8 3 put x1 LetTac x1 x2 -> do putWord8 4 put x1 put x2 Exact x1 -> do putWord8 5 put x1 Compute -> putWord8 6 Trivial -> putWord8 7 Solve -> putWord8 8 Attack -> putWord8 9 ProofState -> putWord8 10 ProofTerm -> putWord8 11 Undo -> putWord8 12 Try x1 x2 -> do putWord8 13 put x1 put x2 TSeq x1 x2 -> do putWord8 14 put x1 put x2 Qed -> putWord8 15 ApplyTactic x1 -> do putWord8 16 put x1 Reflect x1 -> do putWord8 17 put x1 Fill x1 -> do putWord8 18 put x1 Induction x1 -> do putWord8 19 put x1 ByReflection x1 -> do putWord8 20 put x1 ProofSearch x1 x2 x3 x4 x5 x6 -> do putWord8 21 put x1 put x2 put x3 put x4 put x5 put x6 DoUnify -> putWord8 22 CaseTac x1 -> do putWord8 23 put x1 SourceFC -> putWord8 24 Intros -> putWord8 25 Equiv x1 -> do putWord8 26 put x1 Claim x1 x2 -> do putWord8 27 put x1 put x2 Unfocus -> putWord8 28 MatchRefine x1 -> do putWord8 29 put x1 LetTacTy x1 x2 x3 -> do putWord8 30 put x1 put x2 put x3 TCImplementation -> putWord8 31 GoalType x1 x2 -> do putWord8 32 put x1 put x2 TCheck x1 -> do putWord8 33 put x1 TEval x1 -> do putWord8 34 put x1 TDocStr x1 -> do putWord8 35 put x1 TSearch x1 -> do putWord8 36 put x1 Skip -> putWord8 37 TFail x1 -> do putWord8 38 put x1 Abandon -> putWord8 39 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Intro x1) 1 -> do x1 <- get return (Focus x1) 2 -> do x1 <- get x2 <- get return (Refine x1 x2) 3 -> do x1 <- get return (Rewrite x1) 4 -> do x1 <- get x2 <- get return (LetTac x1 x2) 5 -> do x1 <- get return (Exact x1) 6 -> return Compute 7 -> return Trivial 8 -> return Solve 9 -> return Attack 10 -> return ProofState 11 -> return ProofTerm 12 -> return Undo 13 -> do x1 <- get x2 <- get return (Try x1 x2) 14 -> do x1 <- get x2 <- get return (TSeq x1 x2) 15 -> return Qed 16 -> do x1 <- get return (ApplyTactic x1) 17 -> do x1 <- get return (Reflect x1) 18 -> do x1 <- get return (Fill x1) 19 -> do x1 <- get return (Induction x1) 20 -> do x1 <- get return (ByReflection x1) 21 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (ProofSearch x1 x2 x3 x4 x5 x6) 22 -> return DoUnify 23 -> do x1 <- get return (CaseTac x1) 24 -> return SourceFC 25 -> return Intros 26 -> do x1 <- get return (Equiv x1) 27 -> do x1 <- get x2 <- get return (Claim x1 x2) 28 -> return Unfocus 29 -> do x1 <- get return (MatchRefine x1) 30 -> do x1 <- get x2 <- get x3 <- get return (LetTacTy x1 x2 x3) 31 -> return TCImplementation 32 -> do x1 <- get x2 <- get return (GoalType x1 x2) 33 -> do x1 <- get return (TCheck x1) 34 -> do x1 <- get return (TEval x1) 35 -> do x1 <- get return (TDocStr x1) 36 -> do x1 <- get return (TSearch x1) 37 -> return Skip 38 -> do x1 <- get return (TFail x1) 39 -> return Abandon _ -> error "Corrupted binary data for PTactic'" instance (Binary t) => Binary (PDo' t) where put x = case x of DoExp x1 x2 -> do putWord8 0 put x1 put x2 DoBind x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 DoBindP x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 DoLet x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 DoLetP x1 x2 x3 -> do putWord8 4 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (DoExp x1 x2) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (DoBind x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (DoBindP x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (DoLet x1 x2 x3 x4 x5) 4 -> do x1 <- get x2 <- get x3 <- get return (DoLetP x1 x2 x3) _ -> error "Corrupted binary data for PDo'" instance (Binary t) => Binary (PArg' t) where put x = case x of PImp x1 x2 x3 x4 x5 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 PExp x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 PConstraint x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PTacImplicit x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PImp x1 x2 x3 x4 x5) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PExp x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PConstraint x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PTacImplicit x1 x2 x3 x4 x5) _ -> error "Corrupted binary data for PArg'" instance Binary InterfaceInfo where put (CI x1 x2 x3 x4 x5 x6 x7 _ x8) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (CI x1 x2 x3 x4 x5 x6 x7 [] x8) instance Binary RecordInfo where put (RI x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (RI x1 x2 x3) instance Binary OptInfo where put (Optimise x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (Optimise x1 x2 x3) instance Binary FnInfo where put (FnInfo x1) = put x1 get = do x1 <- get return (FnInfo x1) instance Binary TypeInfo where put (TI x1 x2 x3 x4 x5 x6) = do put x1 put x2 put x3 put x4 put x5 put x6 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (TI x1 x2 x3 x4 x5 x6) instance Binary SynContext where put x = case x of PatternSyntax -> putWord8 0 TermSyntax -> putWord8 1 AnySyntax -> putWord8 2 get = do i <- getWord8 case i of 0 -> return PatternSyntax 1 -> return TermSyntax 2 -> return AnySyntax _ -> error "Corrupted binary data for SynContext" instance Binary Syntax where put (Rule x1 x2 x3) = do putWord8 0 put x1 put x2 put x3 put (DeclRule x1 x2) = do putWord8 1 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (Rule x1 x2 x3) 1 -> do x1 <- get x2 <- get return (DeclRule x1 x2) _ -> error "Corrupted binary data for Syntax" instance (Binary t) => Binary (DSL' t) where put (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get return (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9) instance Binary SSymbol where put x = case x of Keyword x1 -> do putWord8 0 put x1 Symbol x1 -> do putWord8 1 put x1 Expr x1 -> do putWord8 2 put x1 SimpleExpr x1 -> do putWord8 3 put x1 Binding x1 -> do putWord8 4 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Keyword x1) 1 -> do x1 <- get return (Symbol x1) 2 -> do x1 <- get return (Expr x1) 3 -> do x1 <- get return (SimpleExpr x1) 4 -> do x1 <- get return (Binding x1) _ -> error "Corrupted binary data for SSymbol" instance Binary Codegen where put x = case x of Via ir str -> do putWord8 0 put ir put str Bytecode -> putWord8 1 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (Via x1 x2) 1 -> return Bytecode _ -> error "Corrupted binary data for Codegen" instance Binary IRFormat where put x = case x of IBCFormat -> putWord8 0 JSONFormat -> putWord8 1 get = do i <- getWord8 case i of 0 -> return IBCFormat 1 -> return JSONFormat _ -> error "Corrupted binary data for IRFormat"
FranklinChen/Idris-dev
src/Idris/IBC.hs
bsd-3-clause
102,681
0
21
56,796
28,070
12,890
15,180
2,461
17
{-# LANGUAGE BangPatterns, DeriveFunctor #-} ----------------------------------------------------------------------------- -- | -- Module : Call.Data.Wave -- Copyright : (c) Fumiaki Kinoshita 2014 -- License : BSD3 -- -- Maintainer : Fumiaki Kinoshita <[email protected]> -- Stability : experimental -- Portability : non-portable -- ----------------------------------------------------------------------------- module Data.Audio ( Source(..), Sample(..), Stereo, Time, readWAVE ) where import Data.WAVE import Linear import Control.Monad.IO.Class import qualified Data.Vector.Unboxed as V import GHC.Float import Data.Monoid import Control.Applicative type Time = Float type Stereo = V2 Float newtype Source a = Source (Time -> a) deriving Functor instance Applicative Source where pure a = Source (const a) Source f <*> Source g = Source (f <*> g) instance Num a => Monoid (Source a) where mempty = pure 0 mappend = liftA2 (+) readWAVE :: MonadIO m => FilePath -> m (Sample Stereo) readWAVE path = liftIO $ do WAVE h ss <- getWAVEFile path let vec = V.fromList (map fr ss) rate = fromIntegral (waveFrameRate h) !dur = fromIntegral (V.length vec) / rate sample t | t < 0 || t >= dur - (1/rate) = zero | otherwise = vec V.! round (t * rate) return $ Sample dur (Source sample) where fr [a, b] = V2 (double2Float $ sampleToDouble a) (double2Float $ sampleToDouble b) fr _ = zero data Sample a = Sample { sampleLength :: Time ,sampleSource :: Source a} -- TODO: Lazy processing
fumieval/audiovisual
src/Data/Audio.hs
bsd-3-clause
1,573
0
17
323
472
254
218
36
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS -Wall #-} module Main (main) where import Control.Monad (foldM) import Control.Monad.Trans (liftIO, MonadIO) import qualified Data.ByteString.Char8 as C import Data.Attoparsec.Iteratee import Data.ByteString (ByteString) import Data.Default import qualified Data.IntMap as IM import Data.Iteratee (Iteratee, Enumeratee) import qualified Data.Iteratee as I import qualified Data.Iteratee.IO as I import Data.ZoomCache import Data.ZoomCache.Dump import System.Console.GetOpt import UI.Command import HeapScope.HeapProfile import HeapScope.Parse import HeapScope.Scope import HeapScope.ZoomCache () ------------------------------------------------------------ data Config = Config { noRaw :: Bool , wmLevel :: Int , track :: TrackNo , spec :: TrackSpec } instance Default Config where def = defConfig defConfig :: Config defConfig = Config { noRaw = False , wmLevel = 1024 , track = 1 , spec = def { specDeltaEncode = False , specZlibCompress = False , specName = "hp" } } data Option = NoRaw | Watermark String | Track String | ZLib | Label String deriving (Eq) options :: [OptDescr Option] options = genOptions genOptions :: [OptDescr Option] genOptions = [ Option ['z'] ["no-raw"] (NoArg NoRaw) "Do NOT include raw data in the output" , Option ['w'] ["watermark"] (ReqArg Watermark "watermark") "Set high-watermark level" , Option ['t'] ["track"] (ReqArg Track "trackNo") "Set or select track number" , Option ['Z'] ["zlib"] (NoArg ZLib) "Zlib-compress data" , Option ['l'] ["label"] (ReqArg Label "label") "Set track label" ] processArgs :: [String] -> IO (Config, [String]) processArgs args = do case getOpt RequireOrder options args of (opts, args', [] ) -> do config <- processConfig def opts return (config, args') (_, _, _:_) -> return (def, args) processConfig :: Config -> [Option] -> IO Config processConfig = foldM processOneOption where processOneOption config NoRaw = do return $ config {noRaw = True} processOneOption config (Watermark s) = do return $ config {wmLevel = read s} processOneOption config (Track s) = do return $ config {track = read s} processOneOption config ZLib = do return $ config { spec = (spec config){specZlibCompress = True} } processOneOption config (Label s) = do return $ config { spec = (spec config){specName = C.pack s} } ---------------------------------------------------------------------- hszcGen :: Command () hszcGen = defCmd { cmdName = "gen" , cmdHandler = hszcGenHandler , cmdCategory = "Writing" , cmdShortDesc = "Generate heapscope zoom-cache data" , cmdExamples = [("Read foo.hp, generating a file called foo.hp.zoom", "foo.hp")] } hszcGenHandler :: App () () hszcGenHandler = do (config, filenames) <- liftIO . processArgs =<< appArgs liftIO $ mapM_ (hszcWriteFile config) filenames hszcWriteFile :: Config -> FilePath -> IO () hszcWriteFile Config{..} path = withFileWrite trackMap Nothing True iter zpath where iter = I.run =<< I.enumFileRandom 102400 path (I.joinI $ (hpEnum (emptyHeapProfile) hpDo)) zpath = path ++ ".zoom" trackMap = IM.singleton track (setCodec (undefined :: HeapProfile) spec) hpDo :: Iteratee [HeapProfile] ZoomW () hpDo = I.mapM_ (\hp -> maybe (return ()) (\ts -> write 1 (TS ts, hp)) (hpSampleStart hp)) hpEnum :: MonadIO m => HeapProfile -> Enumeratee ByteString [HeapProfile] m a hpEnum = I.unfoldConvStream hpIter hpIter :: MonadIO m => HeapProfile -> Iteratee ByteString m (HeapProfile, [HeapProfile]) hpIter = parserToIteratee . hpParse ------------------------------------------------------------ hszcInfo :: Command () hszcInfo = defCmd { cmdName = "info" , cmdHandler = hszcInfoHandler , cmdCategory = "Reading" , cmdShortDesc = "Display basic info about a heapscope zoom-cache file" , cmdExamples = [("Display info about foo.hp.zoom", "foo.hp.zoom")] } hszcInfoHandler :: App () () hszcInfoHandler = mapM_ (liftIO . zoomInfoFile hsIdentifiers) =<< appArgs ------------------------------------------------------------ hszcDump :: Command () hszcDump = defCmd { cmdName = "dump" , cmdHandler = hszcDumpHandler , cmdCategory = "Reading" , cmdShortDesc = "Read zoom-cache data" , cmdExamples = [("Yo", "")] } hszcDumpHandler :: App () () hszcDumpHandler = do (config, filenames) <- liftIO . processArgs =<< appArgs mapM_ (liftIO . zoomDumpFile hsIdentifiers (track config)) filenames ------------------------------------------------------------ hszcSummary :: Command () hszcSummary = defCmd { cmdName = "summary" , cmdHandler = hszcSummaryHandler , cmdCategory = "Reading" , cmdShortDesc = "Read zoom-cache summary data" , cmdExamples = [("Read summary level 3 from foo.zoom", "3 foo.zoom")] } hszcSummaryHandler :: App () () hszcSummaryHandler = do (config, filenames) <- liftIO . processArgs =<< appArgs liftIO . (f (track config)) $ filenames where f trackNo (lvl:paths) = mapM_ (zoomDumpSummaryLevel (read lvl) hsIdentifiers trackNo) paths f _ _ = putStrLn "Usage: zoom-cache summary n file.zoom" ------------------------------------------------------------ -- The Application -- hszc :: Application () () hszc = def { appName = "zoom" , appVersion = "0.1" , appAuthors = ["Conrad Parker"] , appBugEmail = "[email protected]" , appShortDesc = "Trivial heapscope zoom-cache inspection tools" , appLongDesc = longDesc , appCategories = ["Reading", "Writing"] , appSeeAlso = [""] , appProject = "HeapScope" , appCmds = [ hszcGen , hszcInfo , hszcDump , hszcSummary ] } longDesc :: String longDesc = "Manipulate heapscope zoom-cache files" ------------------------------------------------------------ -- Main -- main :: IO () main = appMain hszc
kfish/heapscope
tools/heapscope-zc.hs
bsd-3-clause
6,617
2
15
1,730
1,694
957
737
153
5
{-# LANGUAGE RecordWildCards #-} module Passman.Engine.KeyDerivation.PBKDF2 ( PBKDF2WithHmacSHA1(..) , PBKDF2WithHmacSHA256(..) ) where import Crypto.Hash.Algorithms (HashAlgorithm, SHA1(..), SHA256(..)) import Crypto.KDF.PBKDF2 import Data.Semigroup ((<>)) import qualified Passman.Engine.ByteString as B import Passman.Engine.Errors import Passman.Engine.KeyDerivation.Class import Passman.Engine.KeyDerivation.Internal newtype PBKDF2WithHmacSHA1 = PBKDF2WithHmacSHA1 Int deriving (Show, Eq) instance KDF PBKDF2WithHmacSHA1 where deriveKey (PBKDF2WithHmacSHA1 baseIterations) = deriveKey' SHA1 baseIterations maxSize (PBKDF2WithHmacSHA1 _) = Nothing newtype PBKDF2WithHmacSHA256 = PBKDF2WithHmacSHA256 Int deriving (Show, Eq) instance KDF PBKDF2WithHmacSHA256 where deriveKey (PBKDF2WithHmacSHA256 baseIterations) = deriveKey' SHA256 baseIterations maxSize (PBKDF2WithHmacSHA256 _) = Nothing baseSalt :: B.ByteString baseSalt = B.pack [ 0x78, 0x94, 0xad, 0xf8, 0x2f, 0x7b, 0x07, 0x11, 0x85, 0xf9, 0x44, 0xbe, 0x25, 0x3b, 0x16, 0x57 ] deriveKey' :: HashAlgorithm a => a -> Int -> Parameters -> Key -> Salt -> Either EngineError B.ByteString deriveKey' alg baseIterations Parameters{..} key salt = do checkRequest key' salt' iterCounts return $ generate prf params key' (baseSalt <> salt') where params = Parameters (baseIterations + iterCounts) outputLength prf = prfHMAC alg key' = unwrapKey key salt' = unwrapSalt salt
chwthewke/passman-hs
src/Passman/Engine/KeyDerivation/PBKDF2.hs
bsd-3-clause
1,614
0
12
356
419
238
181
31
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} module System.Nemesis.Titan where import System.Nemesis.Env import System.Nemesis (Unit) import Air.Env hiding (mod) import Prelude () import Air.TH import Air.Data.Record.SimpleLabel (get, set, mod, label) import qualified Data.ByteString.Char8 as B import qualified Data.UUID as UUID import System.Directory import System.Random import System.FilePath import System.Exit (ExitCode(..)) import qualified Control.Exception as E import Control.Monad (forever) import Test.Hspec import Text.StringTemplate import Text.Printf import Data.Maybe (fromMaybe) angel_template :: StringTemplate String angel_template = newSTMP - [here| server { exec = "runghc Nemesis $project_name$/run" stdout = "/dev/stdout" stderr = "/dev/stderr" delay = 0 } code-reload { exec = "runghc Nemesis $project_name$/guard" stdout = "/dev/stdout" stderr = "/dev/stderr" delay = 0 } |] -- Live mode without auto recompile, e.g. `runghc Nemesis compile-and-kill` is run inside git-post-receive-hook angel_live_template :: StringTemplate String angel_live_template = newSTMP - [here| server { exec = "runghc Nemesis $project_name$/run" stdout = "/dev/stdout" stderr = "/dev/stderr" delay = 0 } |] guard_template :: StringTemplate String guard_template = newSTMP - [here| guard :shell do event_time = Time.now update_time = Time.now update_interval = 0.1 watch(%r{^src/.+hs\$}) do |m| puts "Changed #{m[0]}" event_time = Time.now end # compile at most once for every \$update_interval seconds Thread.new do while true sleep update_interval if event_time > update_time update_time = Time.now system("runghc Nemesis $project_name$/compile-and-kill") end end end end |] haskell_template :: StringTemplate String haskell_template = newSTMP - [here| module Main where import System.Nemesis.Titan import Test.Hspec spec :: IO () spec = hspec \$ do describe "$project_name$" \$ do it "should run spec" True main = do with_spec spec halt |] titan_spec :: IO () titan_spec = hspec - do describe "Titan" - do it "should run spec" True it "should use templates" - do let text = render - setAttribute "project_name" "Main" angel_template -- puts text text `shouldSatisfy` (null > not) data Config = Config { pid_name :: String , bin_directory :: String , config_directory :: String , haskell_source_directory :: String , project_name :: String , file_name :: String , ghc_arg_string :: String , ghc_default_arg_string :: String , guard_arg_string :: String , guard_default_arg_string :: String } deriving (Show, Eq) mkLabel ''Config instance Default Config where def = Config { pid_name = "uuid.txt" , bin_directory = ".bin" , config_directory = "config" , haskell_source_directory = "src" , project_name = "Main" , file_name = "Main.hs" , ghc_arg_string = def , ghc_default_arg_string = "-threaded" , guard_arg_string = def , guard_default_arg_string = "--no-bundler-warning --no-interactions" } titan_with_config :: Config -> Unit titan_with_config config = do namespace (config.project_name) - do let _project_name = config.project_name config_project_name_directory = config.config_directory / _project_name angel_path = config_project_name_directory / "Angel.conf" angel_live_path = config_project_name_directory / "AngelLive.conf" guard_path = config_project_name_directory / "Guardfile" pid_directory = config.bin_directory / _project_name pid_path = pid_directory / config.pid_name haskell_source_path = config.haskell_source_directory / config.file_name desc "Initialize a Titan node" task "init" - io - do createDirectoryIfMissing True config_project_name_directory createDirectoryIfMissing True (config.haskell_source_directory) let angel_file_content = render - setAttribute "project_name" _project_name angel_template angel_live_file_content = render - setAttribute "project_name" _project_name angel_live_template guard_file_content = render - setAttribute "project_name" _project_name guard_template haskell_file_content = render - setAttribute "project_name" _project_name haskell_template let { write_if_not_exist file_path str = do file_exist <- doesFileExist file_path if not - file_exist then B.writeFile file_path - B.pack str else do puts - file_path + " already exists!" return () } write_if_not_exist angel_path angel_file_content write_if_not_exist angel_live_path angel_live_file_content write_if_not_exist guard_path guard_file_content write_if_not_exist haskell_source_path haskell_file_content let { get_and_create_if_missing_upid = do createDirectoryIfMissing True pid_directory pid_exist <- doesFileExist pid_path if pid_exist then do uuid <- B.readFile pid_path ^ B.unpack return uuid else do uuid <- randomIO ^ UUID.toString puts - "Created UPID: " + uuid B.writeFile pid_path - uuid.B.pack return - uuid } let { get_bin = do uuid <- get_and_create_if_missing_upid return - pid_directory / uuid } desc "Start the Titan managed process" task "titan:uuid compile" - do sh - "angel " + angel_path desc "Start the Titan managed process for deployment (no auto recompile)" task "titan-live:uuid compile" - do sh - "angel " + angel_live_path desc "Create a uuid for this process if not already exist" task "uuid" - do io - void - get_and_create_if_missing_upid desc "Compile the binary" task "compile" - do bin <- get_bin let { cmd = printf "ghc --make -i%s %s %s %s -o %s" (config.haskell_source_directory) (config.ghc_default_arg_string) (config.ghc_arg_string) haskell_source_path bin } -- puts cmd sh cmd desc "Start the process" task "run" - do bin <- get_bin sh - bin desc "Kill the process" task "kill" - do upid <- get_and_create_if_missing_upid sh - "killall -SIGTERM " + upid + "; true" desc "Compile and Kill" task "compile-and-kill: compile kill" - return () desc "Start the Guard process" task "guard" - do sh - printf "guard %s %s -G %s" (config.guard_default_arg_string) (config.guard_arg_string) guard_path -- shortcut let shortcut_task_name = printf "t:%s/titan" (config.project_name) shortcut_description = printf "Short task name for %s/titan" (config.project_name) desc shortcut_description task shortcut_task_name - return () titan :: String -> Unit titan _file_name = do let _project_name = _file_name.takeBaseName titan_with_config def {file_name = _file_name, project_name = _project_name} data MacAppArgs = MacAppArgs { derived_data_path :: String , scheme_name :: Maybe String , target_name :: String , frameworks :: [String] , mac_app_config :: Config , mac_app_project_name :: Maybe String , mac_app_file_name :: Maybe String } deriving (Show) mkLabel ''MacAppArgs default_mac_app_config :: Config default_mac_app_config = def.set __ghc_arg_string "-lobjc" instance Default MacAppArgs where def = MacAppArgs { derived_data_path = "DerivedData" , scheme_name = def , target_name = "Hello World Application" , frameworks = ["Cocoa"] , mac_app_config = default_mac_app_config , mac_app_project_name = def , mac_app_file_name = def } titan_mac_app :: MacAppArgs -> Unit titan_mac_app args = do let _target_name = args.target_name _dashed_target_name = _target_name.map (\x -> if x.is ' ' then '-' else x) _project_name = args.mac_app_project_name.fromMaybe _dashed_target_name _file_name = args.mac_app_file_name.fromMaybe (args.mac_app_config.file_name) _new_ghc_arg_string = args.frameworks.map ("-framework" +) .join " " _config = args.mac_app_config .set __file_name _file_name .set __project_name _project_name .mod __ghc_arg_string (_new_ghc_arg_string + " " +) titan_with_config _config let _scheme_name = args.scheme_name.fromMaybe _target_name _derived_data_path = args.derived_data_path namespace _project_name - do let config = _config haskell_source_path = config.haskell_source_directory / config.file_name bin = config.bin_directory / _project_name / "dummy_binary" task ("clean") - do sh - printf "rm -rf %s" _derived_data_path sh - printf "mkdir %s" _derived_data_path sh - printf "rm %s" bin desc "Compile the binary" task ("compile:uuid") - do let { cmd = printf "ghc --make -i%s %s %s %s -o %s" (config.haskell_source_directory) (config.ghc_default_arg_string) (config.ghc_arg_string) haskell_source_path bin } sh cmd let xcode_build_cmd = printf "cd .. && xcodebuild -scheme '%s' > /dev/null" _scheme_name sh xcode_build_cmd task ("kill") - do let osascript = printf "tell application \"%s\" to quit" _target_name sh - printf "osascript -e '%s'" (osascript :: String) task ("run") - do sh - printf "cd %s; find . -name '%s' -exec '{}' \\;" _derived_data_path _target_name -- shortcut let shortcut_task_name = printf "t:%s/kill %s/titan" _project_name _project_name shortcut_description = printf "%s/kill then %s/titan" _project_name _project_name desc shortcut_description task shortcut_task_name - return () -- Helpers safe_spec :: IO () -> IO ExitCode safe_spec spec = E.handle (\e -> return (e :: ExitCode)) - do spec return ExitSuccess halt :: IO () halt = forever - sleep (1 :: Double) with_spec :: IO () -> IO b -> IO () with_spec spec process = do exit_code <- safe_spec spec case exit_code of ExitSuccess -> do fork - process _ -> return () halt
nfjinjing/nemesis-titan
src/System/Nemesis/Titan.hs
bsd-3-clause
10,337
15
22
2,476
2,149
1,096
1,053
236
3
import System.Random.Mersenne import qualified Data.Judy as J import Control.Monad data Nilsxp data SymSxp main = do g <- getStdGen rs <- randoms g j <- J.new :: IO (J.JudyL Int) forM_ (take 1000000 rs) $ \n -> J.insert n 1 j v <- J.findMax j case v of Nothing -> print "Done." Just (k,_) -> print k
rosenbergdm/language-r
src/Language/R/sketches/judyex.hs
bsd-3-clause
349
1
11
106
152
74
78
-1
-1
module Data.Git.Common where import Bindings.Libgit2.Common import Data.Char pathListSeparator = chr c'GIT_PATH_LIST_SEPARATOR
iand675/hgit
Data/Git/Common.hs
bsd-3-clause
127
0
5
11
26
16
10
4
1
module Hydra.Utils.Impossible (impossible) where import qualified Language.Haskell.TH as TH impossible :: TH.ExpQ impossible = do loc <- TH.location let pos = (TH.loc_filename loc, fst (TH.loc_start loc), snd (TH.loc_start loc)) let message = "hydra: Impossbile happend at " ++ show pos return (TH.AppE (TH.VarE (TH.mkName "error")) (TH.LitE (TH.StringL message)))
giorgidze/Hydra
src/Hydra/Utils/Impossible.hs
bsd-3-clause
375
0
14
58
151
78
73
8
1
{-# LANGUAGE BangPatterns, FlexibleInstances, DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main where import Data.Binary import qualified MinimalNN import System.Environment import System.FilePath import System.Directory import Text.Printf import GHC.Generics (Generic) import Data.Typeable import qualified Data.Packed.Vector as HM import qualified Data.Packed.Matrix as HM import qualified Numeric.Container as HM import "hmatrix" Numeric.LinearAlgebra () import MyVectorType as V data TNetwork = TNetwork { weights :: ![HM.Matrix Double] , biases :: ![HM.Vector Double] } deriving (Show, Eq, Typeable, Read, Generic) -- instance Binary TNetworkHM fromHMNetwork :: Main.TNetwork -> MinimalNN.TNetwork fromHMNetwork (TNetwork ws bs) = (MinimalNN.TNetwork (map (V.transFix . V.fromLists . HM.toLists) ws) (map (V.fromList . HM.toList) bs)) main :: IO () main = mapM_ convertDBN =<< getArgs convertDBN :: FilePath -> IO () convertDBN fn = do let fnOut = dropExtension fn <.> "bin" ex <- doesFileExist fnOut case ex of False -> do putStrLn $ printf "Converting: %s -> %s" fn fnOut net <- read `fmap` readFile fn MinimalNN.encodeFile fnOut (fromHMNetwork net) True -> do putStrLn $ printf "Converting: %s -> %s [skipped]" fn fnOut
Tener/deeplearning-thesis
src/dbn-converter.hs
bsd-3-clause
1,467
0
14
332
387
210
177
41
2
{-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveGeneric #-} -- | -- Module : Pact.Types.Capability -- Copyright : (C) 2019 Stuart Popejoy, Kadena LLC -- License : BSD-style (see the file LICENSE) -- Maintainer : Stuart Popejoy <[email protected]> -- -- Capability and related types. -- module Pact.Types.Capability ( Capability(..) , CapEvalResult(..) , SigCapability(..) , UserCapability , ManagedCapability(..), mcInstalled, mcStatic, mcManaged , UserManagedCap(..), umcManagedValue, umcManageParamIndex, umcManageParamName, umcMgrFun , AutoManagedCap(..), amcActive , decomposeManaged, decomposeManaged', matchManaged , Capabilities(..), capStack, capManaged, capModuleAdmin, capAutonomous , CapScope(..) , CapSlot(..), csCap, csComposed, csScope ) where import Control.DeepSeq (NFData) import Control.Lens hiding ((.=),DefName) import Data.Aeson import Data.Default import Data.Set (Set) import Data.Text (Text) import GHC.Generics import Pact.Types.Lang import Pact.Types.Orphans () import Pact.Types.PactValue import Pact.Types.Pretty data Capability = CapModuleAdmin ModuleName | CapUser UserCapability deriving (Eq,Show,Ord,Generic) instance NFData Capability instance Pretty Capability where pretty (CapModuleAdmin mn) = pretty mn pretty (CapUser s) = pretty s -- | Both UX type (thus the name) and "UserCapability". -- TODO rename when downstream deps are more stable. type UserCapability = SigCapability data SigCapability = SigCapability { _scName :: !QualifiedName , _scArgs :: ![PactValue] } deriving (Eq,Show,Generic,Ord) instance NFData SigCapability instance Pretty SigCapability where pretty SigCapability{..} = parens $ hsep (pretty _scName:map pretty _scArgs) instance ToJSON SigCapability where toJSON (SigCapability n args) = object $ [ "name" .= n , "args" .= args ] instance FromJSON SigCapability where parseJSON = withObject "SigCapability" $ \o -> SigCapability <$> o .: "name" <*> o .: "args" -- | Various results of evaluating a capability. -- Note: dupe managed install is an error, thus no case here. data CapEvalResult = NewlyAcquired | AlreadyAcquired | NewlyInstalled (ManagedCapability UserCapability) deriving (Eq,Show) data CapScope = CapCallStack -- ^ Call stack scope a la 'with-capability' | CapManaged -- ^ Managed-scope capability | CapComposed -- ^ Composed into some other capability deriving (Eq,Show,Ord,Generic) instance NFData CapScope instance Pretty CapScope where pretty = viaShow -- | Runtime storage of acquired or managed capability. data CapSlot c = CapSlot { _csScope :: CapScope , _csCap :: c , _csComposed :: [c] } deriving (Eq,Show,Ord,Functor,Foldable,Traversable,Generic) instance NFData c => NFData (CapSlot c) -- | Model a managed capability where a user-provided function -- maintains a selected parameter value. data UserManagedCap = UserManagedCap { _umcManagedValue :: PactValue -- ^ mutating value , _umcManageParamIndex :: Int -- ^ index of managed param value in defcap , _umcManageParamName :: Text -- ^ name of managed param value in defcap , _umcMgrFun :: Def Ref -- ^ manager function } deriving (Show,Generic) instance NFData UserManagedCap -- | Model an auto-managed "one-shot" capability. newtype AutoManagedCap = AutoManagedCap { _amcActive :: Bool } deriving (Show, Generic) instance NFData AutoManagedCap instance Pretty AutoManagedCap where pretty = viaShow data ManagedCapability c = ManagedCapability { _mcInstalled :: CapSlot c -- ^ original installed capability , _mcStatic :: UserCapability -- ^ Cap without any mutating components (for auto, same as cap in installed) , _mcManaged :: Either AutoManagedCap UserManagedCap -- ^ either auto-managed or user-managed } deriving (Show,Generic,Foldable) -- | Given arg index, split capability args into (before,at,after) decomposeManaged :: Int -> UserCapability -> Maybe ([PactValue],PactValue,[PactValue]) decomposeManaged idx SigCapability{..} | idx < 0 || idx >= length _scArgs = Nothing | otherwise = Just (take idx _scArgs,_scArgs !! idx,drop (succ idx) _scArgs) {-# INLINABLE decomposeManaged #-} -- | Given arg index, get "static" capability and value decomposeManaged' :: Int -> UserCapability -> Maybe (SigCapability,PactValue) decomposeManaged' idx cap@SigCapability{..} = case decomposeManaged idx cap of Nothing -> Nothing Just (h,v,t) -> Just (SigCapability _scName (h ++ t),v) {-# INLINABLE decomposeManaged' #-} -- | Match static value to managed. matchManaged :: ManagedCapability UserCapability -> UserCapability -> Bool matchManaged ManagedCapability{..} cap@SigCapability{} = case _mcManaged of Left {} -> _mcStatic == cap Right UserManagedCap{..} -> case decomposeManaged' _umcManageParamIndex cap of Nothing -> False Just (c,_) -> c == _mcStatic {-# INLINABLE matchManaged #-} instance Eq a => Eq (ManagedCapability a) where a == b = _mcStatic a == _mcStatic b instance Ord a => Ord (ManagedCapability a) where a `compare` b = _mcStatic a `compare` _mcStatic b instance Pretty a => Pretty (ManagedCapability a) where pretty ManagedCapability {..} = pretty _mcStatic <> "~" <> mgd _mcManaged where mgd (Left b) = pretty b mgd (Right UserManagedCap{..}) = pretty _umcManagedValue instance NFData a => NFData (ManagedCapability a) -- | Runtime datastructure. data Capabilities = Capabilities { _capStack :: [CapSlot UserCapability] -- ^ Stack of "acquired" capabilities. , _capManaged :: Set (ManagedCapability UserCapability) -- ^ Set of installed managed capabilities. Maybe indicates whether it has been -- initialized from signature set. , _capModuleAdmin :: (Set ModuleName) -- ^ Set of module admin capabilities. , _capAutonomous :: (Set UserCapability) } deriving (Eq,Show,Generic) instance Default Capabilities where def = Capabilities [] mempty mempty mempty instance NFData Capabilities makeLenses ''ManagedCapability makeLenses ''Capabilities makeLenses ''CapSlot makeLenses ''UserManagedCap makeLenses ''AutoManagedCap
kadena-io/pact
src/Pact/Types/Capability.hs
bsd-3-clause
6,378
0
12
1,084
1,500
828
672
130
3
module Main where import City import Weather import Output import Model import Control.Monad main :: IO () main = do let towns = [Sydney .. Dubbo] ts <- timeSeries let stationData = map (makeStationData ts) towns mapM_ (mapM_ print) stationData
Michaelt293/TheWeather
app/Main.hs
bsd-3-clause
264
0
12
59
92
48
44
12
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Data.PList.Binary import Test.Framework.TH import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck import Data.DeriveTH import Test.QuickCheck.Instances import qualified Data.Vector as V import qualified Data.HashMap.Strict as H import qualified Data.ByteString.Lazy as BL import System.Process import System.Exit import System.IO.Unsafe import GHC.IO.Handle import System.IO.Temp instance Arbitrary a => Arbitrary (V.Vector a) where arbitrary = fmap V.fromList arbitrary shrink = map V.fromList . shrink . V.toList derive makeArbitrary ''PList -- TODO: forbid 0 length UTF16 strings decodePList' x = let Right res = decodePList x in res equal :: PList -> PList -> Bool equal (PBool x1) (PBool x2) = x1 == x2 equal (PInt x1) (PInt x2) = x1 == x2 equal (PReal x1) (PReal x2) = abs (x1 - x2) < 1e-8 equal (PDate x1) (PDate x2) = abs (x1 - x2) < 1e-8 equal (PData x1) (PData x2) = x1 == x2 equal (PASCII x1) (PASCII x2) = x1 == x2 equal (PUTF16 x1) (PUTF16 x2) = x1 == x2 equal (PUID x1) (PUID x2) = x1 == x2 equal (PArray x1) (PArray x2) = V.all (==True) $ V.zipWith equal x1 x2 equal (PDict x1) (PDict x2) = all (==True) (zipWith (==) (H.keys x1) (H.keys x2)) && all (==True) (zipWith equal (H.elems x1) (H.elems x2)) equal _ _ = False prop_encode_decode x = (decodePList' $ encodePList x) `equal` x prop_encode_decode_encode x = (encodePList $ decodePList' $ encodePList x) == encodePList x -- would like to use stdin, but unpacking bytestring seems to change encoding prop_plutil x = unsafePerformIO $ withSystemTempFile "XXXX.tmp" $ \filepath handle -> do BL.hPut handle $ encodePList $ PDict $ H.fromList [("root", x)] hClose handle res <- readProcessWithExitCode "plutil" ["-lint", filepath] [] case res of (ExitSuccess, _, _) -> return True (ExitFailure _, _, _) -> return False {-# NOINLINE prop_plutil #-} main = $defaultMainGenerator
tkonolige/haskell-bplist
test/properties.hs
bsd-3-clause
2,076
0
13
434
775
407
368
47
2
module OpenGL.Evaluator.GLFunction where import Data.Char (toUpper, toLower, isUpper, isNumber) import Data.List data TGLPrimitive = TGLbitfield | TGLboolean | TGLbyte | TGLchar | TGLclampf | TGLenum | TGLfloat | TGLint | TGLshort | TGLsizei | TGLubyte | TGLuint | TGLushort | TVoid | TGLsizeiptr | TGLIntPtr | TGLvoid deriving(Show, Eq) data TypeQualifier = Const | None deriving(Show, Eq) data GLType = GLType { qualifier :: TypeQualifier, indirection_count :: Int, typ :: TGLPrimitive } deriving(Show, Eq) is_output x = qualifier x == None && indirection_count x > 0 function_name_to_struct_name (x:y:xs) = (toUpper x):(toUpper y):xs fn_to_sn = function_name_to_struct_name --ugly consume :: String -> (String, [String]) -> (String, [String]) consume [] (current, old) = ([], (reverse current):old) consume (x:[]) (current, old) = if (isUpper x || isNumber x) then ([], [x]:(reverse current):old) else ([], (reverse $ x:current):old) consume (x:y:xs) (current, old) = if (isUpper x || isNumber x) then consume xs (toLower y:(toLower x):[], (reverse $ current):old) else consume (y:xs) (x:current, old) to_under_score :: String -> String to_under_score camel_case = result where (x:concatted) = concat $ intersperse "_" $ reverse $ snd $ consume (camel_case) ([], []) result = if x == '_' then concatted else x:concatted data GLFunction = GLFunction { gl_function_name :: String, gl_function_return_value :: GLType, gl_parameters :: [(String, GLType)] } deriving(Show, Eq) size_of_tgl TGLbitfield = 4 size_of_tgl TGLboolean = 1 size_of_tgl TGLbyte = 1 size_of_tgl TGLchar = 1 size_of_tgl TGLclampf = 4 size_of_tgl TGLenum = 4 size_of_tgl TGLfloat = 4 size_of_tgl TGLint = 4 size_of_tgl TGLshort = 2 size_of_tgl TGLsizei = 4 size_of_tgl TGLubyte = 1 size_of_tgl TGLuint = 4 size_of_tgl TGLushort = 2 size_of_tgl TVoid = error "TVoid does not have a size" size_of_tgl TGLsizeiptr = 4 size_of_tgl TGLIntPtr = 4 size_of_tgl TGLvoid = error "TGLvoid does not have a size"
jfischoff/opengl-eval
src/OpenGL/Evaluator/GLFunction.hs
bsd-3-clause
2,573
0
11
895
778
430
348
64
3
module Type.PrettyPrint where import Text.PrettyPrint import qualified SourceSyntax.PrettyPrint as Src data ParensWhen = Fn | App | Never class PrettyType a where pretty :: ParensWhen -> a -> Doc commaSep docs = sep (punctuate comma docs) parensIf bool doc = if bool then parens doc else doc reprime = Src.reprime
deadfoxygrandpa/Elm
compiler/Type/PrettyPrint.hs
bsd-3-clause
322
0
8
58
101
56
45
9
2
module ExplainFolding where sum' :: [Integer] -> Integer sum'[] = 0 sum' (x:xs) = x + sum' xs length' :: [a] -> Integer length' [] = 0 length' (x:xs) = 1 + length' xs product' :: [Integer] -> Integer product' [] = 1 product' (x:xs) = x * product' xs concat' :: [[a]] -> [a] concat' [] = [] concat' (x:xs) = x ++ concat' xs -- abstract the pattern above myFolding :: (a -> b ->b) -> b -> [a] -> b myFolding _ b [] = b myFolding f b (x:xs) = x `f` myFolding f b xs -- rewrite with myFolding sum'' :: [Integer] -> Integer sum'' = myFolding (+) 0 length'' :: [a] -> Integer length'' = myFolding (\_ n -> n + 1) 0 product'' :: [Integer] -> Integer product'' = myFolding (*) 1 concat'' :: [[a]] -> [a] concat'' = myFolding (++) [] --visulize the folding process {- example: foldr (visual "*") "1" (map show [1..10]) >> λ:-) mapM_ putStrLn $ scanr (visual "+") "0" (map show [1..10]) foldr (visual "+") "0" (map show [1..10]) = "(1+(2+(3+(4+(5+(6+(7+(8+(9+(10+0))))))))))"o evaluation process: -> 0 -> (10+0) -> (9+(10+0)) -> (8+(9+(10+0))) -> (7+(8+(9+(10+0)))) -> (6+(7+(8+(9+(10+0))))) -> (5+(6+(7+(8+(9+(10+0)))))) -> (4+(5+(6+(7+(8+(9+(10+0))))))) -> (3+(4+(5+(6+(7+(8+(9+(10+0)))))))) -> (2+(3+(4+(5+(6+(7+(8+(9+(10+0))))))))) -> (1+(2+(3+(4+(5+(6+(7+(8+(9+(10+0)))))))))) -} visual :: String -> String -> String -> String visual op x y = concat ["(", x, op, y, ")"] -- Folding exercise {- foldr (++) "" ["woot", "WOOT"] foldr max ' ' "fear is the little death" foldr (&&) True [False, True] foldr (||) True [False, True] foldl (++) "" $ map show [1..5] foldr const "a" $ map show [1..5] -}
chengzh2008/hpffp
src/ch10-FoldingList/explainFolding.hs
bsd-3-clause
1,641
0
8
321
434
240
194
26
1
{-# LANGUAGE CPP #-} {-# LANGUAGE NoImplicitPrelude #-} -- | -- Module: $HEADER$ -- Description: Support for hidden exceptions. -- Copyright: (c) 2009-2016, Peter Trško -- License: BSD3 -- -- Stability: provisional -- Portability: non-portable (CPP, NoImplicitPrelude, depends on non-portable -- module) module Control.Monad.TaggedException.Hidden ( -- * HiddenException class -- -- | Since 'HiddenException' provides default implementation for 'hide' -- method making instances of it is trivial. Example of how to create -- instance of HiddenException: -- -- > data MyException = MyException String -- > deriving (Typeable) -- > -- > instance Show MyException where -- > showsPrec _ (MyException msg) = -- > showString "MyException: " . shows msg -- > -- > instance Exception MyException -- > instance HiddenException MyException HiddenException(..) -- ** Mapping existing visible exception to hidden ones -- -- | This is a prefered way of hiding exceptions. Difference from just -- hiding the type tag and mapping it in to hidden exception is that in -- later case we can provide additional information. Most important is to -- specify why that particluar exception was hidden. -- -- Example: -- -- > data UnrecoverableException -- > = UnrecoverableIOException String IOException -- > deriving (Typeable) -- > -- > instance Show UnrecoverableException where -- > showsPrec _ (UnrecoverableIOException info e) -- > showString "Unrecoverable exception occurred in " -- > . showString info . showString ": " . shows e -- > -- > instance Exception UnrecoverableException -- > instance HiddenException UnrecoverableException -- > -- > hideIOException -- > :: (MonadCatch e) -- > => String -- > -> Throws IOException m a -- > -> m a -- > hideIOException = hideWith . UnrecoverableIOException , hideWith -- ** Raising hidden exceptions , throwHidden , throw' ) where import Control.Exception (Exception) import qualified Control.Exception as E #if MIN_VERSION_base(4,8,0) ( AllocationLimitExceeded , ArithException #else ( ArithException #endif , ArrayException , AssertionFailed , AsyncException #if MIN_VERSION_base(4,2,0) , BlockedIndefinitelyOnMVar , BlockedIndefinitelyOnSTM #else , BlockedIndefinitely , BlockedOnDeadMVar #endif , Deadlock , ErrorCall , IOException , NestedAtomically , NoMethodError , NonTermination , PatternMatchFail , RecConError , RecSelError , RecUpdError #if MIN_VERSION_base(4,7,0) , SomeAsyncException #endif , SomeException #if MIN_VERSION_base(4,9,0) , TypeError #endif ) import Data.Dynamic (Dynamic) import Data.Function ((.)) #if MIN_VERSION_base(4,8,0) import Data.Void (Void) #endif import System.Exit (ExitCode) import Control.Monad.Catch (MonadCatch, MonadThrow) import qualified Control.Monad.Catch as Exceptions ( MonadCatch(catch) , MonadThrow(throwM) ) -- This module depends only on internals and nothing else from this package. -- Try, hard, to keep it that way. import Control.Monad.TaggedException.Internal.Throws (Throws(Throws)) import qualified Control.Monad.TaggedException.Internal.Throws as Internal (Throws(hideException)) -- | Class for exception that can be removed from the type signature. Default -- implementation for 'hideException' method is provided. class Exception e => HiddenException e where -- | Hide exception tag. hideException :: MonadThrow m => Throws e m a -> m a hideException = Internal.hideException {-# INLINE hideException #-} -- {{{ HiddenException -- Instances ------------------------------------------- -- (sorted alphabetically) instance HiddenException Dynamic instance HiddenException E.ArithException instance HiddenException E.ArrayException instance HiddenException E.AssertionFailed instance HiddenException E.AsyncException instance HiddenException E.BlockedIndefinitelyOnMVar instance HiddenException E.BlockedIndefinitelyOnSTM instance HiddenException E.Deadlock instance HiddenException E.ErrorCall instance HiddenException E.IOException instance HiddenException E.NestedAtomically instance HiddenException E.NoMethodError instance HiddenException E.NonTermination instance HiddenException E.PatternMatchFail instance HiddenException E.RecConError instance HiddenException E.RecSelError instance HiddenException E.RecUpdError instance HiddenException E.SomeException instance HiddenException ExitCode #if MIN_VERSION_base(4,7,0) instance HiddenException E.SomeAsyncException #endif #if MIN_VERSION_base(4,8,0) instance HiddenException E.AllocationLimitExceeded instance HiddenException Void #endif #if MIN_VERSION_base(4,9,0) instance HiddenException E.TypeError #endif -- }}} HiddenException -- Instances ------------------------------------------- -- | Map exception before hiding it. -- -- This is the preferred way to do exception hiding, by mapping it in to a -- different exception that better describes its fatality. hideWith :: (Exception e, HiddenException e', MonadCatch m) => (e -> e') -> Throws e m a -> m a hideWith f (Throws ma) = Exceptions.catch ma (Exceptions.throwM . f) -- | Throw exceptions and then disregard type tag. throwHidden :: (HiddenException e, MonadThrow m) => e -> m a throwHidden = Exceptions.throwM {-# INLINE throwHidden #-} -- | Alias for @throwHidden@. throw' :: (HiddenException e, MonadThrow m) => e -> m a throw' = Exceptions.throwM {-# INLINE throw' #-}
trskop/tagged-exception-core
src/Control/Monad/TaggedException/Hidden.hs
bsd-3-clause
5,758
0
9
1,151
714
430
284
78
1
module Events.Keybindings ( defaultBindings , lookupKeybinding , getFirstDefaultBinding , mkKb , staticKb , mkKeybindings , handleKeyboardEvent -- Re-exports: , Keybinding (..) , KeyEvent (..) , KeyConfig , allEvents , parseBinding , keyEventName , keyEventFromName ) where import Prelude () import Prelude.MH import qualified Data.Map.Strict as M import qualified Graphics.Vty as Vty import Types import Types.KeyEvents -- * Keybindings -- | A 'Keybinding' represents a keybinding along with its -- implementation data Keybinding = KB { kbDescription :: Text , kbEvent :: Vty.Event , kbAction :: MH () , kbBindingInfo :: Maybe KeyEvent } -- | Find a keybinding that matches a Vty Event lookupKeybinding :: Vty.Event -> [Keybinding] -> Maybe Keybinding lookupKeybinding e kbs = case filter ((== e) . kbEvent) kbs of [] -> Nothing (x:_) -> Just x handleKeyboardEvent :: (KeyConfig -> [Keybinding]) -> (Vty.Event -> MH ()) -> Vty.Event -> MH () handleKeyboardEvent keyList fallthrough e = do conf <- use (csResources.crConfiguration) let keyMap = keyList (configUserKeys conf) case lookupKeybinding e keyMap of Just kb -> kbAction kb Nothing -> fallthrough e mkKb :: KeyEvent -> Text -> MH () -> KeyConfig -> [Keybinding] mkKb ev msg action conf = [ KB msg (bindingToEvent key) action (Just ev) | key <- allKeys ] where allKeys | Just (BindingList ks) <- M.lookup ev conf = ks | Just Unbound <- M.lookup ev conf = [] | otherwise = defaultBindings ev staticKb :: Text -> Vty.Event -> MH () -> KeyConfig -> [Keybinding] staticKb msg event action _ = [KB msg event action Nothing] mkKeybindings :: [KeyConfig -> [Keybinding]] -> KeyConfig -> [Keybinding] mkKeybindings ks conf = concat [ k conf | k <- ks ] bindingToEvent :: Binding -> Vty.Event bindingToEvent binding = Vty.EvKey (kbKey binding) (kbMods binding) getFirstDefaultBinding :: KeyEvent -> Binding getFirstDefaultBinding ev = case defaultBindings ev of [] -> error $ "BUG: event " <> show ev <> " has no default bindings!" (b:_) -> b defaultBindings :: KeyEvent -> [Binding] defaultBindings ev = let meta binding = binding { kbMods = Vty.MMeta : kbMods binding } ctrl binding = binding { kbMods = Vty.MCtrl : kbMods binding } kb k = Binding { kbMods = [], kbKey = k } key c = Binding { kbMods = [], kbKey = Vty.KChar c } fn n = Binding { kbMods = [], kbKey = Vty.KFun n } in case ev of VtyRefreshEvent -> [ ctrl (key 'l') ] ShowHelpEvent -> [ fn 1 ] EnterSelectModeEvent -> [ ctrl (key 's') ] ReplyRecentEvent -> [ ctrl (key 'r') ] ToggleMessagePreviewEvent -> [ meta (key 'p') ] InvokeEditorEvent -> [ meta (key 'k') ] EnterFastSelectModeEvent -> [ ctrl (key 'g') ] QuitEvent -> [ ctrl (key 'q') ] NextChannelEvent -> [ ctrl (key 'n') ] PrevChannelEvent -> [ ctrl (key 'p') ] NextUnreadChannelEvent -> [ meta (key 'a') ] NextUnreadUserOrChannelEvent -> [ ] LastChannelEvent -> [ meta (key 's') ] EnterOpenURLModeEvent -> [ ctrl (key 'o') ] ClearUnreadEvent -> [ meta (key 'l') ] ToggleMultiLineEvent -> [ meta (key 'e') ] EnterFlaggedPostsEvent -> [ meta (key '8') ] ToggleChannelListVisibleEvent -> [ fn 2 ] CancelEvent -> [ kb Vty.KEsc , ctrl (key 'c') ] -- channel-scroll-specific LoadMoreEvent -> [ ctrl (key 'b') ] -- scrolling events ScrollUpEvent -> [ kb Vty.KUp ] ScrollDownEvent -> [ kb Vty.KDown ] PageUpEvent -> [ kb Vty.KPageUp ] PageDownEvent -> [ kb Vty.KPageDown ] ScrollTopEvent -> [ kb Vty.KHome ] ScrollBottomEvent -> [ kb Vty.KEnd ] SelectUpEvent -> [ key 'k', kb Vty.KUp ] SelectDownEvent -> [ key 'j', kb Vty.KDown ] ActivateListItemEvent -> [ kb Vty.KEnter ] -- search selection - like SelectUp/Down above but need to not -- conflict with editor inputs SearchSelectUpEvent -> [ ctrl (key 'p'), kb Vty.KUp ] SearchSelectDownEvent -> [ ctrl (key 'n'), kb Vty.KDown ] ViewMessageEvent -> [ key 'v' ] FlagMessageEvent -> [ key 'f' ] YankMessageEvent -> [ key 'y' ] YankWholeMessageEvent -> [ key 'Y' ] DeleteMessageEvent -> [ key 'd' ] EditMessageEvent -> [ key 'e' ] ReplyMessageEvent -> [ key 'r' ] OpenMessageURLEvent -> [ key 'o' ]
aisamanra/matterhorn
src/Events/Keybindings.hs
bsd-3-clause
4,664
0
13
1,331
1,494
775
719
107
39
module IOChoiceSpec where import Control.Exception import Control.Exception.IOChoice import System.IO.Error import Test.Hspec spec :: Spec spec = describe "||>" $ do it "selects IO" $ do good ||> bad `shouldReturn` "good" bad ||> good `shouldReturn` "good" it "throws an error if all choices fail" $ do bad ||> bad `shouldThrow` isUserError it "can be used with goNext" $ do goNext ||> good `shouldReturn` "good" it "does not catch exceptions except IOException" $ do throwIO Overflow ||> good `shouldThrow` isOverLow good :: IO String good = return "good" bad :: IO String bad = throwIO ioErr ioErr :: IOException ioErr = userError "userError" isOverLow :: Selector ArithException isOverLow e = e == Overflow
kazu-yamamoto/io-choice
test/IOChoiceSpec.hs
bsd-3-clause
772
0
13
173
216
111
105
24
1
module Text.HTML.Moe2.Type where import Data.Default import Control.Monad.Writer import Text.HTML.Moe2.Utils import Data.DList (DList) data Element = Element { name :: Internal , elements :: [Element] , attributes :: [Attribute] , indent :: Bool , self_close :: Bool } | Raw Internal -- no escape, no indent | Pre Internal -- escape, no indent | Data Internal -- escape, indent | Prim Internal -- no escape, indent | Attributes [Attribute] Element deriving (Show) instance Default Element where def = Element { name = none , elements = def , attributes = def , indent = True , self_close = False } data Attribute = Attribute { key :: Internal , value :: Internal } deriving (Show) instance Default Attribute where def = Attribute none none type MoeUnitT a = Writer (DList Element) a type MoeUnit = MoeUnitT () type MoeCombinator = MoeUnit -> MoeUnit type LightCombinator = MoeCombinator
nfjinjing/moe
src/Text/HTML/Moe2/Type.hs
bsd-3-clause
1,005
0
9
264
258
159
99
35
0
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts, FlexibleInstances, RankNTypes, MagicHash, UnboxedTuples #-} {-# OPTIONS_HADDOCK hide #-} {-# OPTIONS_GHC -fno-warn-orphans -fno-warn-name-shadowing -fno-warn-unused-binds #-} module Data.PhaseChange.Instances () where import Data.PhaseChange.Internal import Control.Monad import Control.Monad.Primitive import Control.Monad.ST import Unsafe.Coerce import GHC.Exts -- they sure made a big mess out of the Array modules... import Data.Primitive.Array as Prim import Data.Primitive.ByteArray as Prim import Data.Array as Arr (Array) import Data.Array.ST as Arr (STArray, STUArray) import Data.Array.Unboxed as Arr (UArray) import Data.Array.IArray as Arr (IArray, Ix) import Data.Array.MArray as Arr (MArray, mapArray) import Data.Array.Unsafe as Arr (unsafeThaw, unsafeFreeze) import Data.Vector as Vec import Data.Vector.Primitive as PVec import Data.Vector.Unboxed as UVec import Data.Vector.Storable as SVec import Data.Vector.Generic.Mutable as GVec cloneMutableArray :: (PrimMonad m, s ~ PrimState m) => MutableArray s a -> Int -> Int -> m (MutableArray s a) cloneMutableArray (MutableArray a#) (I# begin#) (I# size#) = primitive $ \s# -> case cloneMutableArray# a# begin# size# s# of (# s'#, a'# #) -> (# s'#, MutableArray a'# #) sizeofMutableArray :: MutableArray s a -> Int sizeofMutableArray (MutableArray a#) = I# (sizeofMutableArray# a#) -- * primitive -- | Data.Primitive.ByteArray instance PhaseChange Prim.ByteArray Prim.MutableByteArray where type Thawed Prim.ByteArray = Prim.MutableByteArray type Frozen Prim.MutableByteArray = Prim.ByteArray unsafeThawImpl = unsafeThawByteArray unsafeFreezeImpl = unsafeFreezeByteArray copyImpl old = do let size = sizeofMutableByteArray old new <- newByteArray size copyMutableByteArray new 0 old 0 size return new -- | Data.Primitive.Array instance PhaseChange (Prim.Array a) (M1 Prim.MutableArray a) where type Thawed (Prim.Array a) = M1 Prim.MutableArray a type Frozen (M1 Prim.MutableArray a) = Prim.Array a unsafeThawImpl = liftM M1 . unsafeThawArray unsafeFreezeImpl = unsafeFreezeArray . unM1 copyImpl (M1 a) = liftM M1 $ cloneMutableArray a 0 (sizeofMutableArray a) -- * array -- NOTE -- for the Array types, we have to use a hack: we want to write "forall s. MArray (STArray s) a (ST s)" -- in the instance declaration, but we can't do that. our hack is that we have an unexported type, S, -- and we write "MArray (STArray S) a (ST S)" instead. because S is not exported, the only way the -- constraint can be satisfied is if it is true forall s. and then we use unsafeCoerce. -- (this trick is borrowed from Edward Kmett's constraints library) -- capture and store the evidence for an MArray constraint in CPS form type WithMArray stArray s a = forall r. (MArray (stArray s) a (ST s) => r) -> r -- capture locally available evidence and store it mArray :: MArray (stArray s) a (ST s) => WithMArray stArray s a mArray a = a -- see NOTE above. do not export! newtype S = S S -- if we know MArray for S, it must be true forall s. make it so. anyS :: WithMArray stArray S a -> WithMArray stArray s a anyS = unsafeCoerce -- from locally available evidence of MArray for S, produce evidence we can use -- for any s. the first argument is just a dummy to bring type variables into scope, -- chosen to be convenient for the particular use sites that we have. hack :: MArray (stArray S) a (ST S) => ST s (M2 stArray i a s) -> WithMArray stArray s a hack _ = anyS mArray -- | Data.Array instance (Ix i, IArray Arr.Array a, MArray (Arr.STArray S) a (ST S)) => PhaseChange (Arr.Array i a) (M2 Arr.STArray i a) where type Thawed (Arr.Array i a) = M2 Arr.STArray i a type Frozen (M2 Arr.STArray i a) = Arr.Array i a unsafeThawImpl a = r where r = hack r (liftM M2 $ Arr.unsafeThaw a) unsafeFreezeImpl a = hack (return a) (Arr.unsafeFreeze $ unM2 a) copyImpl a = hack (return a) (liftM M2 . mapArray id . unM2 $ a) -- | Data.Array.Unboxed instance (Ix i, IArray Arr.UArray a, MArray (Arr.STUArray S) a (ST S)) => PhaseChange (Arr.UArray i a) (M2 Arr.STUArray i a) where type Thawed (Arr.UArray i a) = M2 Arr.STUArray i a type Frozen (M2 Arr.STUArray i a) = Arr.UArray i a unsafeThawImpl a = r where r = hack r (liftM M2 $ Arr.unsafeThaw a) unsafeFreezeImpl a = hack (return a) (Arr.unsafeFreeze $ unM2 a) copyImpl a = hack (return a) (liftM M2 . mapArray id . unM2 $ a) -- * vector -- | Data.Vector instance PhaseChange (Vec.Vector a) (M1 Vec.MVector a) where type Thawed (Vec.Vector a) = M1 Vec.MVector a type Frozen (M1 Vec.MVector a) = Vec.Vector a unsafeThawImpl = liftM M1 . Vec.unsafeThaw unsafeFreezeImpl = Vec.unsafeFreeze . unM1 copyImpl = liftM M1 . GVec.clone . unM1 -- | Data.Vector.Storable instance Storable a => PhaseChange (SVec.Vector a) (M1 SVec.MVector a) where type Thawed (SVec.Vector a) = M1 SVec.MVector a type Frozen (M1 SVec.MVector a) = SVec.Vector a unsafeThawImpl = liftM M1 . SVec.unsafeThaw unsafeFreezeImpl = SVec.unsafeFreeze . unM1 copyImpl = liftM M1 . GVec.clone . unM1 -- | Data.Vector.Primitive instance Prim a => PhaseChange (PVec.Vector a) (M1 PVec.MVector a) where type Thawed (PVec.Vector a) = M1 PVec.MVector a type Frozen (M1 PVec.MVector a) = PVec.Vector a unsafeThawImpl = liftM M1 . PVec.unsafeThaw unsafeFreezeImpl = PVec.unsafeFreeze . unM1 copyImpl = liftM M1 . GVec.clone . unM1 -- | Data.Vector.Unboxed instance Unbox a => PhaseChange (UVec.Vector a) (M1 UVec.MVector a) where type Thawed (UVec.Vector a) = M1 UVec.MVector a type Frozen (M1 UVec.MVector a) = UVec.Vector a unsafeThawImpl = liftM M1 . UVec.unsafeThaw unsafeFreezeImpl = UVec.unsafeFreeze . unM1 copyImpl = liftM M1 . GVec.clone . unM1
glaebhoerl/phasechange
Data/PhaseChange/Instances.hs
bsd-3-clause
6,143
0
12
1,376
1,769
932
837
89
1
{-# LANGUAGE FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- Module : MuTerm.Framework.Strategy -- Copyright : (c) muterm development team -- License : see LICENSE -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : non-portable -- -- This module manage the different strategies to solve a termination -- problem -- ----------------------------------------------------------------------------- module MuTerm.Framework.Strategy ( (.|.), (.||.), (.|||.), (.&.), final, FinalProcessor, try, simultaneously, parallelize, fixSolver, repeatSolver, lfp ) where import MuTerm.Framework.Proof(Proof) import Control.Applicative import Control.DeepSeq import Control.Monad ((>=>), mplus, MonadPlus) import Control.Monad.Free import Control.Parallel.Strategies import Data.Traversable (Traversable, traverse) import MuTerm.Framework.Processor import MuTerm.Framework.Proof ----------------------------------------------------------------------------- -- Data ----------------------------------------------------------------------------- -- | The final processor ends the strategy data FinalProcessor = FinalProcessor ----------------------------------------------------------------------------- -- Functions ----------------------------------------------------------------------------- -- Strategy combinators -- | Or strategy combinator (.|.) :: (MonadPlus m) => (t -> m a) -> (t -> m a) -> t -> m a (f .|. g) m = f m `mplus` g m -- | shallow parallel Or strategy combinator (.||.) :: MonadPlus m => (t -> m a) -> (t -> m a) -> t -> m a (f .||. g) m = uncurry mplus ((f m, g m) `using` parTuple2 rseq rseq) -- | deep parallel Or strategy combinator (.|||.) :: (NFData (Proof info m a), MonadPlus m) => (t -> Proof info m a) -> (t -> Proof info m a) -> t -> Proof info m a (f .|||. g) m = uncurry mplus ((f m, g m) `using` parTuple2 rdeepseq rdeepseq) -- | And strategy combinator (.&.) :: Monad mp => (a -> Proof info mp b) -> (b -> Proof info mp c) -> a -> Proof info mp c (.&.) = (>=>) infixr 5 .|., .||., .|||. infixr 5 .&. parallelize :: (a -> Proof info mp a) -> a -> Proof info mp a parallelize = (simultaneously .) simultaneously :: Proof info mp a -> Proof info mp a simultaneously = withStrategy parAnds -- | Apply a strategy until a fixpoint is reached fixSolver :: Monad mp => (a -> Proof info mp a) -> a -> Proof info mp a fixSolver f x = let x' = f x in (x' >>= fixSolver f) -- | Apply a strategy a bounded number of times repeatSolver :: Monad mp => Int -> (a -> Proof info mp a) -> a -> Proof info mp a repeatSolver max f = go max where go 0 x = return x go n x = let x' = f x in (x' >>= go (n-1)) -- | Try to apply a strategy and if it fails return the problem unmodified try :: (Info info typ, Processor info processor typ typ, MonadPlus mp) => processor -> typ -> Proof info mp typ try n x = case apply n x of Impure DontKnow{} -> return x Impure (Search m) -> Impure (Search (m `mplus` (return.return) x)) res -> res lfp :: (Eq prob, Info info prob, Processor info processor prob prob, MonadPlus mp) => processor -> prob -> Proof info mp prob lfp proc prob = do prob' <- try proc prob if prob == prob' then return prob' else lfp proc prob' -- | If we have branches in the strategy that arrive to different kind -- of problems, we have to close each branch with the same type final _ = return FinalProcessor
pepeiborra/muterm-framework
MuTerm/Framework/Strategy.hs
bsd-3-clause
3,609
0
15
759
1,060
574
486
55
3
module Utils where import Data.List import Data.Array mkPseudoImage size = let ps = generateCirclePoints (size `quot` 2, size `quot`2) (size `quot` 4) in listArray ((0,0),(size-1,size-1)) [if (x,y) `elem` ps then 255 else 0 | x <- [0..size-1], y <- [0..size-1]] type Point = (Int, Int) -- Takes the center of the circle and radius, and returns the circle points generateCirclePoints :: Point -> Int -> [Point] generateCirclePoints (x0, y0) radius = (x0, y0 + radius) : (x0, y0 - radius) : (x0 + radius, y0) : (x0 - radius, y0) : points where points = concatMap generatePoints $ unfoldr step initialValues generatePoints (x, y) = [(xop x0 x', yop y0 y') | (x', y') <- [(x, y), (y, x)], xop <- [(+), (-)], yop <- [(+), (-)]] initialValues = (1 - radius, 1, (-2) * radius, 0, radius) step (f, ddf_x, ddf_y, x, y) | x >= y = Nothing | otherwise = Just ((x', y'), (f', ddf_x', ddf_y', x', y')) where (f', ddf_y', y') | f >= 0 = (f + ddf_y' + ddf_x', ddf_y + 2, y - 1) | otherwise = (f + ddf_x, ddf_y, y) ddf_x' = ddf_x + 2 x' = x + 1
zelinskiy/ImRec
src/Utils.hs
bsd-3-clause
1,331
0
12
501
571
330
241
22
2
{-# LANGUAGE OverloadedStrings #-} module Web.Spock.Internal.Util where import Data.Maybe import Network.HTTP.Types import Network.Wai.Internal import qualified Data.Text as T import qualified Data.HashMap.Strict as HM data ClientPreferredFormat = PrefJSON | PrefXML | PrefHTML | PrefText | PrefUnknown deriving (Show, Eq) mimeMapping :: HM.HashMap T.Text ClientPreferredFormat mimeMapping = HM.fromList [ ("application/json", PrefJSON) , ("text/javascript", PrefJSON) , ("text/json", PrefJSON) , ("application/javascript", PrefJSON) , ("application/xml", PrefXML) , ("text/xml", PrefXML) , ("text/plain", PrefText) , ("text/html", PrefHTML) , ("application/xhtml+xml", PrefHTML) ] detectPreferredFormat :: T.Text -> ClientPreferredFormat detectPreferredFormat t = let (mimeTypeStr, _) = T.breakOn ";" t mimeTypes = map (T.toLower . T.strip) $ T.splitOn "," mimeTypeStr firstMatch [] = PrefUnknown firstMatch (x:xs) = fromMaybe (firstMatch xs) (HM.lookup x mimeMapping) in firstMatch mimeTypes mapReqHeaders :: (ResponseHeaders -> ResponseHeaders) -> Response -> Response mapReqHeaders f resp = case resp of (ResponseFile s h b1 b2) -> ResponseFile s (f h) b1 b2 (ResponseBuilder s h b) -> ResponseBuilder s (f h) b (ResponseStream s h b) -> ResponseStream s (f h) b (ResponseRaw x r) -> ResponseRaw x (mapReqHeaders f r)
nmk/Spock
src/Web/Spock/Internal/Util.hs
bsd-3-clause
1,450
0
13
300
453
251
202
40
4
module Util ( CInt (..) , CString , CStringLen , withCString , withCStringLen , peekCStringLen ) where import Foreign.C (CInt (..), CString, CStringLen) import System.IO (utf8) import qualified GHC.Foreign as GHC withCStringLen :: String -> (CStringLen -> IO a) -> IO a withCStringLen s f = GHC.withCStringLen utf8 s f withCString :: String -> (CString -> IO a) -> IO a withCString s f = GHC.withCString utf8 s f peekCStringLen :: CStringLen -> IO String peekCStringLen s = GHC.peekCStringLen utf8 s
sol/v8
src/Util.hs
mit
526
0
9
107
183
101
82
16
1
{-# LANGUAGE BangPatterns #-} module Lib.Directory ( getMFileStatus , catchDoesNotExist , removeFileOrDirectory , removeFileOrDirectoryOrNothing , createDirectories , getDirectoryContents , getDirectoryContentsHash , makeAbsolutePath ) where import qualified Control.Exception as E import Control.Monad import qualified Crypto.Hash.MD5 as MD5 import qualified Data.ByteString.Char8 as BS8 import Data.Monoid ((<>)) import Lib.Exception (bracket) import Lib.FilePath (FilePath, (</>)) import qualified Lib.FilePath as FilePath import qualified System.Directory as Dir import System.IO.Error import qualified System.Posix.ByteString as Posix import Prelude.Compat hiding (FilePath) catchErrorPred :: (IOErrorType -> Bool) -> IO a -> IO a -> IO a catchErrorPred predicate act handler = act `E.catch` \e -> if predicate (ioeGetErrorType e) then handler else E.throwIO e catchDoesNotExist :: IO a -> IO a -> IO a catchDoesNotExist = catchErrorPred isDoesNotExistErrorType catchAlreadyExists :: IO a -> IO a -> IO a catchAlreadyExists = catchErrorPred isAlreadyExistsErrorType getMFileStatus :: FilePath -> IO (Maybe Posix.FileStatus) getMFileStatus path = do doesExist <- FilePath.exists path if doesExist then (Just <$> Posix.getFileStatus path) `catchDoesNotExist` pure Nothing else pure Nothing createDirectories :: FilePath -> IO () createDirectories path | BS8.null path = pure () | otherwise = do doesExist <- FilePath.exists path unless doesExist $ do createDirectories $ FilePath.takeDirectory path Posix.createDirectory path 0o777 `catchAlreadyExists` pure () removeFileByStat :: IO () -> FilePath -> IO () removeFileByStat notExist path = do mFileStat <- getMFileStatus path case mFileStat of Nothing -> notExist Just fileStat | Posix.isRegularFile fileStat -> Posix.removeLink path | Posix.isSymbolicLink fileStat -> Posix.removeLink path | Posix.isDirectory fileStat -> Dir.removeDirectoryRecursive $ BS8.unpack path | otherwise -> error $ "removeFileOrDirectoryOrNothing: unsupported filestat " ++ show path removeFileOrDirectoryOrNothing :: FilePath -> IO () removeFileOrDirectoryOrNothing = removeFileByStat $ pure () removeFileOrDirectory :: FilePath -> IO () removeFileOrDirectory path = removeFileByStat -- Try to remove the file when it doesn't exist in order to generate -- the meaningful IO exception: (Posix.removeLink path) path getDirectoryContents :: FilePath -> IO [FilePath] getDirectoryContents path = bracket (Posix.openDirStream path) Posix.closeDirStream go where go dirStream = do fn <- Posix.readDirStream dirStream if BS8.null fn then pure [] else (fn :) <$> go dirStream getDirectoryContentsHash :: FilePath -> IO BS8.ByteString getDirectoryContentsHash path = bracket (Posix.openDirStream path) Posix.closeDirStream (go BS8.empty) where go !hash !dirStream = do fn <- Posix.readDirStream dirStream if BS8.null fn then pure hash else go (MD5.hash (hash <> fn)) dirStream makeAbsolutePath :: FilePath -> IO FilePath makeAbsolutePath path = (</> path) <$> Posix.getWorkingDirectory
buildsome/buildsome
src/Lib/Directory.hs
gpl-2.0
3,266
0
14
640
906
462
444
80
2
----------------------------------------------------------------------------- -- | -- Module : Text.Parsec.Language -- Copyright : (c) Daan Leijen 1999-2001, (c) Paolo Martini 2007 -- License : BSD-style (see the LICENSE file) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (uses non-portable module Text.Parsec.Token) -- -- A helper module that defines some language definitions that can be used -- to instantiate a token parser (see "Text.Parsec.Token"). -- ----------------------------------------------------------------------------- module Text.Parsec.Language ( haskellDef, haskell , mondrianDef, mondrian , emptyDef , haskellStyle , javaStyle , LanguageDef , GenLanguageDef ) where import Text.Parsec import Text.Parsec.Token ----------------------------------------------------------- -- Styles: haskellStyle, javaStyle ----------------------------------------------------------- -- | This is a minimal token definition for Haskell style languages. It -- defines the style of comments, valid identifiers and case -- sensitivity. It does not define any reserved words or operators. haskellStyle :: LanguageDef st haskellStyle = emptyDef { commentStart = "{-" , commentEnd = "-}" , commentLine = "--" , nestedComments = True , identStart = letter , identLetter = alphaNum <|> oneOf "_'" , opStart = opLetter haskellStyle , opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~" , reservedOpNames= [] , reservedNames = [] , caseSensitive = True } -- | This is a minimal token definition for Java style languages. It -- defines the style of comments, valid identifiers and case -- sensitivity. It does not define any reserved words or operators. javaStyle :: LanguageDef st javaStyle = emptyDef { commentStart = "/*" , commentEnd = "*/" , commentLine = "//" , nestedComments = True , identStart = letter , identLetter = alphaNum <|> oneOf "_'" , reservedNames = [] , reservedOpNames= [] , caseSensitive = False } ----------------------------------------------------------- -- minimal language definition -------------------------------------------------------- -- TODO: This seems wrong -- < This is the most minimal token definition. It is recommended to use -- this definition as the basis for other definitions. @emptyDef@ has -- no reserved names or operators, is case sensitive and doesn't accept -- comments, identifiers or operators. emptyDef :: LanguageDef st emptyDef = LanguageDef { commentStart = "" , commentEnd = "" , commentLine = "" , nestedComments = True , identStart = letter <|> char '_' , identLetter = alphaNum <|> oneOf "_'" , opStart = opLetter emptyDef , opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~" , reservedOpNames= [] , reservedNames = [] , caseSensitive = True } ----------------------------------------------------------- -- Haskell ----------------------------------------------------------- -- | A lexer for the haskell language. haskell :: TokenParser st haskell = makeTokenParser haskellDef -- | The language definition for the Haskell language. haskellDef :: LanguageDef st haskellDef = haskell98Def { identLetter = identLetter haskell98Def <|> char '#' , reservedNames = reservedNames haskell98Def ++ ["foreign","import","export","primitive" ,"_ccall_","_casm_" ,"forall" ] } -- | The language definition for the language Haskell98. haskell98Def :: LanguageDef st haskell98Def = haskellStyle { reservedOpNames= ["::","..","=","\\","|","<-","->","@","~","=>"] , reservedNames = ["let","in","case","of","if","then","else", "data","type", "class","default","deriving","do","import", "infix","infixl","infixr","instance","module", "newtype","where", "primitive" -- "as","qualified","hiding" ] } ----------------------------------------------------------- -- Mondrian ----------------------------------------------------------- -- | A lexer for the mondrian language. mondrian :: TokenParser st mondrian = makeTokenParser mondrianDef -- | The language definition for the language Mondrian. mondrianDef :: LanguageDef st mondrianDef = javaStyle { reservedNames = [ "case", "class", "default", "extends" , "import", "in", "let", "new", "of", "package" ] , caseSensitive = True }
antarestrader/sapphire
Text/Parsec/Language.hs
gpl-3.0
5,121
36
8
1,496
686
431
255
72
1
{-# LANGUAGE FlexibleInstances, IncoherentInstances #-} module Test.QuickFuzz.Gen.Base.String where import Test.QuickCheck import qualified Data.Text as TS import qualified Data.Text.Lazy as TL import Test.QuickFuzz.Gen.Base.Value -- String instance Arbitrary String where arbitrary = genStrValue "String" -- Text instance Arbitrary TS.Text where arbitrary = TS.pack <$> genStrValue "Text" shrink xs = TS.pack <$> shrink (TS.unpack xs) instance Arbitrary TL.Text where arbitrary = TL.pack <$> genStrValue "Text" shrink xs = TL.pack <$> shrink (TL.unpack xs) instance CoArbitrary TS.Text where coarbitrary = coarbitrary . TS.unpack instance CoArbitrary TL.Text where coarbitrary = coarbitrary . TL.unpack
elopez/QuickFuzz
src/Test/QuickFuzz/Gen/Base/String.hs
gpl-3.0
740
0
10
124
198
110
88
18
0
{-| Module : Matchers License : GPL Maintainer : [email protected] Stability : experimental Portability : portable Matching expressions (directives based on "Scripting the Type Inference Process", ICFP 2003) -} module Helium.StaticAnalysis.Directives.Matchers where import Helium.Syntax.UHA_Syntax import Helium.StaticAnalysis.Messages.Messages () -- instance Eq Name ------------------------------------------------------------- -- Expression match_Expression_Literal :: Literal -> Expression -> Maybe () match_Expression_Literal l1 expr = case expr of Expression_Literal _ l2 | l1 `eqLiteral` l2 -> Just () _ -> Nothing match_Expression_Variable :: Name -> Expression -> Maybe () match_Expression_Variable n1 expr = case expr of Expression_Variable _ n2 | n1 == n2 -> Just () _ -> Nothing match_Expression_Constructor :: Name -> Expression -> Maybe () match_Expression_Constructor n1 expr = case expr of Expression_Constructor _ n2 | n1 == n2 -> Just () _ -> Nothing match_Expression_NormalApplication :: Expression -> Maybe (Expression, Expressions) match_Expression_NormalApplication expr = case expr of Expression_NormalApplication _ e es -> Just (e,es) _ -> Nothing match_Expression_InfixApplication :: Expression -> Maybe (MaybeExpression, Expression, MaybeExpression) match_Expression_InfixApplication expr = case expr of Expression_InfixApplication _ me1 e me2 -> Just (me1,e,me2) _ -> Nothing match_Expression_If :: Expression -> Maybe (Expression,Expression,Expression) match_Expression_If expr = case expr of Expression_If _ e1 e2 e3 -> Just (e1,e2,e3) _ -> Nothing match_Expression_Lambda :: Expression -> Maybe (Patterns,Expression) match_Expression_Lambda expr = case expr of Expression_Lambda _ p e -> Just (p,e) _ -> Nothing match_Expression_Case :: Expression -> Maybe (Expression,Alternatives) match_Expression_Case expr = case expr of Expression_Case _ e as -> Just (e,as) _ -> Nothing match_Expression_Let :: Expression -> Maybe (Declarations,Expression) match_Expression_Let expr = case expr of Expression_Let _ ds e -> Just (ds,e) _ -> Nothing match_Expression_Do :: Expression -> Maybe Statements match_Expression_Do expr = case expr of Expression_Do _ ss -> Just ss _ -> Nothing match_Expression_List :: Expression -> Maybe Expressions match_Expression_List expr = case expr of Expression_List _ es -> Just es _ -> Nothing match_Expression_Tuple :: Expression -> Maybe Expressions match_Expression_Tuple expr = case expr of Expression_Tuple _ es -> Just es _ -> Nothing match_Expression_Comprehension :: Expression -> Maybe (Expression,Qualifiers) match_Expression_Comprehension expr = case expr of Expression_Comprehension _ e qs -> Just (e,qs) _ -> Nothing match_Expression_Typed :: Expression -> Maybe (Expression,Type) match_Expression_Typed expr = case expr of Expression_Typed _ e t -> Just (e,t) _ -> Nothing match_Expression_Enum :: Expression -> Maybe (Expression,MaybeExpression,MaybeExpression) match_Expression_Enum expr = case expr of Expression_Enum _ e me1 me2 -> Just (e,me1,me2) _ -> Nothing match_Expression_Negate :: Expression -> Maybe Expression match_Expression_Negate expr = case expr of Expression_Negate _ e -> Just e _ -> Nothing match_Expression_NegateFloat :: Expression -> Maybe Expression match_Expression_NegateFloat expr = case expr of Expression_NegateFloat _ e -> Just e _ -> Nothing ------------------------------------------------------------- -- Expressions match_Expressions_Cons :: Expressions -> Maybe (Expression,Expressions) match_Expressions_Cons exprs = case exprs of e:es -> Just (e,es) _ -> Nothing match_Expressions_Nil :: Expressions -> Maybe () match_Expressions_Nil exprs = case exprs of [] -> Just () _ -> Nothing ------------------------------------------------------------- -- MaybeExpression match_MaybeExpression_Just :: MaybeExpression -> Maybe Expression match_MaybeExpression_Just mexpr = case mexpr of MaybeExpression_Just e -> Just e _ -> Nothing match_MaybeExpression_Nothing :: MaybeExpression -> Maybe () match_MaybeExpression_Nothing mexpr = case mexpr of MaybeExpression_Nothing -> Just () _ -> Nothing ------------------------------------------------------------- eqLiteral :: Literal -> Literal -> Bool eqLiteral (Literal_Char _ x) (Literal_Char _ y) = x == y eqLiteral (Literal_Float _ x) (Literal_Float _ y) = x == y eqLiteral (Literal_Int _ x) (Literal_Int _ y) = x == y eqLiteral (Literal_String _ x) (Literal_String _ y) = x == y eqLiteral _ _ = False
roberth/uu-helium
src/Helium/StaticAnalysis/Directives/Matchers.hs
gpl-3.0
5,432
0
11
1,562
1,321
672
649
114
2
main :: Bool -> Bool -> () main True = const ()
roberth/uu-helium
test/staticwarnings/Missing7.hs
gpl-3.0
49
0
7
13
29
14
15
2
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.SNS.Subscribe -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Prepares to subscribe an endpoint by sending the endpoint a confirmation -- message. To actually create a subscription, the endpoint owner must call -- the 'ConfirmSubscription' action with the token from the confirmation -- message. Confirmation tokens are valid for three days. -- -- /See:/ <http://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html AWS API Reference> for Subscribe. module Network.AWS.SNS.Subscribe ( -- * Creating a Request subscribe , Subscribe -- * Request Lenses , subEndpoint , subTopicARN , subProtocol -- * Destructuring the Response , subscribeResponse , SubscribeResponse -- * Response Lenses , srsSubscriptionARN , srsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.SNS.Types import Network.AWS.SNS.Types.Product -- | Input for Subscribe action. -- -- /See:/ 'subscribe' smart constructor. data Subscribe = Subscribe' { _subEndpoint :: !(Maybe Text) , _subTopicARN :: !Text , _subProtocol :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Subscribe' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'subEndpoint' -- -- * 'subTopicARN' -- -- * 'subProtocol' subscribe :: Text -- ^ 'subTopicARN' -> Text -- ^ 'subProtocol' -> Subscribe subscribe pTopicARN_ pProtocol_ = Subscribe' { _subEndpoint = Nothing , _subTopicARN = pTopicARN_ , _subProtocol = pProtocol_ } -- | The endpoint that you want to receive notifications. Endpoints vary by -- protocol: -- -- - For the 'http' protocol, the endpoint is an URL beginning with -- \"http:\/\/\" -- - For the 'https' protocol, the endpoint is a URL beginning with -- \"https:\/\/\" -- - For the 'email' protocol, the endpoint is an email address -- - For the 'email-json' protocol, the endpoint is an email address -- - For the 'sms' protocol, the endpoint is a phone number of an -- SMS-enabled device -- - For the 'sqs' protocol, the endpoint is the ARN of an Amazon SQS -- queue -- - For the 'application' protocol, the endpoint is the EndpointArn of a -- mobile app and device. subEndpoint :: Lens' Subscribe (Maybe Text) subEndpoint = lens _subEndpoint (\ s a -> s{_subEndpoint = a}); -- | The ARN of the topic you want to subscribe to. subTopicARN :: Lens' Subscribe Text subTopicARN = lens _subTopicARN (\ s a -> s{_subTopicARN = a}); -- | The protocol you want to use. Supported protocols include: -- -- - 'http' -- delivery of JSON-encoded message via HTTP POST -- - 'https' -- delivery of JSON-encoded message via HTTPS POST -- - 'email' -- delivery of message via SMTP -- - 'email-json' -- delivery of JSON-encoded message via SMTP -- - 'sms' -- delivery of message via SMS -- - 'sqs' -- delivery of JSON-encoded message to an Amazon SQS queue -- - 'application' -- delivery of JSON-encoded message to an EndpointArn -- for a mobile app and device. subProtocol :: Lens' Subscribe Text subProtocol = lens _subProtocol (\ s a -> s{_subProtocol = a}); instance AWSRequest Subscribe where type Rs Subscribe = SubscribeResponse request = postQuery sNS response = receiveXMLWrapper "SubscribeResult" (\ s h x -> SubscribeResponse' <$> (x .@? "SubscriptionArn") <*> (pure (fromEnum s))) instance ToHeaders Subscribe where toHeaders = const mempty instance ToPath Subscribe where toPath = const "/" instance ToQuery Subscribe where toQuery Subscribe'{..} = mconcat ["Action" =: ("Subscribe" :: ByteString), "Version" =: ("2010-03-31" :: ByteString), "Endpoint" =: _subEndpoint, "TopicArn" =: _subTopicARN, "Protocol" =: _subProtocol] -- | Response for Subscribe action. -- -- /See:/ 'subscribeResponse' smart constructor. data SubscribeResponse = SubscribeResponse' { _srsSubscriptionARN :: !(Maybe Text) , _srsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SubscribeResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'srsSubscriptionARN' -- -- * 'srsResponseStatus' subscribeResponse :: Int -- ^ 'srsResponseStatus' -> SubscribeResponse subscribeResponse pResponseStatus_ = SubscribeResponse' { _srsSubscriptionARN = Nothing , _srsResponseStatus = pResponseStatus_ } -- | The ARN of the subscription, if the service was able to create a -- subscription immediately (without requiring endpoint owner -- confirmation). srsSubscriptionARN :: Lens' SubscribeResponse (Maybe Text) srsSubscriptionARN = lens _srsSubscriptionARN (\ s a -> s{_srsSubscriptionARN = a}); -- | The response status code. srsResponseStatus :: Lens' SubscribeResponse Int srsResponseStatus = lens _srsResponseStatus (\ s a -> s{_srsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-sns/gen/Network/AWS/SNS/Subscribe.hs
mpl-2.0
5,859
0
13
1,277
730
448
282
89
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, MagicHash, ImplicitParams #-} {-# LANGUAGE RankNTypes #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Err -- Copyright : (c) The University of Glasgow, 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- The "GHC.Err" module defines the code for the wired-in error functions, -- which have a special type in the compiler (with \"open tyvars\"). -- -- We cannot define these functions in a module where they might be used -- (e.g., "GHC.Base"), because the magical wired-in type will get confused -- with what the typechecker figures out. -- ----------------------------------------------------------------------------- module GHC.Err( absentErr, error, errorWithoutStackTrace, undefined ) where import GHC.CString () import GHC.Types (Char) import GHC.Stack.Types import GHC.Prim import GHC.Integer () -- Make sure Integer is compiled first -- because GHC depends on it in a wired-in way -- so the build system doesn't see the dependency import {-# SOURCE #-} GHC.Exception( errorCallException ) -- | 'error' stops execution and displays an error message. -- error :: [Char] -> a -- error s = raise# (errorCallException s) error :: [Char] -> a error s = raise# (errorCallException s) -- Bleh, we should be using 'GHC.Stack.callStack' instead of -- '?callStack' here, but 'GHC.Stack.callStack' depends on -- 'GHC.Stack.popCallStack', which is partial and depends on -- 'error'.. Do as I say, not as I do. -- | A variant of 'error' that does not produce a stack trace. -- -- @since 4.9.0.0 errorWithoutStackTrace :: [Char] -> a errorWithoutStackTrace s = raise# (errorCallException s) -- raise# (errorCallException s) -- {-# NOINLINE errorWithoutStackTrace #-} --raise# (errorCallException s) -- -- we don't have withFrozenCallStack yet, so we just inline the definition -- Note [Errors in base] -- ~~~~~~~~~~~~~~~~~~~~~ -- As of base-4.9.0.0, `error` produces a stack trace alongside the -- error message using the HasCallStack machinery. This provides -- a partial stack trace, containing the call-site of each function -- with a HasCallStack constraint. -- -- In base, however, the only functions that have such constraints are -- error and undefined, so the stack traces from partial functions in -- base will never contain a call-site in user code. Instead we'll -- usually just get the actual call to error. Base functions already -- have a good habit of providing detailed error messages, including the -- name of the offending partial function, so the partial stack-trace -- does not provide any extra information, just noise. Thus, we export -- the callstack-aware error, but within base we use the -- errorWithoutStackTrace variant for more hygienic error messages. -- | A special case of 'error'. -- It is expected that compilers will recognize this and insert error -- messages which are more appropriate to the context in which 'undefined' -- appears. undefined :: a undefined = error "Prelude.undefined" -- | Used for compiler-generated error message; -- encoding saves bytes of string junk. absentErr :: a absentErr = errorWithoutStackTrace "Oops! The program has entered an `absent' argument!\n"
rahulmutt/ghcvm
libraries/base/GHC/Err.hs
bsd-3-clause
3,497
0
7
630
214
149
65
19
1
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "Network/HPACK/Huffman/Tree.hs" #-} {-# LANGUAGE BangPatterns #-} module Network.HPACK.Huffman.Tree ( -- * Huffman decoding HTree(..) , eosInfo , toHTree , showTree , printTree , flatten ) where import Control.Arrow (second) import Data.List (partition) import Network.HPACK.Huffman.Bit import Network.HPACK.Huffman.Params ---------------------------------------------------------------- type EOSInfo = Maybe Int -- | Type for Huffman decoding. data HTree = Tip !EOSInfo -- EOS info from 1 {-# UNPACK #-} !Int -- Decoded value. Essentially Word8 | Bin !EOSInfo -- EOS info from 1 {-# UNPACK #-} !Int -- Sequence no from 0 !HTree -- Left !HTree -- Right deriving Show eosInfo :: HTree -> EOSInfo eosInfo (Tip mx _) = mx eosInfo (Bin mx _ _ _) = mx ---------------------------------------------------------------- showTree :: HTree -> String showTree = showTree' "" showTree' :: String -> HTree -> String showTree' _ (Tip _ i) = show i ++ "\n" showTree' pref (Bin _ n l r) = "No " ++ show n ++ "\n" ++ pref ++ "+ " ++ showTree' pref' l ++ pref ++ "+ " ++ showTree' pref' r where pref' = " " ++ pref printTree :: HTree -> IO () printTree = putStr . showTree ---------------------------------------------------------------- -- | Creating 'HTree'. toHTree :: [Bits] -> HTree toHTree bs = mark 1 eos $ snd $ build 0 $ zip [0..idxEos] bs where eos = bs !! idxEos build :: Int -> [(Int,Bits)] -> (Int, HTree) build !cnt0 [(v,[])] = (cnt0,Tip Nothing v) build !cnt0 xs = let (cnt1,l) = build (cnt0 + 1) fs (cnt2,r) = build cnt1 ts in (cnt2, Bin Nothing cnt0 l r) where (fs',ts') = partition ((==) F . head . snd) xs fs = map (second tail) fs' ts = map (second tail) ts' -- | Marking the EOS path mark :: Int -> Bits -> HTree -> HTree mark i [] (Tip Nothing v) = Tip (Just i) v mark i (F:bs) (Bin Nothing n l r) = Bin (Just i) n (mark (i+1) bs l) r mark i (T:bs) (Bin Nothing n l r) = Bin (Just i) n l (mark (i+1) bs r) mark _ _ _ = error "mark" ---------------------------------------------------------------- flatten :: HTree -> [HTree] flatten (Tip _ _) = [] flatten t@(Bin _ _ l r) = t : (flatten l ++ flatten r)
phischu/fragnix
tests/packages/scotty/Network.HPACK.Huffman.Tree.hs
bsd-3-clause
2,516
0
13
753
849
453
396
64
1
module PackageTests.TestStanza.Check where import Test.HUnit import System.FilePath import PackageTests.PackageTester import Distribution.Version import Distribution.PackageDescription.Parse (readPackageDescription) import Distribution.PackageDescription.Configuration (finalizePackageDescription) import Distribution.Package (PackageName(..), Dependency(..)) import Distribution.PackageDescription ( PackageDescription(..), BuildInfo(..), TestSuite(..) , TestSuiteInterface(..), emptyBuildInfo, emptyTestSuite) import Distribution.Verbosity (silent) import Distribution.System (buildPlatform) import Distribution.Compiler (CompilerId(..), CompilerFlavor(..)) import Distribution.Text suite :: FilePath -> Test suite ghcPath = TestCase $ do let dir = "PackageTests" </> "TestStanza" pdFile = dir </> "my" <.> "cabal" spec = PackageSpec dir [] result <- cabal_configure spec ghcPath assertOutputDoesNotContain "unknown section type" result genPD <- readPackageDescription silent pdFile let compiler = CompilerId GHC $ Version [6, 12, 2] [] anticipatedTestSuite = emptyTestSuite { testName = "dummy" , testInterface = TestSuiteExeV10 (Version [1,0] []) "dummy.hs" , testBuildInfo = emptyBuildInfo { targetBuildDepends = [ Dependency (PackageName "base") anyVersion ] , hsSourceDirs = ["."] } , testEnabled = False } case finalizePackageDescription [] (const True) buildPlatform compiler [] genPD of Left xs -> let depMessage = "should not have missing dependencies:\n" ++ (unlines $ map (show . disp) xs) in assertEqual depMessage True False Right (f, _) -> let gotTest = head $ testSuites f in assertEqual "parsed test-suite stanza does not match anticipated" gotTest anticipatedTestSuite
jwiegley/ghc-release
libraries/Cabal/cabal/tests/PackageTests/TestStanza/Check.hs
gpl-3.0
2,025
0
20
529
483
267
216
40
2
{-# LANGUAGE GADTs #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} -- | -- Module : Data.Array.Accelerate.CUDA.CodeGen.IndexSpace -- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller -- [2009..2014] Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Trevor L. McDonell <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module Data.Array.Accelerate.CUDA.CodeGen.IndexSpace ( -- Array construction mkGenerate, -- Permutations mkTransform, mkPermute, ) where import Language.C.Quote.CUDA import Foreign.CUDA.Analysis.Device import qualified Language.C.Syntax as C import Data.Array.Accelerate.Array.Sugar ( Array, Shape, Elt, ignore, shapeToList ) import Data.Array.Accelerate.Error ( internalError ) import Data.Array.Accelerate.CUDA.AST ( Gamma ) import Data.Array.Accelerate.CUDA.CodeGen.Base -- Construct a new array by applying a function to each index. Each thread -- processes multiple elements, striding the array by the grid size. -- -- generate :: (Shape ix, Elt e) -- => Exp ix -- dimension of the result -- -> (Exp ix -> Exp a) -- function to apply at each index -- -> Acc (Array ix a) -- mkGenerate :: forall aenv sh e. (Shape sh, Elt e) => DeviceProperties -> Gamma aenv -> CUFun1 aenv (sh -> e) -> [CUTranslSkel aenv (Array sh e)] mkGenerate dev aenv (CUFun1 dce f) = return $ CUTranslSkel "generate" [cunit| $esc:("#include <accelerate_cuda.h>") $edecls:texIn extern "C" __global__ void generate ( $params:argIn, $params:argOut ) { const int shapeSize = $exp:(csize shOut); const int gridSize = $exp:(gridSize dev); int ix; for ( ix = $exp:(threadIdx dev) ; ix < shapeSize ; ix += gridSize ) { $items:(dce sh .=. cfromIndex shOut "ix" "tmp") $items:(setOut "ix" .=. f sh) } } |] where (sh, _, _) = locals "sh" (undefined :: sh) (texIn, argIn) = environment dev aenv (argOut, shOut, setOut) = writeArray "Out" (undefined :: Array sh e) -- A combination map/backpermute, where the index and value transformations have -- been separated. -- -- transform :: (Elt a, Elt b, Shape sh, Shape sh') -- => PreExp acc aenv sh' -- dimension of the result -- -> PreFun acc aenv (sh' -> sh) -- index permutation function -- -> PreFun acc aenv (a -> b) -- function to apply at each element -- -> acc aenv (Array sh a) -- source array -- -> PreOpenAcc acc aenv (Array sh' b) -- mkTransform :: forall aenv sh sh' a b. (Shape sh, Shape sh', Elt a, Elt b) => DeviceProperties -> Gamma aenv -> CUFun1 aenv (sh' -> sh) -> CUFun1 aenv (a -> b) -> CUDelayedAcc aenv sh a -> [CUTranslSkel aenv (Array sh' b)] mkTransform dev aenv perm fun arr | CUFun1 dce_p p <- perm , CUFun1 dce_f f <- fun , CUDelayed _ (CUFun1 dce_g get) _ <- arr = return $ CUTranslSkel "transform" [cunit| $esc:("#include <accelerate_cuda.h>") $edecls:texIn extern "C" __global__ void transform ( $params:argIn, $params:argOut ) { const int shapeSize = $exp:(csize shOut); const int gridSize = $exp:(gridSize dev); int ix; for ( ix = $exp:(threadIdx dev) ; ix < shapeSize ; ix += gridSize ) { $items:(dce_p sh' .=. cfromIndex shOut "ix" "tmp") $items:(dce_g sh .=. p sh') $items:(dce_f x0 .=. get sh) $items:(setOut "ix" .=. f x0) } } |] where (texIn, argIn) = environment dev aenv (argOut, shOut, setOut) = writeArray "Out" (undefined :: Array sh' b) (x0, _, _) = locals "x" (undefined :: a) (sh, _, _) = locals "sh" (undefined :: sh) (sh', _, _) = locals "sh_" (undefined :: sh') -- Forward permutation specified by an index mapping that determines for each -- element in the source array where it should go in the target. The resultant -- array is initialised with the given defaults and any further values that are -- permuted into the result array are added to the current value using the given -- combination function. -- -- The combination function must be associative. Extents that are mapped to the -- magic value 'ignore' by the permutation function are dropped. -- -- permute :: (Shape ix, Shape ix', Elt a) -- => (Exp a -> Exp a -> Exp a) -- combination function -- -> Acc (Array ix' a) -- array of default values -- -> (Exp ix -> Exp ix') -- permutation -- -> Acc (Array ix a) -- permuted array -- -> Acc (Array ix' a) -- mkPermute :: forall aenv sh sh' e. (Shape sh, Shape sh', Elt e) => DeviceProperties -> Gamma aenv -> CUFun2 aenv (e -> e -> e) -> CUFun1 aenv (sh -> sh') -> CUDelayedAcc aenv sh e -> [CUTranslSkel aenv (Array sh' e)] mkPermute dev aenv (CUFun2 dce_x dce_y combine) (CUFun1 dce_p prj) arr | CUDelayed (CUExp shIn) _ (CUFun1 _ get) <- arr = return $ CUTranslSkel "permute" [cunit| $esc:("#include <accelerate_cuda.h>") $edecls:texIn extern "C" __global__ void permute ( $params:argIn, $params:argOut, typename Int32 * __restrict__ lock ) { /* * The input shape might be a complex expression. Evaluate it first to reuse the result. */ $items:(sh .=. shIn) const int shapeSize = $exp:(csize sh); const int gridSize = $exp:(gridSize dev); int ix; for ( ix = $exp:(threadIdx dev) ; ix < shapeSize ; ix += gridSize ) { $items:(dce_p src .=. cfromIndex sh "ix" "srcTmp") $items:(dst .=. prj src) if ( ! $exp:(cignore dst) ) { $items:(jx .=. ctoIndex shOut dst) $items:(dce_x x .=. get ix) $items:(atomically jx [ dce_y y .=. setOut jx , setOut jx .=. combine x y ] ) } } } |] where (texIn, argIn) = environment dev aenv (argOut, shOut, setOut) = writeArray "Out" (undefined :: Array sh' e) (x, _, _) = locals "x" (undefined :: e) (y, _, _) = locals "y" (undefined :: e) (sh, _, _) = locals "shIn" (undefined :: sh) (src, _, _) = locals "sh" (undefined :: sh) (dst, _, _) = locals "sh_" (undefined :: sh') ([jx], _, _) = locals "jx" (undefined :: Int) ix = [cvar "ix"] sm = computeCapability dev -- If the destination index resolves to the magic index "ignore", the result -- is dropped from the output array. -- cignore :: Rvalue x => [x] -> C.Exp cignore [] = $internalError "permute" "singleton arrays not supported" cignore xs = foldl1 (\a b -> [cexp| $exp:a && $exp:b |]) $ zipWith (\a b -> [cexp| $exp:(rvalue a) == $int:b |]) xs $ shapeToList (ignore :: sh') -- If we can determine that the old values are not used in the combination -- function (e.g. filter) then the lock and unlock fragments can be replaced -- with a NOP. -- -- If locking is required but the hardware does not support it (compute 1.0) -- then we issue a runtime error immediately instead of silently failing. -- mustLock = or . fst . unzip $ dce_y y -- The atomic section is acquired using a spin lock. This requires a -- temporary array to represent the lock state for each element of the -- output. We use 1 to represent the locked state, and 0 to represent -- unlocked elements. -- -- do { -- old = atomicExch(&lock[i], 1); // atomic exchange -- } while (old == 1); -- -- /* critical section */ -- -- atomicExch(&lock[i], 0); -- -- The initial loop repeatedly attempts to take the lock by writing a 1 into -- the slot. Once the 'old' state of the lock returns 0 (unlocked), we have -- just acquired the lock, and the atomic section can be computed. Finally, -- atomically write a 0 back into the slot to unlock the element. -- -- However, there is a complication with CUDA devices because all threads in -- the warp must execute in lockstep (with predicated execution). Once a -- thread acquires a lock, then it will be disabled and stop participating -- in the first loop, waiting until all other threads in the warp acquire -- their locks. If two threads in a warp are attempting to acquire the same -- lock, once the lock is acquired by the first thread, it sits idle while -- the second thread spins attempting to grab a lock that will never be -- released, because the first thread can not progress. DEADLOCK. -- -- So, we need to invert the algorithm so that threads can always make -- progress, until each thread in the warp has committed their result. -- -- done = 0; -- do { -- if (atomicExch(&lock[i], 1) == 0) { -- -- /* critical section */ -- -- done = 1; -- atomicExch(&lock[i], 0); -- } -- } while (done == 0) -- atomically :: (C.Type, Name) -> [[C.BlockItem]] -> [C.BlockItem] atomically (_,i) (concat -> body) | not mustLock = body | sm < Compute 1 1 = $internalError "permute" "Requires at least compute compatibility 1.1" | otherwise = [ [citem| typename Int32 done = 0; |] , [citem| do { __threadfence(); if ( atomicExch(&lock[ $exp:(cvar i) ], 1) == 0 ) { $items:body done = 1; atomicExch(&lock[ $exp:(cvar i) ], 0); } } while (done == 0); |] ]
mwu-tow/accelerate-cuda
Data/Array/Accelerate/CUDA/CodeGen/IndexSpace.hs
bsd-3-clause
10,838
0
15
3,776
1,351
794
557
83
2
-------------------------------------------------------------------- -- | -- Module : Text.DublinCore.Types -- Copyright : (c) Galois, Inc. 2008, -- (c) Sigbjorn Finne 2009- -- License : BSD3 -- -- Maintainer: Sigbjorn Finne <[email protected]> -- Stability : provisional -- -- Representing the DublinCore metadata elements in Haskell. -- For information on the Dublin Core Metadata Element Set, -- see: <http://dublincore.org/> -- module Text.DublinCore.Types where -- | A DCItem pairs a specific element with its (string) value. data DCItem = DCItem { dcElt :: DCInfo , dcText :: String } deriving (Eq, Show) -- | The Dublin Core Metadata Element Set, all 15 of them (plus an extension constructor.) data DCInfo = DC_Title -- ^ A name given to the resource. | DC_Creator -- ^ An entity primarily responsible for making the content of the resource. | DC_Subject -- ^ The topic of the content of the resource. | DC_Description -- ^ An account of the content of the resource. | DC_Publisher -- ^ An entity responsible for making the resource available | DC_Contributor -- ^ An entity responsible for making contributions to the content of the resource. | DC_Date -- ^ A date associated with an event in the life cycle of the resource (YYYY-MM-DD) | DC_Type -- ^ The nature or genre of the content of the resource. | DC_Format -- ^ The physical or digital manifestation of the resource. | DC_Identifier -- ^ An unambiguous reference to the resource within a given context. | DC_Source -- ^ A Reference to a resource from which the present resource is derived. | DC_Language -- ^ A language of the intellectual content of the resource. | DC_Relation -- ^ A reference to a related resource. | DC_Coverage -- ^ The extent or scope of the content of the resource. | DC_Rights -- ^ Information about rights held in and over the resource. | DC_Other String -- ^ Other; data type extension mechanism. deriving (Eq, Show) infoToTag :: DCInfo -> String infoToTag i = case i of DC_Title -> "title" DC_Creator -> "creator" DC_Subject -> "subject" DC_Description -> "description" DC_Publisher -> "publisher" DC_Contributor -> "contributor" DC_Date -> "date" DC_Type -> "type" DC_Format -> "format" DC_Identifier -> "identifier" DC_Source -> "source" DC_Language -> "language" DC_Relation -> "relation" DC_Coverage -> "coverage" DC_Rights -> "rights" DC_Other o -> o dc_element_names :: [String] dc_element_names = [ "title" , "creator" , "subject" , "description" , "publisher" , "contributor" , "date" , "type" , "format" , "identifier" , "source" , "language" , "relation" , "coverage" , "rights" ]
danfran/feed
src/Text/DublinCore/Types.hs
bsd-3-clause
2,905
0
8
736
314
195
119
60
16
{- | Module : StringUtils Description : Utilities for string operations. Copyright : (c) 2014—2015 The F2J Project Developers (given in AUTHORS.txt) License : BSD3 Maintainer : Zhiyuan Shi <[email protected]> Stability : experimental Portability : portable -} module StringUtils ( capitalize ) where import qualified Data.Char as Char (toUpper) capitalize :: String -> String capitalize "" = "" capitalize (s:ss) = Char.toUpper s : ss
bixuanzju/fcore
lib/StringUtils.hs
bsd-2-clause
470
0
7
94
64
37
27
6
1
-- (c) The University of Glasgow 2006 {-# LANGUAGE CPP, FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- instance MonadThings is necessarily an orphan module TcEnv( TyThing(..), TcTyThing(..), TcId, -- Instance environment, and InstInfo type InstInfo(..), iDFunId, pprInstInfoDetails, simpleInstInfoClsTy, simpleInstInfoTy, simpleInstInfoTyCon, InstBindings(..), -- Global environment tcExtendGlobalEnv, tcExtendGlobalEnvImplicit, setGlobalTypeEnv, tcExtendGlobalValEnv, tcLookupLocatedGlobal, tcLookupGlobal, tcLookupField, tcLookupTyCon, tcLookupClass, tcLookupDataCon, tcLookupPatSyn, tcLookupConLike, tcLookupLocatedGlobalId, tcLookupLocatedTyCon, tcLookupLocatedClass, tcLookupAxiom, -- Local environment tcExtendKindEnv, tcExtendKindEnv2, tcExtendTyVarEnv, tcExtendTyVarEnv2, tcExtendLetEnv, tcExtendIdEnv, tcExtendIdEnv1, tcExtendIdEnv2, tcExtendIdEnv3, tcExtendIdBndrs, tcExtendGhciIdEnv, tcLookup, tcLookupLocated, tcLookupLocalIds, tcLookupId, tcLookupTyVar, tcLookupLcl_maybe, getScopedTyVarBinds, getInLocalScope, wrongThingErr, pprBinders, tcExtendRecEnv, -- For knot-tying -- Instances tcLookupInstance, tcGetInstEnvs, -- Rules tcExtendRules, -- Defaults tcGetDefaultTys, -- Global type variables tcGetGlobalTyVars, zapLclTypeEnv, -- Template Haskell stuff checkWellStaged, tcMetaTy, thLevel, topIdLvl, isBrackStage, -- New Ids newLocalName, newDFunName, newFamInstTyConName, newFamInstAxiomName, mkStableIdFromString, mkStableIdFromName, mkWrapperName ) where #include "HsVersions.h" import HsSyn import IfaceEnv import TcRnMonad import TcMType import TcType import LoadIface import PrelNames import TysWiredIn import Id import IdInfo( IdDetails(VanillaId) ) import Var import VarSet import RdrName import InstEnv import DataCon ( DataCon ) import PatSyn ( PatSyn ) import ConLike import TyCon import CoAxiom import TypeRep import Class import Name import NameEnv import VarEnv import HscTypes import DynFlags import SrcLoc import BasicTypes hiding( SuccessFlag(..) ) import Module import Outputable import Encoding import FastString import ListSetOps import Util import Maybes( MaybeErr(..) ) import Data.IORef import Data.List {- ************************************************************************ * * * tcLookupGlobal * * * ************************************************************************ Using the Located versions (eg. tcLookupLocatedGlobal) is preferred, unless you know that the SrcSpan in the monad is already set to the span of the Name. -} tcLookupLocatedGlobal :: Located Name -> TcM TyThing -- c.f. IfaceEnvEnv.tcIfaceGlobal tcLookupLocatedGlobal name = addLocM tcLookupGlobal name tcLookupGlobal :: Name -> TcM TyThing -- The Name is almost always an ExternalName, but not always -- In GHCi, we may make command-line bindings (ghci> let x = True) -- that bind a GlobalId, but with an InternalName tcLookupGlobal name = do { -- Try local envt env <- getGblEnv ; case lookupNameEnv (tcg_type_env env) name of { Just thing -> return thing ; Nothing -> -- Should it have been in the local envt? if nameIsLocalOrFrom (tcg_mod env) name then notFound name -- Internal names can happen in GHCi else -- Try home package table and external package table do { mb_thing <- tcLookupImported_maybe name ; case mb_thing of Succeeded thing -> return thing Failed msg -> failWithTc msg }}} tcLookupField :: Name -> TcM Id -- Returns the selector Id tcLookupField name = tcLookupId name -- Note [Record field lookup] {- Note [Record field lookup] ~~~~~~~~~~~~~~~~~~~~~~~~~~ You might think we should have tcLookupGlobal here, since record fields are always top level. But consider f = e { f = True } Then the renamer (which does not keep track of what is a record selector and what is not) will rename the definition thus f_7 = e { f_7 = True } Now the type checker will find f_7 in the *local* type environment, not the global (imported) one. It's wrong, of course, but we want to report a tidy error, not in TcEnv.notFound. -} tcLookupDataCon :: Name -> TcM DataCon tcLookupDataCon name = do thing <- tcLookupGlobal name case thing of AConLike (RealDataCon con) -> return con _ -> wrongThingErr "data constructor" (AGlobal thing) name tcLookupPatSyn :: Name -> TcM PatSyn tcLookupPatSyn name = do thing <- tcLookupGlobal name case thing of AConLike (PatSynCon ps) -> return ps _ -> wrongThingErr "pattern synonym" (AGlobal thing) name tcLookupConLike :: Name -> TcM ConLike tcLookupConLike name = do thing <- tcLookupGlobal name case thing of AConLike cl -> return cl _ -> wrongThingErr "constructor-like thing" (AGlobal thing) name tcLookupClass :: Name -> TcM Class tcLookupClass name = do thing <- tcLookupGlobal name case thing of ATyCon tc | Just cls <- tyConClass_maybe tc -> return cls _ -> wrongThingErr "class" (AGlobal thing) name tcLookupTyCon :: Name -> TcM TyCon tcLookupTyCon name = do thing <- tcLookupGlobal name case thing of ATyCon tc -> return tc _ -> wrongThingErr "type constructor" (AGlobal thing) name tcLookupAxiom :: Name -> TcM (CoAxiom Branched) tcLookupAxiom name = do thing <- tcLookupGlobal name case thing of ACoAxiom ax -> return ax _ -> wrongThingErr "axiom" (AGlobal thing) name tcLookupLocatedGlobalId :: Located Name -> TcM Id tcLookupLocatedGlobalId = addLocM tcLookupId tcLookupLocatedClass :: Located Name -> TcM Class tcLookupLocatedClass = addLocM tcLookupClass tcLookupLocatedTyCon :: Located Name -> TcM TyCon tcLookupLocatedTyCon = addLocM tcLookupTyCon -- Find the instance that exactly matches a type class application. The class arguments must be precisely -- the same as in the instance declaration (modulo renaming). -- tcLookupInstance :: Class -> [Type] -> TcM ClsInst tcLookupInstance cls tys = do { instEnv <- tcGetInstEnvs ; case lookupUniqueInstEnv instEnv cls tys of Left err -> failWithTc $ ptext (sLit "Couldn't match instance:") <+> err Right (inst, tys) | uniqueTyVars tys -> return inst | otherwise -> failWithTc errNotExact } where errNotExact = ptext (sLit "Not an exact match (i.e., some variables get instantiated)") uniqueTyVars tys = all isTyVarTy tys && hasNoDups (map extractTyVar tys) where extractTyVar (TyVarTy tv) = tv extractTyVar _ = panic "TcEnv.tcLookupInstance: extractTyVar" tcGetInstEnvs :: TcM InstEnvs -- Gets both the external-package inst-env -- and the home-pkg inst env (includes module being compiled) tcGetInstEnvs = do { eps <- getEps ; env <- getGblEnv ; return (InstEnvs { ie_global = eps_inst_env eps , ie_local = tcg_inst_env env , ie_visible = tcg_visible_orphan_mods env }) } instance MonadThings (IOEnv (Env TcGblEnv TcLclEnv)) where lookupThing = tcLookupGlobal {- ************************************************************************ * * Extending the global environment * * ************************************************************************ -} setGlobalTypeEnv :: TcGblEnv -> TypeEnv -> TcM TcGblEnv -- Use this to update the global type env -- It updates both * the normal tcg_type_env field -- * the tcg_type_env_var field seen by interface files setGlobalTypeEnv tcg_env new_type_env = do { -- Sync the type-envt variable seen by interface files writeMutVar (tcg_type_env_var tcg_env) new_type_env ; return (tcg_env { tcg_type_env = new_type_env }) } tcExtendGlobalEnvImplicit :: [TyThing] -> TcM r -> TcM r -- Extend the global environment with some TyThings that can be obtained -- via implicitTyThings from other entities in the environment. Examples -- are dfuns, famInstTyCons, data cons, etc. -- These TyThings are not added to tcg_tcs. tcExtendGlobalEnvImplicit things thing_inside = do { tcg_env <- getGblEnv ; let ge' = extendTypeEnvList (tcg_type_env tcg_env) things ; tcg_env' <- setGlobalTypeEnv tcg_env ge' ; setGblEnv tcg_env' thing_inside } tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r -- Given a mixture of Ids, TyCons, Classes, all defined in the -- module being compiled, extend the global environment tcExtendGlobalEnv things thing_inside = do { env <- getGblEnv ; let env' = env { tcg_tcs = [tc | ATyCon tc <- things] ++ tcg_tcs env, tcg_patsyns = [ps | AConLike (PatSynCon ps) <- things] ++ tcg_patsyns env } ; setGblEnv env' $ tcExtendGlobalEnvImplicit things thing_inside } tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a -- Same deal as tcExtendGlobalEnv, but for Ids tcExtendGlobalValEnv ids thing_inside = tcExtendGlobalEnvImplicit [AnId id | id <- ids] thing_inside tcExtendRecEnv :: [(Name,TyThing)] -> TcM r -> TcM r -- Extend the global environments for the type/class knot tying game -- Just like tcExtendGlobalEnv, except the argument is a list of pairs tcExtendRecEnv gbl_stuff thing_inside = do { tcg_env <- getGblEnv ; let ge' = extendNameEnvList (tcg_type_env tcg_env) gbl_stuff ; tcg_env' <- setGlobalTypeEnv tcg_env ge' ; setGblEnv tcg_env' thing_inside } {- ************************************************************************ * * \subsection{The local environment} * * ************************************************************************ -} tcLookupLocated :: Located Name -> TcM TcTyThing tcLookupLocated = addLocM tcLookup tcLookupLcl_maybe :: Name -> TcM (Maybe TcTyThing) tcLookupLcl_maybe name = do { local_env <- getLclTypeEnv ; return (lookupNameEnv local_env name) } tcLookup :: Name -> TcM TcTyThing tcLookup name = do local_env <- getLclTypeEnv case lookupNameEnv local_env name of Just thing -> return thing Nothing -> AGlobal <$> tcLookupGlobal name tcLookupTyVar :: Name -> TcM TcTyVar tcLookupTyVar name = do { thing <- tcLookup name ; case thing of ATyVar _ tv -> return tv _ -> pprPanic "tcLookupTyVar" (ppr name) } tcLookupId :: Name -> TcM Id -- Used when we aren't interested in the binding level, nor refinement. -- The "no refinement" part means that we return the un-refined Id regardless -- -- The Id is never a DataCon. (Why does that matter? see TcExpr.tcId) tcLookupId name = do thing <- tcLookup name case thing of ATcId { tct_id = id} -> return id AGlobal (AnId id) -> return id _ -> pprPanic "tcLookupId" (ppr name) tcLookupLocalIds :: [Name] -> TcM [TcId] -- We expect the variables to all be bound, and all at -- the same level as the lookup. Only used in one place... tcLookupLocalIds ns = do { env <- getLclEnv ; return (map (lookup (tcl_env env)) ns) } where lookup lenv name = case lookupNameEnv lenv name of Just (ATcId { tct_id = id }) -> id _ -> pprPanic "tcLookupLocalIds" (ppr name) getInLocalScope :: TcM (Name -> Bool) -- Ids only getInLocalScope = do { lcl_env <- getLclTypeEnv ; return (`elemNameEnv` lcl_env) } tcExtendKindEnv2 :: [(Name, TcTyThing)] -> TcM r -> TcM r -- Used only during kind checking, for TcThings that are -- AThing or APromotionErr -- No need to update the global tyvars, or tcl_th_bndrs, or tcl_rdr tcExtendKindEnv2 things thing_inside = updLclEnv upd_env thing_inside where upd_env env = env { tcl_env = extendNameEnvList (tcl_env env) things } tcExtendKindEnv :: [(Name, TcKind)] -> TcM r -> TcM r tcExtendKindEnv name_kind_prs = tcExtendKindEnv2 [(n, AThing k) | (n,k) <- name_kind_prs] ----------------------- -- Scoped type and kind variables tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r tcExtendTyVarEnv tvs thing_inside = tcExtendTyVarEnv2 [(tyVarName tv, tv) | tv <- tvs] thing_inside tcExtendTyVarEnv2 :: [(Name,TcTyVar)] -> TcM r -> TcM r tcExtendTyVarEnv2 binds thing_inside = do { stage <- getStage ; tc_extend_local_env (NotTopLevel, thLevel stage) [(name, ATyVar name tv) | (name, tv) <- binds] $ do { env <- getLclEnv ; let env' = env { tcl_tidy = add_tidy_tvs (tcl_tidy env) } ; setLclEnv env' thing_inside }} where add_tidy_tvs env = foldl add env binds -- We initialise the "tidy-env", used for tidying types before printing, -- by building a reverse map from the in-scope type variables to the -- OccName that the programmer originally used for them add :: TidyEnv -> (Name, TcTyVar) -> TidyEnv add (env,subst) (name, tyvar) = case tidyOccName env (nameOccName name) of (env', occ') -> (env', extendVarEnv subst tyvar tyvar') where tyvar' = setTyVarName tyvar name' name' = tidyNameOcc name occ' getScopedTyVarBinds :: TcM [(Name, TcTyVar)] getScopedTyVarBinds = do { lcl_env <- getLclEnv ; return [(name, tv) | ATyVar name tv <- nameEnvElts (tcl_env lcl_env)] } {- Note [Initialising the type environment for GHCi] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tcExtendGhciIdEnv extends the local type environemnt with GHCi identifiers (from ic_tythings), bound earlier in the interaction. They may have free type variables (RuntimeUnk things), and if we don't register these free TyVars as global TyVars then the typechecker will try to quantify over them and fall over in zonkQuantifiedTyVar. So we must add any free TyVars to the typechecker's global TyVar set. That is most conveniently done here, using the local function tcExtendLocalTypeEnv. Note especially that * tcExtendGhciIdEnv extends the local type env, tcl_env That's important because some are not closed (ie have free tyvars) and the compiler assumes that the global type env (tcg_type_env) has no free tyvars. Actually, only ones with Internal names can be non-closed so we jsut add those * The tct_closed flag depends on whether the thing has free (RuntimeUnk) type variables * It will also does tcExtendGlobalTyVars; this is important because of those RuntimeUnk variables * It does not extend the local RdrEnv (tcl_rdr), because the things are already in the GlobalRdrEnv. Extending the local RdrEnv isn't terrible, but it means there is an entry for the same Name in both global and local RdrEnvs, and that lead to duplicate "perhaps you meant..." suggestions (e.g. T5564). We don't bother with the tcl_th_bndrs environment either. * NB: all these TcTyThings will be in the global type envt (tcg_type_env) as well. We are just shadowing them here to deal with the global tyvar stuff. That's why we can simply drop the External-Name ones; they will be found in the global envt -} tcExtendGhciIdEnv :: [TyThing] -> TcM a -> TcM a -- Used to bind Ids for GHCi identifiers bound earlier in the user interaction -- See Note [Initialising the type environment for GHCi] tcExtendGhciIdEnv ids thing_inside = do { lcl_env <- tcExtendLocalTypeEnv tc_ty_things emptyVarSet ; setLclEnv lcl_env thing_inside } where tc_ty_things = [ (name, ATcId { tct_id = id , tct_closed = is_top id }) | AnId id <- ids , let name = idName id , isInternalName name ] is_top id | isEmptyVarSet (tyVarsOfType (idType id)) = TopLevel | otherwise = NotTopLevel tcExtendLetEnv :: TopLevelFlag -> TopLevelFlag -> [TcId] -> TcM a -> TcM a -- Used for both top-level value bindings and and nested let/where-bindings tcExtendLetEnv top_lvl closed ids thing_inside = do { stage <- getStage ; tc_extend_local_env (top_lvl, thLevel stage) [ (idName id, ATcId { tct_id = id , tct_closed = closed }) | id <- ids] $ tcExtendIdBndrs [TcIdBndr id top_lvl | id <- ids] thing_inside } tcExtendIdEnv :: [TcId] -> TcM a -> TcM a tcExtendIdEnv ids thing_inside = tcExtendIdEnv2 [(idName id, id) | id <- ids] $ tcExtendIdBndrs [TcIdBndr id NotTopLevel | id <- ids] thing_inside tcExtendIdEnv1 :: Name -> TcId -> TcM a -> TcM a tcExtendIdEnv1 name id thing_inside = tcExtendIdEnv2 [(name,id)] $ tcExtendIdBndrs [TcIdBndr id NotTopLevel] thing_inside tcExtendIdEnv2 :: [(Name,TcId)] -> TcM a -> TcM a -- Do *not* extend the tcl_bndrs stack -- The tct_closed flag really doesn't matter -- Invariant: the TcIds are fully zonked (see tcExtendIdEnv above) tcExtendIdEnv2 names_w_ids thing_inside = tcExtendIdEnv3 names_w_ids emptyVarSet thing_inside -- | 'tcExtendIdEnv2', but don't bind the 'TcId's in the 'TyVarSet' argument. tcExtendIdEnv3 :: [(Name,TcId)] -> TyVarSet -> TcM a -> TcM a -- Invariant: the TcIds are fully zonked (see tcExtendIdEnv above) tcExtendIdEnv3 names_w_ids not_actually_free thing_inside = do { stage <- getStage ; tc_extend_local_env2 (NotTopLevel, thLevel stage) [ (name, ATcId { tct_id = id , tct_closed = NotTopLevel }) | (name,id) <- names_w_ids] not_actually_free $ thing_inside } tcExtendIdBndrs :: [TcIdBinder] -> TcM a -> TcM a tcExtendIdBndrs bndrs = updLclEnv (\env -> env { tcl_bndrs = bndrs ++ tcl_bndrs env }) tc_extend_local_env :: (TopLevelFlag, ThLevel) -> [(Name, TcTyThing)] -> TcM a -> TcM a tc_extend_local_env thlvl extra_env thing_inside = tc_extend_local_env2 thlvl extra_env emptyVarSet thing_inside tc_extend_local_env2 :: (TopLevelFlag, ThLevel) -> [(Name, TcTyThing)] -> TyVarSet -> TcM a -> TcM a tc_extend_local_env2 thlvl extra_env not_actually_free thing_inside -- Precondition: the argument list extra_env has TcTyThings -- that ATcId or ATyVar, but nothing else -- -- Invariant: the ATcIds are fully zonked. Reasons: -- (a) The kinds of the forall'd type variables are defaulted -- (see Kind.defaultKind, done in zonkQuantifiedTyVar) -- (b) There are no via-Indirect occurrences of the bound variables -- in the types, because instantiation does not look through such things -- (c) The call to tyVarsOfTypes is ok without looking through refs -- The second argument of type TyVarSet is a set of type variables -- that are bound together with extra_env and should not be regarded -- as free in the types of extra_env. = do { traceTc "env2" (ppr extra_env) ; env1 <- tcExtendLocalTypeEnv extra_env not_actually_free ; let env2 = extend_local_env thlvl extra_env env1 ; setLclEnv env2 thing_inside } where extend_local_env :: (TopLevelFlag, ThLevel) -> [(Name, TcTyThing)] -> TcLclEnv -> TcLclEnv -- Extend the local LocalRdrEnv and Template Haskell staging env simultaneously -- Reason for extending LocalRdrEnv: after running a TH splice we need -- to do renaming. extend_local_env thlvl pairs env@(TcLclEnv { tcl_rdr = rdr_env , tcl_th_bndrs = th_bndrs }) = env { tcl_rdr = extendLocalRdrEnvList rdr_env [ n | (n, _) <- pairs, isInternalName n ] -- The LocalRdrEnv contains only non-top-level names -- (GlobalRdrEnv handles the top level) , tcl_th_bndrs = extendNameEnvList th_bndrs -- We only track Ids in tcl_th_bndrs [(n, thlvl) | (n, ATcId {}) <- pairs] } tcExtendLocalTypeEnv :: [(Name, TcTyThing)] -> TyVarSet -> TcM TcLclEnv tcExtendLocalTypeEnv tc_ty_things not_actually_free | isEmptyVarSet extra_tvs = do { lcl_env@(TcLclEnv { tcl_env = lcl_type_env }) <- getLclEnv ; return (lcl_env { tcl_env = extendNameEnvList lcl_type_env tc_ty_things } ) } | otherwise = do { lcl_env@(TcLclEnv { tcl_env = lcl_type_env }) <- getLclEnv ; global_tvs <- readMutVar (tcl_tyvars lcl_env) ; new_g_var <- newMutVar (global_tvs `unionVarSet` extra_tvs) ; return (lcl_env { tcl_tyvars = new_g_var , tcl_env = extendNameEnvList lcl_type_env tc_ty_things } ) } where extra_tvs = foldr get_tvs emptyVarSet tc_ty_things `minusVarSet` not_actually_free get_tvs (_, ATcId { tct_id = id, tct_closed = closed }) tvs = case closed of TopLevel -> ASSERT2( isEmptyVarSet id_tvs, ppr id $$ ppr (idType id) ) tvs NotTopLevel -> tvs `unionVarSet` id_tvs where id_tvs = tyVarsOfType (idType id) get_tvs (_, ATyVar _ tv) tvs -- See Note [Global TyVars] = tvs `unionVarSet` tyVarsOfType (tyVarKind tv) `extendVarSet` tv get_tvs (_, AThing k) tvs = tvs `unionVarSet` tyVarsOfType k get_tvs (_, AGlobal {}) tvs = tvs get_tvs (_, APromotionErr {}) tvs = tvs -- Note [Global TyVars] -- It's important to add the in-scope tyvars to the global tyvar set -- as well. Consider -- f (_::r) = let g y = y::r in ... -- Here, g mustn't be generalised. This is also important during -- class and instance decls, when we mustn't generalise the class tyvars -- when typechecking the methods. -- -- Nor must we generalise g over any kind variables free in r's kind zapLclTypeEnv :: TcM a -> TcM a zapLclTypeEnv thing_inside = do { tvs_var <- newTcRef emptyVarSet ; let upd env = env { tcl_env = emptyNameEnv , tcl_rdr = emptyLocalRdrEnv , tcl_tyvars = tvs_var } ; updLclEnv upd thing_inside } {- ************************************************************************ * * \subsection{Rules} * * ************************************************************************ -} tcExtendRules :: [LRuleDecl Id] -> TcM a -> TcM a -- Just pop the new rules into the EPS and envt resp -- All the rules come from an interface file, not source -- Nevertheless, some may be for this module, if we read -- its interface instead of its source code tcExtendRules lcl_rules thing_inside = do { env <- getGblEnv ; let env' = env { tcg_rules = lcl_rules ++ tcg_rules env } ; setGblEnv env' thing_inside } {- ************************************************************************ * * Meta level * * ************************************************************************ -} checkWellStaged :: SDoc -- What the stage check is for -> ThLevel -- Binding level (increases inside brackets) -> ThLevel -- Use stage -> TcM () -- Fail if badly staged, adding an error checkWellStaged pp_thing bind_lvl use_lvl | use_lvl >= bind_lvl -- OK! Used later than bound = return () -- E.g. \x -> [| $(f x) |] | bind_lvl == outerLevel -- GHC restriction on top level splices = stageRestrictionError pp_thing | otherwise -- Badly staged = failWithTc $ -- E.g. \x -> $(f x) ptext (sLit "Stage error:") <+> pp_thing <+> hsep [ptext (sLit "is bound at stage") <+> ppr bind_lvl, ptext (sLit "but used at stage") <+> ppr use_lvl] stageRestrictionError :: SDoc -> TcM a stageRestrictionError pp_thing = failWithTc $ sep [ ptext (sLit "GHC stage restriction:") , nest 2 (vcat [ pp_thing <+> ptext (sLit "is used in a top-level splice or annotation,") , ptext (sLit "and must be imported, not defined locally")])] topIdLvl :: Id -> ThLevel -- Globals may either be imported, or may be from an earlier "chunk" -- (separated by declaration splices) of this module. The former -- *can* be used inside a top-level splice, but the latter cannot. -- Hence we give the former impLevel, but the latter topLevel -- E.g. this is bad: -- x = [| foo |] -- $( f x ) -- By the time we are prcessing the $(f x), the binding for "x" -- will be in the global env, not the local one. topIdLvl id | isLocalId id = outerLevel | otherwise = impLevel tcMetaTy :: Name -> TcM Type -- Given the name of a Template Haskell data type, -- return the type -- E.g. given the name "Expr" return the type "Expr" tcMetaTy tc_name = do t <- tcLookupTyCon tc_name return (mkTyConApp t []) isBrackStage :: ThStage -> Bool isBrackStage (Brack {}) = True isBrackStage _other = False {- ************************************************************************ * * getDefaultTys * * ************************************************************************ -} tcGetDefaultTys :: TcM ([Type], -- Default types (Bool, -- True <=> Use overloaded strings Bool)) -- True <=> Use extended defaulting rules tcGetDefaultTys = do { dflags <- getDynFlags ; let ovl_strings = xopt Opt_OverloadedStrings dflags extended_defaults = xopt Opt_ExtendedDefaultRules dflags -- See also Trac #1974 flags = (ovl_strings, extended_defaults) ; mb_defaults <- getDeclaredDefaultTys ; case mb_defaults of { Just tys -> return (tys, flags) ; -- User-supplied defaults Nothing -> do -- No use-supplied default -- Use [Integer, Double], plus modifications { integer_ty <- tcMetaTy integerTyConName ; checkWiredInTyCon doubleTyCon ; string_ty <- tcMetaTy stringTyConName ; let deflt_tys = opt_deflt extended_defaults unitTy -- Note [Default unitTy] ++ [integer_ty, doubleTy] ++ opt_deflt ovl_strings string_ty ; return (deflt_tys, flags) } } } where opt_deflt True ty = [ty] opt_deflt False _ = [] {- Note [Default unitTy] ~~~~~~~~~~~~~~~~~~~~~ In interative mode (or with -XExtendedDefaultRules) we add () as the first type we try when defaulting. This has very little real impact, except in the following case. Consider: Text.Printf.printf "hello" This has type (forall a. IO a); it prints "hello", and returns 'undefined'. We don't want the GHCi repl loop to try to print that 'undefined'. The neatest thing is to default the 'a' to (), rather than to Integer (which is what would otherwise happen; and then GHCi doesn't attempt to print the (). So in interactive mode, we add () to the list of defaulting types. See Trac #1200. ************************************************************************ * * \subsection{The InstInfo type} * * ************************************************************************ The InstInfo type summarises the information in an instance declaration instance c => k (t tvs) where b It is used just for *local* instance decls (not ones from interface files). But local instance decls includes - derived ones - generic ones as well as explicit user written ones. -} data InstInfo a = InstInfo { iSpec :: ClsInst, -- Includes the dfun id. Its forall'd type iBinds :: InstBindings a -- variables scope over the stuff in InstBindings! } iDFunId :: InstInfo a -> DFunId iDFunId info = instanceDFunId (iSpec info) data InstBindings a = InstBindings { ib_tyvars :: [Name] -- Names of the tyvars from the instance head -- that are lexically in scope in the bindings , ib_binds :: (LHsBinds a) -- Bindings for the instance methods , ib_pragmas :: [LSig a] -- User pragmas recorded for generating -- specialised instances , ib_extensions :: [ExtensionFlag] -- Any extra extensions that should -- be enabled when type-checking this -- instance; needed for -- GeneralizedNewtypeDeriving , ib_derived :: Bool -- True <=> This code was generated by GHC from a deriving clause -- or standalone deriving declaration -- Used only to improve error messages } instance OutputableBndr a => Outputable (InstInfo a) where ppr = pprInstInfoDetails pprInstInfoDetails :: OutputableBndr a => InstInfo a -> SDoc pprInstInfoDetails info = hang (pprInstanceHdr (iSpec info) <+> ptext (sLit "where")) 2 (details (iBinds info)) where details (InstBindings { ib_binds = b }) = pprLHsBinds b simpleInstInfoClsTy :: InstInfo a -> (Class, Type) simpleInstInfoClsTy info = case instanceHead (iSpec info) of (_, cls, [ty]) -> (cls, ty) _ -> panic "simpleInstInfoClsTy" simpleInstInfoTy :: InstInfo a -> Type simpleInstInfoTy info = snd (simpleInstInfoClsTy info) simpleInstInfoTyCon :: InstInfo a -> TyCon -- Gets the type constructor for a simple instance declaration, -- i.e. one of the form instance (...) => C (T a b c) where ... simpleInstInfoTyCon inst = tcTyConAppTyCon (simpleInstInfoTy inst) {- Make a name for the dict fun for an instance decl. It's an *external* name, like otber top-level names, and hence must be made with newGlobalBinder. -} newDFunName :: Class -> [Type] -> SrcSpan -> TcM Name newDFunName clas tys loc = do { is_boot <- tcIsHsBootOrSig ; mod <- getModule ; let info_string = occNameString (getOccName clas) ++ concatMap (occNameString.getDFunTyKey) tys ; dfun_occ <- chooseUniqueOccTc (mkDFunOcc info_string is_boot) ; newGlobalBinder mod dfun_occ loc } {- Make a name for the representation tycon of a family instance. It's an *external* name, like other top-level names, and hence must be made with newGlobalBinder. -} newFamInstTyConName :: Located Name -> [Type] -> TcM Name newFamInstTyConName (L loc name) tys = mk_fam_inst_name id loc name [tys] newFamInstAxiomName :: SrcSpan -> Name -> [CoAxBranch] -> TcM Name newFamInstAxiomName loc name branches = mk_fam_inst_name mkInstTyCoOcc loc name (map coAxBranchLHS branches) mk_fam_inst_name :: (OccName -> OccName) -> SrcSpan -> Name -> [[Type]] -> TcM Name mk_fam_inst_name adaptOcc loc tc_name tyss = do { mod <- getModule ; let info_string = occNameString (getOccName tc_name) ++ intercalate "|" ty_strings ; occ <- chooseUniqueOccTc (mkInstTyTcOcc info_string) ; newGlobalBinder mod (adaptOcc occ) loc } where ty_strings = map (concatMap (occNameString . getDFunTyKey)) tyss {- Stable names used for foreign exports and annotations. For stable names, the name must be unique (see #1533). If the same thing has several stable Ids based on it, the top-level bindings generated must not have the same name. Hence we create an External name (doesn't change), and we append a Unique to the string right here. -} mkStableIdFromString :: String -> Type -> SrcSpan -> (OccName -> OccName) -> TcM TcId mkStableIdFromString str sig_ty loc occ_wrapper = do uniq <- newUnique mod <- getModule name <- mkWrapperName "stable" str let occ = mkVarOccFS name :: OccName gnm = mkExternalName uniq mod (occ_wrapper occ) loc :: Name id = mkExportedLocalId VanillaId gnm sig_ty :: Id return id mkStableIdFromName :: Name -> Type -> SrcSpan -> (OccName -> OccName) -> TcM TcId mkStableIdFromName nm = mkStableIdFromString (getOccString nm) mkWrapperName :: (MonadIO m, HasDynFlags m, HasModule m) => String -> String -> m FastString mkWrapperName what nameBase = do dflags <- getDynFlags thisMod <- getModule let -- Note [Generating fresh names for ccall wrapper] wrapperRef = nextWrapperNum dflags pkg = packageKeyString (modulePackageKey thisMod) mod = moduleNameString (moduleName thisMod) wrapperNum <- liftIO $ atomicModifyIORef wrapperRef $ \mod_env -> let num = lookupWithDefaultModuleEnv mod_env 0 thisMod mod_env' = extendModuleEnv mod_env thisMod (num+1) in (mod_env', num) let components = [what, show wrapperNum, pkg, mod, nameBase] return $ mkFastString $ zEncodeString $ intercalate ":" components {- Note [Generating fresh names for FFI wrappers] We used to use a unique, rather than nextWrapperNum, to distinguish between FFI wrapper functions. However, the wrapper names that we generate are external names. This means that if a call to them ends up in an unfolding, then we can't alpha-rename them, and thus if the unique randomly changes from one compile to another then we get a spurious ABI change (#4012). The wrapper counter has to be per-module, not global, so that the number we end up using is not dependent on the modules compiled before the current one. -} {- ************************************************************************ * * \subsection{Errors} * * ************************************************************************ -} pprBinders :: [Name] -> SDoc -- Used in error messages -- Use quotes for a single one; they look a bit "busy" for several pprBinders [bndr] = quotes (ppr bndr) pprBinders bndrs = pprWithCommas ppr bndrs notFound :: Name -> TcM TyThing notFound name = do { lcl_env <- getLclEnv ; let stage = tcl_th_ctxt lcl_env ; case stage of -- See Note [Out of scope might be a staging error] Splice {} -> stageRestrictionError (quotes (ppr name)) _ -> failWithTc $ vcat[ptext (sLit "GHC internal error:") <+> quotes (ppr name) <+> ptext (sLit "is not in scope during type checking, but it passed the renamer"), ptext (sLit "tcl_env of environment:") <+> ppr (tcl_env lcl_env)] -- Take case: printing the whole gbl env can -- cause an infinite loop, in the case where we -- are in the middle of a recursive TyCon/Class group; -- so let's just not print it! Getting a loop here is -- very unhelpful, because it hides one compiler bug with another } wrongThingErr :: String -> TcTyThing -> Name -> TcM a -- It's important that this only calls pprTcTyThingCategory, which in -- turn does not look at the details of the TcTyThing. -- See Note [Placeholder PatSyn kinds] in TcBinds wrongThingErr expected thing name = failWithTc (pprTcTyThingCategory thing <+> quotes (ppr name) <+> ptext (sLit "used as a") <+> text expected) {- Note [Out of scope might be a staging error] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider x = 3 data T = MkT $(foo x) This is really a staging error, because we can't run code involving 'x'. But in fact the type checker processes types first, so 'x' won't even be in the type envt when we look for it in $(foo x). So inside splices we report something missing from the type env as a staging error. See Trac #5752 and #5795. -}
forked-upstream-packages-for-ghcjs/ghc
compiler/typecheck/TcEnv.hs
bsd-3-clause
37,248
6
18
10,523
6,392
3,367
3,025
482
6
module Type5 where data Data = C1 Int Char | C2 Int | C3 Float errorData field dat function = errorData ("the binding for " ++ field ++ " in a pattern binding involving " ++ dat ++ " has been removed in function " ++ function) f :: Data -> Data -> a f (C1 b c) (C1 b1 b2) = errorData "a1" "C1" "f" f (C2 a) = a f (C3 a) = 42 (C1 b c) = 89 g :: Data -> Int g (C3 a) = 42
kmate/HaRe
old/testing/removeField/Type5_TokOut.hs
bsd-3-clause
404
0
11
125
174
90
84
-1
-1
{-# LANGUAGE TypeFamilies, ExplicitForAll #-} module T15828 where class C a where type T a b instance C (Maybe a) where type forall a b. T (Maybe a) b = b
sdiehl/ghc
testsuite/tests/rename/should_fail/T15828.hs
bsd-3-clause
162
1
10
38
63
32
31
-1
-1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.ConstrainedResize -- Copyright : (c) Dougal Stanton -- License : BSD3-style (see LICENSE) -- -- Maintainer : <[email protected]> -- Stability : stable -- Portability : unportable -- -- Lets you constrain the aspect ratio of a floating -- window (by, say, holding shift while you resize). -- -- Useful for making a nice circular XClock window. -- ----------------------------------------------------------------------------- module XMonad.Actions.ConstrainedResize ( -- * Usage -- $usage XMonad.Actions.ConstrainedResize.mouseResizeWindow ) where import XMonad -- $usage -- -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import qualified XMonad.Actions.ConstrainedResize as Sqr -- -- Then add something like the following to your mouse bindings: -- -- > , ((modm, button3), (\w -> focus w >> Sqr.mouseResizeWindow w False)) -- > , ((modm .|. shiftMask, button3), (\w -> focus w >> Sqr.mouseResizeWindow w True )) -- -- The line without the shiftMask replaces the standard mouse resize -- function call, so it's not completely necessary but seems neater -- this way. -- -- For detailed instructions on editing your mouse bindings, see -- "XMonad.Doc.Extending#Editing_mouse_bindings". -- | Resize (floating) window with optional aspect ratio constraints. mouseResizeWindow :: Window -> Bool -> X () mouseResizeWindow w c = whenX (isClient w) $ withDisplay $ \d -> do io $ raiseWindow d w wa <- io $ getWindowAttributes d w sh <- io $ getWMNormalHints d w io $ warpPointer d none w 0 0 0 0 (fromIntegral (wa_width wa)) (fromIntegral (wa_height wa)) mouseDrag (\ex ey -> do let x = ex - fromIntegral (wa_x wa) y = ey - fromIntegral (wa_y wa) sz = if c then (max x y, max x y) else (x,y) io $ resizeWindow d w `uncurry` applySizeHintsContents sh sz) (float w)
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Actions/ConstrainedResize.hs
bsd-2-clause
2,112
0
20
491
321
179
142
16
2
{-# LANGUAGE OverloadedStrings #-} module BadWarning where data MyString = MyString String f1 (MyString "a") = undefined f1 (MyString "bb") = undefined f1 _ = undefined f2 (MyString "aa") = undefined f2 (MyString "bb") = undefined f2 _ = undefined -- Genuine overlap here! f3(MyString ('a':_)) = undefined f3 (MyString "a") = undefined f3 _ = undefined
urbanslug/ghc
testsuite/tests/deSugar/should_compile/T5117.hs
bsd-3-clause
374
0
9
78
130
68
62
12
1
{-# LANGUAGE TypeFamilies, ScopedTypeVariables#-} module T3220 where class Foo m where type Bar m :: * action :: m -> Bar m -> m right x m = action m (Right x) right' :: (Either a b ~ Bar m, Foo m) => b -> m -> m right' x m = action m (Right x) instance Foo Int where type Bar Int = Either Int Int action m a = either (*) (+) a m instance Foo Float where type Bar Float = Either Float Float action m a = either (*) (+) a m foo = print $ right (1::Int) (3 :: Int) bar = print $ right (1::Float) (3 :: Float)
urbanslug/ghc
testsuite/tests/indexed-types/should_compile/T3220.hs
bsd-3-clause
537
0
9
144
259
138
121
16
1
module GitHub.Gists where import GitHub.Internal gists = "/gists" public = gists <> "/public" starred = gists <> "/starred" gist i = gists <> "/" <> i star i = gists i <> "/star" forks i = gists i <> "/forks" --| GET /users/:user/gists listUserGists :: UserName -> GitHub GistsData listUserGists u = ghGet (user u <> gists) --| GET /gists listCurrentUserGists :: GitHub GistsData listCurrentUserGists = ghGet gists --| GET /gists/public listCurrentUserPublicGists :: GitHub GistsData listCurrentUserPublicGists = ghGet public --| GET /gists/starred listCurrentUserStarredGists :: GitHub GistsData listCurrentUserStarredGists = ghGet starred --| GET /gists/:id getGist :: Int -> GitHub GistData getGist = ghGet . gist --| POST /gists createGist :: NewGist -> GitHub GistData createGist = ghPost gists --| PATCH /gists/:id editGist :: Int -> GistPatch -> GitHub GistData editGist i = ghPatch (gist i) --| PUT /gists/:id/star starGist :: Int -> GitHub () starGist = ghPut' . star --| DELETE /gists/:id/star unstarGist :: Int -> GitHub () unstarGist = ghDelete . star --| GET /gists/:id/star isGistStarred :: Int -> GitHub Bool isGistStarred = ghGet . star --| POST /gists/:id/forks forkGist :: Int -> GitHub GistData forkGist = ghPost' . forks --| DELETE /gists/:id deleteGist :: Int -> GitHub () deleteGist = ghDelete . gist
SaneApp/github-api
src/GitHub/Gists.hs
mit
1,358
44
9
239
606
301
305
-1
-1
module Shadowing where bindExp1 :: Integer -> String bindExp1 x = let z = 10; y = 5 in "the integer was: " ++ show x ++ " and y was: " ++ show y bindExp2 :: Integer -> String bindExp2 x = let x = 10; y = 5 in "the integer was: " ++ show x ++ " and y was: " ++ show y main :: IO () main = do putStrLn ("bindExp1 500 : " ++ ( bindExp1 500 )) putStrLn ("bindExp2 500 : " ++ ( bindExp2 500 ))
Lyapunov/haskell-programming-from-first-principles
chapter_7/shadowing.hs
mit
462
0
11
167
161
81
80
13
1
{-# LANGUAGE DeriveGeneric #-} module Player (Player(White, Black), next) where import Data.Aeson import GHC.Generics -- Player & Related Functions-- data Player = White | Black deriving (Eq, Show, Read, Ord, Bounded, Enum, Generic) instance FromJSON Player instance ToJSON Player next :: Player -> Player next White = Black next Black = White
danmane/abalone
unsupported/hs/src/player.hs
mit
352
2
6
60
113
63
50
14
1
{-# LANGUAGE DeriveDataTypeable #-} module Haskakafka.InternalTypes where import Control.Exception import Data.Int import Data.Typeable import Haskakafka.InternalRdKafka import Haskakafka.InternalRdKafkaEnum import qualified Data.ByteString as BS -- -- Pointer wrappers -- -- | Kafka configuration object data KafkaConf = KafkaConf RdKafkaConfTPtr deriving (Show) -- | Kafka topic configuration object data KafkaTopicConf = KafkaTopicConf RdKafkaTopicConfTPtr -- | Main pointer to Kafka object, which contains our brokers data Kafka = Kafka { kafkaPtr :: RdKafkaTPtr, _kafkaConf :: KafkaConf} deriving (Show) -- | Main pointer to Kafka topic, which is what we consume from or produce to data KafkaTopic = KafkaTopic RdKafkaTopicTPtr Kafka -- Kept around to prevent garbage collection KafkaTopicConf -- -- Consumer -- -- | Starting locations for a consumer data KafkaOffset = -- | Start reading from the beginning of the partition KafkaOffsetBeginning -- | Start reading from the end | KafkaOffsetEnd -- | Start reading from a specific location within the partition | KafkaOffset Int64 -- | Start reading from the stored offset. See -- <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md librdkafka's documentation> -- for offset store configuration. | KafkaOffsetStored | KafkaOffsetTail Int64 | KafkaOffsetInvalid deriving (Eq, Show) -- | Represents /received/ messages from a Kafka broker (i.e. used in a consumer) data KafkaMessage = KafkaMessage { messageTopic :: !String -- | Kafka partition this message was received from , messagePartition :: !Int -- | Offset within the 'messagePartition' Kafka partition , messageOffset :: !Int64 -- | Contents of the message, as a 'ByteString' , messagePayload :: !BS.ByteString -- | Optional key of the message. 'Nothing' when the message -- was enqueued without a key , messageKey :: Maybe BS.ByteString } deriving (Eq, Show, Read, Typeable) -- -- Producer -- -- | Represents messages /to be enqueued/ onto a Kafka broker (i.e. used for a producer) data KafkaProduceMessage = -- | A message without a key, assigned to 'KafkaSpecifiedPartition' or 'KafkaUnassignedPartition' KafkaProduceMessage {-# UNPACK #-} !BS.ByteString -- message payload -- | A message with a key, assigned to a partition based on the key | KafkaProduceKeyedMessage {-# UNPACK #-} !BS.ByteString -- message key {-# UNPACK #-} !BS.ByteString -- message payload deriving (Eq, Show, Typeable) -- | Options for destination partition when enqueuing a message data KafkaProducePartition = -- | A specific partition in the topic KafkaSpecifiedPartition {-# UNPACK #-} !Int -- the partition number of the topic -- | A random partition within the topic | KafkaUnassignedPartition -- -- Metadata -- -- | Metadata for all Kafka brokers data KafkaMetadata = KafkaMetadata { -- | Broker metadata brokers :: [KafkaBrokerMetadata] -- | topic metadata , topics :: [Either KafkaError KafkaTopicMetadata] } deriving (Eq, Show, Typeable) -- | Metadata for a specific Kafka broker data KafkaBrokerMetadata = KafkaBrokerMetadata { -- | broker identifier brokerId :: Int -- | hostname for the broker , brokerHost :: String -- | port for the broker , brokerPort :: Int } deriving (Eq, Show, Typeable) -- | Metadata for a specific topic data KafkaTopicMetadata = KafkaTopicMetadata { -- | name of the topic topicName :: String -- | partition metadata , topicPartitions :: [Either KafkaError KafkaPartitionMetadata] } deriving (Eq, Show, Typeable) -- | Metadata for a specific partition data KafkaPartitionMetadata = KafkaPartitionMetadata { -- | identifier for the partition partitionId :: Int -- | broker leading this partition , partitionLeader :: Int -- | replicas of the leader , partitionReplicas :: [Int] -- | In-sync replica set, see <http://kafka.apache.org/documentation.html> , partitionIsrs :: [Int] } deriving (Eq, Show, Typeable) -- -- Helpers, exposed directly -- -- | Log levels for the RdKafkaLibrary used in 'setKafkaLogLevel' data KafkaLogLevel = KafkaLogEmerg | KafkaLogAlert | KafkaLogCrit | KafkaLogErr | KafkaLogWarning | KafkaLogNotice | KafkaLogInfo | KafkaLogDebug instance Enum KafkaLogLevel where toEnum 0 = KafkaLogEmerg toEnum 1 = KafkaLogAlert toEnum 2 = KafkaLogCrit toEnum 3 = KafkaLogErr toEnum 4 = KafkaLogWarning toEnum 5 = KafkaLogNotice toEnum 6 = KafkaLogInfo toEnum 7 = KafkaLogDebug toEnum _ = undefined fromEnum KafkaLogEmerg = 0 fromEnum KafkaLogAlert = 1 fromEnum KafkaLogCrit = 2 fromEnum KafkaLogErr = 3 fromEnum KafkaLogWarning = 4 fromEnum KafkaLogNotice = 5 fromEnum KafkaLogInfo = 6 fromEnum KafkaLogDebug = 7 -- | Any Kafka errors data KafkaError = KafkaError String | KafkaInvalidReturnValue | KafkaBadSpecification String | KafkaResponseError RdKafkaRespErrT | KafkaInvalidConfigurationValue String | KafkaUnknownConfigurationKey String | KakfaBadConfiguration deriving (Eq, Show, Typeable) instance Exception KafkaError
cosbynator/haskakafka
src/Haskakafka/InternalTypes.hs
mit
5,497
0
10
1,318
745
447
298
99
0