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
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Futhark.IR.PropTests ( tests, ) where import qualified Futhark.IR.Prop.RearrangeTests import qualified Futhark.IR.Prop.ReshapeTests import Test.Tasty tests :: TestTree tests = testGroup "PropTests" [ Futhark.IR.Prop.ReshapeTests.tests, Futhark.IR.Prop.RearrangeTests.tests ]
HIPERFIT/futhark
unittests/Futhark/IR/PropTests.hs
isc
382
0
7
60
67
46
21
13
1
{-# LANGUAGE DeriveDataTypeable #-} module Data.Logic.Prop where import Numeric.Natural.QuickCheck () import Data.Typeable (Typeable) import Control.Applicative import Test.QuickCheck import Text.Read import Data.Data (Data) import Data.Name -- $setup -- >>> import Text.Show.Functions () -- >>> :set -XOverloadedStrings -- >>> :set -XScopedTypeVariables -- >>> import Data.Maybe -- >>> import Data.List data Prop = Prop Name | Imply Prop Prop deriving (Eq, Ord, Data, Typeable) infixr `Imply` instance Arbitrary Prop where arbitrary = frequency [ (,) 2 $ Prop <$> arbitrary , (,) 1 $ Imply <$> arbitrary <*> arbitrary ] instance CoArbitrary Prop where coarbitrary (Prop a) = coarbitrary a coarbitrary (Imply a b) = coarbitrary a . coarbitrary b -- | >>> Prop "a" `Imply` (Prop "b" `Imply` Prop "c") -- a -> b -> c -- >>> (Prop "a" `Imply` Prop "b") `Imply` Prop "c" -- (a -> b) -> c instance Show Prop where showsPrec _ (Prop a) = shows a showsPrec d (Imply p q) = showParen (app_prec < d) $ showsPrec (app_prec+1) p . showString " -> " . shows q where app_prec = 10 -- | >>> read "a -> b -> c" :: Prop -- a -> b -> c -- >>> read "(a -> b) -> c" :: Prop -- (a -> b) -> c -- -- prop> \ (x :: Prop) -> (read . show) x == x instance Read Prop where readPrec = parens (imply <++ prop) where prop = Prop <$> readPrec imply = prec app_prec $ Imply <$> step readPrec <*> (lexP >>= isArrow >> readPrec) isArrow (Punc "->") = return () isArrow _ = pfail app_prec = 10 readsPrec = readPrec_to_S readPrec
kmyk/proof-haskell
Data/Logic/Prop.hs
mit
1,627
0
12
404
418
227
191
34
0
{-# LANGUAGE FlexibleContexts #-} module HolyProject.StringUtils.Test ( stringUtilsSuite ) where import Data.Char (isPrint,isSymbol) import Test.Tasty (testGroup, TestTree) import Test.Tasty.HUnit import Test.Tasty.SmallCheck (forAll) import qualified Test.Tasty.SmallCheck as SC import qualified Test.Tasty.QuickCheck as QC import Test.SmallCheck.Series (Serial) import HolyProject.StringUtils -- | Test with QuickCheck and SmallCheck tp name prop = testGroup name [ QC.testProperty "QC" prop , SC.testProperty "SC" prop ] stringUtilsSuite :: TestTree stringUtilsSuite = testGroup "StringUtils" [ tp "projectNameFromString idempotent" $ idempotent projectNameFromString , SC.testProperty "capitalize idempotent" $ deeperIdempotent capitalize , tp "no space in project name" $ \s -> ' ' `notElem` projectNameFromString s , tp "no space in capitalized name" $ \s -> ' ' `notElem` capitalize s , tp "no dash in capitalized name" $ \s -> '-' `notElem` capitalize s , tp "no control char" $ \s -> not (checkProjectName s) || all isPrint s , tp "no symbol char" $ \s -> not (checkProjectName s) || all (not . isSymbol) s , testCase "doesn't accept empty project name" $ checkProjectName "" @=? False ] idempotent :: (Eq a) => (a -> a) -> a -> Bool idempotent f = \s -> f s == f (f s) deeperIdempotent :: (Eq a, Show a, Serial m a) => (a -> a) -> SC.Property m deeperIdempotent f = forAll $ SC.changeDepth1 (+1) $ \s -> f s == f (f s)
yogsototh/holy-project
test/HolyProject/StringUtils/Test.hs
mit
1,719
0
12
513
479
258
221
36
1
----------------------------------------------------------------------- -- -- Haskell: The Craft of Functional Programming, 3e -- Simon Thompson -- (c) Addison-Wesley, 1996-2011. -- -- Chapter 12 -- ----------------------------------------------------------------------- -- For Rock-Paper-Scissors examples see RPS.hs module Chapter12 where import Craft.Pictures hiding (flipH,rotate,flipV,beside,invertColour, superimpose,printPicture) -- Revisiting the Pictures example, yet again. flipV :: Picture -> Picture flipV = map reverse beside :: Picture -> Picture -> Picture beside = zipWith (++) -- Revisiting the Picture example -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- Some of the functions are already (re)defined in this script. -- Among the other functions mentioned were invertColour :: Picture -> Picture invertColour = map (map invert) superimpose :: Picture -> Picture -> Picture superimpose = zipWith (zipWith combineChar) -- The definition of combineChar is left as an exercise: it's a dummy definition -- here. combineChar :: Char -> Char -> Char combineChar = combineChar -- Printing a picture: uses putStr after a newline has been added at the end of -- every line and the lines are joined into a single string. printPicture :: Picture -> IO () printPicture = putStr . concat . map (++"\n") -- Regular expressions type RegExp = String -> Bool char :: Char -> RegExp epsilon = (=="") char ch = (==[ch]) (|||) :: RegExp -> RegExp -> RegExp e1 ||| e2 = \x -> e1 x || e2 x (<*>) :: RegExp -> RegExp -> RegExp e1 <*> e2 = \x -> or [ e1 y && e2 z | (y,z) <- splits x ] (<**>) :: RegExp -> RegExp -> RegExp e1 <**> e2 = \x -> or [ e1 y && e2 z | (y,z) <- fsplits x ] splits xs = [splitAt n xs | n<-[0..len]] where len = length xs star :: RegExp -> RegExp star p = epsilon ||| (p <**> star p) -- epsilon ||| (p <*> star p) -- is OK as long as p can't have epsilon match fsplits xs = tail (splits xs) -- -- Case studies: functions as data -- -- Natural numbers as functions. type Natural a = (a -> a) -> (a -> a) zero, one, two :: Natural a zero f = id one f = f two f = f.f int :: Natural Int -> Int int n = n (+1) 0 -- sends representation of n to rep. of n+1 succ :: Natural a -> Natural a succ fn f = f . (fn f) -- sends reps. of n and m to rep. of n+m plus :: Natural a -> Natural a -> Natural a plus a b f = (a f) . (b f) -- sends reps. of n and m to rep. of n*m times :: Natural a -> Natural a -> Natural a times m n f = (m (n f)) -- Creating an index -- ^^^^^^^^^^^^^^^^^ -- See Index.hs -- Development in practice -- ^^^^^^^^^^^^^^^^^^^^^^^ -- Defining the .. notation (not executable code). -- -- [m .. n] -- | m>n = [] -- | otherwise = m : [m+1 .. n] -- [1 .. n] -- | 1>n = [] -- | otherwise = [1 .. n-1] ++ [n] -- A simple palindrome check. simplePalCheck :: String -> Bool simplePalCheck st = (reverse st == st) -- The full check palCheck = simplePalCheck . clean -- where the clean function combines mapping (capitals to smalls) and -- filtering (removing punctuation) clean :: String -> String clean = map toSmall . filter notPunct toSmall = toSmall -- dummy definition notPunct = notPunct -- dummy definition -- Auxiliary functions -- When is one string a subsequence of another? subseq :: String -> String -> Bool subseq [] _ = True subseq (_:_) [] = False subseq (x:xs) (y:ys) = subseq (x:xs) ys || frontseq (x:xs) (y:ys) -- When is one strong a subsequece of another, starting at the front? frontseq :: String -> String -> Bool frontseq [] _ = True frontseq (_:_) [] = False frontseq (x:xs) (y:ys) = (x==y) && frontseq xs ys -- Understanding programs -- ^^^^^^^^^^^^^^^^^^^^^^ mapWhile :: (a -> b) -> (a -> Bool) -> [a] -> [b] mapWhile f p [] = [] mapWhile f p (x:xs) | p x = f x : mapWhile f p xs | otherwise = [] example1 = mapWhile (2+) (>7) [8,12,7,13,16]
Numberartificial/workflow
snipets/src/Craft/Chapter12.hs
mit
3,982
0
10
916
1,148
632
516
69
1
module Ex6 where test = \x -> let f = \y -> y x in (f (\z -> z)) (f (\u -> \v -> u))
roberth/uu-helium
test/typeerrors/Edinburgh/Ex6.hs
gpl-3.0
99
0
13
39
69
38
31
3
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.SDB.BatchDeleteAttributes -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Performs multiple DeleteAttributes operations in a single call, which -- reduces round trips and latencies. This enables Amazon SimpleDB to -- optimize requests, which generally yields better throughput. -- -- The following limitations are enforced for this operation: -- -- - 1 MB request size -- - 25 item limit per BatchDeleteAttributes operation -- -- /See:/ <http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_BatchDeleteAttributes.html AWS API Reference> for BatchDeleteAttributes. module Network.AWS.SDB.BatchDeleteAttributes ( -- * Creating a Request batchDeleteAttributes , BatchDeleteAttributes -- * Request Lenses , bdaDomainName , bdaItems -- * Destructuring the Response , batchDeleteAttributesResponse , BatchDeleteAttributesResponse ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.SDB.Types import Network.AWS.SDB.Types.Product -- | /See:/ 'batchDeleteAttributes' smart constructor. data BatchDeleteAttributes = BatchDeleteAttributes' { _bdaDomainName :: !Text , _bdaItems :: ![DeletableItem] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'BatchDeleteAttributes' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bdaDomainName' -- -- * 'bdaItems' batchDeleteAttributes :: Text -- ^ 'bdaDomainName' -> BatchDeleteAttributes batchDeleteAttributes pDomainName_ = BatchDeleteAttributes' { _bdaDomainName = pDomainName_ , _bdaItems = mempty } -- | The name of the domain in which the attributes are being deleted. bdaDomainName :: Lens' BatchDeleteAttributes Text bdaDomainName = lens _bdaDomainName (\ s a -> s{_bdaDomainName = a}); -- | A list of items on which to perform the operation. bdaItems :: Lens' BatchDeleteAttributes [DeletableItem] bdaItems = lens _bdaItems (\ s a -> s{_bdaItems = a}) . _Coerce; instance AWSRequest BatchDeleteAttributes where type Rs BatchDeleteAttributes = BatchDeleteAttributesResponse request = postQuery sDB response = receiveNull BatchDeleteAttributesResponse' instance ToHeaders BatchDeleteAttributes where toHeaders = const mempty instance ToPath BatchDeleteAttributes where toPath = const "/" instance ToQuery BatchDeleteAttributes where toQuery BatchDeleteAttributes'{..} = mconcat ["Action" =: ("BatchDeleteAttributes" :: ByteString), "Version" =: ("2009-04-15" :: ByteString), "DomainName" =: _bdaDomainName, toQueryList "Item" _bdaItems] -- | /See:/ 'batchDeleteAttributesResponse' smart constructor. data BatchDeleteAttributesResponse = BatchDeleteAttributesResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'BatchDeleteAttributesResponse' with the minimum fields required to make a request. -- batchDeleteAttributesResponse :: BatchDeleteAttributesResponse batchDeleteAttributesResponse = BatchDeleteAttributesResponse'
fmapfmapfmap/amazonka
amazonka-sdb/gen/Network/AWS/SDB/BatchDeleteAttributes.hs
mpl-2.0
3,873
0
10
744
449
274
175
62
1
{- Module : Database.Util Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley License : BSD-style Maintainer : oleg@pobox.com, alistair@abayley.org Stability : experimental Portability : non-portable Utility functions. Mostly used in database back-ends, and tests. -} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE UndecidableInstances #-} module Database.Util where import System.Time import Control.Monad.Trans (liftIO) import Control.Monad.Reader import Data.Int import Data.List import Data.Char import Data.Time import Data.Word (Word8) import Foreign.Ptr (Ptr, castPtr) import Foreign.Marshal.Array (peekArray) import Numeric (showHex) import Text.Printf {- MyShow requires overlapping AND undecidable instances. -} class Show a => MyShow a where show_ :: a -> String instance MyShow String where show_ s = s instance (Show a) => MyShow a where show_ = show -- Like 'System.IO.print', except that Strings are not escaped or quoted. print_ :: (MonadIO m, MyShow a) => a -> m () print_ s = liftIO (putStrLn (show_ s)) -- Convenience for making UTCTimes. Assumes the time given is already UTC time -- i.e. there's no timezone adjustment. mkUTCTime :: (Integral a, Real b) => a -> a -> a -> a -> a -> b -> UTCTime mkUTCTime year month day hour minute second = localTimeToUTC (hoursToTimeZone 0) (LocalTime (fromGregorian (fromIntegral year) (fromIntegral month) (fromIntegral day)) (TimeOfDay (fromIntegral hour) (fromIntegral minute) (realToFrac second))) mkCalTime :: Integral a => a -> a -> a -> a -> a -> a -> CalendarTime mkCalTime year month day hour minute second = CalendarTime { ctYear = fromIntegral year , ctMonth = toEnum (fromIntegral month - 1) , ctDay = fromIntegral day , ctHour = fromIntegral hour , ctMin = fromIntegral minute , ctSec = fromIntegral second , ctPicosec = 0 , ctWDay = Sunday , ctYDay = -1 , ctTZName = "UTC" , ctTZ = 0 , ctIsDST = False } {- 20040822073512 10000000000 (10 ^ 10) * year 100000000 (10 ^ 8) * month 1000000 (10 ^ 6) * day 10000 (10^4) * hour Use quot and rem, /not/ div and mod, so that we get sensible behaviour for -ve numbers. -} int64ToDateParts :: Int64 -> (Int64, Int64, Int64, Int64, Int64, Int64) int64ToDateParts i = let year1 = (i `quot` 10000000000) month = ((abs i) `rem` 10000000000) `quot` 100000000 day = ((abs i) `rem` 100000000) `quot` 1000000 hour = ((abs i) `rem` 1000000) `quot` 10000 minute = ((abs i) `rem` 10000) `quot` 100 second = ((abs i) `rem` 100) in (year1, month, day, hour, minute, second) datePartsToInt64 :: (Integral a1, Integral a2, Integral a3, Integral a4, Integral a5, Integral a6) => (a1, a2, a3, a4, a5, a6) -> Int64 datePartsToInt64 (year, month, day, hour, minute, second) = let yearm :: Int64 yearm = 10000000000 sign :: Int64 sign = if year < 0 then -1 else 1 in yearm * fromIntegral year + sign * 100000000 * fromIntegral month + sign * 1000000 * fromIntegral day + sign * 10000 * fromIntegral hour + sign * 100 * fromIntegral minute + sign * fromIntegral second calTimeToInt64 :: CalendarTime -> Int64 calTimeToInt64 ct = datePartsToInt64 ( ctYear ct, fromEnum (ctMonth ct) + 1, ctDay ct , ctHour ct, ctMin ct, ctSec ct) utcTimeToInt64 utc = let (LocalTime ltday time) = utcToLocalTime (hoursToTimeZone 0) utc (TimeOfDay hour minute second) = time (year, month, day) = toGregorian ltday in datePartsToInt64 (year, month, day, hour, minute, round second) int64ToCalTime :: Int64 -> CalendarTime int64ToCalTime i = let (year, month, day, hour, minute, second) = int64ToDateParts i in mkCalTime year month day hour minute second int64ToUTCTime :: Int64 -> UTCTime int64ToUTCTime i = let (year, month, day, hour, minute, second) = int64ToDateParts i in mkUTCTime year month day hour minute second zeroPad n i = if i < 0 then "-" ++ (zeroPad n (abs i)) else take (n - length (show i)) (repeat '0') ++ show i substr i n s = take n (drop (i-1) s) wordsBy :: (Char -> Bool) -> String -> [String] wordsBy pred s = skipNonMatch pred s {- 2 states: - skipNonMatch is for when we are looking for the start of our next word - scanWord is for when we are currently scanning a word -} skipNonMatch :: (Char -> Bool) -> String -> [String] skipNonMatch pred "" = [] skipNonMatch pred (c:cs) | pred c = scanWord pred cs [c] | otherwise = skipNonMatch pred cs scanWord pred "" acc = [reverse acc] scanWord pred (c:cs) acc | pred c = scanWord pred cs (c:acc) | otherwise = [reverse acc] ++ skipNonMatch pred cs positions :: Eq a => [a] -> [a] -> [Int] positions [] _ = [] positions s ins = map fst (filter (isPrefixOf s . snd) (zip [1..] (tails ins))) {- 1234567890123456789012345 "2006-11-24 07:51:49.228+00" "2006-11-24 07:51:49.228" "2006-11-24 07:51:49.228 BC" "2006-11-24 07:51:49+00 BC" FIXME use TZ to specify timezone? Not necessary, PostgreSQL always seems to output +00 for timezone. It's already adjusted the time, I think. Need to test this with different server timezones, though. -} pgDatetimetoUTCTime :: String -> UTCTime pgDatetimetoUTCTime s = let (year, month, day, hour, minute, second, tz) = pgDatetimeToParts s in mkUTCTime year month day hour minute second isoDatetimeToUTCTime s = pgDatetimetoUTCTime s pgDatetimetoCalTime :: String -> CalendarTime pgDatetimetoCalTime s = let (year, month, day, hour, minute, second, tz) = pgDatetimeToParts s in mkCalTime year month day hour minute (round second) {- isInfixOf is defined in the Data.List that comes with ghc-6.6, but it is not in the libs that come with ghc-6.4.1. -} myIsInfixOf srch list = or (map (isPrefixOf srch) (tails list)) -- Parses ISO format datetimes, and also the variation that PostgreSQL uses. pgDatetimeToParts :: String -> (Int, Int, Int, Int, Int, Double, Int) pgDatetimeToParts s = let pred c = isAlphaNum c || c == '.' ws = wordsBy pred s parts :: [Int]; parts = map read (take 5 ws) secs :: Double; secs = read (ws!!5) hasTZ = myIsInfixOf "+" s tz :: Int; tz = if hasTZ then read (ws !! 6) else 0 isBC = myIsInfixOf "BC" s -- It seems only PostgreSQL uses the AD/BC suffix. -- If BC is present then we need to do something odd with the year. year :: Int; year = if isBC then (- ((parts !! 0) - 1)) else parts !! 0 in (year, (parts !! 1), (parts !! 2) , (parts !! 3), (parts !! 4), secs, tz) utcTimeToIsoString :: (Show a, Integral a, Integral b) => UTCTime -> String -> (a -> a) -> (b -> String) -> String utcTimeToIsoString utc dtSep adjYear mkSuffix = let (LocalTime ltday time) = utcToLocalTime (hoursToTimeZone 0) utc (TimeOfDay hour minute second) = time (year1, month, day) = toGregorian ltday suffix = mkSuffix (fromIntegral year1) year = adjYear (fromIntegral year1) s1 :: Double; s1 = realToFrac second secs :: String; secs = printf "%09.6f" s1 in zeroPad 4 year ++ "-" ++ zeroPad 2 month ++ "-" ++ zeroPad 2 day ++ dtSep ++ zeroPad 2 hour ++ ":" ++ zeroPad 2 minute ++ ":" ++ secs ++ "+00" ++ suffix utcTimeToPGDatetime :: UTCTime -> String utcTimeToPGDatetime utc = utcTimeToIsoString utc "T" adjYear mkSuffix where mkSuffix year1 = if year1 < 1 then " BC" else " AD" adjYear year1 = if year1 < 1 then abs(year1 - 1) else year1 utcTimeToIsoDatetime :: UTCTime -> String utcTimeToIsoDatetime utc = utcTimeToIsoString utc "T" id (const "Z") utcTimeToOdbcDatetime :: UTCTime -> String utcTimeToOdbcDatetime utc = utcTimeToIsoString utc " " id (const "") -- Assumes CalendarTime is also UTC i.e. ignores ctTZ component. calTimeToPGDatetime :: CalendarTime -> String calTimeToPGDatetime ct = let (year1, month, day, hour, minute, second, pico, tzsecs) = ( ctYear ct, fromEnum (ctMonth ct) + 1, ctDay ct , ctHour ct, ctMin ct, ctSec ct, ctPicosec ct, ctTZ ct) suffix = if year1 < 1 then " BC" else " AD" year = if year1 < 1 then abs(year1 - 1) else year1 s1 :: Double; s1 = realToFrac second + ((fromIntegral pico) / (10.0 ^ 12) ) secs :: String; secs = printf "%09.6f" s1 in zeroPad 4 year ++ "-" ++ zeroPad 2 month ++ "-" ++ zeroPad 2 day ++ " " ++ zeroPad 2 hour ++ ":" ++ zeroPad 2 minute ++ ":" ++ secs ++ "+00" ++ suffix printArrayContents :: Int -> Ptr Word8 -> IO () printArrayContents sz ptr = do putStrLn ("printArrayContents: sz = " ++ show sz) l <- peekArray sz ptr let toHex :: Word8 -> String; toHex i = (if i < 16 then "0" else "") ++ showHex i "" putStrLn (concat (intersperse " " (map toHex l))) let toChar :: Word8 -> String toChar i = if 31 < i && i < 127 then [chr (fromIntegral i)] else " " putStrLn (concat (intersperse " " (map toChar l)))
bagl/takusen-oracle
Database/Util.hs
bsd-3-clause
9,203
0
22
2,243
2,971
1,575
1,396
184
3
module MatrixTree ( addSubtreeNorms , ifZeroReplace , isZero , matrixListToTree , MatrixTree , mmReadTree , mmWriteTree , MTree(..) , nextPowOf2 , norm , Norm , setNorm , size , Size , treeToMatrixList , Value , valueNorm ) where -- a recursive matrix data type that efficiently encodes sparsity import MatrixList (MatrixList, mEntryVal) import MatrixMarket (mmReadFile, mmWriteFile) type Size = Int ; type Value = Double ; type Norm = Double data MTree = Zero Size | Leaf Norm Value | Square Size Norm MTree MTree MTree MTree deriving (Eq, Show) type MatrixTree = (Int, Int, MTree) size :: MTree -> Size size (Zero s) = s size (Leaf _ _) = 1 size (Square s _ _ _ _ _) = s norm :: MTree -> Norm norm (Zero _) = 0 norm (Leaf n _) = n norm (Square _ n _ _ _ _) = n subTrees :: MTree -> [MTree] subTrees (Square _ _ tl tr bl br) = [tl, tr, bl, br] subTrees _ = [] -- setting norms setNorm :: MTree -> MTree setNorm tree@(Zero _) = tree setNorm tree@(Leaf _ x) = Leaf (valueNorm x) x setNorm tree@(Square s _ _ _ _ _) = Square s n ntl ntr nbl nbr where [ntl, ntr, nbl, nbr] = fmap setNorm $ subTrees tree n = addSubtreeNorms [ntl, ntr, nbl, nbr] valueNorm :: Value -> Norm valueNorm = abs addSubtreeNorms :: [MTree] -> Norm addSubtreeNorms = sqrt . sum . fmap ((^2) . norm) -- reading from/writing to MatrixMarket files mmReadTree :: FilePath -> IO MatrixTree mmReadTree filePath = mmReadFile filePath >>= (return . matrixListToTree) mmWriteTree :: MatrixTree -> String -> FilePath -> IO () mmWriteTree tree format filePath = mmWriteFile (treeToMatrixList tree) format filePath matrixListToTree :: MatrixList Double -> MatrixTree matrixListToTree (h, w, ijxs) = (h, w, setNorm $ foldr addVal (Zero p) entries) where p = nextPowOf2 $ max h w entries = filter ((/= 0) . mEntryVal) ijxs addVal :: (Int, Int, Value) -> MTree -> MTree addVal (_, _, x) (Leaf _ _) = Leaf 0 x addVal (i, j, x) (Zero s) | s == 1 = Leaf 0 x | within [i,j] = Square s 0 (addVal (i, j, x) zro) zro zro zro | within [i,jr] = Square s 0 zro (addVal (i, jr, x) zro) zro zro | within [ib,j] = Square s 0 zro zro (addVal (ib, j, x) zro) zro | within [ib,jr] = Square s 0 zro zro zro (addVal (ib, jr, x) zro) where halfs = s `div` 2 within = all (<= halfs) ib = i - halfs ; jr = j - halfs zro = Zero halfs addVal (i, j, x) (Square s _ tl tr bl br) = Square s 0 newtl newtr newbl newbr where [newtl, newtr, newbl, newbr] | within [i,j] = [addVal (i, j, x) tl, tr, bl, br] | within [i,jr] = [tl, addVal (i, jr, x) tr, bl, br] | within [ib,j] = [tl, tr, addVal (ib, j, x) bl, br] | within [ib,jr] = [tl, tr, bl, addVal (ib, jr, x) br] within = all (<= halfs) ib = i - halfs ; jr = j - halfs halfs = s `div` 2 treeToMatrixList :: MatrixTree -> MatrixList Double treeToMatrixList (h, w, mTree) = (h, w, mTreeToList mTree) mTreeToList :: MTree -> [(Int, Int, Value)] mTreeToList (Zero _) = [] mTreeToList (Leaf _ x) = [(1, 1, x)] mTreeToList tree@(Square s _ _ _ _ _) = concat [tlijxs, fmap wshift trijxs, fmap hshift blijxs, fmap (hshift . wshift) brijxs] where [tlijxs, trijxs, blijxs, brijxs] = fmap mTreeToList $ subTrees tree hshift (i, j, x) = (i + halfs, j, x) wshift (i, j, x) = (i, j + halfs, x) halfs = s `div` 2 -- utility functions isZero :: MTree -> Bool isZero (Zero _) = True isZero _ = False ifZeroReplace :: MTree -> MTree ifZeroReplace tree@(Zero _) = tree ifZeroReplace tree@(Leaf _ x) = if x == 0 then Zero 1 else tree ifZeroReplace tree@(Square s _ _ _ _ _) = if all isZero (subTrees tree) then Zero s else tree nextPowOf2 :: Integral a => a -> a nextPowOf2 n = head . dropWhile (< n) $ map (2^) [0..]
FreeON/spammpack
src-Haskell/MatrixTree.hs
bsd-3-clause
4,216
0
11
1,349
1,803
991
812
100
3
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} -- | Stream operations on 'ByteString'. module System.IO.Streams.ByteString ( -- * Counting bytes countInput , countOutput -- * Treating strings as streams , fromByteString , fromLazyByteString -- * Input and output , readExactly , takeBytesWhile , writeLazyByteString -- * Stream transformers -- ** Splitting/Joining , splitOn , lines , unlines , words , unwords -- ** Other , giveBytes , giveExactly , takeBytes , takeExactly , throwIfConsumesMoreThan , throwIfProducesMoreThan -- ** Rate limiting , throwIfTooSlow -- * String search , MatchInfo(..) , search -- * Exception types , RateTooSlowException , ReadTooShortException , TooManyBytesReadException , TooManyBytesWrittenException , TooFewBytesWrittenException ) where ------------------------------------------------------------------------------ import Control.Exception (Exception, throwIO) import Control.Monad (when, (>=>)) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.ByteString.Unsafe as S import Data.Char (isSpace) import Data.Int (Int64) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.Time.Clock.POSIX (getPOSIXTime) import Data.Typeable (Typeable) import Prelude hiding (lines, read, unlines, unwords, words) ------------------------------------------------------------------------------ import System.IO.Streams.Combinators (filterM, intersperse, outputFoldM) import System.IO.Streams.Internal (InputStream (..), OutputStream, makeInputStream, makeOutputStream, read, unRead, write) import System.IO.Streams.Internal.Search (MatchInfo (..), search) import System.IO.Streams.List (fromList, writeList) ------------------------------------------------------------------------------ {-# INLINE modifyRef #-} modifyRef :: IORef a -> (a -> a) -> IO () modifyRef ref f = do x <- readIORef ref writeIORef ref $! f x ------------------------------------------------------------------------------ -- | Writes a lazy 'ByteString' to an 'OutputStream'. -- -- Example: -- -- @ -- ghci> Streams.'writeLazyByteString' \"Test\\n\" Streams.'System.IO.Streams.stdout' -- Test -- @ writeLazyByteString :: L.ByteString -- ^ string to write to output -> OutputStream ByteString -- ^ output stream -> IO () writeLazyByteString = writeList . L.toChunks {-# INLINE writeLazyByteString #-} ------------------------------------------------------------------------------ -- | Creates an 'InputStream' from a 'ByteString'. fromByteString :: ByteString -> IO (InputStream ByteString) fromByteString = fromList . (:[]) ------------------------------------------------------------------------------ -- | Creates an 'InputStream' from a lazy 'ByteString'. fromLazyByteString :: L.ByteString -> IO (InputStream ByteString) fromLazyByteString = fromList . L.toChunks ------------------------------------------------------------------------------ -- | Wraps an 'InputStream', counting the number of bytes produced by the -- stream as a side effect. Produces a new 'InputStream' as well as an IO -- action to retrieve the count of bytes produced. -- -- Strings pushed back to the returned 'InputStream' will be pushed back to the -- original stream, and the count of produced bytes will be subtracted -- accordingly. -- -- Example: -- -- @ -- ghci> is <- Streams.'System.IO.Streams.fromList' [\"abc\", \"def\", \"ghi\"::ByteString] -- ghci> (is', getCount) <- Streams.'countInput' is -- ghci> Streams.'read' is' -- Just \"abc\" -- ghci> getCount -- 3 -- ghci> Streams.'unRead' \"bc\" is' -- ghci> getCount -- 1 -- ghci> Streams.'System.IO.Streams.peek' is -- Just \"bc\" -- ghci> Streams.'System.IO.Streams.toList' is' -- [\"bc\",\"def\",\"ghi\"] -- ghci> getCount -- 9 -- @ -- countInput :: InputStream ByteString -> IO (InputStream ByteString, IO Int64) countInput src = do ref <- newIORef (0 :: Int64) return $! (InputStream (prod ref) (pb ref), readIORef ref) where prod ref = read src >>= maybe (return Nothing) (\x -> do modifyRef ref (+ (fromIntegral $ S.length x)) return $! Just x) pb ref s = do modifyRef ref (\x -> x - (fromIntegral $ S.length s)) unRead s src ------------------------------------------------------------------------------ -- | Wraps an 'OutputStream', counting the number of bytes consumed by the -- stream as a side effect. Produces a new 'OutputStream' as well as an IO -- action to retrieve the count of bytes consumed. -- -- Example: -- -- @ -- ghci> (os :: OutputStream ByteString, getList) <- Streams.'System.IO.Streams.listOutputStream' -- ghci> (os', getCount) <- Streams.'countOutput' os -- ghci> Streams.'System.IO.Streams.fromList' [\"abc\", \"def\", \"ghi\"] >>= Streams.'System.IO.Streams.connectTo' os' -- ghci> getList -- [\"abc\",\"def\",\"ghi\"] -- ghci> getCount -- 9 -- @ countOutput :: OutputStream ByteString -> IO (OutputStream ByteString, IO Int64) countOutput = outputFoldM f 0 where f !count s = return z where !c = S.length s !z = toEnum c + count ------------------------------------------------------------------------------ -- | Wraps an 'InputStream', producing a new 'InputStream' that will produce at -- most @n@ bytes, subsequently yielding end-of-stream forever. -- -- Strings pushed back to the returned 'InputStream' will be propagated -- upstream, modifying the count of taken bytes accordingly. -- -- Example: -- -- @ -- ghci> is <- Streams.'System.IO.Streams.fromList' [\"truncated\", \" string\"::ByteString] -- ghci> is' <- Streams.'takeBytes' 9 is -- ghci> Streams.'read' is' -- Just \"truncated\" -- ghci> Streams.'read' is' -- Nothing -- ghci> Streams.'System.IO.Streams.peek' is -- Just \" string\" -- ghci> Streams.'unRead' \"cated\" is' -- ghci> Streams.'System.IO.Streams.peek' is -- Just \"cated\" -- ghci> Streams.'System.IO.Streams.peek' is' -- Just \"cated\" -- ghci> Streams.'read' is' -- Just \"cated\" -- ghci> Streams.'read' is' -- Nothing -- ghci> Streams.'read' is -- Just \" string\" -- @ takeBytes :: Int64 -- ^ maximum number of bytes to read -> InputStream ByteString -- ^ input stream to wrap -> IO (InputStream ByteString) takeBytes k0 = takeBytes' k0 (return Nothing) {-# INLINE takeBytes #-} ------------------------------------------------------------------------------ -- | Like @Streams.'takeBytes'@, but throws 'ReadTooShortException' when -- there aren't enough bytes present on the source. takeExactly :: Int64 -- ^ number of bytes to read -> InputStream ByteString -- ^ input stream to wrap -> IO (InputStream ByteString) takeExactly k0 = takeBytes' k0 (throwIO $ ReadTooShortException k0) {-# INLINE takeExactly #-} ------------------------------------------------------------------------------ -- Helper for the two above. takeBytes' :: Int64 -> IO (Maybe ByteString) -- ^ What to do if the input ends before having consumed the -- right amount of bytes. -> InputStream ByteString -> IO (InputStream ByteString) takeBytes' k0 h src = do kref <- newIORef k0 return $! InputStream (prod kref) (pb kref) where prod kref = do k <- readIORef kref if k <= 0 then return Nothing else read src >>= maybe h (chunk k) where chunk k s = do let l = fromIntegral $ S.length s let k' = k - l if k' <= 0 then let (a,b) = S.splitAt (fromIntegral k) s in do when (not $ S.null b) $ unRead b src writeIORef kref 0 return $! Just a else writeIORef kref k' >> return (Just s) pb kref s = do modifyRef kref (+ (fromIntegral $ S.length s)) unRead s src {-# INLINE takeBytes' #-} ------------------------------------------------------------------------------ -- | Splits an 'InputStream' over 'ByteString's using a delimiter predicate. -- -- Note that: -- -- * data pushed back with 'unRead' is *not* propagated upstream here. -- -- * the resulting 'InputStream' may hold an unbounded amount of the -- bytestring in memory waiting for the function to return true, so this -- function should not be used in unsafe contexts. -- -- * the delimiter is NOT included in the output. -- -- * consecutive delimiters are not merged. -- -- * if the input ends in the delimiter, a final empty string is /not/ -- emitted. (/Since: 1.5.0.0. Previous versions had the opposite behaviour, -- which was changed to match 'Prelude.lines'./) -- -- Example: -- -- @ -- ghci> Streams.'System.IO.Streams.fromList' [\"the quick br\", \"own fox\"::'ByteString'] >>= -- Streams.'splitOn' (== \' \') >>= Streams.'System.IO.Streams.toList' -- [\"the\",\"quick\",\"brown\",\"\",\"fox\"] -- @ -- splitOn :: (Char -> Bool) -- ^ predicate used to break the input -- stream into chunks -> InputStream ByteString -- ^ input stream -> IO (InputStream ByteString) splitOn p is = do ref <- newIORef id makeInputStream $ start ref where start ref = go where go = read is >>= maybe end chunk end = do dl <- readIORef ref case dl [] of [] -> return Nothing xs -> writeIORef ref id >> (return $! Just $! S.concat xs) chunk s = let (a, b) = S.break p s in if S.null b then modifyRef ref (\f -> f . (a:)) >> go else do let !b' = S.unsafeDrop 1 b dl <- readIORef ref when (not $ S.null b') $ unRead b' is writeIORef ref id return $ Just $! S.concat $ dl [a] ------------------------------------------------------------------------------ -- | Splits a bytestring 'InputStream' into lines. See 'splitOn' and -- 'Prelude.lines'. -- -- Example: -- -- @ -- ghci> is \<- Streams.'System.IO.Streams.fromList' [\"Hello,\\n world!\"] >>= Streams.'lines' -- ghci> replicateM 3 (Streams.'read' is) -- [Just \"Hello\", Just \", world!\", Nothing] -- @ -- -- Note that this may increase the chunk size if the input contains extremely -- long lines. lines :: InputStream ByteString -> IO (InputStream ByteString) lines = splitOn (== '\n') ------------------------------------------------------------------------------ -- | Splits a bytestring 'InputStream' into words. See 'splitOn' and -- 'Prelude.words'. -- -- Example: -- -- @ -- ghci> is \<- Streams.'System.IO.Streams.fromList' [\"Hello, world!\"] >>= Streams.'words' -- ghci> replicateM 3 (Streams.'read' is) -- [Just \"Hello,\", Just \"world!\", Nothing] -- @ -- -- Note that this may increase the chunk size if the input contains extremely -- long words. words :: InputStream ByteString -> IO (InputStream ByteString) words = splitOn isSpace >=> filterM (return . not . S.all isSpace) ------------------------------------------------------------------------------ -- | Intersperses string chunks sent to the given 'OutputStream' with newlines. -- See 'intersperse' and 'Prelude.unlines'. -- -- @ -- ghci> os <- Streams.'unlines' Streams.'System.IO.Streams.stdout' -- ghci> Streams.'write' (Just \"Hello,\") os -- Hello -- ghci> Streams.'write' Nothing os -- ghci> Streams.'write' (Just \"world!\") os -- world! -- @ unlines :: OutputStream ByteString -> IO (OutputStream ByteString) unlines os = makeOutputStream $ \m -> do write m os case m of Nothing -> return $! () Just _ -> write (Just "\n") os ------------------------------------------------------------------------------ -- | Intersperses string chunks sent to the given 'OutputStream' with spaces. -- See 'intersperse' and 'Prelude.unwords'. -- -- @ -- ghci> os <- Streams.'unwords' Streams.'System.IO.Streams.stdout' -- ghci> forM_ [Just \"Hello,\", Nothing, Just \"world!\\n\"] $ \w -> Streams.'write' w os -- Hello, world! -- @ unwords :: OutputStream ByteString -> IO (OutputStream ByteString) unwords = intersperse " " ------------------------------------------------------------------------------ -- | Thrown by 'throwIfProducesMoreThan' when too many bytes were read from the -- original 'InputStream'. data TooManyBytesReadException = TooManyBytesReadException deriving (Typeable) instance Show TooManyBytesReadException where show TooManyBytesReadException = "Too many bytes read" instance Exception TooManyBytesReadException ------------------------------------------------------------------------------ -- | Thrown by 'giveExactly' when too few bytes were written to the produced -- 'OutputStream'. data TooFewBytesWrittenException = TooFewBytesWrittenException deriving (Typeable) instance Show TooFewBytesWrittenException where show TooFewBytesWrittenException = "Too few bytes written" instance Exception TooFewBytesWrittenException ------------------------------------------------------------------------------ -- | Thrown by 'throwIfConsumesMoreThan' when too many bytes were sent to the -- produced 'OutputStream'. data TooManyBytesWrittenException = TooManyBytesWrittenException deriving (Typeable) instance Show TooManyBytesWrittenException where show TooManyBytesWrittenException = "Too many bytes written" instance Exception TooManyBytesWrittenException ------------------------------------------------------------------------------ -- | Thrown by 'readExactly' and 'takeExactly' when not enough bytes were -- available on the input. data ReadTooShortException = ReadTooShortException Int64 deriving (Typeable) instance Show ReadTooShortException where show (ReadTooShortException x) = "Short read, expected " ++ show x ++ " bytes" instance Exception ReadTooShortException ------------------------------------------------------------------------------ -- | Wraps an 'InputStream'. If more than @n@ bytes are produced by this -- stream, 'read' will throw a 'TooManyBytesReadException'. -- -- If a chunk yielded by the input stream would result in more than @n@ bytes -- being produced, 'throwIfProducesMoreThan' will cut the generated string such -- that exactly @n@ bytes are yielded by the returned stream, and the -- /subsequent/ read will throw an exception. Example: -- -- @ -- ghci> is \<- Streams.'System.IO.Streams.fromList' [\"abc\", \"def\", \"ghi\"] >>= -- Streams.'throwIfProducesMoreThan' 5 -- ghci> 'Control.Monad.replicateM' 2 ('read' is) -- [Just \"abc\",Just \"de\"] -- ghci> Streams.'read' is -- *** Exception: Too many bytes read -- @ -- -- Strings pushed back to the returned 'InputStream' will be propagated -- upstream, modifying the count of taken bytes accordingly. Example: -- -- @ -- ghci> is <- Streams.'System.IO.Streams.fromList' [\"abc\", \"def\", \"ghi\"] -- ghci> is' <- Streams.'throwIfProducesMoreThan' 5 is -- ghci> Streams.'read' is' -- Just \"abc\" -- ghci> Streams.'unRead' \"xyz\" is' -- ghci> Streams.'System.IO.Streams.peek' is -- Just \"xyz\" -- ghci> Streams.'read' is -- Just \"xyz\" -- ghci> Streams.'read' is -- Just \"de\" -- ghci> Streams.'read' is -- *** Exception: Too many bytes read -- @ -- throwIfProducesMoreThan :: Int64 -- ^ maximum number of bytes to read -> InputStream ByteString -- ^ input stream -> IO (InputStream ByteString) throwIfProducesMoreThan k0 src = do kref <- newIORef k0 return $! InputStream (prod kref) (pb kref) where prod kref = read src >>= maybe (return Nothing) chunk where chunk s = do k <- readIORef kref let k' = k - l case () of !_ | l == 0 -> return (Just s) | k == 0 -> throwIO TooManyBytesReadException | k' >= 0 -> writeIORef kref k' >> return (Just s) | otherwise -> do let (!a,!b) = S.splitAt (fromEnum k) s writeIORef kref 0 unRead b src return $! Just a where l = toEnum $ S.length s pb kref s = do unRead s src modifyRef kref (+ (fromIntegral $ S.length s)) ------------------------------------------------------------------------------ -- | Reads an @n@-byte ByteString from an input stream. Throws a -- 'ReadTooShortException' if fewer than @n@ bytes were available. -- -- Example: -- -- @ -- ghci> Streams.'System.IO.Streams.fromList' [\"long string\"] >>= Streams.'readExactly' 6 -- \"long s\" -- ghci> Streams.'System.IO.Streams.fromList' [\"short\"] >>= Streams.'readExactly' 6 -- *** Exception: Short read, expected 6 bytes -- @ -- readExactly :: Int -- ^ number of bytes to read -> InputStream ByteString -- ^ input stream -> IO ByteString readExactly n input = go id n where go !dl 0 = return $! S.concat $! dl [] go !dl k = read input >>= maybe (throwIO $ ReadTooShortException (fromIntegral n)) (\s -> do let l = S.length s if l >= k then do let (a,b) = S.splitAt k s when (not $ S.null b) $ unRead b input return $! S.concat $! dl [a] else go (dl . (s:)) (k - l)) ------------------------------------------------------------------------------ -- | Takes from a stream until the given predicate is no longer satisfied. -- Returns Nothing on end-of-stream, or @Just \"\"@ if the predicate is never -- satisfied. See 'Prelude.takeWhile' and 'Data.ByteString.Char8.takeWhile'. -- -- Example: -- -- @ -- ghci> Streams.'System.IO.Streams.fromList' [\"Hello, world!\"] >>= Streams.'takeBytesWhile' (/= ',') -- Just \"Hello\" -- ghci> import Data.Char -- ghci> Streams.'System.IO.Streams.fromList' [\"7 Samurai\"] >>= Streams.'takeBytesWhile' isAlpha -- Just \"\" -- ghci> Streams.'System.IO.Streams.fromList' [] >>= Streams.'takeBytesWhile' isAlpha -- Nothing -- @ takeBytesWhile :: (Char -> Bool) -- ^ predicate -> InputStream ByteString -- ^ input stream -> IO (Maybe ByteString) takeBytesWhile p input = read input >>= maybe (return Nothing) (go id) where go dl !s | S.null b = read input >>= maybe finish (go dl') | otherwise = unRead b input >> finish where (a, b) = S.span p s dl' = dl . (a:) finish = return $! Just $! S.concat $! dl [a] ------------------------------------------------------------------------------ -- | Wraps an 'OutputStream', producing a new stream that will pass along at -- most @n@ bytes to the wrapped stream, throwing any subsequent input away. -- -- Example: -- -- @ -- ghci> (os :: OutputStream ByteString, getList) <- Streams.'System.IO.Streams.listOutputStream' -- ghci> os' <- Streams.'giveBytes' 6 os -- ghci> Streams.'System.IO.Streams.fromList' [\"long \", \"string\"] >>= Streams.'System.IO.Streams.connectTo' os' -- ghci> getList -- [\"long \",\"s\"] -- @ giveBytes :: Int64 -- ^ maximum number of bytes to send -- to the wrapped stream -> OutputStream ByteString -- ^ output stream to wrap -> IO (OutputStream ByteString) giveBytes k0 str = do kref <- newIORef k0 makeOutputStream $ sink kref where sink _ Nothing = write Nothing str sink kref mb@(Just x) = do k <- readIORef kref let l = fromIntegral $ S.length x let k' = k - l if k' < 0 then do let a = S.take (fromIntegral k) x when (not $ S.null a) $ write (Just a) str writeIORef kref 0 else writeIORef kref k' >> write mb str ------------------------------------------------------------------------------ -- | Wraps an 'OutputStream', producing a new stream that will pass along -- exactly @n@ bytes to the wrapped stream. If the stream is sent more or fewer -- than the given number of bytes, the resulting stream will throw an exception -- (either 'TooFewBytesWrittenException' or 'TooManyBytesWrittenException') -- during a call to 'write'. -- -- Example: -- -- @ -- ghci> is <- Streams.'System.IO.Streams.fromList' [\"ok\"] -- ghci> Streams.'System.IO.Streams.outputToList' (Streams.'giveExactly' 2 >=> Streams.'System.IO.Streams.connect' is) -- [\"ok\"] -- ghci> is <- Streams.'System.IO.Streams.fromList' [\"ok\"] -- ghci> Streams.'System.IO.Streams.outputToList' (Streams.'giveExactly' 1 >=> Streams.'System.IO.Streams.connect' is) -- *** Exception: Too many bytes written -- ghci> is <- Streams.'System.IO.Streams.fromList' [\"ok\"] -- ghci> Streams.'System.IO.Streams.outputToList' (Streams.'giveExactly' 3 >=> Streams.'System.IO.Streams.connect' is) -- *** Exception: Too few bytes written -- @ giveExactly :: Int64 -> OutputStream ByteString -> IO (OutputStream ByteString) giveExactly k0 os = do ref <- newIORef k0 makeOutputStream $ go ref where go ref chunk = do !n <- readIORef ref case chunk of Nothing -> if n /= 0 then throwIO TooFewBytesWrittenException else return $! () Just s -> let n' = n - fromIntegral (S.length s) in if n' < 0 then throwIO TooManyBytesWrittenException else do writeIORef ref n' write chunk os ------------------------------------------------------------------------------ -- | Wraps an 'OutputStream', producing a new stream that will pass along at -- most @n@ bytes to the wrapped stream. If more than @n@ bytes are sent to the -- outer stream, a 'TooManyBytesWrittenException' will be thrown. -- -- /Note/: if more than @n@ bytes are sent to the outer stream, -- 'throwIfConsumesMoreThan' will not necessarily send the first @n@ bytes -- through to the wrapped stream before throwing the exception. -- -- Example: -- -- @ -- ghci> (os :: OutputStream ByteString, getList) <- Streams.'System.IO.Streams.listOutputStream' -- ghci> os' <- Streams.'throwIfConsumesMoreThan' 5 os -- ghci> Streams.'System.IO.Streams.fromList' [\"short\"] >>= Streams.'System.IO.Streams.connectTo' os' -- ghci> getList -- [\"short\"] -- ghci> os'' <- Streams.'throwIfConsumesMoreThan' 5 os -- ghci> Streams.'System.IO.Streams.fromList' [\"long\", \"string\"] >>= Streams.'System.IO.Streams.connectTo' os'' -- *** Exception: Too many bytes written -- @ throwIfConsumesMoreThan :: Int64 -- ^ maximum number of bytes to send to the -- wrapped stream -> OutputStream ByteString -- ^ output stream to wrap -> IO (OutputStream ByteString) throwIfConsumesMoreThan k0 str = do kref <- newIORef k0 makeOutputStream $ sink kref where sink _ Nothing = write Nothing str sink kref mb@(Just x) = do k <- readIORef kref let l = toEnum $ S.length x let k' = k - l if k' < 0 then throwIO TooManyBytesWrittenException else writeIORef kref k' >> write mb str ------------------------------------------------------------------------------ -- | Gets the current posix time getTime :: IO Double getTime = realToFrac `fmap` getPOSIXTime ------------------------------------------------------------------------------ -- | Thrown by 'throwIfTooSlow' if input is not being produced fast enough by -- the given 'InputStream'. -- data RateTooSlowException = RateTooSlowException deriving (Typeable) instance Show RateTooSlowException where show RateTooSlowException = "Input rate too slow" instance Exception RateTooSlowException ------------------------------------------------------------------------------ -- | Rate-limits an input stream. If the input stream is not read from faster -- than the given rate, reading from the wrapped stream will throw a -- 'RateTooSlowException'. -- -- Strings pushed back to the returned 'InputStream' will be propagated up to -- the original stream. throwIfTooSlow :: IO () -- ^ action to bump timeout -> Double -- ^ minimum data rate, in bytes per second -> Int -- ^ amount of time in seconds to wait before -- data rate calculation takes effect -> InputStream ByteString -- ^ input stream -> IO (InputStream ByteString) throwIfTooSlow !bump !minRate !minSeconds' !stream = do !_ <- bump startTime <- getTime bytesRead <- newIORef (0 :: Int64) return $! InputStream (prod startTime bytesRead) (pb bytesRead) where prod startTime bytesReadRef = read stream >>= maybe (return Nothing) chunk where chunk s = do let slen = S.length s now <- getTime let !delta = now - startTime nb <- readIORef bytesReadRef let newBytes = nb + fromIntegral slen when (delta > minSeconds + 1 && (fromIntegral newBytes / (delta - minSeconds)) < minRate) $ throwIO RateTooSlowException -- otherwise, bump the timeout and return the input !_ <- bump writeIORef bytesReadRef newBytes return $! Just s pb bytesReadRef s = do modifyRef bytesReadRef $ \x -> x - (fromIntegral $ S.length s) unRead s stream minSeconds = fromIntegral minSeconds'
snapframework/io-streams
src/System/IO/Streams/ByteString.hs
bsd-3-clause
26,417
0
22
6,399
3,964
2,128
1,836
297
4
{-# LANGUAGE CPP, BangPatterns #-} module Main where import Control.Monad import Data.Int import System.Environment (getArgs, withArgs) import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime) import System.IO (withFile, IOMode(..), hPutStrLn, Handle, stderr) import Control.Concurrent (forkIO) import Control.Concurrent.MVar (newEmptyMVar, takeMVar, putMVar) import Debug.Trace import Data.ByteString (ByteString) import Data.ByteString.Char8 (pack, unpack) import qualified Data.ByteString as BS import qualified Network.Socket.ByteString as NBS import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime) import qualified Data.ByteString as BS import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime) import System.ZMQ4 (Socket, Push(..), Pull(..),socket, connect, bind, context) import qualified System.ZMQ4 as ZMQ import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TMChan (TMChan, newTMChan, readTMChan, writeTMChan) main = do [pingsStr] <- getArgs clientDone <- newEmptyMVar ctx <- context -- Start the server forkIO $ do putStrLn "server: creating TCP connection" push <- socket ctx Push connect push "tcp://127.0.0.1:8080" putStrLn "server: awaiting client connection" pull <- socket ctx Pull bind pull "tcp://*:8081" putStrLn "server: listening for pings" -- Set up multiplexing channel multiplexChannel <- atomically $ newTMChan -- Wait for incoming connections (pings from the client) forkIO $ socketToChan pull multiplexChannel -- Reply to the client forever $ atomically (readTMChan multiplexChannel) >>= \(Just x) -> send push x -- Start the client forkIO $ do let pings = read pingsStr push <- socket ctx Push connect push "tcp://127.0.0.1:8081" putStrLn "server: awaiting client connection" pull <- socket ctx Pull bind pull "tcp://*:8080" ping pull push pings putMVar clientDone () -- Wait for the client to finish takeMVar clientDone socketToChan :: Socket Pull -> TMChan ByteString -> IO () socketToChan sock chan = go where go = do bs <- recv sock when (BS.length bs > 0) $ do atomically $ writeTMChan chan bs go pingMessage :: ByteString pingMessage = pack "ping123" ping :: Socket Pull -> Socket Push -> Int -> IO () ping pull push pings = go pings where go :: Int -> IO () go 0 = do putStrLn $ "client did " ++ show pings ++ " pings" go !i = do before <- getCurrentTime send push pingMessage bs <- recv pull after <- getCurrentTime -- putStrLn $ "client received " ++ unpack bs let latency = (1e6 :: Double) * realToFrac (diffUTCTime after before) hPutStrLn stderr $ show i ++ " " ++ show latency go (i - 1) -- | Receive a package recv :: Socket Pull -> IO ByteString recv = ZMQ.receive -- | Send a package send :: Socket Push -> ByteString -> IO () send sock bs = ZMQ.send sock [] bs
tweag/network-transport-zeromq
benchmarks/subparts/h-zmq-tmchan.hs
bsd-3-clause
2,983
0
15
640
870
447
423
71
2
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 The @TyCon@ datatype -} {-# LANGUAGE CPP, DeriveDataTypeable #-} module TyCon( -- * Main TyCon data types TyCon, AlgTyConRhs(..), visibleDataCons, AlgTyConFlav(..), isNoParent, FamTyConFlav(..), Role(..), Promoted(..), Injectivity(..), -- ** Field labels tyConFieldLabels, tyConFieldLabelEnv, -- ** Constructing TyCons mkAlgTyCon, mkClassTyCon, mkFunTyCon, mkPrimTyCon, mkKindTyCon, mkLiftedPrimTyCon, mkTupleTyCon, mkSynonymTyCon, mkFamilyTyCon, mkPromotedDataCon, mkPromotedTyCon, -- ** Predicates on TyCons isAlgTyCon, isClassTyCon, isFamInstTyCon, isFunTyCon, isPrimTyCon, isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon, isTypeSynonymTyCon, mightBeUnsaturatedTyCon, isPromotedDataCon, isPromotedTyCon, isPromotedDataCon_maybe, isPromotedTyCon_maybe, promotableTyCon_maybe, isPromotableTyCon, promoteTyCon, isDataTyCon, isProductTyCon, isDataProductTyCon_maybe, isEnumerationTyCon, isNewTyCon, isAbstractTyCon, isFamilyTyCon, isOpenFamilyTyCon, isTypeFamilyTyCon, isDataFamilyTyCon, isOpenTypeFamilyTyCon, isClosedSynFamilyTyConWithAxiom_maybe, familyTyConInjectivityInfo, isBuiltInSynFamTyCon_maybe, isUnLiftedTyCon, isGadtSyntaxTyCon, isInjectiveTyCon, isGenerativeTyCon, isGenInjAlgRhs, isTyConAssoc, tyConAssoc_maybe, isRecursiveTyCon, isImplicitTyCon, -- ** Extracting information out of TyCons tyConName, tyConKind, tyConUnique, tyConTyVars, tyConCType, tyConCType_maybe, tyConDataCons, tyConDataCons_maybe, tyConSingleDataCon_maybe, tyConSingleDataCon, tyConSingleAlgDataCon_maybe, tyConFamilySize, tyConStupidTheta, tyConArity, tyConRoles, tyConFlavour, tyConTuple_maybe, tyConClass_maybe, tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe, tyConFamilyResVar_maybe, synTyConDefn_maybe, synTyConRhs_maybe, famTyConFlav_maybe, famTcResVar, algTyConRhs, newTyConRhs, newTyConEtadArity, newTyConEtadRhs, unwrapNewTyCon_maybe, unwrapNewTyConEtad_maybe, algTcFields, -- ** Manipulating TyCons expandSynTyCon_maybe, makeTyConAbstract, newTyConCo, newTyConCo_maybe, pprPromotionQuote, -- * Runtime type representation TyConRepName, tyConRepName_maybe, -- * Primitive representations of Types PrimRep(..), PrimElemRep(..), tyConPrimRep, isVoidRep, isGcPtrRep, primRepSizeW, primElemRepSizeB, primRepIsFloat, -- * Recursion breaking RecTcChecker, initRecTc, checkRecTc ) where #include "HsVersions.h" import {-# SOURCE #-} TypeRep ( Kind, Type, PredType ) import {-# SOURCE #-} DataCon ( DataCon, dataConExTyVars, dataConFieldLabels ) import Binary import Var import Class import BasicTypes import DynFlags import ForeignCall import Name import NameEnv import CoAxiom import PrelNames import Maybes import Outputable import FastStringEnv import FieldLabel import Constants import Util import qualified Data.Data as Data import Data.Typeable (Typeable) {- ----------------------------------------------- Notes about type families ----------------------------------------------- Note [Type synonym families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Type synonym families, also known as "type functions", map directly onto the type functions in FC: type family F a :: * type instance F Int = Bool ..etc... * Reply "yes" to isTypeFamilyTyCon, and isFamilyTyCon * From the user's point of view (F Int) and Bool are simply equivalent types. * A Haskell 98 type synonym is a degenerate form of a type synonym family. * Type functions can't appear in the LHS of a type function: type instance F (F Int) = ... -- BAD! * Translation of type family decl: type family F a :: * translates to a FamilyTyCon 'F', whose FamTyConFlav is OpenSynFamilyTyCon type family G a :: * where G Int = Bool G Bool = Char G a = () translates to a FamilyTyCon 'G', whose FamTyConFlav is ClosedSynFamilyTyCon, with the appropriate CoAxiom representing the equations We also support injective type families -- see Note [Injective type families] Note [Data type families] ~~~~~~~~~~~~~~~~~~~~~~~~~ See also Note [Wrappers for data instance tycons] in MkId.hs * Data type families are declared thus data family T a :: * data instance T Int = T1 | T2 Bool Here T is the "family TyCon". * Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon * The user does not see any "equivalent types" as he did with type synonym families. He just sees constructors with types T1 :: T Int T2 :: Bool -> T Int * Here's the FC version of the above declarations: data T a data R:TInt = T1 | T2 Bool axiom ax_ti : T Int ~R R:TInt Note that this is a *representational* coercion The R:TInt is the "representation TyCons". It has an AlgTyConFlav of DataFamInstTyCon T [Int] ax_ti * The axiom ax_ti may be eta-reduced; see Note [Eta reduction for data family axioms] in TcInstDcls * The data contructor T2 has a wrapper (which is what the source-level "T2" invokes): $WT2 :: Bool -> T Int $WT2 b = T2 b `cast` sym ax_ti * A data instance can declare a fully-fledged GADT: data instance T (a,b) where X1 :: T (Int,Bool) X2 :: a -> b -> T (a,b) Here's the FC version of the above declaration: data R:TPair a where X1 :: R:TPair Int Bool X2 :: a -> b -> R:TPair a b axiom ax_pr :: T (a,b) ~R R:TPair a b $WX1 :: forall a b. a -> b -> T (a,b) $WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b) The R:TPair are the "representation TyCons". We have a bit of work to do, to unpick the result types of the data instance declaration for T (a,b), to get the result type in the representation; e.g. T (a,b) --> R:TPair a b The representation TyCon R:TList, has an AlgTyConFlav of DataFamInstTyCon T [(a,b)] ax_pr * Notice that T is NOT translated to a FC type function; it just becomes a "data type" with no constructors, which can be coerced inot into R:TInt, R:TPair by the axioms. These axioms axioms come into play when (and *only* when) you - use a data constructor - do pattern matching Rather like newtype, in fact As a result - T behaves just like a data type so far as decomposition is concerned - (T Int) is not implicitly converted to R:TInt during type inference. Indeed the latter type is unknown to the programmer. - There *is* an instance for (T Int) in the type-family instance environment, but it is only used for overlap checking - It's fine to have T in the LHS of a type function: type instance F (T a) = [a] It was this last point that confused me! The big thing is that you should not think of a data family T as a *type function* at all, not even an injective one! We can't allow even injective type functions on the LHS of a type function: type family injective G a :: * type instance F (G Int) = Bool is no good, even if G is injective, because consider type instance G Int = Bool type instance F Bool = Char So a data type family is not an injective type function. It's just a data type with some axioms that connect it to other data types. * The tyConTyVars of the representation tycon are the tyvars that the user wrote in the patterns. This is important in TcDeriv, where we bring these tyvars into scope before type-checking the deriving clause. This fact is arranged for in TcInstDecls.tcDataFamInstDecl. Note [Associated families and their parent class] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *Associated* families are just like *non-associated* families, except that they have a famTcParent field of (Just cls), which identifies the parent class. However there is an important sharing relationship between * the tyConTyVars of the parent Class * the tyConTyvars of the associated TyCon class C a b where data T p a type F a q b Here the 'a' and 'b' are shared with the 'Class'; that is, they have the same Unique. This is important. In an instance declaration we expect * all the shared variables to be instantiated the same way * the non-shared variables of the associated type should not be instantiated at all instance C [x] (Tree y) where data T p [x] = T1 x | T2 p type F [x] q (Tree y) = (x,y,q) Note [TyCon Role signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Every tycon has a role signature, assigning a role to each of the tyConTyVars (or of equal length to the tyConArity, if there are no tyConTyVars). An example demonstrates these best: say we have a tycon T, with parameters a at nominal, b at representational, and c at phantom. Then, to prove representational equality between T a1 b1 c1 and T a2 b2 c2, we need to have nominal equality between a1 and a2, representational equality between b1 and b2, and nothing in particular (i.e., phantom equality) between c1 and c2. This might happen, say, with the following declaration: data T a b c where MkT :: b -> T Int b c Data and class tycons have their roles inferred (see inferRoles in TcTyDecls), as do vanilla synonym tycons. Family tycons have all parameters at role N, though it is conceivable that we could relax this restriction. (->)'s and tuples' parameters are at role R. Each primitive tycon declares its roles; it's worth noting that (~#)'s parameters are at role N. Promoted data constructors' type arguments are at role R. All kind arguments are at role N. Note [Injective type families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We allow injectivity annotations for type families (both open and closed): type family F (a :: k) (b :: k) = r | r -> a type family G a b = res | res -> a b where ... Injectivity information is stored in the `famTcInj` field of `FamilyTyCon`. `famTcInj` maybe stores a list of Bools, where each entry corresponds to a single element of `tyConTyVars` (both lists should have identical length). If no injectivity annotation was provided `famTcInj` is Nothing. From this follows an invariant that if `famTcInj` is a Just then at least one element in the list must be True. See also: * [Injectivity annotation] in HsDecls * [Renaming injectivity annotation] in RnSource * [Verifying injectivity annotation] in FamInstEnv * [Type inference for type families with injectivity] in TcInteract ************************************************************************ * * \subsection{The data type} * * ************************************************************************ -} -- | TyCons represent type constructors. Type constructors are introduced by -- things such as: -- -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of -- kind @*@ -- -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor -- -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor -- of kind @* -> *@ -- -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor -- of kind @*@ -- -- This data type also encodes a number of primitive, built in type constructors -- such as those for function and tuple types. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data TyCon = -- | The function type constructor, @(->)@ FunTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tcRepName :: TyConRepName } -- | Algebraic data types, from -- - @data@ declararations -- - @newtype@ declarations -- - data instance declarations -- - type instance declarations -- - the TyCon generated by a class declaration -- - boxed tuples -- - unboxed tuples -- - constraint tuples -- All these constructors are lifted and boxed except unboxed tuples -- which should have an 'UnboxedAlgTyCon' parent. -- Data/newtype/type /families/ are handled by 'FamilyTyCon'. -- See 'AlgTyConRhs' for more information. | AlgTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tyConTyVars :: [TyVar], -- ^ The kind and type variables used in the -- type constructor. -- Invariant: length tyvars = arity -- Precisely, this list scopes over: -- -- 1. The 'algTcStupidTheta' -- 2. The cached types in algTyConRhs.NewTyCon -- 3. The family instance types if present -- -- Note that it does /not/ scope over the data -- constructors. tcRoles :: [Role], -- ^ The role for each type variable -- This list has the same length as tyConTyVars -- See also Note [TyCon Role signatures] tyConCType :: Maybe CType,-- ^ The C type that should be used -- for this type when using the FFI -- and CAPI algTcGadtSyntax :: Bool, -- ^ Was the data type declared with GADT -- syntax? If so, that doesn't mean it's a -- true GADT; only that the "where" form -- was used. This field is used only to -- guide pretty-printing algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data -- type (always empty for GADTs). A -- \"stupid theta\" is the context to -- the left of an algebraic type -- declaration, e.g. @Eq a@ in the -- declaration @data Eq a => T a ...@. algTcRhs :: AlgTyConRhs, -- ^ Contains information about the -- data constructors of the algebraic type algTcFields :: FieldLabelEnv, -- ^ Maps a label to information -- about the field algTcRec :: RecFlag, -- ^ Tells us whether the data type is part -- of a mutually-recursive group or not algTcParent :: AlgTyConFlav, -- ^ Gives the class or family declaration -- 'TyCon' for derived 'TyCon's representing -- class or family instances, respectively. tcPromoted :: Promoted TyCon -- ^ Promoted TyCon, if any } -- | Represents type synonyms | SynonymTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tyConTyVars :: [TyVar], -- ^ List of type and kind variables in this -- TyCon. Includes implicit kind variables. -- Invariant: length tyConTyVars = tyConArity tcRoles :: [Role], -- ^ The role for each type variable -- This list has the same length as tyConTyVars -- See also Note [TyCon Role signatures] synTcRhs :: Type -- ^ Contains information about the expansion -- of the synonym } -- | Represents families (both type and data) -- Argument roles are all Nominal | FamilyTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tyConTyVars :: [TyVar], -- ^ The kind and type variables used in the -- type constructor. -- Invariant: length tyvars = arity -- Precisely, this list scopes over: -- -- 1. The 'algTcStupidTheta' -- 2. The cached types in 'algTyConRhs.NewTyCon' -- 3. The family instance types if present -- -- Note that it does /not/ scope over the data -- constructors. famTcResVar :: Maybe Name, -- ^ Name of result type variable, used -- for pretty-printing with --show-iface -- and for reifying TyCon in Template -- Haskell famTcFlav :: FamTyConFlav, -- ^ Type family flavour: open, closed, -- abstract, built-in. See comments for -- FamTyConFlav famTcParent :: Maybe Class, -- ^ For *associated* type/data families -- The class in whose declaration the family is declared -- See Note [Associated families and their parent class] famTcInj :: Injectivity -- ^ is this a type family injective in -- its type variables? Nothing if no -- injectivity annotation was given } -- | Primitive types; cannot be defined in Haskell. This includes -- the usual suspects (such as @Int#@) as well as foreign-imported -- types and kinds (@*@, @#@, and @?@) | PrimTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tcRoles :: [Role], -- ^ The role for each type variable -- This list has the same length as tyConTyVars -- See also Note [TyCon Role signatures] primTyConRep :: PrimRep,-- ^ Many primitive tycons are unboxed, but -- some are boxed (represented by -- pointers). This 'PrimRep' holds that -- information. Only relevant if tyConKind = * isUnLifted :: Bool, -- ^ Most primitive tycons are unlifted (may -- not contain bottom) but other are lifted, -- e.g. @RealWorld@ -- Only relevant if tyConKind = * primRepName :: Maybe TyConRepName -- Only relevant for kind TyCons -- i.e, *, #, ? } -- | Represents promoted data constructor. | PromotedDataCon { -- See Note [Promoted data constructors] tyConUnique :: Unique, -- ^ Same Unique as the data constructor tyConName :: Name, -- ^ Same Name as the data constructor tyConArity :: Arity, tyConKind :: Kind, -- ^ Translated type of the data constructor tcRoles :: [Role], -- ^ Roles: N for kind vars, R for type vars dataCon :: DataCon,-- ^ Corresponding data constructor tcRepName :: TyConRepName } -- | Represents promoted type constructor. | PromotedTyCon { tyConUnique :: Unique, -- ^ Same Unique as the type constructor tyConName :: Name, -- ^ Same Name as the type constructor tyConArity :: Arity, -- ^ n if ty_con :: * -> ... -> * n times tyConKind :: Kind, -- ^ Always TysPrim.superKind ty_con :: TyCon, -- ^ Corresponding type constructor tcRepName :: TyConRepName } deriving Typeable -- | Represents right-hand-sides of 'TyCon's for algebraic types data AlgTyConRhs -- | Says that we know nothing about this data type, except that -- it's represented by a pointer. Used when we export a data type -- abstractly into an .hi file. = AbstractTyCon Bool -- True <=> It's definitely a distinct data type, -- equal only to itself; ie not a newtype -- False <=> Not sure -- | Information about those 'TyCon's derived from a @data@ -- declaration. This includes data types with no constructors at -- all. | DataTyCon { data_cons :: [DataCon], -- ^ The data type constructors; can be empty if the -- user declares the type to have no constructors -- -- INVARIANT: Kept in order of increasing 'DataCon' -- tag (see the tag assignment in DataCon.mkDataCon) is_enum :: Bool -- ^ Cached value: is this an enumeration type? -- See Note [Enumeration types] } | TupleTyCon { -- A boxed, unboxed, or constraint tuple data_con :: DataCon, -- NB: it can be an *unboxed* tuple tup_sort :: TupleSort -- ^ Is this a boxed, unboxed or constraint -- tuple? } -- | Information about those 'TyCon's derived from a @newtype@ declaration | NewTyCon { data_con :: DataCon, -- ^ The unique constructor for the @newtype@. -- It has no existentials nt_rhs :: Type, -- ^ Cached value: the argument type of the -- constructor, which is just the representation -- type of the 'TyCon' (remember that @newtype@s -- do not exist at runtime so need a different -- representation type). -- -- The free 'TyVar's of this type are the -- 'tyConTyVars' from the corresponding 'TyCon' nt_etad_rhs :: ([TyVar], Type), -- ^ Same as the 'nt_rhs', but this time eta-reduced. -- Hence the list of 'TyVar's in this field may be -- shorter than the declared arity of the 'TyCon'. -- See Note [Newtype eta] nt_co :: CoAxiom Unbranched -- The axiom coercion that creates the @newtype@ -- from the representation 'Type'. -- See Note [Newtype coercions] -- Invariant: arity = #tvs in nt_etad_rhs; -- See Note [Newtype eta] -- Watch out! If any newtypes become transparent -- again check Trac #1072. } -- | Isomorphic to Maybe, but used when the question is -- whether or not something is promoted data Promoted a = NotPromoted | Promoted a -- | Extract those 'DataCon's that we are able to learn about. Note -- that visibility in this sense does not correspond to visibility in -- the context of any particular user program! visibleDataCons :: AlgTyConRhs -> [DataCon] visibleDataCons (AbstractTyCon {}) = [] visibleDataCons (DataTyCon{ data_cons = cs }) = cs visibleDataCons (NewTyCon{ data_con = c }) = [c] visibleDataCons (TupleTyCon{ data_con = c }) = [c] -- ^ Both type classes as well as family instances imply implicit -- type constructors. These implicit type constructors refer to their parent -- structure (ie, the class or family from which they derive) using a type of -- the following form. data AlgTyConFlav = -- | An ordinary type constructor has no parent. VanillaAlgTyCon TyConRepName -- | An unboxed type constructor. Note that this carries no TyConRepName -- as it is not representable. | UnboxedAlgTyCon -- | Type constructors representing a class dictionary. -- See Note [ATyCon for classes] in TypeRep | ClassTyCon Class -- INVARIANT: the classTyCon of this Class is the -- current tycon TyConRepName -- | Type constructors representing an *instance* of a *data* family. -- Parameters: -- -- 1) The type family in question -- -- 2) Instance types; free variables are the 'tyConTyVars' -- of the current 'TyCon' (not the family one). INVARIANT: -- the number of types matches the arity of the family 'TyCon' -- -- 3) A 'CoTyCon' identifying the representation -- type with the type instance family | DataFamInstTyCon -- See Note [Data type families] (CoAxiom Unbranched) -- The coercion axiom. -- A *Representational* coercion, -- of kind T ty1 ty2 ~R R:T a b c -- where T is the family TyCon, -- and R:T is the representation TyCon (ie this one) -- and a,b,c are the tyConTyVars of this TyCon -- -- BUT may be eta-reduced; see TcInstDcls -- Note [Eta reduction for data family axioms] -- Cached fields of the CoAxiom, but adjusted to -- use the tyConTyVars of this TyCon TyCon -- The family TyCon [Type] -- Argument types (mentions the tyConTyVars of this TyCon) -- Match in length the tyConTyVars of the family TyCon -- E.g. data intance T [a] = ... -- gives a representation tycon: -- data R:TList a = ... -- axiom co a :: T [a] ~ R:TList a -- with R:TList's algTcParent = DataFamInstTyCon T [a] co instance Outputable AlgTyConFlav where ppr (VanillaAlgTyCon {}) = text "Vanilla ADT" ppr (UnboxedAlgTyCon {}) = text "Unboxed ADT" ppr (ClassTyCon cls _) = text "Class parent" <+> ppr cls ppr (DataFamInstTyCon _ tc tys) = text "Family parent (family instance)" <+> ppr tc <+> sep (map ppr tys) -- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class -- name, if any okParent :: Name -> AlgTyConFlav -> Bool okParent _ (VanillaAlgTyCon {}) = True okParent _ (UnboxedAlgTyCon) = True okParent tc_name (ClassTyCon cls _) = tc_name == tyConName (classTyCon cls) okParent _ (DataFamInstTyCon _ fam_tc tys) = tyConArity fam_tc == length tys isNoParent :: AlgTyConFlav -> Bool isNoParent (VanillaAlgTyCon {}) = True isNoParent _ = False -------------------- data Injectivity = NotInjective | Injective [Bool] -- Length is 1-1 with tyConTyVars (incl kind vars) deriving( Eq ) -- | Information pertaining to the expansion of a type synonym (@type@) data FamTyConFlav = -- | Represents an open type family without a fixed right hand -- side. Additional instances can appear at any time. -- -- These are introduced by either a top level declaration: -- -- > data T a :: * -- -- Or an associated data type declaration, within a class declaration: -- -- > class C a b where -- > data T b :: * DataFamilyTyCon TyConRepName -- | An open type synonym family e.g. @type family F x y :: * -> *@ | OpenSynFamilyTyCon -- | A closed type synonym family e.g. -- @type family F x where { F Int = Bool }@ | ClosedSynFamilyTyCon (Maybe (CoAxiom Branched)) -- See Note [Closed type families] -- | A closed type synonym family declared in an hs-boot file with -- type family F a where .. | AbstractClosedSynFamilyTyCon -- | Built-in type family used by the TypeNats solver | BuiltInSynFamTyCon BuiltInSynFamily {- Note [Closed type families] ~~~~~~~~~~~~~~~~~~~~~~~~~ * In an open type family you can add new instances later. This is the usual case. * In a closed type family you can only put equations where the family is defined. A non-empty closed type family has a single axiom with multiple branches, stored in the 'ClosedSynFamilyTyCon' constructor. A closed type family with no equations does not have an axiom, because there is nothing for the axiom to prove! Note [Promoted data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A data constructor can be promoted to become a type constructor, via the PromotedTyCon alternative in TyCon. * Only data constructors with (a) no kind polymorphism (b) no constraints in its type (eg GADTs) are promoted. Existentials are ok; see Trac #7347. * The TyCon promoted from a DataCon has the *same* Name and Unique as the DataCon. Eg. If the data constructor Data.Maybe.Just(unique 78, say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78) * The *kind* of a promoted DataCon may be polymorphic. Example: type of DataCon Just :: forall (a:*). a -> Maybe a kind of (promoted) tycon Just :: forall (a:box). a -> Maybe a The kind is not identical to the type, because of the */box kind signature on the forall'd variable; so the tyConKind field of PromotedTyCon is not identical to the dataConUserType of the DataCon. But it's the same modulo changing the variable kinds, done by DataCon.promoteType. * Small note: We promote the *user* type of the DataCon. Eg data T = MkT {-# UNPACK #-} !(Bool, Bool) The promoted kind is MkT :: (Bool,Bool) -> T *not* MkT :: Bool -> Bool -> T Note [Enumeration types] ~~~~~~~~~~~~~~~~~~~~~~~~ We define datatypes with no constructors to *not* be enumerations; this fixes trac #2578, Otherwise we end up generating an empty table for <mod>_<type>_closure_tbl which is used by tagToEnum# to map Int# to constructors in an enumeration. The empty table apparently upset the linker. Moreover, all the data constructor must be enumerations, meaning they have type (forall abc. T a b c). GADTs are not enumerations. For example consider data T a where T1 :: T Int T2 :: T Bool T3 :: T a What would [T1 ..] be? [T1,T3] :: T Int? Easiest thing is to exclude them. See Trac #4528. Note [Newtype coercions] ~~~~~~~~~~~~~~~~~~~~~~~~ The NewTyCon field nt_co is a CoAxiom which is used for coercing from the representation type of the newtype, to the newtype itself. For example, newtype T a = MkT (a -> a) the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t -> t. In the case that the right hand side is a type application ending with the same type variables as the left hand side, we "eta-contract" the coercion. So if we had newtype S a = MkT [a] then we would generate the arity 0 axiom CoS : S ~ []. The primary reason we do this is to make newtype deriving cleaner. In the paper we'd write axiom CoT : (forall t. T t) ~ (forall t. [t]) and then when we used CoT at a particular type, s, we'd say CoT @ s which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s]) Note [Newtype eta] ~~~~~~~~~~~~~~~~~~ Consider newtype Parser a = MkParser (IO a) deriving Monad Are these two types equal (to Core)? Monad Parser Monad IO which we need to make the derived instance for Monad Parser. Well, yes. But to see that easily we eta-reduce the RHS type of Parser, in this case to ([], Froogle), so that even unsaturated applications of Parser will work right. This eta reduction is done when the type constructor is built, and cached in NewTyCon. Here's an example that I think showed up in practice Source code: newtype T a = MkT [a] newtype Foo m = MkFoo (forall a. m a -> Int) w1 :: Foo [] w1 = ... w2 :: Foo T w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x) After desugaring, and discarding the data constructors for the newtypes, we get: w2 = w1 `cast` Foo CoT so the coercion tycon CoT must have kind: T ~ [] and arity: 0 ************************************************************************ * * TyConRepName * * ********************************************************************* -} type TyConRepName = Name -- The Name of the top-level declaration -- $tcMaybe :: Data.Typeable.Internal.TyCon -- $tcMaybe = TyCon { tyConName = "Maybe", ... } tyConRepName_maybe :: TyCon -> Maybe TyConRepName tyConRepName_maybe (FunTyCon { tcRepName = rep_nm }) = Just rep_nm tyConRepName_maybe (PrimTyCon { primRepName = mb_rep_nm }) = mb_rep_nm tyConRepName_maybe (AlgTyCon { algTcParent = parent }) | VanillaAlgTyCon rep_nm <- parent = Just rep_nm | ClassTyCon _ rep_nm <- parent = Just rep_nm tyConRepName_maybe (FamilyTyCon { famTcFlav = DataFamilyTyCon rep_nm }) = Just rep_nm tyConRepName_maybe (PromotedDataCon { tcRepName = rep_nm }) = Just rep_nm tyConRepName_maybe (PromotedTyCon { tcRepName = rep_nm }) = Just rep_nm tyConRepName_maybe _ = Nothing {- ********************************************************************* * * PrimRep * * ************************************************************************ Note [rep swamp] GHC has a rich selection of types that represent "primitive types" of one kind or another. Each of them makes a different set of distinctions, and mostly the differences are for good reasons, although it's probably true that we could merge some of these. Roughly in order of "includes more information": - A Width (cmm/CmmType) is simply a binary value with the specified number of bits. It may represent a signed or unsigned integer, a floating-point value, or an address. data Width = W8 | W16 | W32 | W64 | W80 | W128 - Size, which is used in the native code generator, is Width + floating point information. data Size = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80 it is necessary because e.g. the instruction to move a 64-bit float on x86 (movsd) is different from the instruction to move a 64-bit integer (movq), so the mov instruction is parameterised by Size. - CmmType wraps Width with more information: GC ptr, float, or other value. data CmmType = CmmType CmmCat Width data CmmCat -- "Category" (not exported) = GcPtrCat -- GC pointer | BitsCat -- Non-pointer | FloatCat -- Float It is important to have GcPtr information in Cmm, since we generate info tables containing pointerhood for the GC from this. As for why we have float (and not signed/unsigned) here, see Note [Signed vs unsigned]. - ArgRep makes only the distinctions necessary for the call and return conventions of the STG machine. It is essentially CmmType + void. - PrimRep makes a few more distinctions than ArgRep: it divides non-GC-pointers into signed/unsigned and addresses, information that is necessary for passing these values to foreign functions. There's another tension here: whether the type encodes its size in bytes, or whether its size depends on the machine word size. Width and CmmType have the size built-in, whereas ArgRep and PrimRep do not. This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags. On the other hand, CmmType includes some "nonsense" values, such as CmmType GcPtrCat W32 on a 64-bit machine. -} -- | A 'PrimRep' is an abstraction of a type. It contains information that -- the code generator needs in order to pass arguments, return results, -- and store values of this type. data PrimRep = VoidRep | PtrRep | IntRep -- ^ Signed, word-sized value | WordRep -- ^ Unsigned, word-sized value | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only) | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only) | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep') | FloatRep | DoubleRep | VecRep Int PrimElemRep -- ^ A vector deriving( Eq, Show ) data PrimElemRep = Int8ElemRep | Int16ElemRep | Int32ElemRep | Int64ElemRep | Word8ElemRep | Word16ElemRep | Word32ElemRep | Word64ElemRep | FloatElemRep | DoubleElemRep deriving( Eq, Show ) instance Outputable PrimRep where ppr r = text (show r) instance Outputable PrimElemRep where ppr r = text (show r) isVoidRep :: PrimRep -> Bool isVoidRep VoidRep = True isVoidRep _other = False isGcPtrRep :: PrimRep -> Bool isGcPtrRep PtrRep = True isGcPtrRep _ = False -- | Find the size of a 'PrimRep', in words primRepSizeW :: DynFlags -> PrimRep -> Int primRepSizeW _ IntRep = 1 primRepSizeW _ WordRep = 1 primRepSizeW dflags Int64Rep = wORD64_SIZE `quot` wORD_SIZE dflags primRepSizeW dflags Word64Rep = wORD64_SIZE `quot` wORD_SIZE dflags primRepSizeW _ FloatRep = 1 -- NB. might not take a full word primRepSizeW dflags DoubleRep = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags primRepSizeW _ AddrRep = 1 primRepSizeW _ PtrRep = 1 primRepSizeW _ VoidRep = 0 primRepSizeW dflags (VecRep len rep) = len * primElemRepSizeB rep `quot` wORD_SIZE dflags primElemRepSizeB :: PrimElemRep -> Int primElemRepSizeB Int8ElemRep = 1 primElemRepSizeB Int16ElemRep = 2 primElemRepSizeB Int32ElemRep = 4 primElemRepSizeB Int64ElemRep = 8 primElemRepSizeB Word8ElemRep = 1 primElemRepSizeB Word16ElemRep = 2 primElemRepSizeB Word32ElemRep = 4 primElemRepSizeB Word64ElemRep = 8 primElemRepSizeB FloatElemRep = 4 primElemRepSizeB DoubleElemRep = 8 -- | Return if Rep stands for floating type, -- returns Nothing for vector types. primRepIsFloat :: PrimRep -> Maybe Bool primRepIsFloat FloatRep = Just True primRepIsFloat DoubleRep = Just True primRepIsFloat (VecRep _ _) = Nothing primRepIsFloat _ = Just False {- ************************************************************************ * * Field labels * * ************************************************************************ -} -- | The labels for the fields of this particular 'TyCon' tyConFieldLabels :: TyCon -> [FieldLabel] tyConFieldLabels tc = fsEnvElts $ tyConFieldLabelEnv tc -- | The labels for the fields of this particular 'TyCon' tyConFieldLabelEnv :: TyCon -> FieldLabelEnv tyConFieldLabelEnv tc | isAlgTyCon tc = algTcFields tc | otherwise = emptyFsEnv -- | Make a map from strings to FieldLabels from all the data -- constructors of this algebraic tycon fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv fieldsOfAlgTcRhs rhs = mkFsEnv [ (flLabel fl, fl) | fl <- dataConsFields (visibleDataCons rhs) ] where -- Duplicates in this list will be removed by 'mkFsEnv' dataConsFields dcs = concatMap dataConFieldLabels dcs {- ************************************************************************ * * \subsection{TyCon Construction} * * ************************************************************************ Note: the TyCon constructors all take a Kind as one argument, even though they could, in principle, work out their Kind from their other arguments. But to do so they need functions from Types, and that makes a nasty module mutual-recursion. And they aren't called from many places. So we compromise, and move their Kind calculation to the call site. -} -- | Given the name of the function type constructor and it's kind, create the -- corresponding 'TyCon'. It is reccomended to use 'TypeRep.funTyCon' if you want -- this functionality mkFunTyCon :: Name -> Kind -> Name -> TyCon mkFunTyCon name kind rep_nm = FunTyCon { tyConUnique = nameUnique name, tyConName = name, tyConKind = kind, tyConArity = 2, tcRepName = rep_nm } -- | This is the making of an algebraic 'TyCon'. Notably, you have to -- pass in the generic (in the -XGenerics sense) information about the -- type constructor - you can get hold of it easily (see Generics -- module) mkAlgTyCon :: Name -> Kind -- ^ Kind of the resulting 'TyCon' -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'. -- Arity is inferred from the length of this -- list -> [Role] -- ^ The roles for each TyVar -> Maybe CType -- ^ The C type this type corresponds to -- when using the CAPI FFI -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta' -> AlgTyConRhs -- ^ Information about data constructors -> AlgTyConFlav -- ^ What flavour is it? -- (e.g. vanilla, type family) -> RecFlag -- ^ Is the 'TyCon' recursive? -> Bool -- ^ Was the 'TyCon' declared with GADT syntax? -> Promoted TyCon -- ^ Promoted version -> TyCon mkAlgTyCon name kind tyvars roles cType stupid rhs parent is_rec gadt_syn prom_tc = AlgTyCon { tyConName = name, tyConUnique = nameUnique name, tyConKind = kind, tyConArity = length tyvars, tyConTyVars = tyvars, tcRoles = roles, tyConCType = cType, algTcStupidTheta = stupid, algTcRhs = rhs, algTcFields = fieldsOfAlgTcRhs rhs, algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent, algTcRec = is_rec, algTcGadtSyntax = gadt_syn, tcPromoted = prom_tc } -- | Simpler specialization of 'mkAlgTyCon' for classes mkClassTyCon :: Name -> Kind -> [TyVar] -> [Role] -> AlgTyConRhs -> Class -> RecFlag -> Name -> TyCon mkClassTyCon name kind tyvars roles rhs clas is_rec tc_rep_name = mkAlgTyCon name kind tyvars roles Nothing [] rhs (ClassTyCon clas tc_rep_name) is_rec False NotPromoted -- Class TyCons are not promoted mkTupleTyCon :: Name -> Kind -- ^ Kind of the resulting 'TyCon' -> Arity -- ^ Arity of the tuple -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars' -> DataCon -> TupleSort -- ^ Whether the tuple is boxed or unboxed -> Promoted TyCon -- ^ Promoted version -> AlgTyConFlav -> TyCon mkTupleTyCon name kind arity tyvars con sort prom_tc parent = AlgTyCon { tyConName = name, tyConUnique = nameUnique name, tyConKind = kind, tyConArity = arity, tyConTyVars = tyvars, tcRoles = replicate arity Representational, tyConCType = Nothing, algTcStupidTheta = [], algTcRhs = TupleTyCon { data_con = con, tup_sort = sort }, algTcFields = emptyFsEnv, algTcParent = parent, algTcRec = NonRecursive, algTcGadtSyntax = False, tcPromoted = prom_tc } -- | Create an unlifted primitive 'TyCon', such as @Int#@ mkPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon mkPrimTyCon name kind roles rep = mkPrimTyCon' name kind roles rep True Nothing -- | Kind constructors mkKindTyCon :: Name -> Kind -> Name -> TyCon mkKindTyCon name kind rep_nm = mkPrimTyCon' name kind [] VoidRep True (Just rep_nm) -- | Create a lifted primitive 'TyCon' such as @RealWorld@ mkLiftedPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon mkLiftedPrimTyCon name kind roles rep = mkPrimTyCon' name kind roles rep False Nothing mkPrimTyCon' :: Name -> Kind -> [Role] -> PrimRep -> Bool -> Maybe TyConRepName -> TyCon mkPrimTyCon' name kind roles rep is_unlifted rep_nm = PrimTyCon { tyConName = name, tyConUnique = nameUnique name, tyConKind = kind, tyConArity = length roles, tcRoles = roles, primTyConRep = rep, isUnLifted = is_unlifted, primRepName = rep_nm } -- | Create a type synonym 'TyCon' mkSynonymTyCon :: Name -> Kind -> [TyVar] -> [Role] -> Type -> TyCon mkSynonymTyCon name kind tyvars roles rhs = SynonymTyCon { tyConName = name, tyConUnique = nameUnique name, tyConKind = kind, tyConArity = length tyvars, tyConTyVars = tyvars, tcRoles = roles, synTcRhs = rhs } -- | Create a type family 'TyCon' mkFamilyTyCon:: Name -> Kind -> [TyVar] -> Maybe Name -> FamTyConFlav -> Maybe Class -> Injectivity -> TyCon mkFamilyTyCon name kind tyvars resVar flav parent inj = FamilyTyCon { tyConUnique = nameUnique name , tyConName = name , tyConKind = kind , tyConArity = length tyvars , tyConTyVars = tyvars , famTcResVar = resVar , famTcFlav = flav , famTcParent = parent , famTcInj = inj } -- | Create a promoted data constructor 'TyCon' -- Somewhat dodgily, we give it the same Name -- as the data constructor itself; when we pretty-print -- the TyCon we add a quote; see the Outputable TyCon instance mkPromotedDataCon :: DataCon -> Name -> TyConRepName -> Kind -> [Role] -> TyCon mkPromotedDataCon con name rep_name kind roles = PromotedDataCon { tyConUnique = nameUnique name, tyConName = name, tyConArity = arity, tcRoles = roles, tyConKind = kind, dataCon = con, tcRepName = rep_name } where arity = length roles -- | Create a promoted type constructor 'TyCon' -- Somewhat dodgily, we give it the same Name -- as the type constructor itself mkPromotedTyCon :: TyCon -> Kind -> TyCon mkPromotedTyCon tc kind = PromotedTyCon { tyConName = getName tc, tyConUnique = getUnique tc, tyConArity = tyConArity tc, tyConKind = kind, ty_con = tc, tcRepName = case tyConRepName_maybe tc of Just rep_nm -> rep_nm Nothing -> pprPanic "mkPromotedTyCon" (ppr tc) -- Promoted TyCons always have a TyConRepName } isFunTyCon :: TyCon -> Bool isFunTyCon (FunTyCon {}) = True isFunTyCon _ = False -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors) isAbstractTyCon :: TyCon -> Bool isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True isAbstractTyCon _ = False -- | Make an algebraic 'TyCon' abstract. Panics if the supplied 'TyCon' is not -- algebraic makeTyConAbstract :: TyCon -> TyCon makeTyConAbstract tc@(AlgTyCon { algTcRhs = rhs }) = tc { algTcRhs = AbstractTyCon (isGenInjAlgRhs rhs) } makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc) -- | Does this 'TyCon' represent something that cannot be defined in Haskell? isPrimTyCon :: TyCon -> Bool isPrimTyCon (PrimTyCon {}) = True isPrimTyCon _ = False -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can -- only be true for primitive and unboxed-tuple 'TyCon's isUnLiftedTyCon :: TyCon -> Bool isUnLiftedTyCon (PrimTyCon {isUnLifted = is_unlifted}) = is_unlifted isUnLiftedTyCon (AlgTyCon { algTcRhs = rhs } ) | TupleTyCon { tup_sort = sort } <- rhs = not (isBoxed (tupleSortBoxity sort)) isUnLiftedTyCon _ = False -- | Returns @True@ if the supplied 'TyCon' resulted from either a -- @data@ or @newtype@ declaration isAlgTyCon :: TyCon -> Bool isAlgTyCon (AlgTyCon {}) = True isAlgTyCon _ = False isDataTyCon :: TyCon -> Bool -- ^ Returns @True@ for data types that are /definitely/ represented by -- heap-allocated constructors. These are scrutinised by Core-level -- @case@ expressions, and they get info tables allocated for them. -- -- Generally, the function will be true for all @data@ types and false -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is -- not guaranteed to return @True@ in all cases that it could. -- -- NB: for a data type family, only the /instance/ 'TyCon's -- get an info table. The family declaration 'TyCon' does not isDataTyCon (AlgTyCon {algTcRhs = rhs}) = case rhs of TupleTyCon { tup_sort = sort } -> isBoxed (tupleSortBoxity sort) DataTyCon {} -> True NewTyCon {} -> False AbstractTyCon {} -> False -- We don't know, so return False isDataTyCon _ = False -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds -- (where X is the role passed in): -- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2) -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X) -- See also Note [Decomposing equalities] in TcCanonical isInjectiveTyCon :: TyCon -> Role -> Bool isInjectiveTyCon _ Phantom = False isInjectiveTyCon (FunTyCon {}) _ = True isInjectiveTyCon (AlgTyCon {}) Nominal = True isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational = isGenInjAlgRhs rhs isInjectiveTyCon (SynonymTyCon {}) _ = False isInjectiveTyCon (FamilyTyCon {famTcFlav = flav}) Nominal = isDataFamFlav flav isInjectiveTyCon (FamilyTyCon {}) Representational = False isInjectiveTyCon (PrimTyCon {}) _ = True isInjectiveTyCon (PromotedDataCon {}) _ = True isInjectiveTyCon (PromotedTyCon {ty_con = tc}) r = isInjectiveTyCon tc r -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds -- (where X is the role passed in): -- If (T tys ~X t), then (t's head ~X T). -- See also Note [Decomposing equalities] in TcCanonical isGenerativeTyCon :: TyCon -> Role -> Bool isGenerativeTyCon = isInjectiveTyCon -- as it happens, generativity and injectivity coincide, but there's -- no a priori reason this must be the case -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective -- with respect to representational equality? isGenInjAlgRhs :: AlgTyConRhs -> Bool isGenInjAlgRhs (TupleTyCon {}) = True isGenInjAlgRhs (DataTyCon {}) = True isGenInjAlgRhs (AbstractTyCon distinct) = distinct isGenInjAlgRhs (NewTyCon {}) = False -- | Is this 'TyCon' that for a @newtype@ isNewTyCon :: TyCon -> Bool isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True isNewTyCon _ = False -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands -- into, and (possibly) a coercion from the representation type to the @newtype@. -- Returns @Nothing@ if this is not possible. unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched) unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, algTcRhs = NewTyCon { nt_co = co, nt_rhs = rhs }}) = Just (tvs, rhs, co) unwrapNewTyCon_maybe _ = Nothing unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched) unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co, nt_etad_rhs = (tvs,rhs) }}) = Just (tvs, rhs, co) unwrapNewTyConEtad_maybe _ = Nothing isProductTyCon :: TyCon -> Bool -- True of datatypes or newtypes that have -- one, non-existential, data constructor -- See Note [Product types] isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of TupleTyCon {} -> True DataTyCon{ data_cons = [data_con] } -> null (dataConExTyVars data_con) NewTyCon {} -> True _ -> False isProductTyCon _ = False isDataProductTyCon_maybe :: TyCon -> Maybe DataCon -- True of datatypes (not newtypes) with -- one, vanilla, data constructor -- See Note [Product types] isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = [con] } | null (dataConExTyVars con) -- non-existential -> Just con TupleTyCon { data_con = con } -> Just con _ -> Nothing isDataProductTyCon_maybe _ = Nothing {- Note [Product types] ~~~~~~~~~~~~~~~~~~~~~~~ A product type is * A data type (not a newtype) * With one, boxed data constructor * That binds no existential type variables The main point is that product types are amenable to unboxing for * Strict function calls; we can transform f (D a b) = e to fw a b = e via the worker/wrapper transformation. (Question: couldn't this work for existentials too?) * CPR for function results; we can transform f x y = let ... in D a b to fw x y = let ... in (# a, b #) Note that the data constructor /can/ have evidence arguments: equality constraints, type classes etc. So it can be GADT. These evidence arguments are simply value arguments, and should not get in the way. -} -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)? isTypeSynonymTyCon :: TyCon -> Bool isTypeSynonymTyCon (SynonymTyCon {}) = True isTypeSynonymTyCon _ = False -- As for newtypes, it is in some contexts important to distinguish between -- closed synonyms and synonym families, as synonym families have no unique -- right hand side to which a synonym family application can expand. -- -- | True iff we can decompose (T a b c) into ((T a b) c) -- I.e. is it injective and generative w.r.t nominal equality? -- That is, if (T a b) ~N d e f, is it always the case that -- (T ~N d), (a ~N e) and (b ~N f)? -- Specifically NOT true of synonyms (open and otherwise) -- -- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98 -- type synonym, because you should probably have expanded it first -- But regardless, it's not decomposable mightBeUnsaturatedTyCon :: TyCon -> Bool mightBeUnsaturatedTyCon (SynonymTyCon {}) = False mightBeUnsaturatedTyCon (FamilyTyCon { famTcFlav = flav}) = isDataFamFlav flav mightBeUnsaturatedTyCon _other = True -- | Is this an algebraic 'TyCon' declared with the GADT syntax? isGadtSyntaxTyCon :: TyCon -> Bool isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res isGadtSyntaxTyCon _ = False -- | Is this an algebraic 'TyCon' which is just an enumeration of values? isEnumerationTyCon :: TyCon -> Bool -- See Note [Enumeration types] in TyCon isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs }) = case rhs of DataTyCon { is_enum = res } -> res TupleTyCon {} -> arity == 0 _ -> False isEnumerationTyCon _ = False -- | Is this a 'TyCon', synonym or otherwise, that defines a family? isFamilyTyCon :: TyCon -> Bool isFamilyTyCon (FamilyTyCon {}) = True isFamilyTyCon _ = False -- | Is this a 'TyCon', synonym or otherwise, that defines a family with -- instances? isOpenFamilyTyCon :: TyCon -> Bool isOpenFamilyTyCon (FamilyTyCon {famTcFlav = flav }) | OpenSynFamilyTyCon <- flav = True | DataFamilyTyCon {} <- flav = True isOpenFamilyTyCon _ = False -- | Is this a synonym 'TyCon' that can have may have further instances appear? isTypeFamilyTyCon :: TyCon -> Bool isTypeFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = not (isDataFamFlav flav) isTypeFamilyTyCon _ = False -- | Is this a synonym 'TyCon' that can have may have further instances appear? isDataFamilyTyCon :: TyCon -> Bool isDataFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav isDataFamilyTyCon _ = False -- | Is this an open type family TyCon? isOpenTypeFamilyTyCon :: TyCon -> Bool isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True isOpenTypeFamilyTyCon _ = False -- | Is this a non-empty closed type family? Returns 'Nothing' for -- abstract or empty closed families. isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched) isClosedSynFamilyTyConWithAxiom_maybe (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing -- | Try to read the injectivity information from a FamilyTyCon. Only -- FamilyTyCons can be injective so for every other TyCon this function panics. familyTyConInjectivityInfo :: TyCon -> Injectivity familyTyConInjectivityInfo (FamilyTyCon { famTcInj = inj }) = inj familyTyConInjectivityInfo _ = panic "familyTyConInjectivityInfo" isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily isBuiltInSynFamTyCon_maybe (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops isBuiltInSynFamTyCon_maybe _ = Nothing isDataFamFlav :: FamTyConFlav -> Bool isDataFamFlav (DataFamilyTyCon {}) = True -- Data family isDataFamFlav _ = False -- Type synonym family -- | Are we able to extract information 'TyVar' to class argument list -- mapping from a given 'TyCon'? isTyConAssoc :: TyCon -> Bool isTyConAssoc tc = isJust (tyConAssoc_maybe tc) tyConAssoc_maybe :: TyCon -> Maybe Class tyConAssoc_maybe (FamilyTyCon { famTcParent = mb_cls }) = mb_cls tyConAssoc_maybe _ = Nothing -- The unit tycon didn't used to be classed as a tuple tycon -- but I thought that was silly so I've undone it -- If it can't be for some reason, it should be a AlgTyCon isTupleTyCon :: TyCon -> Bool -- ^ Does this 'TyCon' represent a tuple? -- -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they -- get spat into the interface file as tuple tycons, so I don't think -- it matters. isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True isTupleTyCon _ = False tyConTuple_maybe :: TyCon -> Maybe TupleSort tyConTuple_maybe (AlgTyCon { algTcRhs = rhs }) | TupleTyCon { tup_sort = sort} <- rhs = Just sort tyConTuple_maybe _ = Nothing -- | Is this the 'TyCon' for an unboxed tuple? isUnboxedTupleTyCon :: TyCon -> Bool isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs }) | TupleTyCon { tup_sort = sort } <- rhs = not (isBoxed (tupleSortBoxity sort)) isUnboxedTupleTyCon _ = False -- | Is this the 'TyCon' for a boxed tuple? isBoxedTupleTyCon :: TyCon -> Bool isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs }) | TupleTyCon { tup_sort = sort } <- rhs = isBoxed (tupleSortBoxity sort) isBoxedTupleTyCon _ = False -- | Is this a recursive 'TyCon'? isRecursiveTyCon :: TyCon -> Bool isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True isRecursiveTyCon _ = False promotableTyCon_maybe :: TyCon -> Promoted TyCon promotableTyCon_maybe (AlgTyCon { tcPromoted = prom }) = prom promotableTyCon_maybe _ = NotPromoted isPromotableTyCon :: TyCon -> Bool isPromotableTyCon tc = case promotableTyCon_maybe tc of Promoted {} -> True NotPromoted -> False promoteTyCon :: TyCon -> TyCon promoteTyCon tc = case promotableTyCon_maybe tc of Promoted prom_tc -> prom_tc NotPromoted -> pprPanic "promoteTyCon" (ppr tc) -- | Is this a PromotedTyCon? isPromotedTyCon :: TyCon -> Bool isPromotedTyCon (PromotedTyCon {}) = True isPromotedTyCon _ = False -- | Retrieves the promoted TyCon if this is a PromotedTyCon; isPromotedTyCon_maybe :: TyCon -> Maybe TyCon isPromotedTyCon_maybe (PromotedTyCon { ty_con = tc }) = Just tc isPromotedTyCon_maybe _ = Nothing -- | Is this a PromotedDataCon? isPromotedDataCon :: TyCon -> Bool isPromotedDataCon (PromotedDataCon {}) = True isPromotedDataCon _ = False -- | Retrieves the promoted DataCon if this is a PromotedDataCon; isPromotedDataCon_maybe :: TyCon -> Maybe DataCon isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc isPromotedDataCon_maybe _ = Nothing -- | Identifies implicit tycons that, in particular, do not go into interface -- files (because they are implicitly reconstructed when the interface is -- read). -- -- Note that: -- -- * Associated families are implicit, as they are re-constructed from -- the class declaration in which they reside, and -- -- * Family instances are /not/ implicit as they represent the instance body -- (similar to a @dfun@ does that for a class instance). -- -- * Tuples are implicit iff they have a wired-in name -- (namely: boxed and unboxed tupeles are wired-in and implicit, -- but constraint tuples are not) isImplicitTyCon :: TyCon -> Bool isImplicitTyCon (FunTyCon {}) = True isImplicitTyCon (PrimTyCon {}) = True isImplicitTyCon (PromotedDataCon {}) = True isImplicitTyCon (PromotedTyCon {}) = True isImplicitTyCon (AlgTyCon { algTcRhs = rhs, tyConName = name }) | TupleTyCon {} <- rhs = isWiredInName name | otherwise = False isImplicitTyCon (FamilyTyCon { famTcParent = parent }) = isJust parent isImplicitTyCon (SynonymTyCon {}) = False tyConCType_maybe :: TyCon -> Maybe CType tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc tyConCType_maybe _ = Nothing {- ----------------------------------------------- -- Expand type-constructor applications ----------------------------------------------- -} expandSynTyCon_maybe :: TyCon -> [tyco] -- ^ Arguments to 'TyCon' -> Maybe ([(TyVar,tyco)], Type, [tyco]) -- ^ Returns a 'TyVar' substitution, the body -- type of the synonym (not yet substituted) -- and any arguments remaining from the -- application -- ^ Expand a type synonym application, if any expandSynTyCon_maybe tc tys | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs } <- tc , let n_tvs = length tvs = case n_tvs `compare` length tys of LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys) EQ -> Just (tvs `zip` tys, rhs, []) GT -> Nothing | otherwise = Nothing ---------------- -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no -- constructors could be found tyConDataCons :: TyCon -> [DataCon] -- It's convenient for tyConDataCons to return the -- empty list for type synonyms etc tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` [] -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon' -- is the sort that can have any constructors (note: this does not include -- abstract algebraic types) tyConDataCons_maybe :: TyCon -> Maybe [DataCon] tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs}) = case rhs of DataTyCon { data_cons = cons } -> Just cons NewTyCon { data_con = con } -> Just [con] TupleTyCon { data_con = con } -> Just [con] _ -> Nothing tyConDataCons_maybe _ = Nothing -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@ -- type with one alternative, a tuple type or a @newtype@ then that constructor -- is returned. If the 'TyCon' has more than one constructor, or represents a -- primitive or function type constructor then @Nothing@ is returned. In any -- other case, the function panics tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = [c] } -> Just c TupleTyCon { data_con = c } -> Just c NewTyCon { data_con = c } -> Just c _ -> Nothing tyConSingleDataCon_maybe _ = Nothing tyConSingleDataCon :: TyCon -> DataCon tyConSingleDataCon tc = case tyConSingleDataCon_maybe tc of Just c -> c Nothing -> pprPanic "tyConDataCon" (ppr tc) tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon -- Returns (Just con) for single-constructor -- *algebraic* data types *not* newtypes tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = [c] } -> Just c TupleTyCon { data_con = c } -> Just c _ -> Nothing tyConSingleAlgDataCon_maybe _ = Nothing -- | Determine the number of value constructors a 'TyCon' has. Panics if the -- 'TyCon' is not algebraic or a tuple tyConFamilySize :: TyCon -> Int tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = cons } -> length cons NewTyCon {} -> 1 TupleTyCon {} -> 1 _ -> pprPanic "tyConFamilySize 1" (ppr tc) tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc) -- | Extract an 'AlgTyConRhs' with information about data constructors from an -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon' algTyConRhs :: TyCon -> AlgTyConRhs algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs algTyConRhs other = pprPanic "algTyConRhs" (ppr other) -- | Extract type variable naming the result of injective type family tyConFamilyResVar_maybe :: TyCon -> Maybe Name tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res tyConFamilyResVar_maybe _ = Nothing -- | Get the list of roles for the type parameters of a TyCon tyConRoles :: TyCon -> [Role] -- See also Note [TyCon Role signatures] tyConRoles tc = case tc of { FunTyCon {} -> const_role Representational ; AlgTyCon { tcRoles = roles } -> roles ; SynonymTyCon { tcRoles = roles } -> roles ; FamilyTyCon {} -> const_role Nominal ; PrimTyCon { tcRoles = roles } -> roles ; PromotedDataCon { tcRoles = roles } -> roles ; PromotedTyCon {} -> const_role Nominal } where const_role r = replicate (tyConArity tc) r -- | Extract the bound type variables and type expansion of a type synonym -- 'TyCon'. Panics if the 'TyCon' is not a synonym newTyConRhs :: TyCon -> ([TyVar], Type) newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs) newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon) -- | The number of type parameters that need to be passed to a newtype to -- resolve it. May be less than in the definition if it can be eta-contracted. newTyConEtadArity :: TyCon -> Int newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = length (fst tvs_rhs) newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon) -- | Extract the bound type variables and type expansion of an eta-contracted -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym newTyConEtadRhs :: TyCon -> ([TyVar], Type) newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon) -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to -- construct something with the @newtype@s type from its representation type -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns -- @Nothing@ newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched) newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co newTyConCo_maybe _ = Nothing newTyConCo :: TyCon -> CoAxiom Unbranched newTyConCo tc = case newTyConCo_maybe tc of Just co -> co Nothing -> pprPanic "newTyConCo" (ppr tc) -- | Find the primitive representation of a 'TyCon' tyConPrimRep :: TyCon -> PrimRep tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration -- @data Eq a => T a ...@ tyConStupidTheta :: TyCon -> [PredType] tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon) -- | Extract the 'TyVar's bound by a vanilla type synonym -- and the corresponding (unsubstituted) right hand side. synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type) synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty}) = Just (tyvars, ty) synTyConDefn_maybe _ = Nothing -- | Extract the information pertaining to the right hand side of a type synonym -- (@type@) declaration. synTyConRhs_maybe :: TyCon -> Maybe Type synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs synTyConRhs_maybe _ = Nothing -- | Extract the flavour of a type family (with all the extra information that -- it carries) famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav famTyConFlav_maybe _ = Nothing -- | Is this 'TyCon' that for a class instance? isClassTyCon :: TyCon -> Bool isClassTyCon (AlgTyCon {algTcParent = ClassTyCon {}}) = True isClassTyCon _ = False -- | If this 'TyCon' is that for a class instance, return the class it is for. -- Otherwise returns @Nothing@ tyConClass_maybe :: TyCon -> Maybe Class tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas _}) = Just clas tyConClass_maybe _ = Nothing ---------------------------------------------------------------------------- -- | Is this 'TyCon' that for a data family instance? isFamInstTyCon :: TyCon -> Bool isFamInstTyCon (AlgTyCon {algTcParent = DataFamInstTyCon {} }) = True isFamInstTyCon _ = False tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched) tyConFamInstSig_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax f ts }) = Just (f, ts, ax) tyConFamInstSig_maybe _ = Nothing -- | If this 'TyCon' is that of a data family instance, return the family in question -- and the instance types. Otherwise, return @Nothing@ tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type]) tyConFamInst_maybe (AlgTyCon {algTcParent = DataFamInstTyCon _ f ts }) = Just (f, ts) tyConFamInst_maybe _ = Nothing -- | If this 'TyCon' is that of a data family instance, return a 'TyCon' which -- represents a coercion identifying the representation type with the type -- instance family. Otherwise, return @Nothing@ tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched) tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax _ _ }) = Just ax tyConFamilyCoercion_maybe _ = Nothing {- ************************************************************************ * * \subsection[TyCon-instances]{Instance declarations for @TyCon@} * * ************************************************************************ @TyCon@s are compared by comparing their @Unique@s. The strictness analyser needs @Ord@. It is a lexicographic order with the property @(a<=b) || (b<=a)@. -} instance Eq TyCon where a == b = case (a `compare` b) of { EQ -> True; _ -> False } a /= b = case (a `compare` b) of { EQ -> False; _ -> True } instance Ord TyCon where a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False } a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False } a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True } a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True } compare a b = getUnique a `compare` getUnique b instance Uniquable TyCon where getUnique tc = tyConUnique tc instance Outputable TyCon where -- At the moment a promoted TyCon has the same Name as its -- corresponding TyCon, so we add the quote to distinguish it here ppr tc = pprPromotionQuote tc <> ppr (tyConName tc) tyConFlavour :: TyCon -> String tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs }) | ClassTyCon _ _ <- parent = "class" | otherwise = case rhs of TupleTyCon { tup_sort = sort } | isBoxed (tupleSortBoxity sort) -> "tuple" | otherwise -> "unboxed tuple" DataTyCon {} -> "data type" NewTyCon {} -> "newtype" AbstractTyCon {} -> "abstract type" tyConFlavour (FamilyTyCon { famTcFlav = flav }) | isDataFamFlav flav = "data family" | otherwise = "type family" tyConFlavour (SynonymTyCon {}) = "type synonym" tyConFlavour (FunTyCon {}) = "built-in type" tyConFlavour (PrimTyCon {}) = "built-in type" tyConFlavour (PromotedDataCon {}) = "promoted data constructor" tyConFlavour (PromotedTyCon {}) = "promoted type constructor" pprPromotionQuote :: TyCon -> SDoc -- Promoted data constructors already have a tick in their OccName pprPromotionQuote tc = case tc of PromotedDataCon {} -> char '\'' -- Always quote promoted DataCons in types PromotedTyCon {} -> ifPprDebug (char '\'') -- However, we don't quote TyCons in kinds, except with -dppr-debug -- e.g. type family T a :: Bool -> * -- cf Trac #5952. _ -> empty instance NamedThing TyCon where getName = tyConName instance Data.Data TyCon where -- don't traverse? toConstr _ = abstractConstr "TyCon" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "TyCon" instance Binary Injectivity where put_ bh NotInjective = putByte bh 0 put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs get bh = do { h <- getByte bh ; case h of 0 -> return NotInjective _ -> do { xs <- get bh ; return (Injective xs) } } {- ************************************************************************ * * Walking over recursive TyCons * * ************************************************************************ Note [Expanding newtypes and products] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When expanding a type to expose a data-type constructor, we need to be careful about newtypes, lest we fall into an infinite loop. Here are the key examples: newtype Id x = MkId x newtype Fix f = MkFix (f (Fix f)) newtype T = MkT (T -> T) Type Expansion -------------------------- T T -> T Fix Maybe Maybe (Fix Maybe) Id (Id Int) Int Fix Id NO NO NO Notice that * We can expand T, even though it's recursive. * We can expand Id (Id Int), even though the Id shows up twice at the outer level, because Id is non-recursive So, when expanding, we keep track of when we've seen a recursive newtype at outermost level; and bale out if we see it again. We sometimes want to do the same for product types, so that the strictness analyser doesn't unbox infinitely deeply. More precisely, we keep a *count* of how many times we've seen it. This is to account for data instance T (a,b) = MkT (T a) (T b) Then (Trac #10482) if we have a type like T (Int,(Int,(Int,(Int,Int)))) we can still unbox deeply enough during strictness analysis. We have to treat T as potentially recursive, but it's still good to be able to unwrap multiple layers. The function that manages all this is checkRecTc. -} data RecTcChecker = RC !Int (NameEnv Int) -- The upper bound, and the number of times -- we have encountered each TyCon initRecTc :: RecTcChecker -- Intialise with a fixed max bound of 100 -- We should probably have a flag for this initRecTc = RC 100 emptyNameEnv checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker -- Nothing => Recursion detected -- Just rec_tcs => Keep going checkRecTc rc@(RC bound rec_nts) tc | not (isRecursiveTyCon tc) = Just rc -- Tuples are a common example here | otherwise = case lookupNameEnv rec_nts tc_name of Just n | n >= bound -> Nothing | otherwise -> Just (RC bound (extendNameEnv rec_nts tc_name (n+1))) Nothing -> Just (RC bound (extendNameEnv rec_nts tc_name 1)) where tc_name = tyConName tc
AlexanderPankiv/ghc
compiler/types/TyCon.hs
bsd-3-clause
80,521
1
17
23,968
9,412
5,341
4,071
822
7
<?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="ru-RU"> <title>Viewstate (просмотр состояния)</title> <maps> <homeID>viewstate</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Содержание</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/viewstate/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
apache-2.0
1,030
82
52
157
482
250
232
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.InstalledPackageInfo -- Copyright : (c) The University of Glasgow 2004 -- -- Maintainer : libraries@haskell.org -- Portability : portable -- -- This is the information about an /installed/ package that -- is communicated to the @ghc-pkg@ program in order to register -- a package. @ghc-pkg@ now consumes this package format (as of version -- 6.4). This is specific to GHC at the moment. -- -- The @.cabal@ file format is for describing a package that is not yet -- installed. It has a lot of flexibility, like conditionals and dependency -- ranges. As such, that format is not at all suitable for describing a package -- that has already been built and installed. By the time we get to that stage, -- we have resolved all conditionals and resolved dependency version -- constraints to exact versions of dependent packages. So, this module defines -- the 'InstalledPackageInfo' data structure that contains all the info we keep -- about an installed package. There is a parser and pretty printer. The -- textual format is rather simpler than the @.cabal@ format: there are no -- sections, for example. -- This module is meant to be local-only to Distribution... module Distribution.InstalledPackageInfo ( InstalledPackageInfo(..), installedPackageId, installedComponentId, installedOpenUnitId, sourceComponentName, requiredSignatures, ExposedModule(..), AbiDependency(..), ParseResult(..), PError(..), PWarning, emptyInstalledPackageInfo, parseInstalledPackageInfo, showInstalledPackageInfo, showInstalledPackageInfoField, showSimpleInstalledPackageInfoField, fieldsInstalledPackageInfo, ) where import Prelude () import Distribution.Compat.Prelude import Distribution.ParseUtils import Distribution.License import Distribution.Package hiding (installedUnitId, installedPackageId) import Distribution.Backpack import qualified Distribution.Package as Package import Distribution.ModuleName import Distribution.Version import Distribution.Text import qualified Distribution.Compat.ReadP as Parse import Distribution.Compat.Graph import Distribution.Types.MungedPackageId import Distribution.Types.ComponentName import Distribution.Types.MungedPackageName import Distribution.Types.UnqualComponentName import Text.PrettyPrint as Disp import qualified Data.Char as Char import qualified Data.Map as Map import Data.Set (Set) -- ----------------------------------------------------------------------------- -- The InstalledPackageInfo type -- For BC reasons, we continue to name this record an InstalledPackageInfo; -- but it would more accurately be called an InstalledUnitInfo with Backpack data InstalledPackageInfo = InstalledPackageInfo { -- these parts are exactly the same as PackageDescription sourcePackageId :: PackageId, installedUnitId :: UnitId, installedComponentId_ :: ComponentId, -- INVARIANT: if this package is definite, OpenModule's -- OpenUnitId directly records UnitId. If it is -- indefinite, OpenModule is always an OpenModuleVar -- with the same ModuleName as the key. instantiatedWith :: [(ModuleName, OpenModule)], sourceLibName :: Maybe UnqualComponentName, compatPackageKey :: String, license :: License, copyright :: String, maintainer :: String, author :: String, stability :: String, homepage :: String, pkgUrl :: String, synopsis :: String, description :: String, category :: String, -- these parts are required by an installed package only: abiHash :: AbiHash, indefinite :: Bool, exposed :: Bool, -- INVARIANT: if the package is definite, OpenModule's -- OpenUnitId directly records UnitId. exposedModules :: [ExposedModule], hiddenModules :: [ModuleName], trusted :: Bool, importDirs :: [FilePath], libraryDirs :: [FilePath], libraryDynDirs :: [FilePath], -- ^ overrides 'libraryDirs' dataDir :: FilePath, hsLibraries :: [String], extraLibraries :: [String], extraGHCiLibraries:: [String], -- overrides extraLibraries for GHCi includeDirs :: [FilePath], includes :: [String], -- INVARIANT: if the package is definite, UnitId is NOT -- a ComponentId of an indefinite package depends :: [UnitId], abiDepends :: [AbiDependency], ccOptions :: [String], ldOptions :: [String], frameworkDirs :: [FilePath], frameworks :: [String], haddockInterfaces :: [FilePath], haddockHTMLs :: [FilePath], pkgRoot :: Maybe FilePath } deriving (Eq, Generic, Typeable, Read, Show) installedComponentId :: InstalledPackageInfo -> ComponentId installedComponentId ipi = case unComponentId (installedComponentId_ ipi) of "" -> mkComponentId (unUnitId (installedUnitId ipi)) _ -> installedComponentId_ ipi -- | Get the indefinite unit identity representing this package. -- This IS NOT guaranteed to give you a substitution; for -- instantiated packages you will get @DefiniteUnitId (installedUnitId ipi)@. -- For indefinite libraries, however, you will correctly get -- an @OpenUnitId@ with the appropriate 'OpenModuleSubst'. installedOpenUnitId :: InstalledPackageInfo -> OpenUnitId installedOpenUnitId ipi = mkOpenUnitId (installedUnitId ipi) (installedComponentId ipi) (Map.fromList (instantiatedWith ipi)) -- | Returns the set of module names which need to be filled for -- an indefinite package, or the empty set if the package is definite. requiredSignatures :: InstalledPackageInfo -> Set ModuleName requiredSignatures ipi = openModuleSubstFreeHoles (Map.fromList (instantiatedWith ipi)) {-# DEPRECATED installedPackageId "Use installedUnitId instead" #-} -- | Backwards compatibility with Cabal pre-1.24. -- -- This type synonym is slightly awful because in cabal-install -- we define an 'InstalledPackageId' but it's a ComponentId, -- not a UnitId! installedPackageId :: InstalledPackageInfo -> UnitId installedPackageId = installedUnitId instance Binary InstalledPackageInfo instance Package.HasMungedPackageId InstalledPackageInfo where mungedId = mungedPackageId instance Package.Package InstalledPackageInfo where packageId = sourcePackageId instance Package.HasUnitId InstalledPackageInfo where installedUnitId = installedUnitId instance Package.PackageInstalled InstalledPackageInfo where installedDepends = depends instance IsNode InstalledPackageInfo where type Key InstalledPackageInfo = UnitId nodeKey = installedUnitId nodeNeighbors = depends emptyInstalledPackageInfo :: InstalledPackageInfo emptyInstalledPackageInfo = InstalledPackageInfo { sourcePackageId = PackageIdentifier (mkPackageName "") nullVersion, installedUnitId = mkUnitId "", installedComponentId_ = mkComponentId "", instantiatedWith = [], sourceLibName = Nothing, compatPackageKey = "", license = UnspecifiedLicense, copyright = "", maintainer = "", author = "", stability = "", homepage = "", pkgUrl = "", synopsis = "", description = "", category = "", abiHash = mkAbiHash "", indefinite = False, exposed = False, exposedModules = [], hiddenModules = [], trusted = False, importDirs = [], libraryDirs = [], libraryDynDirs = [], dataDir = "", hsLibraries = [], extraLibraries = [], extraGHCiLibraries= [], includeDirs = [], includes = [], depends = [], abiDepends = [], ccOptions = [], ldOptions = [], frameworkDirs = [], frameworks = [], haddockInterfaces = [], haddockHTMLs = [], pkgRoot = Nothing } -- ----------------------------------------------------------------------------- -- Exposed modules data ExposedModule = ExposedModule { exposedName :: ModuleName, exposedReexport :: Maybe OpenModule } deriving (Eq, Generic, Read, Show) instance Text ExposedModule where disp (ExposedModule m reexport) = Disp.hsep [ disp m , case reexport of Just m' -> Disp.hsep [Disp.text "from", disp m'] Nothing -> Disp.empty ] parse = do m <- parseModuleNameQ Parse.skipSpaces reexport <- Parse.option Nothing $ do _ <- Parse.string "from" Parse.skipSpaces fmap Just parse return (ExposedModule m reexport) instance Binary ExposedModule -- To maintain backwards-compatibility, we accept both comma/non-comma -- separated variants of this field. You SHOULD use the comma syntax if you -- use any new functions, although actually it's unambiguous due to a quirk -- of the fact that modules must start with capital letters. showExposedModules :: [ExposedModule] -> Disp.Doc showExposedModules xs | all isExposedModule xs = fsep (map disp xs) | otherwise = fsep (Disp.punctuate comma (map disp xs)) where isExposedModule (ExposedModule _ Nothing) = True isExposedModule _ = False parseExposedModules :: Parse.ReadP r [ExposedModule] parseExposedModules = parseOptCommaList parse dispMaybe :: Text a => Maybe a -> Disp.Doc dispMaybe Nothing = Disp.empty dispMaybe (Just x) = disp x parseMaybe :: Text a => Parse.ReadP r (Maybe a) parseMaybe = fmap Just parse Parse.<++ return Nothing -- ----------------------------------------------------------------------------- -- ABI dependency -- | An ABI dependency is a dependency on a library which also -- records the ABI hash ('abiHash') of the library it depends -- on. -- -- The primary utility of this is to enable an extra sanity when -- GHC loads libraries: it can check if the dependency has a matching -- ABI and if not, refuse to load this library. This information -- is critical if we are shadowing libraries; differences in the -- ABI hash let us know what packages get shadowed by the new version -- of a package. data AbiDependency = AbiDependency { depUnitId :: UnitId, depAbiHash :: AbiHash } deriving (Eq, Generic, Read, Show) instance Text AbiDependency where disp (AbiDependency uid abi) = disp uid <<>> Disp.char '=' <<>> disp abi parse = do uid <- parse _ <- Parse.char '=' abi <- parse return (AbiDependency uid abi) instance Binary AbiDependency -- ----------------------------------------------------------------------------- -- Munging sourceComponentName :: InstalledPackageInfo -> ComponentName sourceComponentName ipi = case sourceLibName ipi of Nothing -> CLibName Just qn -> CSubLibName qn -- | Returns @Just@ if the @name@ field of the IPI record would not contain -- the package name verbatim. This helps us avoid writing @package-name@ -- when it's redundant. maybePackageName :: InstalledPackageInfo -> Maybe PackageName maybePackageName ipi = case sourceLibName ipi of Nothing -> Nothing Just _ -> Just (packageName ipi) -- | Setter for the @package-name@ field. It should be acceptable for this -- to be a no-op. setMaybePackageName :: Maybe PackageName -> InstalledPackageInfo -> InstalledPackageInfo setMaybePackageName Nothing ipi = ipi setMaybePackageName (Just pn) ipi = ipi { sourcePackageId=(sourcePackageId ipi){pkgName=pn} } -- | Returns the munged package name, which we write into @name@ for -- compatibility with old versions of GHC. mungedPackageName :: InstalledPackageInfo -> MungedPackageName mungedPackageName ipi = computeCompatPackageName (packageName ipi) (sourceLibName ipi) setMungedPackageName :: MungedPackageName -> InstalledPackageInfo -> InstalledPackageInfo setMungedPackageName mpn ipi = let (pn, mb_uqn) = decodeCompatPackageName mpn in ipi { sourcePackageId = (sourcePackageId ipi) {pkgName=pn}, sourceLibName = mb_uqn } mungedPackageId :: InstalledPackageInfo -> MungedPackageId mungedPackageId ipi = MungedPackageId (mungedPackageName ipi) (packageVersion ipi) -- ----------------------------------------------------------------------------- -- Parsing parseInstalledPackageInfo :: String -> ParseResult InstalledPackageInfo parseInstalledPackageInfo = parseFieldsFlat (fieldsInstalledPackageInfo ++ deprecatedFieldDescrs) emptyInstalledPackageInfo -- ----------------------------------------------------------------------------- -- Pretty-printing showInstalledPackageInfo :: InstalledPackageInfo -> String showInstalledPackageInfo = showFields fieldsInstalledPackageInfo showInstalledPackageInfoField :: String -> Maybe (InstalledPackageInfo -> String) showInstalledPackageInfoField = showSingleNamedField fieldsInstalledPackageInfo showSimpleInstalledPackageInfoField :: String -> Maybe (InstalledPackageInfo -> String) showSimpleInstalledPackageInfoField = showSimpleSingleNamedField fieldsInstalledPackageInfo dispCompatPackageKey :: String -> Doc dispCompatPackageKey = text parseCompatPackageKey :: Parse.ReadP r String parseCompatPackageKey = Parse.munch1 uid_char where uid_char c = Char.isAlphaNum c || c `elem` "-_.=[],:<>+" -- ----------------------------------------------------------------------------- -- Description of the fields, for parsing/printing fieldsInstalledPackageInfo :: [FieldDescr InstalledPackageInfo] fieldsInstalledPackageInfo = basicFieldDescrs ++ installedFieldDescrs basicFieldDescrs :: [FieldDescr InstalledPackageInfo] basicFieldDescrs = [ simpleField "name" disp (parseMaybeQuoted parse) mungedPackageName setMungedPackageName , simpleField "version" disp parseOptVersion packageVersion (\ver pkg -> pkg{sourcePackageId=(sourcePackageId pkg){pkgVersion=ver}}) , simpleField "id" disp parse installedUnitId (\pk pkg -> pkg{installedUnitId=pk}) , simpleField "instantiated-with" (dispOpenModuleSubst . Map.fromList) (fmap Map.toList parseOpenModuleSubst) instantiatedWith (\iw pkg -> pkg{instantiatedWith=iw}) , simpleField "package-name" dispMaybe parseMaybe maybePackageName setMaybePackageName , simpleField "lib-name" dispMaybe parseMaybe sourceLibName (\n pkg -> pkg{sourceLibName=n}) , simpleField "key" dispCompatPackageKey parseCompatPackageKey compatPackageKey (\pk pkg -> pkg{compatPackageKey=pk}) , simpleField "license" disp parseLicenseQ license (\l pkg -> pkg{license=l}) , simpleField "copyright" showFreeText parseFreeText copyright (\val pkg -> pkg{copyright=val}) , simpleField "maintainer" showFreeText parseFreeText maintainer (\val pkg -> pkg{maintainer=val}) , simpleField "stability" showFreeText parseFreeText stability (\val pkg -> pkg{stability=val}) , simpleField "homepage" showFreeText parseFreeText homepage (\val pkg -> pkg{homepage=val}) , simpleField "package-url" showFreeText parseFreeText pkgUrl (\val pkg -> pkg{pkgUrl=val}) , simpleField "synopsis" showFreeText parseFreeText synopsis (\val pkg -> pkg{synopsis=val}) , simpleField "description" showFreeText parseFreeText description (\val pkg -> pkg{description=val}) , simpleField "category" showFreeText parseFreeText category (\val pkg -> pkg{category=val}) , simpleField "author" showFreeText parseFreeText author (\val pkg -> pkg{author=val}) ] installedFieldDescrs :: [FieldDescr InstalledPackageInfo] installedFieldDescrs = [ boolField "exposed" exposed (\val pkg -> pkg{exposed=val}) , boolField "indefinite" indefinite (\val pkg -> pkg{indefinite=val}) , simpleField "exposed-modules" showExposedModules parseExposedModules exposedModules (\xs pkg -> pkg{exposedModules=xs}) , listField "hidden-modules" disp parseModuleNameQ hiddenModules (\xs pkg -> pkg{hiddenModules=xs}) , simpleField "abi" disp parse abiHash (\abi pkg -> pkg{abiHash=abi}) , boolField "trusted" trusted (\val pkg -> pkg{trusted=val}) , listField "import-dirs" showFilePath parseFilePathQ importDirs (\xs pkg -> pkg{importDirs=xs}) , listField "library-dirs" showFilePath parseFilePathQ libraryDirs (\xs pkg -> pkg{libraryDirs=xs}) , listField "dynamic-library-dirs" showFilePath parseFilePathQ libraryDynDirs (\xs pkg -> pkg{libraryDynDirs=xs}) , simpleField "data-dir" showFilePath (parseFilePathQ Parse.<++ return "") dataDir (\val pkg -> pkg{dataDir=val}) , listField "hs-libraries" showFilePath parseTokenQ hsLibraries (\xs pkg -> pkg{hsLibraries=xs}) , listField "extra-libraries" showToken parseTokenQ extraLibraries (\xs pkg -> pkg{extraLibraries=xs}) , listField "extra-ghci-libraries" showToken parseTokenQ extraGHCiLibraries (\xs pkg -> pkg{extraGHCiLibraries=xs}) , listField "include-dirs" showFilePath parseFilePathQ includeDirs (\xs pkg -> pkg{includeDirs=xs}) , listField "includes" showFilePath parseFilePathQ includes (\xs pkg -> pkg{includes=xs}) , listField "depends" disp parse depends (\xs pkg -> pkg{depends=xs}) , listField "abi-depends" disp parse abiDepends (\xs pkg -> pkg{abiDepends=xs}) , listField "cc-options" showToken parseTokenQ ccOptions (\path pkg -> pkg{ccOptions=path}) , listField "ld-options" showToken parseTokenQ ldOptions (\path pkg -> pkg{ldOptions=path}) , listField "framework-dirs" showFilePath parseFilePathQ frameworkDirs (\xs pkg -> pkg{frameworkDirs=xs}) , listField "frameworks" showToken parseTokenQ frameworks (\xs pkg -> pkg{frameworks=xs}) , listField "haddock-interfaces" showFilePath parseFilePathQ haddockInterfaces (\xs pkg -> pkg{haddockInterfaces=xs}) , listField "haddock-html" showFilePath parseFilePathQ haddockHTMLs (\xs pkg -> pkg{haddockHTMLs=xs}) , simpleField "pkgroot" (const Disp.empty) parseFilePathQ (fromMaybe "" . pkgRoot) (\xs pkg -> pkg{pkgRoot=Just xs}) ] deprecatedFieldDescrs :: [FieldDescr InstalledPackageInfo] deprecatedFieldDescrs = [ listField "hugs-options" showToken parseTokenQ (const []) (const id) ]
themoritz/cabal
Cabal/Distribution/InstalledPackageInfo.hs
bsd-3-clause
20,883
0
14
5,978
3,651
2,080
1,571
371
2
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} #if __GLASGOW_HASKELL__ >= 707 {-# LANGUAGE DeriveDataTypeable #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Comonad.Trans.Coiter -- Copyright : (C) 2008-2013 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : MPTCs, fundeps -- -- The coiterative comonad generated by a comonad ---------------------------------------------------------------------------- module Control.Comonad.Trans.Coiter ( -- | -- Coiterative comonads represent non-terminating, productive computations. -- -- They are the dual notion of iterative monads. While iterative computations -- produce no values or eventually terminate with one, coiterative -- computations constantly produce values and they never terminate. -- -- It's simpler form, 'Coiter', is an infinite stream of data. 'CoiterT' -- extends this so that each step of the computation can be performed in -- a comonadic context. -- * The coiterative comonad transformer CoiterT(..) -- * The coiterative comonad , Coiter, coiter, runCoiter -- * Generating coiterative comonads , unfold -- * Cofree comonads , ComonadCofree(..) -- * Examples -- $example ) where import Control.Arrow hiding (second) import Control.Comonad import Control.Comonad.Cofree.Class import Control.Comonad.Env.Class import Control.Comonad.Hoist.Class import Control.Comonad.Store.Class import Control.Comonad.Traced.Class import Control.Comonad.Trans.Class import Control.Category import Data.Bifunctor import Data.Bifoldable import Data.Bitraversable import Data.Data import Data.Foldable import Data.Function (on) import Data.Functor.Identity import Data.Traversable import Prelude hiding (id,(.)) import Prelude.Extras -- | This is the coiterative comonad generated by a comonad newtype CoiterT w a = CoiterT { runCoiterT :: w (a, CoiterT w a) } #if __GLASGOW_HASKELL__ >= 707 deriving Typeable #endif instance (Functor w, Eq1 w) => Eq1 (CoiterT w) where (==#) = on (==#) (fmap (fmap Lift1) . runCoiterT) instance (Functor w, Ord1 w) => Ord1 (CoiterT w) where compare1 = on compare1 (fmap (fmap Lift1) . runCoiterT) instance (Functor w, Show1 w) => Show1 (CoiterT w) where showsPrec1 d (CoiterT as) = showParen (d > 10) $ showString "CoiterT " . showsPrec1 11 (fmap (fmap Lift1) as) instance (Functor w, Read1 w) => Read1 (CoiterT w) where readsPrec1 d = readParen (d > 10) $ \r -> [ (CoiterT (fmap (fmap lower1) m),t) | ("CoiterT",s) <- lex r, (m,t) <- readsPrec1 11 s] -- | The coiterative comonad type Coiter = CoiterT Identity -- | Prepends a result to a coiterative computation. -- -- prop> runCoiter . uncurry coiter == id coiter :: a -> Coiter a -> Coiter a coiter a as = CoiterT $ Identity (a,as) {-# INLINE coiter #-} -- | Extracts the first result from a coiterative computation. -- -- prop> uncurry coiter . runCoiter == id runCoiter :: Coiter a -> (a, Coiter a) runCoiter = runIdentity . runCoiterT {-# INLINE runCoiter #-} instance Functor w => Functor (CoiterT w) where fmap f = CoiterT . fmap (bimap f (fmap f)) . runCoiterT instance Comonad w => Comonad (CoiterT w) where extract = fst . extract . runCoiterT {-# INLINE extract #-} extend f = CoiterT . extend (\w -> (f (CoiterT w), extend f $ snd $ extract w)) . runCoiterT instance Foldable w => Foldable (CoiterT w) where foldMap f = foldMap (bifoldMap f (foldMap f)) . runCoiterT instance Traversable w => Traversable (CoiterT w) where traverse f = fmap CoiterT . traverse (bitraverse f (traverse f)) . runCoiterT instance ComonadTrans CoiterT where lower = fmap fst . runCoiterT instance Comonad w => ComonadCofree Identity (CoiterT w) where unwrap = Identity . snd . extract . runCoiterT {-# INLINE unwrap #-} instance ComonadEnv e w => ComonadEnv e (CoiterT w) where ask = ask . lower {-# INLINE ask #-} instance ComonadHoist CoiterT where cohoist g = CoiterT . fmap (second (cohoist g)) . g . runCoiterT instance ComonadTraced m w => ComonadTraced m (CoiterT w) where trace m = trace m . lower {-# INLINE trace #-} instance ComonadStore s w => ComonadStore s (CoiterT w) where pos = pos . lower peek s = peek s . lower peeks f = peeks f . lower seek = seek seeks = seeks experiment f = experiment f . lower {-# INLINE pos #-} {-# INLINE peek #-} {-# INLINE peeks #-} {-# INLINE seek #-} {-# INLINE seeks #-} {-# INLINE experiment #-} instance Show (w (a, CoiterT w a)) => Show (CoiterT w a) where showsPrec d w = showParen (d > 10) $ showString "CoiterT " . showsPrec 11 w instance Read (w (a, CoiterT w a)) => Read (CoiterT w a) where readsPrec d = readParen (d > 10) $ \r -> [(CoiterT w, t) | ("CoiterT", s) <- lex r, (w, t) <- readsPrec 11 s] instance Eq (w (a, CoiterT w a)) => Eq (CoiterT w a) where CoiterT a == CoiterT b = a == b {-# INLINE (==) #-} instance Ord (w (a, CoiterT w a)) => Ord (CoiterT w a) where compare (CoiterT a) (CoiterT b) = compare a b {-# INLINE compare #-} -- | Unfold a @CoiterT@ comonad transformer from a cokleisli arrow and an initial comonadic seed. unfold :: Comonad w => (w a -> a) -> w a -> CoiterT w a unfold psi = CoiterT . extend (extract &&& unfold psi . extend psi) #if __GLASGOW_HASKELL__ < 707 instance Typeable1 w => Typeable1 (CoiterT w) where typeOf1 t = mkTyConApp coiterTTyCon [typeOf1 (w t)] where w :: CoiterT w a -> w a w = undefined coiterTTyCon :: TyCon #if __GLASGOW_HASKELL__ < 704 coiterTTyCon = mkTyCon "Control.Comonad.Trans.Coiter.CoiterT" #else coiterTTyCon = mkTyCon3 "free" "Control.Comonad.Trans.Coiter" "CoiterT" #endif {-# NOINLINE coiterTTyCon #-} #else #define Typeable1 Typeable #endif instance ( Typeable1 w, Typeable a , Data (w (a, CoiterT w a)) , Data a ) => Data (CoiterT w a) where gfoldl f z (CoiterT w) = z CoiterT `f` w toConstr _ = coiterTConstr gunfold k z c = case constrIndex c of 1 -> k (z CoiterT) _ -> error "gunfold" dataTypeOf _ = coiterTDataType dataCast1 f = gcast1 f coiterTConstr :: Constr coiterTConstr = mkConstr coiterTDataType "CoiterT" [] Prefix {-# NOINLINE coiterTConstr #-} coiterTDataType :: DataType coiterTDataType = mkDataType "Control.Comonad.Trans.Coiter.CoiterT" [coiterTConstr] {-# NOINLINE coiterTDataType #-} {- $example <examples/NewtonCoiter.lhs Newton's method> -}
dalaing/free
src/Control/Comonad/Trans/Coiter.hs
bsd-3-clause
6,653
0
14
1,279
1,850
991
859
-1
-1
module LetIn3 where sumSquares x y = let pow = 2 in (let in ((sq pow) x) + ((sq pow) y)) sq 0 = 0 sq z = z ^ pow anotherFun 0 y = sq y where sq x = x ^ 2
kmate/HaRe
old/testing/liftToToplevel/LetIn3AST.hs
bsd-3-clause
163
0
14
53
109
55
54
6
1
{-# OPTIONS -fglasgow-exts #-} {-# OPTIONS -fforall #-} -- The interesting thign about this one is that -- there's an unbound type variable of kind *->* -- that the typechecker should default to some -- arbitrary type. -- -- GHC 5.02 could only really deal with such things -- of kind *, but 5.03 extended that to *->..->* -- Still not complete, but a lot better. module ShouldCompile where f :: (forall a b . a b -> int) -> (forall c . c int) -> int f x y = x y
hvr/jhc
regress/tests/1_typecheck/2_pass/ghc/tc146.hs
mit
468
0
9
98
67
41
26
-1
-1
{-+ Knot-tying definitions for the type decorated base+property syntax to Stratego translation. -} module TiProp2Stratego2 where import TiPropDecorate(TiDecl(..),TiExp(..), TiAssertion(..),OTiAssertion(..),TiPredicate(..)) import PropSyntax(prop,mapHsIdent) import BaseStruct2Stratego2 import PropStruct2Stratego2 import Prop2Stratego2(transType,transContext,transTlhs,transQType) import TiBase2Stratego2 import qualified Base2Stratego2 as B import StrategoDecl import TiClasses(fromDefs) import Parentheses -- needed for pattern matching. Grr!! transDecs ds = transDecs' (fromDefs ds) transDecs' ds = concatMap transDec ds transDec (Dec d) = prop (transD transId transExp transPat transLocalDecs transType transContext transTlhs) ((:[]) . transPD transId transOAssertion transPredicate) d transExp e = case e of Exp e -> transE transId transExp transPat transLocalDecs transType transContext e TiSpec i _ _ -> transEId (mapHsIdent transId i) TiTyped e _ -> transExp e transOAssertion (OA is ds a) = transAssertion a -- !!! transAssertion (PA a) = transPA transId transExp transQType transAssertion transPredicate a transPredicate (PP p) = transPP transId transExp B.transPat transQType transAssertion transPredicate p transLocalDecs ds = concatMap transLocalDec (fromDefs ds) transLocalDec d = [def|Def (P def)<-transDec d] -- silently ignores unimplemented things!!!
forste/haReFork
tools/hs2stratego/TiProp2Stratego2.hs
bsd-3-clause
1,470
4
11
263
398
215
183
32
3
{-# LANGUAGE TypeInType #-} module Bug11592 where data A (a :: a) = MkA String data B b (a :: a b) = MkB String data C b (a :: b a) = MkC String data D b c (a :: c a b) = MkD String
ezyang/ghc
testsuite/tests/rename/should_fail/T11592.hs
bsd-3-clause
186
0
6
51
84
52
32
-1
-1
-------------------------------------------------------------------------------- -- | The LLVM abstract syntax. -- module Llvm.AbsSyn where import Llvm.MetaData import Llvm.Types import Unique -- | Block labels type LlvmBlockId = Unique -- | A block of LLVM code. data LlvmBlock = LlvmBlock { -- | The code label for this block blockLabel :: LlvmBlockId, -- | A list of LlvmStatement's representing the code for this block. -- This list must end with a control flow statement. blockStmts :: [LlvmStatement] } type LlvmBlocks = [LlvmBlock] -- | An LLVM Module. This is a top level container in LLVM. data LlvmModule = LlvmModule { -- | Comments to include at the start of the module. modComments :: [LMString], -- | LLVM Alias type definitions. modAliases :: [LlvmAlias], -- | LLVM meta data. modMeta :: [MetaDecl], -- | Global variables to include in the module. modGlobals :: [LMGlobal], -- | LLVM Functions used in this module but defined in other modules. modFwdDecls :: LlvmFunctionDecls, -- | LLVM Functions defined in this module. modFuncs :: LlvmFunctions } -- | An LLVM Function data LlvmFunction = LlvmFunction { -- | The signature of this declared function. funcDecl :: LlvmFunctionDecl, -- | The functions arguments funcArgs :: [LMString], -- | The function attributes. funcAttrs :: [LlvmFuncAttr], -- | The section to put the function into, funcSect :: LMSection, -- | The body of the functions. funcBody :: LlvmBlocks } type LlvmFunctions = [LlvmFunction] -- | LLVM ordering types for synchronization purposes. (Introduced in LLVM -- 3.0). Please see the LLVM documentation for a better description. data LlvmSyncOrdering -- | Some partial order of operations exists. = SyncUnord -- | A single total order for operations at a single address exists. | SyncMonotonic -- | Acquire synchronization operation. | SyncAcquire -- | Release synchronization operation. | SyncRelease -- | Acquire + Release synchronization operation. | SyncAcqRel -- | Full sequential Consistency operation. | SyncSeqCst deriving (Show, Eq) -- | Llvm Statements data LlvmStatement {- | Assign an expression to an variable: * dest: Variable to assign to * source: Source expression -} = Assignment LlvmVar LlvmExpression {- | Memory fence operation -} | Fence Bool LlvmSyncOrdering {- | Always branch to the target label -} | Branch LlvmVar {- | Branch to label targetTrue if cond is true otherwise to label targetFalse * cond: condition that will be tested, must be of type i1 * targetTrue: label to branch to if cond is true * targetFalse: label to branch to if cond is false -} | BranchIf LlvmVar LlvmVar LlvmVar {- | Comment Plain comment. -} | Comment [LMString] {- | Set a label on this position. * name: Identifier of this label, unique for this module -} | MkLabel LlvmBlockId {- | Store variable value in pointer ptr. If value is of type t then ptr must be of type t*. * value: Variable/Constant to store. * ptr: Location to store the value in -} | Store LlvmVar LlvmVar {- | Mutliway branch * scrutinee: Variable or constant which must be of integer type that is determines which arm is chosen. * def: The default label if there is no match in target. * target: A list of (value,label) where the value is an integer constant and label the corresponding label to jump to if the scrutinee matches the value. -} | Switch LlvmVar LlvmVar [(LlvmVar, LlvmVar)] {- | Return a result. * result: The variable or constant to return -} | Return (Maybe LlvmVar) {- | An instruction for the optimizer that the code following is not reachable -} | Unreachable {- | Raise an expression to a statement (if don't want result or want to use Llvm unnamed values. -} | Expr LlvmExpression {- | A nop LLVM statement. Useful as its often more efficient to use this then to wrap LLvmStatement in a Just or []. -} | Nop {- | A LLVM statement with metadata attached to it. -} | MetaStmt [MetaAnnot] LlvmStatement deriving (Eq) -- | Llvm Expressions data LlvmExpression {- | Allocate amount * sizeof(tp) bytes on the stack * tp: LlvmType to reserve room for * amount: The nr of tp's which must be allocated -} = Alloca LlvmType Int {- | Perform the machine operator op on the operands left and right * op: operator * left: left operand * right: right operand -} | LlvmOp LlvmMachOp LlvmVar LlvmVar {- | Perform a compare operation on the operands left and right * op: operator * left: left operand * right: right operand -} | Compare LlvmCmpOp LlvmVar LlvmVar {- | Extract a scalar element from a vector * val: The vector * idx: The index of the scalar within the vector -} | Extract LlvmVar LlvmVar {- | Insert a scalar element into a vector * val: The source vector * elt: The scalar to insert * index: The index at which to insert the scalar -} | Insert LlvmVar LlvmVar LlvmVar {- | Allocate amount * sizeof(tp) bytes on the heap * tp: LlvmType to reserve room for * amount: The nr of tp's which must be allocated -} | Malloc LlvmType Int {- | Load the value at location ptr -} | Load LlvmVar {- | Navigate in an structure, selecting elements * inbound: Is the pointer inbounds? (computed pointer doesn't overflow) * ptr: Location of the structure * indexes: A list of indexes to select the correct value. -} | GetElemPtr Bool LlvmVar [LlvmVar] {- | Cast the variable from to the to type. This is an abstraction of three cast operators in Llvm, inttoptr, prttoint and bitcast. * cast: Cast type * from: Variable to cast * to: type to cast to -} | Cast LlvmCastOp LlvmVar LlvmType {- | Call a function. The result is the value of the expression. * tailJumps: CallType to signal if the function should be tail called * fnptrval: An LLVM value containing a pointer to a function to be invoked. Can be indirect. Should be LMFunction type. * args: Concrete arguments for the parameters * attrs: A list of function attributes for the call. Only NoReturn, NoUnwind, ReadOnly and ReadNone are valid here. -} | Call LlvmCallType LlvmVar [LlvmVar] [LlvmFuncAttr] {- | Call a function as above but potentially taking metadata as arguments. * tailJumps: CallType to signal if the function should be tail called * fnptrval: An LLVM value containing a pointer to a function to be invoked. Can be indirect. Should be LMFunction type. * args: Arguments that may include metadata. * attrs: A list of function attributes for the call. Only NoReturn, NoUnwind, ReadOnly and ReadNone are valid here. -} | CallM LlvmCallType LlvmVar [MetaExpr] [LlvmFuncAttr] {- | Merge variables from different basic blocks which are predecessors of this basic block in a new variable of type tp. * tp: type of the merged variable, must match the types of the predecessor variables. * precessors: A list of variables and the basic block that they originate from. -} | Phi LlvmType [(LlvmVar,LlvmVar)] {- | Inline assembly expression. Syntax is very similar to the style used by GCC. * assembly: Actual inline assembly code. * constraints: Operand constraints. * return ty: Return type of function. * vars: Any variables involved in the assembly code. * sideeffect: Does the expression have side effects not visible from the constraints list. * alignstack: Should the stack be conservatively aligned before this expression is executed. -} | Asm LMString LMString LlvmType [LlvmVar] Bool Bool {- | A LLVM expression with metadata attached to it. -} | MExpr [MetaAnnot] LlvmExpression deriving (Eq)
lukexi/ghc-7.8-arm64
compiler/llvmGen/Llvm/AbsSyn.hs
bsd-3-clause
8,442
0
9
2,368
532
345
187
62
0
{-# LANGUAGE RankNTypes, ScopedTypeVariables, PolyKinds #-} module T14066d where import Data.Proxy g :: (forall c b (a :: c). (Proxy a, Proxy c, b)) -> () g _ = () f :: forall b. b -> (Proxy Maybe, ()) f x = (fstOf3 y :: Proxy Maybe, g y) where y :: (Proxy a, Proxy c, b) -- this should NOT generalize over b -- meaning the call to g is ill-typed y = (Proxy, Proxy, x) fstOf3 (x, _, _) = x
sdiehl/ghc
testsuite/tests/dependent/should_fail/T14066d.hs
bsd-3-clause
438
0
9
131
168
97
71
10
1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {- Copyright (C) 2008 John MacFarlane <jgm@berkeley.edu> This program 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 2 of the License, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- Re-exports Happstack functions needed by gitit, including replacements for Happstack functions that don't handle UTF-8 properly, and new functions for setting headers and zipping contents and for looking up IP addresses. -} module Network.Gitit.Server ( module Happstack.Server , withExpiresHeaders , setContentType , setFilename , lookupIPAddr , getHost , compressedResponseFilter ) where import Happstack.Server import Happstack.Server.Compression (compressedResponseFilter) import Network.Socket (getAddrInfo, defaultHints, addrAddress) import Control.Monad.Reader import Data.ByteString.UTF8 as U hiding (lines) withExpiresHeaders :: ServerMonad m => m Response -> m Response withExpiresHeaders = liftM (setHeader "Cache-Control" "max-age=21600") setContentType :: String -> Response -> Response setContentType = setHeader "Content-Type" setFilename :: String -> Response -> Response setFilename = setHeader "Content-Disposition" . \fname -> "attachment; filename=\"" ++ fname ++ "\"" -- IP lookup lookupIPAddr :: String -> IO (Maybe String) lookupIPAddr hostname = do addrs <- getAddrInfo (Just defaultHints) (Just hostname) Nothing if null addrs then return Nothing else return $ Just $ takeWhile (/=':') $ show $ addrAddress $ case addrs of -- head addrs [] -> error "lookupIPAddr, no addrs" (x:_) -> x getHost :: ServerMonad m => m (Maybe String) getHost = liftM (maybe Nothing (Just . U.toString)) $ getHeaderM "Host"
vsivsi/gitit
src/Network/Gitit/Server.hs
gpl-2.0
2,474
0
13
574
365
198
167
31
3
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , NoImplicitPrelude , NondecreasingIndentation #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Encoding.Iconv -- Copyright : (c) The University of Glasgow, 2008-2009 -- License : see libraries/base/LICENSE -- -- Maintainer : libraries@haskell.org -- Stability : internal -- Portability : non-portable -- -- This module provides text encoding/decoding using iconv -- ----------------------------------------------------------------------------- module GHC.IO.Encoding.Iconv ( #if !defined(mingw32_HOST_OS) iconvEncoding, mkIconvEncoding, localeEncodingName #endif ) where #include "MachDeps.h" #include "HsBaseConfig.h" #if defined(mingw32_HOST_OS) import GHC.Base () -- For build ordering #else import Foreign import Foreign.C hiding (charIsRepresentable) import Data.Maybe import GHC.Base import GHC.Foreign (charIsRepresentable) import GHC.IO.Buffer import GHC.IO.Encoding.Failure import GHC.IO.Encoding.Types import GHC.List (span) import GHC.Num import GHC.Show import GHC.Real import System.IO.Unsafe (unsafePerformIO) import System.Posix.Internals c_DEBUG_DUMP :: Bool c_DEBUG_DUMP = False iconv_trace :: String -> IO () iconv_trace s | c_DEBUG_DUMP = puts s | otherwise = return () -- ----------------------------------------------------------------------------- -- iconv encoders/decoders {-# NOINLINE localeEncodingName #-} localeEncodingName :: String localeEncodingName = unsafePerformIO $ do -- Use locale_charset() or nl_langinfo(CODESET) to get the encoding -- if we have either of them. cstr <- c_localeEncoding peekCAString cstr -- Assume charset names are ASCII -- We hope iconv_t is a storable type. It should be, since it has at least the -- value -1, which is a possible return value from iconv_open. type IConv = CLong -- ToDo: (#type iconv_t) foreign import ccall unsafe "hs_iconv_open" hs_iconv_open :: CString -> CString -> IO IConv foreign import ccall unsafe "hs_iconv_close" hs_iconv_close :: IConv -> IO CInt foreign import ccall unsafe "hs_iconv" hs_iconv :: IConv -> Ptr CString -> Ptr CSize -> Ptr CString -> Ptr CSize -> IO CSize foreign import ccall unsafe "localeEncoding" c_localeEncoding :: IO CString haskellChar :: String #ifdef WORDS_BIGENDIAN haskellChar | charSize == 2 = "UTF-16BE" | otherwise = "UTF-32BE" #else haskellChar | charSize == 2 = "UTF-16LE" | otherwise = "UTF-32LE" #endif char_shift :: Int char_shift | charSize == 2 = 1 | otherwise = 2 iconvEncoding :: String -> IO (Maybe TextEncoding) iconvEncoding = mkIconvEncoding ErrorOnCodingFailure -- | Construct an iconv-based 'TextEncoding' for the given character set and -- 'CodingFailureMode'. -- -- As iconv is missing in some minimal environments (e.g. #10298), this -- checks to ensure that iconv is working properly before returning the -- encoding, returning 'Nothing' if not. mkIconvEncoding :: CodingFailureMode -> String -> IO (Maybe TextEncoding) mkIconvEncoding cfm charset = do let enc = TextEncoding { textEncodingName = charset, mkTextDecoder = newIConv raw_charset (haskellChar ++ suffix) (recoverDecode cfm) iconvDecode, mkTextEncoder = newIConv haskellChar charset (recoverEncode cfm) iconvEncode} good <- charIsRepresentable enc 'a' return $ if good then Just enc else Nothing where -- An annoying feature of GNU iconv is that the //PREFIXES only take -- effect when they appear on the tocode parameter to iconv_open: (raw_charset, suffix) = span (/= '/') charset newIConv :: String -> String -> (Buffer a -> Buffer b -> IO (Buffer a, Buffer b)) -> (IConv -> Buffer a -> Buffer b -> IO (CodingProgress, Buffer a, Buffer b)) -> IO (BufferCodec a b ()) newIConv from to rec fn = -- Assume charset names are ASCII withCAString from $ \ from_str -> withCAString to $ \ to_str -> do iconvt <- throwErrnoIfMinus1 "mkTextEncoding" $ hs_iconv_open to_str from_str let iclose = throwErrnoIfMinus1_ "Iconv.close" $ hs_iconv_close iconvt return BufferCodec{ encode = fn iconvt, recover = rec, close = iclose, -- iconv doesn't supply a way to save/restore the state getState = return (), setState = const $ return () } iconvDecode :: IConv -> DecodeBuffer iconvDecode iconv_t ibuf obuf = iconvRecode iconv_t ibuf 0 obuf char_shift iconvEncode :: IConv -> EncodeBuffer iconvEncode iconv_t ibuf obuf = iconvRecode iconv_t ibuf char_shift obuf 0 iconvRecode :: IConv -> Buffer a -> Int -> Buffer b -> Int -> IO (CodingProgress, Buffer a, Buffer b) iconvRecode iconv_t input@Buffer{ bufRaw=iraw, bufL=ir, bufR=iw, bufSize=_ } iscale output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow, bufSize=os } oscale = do iconv_trace ("haskellChar=" ++ show haskellChar) iconv_trace ("iconvRecode before, input=" ++ show (summaryBuffer input)) iconv_trace ("iconvRecode before, output=" ++ show (summaryBuffer output)) withRawBuffer iraw $ \ piraw -> do withRawBuffer oraw $ \ poraw -> do with (piraw `plusPtr` (ir `shiftL` iscale)) $ \ p_inbuf -> do with (poraw `plusPtr` (ow `shiftL` oscale)) $ \ p_outbuf -> do with (fromIntegral ((iw-ir) `shiftL` iscale)) $ \ p_inleft -> do with (fromIntegral ((os-ow) `shiftL` oscale)) $ \ p_outleft -> do res <- hs_iconv iconv_t p_inbuf p_inleft p_outbuf p_outleft new_inleft <- peek p_inleft new_outleft <- peek p_outleft let new_inleft' = fromIntegral new_inleft `shiftR` iscale new_outleft' = fromIntegral new_outleft `shiftR` oscale new_input | new_inleft == 0 = input { bufL = 0, bufR = 0 } | otherwise = input { bufL = iw - new_inleft' } new_output = output{ bufR = os - new_outleft' } iconv_trace ("iconv res=" ++ show res) iconv_trace ("iconvRecode after, input=" ++ show (summaryBuffer new_input)) iconv_trace ("iconvRecode after, output=" ++ show (summaryBuffer new_output)) if (res /= -1) then do -- all input translated return (InputUnderflow, new_input, new_output) else do errno <- getErrno case errno of e | e == e2BIG -> return (OutputUnderflow, new_input, new_output) | e == eINVAL -> return (InputUnderflow, new_input, new_output) -- Sometimes iconv reports EILSEQ for a -- character in the input even when there is no room -- in the output; in this case we might be about to -- change the encoding anyway, so the following bytes -- could very well be in a different encoding. -- -- Because we can only say InvalidSequence if there is at least -- one element left in the output, we have to special case this. | e == eILSEQ -> return (if new_outleft' == 0 then OutputUnderflow else InvalidSequence, new_input, new_output) | otherwise -> do iconv_trace ("iconv returned error: " ++ show (errnoToIOError "iconv" e Nothing Nothing)) throwErrno "iconvRecoder" #endif /* !mingw32_HOST_OS */
tolysz/prepare-ghcjs
spec-lts8/base/GHC/IO/Encoding/Iconv.hs
bsd-3-clause
7,543
0
45
1,843
1,313
693
620
123
3
{-# LANGUAGE GADTs, CPP, Trustworthy, TemplateHaskell, TupleSections, ViewPatterns, DeriveDataTypeable, ScopedTypeVariables #-} module GameB where --import Utils --import Paths_bomberman import qualified CodeWorld as CW import Graphics.Gloss import Graphics.Gloss.Data.Picture import Graphics.Gloss.Interface.IO.Game --import qualified Graphics.Gloss.Juicy as Juicy import Control.Concurrent.Async import Control.Exception.Safe import System.Timeout import Control.Concurrent import Control.Concurrent.MVar --import Gloss.Capture hiding (main) import Control.Monad import Control.DeepSeq import qualified Control.Monad.Reader as Reader import qualified Control.Monad.State as State import Control.Monad.State (StateT(..)) import Control.Monad.IO.Class import Data.Map (Map(..)) import Data.Set (Set(..)) import qualified Data.Text as Text import qualified Data.Map as Map import qualified Data.Set as Set import Data.Maybe import Data.Char as Char import Data.Word import qualified Data.Map as Map import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import Data.Dynamic import qualified Data.Text as T import System.Environment --import System.Console.CmdArgs hiding (record) import Engine hiding (main) --import qualified Bomberman.AI as AI import Text.Printf import Text.Read hiding (Char) import Data.List as List import Safe import qualified Test.QuickCheck as Quick import Unsafe.Coerce import JavaScript.Web.Worker.Extras mainGameB [js2,js3,js4] = jogo $ GUIArgs Nothing GUIPlay mapa p1 p2 p3 p4 1000 False (700,700) 100 200 10 5 where mapa = MGen 25 $ Just 1234 p1 = PHuman ("P1",Nothing) p2 = PBot (runBot js2) ("li1g175",Nothing) p3 = PBot (runBot js3) ("li1g147",Nothing) p4 = PBot (runBot js4) ("li1g100",Nothing) -- * Parâmetros variáveis guiTickFrames :: GUIArgs estado -> Int guiTickFrames args = guiFrameRate args `div` guiTicksPerSec args guiFrameToTick :: GUIArgs estado -> Int -> Int guiFrameToTick args x = x `div` guiTickFrames args data GUIMode = GUIRecord | GUIPlay deriving Show data GUIArgs estado = GUIArgs { guiRecord :: Maybe FilePath , guiMode :: GUIMode , guiMap :: GUIMap , guiP1 :: GUIPlayer estado , guiP2 :: GUIPlayer estado , guiP3 :: GUIPlayer estado , guiP4 :: GUIPlayer estado , guiGameTime :: Int , guiNormalText :: Bool , guiMaxXY :: (Int,Int) , guiImageSize :: Int , guiInfoSize :: Int , guiFrameRate :: Int -- frames per second , guiTicksPerSec :: Int -- ticks per second } deriving (Show) data GUIMap = MGen Int (Maybe Int) | MFile FilePath deriving (Show) guiMapSize :: GUIMap -> Int guiMapSize (MGen sz _) = sz -- name and avatar number type PlayerId = (String,Maybe Word8) data GUIPlayer estado = PBot (Bot estado) PlayerId | PHuman PlayerId | PNone deriving (Show) --guiPlayerEstado :: GUIPlayer estado -> IO estado --guiPlayerEstado (PBot b _) = iniBot bot --guiPlayerEstado PHuman = return mempty --guiPlayerEstado PNone = return mempty guiPlayerName :: GUIPlayer estado -> String guiPlayerName (PBot _ (n,_)) = n guiPlayerName (PHuman (n,_)) = n parseGUIMap :: GUIMap -> IO Mapa parseGUIMap guimap = do str <- case guimap of MGen dim seed -> do seed' <- maybe (Quick.generate Quick.arbitrary) return seed --putStrLn $ "generated map " ++ show dim ++ " " ++ show seed' return $ unlines0 $ tarefa1 dim seed' maxBound MFile file -> readFile file case leMapa str of Left err -> Prelude.error (show err) -- panic! Right mapa -> do --putStrLn $ str --putStrLn $ show mapa return mapa parseGUIPlayer :: GUIPlayer estado -> IO (Maybe (PlayerData estado)) parseGUIPlayer PNone = return Nothing parseGUIPlayer (PHuman (n,Just i)) = do pict <- loadPlayerBMP i return $ Just $ PlayerData (Right ()) n pict Nothing (Prelude.error "human") parseGUIPlayer (PBot bot (n,Just i)) = do pict <- loadPlayerBMP i ini <- initBot bot return $ Just $ PlayerData (Left bot) n pict Nothing ini parseGUIPlayers :: GUIArgs estado -> IO (Map Word8 (PlayerData estado)) parseGUIPlayers args = do [arg1,arg2,arg3,arg4] <- genPlayerAvatars [guiP1 args,guiP2 args,guiP3 args,guiP4 args] p1 <- parseGUIPlayer $ arg1 p2 <- parseGUIPlayer $ arg2 p3 <- parseGUIPlayer $ arg3 p4 <- parseGUIPlayer $ arg4 return $ Map.map (fromJustNote "parseGUIPlayers") $ Map.filter isJust $ Map.fromList $ zip [0..] [p1,p2,p3,p4] addMapPlayers :: Mapa -> Map Word8 (PlayerData estado)-> IO (Mapa,Map Word8 (PlayerData estado)) addMapPlayers m ps = do let m' = foldr aux1 m $ Map.toList ps ps' <- foldM aux3 ps $ Map.toList $ players m return (m',ps') where dim = boardDim $ board m aux1 (p,dta) m = m { players = Map.alter (aux2 p) p $ players m } aux2 p (Just pst) = Just pst aux2 0 Nothing = Just $ defPStat $ Pos 1 1 aux2 1 Nothing = Just $ defPStat $ Pos (dim-2) 1 aux2 2 Nothing = Just $ defPStat $ Pos (dim-2) (dim-2) aux2 3 Nothing = Just $ defPStat $ Pos 1 (dim-2) aux3 ps (p,pst) = do case Map.lookup p ps of Just x -> return ps Nothing -> defPData >>= \dta -> return $ Map.insert p dta ps -- * Bots type MyBot = [String] -> Int -> Int -> Maybe Char --parado :: Bot estado --parado = Bot $ \xs i j estado -> return (Nothing,estado) runBot :: String -> Bot (SyncWorker ([String],Int,Int) (Maybe Char)) runBot workerfile = Bot (newSyncWorker workerfile) go where go mapa player ticks worker = do inp <- Control.Exception.evaluate $! prettyMapa $ avancaTempoMapa mapa ticks tryPutSyncWorker worker (inp::[String],player::Int,ticks::Int) mbres <- tryTakeSyncWorker worker case mbres of Nothing -> do return (Nothing,worker) Just jogada -> return (jogada,worker) asyncTimeout_ :: Int -> IO a -> IO (Maybe a) asyncTimeout_ i f = withAsync f $ \a1 -> withAsync (threadDelay i) $ \a2 -> liftM (either Just (const Nothing)) $ race (wait a1) (wait a2) mkBot :: IO estado -> ([String] -> Int -> Int -> estado -> (Maybe Char,estado)) -> Bot estado mkBot ini f = Bot ini $ \m player ticks estado -> return $ f (prettyMapa m) player ticks estado -- estado data Bot estado = Bot { initBot :: IO estado, unBot :: Mapa -> Int -> Int -> estado -> IO (Maybe Char,estado)} instance Show (Bot estado) where show _ = "<bot>" -- * Gloss loadGraphic :: FilePath -> IO Picture loadGraphic file = do loadImageById ("graphics/" ++ file ++".bmp") loadPlayerBMP :: Word8 -> IO Picture loadPlayerBMP i = loadGraphic $ "players/p" ++ show i loadExplosionBMP :: Word8 -> IO Picture loadExplosionBMP i = loadGraphic $ "explosions/e" ++ show i loadFontBMP :: Char -> IO Picture loadFontBMP c = loadGraphic $ "fonts/" ++ [Char.toLower c] data PlayerData estado = PlayerData { pMove :: Either (Bot estado) (), pName :: String, pAvatar :: Picture, pDead :: Maybe Int, pState :: estado } deriving (Show) genPlayerAvatars :: [GUIPlayer estado] -> IO [GUIPlayer estado] genPlayerAvatars ps = aux ps (concatMap avatar ps) where avatar (PBot _ (n,Just w)) = [w] avatar (PHuman (n,Just w)) = [w] avatar _ = [] aux [] _ = return [] aux (PBot bot (n,Nothing):ps) acc = do let base::[Word8] = [1..28]\\acc i <- Quick.generate $ Quick.elements base ps' <- aux ps (i:acc) return (PBot bot (n,Just i):ps') aux (PHuman (n,Nothing):ps) acc = do let base::[Word8] = [1..28]\\acc i <- Quick.generate $ Quick.elements base ps' <- aux ps (i:acc) return (PHuman (n,Just i):ps') aux (p:ps) acc = do ps' <- aux ps acc return (p:ps') defPData :: IO (PlayerData estado) defPData = do i <- Quick.generate $ Quick.choose (1,28) pict <- loadPlayerBMP i return $ PlayerData (Right ()) "???" pict Nothing (Prelude.error "defPData") -- | função principal jogo :: GUIArgs estado -> IO () jogo guiargs = do mapa0 <- parseGUIMap $ guiMap guiargs players0 <- parseGUIPlayers guiargs (mapa,players) <- addMapPlayers mapa0 players0 let (janela,bloco) = tamanhos guiargs mapa let maxtime = guiGameTime guiargs parede <- loadGraphic "parede" tijolo <- loadGraphic "tijolo" bombs <- loadGraphic "bombs" flames <- loadGraphic "flames" let powerup i = case i of Bombs -> bombs Flames -> flames bomba <- loadGraphic "bomb" explosions <- mapM loadExplosionBMP [0..6] let explosion i = explosions!!i let gloss = MapaGloss (mapa,[]) janela bloco parede tijolo powerup bomba explosion (maxtime * guiFrameRate guiargs) (guiTickFrames guiargs) players (guiNormalText guiargs) case guiMode guiargs of GUIPlay -> joga guiargs gloss GUIRecord -> grava guiargs gloss (guiRecord guiargs) grava :: GUIArgs estado -> MapaGloss estado -> Maybe FilePath -> IO () grava guiargs gloss Nothing = do gloss' <- corre guiargs gloss putStrLn $ unlines $ map show $ getPlayerRank $ playerData gloss' return () getPlayerRank :: Map Word8 (PlayerData estado) -> [(Word8,Int)] getPlayerRank xs = genRanks 1 $ sortBy cmp $ Map.toList xs where cmp :: (Word8,PlayerData estado) -> (Word8,PlayerData estado) -> Ordering cmp x y = compare (f x) (f y) f :: (Word8,PlayerData estado) -> Int f (x,dta) = maybe minBound id (pDead dta) genRanks :: Int -> [(Word8,PlayerData estado)] -> [(Word8,Int)] genRanks i [] = [] genRanks i (x:xs) = let (wins,loses) = partition (\y -> f x == f y) xs in map ((,i) . fst) (x:wins) ++ genRanks (succ i + length wins) loses corre :: GUIArgs estado -> MapaGloss estado -> IO (MapaGloss estado) corre guiargs gloss = do gloss' <- if fim gloss then return gloss else do gloss' <- reageTempo guiargs 1 gloss corre guiargs gloss' return (gloss') fim :: MapaGloss estado -> Bool fim gloss = (framesTillEnd gloss <= 0) || (Map.size (players $ fst $ estado gloss) <= 1) -- | Estado do jogo: data MapaGloss estado = MapaGloss { estado :: (Mapa,Burned) -- estado do jogo (mapa,chamas) , janela :: (Int,Int) -- tamanho da janela , bloco :: Int -- tamanho de cada célula , paredeBMP :: Picture -- sprite da parede fixa , tijoloBMP :: Picture -- sprite do tijolo , powerupBMP :: PowerUp -> Picture -- sprite de powerups , bombaBMP :: Picture -- sprite de uma bomba , explosionBMP :: Int -> Picture -- sprite de uma explosão , framesTillEnd :: Int , framesTillTick :: Int , playerData :: Map Word8 (PlayerData estado) , textStyle :: Bool } playerBMP :: MapaGloss estado -> Word8 -> Picture playerBMP gloss p = case Map.lookup p (playerData gloss) of Nothing -> Prelude.error $ "player " ++ show p ++ " not found" Just dta -> pAvatar dta -- | Desenha o jogo dentro da janela desenhaMapa :: GUIArgs estado -> MapaGloss estado -> IO Picture desenhaMapa guiargs gloss = do let box = Color black $ Polygon [(-x2,-y2),(-x2,y2),(x2,y2),(x2,-y2)] let infobox = Translate (x2-info2) 0 $ Color color $ Polygon [(0,y2),(info,y2),(info,-y2),(0,-y2)] let pict = Translate (-info2) 0 $ Pictures $ box : desenhaTabuleiro guiargs gloss (estado gloss) -- time box let secondsTillEnd = framesTillEnd gloss `div` guiFrameRate guiargs let secondsTillEndAbs = if secondsTillEnd < 0 then 0 else secondsTillEnd timetext <- desenhaTexto (textStyle gloss) $ printf "%03d" secondsTillEndAbs let timecolor = if guiFrameToTick guiargs (framesTillEnd gloss) <= (fromEnum dim-1)^2 then red else black let timebox = Color timecolor $ Translate (x2-info2+45) (y2/2+100) $ Scale (0.5) (0.5) timetext ps <- players return $ Pictures [infobox,pict,timebox,ps,Pictures mapInfo] where dim = boardDim $ board $ fst $ estado gloss (x,y) = janela gloss x2 = fromIntegral x / 2 y2 = fromIntegral y / 2 info = fromIntegral (guiInfoSize guiargs) info2 = info / 2 color = makeColorI 255 178 102 150 color2 = makeColorI 64 23 15 255 players = do ps <- mapM player $ Map.toList $ playerData gloss return $ Translate (x2-info2+45) (y2/2+50) $ Pictures ps player (i,dta) = do pname <- desenhaTexto (textStyle gloss) $ pName dta return $ Translate 0 (-50*fromIntegral i) $ Pictures [pcell i dta,Translate 40 (-10) $ Pictures [dead i, Scale (0.2) (0.2) pname]] pcell i dta = drawCell guiargs gloss $ Pictures [Color color2 $ Polygon [(-70,-70),(-70,70),(70,70),(70,-70)],pAvatar dta] dead i = case fmap pDead (Map.lookup i $ playerData gloss) of Just Nothing -> Color black $ Line [(-5,-10),(-5,25),(87,25),(87,-10),(-5,-10)] Just (Just _) -> Color black $ Line [(-5,7),(87,7)] Nothing -> Blank mapInfo = [Translate (x2-info2+15) (y2/2-180) $ Color color2 $ Scale 0.1 0.1 $ Text "Keys:" ,Translate (x2-info2+15) (y2/2-200) $ Color color2 $ Scale 0.1 0.1 $ Text "Movement (W,S,A,D)" ,Translate (x2-info2+15) (y2/2-220) $ Color color2 $ Scale 0.1 0.1 $ Text "Bomb (Q)" ] desenhaTexto :: Bool -> String -> IO Picture desenhaTexto True s = return $ Scale (0.2) (0.2) $ Text s desenhaTexto False s = do picts <- desenhaTexto' s 0 return $ Translate 30 30 $ Pictures picts where desenhaTexto' [] off = return [] desenhaTexto' (c:cs) off = do p@(Image width _ _) <- loadFontBMP c ps <- desenhaTexto' cs (off+width+2) return (Translate (fromIntegral off) 0 p:ps) desenhaTabuleiro :: GUIArgs estado -> MapaGloss estado -> (Mapa,Burned) -> [Picture] desenhaTabuleiro guiargs gloss (m,burned) = [pb,pfs,Pictures pbs,ppws,ppls] where ppls = drawPlayers guiargs gloss (players m) ppws = drawPowerUps guiargs gloss (powers m) pb = drawBoard guiargs gloss (board m) pfs = paintFlames guiargs gloss burned pbs = map drawPBomb $ Map.toList $ allBombsWithPlayer m drawPBomb (p,(i,bmb)) = drawPos guiargs gloss p $ bombaBMP gloss paintFlames :: GUIArgs estado -> MapaGloss estado -> Burned -> Picture paintFlames guiargs gloss = Pictures . map paintFlame where paintFlame (p,i) = drawPos guiargs gloss p (explosionBMP gloss i) drawBoard :: GUIArgs estado -> MapaGloss estado -> Board -> Picture drawBoard guiargs gloss board = Pictures $ drawTijolos (boardTijolos board) ++ drawParedes where nparedes = boardCaracol board dim = boardDim board closed = closeParedes dim nparedes drawTijolos = map drawTijolo drawTijolo p = drawPos guiargs gloss p $ tijoloBMP gloss paredesfixas = [Pos x y | y <- [0..dim-1], x <- [0..dim-1], isWall dim (Pos x y) closed] drawParedes = map drawParede (paredesfixas ++ closeParedes dim nparedes) drawParede p = drawPos guiargs gloss p $ paredeBMP gloss drawPlayers :: GUIArgs estado -> MapaGloss estado -> Players -> Picture drawPlayers guiargs gloss = Pictures . map drawPlayer . Map.toList where drawPlayer (p,pstat) = drawPos guiargs gloss (pPos pstat) (playerBMP gloss p) drawPowerUps :: GUIArgs estado -> MapaGloss estado -> PowerUps -> Picture drawPowerUps guiargs gloss = Pictures . map drawPowerUp . Map.toList where tijolos = boardTijolos $ board $ fst $ estado gloss drawPowerUp (p,pw) = if List.elem p tijolos then Blank else drawPos guiargs gloss p $ powerupBMP gloss pw drawPos :: GUIArgs estado -> MapaGloss estado -> Pos -> Picture -> Picture drawPos guiargs gloss (Pos x y) pict = Translate px py $ drawCell guiargs gloss pict where b = bloco gloss (pX,pY) = janela gloss px = toEnum (fromIntegral x * b) - (fromIntegral pX / 2) + (toEnum b / 2) py = (fromIntegral pY / 2) - toEnum (fromIntegral y * b) - (toEnum b / 2) drawCell :: GUIArgs estado -> MapaGloss estado -> Picture -> Picture drawCell guiargs gloss pict = Scale s s pict where b = bloco gloss s = toEnum (bloco gloss) / toEnum (guiImageSize guiargs) -- | Reage ao pressionar das setas do teclado, movendo a bola 5 pixéis numa direção reageEvento :: GUIArgs estado -> Event -> MapaGloss estado -> IO (MapaGloss estado) reageEvento guiargs e gloss = case eventToMovimento e of Just (p,Down,k) -> return $ gloss { estado = let (x,y) = estado gloss in (moveMapaPerfect 10 x p k,y) } otherwise -> return gloss -- (player,movimento) eventToMovimento :: Event -> Maybe (Word8,KeyState,Char) eventToMovimento (EventKey (Char 'w') st _ _) = Just (0,st,'U') eventToMovimento (EventKey (Char 's') st _ _) = Just (0,st,'D') eventToMovimento (EventKey (Char 'a') st _ _) = Just (0,st,'L') eventToMovimento (EventKey (Char 'd') st _ _) = Just (0,st,'R') eventToMovimento (EventKey (Char 'q') st _ _) = Just (0,st,'B') eventToMovimento (EventKey (Char 't') st _ _) = Just (1,st,'U') eventToMovimento (EventKey (Char 'g') st _ _) = Just (1,st,'D') eventToMovimento (EventKey (Char 'f') st _ _) = Just (1,st,'L') eventToMovimento (EventKey (Char 'h') st _ _) = Just (1,st,'R') eventToMovimento (EventKey (Char 'y') st _ _) = Just (1,st,'B') eventToMovimento (EventKey (Char 'i') st _ _) = Just (2,st,'U') eventToMovimento (EventKey (Char 'k') st _ _) = Just (2,st,'D') eventToMovimento (EventKey (Char 'j') st _ _) = Just (2,st,'L') eventToMovimento (EventKey (Char 'l') st _ _) = Just (2,st,'R') eventToMovimento (EventKey (Char 'o') st _ _) = Just (2,st,'B') eventToMovimento (EventKey (SpecialKey KeyUp) st _ _) = Just (3,st,'U') eventToMovimento (EventKey (SpecialKey KeyDown) st _ _) = Just (3,st,'D') eventToMovimento (EventKey (SpecialKey KeyLeft) st _ _) = Just (3,st,'L') eventToMovimento (EventKey (SpecialKey KeyRight) st _ _) = Just (3,st,'R') eventToMovimento (EventKey (SpecialKey KeySpace) st _ _) = Just (3,st,'B') eventToMovimento _ = Nothing data DynState where DynState :: a -> DynState instance Show DynState where show (DynState _) = "<DynState>" instance NFData DynState where rnf = (`seq` ()) killPlayersData :: [Word8] -> Int -> Map Word8 (PlayerData estado) -> Map Word8 (PlayerData estado) killPlayersData [] time m = m killPlayersData (x:xs) time m = killPlayersData xs time (Map.update (Just . killPlayerData) x m) where killPlayerData :: PlayerData estado -> PlayerData estado killPlayerData pdta = pdta { pDead = Just $ maybe time id (pDead pdta) } -- | Reage ao tempo. reageTempo :: GUIArgs estado -> Int -> MapaGloss estado -> IO (MapaGloss estado) reageTempo guiargs passedframes gloss = if fim gloss then return $ gloss { framesTillEnd = framesTillEnd gloss - passedframes } else do ((estado',dead'),pdta') <- State.runStateT (chgPlayers $ estado gloss) (playerData gloss) let (estado'',dead'') = chgTime $ estado' return $ gloss { framesTillEnd = framesTillEnd gloss - passedframes , framesTillTick = if frames==0 then guiTickFrames guiargs else frames , estado = estado'' , playerData = killPlayersData (dead'++dead'') ticksTillEnd pdta' } where ticksTillEnd = guiFrameToTick guiargs $ framesTillEnd gloss frames = pred (framesTillTick gloss) chgTime :: (Mapa,Burned) -> ((Mapa,Burned),[Word8]) chgTime st = if frames/=0 then (st,[]) else Reader.runReader (avancaTempo st ticksTillEnd) perfect chgPlayers :: (Mapa,Burned) -> StateT (Map Word8 (PlayerData estado)) IO ((Mapa,Burned),[Word8]) chgPlayers (x,y) = if frames /=0 then return ((x,y),[]) else do let (x',dead) = Reader.runReader (cleanseMap (map fst y) [] x) perfect pdata <- State.get (x'',dead') <- foldM chgPlayer (x',dead) $ Map.toList pdata return ((x'',[]),dead') chgPlayer :: (Mapa,[Word8]) -> (Word8,PlayerData estado) -> StateT (Map Word8 (PlayerData estado)) IO (Mapa,[Word8]) chgPlayer (m,dead) (p,dta) = do let (x,y) = estado gloss --let pos = fmap pPos $ Map.lookup p $ players x case pMove dta of Left (Bot ini bot) -> do case Map.lookup p (players m) of Nothing -> return (m,dead) -- do not call the bot if the player does not exist Just pst -> do mb <- State.lift $ eitherFail botTimeout $ bot (removeHiddenPowerUps m) (fromEnum p) ticksTillEnd (pState dta) case mb of Left err -> State.lift $ putStrLn $ show p ++ " " ++ show (pName dta) ++ " " ++ show err otherwise -> return () let (mv,st') = case mb of Left err -> (Just 'e',pState dta) Right (mv,st) -> (mv,st) let dta' = dta { pState = st' } State.modify $ \psst -> Map.insert p dta' psst case mv of Nothing -> return (m,dead) Just mv -> do unless (List.elem mv "UDLRB") $ State.lift $ putStrLn $ show p ++ " " ++ show (pName dta) ++ " unknown move " ++ show mv let (m',dead') = moveMapaPerfectBot 10 m p mv return (m',dead++dead') Right () -> return (m,dead) -- bot maximum time per play, in seconds botTimeout :: Maybe Float botTimeout = Just 2 -- | tamanho de janela e blocos dinâmicos tamanhos :: GUIArgs estado -> Mapa -> ((Int,Int),Int) tamanhos guiargs mapa = ((fromIntegral $ blockX * x,fromIntegral $ blockX * y),min blockX blockY) where tab = board mapa x = fromIntegral $ boardDim tab y = fromIntegral $ boardDim tab sizeX = min (x * guiImageSize guiargs) (fst $ guiMaxXY guiargs) sizeY = min (y * guiImageSize guiargs) (snd $ guiMaxXY guiargs) blockX0 = sizeX `div` x blockY0 = sizeY `div` y blockX = if odd blockX0 then blockX0+1 else blockX0 blockY = if odd blockY0 then blockY0+1 else blockY0 -- | Inicia um jogo a partir de um mapa inicial joga :: GUIArgs estado -> MapaGloss estado -> IO () joga guiargs mapaInicial = do let (x,y) = (janela mapaInicial) screen <- getDisplay let window = Display (x+fromIntegral (guiInfoSize guiargs)) (y) playFitScreenIO screen window --(InWindow "Bomberman" window (0, 0)) -- Tamanho da janela do jogo (white) -- Côr do fundo da janela (guiFrameRate guiargs) -- refresh rate mapaInicial -- mapa inicial (desenhaMapa guiargs) -- função que desenha o mapa (reageEvento guiargs) -- função que reage a um evento (carregar numa tecla, mover o rato, etc) (\f m -> reageTempo guiargs 1 m) -- função que reage ao passar do tempo mapSnd :: (b -> c) -> (a,b) -> (a,c) mapSnd f (x,y) = (x,f y) eitherFail :: Maybe Float -> IO a -> IO (Either SomeException a) eitherFail cargs m = catch (liftM Right $ m) (\(e::SomeException) -> return $ Left e) unlines0 :: [String] -> String unlines0 [] = "" unlines0 [x] = x unlines0 (x:xs) = x ++ "\n" ++ unlines0 xs
hpacheco/HAAP
examples/gameworker/GameB.hs
mit
23,275
2
34
5,617
8,977
4,640
4,337
441
10
module Hanoi where type Peg = String type Move = (Peg, Peg) type Disc = Integer type PegState = (Peg, [Disc]) type BoardState = [PegState] {- | Solve the Towers of Hanoi puzzle by returning a list of Moves that will transfer a tower of N discs from the first to the second peg. >>> hanoi 2 "a" "b" "c" [("a","c"),("a","b"),("c","b")] This implementation is a literal translation of the spec, which says: To move n discs (stacked in increasing size) from peg a to peg b using peg c as temporary storage, 1. move n − 1 discs from a to c using b as temporary storage 2. move the top disc from a to b 3. move n − 1 discs from c to b using a as temporary storage. -} hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi 0 a b c = [] hanoi n a b c = hanoi (n - 1) a c b ++ [(a,b)] ++ hanoi (n - 1) c b a
ajcoppa/cis194
01-intro/Hanoi.hs
mit
809
0
9
179
156
90
66
9
1
module Beer (song) where song :: String song = concatMap line (reverse [0..99]) -- | line returns the nth line of the song. Only non-negative 'n' would make a -- correct song line line :: Int -> String line 0 = "No more bottles of beer on the wall, no more bottles of beer.\n\ \Go to the store and buy some more, 99 bottles of beer on the wall.\n" line n = bottle n ++ " of beer on the wall, " ++ bottle n ++ " of beer.\n\ \Take " ++ it n ++ " down and pass it around, " ++ bottle (n - 1) ++ " of beer on the wall.\n\ \\n" where bottle 0 = "no more bottles" bottle 1 = "1 bottle" bottle n = show n ++ " bottles" it 1 = "it" it _ = "one"
vaibhav276/exercism_haskell
beer-song/src/Beer.hs
mit
735
0
12
241
158
81
77
12
4
module Y2020.M07.D15.Exercise where {-- Okay, we've got historical context, we have a way to query that historical context, we have active members of our group, and we have already paired them, but it was a simple pairing algorithm, ignoring the context of who was paired with whom before. Today, we're going to create a pairing algorithm that will 1. get only the relevant history for pairings today; and, 2. pair our team-members today, given that relevant history. YEET! --} import Data.Time import Y2020.M07.D08.Exercise import Y2020.M07.D13.Exercise import Y2020.M07.D14.Exercise {-- Side note: You see how these exercises build on each other? That's how I do development. So, if you're just joining this conversation, how do you get started? This is what I would recommend (so I will): look at the imports. For the exercises imported that you have not completed, do those first. You'll find exercises imported in those exercises, do those first-first. When you have all your imports resolved, you've build up your modules to the state where you can now use them in this exercise. THEN do this exercise. So, this 1HaskellADay exercise could turn into several exercises to do. That's a fine learning-experience. /Side note --} depth :: [Member] -> Int depth activeMembers = undefined {-- depth Given the active members (data Member), compute how far back in depth you want to go in the history so you don't have pairings now that become impossible. How do you know that? Eh. floor (length of all active members / 2) should be a pretty good eye-ball. --} pairings :: Int -> History -> [Member] -> [Team] pairings depth history activeMembers = undefined {-- The function pairings pairs all the members who haven't been paired together before, and mobs any remaining people who would fall into a triple (you know, for groups that don't have even numbers of people. --}
geophf/1HaskellADay
exercises/HAD/Y2020/M07/D15/Exercise.hs
mit
1,891
0
8
330
93
58
35
9
1
module U.Codebase.Sqlite.JournalMode where data JournalMode = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF deriving Show
unisonweb/platform
codebase2/codebase-sqlite/U/Codebase/Sqlite/JournalMode.hs
mit
128
0
5
22
33
22
11
3
0
module Store.SQL.Connection where {-- We're basically rewriting Store.SQL.Connection. Good module, if you only have one database to manage, but now I have multiple SQL databases, so I have to make all these functions confirgurable. --} import Database.PostgreSQL.Simple import System.Environment -- let's codify which databases we're talking about here: data Database = WPJ | PILOT | ARCHIVE | ENTITIES | ECOIN deriving (Eq, Show) -- these functions get your database's information from the environment dbUserName, dbPassword, dbmsServer, dbName :: Database -> IO String dbUserName = ge "USERNAME" dbPassword = ge "PASSWORD" dbmsServer = ge "SERVER_URL" dbName = ge "DB_NAME" ge :: String -> Database -> IO String ge str dbname = getEnv ("SQL_DAAS_" ++ str ++ ('_':show dbname)) dbPort :: Database -> IO Int dbPort = fmap read . ge "SERVER_PORT" -- and with those we can do this: connectInfo :: Database -> IO ConnectInfo connectInfo dbname = ConnectInfo <$> dbmsServer dbname <*> (fromIntegral <$> dbPort dbname) <*> dbUserName dbname <*> dbPassword dbname <*> dbName dbname -- and with that we can do this: withConnection :: Database -> (Connection -> IO a) -> IO () withConnection db fn = connectInfo db >>= connect >>= \conn -> fn conn >> close conn -- with all that now connect to your database and do something cutesies -- ('cutesies' is a technical term) -- this module will replace Store.SQL.Connection
geophf/1HaskellADay
exercises/HAD/Store/SQL/Connection.hs
mit
1,509
0
11
323
309
164
145
22
1
module Util.Prelude where -- | Ternary if-then operator (?) :: Bool -> a -> a -> a (?) True t _ = t (?) False _ f = f infix 3 ? -- | Alias for comparison functions type Comparison a = (a -> a -> Ordering) -- | Convert from implicitly ordered projection, to comparison function toComparison :: Ord b => (a -> b) -> Comparison a toComparison f = \a b -> f a `compare` f b
sgord512/Utilities
Util/Prelude.hs
mit
374
0
8
83
132
75
57
8
1
module Main where import Control.Concurrent import Control.Concurrent.STM import Control.Monad import System.IO import System.Process -- import Control.Monad.Trans.Resource -- import Data.Conduit.Process data GhciOutput = StdOutput String | StdError String readerThread :: TChan GhciOutput -> (Handle, Handle) -> IO () readerThread ghciChan (out, err) = do _ <- forkIO (readHandleLine StdOutput out) _ <- forkIO (readHandleLine StdError out) threadDelay (1000 * 1000 * 1000 * 1000) where readHandleLine t hnd = do ln <- hGetLine hnd atomically (writeTChan ghciChan (t ln)) writerThread :: Monad m => Handle -> m () writerThread inp = return () main :: IO () main = do (Just inp, Just out, Just err, ph) <- createProcess (shell "ghci") { std_in = CreatePipe , std_out = CreatePipe , std_err = CreatePipe } forkIO (writerThread inp) ghciChan <- newTChanIO forkIO (readerThread ghciChan (out, err)) print inp print out print err serverThread serverThread = forever serverThread
haskellbr/meetups
code/ghci-api/src/Main.hs
mit
1,211
0
13
381
362
181
181
32
1
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module FP15.Disp where import Text.PrettyPrint import qualified Data.Map as M import Data.Void(Void) -- * The Disp Typeclass -- | The 'Disp' typeclass is for converting a value to string. The difference -- betwen 'Disp' and 'Show' is that 'Show' is made to be parseable by 'Read' and -- 'Disp' is for user-friendly representation. Error types use 'Disp' to -- generate user-readable error messages. class Disp a where {-# MINIMAL disp | pretty #-} disp :: a -> String pretty :: a -> Doc disp = show . pretty pretty = text . disp -- TODO more ways to configure disp: depth control, show location, etc. instance Disp Void where disp = undefined instance Disp () where disp = show instance Disp String where disp = id pretty = text instance (Disp k, Disp v) => Disp (M.Map k v) where pretty = vcat . map (\(k, v) -> pretty k <> colon <+> nest 2 (pretty v)) . M.toList
Ming-Tang/FP15
src/FP15/Disp.hs
mit
967
0
14
196
216
122
94
21
0
module Tape where import Data.Stream (Stream (..), (<:>)) import qualified Data.Stream as S import Parser data Tape a = Tape (Stream a) a (Stream a) instance Functor Tape where fmap f (Tape xs y zs) = Tape (fmap f xs) (f y) (fmap f zs) emptyTape :: Tape Int emptyTape = Tape zeros 0 zeros where zeros = S.repeat 0 emptyStream :: Stream BrainfuckCommand emptyStream = S.repeat Eof moveRight :: Tape a -> Tape a moveRight (Tape ls p (Cons r rs)) = Tape (p <:> ls) r rs moveLeft :: Tape a -> Tape a moveLeft (Tape (Cons l ls) p rs) = Tape ls l (p <:> rs)
Rydgel/Brainfokt
src/Tape.hs
mit
588
0
9
146
277
145
132
16
1
module Handler.AboutSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "getAboutR" $ do error "Spec not implemented: getAboutR"
swamp-agr/carbuyer-advisor
test/Handler/AboutSpec.hs
mit
171
0
11
39
44
23
21
6
1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ScopedTypeVariables #-} #ifdef MYSQL module Persistence.MySQL (connection) where import Persistence.DBConfig import Control.Monad.IO.Class import Control.Monad.Trans.Control import Control.Monad.Logger import Data.Maybe import Data.Pool (Pool) import Database.Persist.MySQL connection :: ( BaseBackend backend ~ SqlBackend , IsPersistBackend backend , MonadIO m , MonadBaseControl IO m , MonadLogger m ) => DBConfig -> Int -> (Pool backend -> m a) -> m a connection dbConfig defaultPoolSize = withMySQLPool (connectionInfo dbConfig) $ fromMaybe defaultPoolSize $ pool dbConfig connectionInfo :: DBConfig -> ConnectInfo connectionInfo config = let hostArg = fromMaybe (connectHost defaultConnectInfo) $ host config portArg = case port config of Nothing -> connectPort defaultConnectInfo Just p -> fromIntegral p userArg = fromMaybe (connectUser defaultConnectInfo) $ username config passArg = fromMaybe (connectPassword defaultConnectInfo) $ password config in defaultConnectInfo { connectHost = hostArg , connectPort = portArg , connectUser = userArg , connectPassword = passArg , connectDatabase = database config } #endif
spechub/Hets
Persistence/MySQL.hs
gpl-2.0
1,532
0
12
474
323
172
151
4
0
module Functions where -- cabal install Crypto import Data.Time import Data.List --import Crypto.HASH import Socket -- Get Date --getTime :: IO UTCTime --getTime = do -- let c = getCurrentTime -- llamar a Socket con c para enviar datos desde aquí -- return() -- Get MD5 --md5 returns a 4-tuple of 32bitWords, it is necessary convert it to String by meaning of concatTuplMD5 and after send it by socket to irc.freenode.net --getMD5 :: (MD5 a) => a -> IO String --getMD5 token = --Enviar (concatTuplMD5 (md5 token)) --concatTuplMD5 :: ABCD -> String --concatTuplMD5 [] = "" --concatTuplMD5 (x:xs) = (show x) ++ (concatTuplMD5 xs) extractMessage :: String -> IO(String) extractMessage xs = do return(xs++"holajaramigo") --splitMessage :: String -> String --splitMessage xs -- | (xs!!0) == ":" = xs -- | otherwise = (splitMessage xs)
overxfl0w/IRC-BOT
Functions.hs
gpl-2.0
892
7
9
195
79
54
25
7
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE Rank2Types #-} -- | exports from "Yi.Config.Simple" which are useful to \"core yi\" rather than just config files. module Yi.Config.Simple.Types where import Control.Monad.State hiding (modify, get) import Control.Monad.Base import Control.Applicative import Control.Lens import Yi.Config import Yi.Types -- | The configuration monad. Run it with 'configMain'. newtype ConfigM a = ConfigM { runConfigM :: StateT Config IO a } deriving (Monad, Functor, Applicative, MonadState Config, MonadBase IO) -- | Fields that can be modified with all lens machinery. type Field a = Lens' Config a {- | Accessor for any 'YiConfigVariable', to be used by modules defining 'YiConfigVariable's. Such modules should provide a custom-named field. For instance, take the following hypothetical 'YiConfigVariable': @newtype UserName = UserName { unUserName :: String } deriving(Typeable, Binary, Default) instance YiConfigVariable UserName $(nameDeriveAccessors ''UserName (\n -> Just (n ++ \"A\"))) userName :: 'Field' 'String' userName = unUserNameA '.' 'customVariable'@ Here, the hypothetical library would provide the field @userName@ to be used in preference to @customVariable@. -} customVariable :: YiConfigVariable a => Field a customVariable = configVariable
atsukotakahashi/wi
src/library/Yi/Config/Simple/Types.hs
gpl-2.0
1,325
0
7
194
135
82
53
15
1
{-# LANGUAGE DeriveDataTypeable #-} module Scyther.Sequent ( -- * Datatype Sequent(..) , SequentQualifier(..) , seProto -- ** Logically safe construction , wellTypedCases , reduceInjectivity , saturate , frule , fruleInst , chainRule , splitEq , exploitTyping , uniqueTIDQuantifiers ) where import Data.Maybe import qualified Data.Map as M import qualified Data.Set as S import Data.Data import Control.Arrow import Control.Monad import Control.Applicative import Extension.Prelude (sortednub) import qualified Scyther.Equalities as E import Scyther.Facts import Scyther.Formula ------------------------------------------------------------------------------ -- Sequents ------------------------------------------------------------------------------ -- | A qualifier changing the interpretation of a sequent. data SequentQualifier = Standard -- ^ The standard interpretation of a sequent as given in our CSF'10 -- paper on strong invariants for the efficient construction of -- machine-checked security proofs. | Injective -- ^ An injective interpretation of a sequent. Only valid for sequents -- that have exactly one free TID-variable in the premise and exactly -- one further TID-variable in the conclusion. deriving( Eq, Ord, Show, Data, Typeable ) -- | A sequent with a conjunction of a set of facts as the premise and a single -- formula as the conclusion denoting a statement about a reachable state of -- a protocol. data Sequent = Sequent { sePrem :: Facts , seConcl :: Formula , seQualifier :: SequentQualifier } deriving( Eq, Show, Ord, Data, Typeable ) -- | The protocol of a sequent. seProto :: Sequent -> Protocol seProto = protocol . sePrem -- | 'True' iff the sequent is viewed with the 'Standard' interpretation. isStandard :: Sequent -> Bool isStandard = (Standard ==) . seQualifier -- Construction --------------- -- | Make all thread identifiers occurring in the sequent unique by -- consistently relabeling the thread identifiers in the conclusion. uniqueTIDQuantifiers :: Sequent -> Sequent uniqueTIDQuantifiers (Sequent prem concl quali) = Sequent prem (relabelTIDs [nextTID prem..] concl) quali -- | Apply a function to the premise, but return only the updated sequent if -- the premise was changed. changePrem :: MonadPlus m => (Facts -> m Facts) -> Sequent -> m Sequent changePrem f se = do let prem0 = sePrem se prem1 <- f prem0 guard (prem0 /= prem1) return $ se { sePrem = prem1 } -- | The named list of sequents which need to be proven in order to prove that -- the given protocol is well typed -- -- PRE: The conclusion of the sequent must be typing atom. -- -- Uses 'fail' for error reporting. wellTypedCases :: MonadPlus m => Sequent -> m [(String, Sequent)] wellTypedCases se@(Sequent _ (FAtom (ATyping typ)) Standard) = return $ protoRoles (seProto se) >>= roleProofs where roleProofs role = proveRecvs S.empty (roleSteps role) where proveRecvs _ [] = [] proveRecvs recv (Send _ _ : steps) = proveRecvs recv steps proveRecvs recv (Match _ False _ _ : steps) = proveRecvs recv steps proveRecvs recv ((Recv _ (PMVar lid)) : steps) = -- don't prove single reiceves as they are handled directly by the tactic -- on the Isabelle side. proveRecvs (S.insert lid recv) steps proveRecvs recv (step@(Recv _ pt) : steps) = let mvars = patFMV pt in (S.toList mvars >>= proveVar recv step) `mplus` (proveRecvs (recv `S.union` mvars) steps) -- TODO: Merge? Special cases? proveRecvs recv (step@(Match _ True _ pt) : steps) = let mvars = patFMV pt in (S.toList mvars >>= proveVar recv step) `mplus` (proveRecvs (recv `S.union` mvars) steps) proveVar recv step v | v `S.member` recv = fail "proveVar: not first receive" | otherwise = return (name, Sequent prem concl Standard) where name = roleName role ++ "_" ++ stepLabel step ++ "_" ++ getId v (tid, prem0) = freshTID (sePrem se) mv = MVar (LocalId (v, tid)) premErr = error $ "wellTypedCases: could not add thread " ++ show tid ++ ". This should not happen." prem1 = maybe premErr saturateFacts . join $ conjoinAtoms [AEv (Step tid step), AEq (E.TIDRoleEq (tid, role))] prem0 prem = fromMaybe (error "failed to set typing") $ setTyping typ prem1 concl = FAtom $ case M.lookup (v, role) typ of Just ty -> AHasType (MMVar mv, ty, tid) Nothing -> error $ "wellTypedCases: no type given for '"++show v++"' in role '"++roleName role++"'" wellTypedCases _ = mzero -- | Emulate a variant Isabelle's 'frule' tactic. It works only if the given -- maping of free variables of the rule makes the premise of the rule provable -- under the given proof state. Then, the conclusion of the rule with free -- variables mapped accordingly is added to premises of the proof state. The -- last step works currently only for conclusions being false of pure -- conclusions. -- -- NOTE that 'frule' works only for rules that are standard sequents and that -- contain no existential quantifiers in the conclusion. fruleInst :: MonadPlus m => Sequent -- ^ rule -> E.Mapping -- ^ mapping of free variables of rule to proof state -> Sequent -- ^ proof state -> m (Maybe Sequent) -- ^ some result if resolution worked. Nothing -- denotes that False was derived. Just means that -- premises of proof state were extended. -- -- mzero if rule could not be applied fruleInst rule mapping state | isStandard rule && isStandard state = do atoms <- conjunctionToAtoms $ seConcl rule let statePrem = sePrem state guard (proveFacts statePrem (sePrem rule) mapping) optStatePrem' <- conjoinAtoms (map (substAtom (E.getMappingEqs mapping)) atoms) statePrem case optStatePrem' of Nothing -> do return Nothing Just statePrem' -> do guard (statePrem /= statePrem') return . Just $ Sequent statePrem' (seConcl state) Standard | otherwise = mzero -- | Like 'fruleInst' but tries all mappings. frule :: MonadPlus m => Sequent -- ^ rule -> Sequent -- ^ proof state -> m (E.Mapping, Maybe Sequent) -- ^ some result if resolution worked. Nothing denotes that False was -- derived. Just means that premises of proof state were extended. -- -- mzero if rule could not be applied frule rule state = case resolutions of [] -> mzero res : _ -> return res where resolutions = do mapping <- freeVariableMappings (sePrem rule) (sePrem state) ((,) mapping) `liftM` fruleInst rule mapping state {- -- | Emulate Isabelle's 'frule' tactic; i.e. the first sequent is the rule that -- is used for resolution. -- -- NOTE that 'frule' works only for rules that contain no existential -- quantifiers in the conclusion. frule :: Sequent -- ^ Rule to use for resolution. -> Sequent -- ^ Proof state that this rule is resolved against. -> [(Mapping, Maybe Sequent)] -- ^ The mapping and no resulting proof state -- if the resolution solved this subgoal; -- otherwise the new subgoal provided it is -- differnt from the old one. frule rule state = do atoms <- conjunctionToAtoms $ seConcl rule let prem0 = sePrem state mapping <- resolve (sePrem rule) prem0 optPrem1 <- conjoinAtoms (map (substAtom (getMappingEqs mapping)) atoms) prem0 case optPrem1 of Nothing -> do return (mapping, Nothing) Just prem1 -> do guard (prem1 /= prem0) return (mapping, Just $ Sequent prem1 (seConcl state)) -} -- | Try to prove an 'Injective' sequent by reducing it to its non-injective -- counterpart. reduceInjectivity :: Sequent -> Maybe (Either String Sequent) reduceInjectivity se | seQualifier se /= Injective = Nothing -- We have an injective sequent => we must reduce it or report a failure to -- reduce it. | otherwise = Just $ case sortednub $ formulaTIDs $ toFormula $ sePrem se of [premTID] -> case decomposeConcl $ seConcl se of Just (concTID, atoms) -> if check premTID concTID atoms then Right (se { seQualifier = Standard }) else Left "conclusion does not immediatly entail injectivity" Nothing -> Left $ "only works for conclusions of the form '? tid. ato1 & ... & atoN'" premTIDs -> Left $ "too few/many thread identifiers in premises " ++ show premTIDs where decomposeConcl (FExists (Left tid) fm) = (,) tid <$> conjunctionToAtoms fm decomposeConcl _ = Nothing -- check that conclusion entails equality of premise TIDs check premTID0 concTID atoms = case E.solve (rawEqs0 ++ rawEqs1) E.empty of Just eqs -> E.substTID eqs premTID0 == E.substTID eqs premTID1 _ -> False where premTID1 = 1 + max premTID0 concTID rawEqs0 = [ eq | AEq eq <- atoms ] rawEqs1 = map rename rawEqs0 rename = E.substAnyEq $ E.getMappingEqs $ E.addTIDMapping premTID0 premTID1 E.emptyMapping -- | Try to saturate a sequent, if possible and leading to new facts. saturate :: MonadPlus m => Sequent -> m Sequent saturate se = do guard (isStandard se) changePrem (return . saturateFacts) se -- | Try to use the chain rule. -- -- MonadPlus is used to report a failure to apply the rule. -- chainRule :: MonadPlus m => Sequent -> Message -> m [((String, [Either TID ArbMsgId]), Sequent)] chainRule se m = do guard (isStandard se) map (second mkSequent) `liftM` chainRuleFacts m (sePrem se) where mkSequent prem = Sequent prem (seConcl se) Standard -- | Try to exploit the typing. Fails if no new facts could be derived. exploitTyping :: MonadPlus m => Sequent -> m Sequent exploitTyping = changePrem exploitTypingFacts -- | Split a splittable equality. -- splitting can be done. splitEq :: E.MsgEq -> Sequent -> [Maybe Sequent] splitEq eq se | eq `elem` splittableEqs prems = map (fmap updPrem) $ splitEqFacts eq prems | otherwise = error $ "splitEq: equality not present" where prems = sePrem se updPrem prem' = se {sePrem = prem'}
meiersi/scyther-proof
src/Scyther/Sequent.hs
gpl-3.0
10,791
0
19
2,941
2,164
1,129
1,035
150
7
module Screepy.Dump (dumpPhotos) where import Control.Monad.Error import Control.Monad.Trans.Resource (runResourceT, ResourceT) import qualified Data.ByteString.Lazy as BL import Screepy.Photo (Photo(..)) import Data.Conduit import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import Data.List.Split (splitOn) import Data.Time.Format (formatTime) import System.Locale (defaultTimeLocale) data DumpError = HttpError String instance Error DumpError where noMsg = HttpError "HTTP error during dump!" strMsg s = HttpError s mkFilePath :: Photo -> FilePath -> FilePath mkFilePath photo directory = directory ++ "/" ++ formatedDate ++ "_" ++ photoName where date = (creationTime photo) photoName = last $ splitOn "/" (url photo) formatedDate = formatTime defaultTimeLocale "%Y-%m-%d-%T" date sinkPhotos :: FilePath -> Sink Photo (ResourceT IO) () sinkPhotos directory = do mphoto <- await case mphoto of Nothing -> return () Just photo -> do yield ct =$ CB.sinkFile fp sinkPhotos directory where fp = mkFilePath photo directory ct = BL.toStrict $ content photo dumpPhotos :: [Photo] -> FilePath -> IO () dumpPhotos photos directory = runResourceT $ CL.sourceList photos $$ (sinkPhotos directory) -- storePhotos :: Config -> [Photo] -> IO () -- storePhotos config photos = do -- let dest = (destination config) -- destExist <- doesDirectoryExist dest -- when (not destExist) (createDirectory dest) -- setCurrentDirectory dest -- putStr $ "data" ++ (show (creationTime . head $ photos)) -- runResourceT $ CL.sourceList photos $$ sinkPhotos -- import Control.Monad.Trans.Resource (runResourceT, ResourceT) -- import Control.Monad (when) -- import qualified Data.ByteString.Lazy as BL -- import Data.Conduit -- import qualified Data.Conduit.Binary as CB -- import qualified Data.Conduit.List as CL -- import Data.List.Split (splitOn) -- import Screepy.Config (Config(..)) -- import Screepy.Photo (Photo(..)) -- import System.Directory (createDirectory, -- doesDirectoryExist, -- setCurrentDirectory) -- import Data.Time.Format (formatTime) -- import System.Locale
kototama/screepy
src/Screepy/Dump.hs
gpl-3.0
2,485
0
14
673
415
234
181
33
2
{-# LANGUAGE RankNTypes, DeriveDataTypeable, ViewPatterns, FlexibleContexts, GADTs #-} -- Static semantics, used by the typechecker to evaluate indexes module Language.SecreC.Prover.Semantics where import Language.SecreC.Syntax import Language.SecreC.Location import Language.SecreC.Position import Language.SecreC.Monad import Language.SecreC.TypeChecker.Base import Language.SecreC.Vars import Language.SecreC.Utils import Language.SecreC.Error import Language.SecreC.Pretty import Language.SecreC.Prover.Base import Language.SecreC.TypeChecker.Environment import {-# SOURCE #-} Language.SecreC.TypeChecker.Type import {-# SOURCE #-} Language.SecreC.TypeChecker.Constraint import {-# SOURCE #-} Language.SecreC.Prover.Expression import Data.Int import Data.Word import Data.Map as Map import Data.Maybe import Data.List as List import Data.Generics import Text.PrettyPrint import System.Timeout.Lifted import Control.Monad import Control.Monad.State.Strict as State import Control.Monad.Writer.Strict as Writer import Control.Monad.Reader as Reader import Control.Monad.Except import Control.Monad.Trans.Control -- * Exports fullyEvaluateIndexExpr :: (ProverK loc m) => loc -> Expr -> TcM m Word64 fullyEvaluateIndexExpr l e = do IUint64 w <- fullyEvaluateExpr l $ fmap (Typed l) e return w fullyEvaluateExpr :: (ProverK loc m) => loc -> Expression GIdentifier (Typed loc) -> TcM m ILit fullyEvaluateExpr l e = evaluate l (text "evaluateExpr") (fullEvalIExpr l =<< expr2IExpr e) fullyEvaluateIExpr :: (ProverK loc m) => loc -> IExpr -> TcM m ILit fullyEvaluateIExpr l e = evaluate l (text "evaluateExpr") (fullEvalIExpr l e) ---- * Internal declarations evaluate :: (ProverK loc m) => loc -> Doc -> TcM m a -> TcM m a evaluate l doc m = do arr <- Reader.ask env <- State.get opts <- TcM $ lift Reader.ask mb <- lift $ timeout (evalTimeOut opts * 10^6) $ runSecrecMWith opts $ execTcM m arr env case mb of Nothing -> tcError (locpos l) $ Halt $ StaticEvalError doc $ Just $ TimedOut $ evalTimeOut opts Just (Left err) -> do tcError (locpos l) $ Halt $ StaticEvalError doc $ Just err Just (Right ((x,env'),warns)) -> do State.put env' TcM (lift $ Writer.tell warns) >> return x fullEvalIExpr :: (ProverK loc m) => loc -> IExpr -> TcM m ILit fullEvalIExpr l e = do i <- evalIExpr l e case i of ILit lit -> return lit otherwise -> do ppi <- pp i tcError (locpos l) $ Halt $ StaticEvalError (text "evalIExpr") $ Just $ GenericError (locpos l) (text "cannot fully evaluate index expression" <+> ppi) Nothing evalIExpr :: (ProverK loc m) => loc -> IExpr -> TcM m IExpr evalIExpr l (ILit lit) = return $ ILit lit evalIExpr l (IIdx v@(VarName t (VIden n@(varIdRead -> True)))) = do mb <- tryResolveEVar l n t case mb of Nothing -> return $ IIdx v Just e -> expr2SimpleIExpr e >>= evalIExpr l evalIExpr l (IBinOp o e1 e2) = do e1' <- evalIExpr l e1 e2' <- evalIExpr l e2 evalIBinOp l o e1' e2' evalIExpr l (IUnOp o e1) = do e1' <- evalIExpr l e1 evalIUnOp l o e1' evalIExpr l (ICond c e1 e2) = do c' <- evalIExpr l c case c' of ILit (IBool True) -> evalIExpr l e1 ILit (IBool False) -> evalIExpr l e2 c' -> do e1' <- evalIExpr l e1 e2' <- evalIExpr l e2 return $ ICond c' e1' e2' evalIExpr l (ISize e) = do e' <- evalIExpr l e case e' of (IArr _ xs) -> do let sz = fromInteger $ toInteger $ sum $ List.map length xs return $ ILit $ IUint64 sz otherwise -> return $ ISize e' evalIExpr l (IShape e) = do e' <- evalIExpr l e case e' of IArr _ xs -> do let szs = List.map (fromInteger . toInteger . length) xs return $ ILit $ ILitArr index [List.map (IUint64) szs] otherwise -> return $ IShape e' evalIExpr l e = return e boolILit :: IExpr -> Maybe Bool boolILit (ILit (IBool b)) = Just b boolILit e = Nothing evalIBinOp :: ProverK loc m => loc -> IBOp -> IExpr -> IExpr -> TcM m IExpr evalIBinOp l IAnd (boolILit -> Just b1) (boolILit -> Just b2) = return $ ILit $ IBool $ b1 && b2 evalIBinOp l IOr (boolILit -> Just b1) (boolILit -> Just b2) = return $ ILit $ IBool $ b1 || b2 evalIBinOp l IImplies (boolILit -> Just False) b2 = return $ ILit $ IBool True evalIBinOp l IImplies b1 (boolILit -> Just False) = return $ ILit $ IBool False evalIBinOp l IImplies (boolILit -> Just b1) (boolILit -> Just b2) = return $ILit $ IBool $ b1 <= b2 evalIBinOp l IXor (boolILit -> Just b1) (boolILit -> Just b2) = return $ ILit $ IBool $ (b1 || b2) && not (b1 && b2) evalIBinOp l (ILeq) (ILit e1) (ILit e2) = return $ ILit $ IBool $ ordILit (<=) e1 e2 evalIBinOp l (ILt) (ILit e1) (ILit e2) = return $ ILit $ IBool $ ordILit (<) e1 e2 evalIBinOp l (IGeq) (ILit e1) (ILit e2) = return $ ILit $ IBool $ ordILit (>=) e1 e2 evalIBinOp l (IGt) (ILit e1) (ILit e2) = return $ ILit $ IBool $ ordILit (>) e1 e2 evalIBinOp l (IEq) (ILit e1) (ILit e2) = return $ ILit $ IBool $ ordILit (==) e1 e2 evalIBinOp l (IPlus) (ILit e1) (ILit e2) = return $ ILit $ numILit (+) e1 e2 evalIBinOp l (IMinus) (ILit e1) (ILit e2) = return $ ILit $ numILit (-) e1 e2 evalIBinOp l (ITimes) (ILit e1) (ILit e2) = return $ ILit $ numILit (*) e1 e2 evalIBinOp l (IPower) (ILit e1) (ILit e2) = return $ ILit $ integralILit (^) e1 e2 evalIBinOp l (IDiv) (ILit e1) (ILit e2) = return $ ILit $ integralILit div e1 e2 evalIBinOp l (IMod) (ILit e1) (ILit e2) = return $ ILit $ integralILit mod e1 e2 evalIBinOp l op e1 e2 = return $ IBinOp op e1 e2 evalIUnOp :: ProverK loc m => loc -> IUOp -> IExpr -> TcM m IExpr evalIUnOp l INot (boolILit -> Just b) = return $ ILit $ IBool $ not b evalIUnOp l INeg (ILit i) = return $ ILit $ numILit (\x y -> -x) i (error "evalIUnOp INed") evalIUnOp l op e1 = return $ IUnOp op e1 numILit :: (forall a . Num a => a -> a -> a) -> ILit -> ILit -> ILit numILit f (IInt8 i1) (IInt8 i2) = IInt8 $ f i1 i2 numILit f (IInt16 i1) (IInt16 i2) = IInt16 $ f i1 i2 numILit f (IInt32 i1) (IInt32 i2) = IInt32 $ f i1 i2 numILit f (IInt64 i1) (IInt64 i2) = IInt64 $ f i1 i2 numILit f (IUint8 i1) (IUint8 i2) = IUint8 $ f i1 i2 numILit f (IUint16 i1) (IUint16 i2) = IUint16 $ f i1 i2 numILit f (IUint32 i1) (IUint32 i2) = IUint32 $ f i1 i2 numILit f (IUint64 i1) (IUint64 i2) = IUint64 $ f i1 i2 numILit f (IFloat32 i1) (IFloat32 i2) = IFloat32 $ f i1 i2 numILit f (IFloat64 i1) (IFloat64 i2) = IFloat64 $ f i1 i2 integralILit :: (forall a . Integral a => a -> a -> a) -> ILit -> ILit -> ILit integralILit f (IInt8 i1) (IInt8 i2) = IInt8 $ f i1 i2 integralILit f (IInt16 i1) (IInt16 i2) = IInt16 $ f i1 i2 integralILit f (IInt32 i1) (IInt32 i2) = IInt32 $ f i1 i2 integralILit f (IInt64 i1) (IInt64 i2) = IInt64 $ f i1 i2 integralILit f (IUint8 i1) (IUint8 i2) = IUint8 $ f i1 i2 integralILit f (IUint16 i1) (IUint16 i2) = IUint16 $ f i1 i2 integralILit f (IUint32 i1) (IUint32 i2) = IUint32 $ f i1 i2 integralILit f (IUint64 i1) (IUint64 i2) = IUint64 $ f i1 i2 ordILit :: (forall a . Ord a => a -> a -> Bool) -> ILit -> ILit -> Bool ordILit f (IInt8 i1) (IInt8 i2) = f i1 i2 ordILit f (IInt16 i1) (IInt16 i2) = f i1 i2 ordILit f (IInt32 i1) (IInt32 i2) = f i1 i2 ordILit f (IInt64 i1) (IInt64 i2) = f i1 i2 ordILit f (IUint8 i1) (IUint8 i2) = f i1 i2 ordILit f (IUint16 i1) (IUint16 i2) = f i1 i2 ordILit f (IUint32 i1) (IUint32 i2) = f i1 i2 ordILit f (IUint64 i1) (IUint64 i2) = f i1 i2 ordILit f (IFloat32 i1) (IFloat32 i2) = f i1 i2 ordILit f (IFloat64 i1) (IFloat64 i2) = f i1 i2 ordILit f (IBool i1) (IBool i2) = f i1 i2
haslab/SecreC
src/Language/SecreC/Prover/Semantics.hs
gpl-3.0
7,738
0
18
1,828
3,516
1,752
1,764
155
6
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } func reallyreallyreallyreallyreallyreallyreallyreallyreallyreallylongvariable reallyreallyreallyreallyreallyreallyreallyreallyreallyreallylongvariable = x
lspitzner/brittany
data/Test412.hs
agpl-3.0
271
0
5
18
12
6
6
2
1
module HelperSequences.A005117 (a005117, a005117_list) where import Data.List (genericIndex) a005117 :: Integral a => a -> a a005117 n = genericIndex a005117_list (n - 1) -- This isn't efficient, but it'll work for now. a005117_list :: Integral a => [a] a005117_list = filter squarefree [1..] where squarefree k = all (\i -> k `mod` i^2 /= 0) [2..max] where max = floor $ sqrt $ fromIntegral k
peterokagey/haskellOEIS
src/HelperSequences/A005117.hs
apache-2.0
402
0
12
74
149
81
68
8
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.ClusterRoleBindingList where import GHC.Generics import Data.Text import Openshift.Unversioned.ListMeta import Openshift.V1.ClusterRoleBinding import qualified Data.Aeson -- | data ClusterRoleBindingList = ClusterRoleBindingList { kind :: Maybe Text -- ^ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds , apiVersion :: Maybe Text -- ^ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources , metadata :: Maybe ListMeta -- ^ , items :: [ClusterRoleBinding] -- ^ list of cluster role bindings } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON ClusterRoleBindingList instance Data.Aeson.ToJSON ClusterRoleBindingList
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/ClusterRoleBindingList.hs
apache-2.0
1,268
0
9
174
125
77
48
19
0
{-# LANGUAGE OverloadedStrings #-} module Gitlog.Types ( GitEntry(..) , GitBody(..) , Config(..) , JiraIssue(..) , OutputFormat(..) , defaultConfig , hasJira ) where import Control.Applicative import Control.Monad ( mzero ) import Control.Parallel.Strategies import Data.Aeson import qualified Data.ByteString.Char8 as BS import Data.Time.Clock ( UTCTime ) import Data.Maybe ( isJust, catMaybes ) import Data.Monoid ( mempty ) import Data.Text ( Text ) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.Text.Encoding ( decodeUtf8 ) import Data.Text.Lazy.Builder import qualified Data.Vector as V import Gitlog.Utils ------------------------------------------------------------------------------ -- | Record describing one git commit data GitEntry = GitEntry { gSHA :: BS.ByteString , gAuthor :: BS.ByteString , gDate :: BS.ByteString , gTitle :: BS.ByteString , gBody :: [GitBody] } deriving ( Eq, Ord, Show ) instance ToJSON GitEntry where toJSON e = object [ "commit" .= decodeUtf8 (gSHA e) , "author" .= decodeUtf8 (gAuthor e) , "date" .= decodeUtf8 (gDate e) , "title" .= decodeUtf8 (gTitle e) , "body" .= object (catMaybes [ nonEmpty "text" (toLazyText text) , nonNull "tags" tags , Just ("intern" .= intern) ]) ] where (text, tags, intern) = foldr go (mempty, [], False) $ gBody e -- group body lines into one text entry -- and aggregate all tag entries go (Line x) (ls, ts, i) = (fromText (decodeUtf8 x) <> "\n" <> ls, ts, i) go t@Tag{} (ls, ts, i) = (ls, tag t : ts, i) go Intern (ls, ts, _) = (ls, ts, True) tag (Tag t x jira) = case jira of (Just j) -> object ["name" .= name, "jira" .= j] Nothing -> object ["name" .= name] where name = T.pack (BS.unpack t ++ "-" ++ show x) tag _ = Null nonEmpty k v | TL.null v = Nothing | otherwise = Just (k .= v) nonNull _ [] = Nothing nonNull k vs = Just (k .= vs) ------------------------------------------------------------------------------ -- | Git commit message body data GitBody = Tag BS.ByteString Int (Maybe JiraIssue) | Line BS.ByteString | Intern deriving ( Ord, Show ) instance NFData GitBody instance Eq GitBody where Intern == Intern = True (Line as) == (Line bs) = as == bs (Tag a x _) == (Tag b y _) = a == b && x == y _ == _ = False ------------------------------------------------------------------------------ -- | Record containing the additional JIRA information -- of a specific issue data JiraIssue = JiraIssue { jKey :: Text , jSummary :: Text , jToTest :: Bool , jDocumentation :: Bool , jPR :: Bool , jStatus :: JiraStatusCategoryType , jParent :: Maybe JiraIssue } deriving ( Eq, Ord, Show ) instance NFData JiraIssue instance FromJSON JiraIssue where parseJSON (Object v) = do key <- v .: "key" fs <- v .: "fields" (s, tt, doc, pr, st, p) <- fields fs return $ JiraIssue key s tt doc pr st p where fields (Object x) = do s <- x .: "summary" -- "to be tested" tt <- exists =<< (x .:? "customfield_10411" .!= Null) -- "documentation relevant" and "PR relevant" cs <- toList =<< (x .:? "customfield_10412" .!= Null) -- issue status st <- status =<< x .: "status" -- optional issue parent p <- x .:? "parent" return (s, tt, hasField "10123" cs, hasField "10220" cs, st, p) fields _ = mzero exists Null = return False exists _ = return True hasField i = any ((== i) . cfId) toList (Array xs) = mapM parseJSON $ V.toList xs toList _ = return [] status (Object s) = (idToType . jscId) <$> s .: "statusCategory" status _ = mzero parseJSON _ = mzero instance ToJSON JiraIssue where toJSON (JiraIssue k s tt d pr _ _) = object [ "key" .= k , "summary" .= s , "toTest" .= tt , "documentation" .= d , "pr" .= pr ] ------------------------------------------------------------------------------ -- | Internal structure to hold the JSON information -- of a JIRA custom field definition data CustomField = CI { cfId :: Text , _cfSelf :: Text , _cfValue :: Text } instance FromJSON CustomField where parseJSON (Object o) = CI <$> o .: "id" <*> o .: "self" <*> o .: "value" parseJSON _ = mzero data JiraStatusCategoryType = NoCategory | New | Complete | InProgress deriving ( Show, Eq, Ord ) idToType :: Int -> JiraStatusCategoryType idToType 1 = NoCategory idToType 2 = New idToType 3 = Complete idToType 4 = InProgress idToType _ = NoCategory data JiraStatusCategory = JSC { jscId :: Int , _jscKey :: Text } instance FromJSON JiraStatusCategory where parseJSON (Object x) = JSC <$> x .: "id" <*> x .: "key" parseJSON _ = mzero ------------------------------------------------------------------------------ -- | Output format used in encoding data OutputFormat = Html | Json deriving ( Eq, Show ) ------------------------------------------------------------------------------ -- | Record holding the application configuration data Config = Config { cRange :: Maybe (String, String) , cPath :: FilePath , cDate :: UTCTime , cJira :: String , cAuth :: Maybe (BS.ByteString, BS.ByteString) , cOutput :: OutputFormat , cDebug :: Bool } deriving ( Eq, Show ) ------------------------------------------------------------------------------ -- | Default application configuration defaultConfig :: UTCTime -> Config defaultConfig d = Config { cRange = Nothing , cPath = "." , cDate = d , cJira = [] , cAuth = Nothing , cOutput = Html , cDebug = False } ------------------------------------------------------------------------------ -- | Does the configuration contain valid JIRA -- information/credentials? hasJira :: Config -> Bool hasJira cfg = not (null jira) && hasAuth where jira = cJira cfg hasAuth = isJust $ cAuth cfg -- vim: set et sw=2 sts=2 tw=80:
kongo2002/gitlog
src/Gitlog/Types.hs
apache-2.0
6,386
0
15
1,762
1,847
1,016
831
164
1
module Foundation ( App (..) , Route (..) , AppMessage (..) , resourcesApp , Handler , Widget , Form , maybeAuth , requireAuth , module Settings , module Model , getExtra ) where import Prelude import Yesod hiding ((==.)) import Yesod.Static import Yesod.Auth import Yesod.Auth.BrowserId import Yesod.Auth.GoogleEmail import Yesod.Default.Config import Yesod.Default.Util (addStaticContentExternal) import Network.HTTP.Conduit (Manager) import qualified Settings import qualified Database.Persist.Store import Settings.StaticFiles import Database.Persist.GenericSql import Settings (widgetFile, Extra (..)) import Model import Text.Jasmine (minifym) import Web.ClientSession (getKey) import Text.Hamlet (hamletFile) import Database.Esqueleto import qualified Text.HyperEstraier.Database as Hs import Data.Conduit.Pool import Data.Maybe (listToMaybe) -- | The site argument for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { settings :: AppConfig DefaultEnv Extra , getStatic :: Static -- ^ Settings for static file serving. , connPool :: Database.Persist.Store.PersistConfigPool Settings.PersistConfig -- ^ Database connection pool. , indexPool :: Pool Hs.Database , httpManager :: Manager , persistConfig :: Settings.PersistConfig } -- Set up i18n messages. See the message folder. mkMessage "App" "messages" "en" -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/handler -- -- This function does three things: -- -- * Creates the route datatype AppRoute. Every valid URL in your -- application can be represented as a value of this type. -- * Creates the associated type: -- type instance Route App = AppRoute -- * Creates the value resourcesApp which contains information on the -- resources declared below. This is used in Handler.hs by the call to -- mkYesodDispatch -- -- What this function does *not* do is create a YesodSite instance for -- App. Creating that instance requires all of the handler functions -- for our application to be in scope. However, the handler functions -- usually require access to the AppRoute datatype. Therefore, we -- split these actions into two functions and place them in separate files. mkYesodData "App" $(parseRoutesFile "config/routes") type Form x = Html -> MForm App App (FormResult x, Widget) -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where approot = ApprootMaster $ appRoot . settings -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = do key <- getKey "config/client_session_key.aes" return . Just $ clientSessionBackend key 1440 defaultLayout widget = do master <- getYesod mmsg <- getMessage -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. muser <- maybeAuth pc <- widgetToPageContent $ do $(widgetFile "normalize") menu <- $(widgetFile "menu") addStylesheet $ StaticR css_bootstrap_css addStylesheet $ StaticR css_bootstrap_responsive_css $(widgetFile "default-layout") hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet") -- This is done to provide an optimization for serving static files from -- a separate domain. Please see the staticRoot setting in Settings.hs urlRenderOverride y (StaticR s) = Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s urlRenderOverride _ _ = Nothing -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute []) -- Place Javascript at bottom of the body tag so the rest of the page loads first jsLoader _ = BottomOfBody isAuthorized route isWrite = do mauth <- maybeAuth runDB $ mauth `isAuthorizedTo` permissionsRequiredFor route isWrite -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlPersist runDB f = do master <- getYesod Database.Persist.Store.runPool (persistConfig master) f (connPool master) instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest _ = HomeR -- Where to send a user after logout logoutDest _ = HomeR getAuthId creds = runDB $ do x <- getBy $ UniqueUser $ credsIdent creds case x of Just (Entity uid _) -> return $ Just uid Nothing -> do fmap Just $ insert $ User (credsIdent creds) Nothing -- You can add other plugins like BrowserID, email or OAuth here authPlugins _ = [authBrowserId, authGoogleEmail] authHttpManager = httpManager -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage -- | Get the 'Extra' value, used to hold data from the settings.yml file. getExtra :: Handler Extra getExtra = fmap (appExtra . settings) getYesod data Permission = Post | Edit NoteId | View NoteId | List | PostLink | EditLink LinkId | ViewLink LinkId | EditJournal JournalId permissionsRequiredFor :: Route App -> Bool -> [Permission] permissionsRequiredFor AddR _ = [Post] permissionsRequiredFor NewLinkR _ = [Post] permissionsRequiredFor ListR _ = [List] permissionsRequiredFor ListLinksR _ = [List] permissionsRequiredFor (EditR noteid) _ = [Edit noteid] permissionsRequiredFor (ViewR noteid) _ = [View noteid] permissionsRequiredFor (EditLinkR link) _ = [EditLink link] permissionsRequiredFor (ViewLinkR link) _ = [ViewLink link] permissionsRequiredFor (WriteJournalR journal) _ = [EditJournal journal] permissionsRequiredFor (JournalEditR journal) _ = [EditJournal journal] permissionsRequiredFor (CreateJournalR) _ = [Post] permissionsRequiredFor _ _ = [] hasPermissionTo :: Entity User -> Permission -> YesodDB sub App AuthResult _ `hasPermissionTo` Post = return Authorized _ `hasPermissionTo` PostLink = return Authorized _ `hasPermissionTo` List = return Authorized (Entity userId _) `hasPermissionTo` (EditLink link) = do link' <- select $ from $ \l -> do where_ (l ^. LinkOwner ==. val userId &&. l ^. LinkId ==. val link) return l return $ maybe (Unauthorized "You have no permission to access this link") (const Authorized) (listToMaybe link') user `hasPermissionTo` (ViewLink link) = user `hasPermissionTo` EditLink link (Entity userId _) `hasPermissionTo` (Edit note) = do note' <- select $ from $ \n -> do where_ (n ^. NoteOwner ==. val userId &&. n ^. NoteId ==. val note) return n case note' of [] -> return $ Unauthorized "You have no permission to edit this note" _ -> return Authorized user `hasPermissionTo` (View note) = user `hasPermissionTo` (Edit note) (Entity userId _) `hasPermissionTo` (EditJournal journal) = do journal <- select $ from $ \j -> do where_ (j ^. JournalOwner ==. val userId &&. j ^. JournalId ==. val journal) return j case journal of [] -> return $ Unauthorized "You have no permission to edit this journal" _ -> return Authorized isAuthorizedTo :: Maybe (Entity User) -> [Permission] -> YesodDB sub App AuthResult _ `isAuthorizedTo` [] = return Authorized Nothing `isAuthorizedTo` (_:_) = return AuthenticationRequired Just u `isAuthorizedTo` (p:ps) = do r <- u `hasPermissionTo` p case r of Authorized -> Just u `isAuthorizedTo` ps _ -> return r -- Note: previous versions of the scaffolding included a deliver function to -- send emails. Unfortunately, there are too many different options for us to -- give a reasonable default. Instead, the information is available on the -- wiki: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email
MasseR/introitu
Foundation.hs
bsd-2-clause
8,981
0
18
1,879
1,848
980
868
-1
-1
-- | -- -- Copyright: -- This file is part of the package vimeta. It is subject to the -- license terms in the LICENSE file found in the top-level -- directory of this distribution and at: -- -- https://github.com/pjones/vimeta -- -- No part of this package, including this file, may be copied, -- modified, propagated, or distributed except according to the terms -- contained in the LICENSE file. -- -- License: BSD-2-Clause module Vimeta.UI.CommandLine.TV ( Options, optionsParser, run, ) where import Network.API.TheMovieDB import Options.Applicative import Vimeta.Core import Vimeta.UI.CommandLine.Common import Vimeta.UI.Common.TV import Vimeta.UI.Term.TV data Options = Options { optsTVID :: Maybe ItemID, optsStartSeason :: Maybe Int, optsStartEpisode :: Maybe Int, optsMappingFile :: Maybe FilePath, optsFiles :: [FilePath], optsCommon :: CommonOptions } optionsParser :: Parser Options optionsParser = Options <$> optional (option auto infoTVID) <*> optional (option auto infoStartSeason) <*> optional (option auto infoStartEpisode) <*> optional (strOption infoMappingFile) <*> many (argument str (metavar "[FILE...]")) <*> commonOptions where infoTVID = short 'i' <> long "id" <> metavar "ID" <> help "Series ID assigned by TheMovieDB.org" infoStartSeason = short 's' <> long "season" <> metavar "NUM" <> help "Starting season number" infoStartEpisode = short 'e' <> long "episode" <> metavar "NUM" <> help "Starting episode number" infoMappingFile = short 'm' <> long "map" <> metavar "FILE" <> help "File to map files to seasons/episodes" run :: Options -> IO (Either String ()) run opts = execVimeta (updateConfig $ optsCommon opts) $ do tv <- case optsTVID opts of Nothing -> tvSearch Just n -> tmdb (fetchFullTVSeries n) case optsMappingFile opts of Nothing -> fromFiles opts tv Just fn -> fromMappingFile opts tv fn fromFiles :: (MonadIO m) => Options -> TV -> Vimeta m () fromFiles opts tv = case (optsStartSeason opts, optsStartEpisode opts) of (Just s, Nothing) -> tagWithFileOrder tv (EpisodeSpec s 1) (optsFiles opts) (Just s, Just e) -> tagWithFileOrder tv (EpisodeSpec s e) (optsFiles opts) (_, _) -> throwError "please use the --season option" fromMappingFile :: (MonadIO m) => Options -> TV -> FilePath -> Vimeta m () fromMappingFile opts tv filename = do unless (null $ optsFiles opts) $ throwError "don't give file arguments when using a mapping file" tagWithMappingFile tv filename
pjones/vimeta
src/Vimeta/UI/CommandLine/TV.hs
bsd-2-clause
2,601
0
14
553
688
352
336
55
3
{-# LANGUAGE GADTs #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE RecordWildCards #-} ----------------------------------------------------------------------------- -- | -- Module : HEP.Physics.LoopCalculation.Box -- Copyright : (c) 2013 Ian-Woo Kim -- -- License : GPL-3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module HEP.Physics.LoopCalculation.Box where import Control.Applicative ((<$>),(<*>)) import Control.Monad ((>=>)) import Data.Foldable (msum, foldrM) import Data.List (nub,sort) import qualified Data.Map as M import Data.Maybe (fromJust,mapMaybe) -- import HEP.Physics.LoopCalculation.Graph -- import Debug.Trace data Partition = I2 | I3 | I4 deriving (Show,Eq,Ord) data Comb a b = Comb a b deriving instance (Eq a, Eq b) => Eq (Comb a b) deriving instance (Show a, Show b) => Show (Comb a b) deriving instance (Ord a, Ord b) => Ord (Comb a b) data Externals = Externals { extPtl1 :: External , extPtl2 :: External , extPtl3 :: External , extPtl4 :: External } deriving (Show) data Blob comb = Blob { blobExternals :: Externals , blobComb :: comb } deriving (Show) isValidComb :: Comb Partition Partition -> Bool isValidComb (Comb p1 p2) = p1 /= p2 makePair :: Partition -> (VLabel,VLabel) makePair I2 = (V1,V2) makePair I3 = (V1,V3) makePair I4 = (V1,V4) makePairComplement :: Partition -> (VLabel,VLabel) makePairComplement I2 = (V3,V4) makePairComplement I3 = (V2,V4) makePairComplement I4 = (V2,V3) makeFPair :: (FDir,FDir) -> Partition -> (FLine (),FLine ()) makeFPair (dir1,dir2) p = let n1 = makePair p n2 = makePairComplement p in (FL n1 dir1 (), FL n2 dir2 ()) makeSPair :: (Dir,Dir) -> Partition -> (SLine (),SLine ()) makeSPair (dir1,dir2) p = let n1 = makePair p n2 = makePairComplement p in (SL n1 dir1 (), SL n2 dir2 ()) snumber :: External -> Int snumber (External l d) = let s' = case l of (_, SM_D G2) -> 1 (_, SM_Dc G2) -> -1 _ -> 0 sgn = case d of I -> -1 O -> 1 in sgn * s' deltaS :: Blob a -> Int deltaS (Blob (Externals p1 p2 p3 p4) _) = (sum . map snumber) [p1,p2,p3,p4] quarkCc = (F, SM_Uc G2) quarkC = (F, SM_U G2) quarkSc = (F, SM_Dc G2) quarkS = (F, SM_D G2) quarkUc = (F, SM_Uc G1) quarkU = (F, SM_U G1) quarkDc = (F, SM_Dc G1) quarkD = (F, SM_D G1) leptonMu = (F, SM_E G2) leptonMuc= (F, SM_Ec G2) leptonE = (F, SM_E G1) leptonEc = (F, SM_Ec G1) allcomb = [ x | p1 <- [I2,I3,I4], p2 <- [I2,I3,I4], let x = Comb p1 p2, isValidComb x ] allfline p = [makeFPair (d1,d2) p | d1 <- allfdir, d2 <- allfdir] allsline p = [makeSPair (d1,d2) p | d1 <- alldir, d2 <- alldir ] makeAllCombFromPartition :: Comb Partition Partition -> [Comb (FLine (),FLine ()) (SLine (),SLine ())] makeAllCombFromPartition (Comb p1 p2) = [Comb fpair spair | fpair <- allfline p1, spair <- allsline p2] makeAllBlob :: Blob () -> [Blob (Comb (FLine (),FLine ()) (SLine (),SLine ()))] makeAllBlob (Blob (Externals pt1 pt2 pt3 pt4) ()) = Blob (Externals pt1 pt2 pt3 pt4) <$> [x | c <- allcomb, x <- makeAllCombFromPartition c ] vertexDirection :: Blob (Comb (FLine (),FLine ()) (SLine (), SLine ())) -> VLabel -> (Dir,Dir,Dir) vertexDirection (Blob (Externals p1 p2 p3 p4) (Comb (f1,f2) (s1,s2))) v = let d1 = case v of V1 -> extDir p1 V2 -> extDir p2 V3 -> extDir p3 V4 -> extDir p4 d2 = (fromJust . msum . map (flip fermionVertexDir v)) [f1,f2] d3 = (fromJust . msum . map (flip scalarVertexDir v)) [s1,s2] in (d1,d2,d3) matchDirection :: [(Dir,Dir,Dir)] -> Blob (Comb (FLine (),FLine ()) (SLine (),SLine ())) -> Bool matchDirection dirs blob = all (\x -> (vertexDirection blob x) `elem` dirs) [V1,V2,V3,V4] findVertexEdgeRel :: Blob (Comb (FLine (),FLine ()) (SLine (),SLine ())) -> VLabel -> (VLabel, ((Int,Dir),(Int,Dir))) findVertexEdgeRel (Blob (Externals _ _ _ _) (Comb (f1,f2) (s1,s2))) v = case (hasVertex f1 v, hasVertex s1 v, hasVertex f2 v, hasVertex s2 v) of (Just iof, Just ios, Nothing, Nothing) -> (v,((1,iof),(1,ios))) (Just iof, Nothing, Nothing, Just ios) -> (v,((1,iof),(2,ios))) (Nothing, Just ios, Just iof, Nothing) -> (v,((2,iof),(1,ios))) (Nothing, Nothing, Just iof, Just ios) -> (v,((2,iof),(2,ios))) makeVertexEdgeMap :: Blob (Comb (FLine (),FLine ()) (SLine (),SLine ())) -> M.Map VLabel ((Int,Dir),(Int,Dir)) makeVertexEdgeMap blob = let lst = map (findVertexEdgeRel blob) [V1,V2,V3,V4] in M.fromList lst type MatchF = Either (FLine ()) (FLine (PtlKind Fermion)) type MatchS = Either (SLine ()) (SLine (PtlKind Scalar)) matchFSLines :: ((Int,Dir),(Int,Dir)) -> [Handle] -> Comb (MatchF, MatchF) (MatchS, MatchS) -> Maybe (Comb (MatchF, MatchF) (MatchS, MatchS)) matchFSLines emap hs c = foldrM (matchFSLinesWorker emap) c hs matchFSLinesWorker :: ((Int,Dir),(Int,Dir)) -> Handle -> Comb (MatchF, MatchF) (MatchS, MatchS) -> Maybe (Comb (MatchF, MatchF) (MatchS, MatchS)) matchFSLinesWorker ((i,iof),(j,ios)) (Handle (k1,d1)) c@(Comb (f1,f2) (s1,s2)) = case getSF k1 of S -> if | j == 1 -> case s1 of Left s@(SL (v1,v2) d ()) -> let ms' = if matchVertexSLineDir (ios,d1) s then Just (SL (v1,v2) d k1) else Nothing in maybe Nothing (\s'->Just (Comb (f1,f2) (Right s',s2))) ms' Right s@(SL (v1,v2) d k) -> if matchVertexSLineDir (ios,d1) s && k == k1 then Just c else Nothing | j == 2 -> case s2 of Left s@(SL (v1,v2) d ()) -> let ms' = if matchVertexSLineDir (ios,d1) s then Just (SL (v1,v2) d k1) else Nothing in maybe Nothing (\s'->Just (Comb (f1,f2) (s1,Right s'))) ms' Right s@(SL (v1,v2) d k) -> if matchVertexSLineDir (ios,d1) s && k == k1 then Just c else Nothing | otherwise -> (error "error in matchFSLines") F -> if | i == 1 -> case f1 of Left f@(FL (v1,v2) d ()) -> do k' <- getFermionKind iof d k1 f' <- if matchVertexFLineDir (iof,d1) f then return (FL (v1,v2) d k') else Nothing return (Comb (Right f',f2) (s1,s2)) Right f@(FL (v1,v2) d k) -> do k' <- getFermionKind iof d k1 if matchVertexFLineDir (iof,d1) f && k == k' then return c else Nothing | i == 2 -> case f2 of Left f@(FL (v1,v2) d ()) -> do k' <- getFermionKind iof d k1 f' <- if matchVertexFLineDir (iof,d1) f then return (FL (v1,v2) d k') else Nothing return (Comb (f1,Right f') (s1,s2)) Right f@(FL (v1,v2) d k) -> do k' <- getFermionKind iof d k1 if matchVertexFLineDir (iof,d1) f && k == k' then return c else Nothing | otherwise -> (error "error in matchFSLines") liftComb :: Comb (FLine (),FLine ()) (SLine (),SLine ()) -> Comb (MatchF, MatchF) (MatchS, MatchS) liftComb (Comb (f1,f2) (s1,s2)) = Comb (Left f1, Left f2) (Left s1, Left s2) data HandleSet = HandleSet { hsetVtx1Int :: [[Handle]] , hsetVtx2Int :: [[Handle]] , hsetVtx3Int :: [[Handle]] , hsetVtx4Int :: [[Handle]] } prepareHandleSet :: [SuperPot3] -> Externals -> HandleSet prepareHandleSet superpot externals = let vertexFFSwoGen = concatMap superpot3toVertexFFS superpot vertexFFSwGen = concatMap assignGenToVertexFFS vertexFFSwoGen (e1,e2,e3,e4) = ((,,,) <$> extPtl1 <*> extPtl2 <*> extPtl3 <*> extPtl4) externals vset1 = (nub . map (map replaceInternalToGAll . sort . snd) . selectVertexForExt e1) vertexFFSwGen vset2 = (nub . map (map replaceInternalToGAll . sort . snd) . selectVertexForExt e2) vertexFFSwGen vset3 = (nub . map (map replaceInternalToGAll . sort . snd) . selectVertexForExt e3) vertexFFSwGen vset4 = (nub . map (map replaceInternalToGAll . sort . snd) . selectVertexForExt e4) vertexFFSwGen in HandleSet { hsetVtx1Int = vset1 , hsetVtx2Int = vset2 , hsetVtx3Int = vset3 , hsetVtx4Int = vset4 } match :: HandleSet -> Blob (Comb (FLine (), FLine ()) (SLine (), SLine ())) -> [Comb (MatchF, MatchF) (MatchS, MatchS)] match HandleSet{..} b@(Blob e c) = let vemap = makeVertexEdgeMap b Just e1 = M.lookup V1 vemap Just e2 = M.lookup V2 vemap Just e3 = M.lookup V3 vemap Just e4 = M.lookup V4 vemap lc = liftComb c allhsets = [(h1,h2,h3,h4)| h1<-hsetVtx1Int, h2<-hsetVtx2Int, h3<-hsetVtx3Int, h4<-hsetVtx4Int] matchForOneHandleCombination (h1',h2',h3',h4') = (matchFSLines e1 h1' >=> matchFSLines e2 h2' >=> matchFSLines e3 h3' >=> matchFSLines e4 h4') lc lst = mapMaybe matchForOneHandleCombination allhsets in lst
wavewave/loopdiagram
src/HEP/Physics/LoopCalculation/Box.hs
bsd-3-clause
9,714
0
22
2,944
4,142
2,230
1,912
193
18
-- | Brand/Box-validation module Data.ByteString.IsoBaseFileFormat.MediaFile where import Data.ByteString.IsoBaseFileFormat.ReExports import Data.ByteString.IsoBaseFileFormat.Util.BoxContent -- TODO move this to general module merge with Box.hs -- | A class that describes (on the type level) how a box can be nested into -- other boxes (see 'Boxes). class IsMediaFileFormat brand where -- | The layout that an IsBoxContent instance has to have, before 'packMedia' accepts it type BoxLayout brand mediaBuilder :: forall t proxy. (IsBoxContent t, IsRuleConform t (BoxLayout brand) ~ 'True) => proxy brand -> t -> Builder mediaBuilder _ t = boxBuilder t
sheyll/isobmff-builder
src/Data/ByteString/IsoBaseFileFormat/MediaFile.hs
bsd-3-clause
684
0
13
122
106
62
44
-1
-1
module Main where import System.IO import Control.Monad.Reader import DiceGame import ConsolePlay main :: IO () main = do putStr "How big a board do you want? " hFlush stdout sizeS <- getLine putStr "What should the maximum dice on a cell be? " hFlush stdout diceS <- getLine putStrLn "playing against the computer?" hFlush stdout cpuS <- getLine case cpuS of "y" -> do let sz = read sizeS :: Int d = read diceS :: Int gs = buildGS 2 sz d brd <- generateBoard gs let startingTree = runReader (buildTree brd 0 0 True Nothing) gs playVsComputer gs startingTree _ -> do putStrLn "How many players?" hFlush stdout playerS <- getLine let sz = read sizeS :: Int d = read diceS :: Int p = read playerS :: Int gs = buildGS p sz d l = sz * sz putStr $ "Creating a board that has " ++ show l ++ " cells with " ++ show p ++ " players and up to " ++ show d ++ " dice per cell\n" brd <- generateBoard gs let startingTree = runReader (buildTree brd 0 0 True Nothing) gs playVsHuman gs startingTree
smithhmark/dice-game
app/Main.hs
bsd-3-clause
1,392
0
18
603
359
166
193
38
2
module ArbiRef where import qualified Data.IntMap as IM import Logic import GenState import BruijnEnvironment import FreeEnvironment import Name class ArbiRef n where updateState :: GenState n -> Bool -> String -> Free -> GenState n refFromState :: GenState n -> Generater (n, Free) instance ArbiRef Bound where updateState = updateStateBound refFromState = boundFromState instance ArbiRef Name where updateState = updateStateName refFromState = nameFromState -- TODO decouple bruijnMap boundFromState :: GenState Bound -> Generater (Bound, Free ) boundFromState s = do (i, (_, f)) <- elementsLogic $ bToList $ tEnv s return (Bound (bruijnDepth (tEnv s ) - i - 1), f) updateStateBound :: GenState n -> Bool -> String -> Free -> GenState n updateStateBound state _ name free = state {tEnv = newTEnv} where newTEnv = bInsert (name, free) (tEnv state) nameFromState :: GenState Name -> Generater (Name, Free ) nameFromState s = do (_, (name, f)) <- elementsLogic $ bToList $ tEnv s return (Name name, f) -- TODO remove bool always remove name from list? updateStateName :: GenState n -> Bool -> String -> Free -> GenState n updateStateName state@State {tEnv = env } newVar name free = state {tEnv = newTEnv} where newTEnv :: BruijnEnv (String, Free) newTEnv = bInsert (name, free) (if newVar then removeVar name env else env) -- TODO decouple bruijnMap removeVar :: String -> BruijnEnv (String, b) -> BruijnEnv (String, b) removeVar varname env = env {bruijnMap = fst $ IM.partition (\ var -> fst var == varname) (bruijnMap env)}
kwibus/myLang
tests/ArbiRef.hs
bsd-3-clause
1,616
0
15
337
554
296
258
35
2
{-# LANGUAGE ScopedTypeVariables #-} import qualified Zora.List as ZList import qualified Zora.Math as ZMath import qualified Data.Ord as Ord import qualified Data.List as List import Data.Maybe import Control.Applicative num_solutions :: Integer -> Integer num_solutions = ZMath.num_divisors_of_n_squared_leq_n sought :: Integer sought = fromJust . List.find ((> 1000) . num_solutions) $ [2..] main :: IO () main = do putStrLn . show $ sought
bgwines/project-euler
src/solved/problem108.hs
bsd-3-clause
455
2
10
73
125
75
50
17
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Lib.Console where import Control.Applicative ((<|>)) import qualified Control.Concurrent.MVar as MVar import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar (TVar, modifyTVar) import Control.Monad (forever) import Data.Monoid ((<>)) import qualified Data.Text as T import qualified Data.Text.IO as TIO import qualified Network.URI as URI import System.Exit (exitSuccess) import qualified System.IO as IO import Control.Lens (over, set) import Lib.Types (RuntimeOptions, ParseError, enableEmptyPlaylist, overrideMasterPlaylist, showRuntimeOptions) import qualified Text.Megaparsec as M import qualified Text.Megaparsec.Text as M data CLICommand = CmdQuit | CmdToggleEmpty | CmdShow | CmdOverride (Maybe URI.URI) | CmdUnknown (Maybe ParseError) deriving (Show, Eq) cliCommandParser :: M.Parser CLICommand cliCommandParser = p "quit" CmdQuit <|> p "empty" CmdToggleEmpty <|> p "show" CmdShow <|> overrideParser where p :: String -> a -> M.Parser a p [] _ = fail "Invalid CLI pattern." p token@(t:_) cmd = (M.try (M.char t *> M.eof) <|> (M.string token *> M.eof)) *> pure cmd overrideParser :: M.Parser CLICommand overrideParser = do _ <- M.try (M.char 'o' *> M.space) <|> (M.string "override" *> M.space) CmdOverride . URI.parseURI <$> M.manyTill M.printChar M.eof parseCLICommand :: T.Text -> CLICommand parseCLICommand input = case M.parse cliCommandParser "<input>" input of Right cmd -> cmd Left err -> CmdUnknown $ pure err interpret :: MVar.MVar () -> TVar RuntimeOptions -> CLICommand -> IO () interpret poison ropts = \case CmdQuit -> MVar.putMVar poison () >> exitSuccess CmdToggleEmpty -> atomically $ modifyTVar ropts (over enableEmptyPlaylist not) CmdOverride o -> atomically $ modifyTVar ropts (set overrideMasterPlaylist o) CmdShow -> TIO.putStrLn =<< atomically (showRuntimeOptions ropts) CmdUnknown Nothing -> TIO.putStrLn "!! Unknown Command" CmdUnknown (Just err) -> TIO.putStrLn $ "!! Error: " <> T.pack (show err) consoleThread :: MVar.MVar () -> TVar RuntimeOptions -> IO () consoleThread poison ropts = forever $ do putStr "> " IO.hFlush IO.stdout interpret poison ropts =<< parseCLICommand <$> TIO.getLine
passy/hls-proxy
src/Lib/Console.hs
bsd-3-clause
2,883
0
15
932
764
404
360
61
6
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} module Numeric.Basics ( -- * Constants pattern M_E, pattern M_LOG2E, pattern M_LOG10E, pattern M_LN2, pattern M_LN10 , pattern M_SQRT2, pattern M_SQRT1_2 , pattern M_PI, pattern M_PI_2, pattern M_PI_3, pattern M_PI_4 , pattern M_1_PI, pattern M_2_PI, pattern M_2_SQRTPI , Epsilon (..), pattern M_EPS -- * Functions , RealExtras (..), RealFloatExtras (..) , negateUnless -- * Exceptions , IterativeMethod, TooManyIterations, tooManyIterations ) where import Data.Int import Data.Word import GHC.Exception import GHC.Stack import Numeric.PrimBytes -- | \( e \) pattern M_E :: (Eq a, Fractional a) => Fractional a => a pattern M_E = 2.718281828459045235360287471352662498 -- | \( \log_2 e \) pattern M_LOG2E :: (Eq a, Fractional a) => Fractional a => a pattern M_LOG2E = 1.442695040888963407359924681001892137 -- | \( \log_{10} e \) pattern M_LOG10E :: (Eq a, Fractional a) => Fractional a => a pattern M_LOG10E = 0.434294481903251827651128918916605082 -- | \( \log_e 2 \) pattern M_LN2 :: (Eq a, Fractional a) => Fractional a => a pattern M_LN2 = 0.693147180559945309417232121458176568 -- | \( \log_e 10 \) pattern M_LN10 :: (Eq a, Fractional a) => Fractional a => a pattern M_LN10 = 2.302585092994045684017991454684364208 -- | \( \sqrt{2} \) pattern M_SQRT2 :: (Eq a, Fractional a) => Fractional a => a pattern M_SQRT2 = 1.414213562373095048801688724209698079 -- | \( \frac{1}{\sqrt{2}} \) pattern M_SQRT1_2 :: (Eq a, Fractional a) => Fractional a => a pattern M_SQRT1_2 = 0.707106781186547524400844362104849039 -- | \( \pi \) pattern M_PI :: (Eq a, Fractional a) => Fractional a => a pattern M_PI = 3.1415926535897932384626433832795028841971 -- | \( \frac{\pi}{2} \) pattern M_PI_2 :: (Eq a, Fractional a) => Fractional a => a pattern M_PI_2 = 1.570796326794896619231321691639751442 -- | \( \frac{\pi}{3} \) pattern M_PI_3 :: (Eq a, Fractional a) => Fractional a => a pattern M_PI_3 = 1.047197551196597746154214461093167628 -- | \( \frac{\pi}{4} \) pattern M_PI_4 :: (Eq a, Fractional a) => Fractional a => a pattern M_PI_4 = 0.785398163397448309615660845819875721 -- | \( \frac{1}{\pi} \) pattern M_1_PI :: (Eq a, Fractional a) => Fractional a => a pattern M_1_PI = 0.318309886183790671537767526745028724 -- | \( \frac{2}{\pi} \) pattern M_2_PI :: (Eq a, Fractional a) => Fractional a => a pattern M_2_PI = 0.636619772367581343075535053490057448 -- | \( \frac{2}{\sqrt{\pi}} \) pattern M_2_SQRTPI :: (Eq a, Fractional a) => Fractional a => a pattern M_2_SQRTPI = 1.128379167095512573896158903121545172 -- | Define a meaningful precision for complex floating-point operations. class (Eq a, Floating a) => Epsilon a where -- | A small positive number that depends on the type of @a@. -- Compare your values to @epsilon@ to tell if they are near zero. epsilon :: a instance Epsilon Double where epsilon = 1e-12 instance Epsilon Float where epsilon = 1e-6 -- | A small positive number that depends on the type of @a@. pattern M_EPS :: Epsilon a => a pattern M_EPS <- ((epsilon ==) -> True) where M_EPS = epsilon -- | Negate if @False@. -- This is a useful alternative to `signum`, -- when @signum 0 == 0@ causing some troubles. negateUnless :: Num t => Bool -> t -> t negateUnless True = id negateUnless False = negate {-# INLINE negateUnless #-} -- | Extra functions for `Real` types. class (Real a, PrimBytes a) => RealExtras a where -- | @copysign x y@ returns a value with the magnitude of x and the sign of y. -- -- NB: in future, this function is to reimplemented using primops -- and should behave the same way as its C analogue. copysign :: a -> a -> a copysign x y | (x >= 0) == (y >= 0) = x | otherwise = negate x {-# INLINE copysign #-} instance RealExtras Int instance RealExtras Int8 instance RealExtras Int16 instance RealExtras Int32 instance RealExtras Int64 instance RealExtras Word instance RealExtras Word8 instance RealExtras Word16 instance RealExtras Word32 instance RealExtras Word64 instance RealExtras Float where copysign = c'copysignf {-# INLINE copysign #-} instance RealExtras Double where copysign = c'copysignd {-# INLINE copysign #-} -- | Extra functions for `RealFrac` types. class (Epsilon a, RealExtras a, RealFloat a) => RealFloatExtras a where -- | \( \sqrt{ x^2 + y^2 } \). -- -- NB: in future, this function is to reimplemented using primops -- and should behave the same way as its C analogue. hypot :: a -> a -> a hypot x y = scaleFloat ea (sqrt (an*an + bn*bn)) where x' = abs x y' = abs y (a,b) = if x' >= y' then (x', y') else (y', x') (_, ea) = decodeFloat a an = scaleFloat (negate ea) a bn = scaleFloat (negate ea) b {-# INLINE hypot #-} -- | Maximum finite number representable by this FP type. maxFinite :: a instance RealFloatExtras Float where hypot = c'hypotf {-# INLINE hypot #-} maxFinite = 3.40282347e+38 {-# INLINE maxFinite #-} instance RealFloatExtras Double where hypot = c'hypotd {-# INLINE hypot #-} maxFinite = 1.7976931348623157e+308 {-# INLINE maxFinite #-} foreign import ccall unsafe "hypot" c'hypotd :: Double -> Double -> Double foreign import ccall unsafe "hypotf" c'hypotf :: Float -> Float -> Float foreign import ccall unsafe "copysign" c'copysignd :: Double -> Double -> Double foreign import ccall unsafe "copysignf" c'copysignf :: Float -> Float -> Float {- | This is just an alias for the `HasCallStack` constraint. It servers two goals: 1. Document functions that use iterative methods and can fail (supposedly in extremely rare cases). 2. Provide a call stack in case of failure. Use `tooManyIterations` function where necessary if you implement an iterative algorithm and annotate your implementation function with `IterativeMethod` constraint. -} type IterativeMethod = HasCallStack -- | Throw a `TooManyIterations` exception. tooManyIterations :: IterativeMethod => String -- ^ Label (e.g. function name) -> a tooManyIterations s = throw TooManyIterations { tmiUserInfo = s , tmiCallStack = callStack } {- | Typically, this exception can occur in an iterative algorithm; when the number of iterations exceeds a pre-defined limit, but the stop condition is not fulfilled. Use the `IterativeMethod` constraint to annotate functions that throw this exception. -} data TooManyIterations = TooManyIterations { tmiUserInfo :: String -- ^ Short description of the error, e.g. a function name. , tmiCallStack :: CallStack -- ^ Function call stack. -- Note, this field is ignored in the `Eq` and `Ord` instances. } -- | Note, this instance ignores `oodCallStack` instance Eq TooManyIterations where (==) a b = tmiUserInfo a == tmiUserInfo b -- | Note, this instance ignores `oodCallStack` instance Ord TooManyIterations where compare a b = compare (tmiUserInfo a) (tmiUserInfo b) instance Show TooManyIterations where showsPrec p e = addLoc errStr where addLoc s = let someE = errorCallWithCallStackException s (tmiCallStack e) errc :: ErrorCall errc = case fromException someE of Nothing -> ErrorCall s Just ec -> ec in showsPrec p errc errStr = unlines [ "An iterative method has exceeded the limit for the iteration number." , "User info: " ++ tmiUserInfo e ] instance Exception TooManyIterations
achirkin/easytensor
easytensor/src/Numeric/Basics.hs
bsd-3-clause
7,689
0
15
1,640
1,586
859
727
138
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} module Webcrank.Internal.HandleRequest where import qualified Blaze.ByteString.Builder as BB import qualified Blaze.ByteString.Builder.Char.Utf8 as BB import Control.Applicative import Control.Lens import Control.Monad.Catch import Control.Monad.Reader import Control.Monad.RWS import Control.Monad.Trans.Maybe import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.UTF8 as LB import Data.Foldable (traverse_) import Network.HTTP.Media import Network.HTTP.Types import Prelude import Webcrank.Internal.DecisionCore import Webcrank.Internal.Halt import Webcrank.Internal.Headers import Webcrank.Internal.Types import Webcrank.Internal.ReqData import Webcrank.Internal.ResourceData -- | Process a request according to the webmachine state diagram. Intended for -- use by server API providers. @run@ is a function which can run process to -- completion. -- -- @'Webcrank.ServerAPI.WebcrankT'@ is provided as a starting point. For the type -- -- @ -- type WaiCrank = ReaderT (Request, HTTPDate) (WebcrankT IO) -- @ -- -- an appropriate @run@ function would be -- -- @ -- run :: Resource WaiCrank -> Request -> HTTPDate -> WaiCrank a -> IO (a, ReqData, LogData) -- run resource req date wa = runReaderT (runWebcrankT wa (ResourceData api resource) newReqData) (req, date) -- @ handleRequest :: (Applicative m, MonadReader r m, HasResourceData r m, MonadState s m, HasReqData s, MonadCatch m, Functor n) => (forall a. m a -> n (a, ReqData, LogData)) -- ^ run -> n (Status, HeadersMap, Maybe Body) handleRequest run = run handler <&> finish where handler = (decisionCore <* callr'' finishRequest) `catch` handleError decisionCore = runHaltT (runFlowChart b13) >>= \case Left (Error s rs) -> s <$ prepError s rs Left (Halt s) -> s <$ prepResponse s Right s -> s <$ prepResponse s -- TODO log decision states finish (s, d, _) = (s, _reqDataRespHeaders d, _reqDataRespBody d) prepResponse :: (Applicative m, MonadReader r m, HasResourceData r m, MonadState s m, HasReqData s) => Status -> m () prepResponse s = case statusCode s of c | c >= 400 && c < 600 -> prepError s (LB.fromStrict $ statusMessage s) 304 -> do removeResponseHeader hContentType reqDataRespBody .= Nothing let header h rm = traverse_ (putResponseHeader h . renderHeader) =<< callr'' (runMaybeT . rm) header hETag generateETag header hExpires expires _ -> return () -- TODO make it customizable prepError :: (Applicative m, MonadReader r m, HasResourceData r m, MonadState s m, HasReqData s) => Status -> LB.ByteString -> m () prepError s r = assign reqDataRespBody . Just =<< encodeBody' =<< renderError s r handleError :: (Applicative m, MonadReader r m, HasResourceData r m, MonadState s m, HasReqData s) => SomeException -> m Status handleError = (internalServerError500 <$) . prepError internalServerError500 . LB.fromString . show renderError :: (Applicative m, MonadReader r m, HasResourceData r m, MonadState s m, HasReqData s) => Status -> LB.ByteString -> m Body renderError s reason = maybe (render s reason) return =<< use reqDataRespBody where render :: (Functor m, HasReqData s, HasResourceData r m, MonadReader r m, MonadState s m) => Status -> LB.ByteString -> m LB.ByteString render s reason = putResponseHeader hContentType "text/html" >> (errorBody s reason) errorBody :: (Functor m, HasResourceData r m, MonadReader r m) => Status -> LB.ByteString -> m LB.ByteString errorBody s reason = case statusCode s of 404 -> return "<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1>The requested document was not found on this server.<p><hr><address>webcrank web server</address></body></html>" 500 -> return $ mconcat [ "<html><head><title>500 Internal Server Error</title></head><body><h1>Internal Server Error</h1>The server encountered an error while processing this request:<br><pre>" , reason , "</pre><p><hr><address>webcrank web server</address></body></html>" ] 501 -> getRequestMethod' <&> \m -> mconcat [ "<html><head><title>501 Not Implemented</title></head><body><h1>Not Implemented</h1>The server does not support the " , LB.fromStrict m , " method.<br><p><hr><address>webmachine web server</address></body></html>" ] 503 -> return "<html><head><title>503 Service Unavailable</title></head><body><h1>Service Unavailable</h1>The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.<br><p><hr><address>webcrank web server</address></body></html>" _ -> return $ BB.toLazyByteString $ mconcat [ BB.fromByteString "<html><head><title>" , BB.fromShow $ statusCode s , BB.fromByteString " " , BB.fromByteString $ statusMessage s , BB.fromByteString "</title></head><body><h1>" , BB.fromByteString $ statusMessage s , BB.fromByteString "</h2>" , BB.fromLazyByteString reason , BB.fromByteString "<p><hr><address>webcrank web server</address></body></html>" ]
webcrank/webcrank.hs
src/Webcrank/Internal/HandleRequest.hs
bsd-3-clause
5,173
0
17
895
1,193
633
560
98
5
{-# LANGUAGE OverloadedStrings #-} -- | Handles parsing of both infix and RPN 'Pred' expressions. module Prednote.Expressions ( ExprDesc(..) , Error , Token , operand , opAnd , opOr , opNot , openParen , closeParen , parseExpression ) where import Data.Either (partitionEithers) import qualified Data.Text as X import qualified Prednote.Expressions.Infix as I import qualified Prednote.Expressions.RPN as R import Prednote.Core import qualified Prelude import Prelude hiding (maybe) -- | A single type for both RPN tokens and infix tokens. newtype Token m a = Token { unToken :: I.InfixToken m a } type Error = X.Text -- | Creates Operands from 'Pred'. operand :: PredM m a -> Token m a operand p = Token (I.TokRPN (R.TokOperand p)) -- | The And operator opAnd :: Token m a opAnd = Token (I.TokRPN (R.TokOperator R.OpAnd)) -- | The Or operator opOr :: Token m a opOr = Token (I.TokRPN (R.TokOperator R.OpOr)) -- | The Not operator opNot :: Token m a opNot = Token (I.TokRPN (R.TokOperator R.OpNot)) -- | Open parentheses openParen :: Token m a openParen = Token (I.TokParen I.Open) -- | Close parentheses closeParen :: Token m a closeParen = Token (I.TokParen I.Close) -- | Is this an infix or RPN expression? data ExprDesc = Infix | RPN deriving (Eq, Show) toksToRPN :: [Token m a] -> Maybe [R.RPNToken m a] toksToRPN toks = let toEither t = case unToken t of I.TokRPN tok -> Right tok _ -> Left () in case partitionEithers . map toEither $ toks of ([], xs) -> return xs _ -> Nothing -- | Parses expressions. Fails if the expression is nonsensical in -- some way (for example, unbalanced parentheses, parentheses in an -- RPN expression, or multiple stack values remaining.) Works by first -- changing infix expressions to RPN ones. parseExpression :: (Functor m, Monad m) => ExprDesc -> [Token m a] -> Either Error (PredM m a) parseExpression e toks = do rpnToks <- case e of Infix -> Prelude.maybe (Left "unbalanced parentheses\n") Right . I.createRPN . map unToken $ toks RPN -> Prelude.maybe (Left "parentheses in an RPN expression\n") Right $ toksToRPN toks R.parseRPN rpnToks
massysett/prednote
lib/Prednote/Expressions.hs
bsd-3-clause
2,236
0
16
507
633
340
293
59
3
module Main where import Sirea.Prelude main = runSireaApp $ record |*| report record = btickOfFreq 3 >>> bsplitOn even >>> bleft (bconst () >>> btimeStamp "r") report = btimeStampMon "r" >>> bprint
dmbarbour/Sirea
tst/TimeStamp.hs
bsd-3-clause
205
0
10
39
71
36
35
5
1
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving, ViewPatterns, RecordWildCards #-} module AbstractInterpretation.LiveVariable.Result where import Lens.Micro.Platform import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Data.Vector (Vector) import qualified Data.Vector as V import qualified Data.Bimap as Bimap import Grin.Grin (Name, Tag) import AbstractInterpretation.LiveVariable.CodeGen (LVAMapping) import AbstractInterpretation.IR hiding (Tag) import qualified AbstractInterpretation.Reduce as R type LivenessId = Int32 data Node = Node { _tag :: Bool , _fields :: Vector Bool } deriving (Eq, Ord, Show) data Liveness = BasicVal Bool | NodeSet (Map Tag Node) deriving (Eq, Ord, Show) newtype Effect = Effect { _hasEffect :: Bool } deriving (Eq, Ord, Show) data LVAResult = LVAResult { _memory :: Vector Liveness , _registerLv :: Map Name Liveness , _functionLv :: Map Name (Liveness, Vector Liveness) , _registerEff :: Map Name Effect , _functionEff :: Map Name Effect } deriving (Eq, Show) emptyLVAResult :: LVAResult emptyLVAResult = LVAResult mempty mempty mempty mempty mempty concat <$> mapM makeLenses [''Node, ''Liveness, ''LVAResult] isNodeLive :: Node -> Bool isNodeLive = (||) <$> hasLiveTag <*> hasLiveField hasLiveTag :: Node -> Bool hasLiveTag (Node tagLv fieldsLv) = tagLv hasLiveField :: Node -> Bool hasLiveField (Node tagLv fieldsLv) = or fieldsLv isLive :: Liveness -> Bool isLive (BasicVal b) = b isLive (NodeSet m) = any isNodeLive m hasLiveArgs :: (Liveness, Vector Liveness) -> Bool hasLiveArgs (_, argsLv) = any isLive argsLv -- | A function is only dead if its return value is dead -- , and all of its parameters are dead as well. The case -- when the return value is dead, but there is a live parameter -- means that the function has some kind of side effect. isFunDead :: (Liveness, Vector Liveness) -> Bool isFunDead (retLv, argsLv) = not (isLive retLv || any isLive argsLv) toLVAResult :: LVAMapping -> R.ComputerState -> LVAResult toLVAResult AbstractMapping{..} R.ComputerState{..} = LVAResult { _memory = V.map convertHeapNodeSet _memory , _registerLv = Map.map convertRegLv _absRegisterMap , _functionLv = Map.map convertFunctionRegs _absFunctionArgMap , _registerEff = Map.map convertRegEff _absRegisterMap , _functionEff = Map.map convertFunctionEffect _absFunctionArgMap } where isLive :: Set LivenessId -> Bool isLive = Set.member (-1) hasEffect :: Set LivenessId -> Bool hasEffect = Set.member (-2) convertReg :: (R.Value -> a) -> Reg -> a convertReg convertValue (Reg i) = convertValue $ _register V.! (fromIntegral i) convertRegLv :: Reg -> Liveness convertRegLv = convertReg convertValueLv convertRegEff :: Reg -> Effect convertRegEff = convertReg convertValueEff -- we can encounter empty node sets on the heap convertHeapNodeSet :: R.NodeSet -> Liveness convertHeapNodeSet rns@(R.NodeSet ns) | Map.null ns = BasicVal False | otherwise = convertNodeSet rns convertFields :: V.Vector (Set LivenessId) -> Node convertFields vec = Node (isLive tagLv) (V.map isLive fieldsLv) where (tagLv, fieldsLv) = (,) <$> V.head <*> V.tail $ vec convertNodeSet :: R.NodeSet -> Liveness convertNodeSet (R.NodeSet ns) = NodeSet $ Map.mapKeys fromIR irTaggedMap where irTaggedMap = Map.map convertFields ns fromIR irTag = _absTagMap Bimap.!> irTag convertValueLv :: R.Value -> Liveness convertValueLv (R.Value vals ns) | Map.null . R._nodeTagMap $ ns = BasicVal (isLive vals) | otherwise = convertNodeSet ns convertFunctionRegs :: (Reg, [Reg]) -> (Liveness, Vector Liveness) convertFunctionRegs (Reg retReg, argRegs) = (convertValueLv $ _register V.! (fromIntegral retReg), V.fromList [convertValueLv $ _register V.! (fromIntegral argReg) | Reg argReg <- argRegs]) convertValueEff :: R.Value -> Effect convertValueEff (R.Value vals _) = Effect (hasEffect vals) convertFunctionEffect :: (Reg, [Reg]) -> Effect convertFunctionEffect (retReg, _) = convertRegEff retReg
andorp/grin
grin/src/AbstractInterpretation/LiveVariable/Result.hs
bsd-3-clause
4,209
0
12
803
1,266
683
583
87
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ExplicitNamespaces #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE StandaloneKindSignatures #-} {-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Type.Equality -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : not portable -- -- Definition of propositional equality @(':~:')@. Pattern-matching on a variable -- of type @(a ':~:' b)@ produces a proof that @a '~' b@. -- -- @since 4.7.0.0 ----------------------------------------------------------------------------- module Data.Type.Equality ( -- * The equality types (:~:)(..), type (~~), (:~~:)(..), -- * Working with equality sym, trans, castWith, gcastWith, apply, inner, outer, -- * Inferring equality from other types TestEquality(..), -- * Boolean type-level equality type (==) ) where import Data.Maybe import GHC.Enum import GHC.Show import GHC.Read import GHC.Base import Data.Type.Bool infix 4 :~:, :~~: -- | Propositional equality. If @a :~: b@ is inhabited by some terminating -- value, then the type @a@ is the same as the type @b@. To use this equality -- in practice, pattern-match on the @a :~: b@ to get out the @Refl@ constructor; -- in the body of the pattern-match, the compiler knows that @a ~ b@. -- -- @since 4.7.0.0 data a :~: b where -- See Note [The equality types story] in TysPrim Refl :: a :~: a -- with credit to Conal Elliott for 'ty', Erik Hesselink & Martijn van -- Steenbergen for 'type-equality', Edward Kmett for 'eq', and Gabor Greif -- for 'type-eq' -- | Symmetry of equality sym :: (a :~: b) -> (b :~: a) sym Refl = Refl -- | Transitivity of equality trans :: (a :~: b) -> (b :~: c) -> (a :~: c) trans Refl Refl = Refl -- | Type-safe cast, using propositional equality castWith :: (a :~: b) -> a -> b castWith Refl x = x -- | Generalized form of type-safe cast using propositional equality gcastWith :: (a :~: b) -> ((a ~ b) => r) -> r gcastWith Refl x = x -- | Apply one equality to another, respectively apply :: (f :~: g) -> (a :~: b) -> (f a :~: g b) apply Refl Refl = Refl -- | Extract equality of the arguments from an equality of applied types inner :: (f a :~: g b) -> (a :~: b) inner Refl = Refl -- | Extract equality of type constructors from an equality of applied types outer :: (f a :~: g b) -> (f :~: g) outer Refl = Refl -- | @since 4.7.0.0 deriving instance Eq (a :~: b) -- | @since 4.7.0.0 deriving instance Show (a :~: b) -- | @since 4.7.0.0 deriving instance Ord (a :~: b) -- | @since 4.7.0.0 deriving instance a ~ b => Read (a :~: b) -- | @since 4.7.0.0 instance a ~ b => Enum (a :~: b) where toEnum 0 = Refl toEnum _ = errorWithoutStackTrace "Data.Type.Equality.toEnum: bad argument" fromEnum Refl = 0 -- | @since 4.7.0.0 deriving instance a ~ b => Bounded (a :~: b) -- | Kind heterogeneous propositional equality. Like ':~:', @a :~~: b@ is -- inhabited by a terminating value if and only if @a@ is the same type as @b@. -- -- @since 4.10.0.0 type (:~~:) :: k1 -> k2 -> Type data a :~~: b where HRefl :: a :~~: a -- | @since 4.10.0.0 deriving instance Eq (a :~~: b) -- | @since 4.10.0.0 deriving instance Show (a :~~: b) -- | @since 4.10.0.0 deriving instance Ord (a :~~: b) -- | @since 4.10.0.0 deriving instance a ~~ b => Read (a :~~: b) -- | @since 4.10.0.0 instance a ~~ b => Enum (a :~~: b) where toEnum 0 = HRefl toEnum _ = errorWithoutStackTrace "Data.Type.Equality.toEnum: bad argument" fromEnum HRefl = 0 -- | @since 4.10.0.0 deriving instance a ~~ b => Bounded (a :~~: b) -- | This class contains types where you can learn the equality of two types -- from information contained in /terms/. Typically, only singleton types should -- inhabit this class. class TestEquality f where -- | Conditionally prove the equality of @a@ and @b@. testEquality :: f a -> f b -> Maybe (a :~: b) -- | @since 4.7.0.0 instance TestEquality ((:~:) a) where testEquality Refl Refl = Just Refl -- | @since 4.10.0.0 instance TestEquality ((:~~:) a) where testEquality HRefl HRefl = Just Refl infix 4 == -- | A type family to compute Boolean equality. type (==) :: k -> k -> Bool type family a == b where f a == g b = f == g && a == b a == a = 'True _ == _ = 'False -- The idea here is to recognize equality of *applications* using -- the first case, and of *constructors* using the second and third -- ones. It would be wonderful if GHC recognized that the -- first and second cases are compatible, which would allow us to -- prove -- -- a ~ b => a == b -- -- but it (understandably) does not. -- -- It is absolutely critical that the three cases occur in precisely -- this order. In particular, if -- -- a == a = 'True -- -- came first, then the type application case would only be reached -- (uselessly) when GHC discovered that the types were not equal. -- -- One might reasonably ask what's wrong with a simpler version: -- -- type family (a :: k) == (b :: k) where -- a == a = True -- a == b = False -- -- Consider -- data Nat = Zero | Succ Nat -- -- Suppose I want -- foo :: (Succ n == Succ m) ~ True => ((n == m) :~: True) -- foo = Refl -- -- This would not type-check with the simple version. `Succ n == Succ m` -- is stuck. We don't know enough about `n` and `m` to reduce the family. -- With the recursive version, `Succ n == Succ m` reduces to -- `Succ == Succ && n == m`, which can reduce to `'True && n == m` and -- finally to `n == m`.
sdiehl/ghc
libraries/base/Data/Type/Equality.hs
bsd-3-clause
6,060
0
11
1,306
1,003
596
407
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} module Development.Shake.Install.Exceptions ( setDefaultUncaughtExceptionHandler ) where import Control.Exception (Exception(..), SomeException(..)) import Data.IORef (IORef, newIORef, writeIORef) import Data.Typeable (Typeable) import GHC.Conc (setUncaughtExceptionHandler) import System.IO (hPutStrLn, stderr) import System.IO.Unsafe (unsafePerformIO) import System.Posix.Signals (raiseSignal, sigABRT) -- | a dummy exception to initialize the global IORef with data NoException = NoException deriving (Typeable) instance Show NoException where show _ = "<<no exception>>" instance Exception NoException -- | storage for the last exception lastException :: IORef SomeException {-# NOINLINE lastException #-} lastException = unsafePerformIO . newIORef $ SomeException NoException -- | when no catch frame handles an exception dump core and terminate the process uncaughtExceptionHandler :: SomeException -> IO () {-# NOINLINE uncaughtExceptionHandler #-} uncaughtExceptionHandler !e = do writeIORef lastException e hPutStrLn stderr $ "Unhandled exception: " ++ show e raiseSignal sigABRT setDefaultUncaughtExceptionHandler :: IO () setDefaultUncaughtExceptionHandler = setUncaughtExceptionHandler uncaughtExceptionHandler
alphaHeavy/shake-install
Development/Shake/Install/Exceptions.hs
bsd-3-clause
1,320
0
9
174
248
139
109
31
1
TaskGroupData { tgdPreds = LevelPreds { lpredPre = NameT { nameTName = "p_galois'find'P" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] } , lpredLoops = [ NameT { nameTName = "p_galois'find'I1" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] } ] , lpredPost = NameT { nameTName = "p_galois'find'Q" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] } , lpredCalls = fromList [] } , tgdGoals = fromList [ G { gName = ( "VCfind_loop_inv_galois_decorator_established" , "WP" ) , gVars = [ ( "retres_0" , TyCon "int" [] ) , ( "size_0" , TyCon "int" [] ) , ( "x_0" , TyCon "int" [] ) , ( "malloc_0" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "mchar_0" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_0" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mptr_0" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "a_0" , TyCon "addr" [] ) ] , gDefs = [] , gAsmps = [ "p_galois'find'P malloc_0 mptr_0 mchar_0 mint_0 a_0 size_0 x_0" , "x_0 < 2147483648" , "- 2147483648 <= x_0" , "size_0 < 2147483648" , "- 2147483648 <= size_0" , "retres_0 < 2147483648" , "- 2147483648 <= retres_0" , "sconst mchar_0" , "linked malloc_0" , "framed mptr_0" ] , gConc = "p_galois'find'I1 malloc_0 mptr_0 mchar_0 mint_0 malloc_0 mptr_0\n mchar_0 mint_0 a_0 size_0 x_0 retres_0 0 a_0 size_0 x_0" } , G { gName = ( "VCfind_loop_inv_galois_decorator_preserved" , "WP" ) , gVars = [ ( "i_0" , TyCon "int" [] ) , ( "retres_0" , TyCon "int" [] ) , ( "size_1" , TyCon "int" [] ) , ( "size_0" , TyCon "int" [] ) , ( "x_1" , TyCon "int" [] ) , ( "x_0" , TyCon "int" [] ) , ( "malloc_1" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "malloc_0" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "mchar_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mchar_0" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_0" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mptr_1" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "mptr_0" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "a_1" , TyCon "addr" [] ) , ( "a_0" , TyCon "addr" [] ) ] , gDefs = [ ( "cse_0" , "shift a_0 i_0" ) , ( "cse_1" , "mint_0[cse_0]" ) , ( "cse_2" , "1 + i_0" ) ] , gAsmps = [ "p_galois'find'P malloc_1 mptr_1 mchar_1 mint_1 a_1 size_1 x_1" , "p_galois'find'I1 malloc_0 mptr_0 mchar_0 mint_0 malloc_1 mptr_1\n mchar_1 mint_1 a_1 size_1 x_1 retres_0 i_0 a_0 size_0 x_0" , "offset a_0 + i_0 + 1 <= malloc_0[base a_0]" , "0 <= offset a_0 + i_0" , "cse_1 < 2147483648" , "- 2147483648 <= cse_1" , "cse_1 <> x_0" , "x_0 < 2147483648" , "- 2147483648 <= x_0" , "x_1 < 2147483648" , "- 2147483648 <= x_1" , "size_0 < 2147483648" , "size_1 < 2147483648" , "- 2147483648 <= size_1" , "retres_0 < 2147483648" , "- 2147483648 <= retres_0" , "- 2147483648 <= i_0" , "sconst mchar_1" , "linked malloc_1" , "framed mptr_1" , "i_0 < size_0" ] , gConc = "p_galois'find'I1 malloc_0 mptr_0 mchar_0 mint_0 malloc_1 mptr_1\n mchar_1 mint_1 a_1 size_1 x_1 retres_0 cse_2 a_0 size_0 x_0" } , G { gName = ( "VCfind_assert_rte_mem_access" , "WP" ) , gVars = [ ( "i_0" , TyCon "int" [] ) , ( "retres_0" , TyCon "int" [] ) , ( "size_1" , TyCon "int" [] ) , ( "size_0" , TyCon "int" [] ) , ( "x_1" , TyCon "int" [] ) , ( "x_0" , TyCon "int" [] ) , ( "malloc_1" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "malloc_0" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "mchar_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mchar_0" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_2" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_0" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mptr_1" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "mptr_0" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "a_1" , TyCon "addr" [] ) , ( "a_0" , TyCon "addr" [] ) ] , gDefs = [ ( "cse_0" , "shift a_0 i_0" ) ] , gAsmps = [ "p_galois'find'P malloc_1 mptr_1 mchar_1 mint_2 a_1 size_1 x_1" , "x_0 < 2147483648" , "- 2147483648 <= x_0" , "x_1 < 2147483648" , "- 2147483648 <= x_1" , "size_0 < 2147483648" , "size_1 < 2147483648" , "- 2147483648 <= size_1" , "retres_0 < 2147483648" , "- 2147483648 <= retres_0" , "sconst mchar_1" , "linked malloc_1" , "framed mptr_1" , "p_galois'find'I1 malloc_0 mptr_0 mchar_0 mint_0 malloc_1 mptr_1\n mchar_1 mint_2 a_1 size_1 x_1 retres_0 i_0 a_0 size_0 x_0" , "mint_1[cse_0] < 2147483648" , "- 2147483648 <= mint_1[cse_0]" , "- 2147483648 <= i_0" , "i_0 < size_0" ] , gConc = "offset a_0 + i_0 + 1 <= malloc_0[base a_0]" } , G { gName = ( "VCfind_assert_rte_mem_access" , "WP" ) , gVars = [ ( "i_0" , TyCon "int" [] ) , ( "retres_0" , TyCon "int" [] ) , ( "size_1" , TyCon "int" [] ) , ( "size_0" , TyCon "int" [] ) , ( "x_1" , TyCon "int" [] ) , ( "x_0" , TyCon "int" [] ) , ( "malloc_1" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "malloc_0" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "mchar_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mchar_0" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_2" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_0" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mptr_1" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "mptr_0" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "a_1" , TyCon "addr" [] ) , ( "a_0" , TyCon "addr" [] ) ] , gDefs = [ ( "cse_0" , "shift a_0 i_0" ) ] , gAsmps = [ "p_galois'find'P malloc_1 mptr_1 mchar_1 mint_2 a_1 size_1 x_1" , "x_0 < 2147483648" , "- 2147483648 <= x_0" , "x_1 < 2147483648" , "- 2147483648 <= x_1" , "size_0 < 2147483648" , "size_1 < 2147483648" , "- 2147483648 <= size_1" , "retres_0 < 2147483648" , "- 2147483648 <= retres_0" , "sconst mchar_1" , "linked malloc_1" , "framed mptr_1" , "p_galois'find'I1 malloc_0 mptr_0 mchar_0 mint_0 malloc_1 mptr_1\n mchar_1 mint_2 a_1 size_1 x_1 retres_0 i_0 a_0 size_0 x_0" , "mint_1[cse_0] < 2147483648" , "- 2147483648 <= mint_1[cse_0]" , "- 2147483648 <= i_0" , "i_0 < size_0" ] , gConc = "0 <= offset a_0 + i_0" } , G { gName = ( "VCfind_post" , "WP" ) , gVars = [ ( "i_0" , TyCon "int" [] ) , ( "retres_0" , TyCon "int" [] ) , ( "size_1" , TyCon "int" [] ) , ( "size_0" , TyCon "int" [] ) , ( "x_1" , TyCon "int" [] ) , ( "x_0" , TyCon "int" [] ) , ( "malloc_2" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "malloc_1" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "mchar_2" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mchar_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_3" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_2" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mptr_2" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "mptr_1" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "a_1" , TyCon "addr" [] ) , ( "a_0" , TyCon "addr" [] ) ] , gDefs = [] , gAsmps = [ "size_0 <= i_0" , "mint_1[shift a_0 i_0] < 2147483648" , "- 2147483648 <= mint_1[shift a_0 i_0]" , "x_0 < 2147483648" , "- 2147483648 <= x_0" , "- 2147483648 <= size_0" , "retres_0 < 2147483648" , "- 2147483648 <= retres_0" , "i_0 < 2147483648" , "p_galois'find'P malloc_1 mptr_1 mchar_1 mint_2 a_1 size_1 x_1" , "p_galois'find'I1 malloc_2 mptr_2 mchar_2 mint_3 malloc_1 mptr_1\n mchar_1 mint_2 a_1 size_1 x_1 retres_0 i_0 a_0 size_0 x_0" , "x_1 < 2147483648" , "- 2147483648 <= x_1" , "size_1 < 2147483648" , "- 2147483648 <= size_1" , "sconst mchar_1" , "linked malloc_1" , "framed mptr_1" ] , gConc = "p_galois'find'Q malloc_2 mptr_2 mchar_2 mint_3 malloc_1 mptr_1\n mchar_1 mint_2 (- 1) a_1 size_1 x_1" } , G { gName = ( "VCfind_post" , "WP" ) , gVars = [ ( "i_0" , TyCon "int" [] ) , ( "retres_0" , TyCon "int" [] ) , ( "size_1" , TyCon "int" [] ) , ( "size_0" , TyCon "int" [] ) , ( "x_1" , TyCon "int" [] ) , ( "malloc_2" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "malloc_1" , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] ) , ( "mchar_2" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mchar_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_3" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_2" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mint_1" , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ) , ( "mptr_2" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "mptr_1" , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] ) , ( "a_1" , TyCon "addr" [] ) , ( "a_0" , TyCon "addr" [] ) ] , gDefs = [ ( "cse_0" , "shift a_0 i_0" ) ] , gAsmps = [ "size_0 < 2147483648" , "retres_0 < 2147483648" , "- 2147483648 <= retres_0" , "p_galois'find'P malloc_1 mptr_1 mchar_1 mint_2 a_1 size_1 x_1" , "p_galois'find'I1 malloc_2 mptr_2 mchar_2 mint_3 malloc_1 mptr_1\n mchar_1 mint_2 a_1 size_1 x_1 retres_0 i_0 a_0 size_0 mint_3[cse_0]" , "offset a_0 + i_0 + 1 <= malloc_2[base a_0]" , "0 <= offset a_0 + i_0" , "i_0 < size_0" , "mint_1[shift a_0 i_0] < 2147483648" , "- 2147483648 <= mint_1[shift a_0 i_0]" , "mint_3[cse_0] < 2147483648" , "- 2147483648 <= mint_3[cse_0]" , "x_1 < 2147483648" , "- 2147483648 <= x_1" , "size_1 < 2147483648" , "- 2147483648 <= size_1" , "- 2147483648 <= i_0" , "sconst mchar_1" , "linked malloc_1" , "framed mptr_1" ] , gConc = "p_galois'find'Q malloc_2 mptr_2 mchar_2 mint_3 malloc_1 mptr_1\n mchar_1 mint_2 i_0 a_1 size_1 x_1" } ] , tgdRoots = [ Concrete 0 , Concrete 1 , Post 2 , Post 3 ] , tgdGraph = fromList [ ( Concrete 0 , [ ( 2 , Other (NormalUInput NameT { nameTName = "p_galois'find'I1" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] }) ) ] ) , ( Concrete 1 , [ ( 3 , Other (NormalUInput NameT { nameTName = "p_galois'find'I1" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] }) ) ] ) , ( Post 2 , [ ( 4 , Other (NormalUInput NameT { nameTName = "p_galois'find'I1" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] }) ) ] ) , ( Post 3 , [ ( 5 , Other (NormalUInput NameT { nameTName = "p_galois'find'I1" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] }) ) ] ) , ( Other (NormalUInput NameT { nameTName = "p_galois'find'I1" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] }) , [ ( 0 , Other (NormalUInput NameT { nameTName = "p_galois'find'P" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] }) ) , ( 1 , Other (NormalUInput NameT { nameTName = "p_galois'find'I1" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] }) ) ] ) , ( Other (NormalUInput NameT { nameTName = "p_galois'find'P" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 7 } ] }) , [] ) ] }
GaloisInc/verification-game
web-prover/demo-levels/find/tasks.hs
bsd-3-clause
30,244
0
21
15,706
7,438
4,134
3,304
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} module Regress (regressions) where import qualified Test.Framework as F import Test.Framework.Providers.HUnit (testCase) import Test.HUnit ((@=?)) import GHC.Generics (Generic) import Data.List (nub) #ifdef HAVE_MMAP import qualified Regress.Mmap as Mmap #endif import Data.Hashable regressions :: [F.Test] regressions = [] ++ #ifdef HAVE_MMAP Mmap.regressions ++ #endif [ F.testGroup "Generic: sum of nullary constructors" [ testCase "0" $ nullaryCase 0 S0 , testCase "1" $ nullaryCase 1 S1 , testCase "2" $ nullaryCase 2 S2 , testCase "3" $ nullaryCase 3 S3 , testCase "4" $ nullaryCase 4 S4 ] , testCase "Generic: Peano https://github.com/tibbe/hashable/issues/135" $ do let ns = take 20 $ iterate S Z let hs = map hash ns hs @=? nub hs ] where nullaryCase :: Int -> SumOfNullary -> IO () nullaryCase n s = do let salt = 42 let expected = salt `hashWithSalt` n `hashWithSalt` () let actual = hashWithSalt salt s expected @=? actual data SumOfNullary = S0 | S1 | S2 | S3 | S4 deriving (Generic) instance Hashable SumOfNullary data Nat = Z | S Nat deriving (Generic) instance Hashable Nat
pacak/cuddly-bassoon
hashable-1.2.6.0/tests/Regress.hs
bsd-3-clause
1,279
0
14
322
389
208
181
31
1
{-# LANGUAGE FlexibleContexts , FlexibleInstances , TypeSynonymInstances , MultiParamTypeClasses , GADTs , TupleSections , RankNTypes , ScopedTypeVariables #-} module Linear.Constraints.Cassowary.AugmentedSimplex where import Prelude hiding (foldr, minimum, zip, lookup, filter) import Linear.Constraints.Cassowary.Refactor (flatten, substitute) import Linear.Constraints.Cassowary.Basic ( nextRowPrimal , nextRowDual , nextBasicPrimal , nextBasicDual ) import Linear.Constraints.Tableau (Tableau (Tableau)) import Linear.Constraints.Weights ( Weight (Weight) , subMapWeight , compressWeight ) import Linear.Grammar.Types.Class (getVars, mapVars, getConst, mapConst, mapAllVars) import Linear.Grammar.Types.Utilities (subMap) import Linear.Grammar.Types.Inequalities ( Equality (Equ, getEqu) , IneqStdForm (EquStd, unEquStd) ) import Data.Maybe (fromMaybe) -- hiding (mapMaybe, catMaybes) import Data.Semigroup ( Option (Option) , Min (Min, getMin) , First (First, getFirst) ) import qualified Data.Vector as V -- hiding (length, all) import qualified Data.Map as Map import qualified Data.IntMap as IntMap import Control.Monad (guard) -- | Finds an optimal solution from one that's already feasible - maximizing. simplexPrimal :: forall k a a' c c' . ( Ord k , Fractional a , Ord a ) => (Tableau k k a a, Equality k a a) -> (Tableau k k a a, Equality k a a) simplexPrimal = fixWhile pivot where go :: k -> IneqStdForm k a a -> Equality k a a -> Equality k a a go var replacement target = unEquStd (substitute var replacement (EquStd target)) pivot :: (Tableau k k a a, Equality k a a) -> Maybe (Tableau k k a a, Equality k a a) pivot = pivotPrimalWith nextBasicPrimal go -- | Performs a single primal pivot, maximizing the basic feasible solution. pivotPrimalWith :: forall k a a' c c' . ( Ord k , Fractional a , Ord a ) => (Equality k a' c' -> Maybe k) -- ^ Next basic variable -> (k -> IneqStdForm k a a -> Equality k a' c' -> Equality k a' c') -- ^ Substitution -> (Tableau k k a a, Equality k a' c') -- ^ Tableau and objective -> Maybe (Tableau k k a a, Equality k a' c') pivotPrimalWith nextBasic substituteObj (Tableau cBasic cSlack, objective) = do (var :: k) <- nextBasic objective slack <- nextRowPrimal var cSlack row <- IntMap.lookup slack cSlack let replacement :: IneqStdForm k a a replacement = flatten var row final = mapAllVars (Map.delete var) replacement pure ( Tableau (Map.insert var final $ substitute var replacement <$> cBasic) (substitute var replacement <$> IntMap.delete slack cSlack) , substituteObj var replacement objective ) -- | Finds a feasible solution from one that's already optimal - minimizing. simplexDual :: ( Ord k , Fractional a , Ord a ) => (Tableau k k a a, Equality k a a) -> (Tableau k k a a, Equality k a a) simplexDual = fixWhile pivot where go var replacement target = unEquStd (substitute var replacement (EquStd target)) pivot = pivotDualWith nextBasicDual go pivotDualWith :: forall k a a' c c' . ( Ord k , Fractional a , Ord a ) => (Equality k a' c' -> IneqStdForm k a a -> Maybe k) -- ^ Next basic variable -> (k -> IneqStdForm k a a -> Equality k a' c' -> Equality k a' c') -- ^ Substitution -> (Tableau k k a a, Equality k a' c') -> Maybe (Tableau k k a a, Equality k a' c') pivotDualWith nextBasic substituteObj (Tableau cBasic cSlack, objective) = do slack <- nextRowDual cSlack row <- IntMap.lookup slack cSlack (var :: k) <- nextBasic objective row let replacement :: IneqStdForm k a a replacement = flatten var row final = mapAllVars (Map.delete var) replacement pure ( Tableau (Map.insert var final $ substitute var replacement <$> cBasic) (substitute var replacement <$> IntMap.delete slack cSlack) , substituteObj var replacement objective ) fixWhile :: (a -> Maybe a) -> a -> a fixWhile f x = case f x of Just y -> fixWhile f y Nothing -> x
athanclark/cassowary-haskell
src/Linear/Constraints/Cassowary/AugmentedSimplex.hs
bsd-3-clause
4,423
0
14
1,249
1,321
705
616
100
2
module System.Termutils.Url ( findUrls , matchUrls -- , showUrls , launchUrl ) where import Text.Regex import Graphics.UI.Gtk.Vte.Vte import System.Posix.Process import Control.Concurrent import Codec.Binary.UTF8.String (encodeString) {- data Attr = Attr { column :: Int , row :: Int , foreground :: Color , background :: Color , underline :: Bool , strikeThrough :: Bool } -} findUrls :: Terminal -> String -> IO [(VteChar, VteChar, String)] findUrls vte regex = do let regx = mkRegex regex vteChars <- terminalGetText vte Nothing return $ matchUrls regx vteChars 0 --fetchAttr = ffi matchUrls :: Regex -> [VteChar] -> Int -> [(VteChar, VteChar, String)] matchUrls regex content i = let str = map vcChar content in case matchRegexAll regex str of Nothing -> [] (Just (b, m, _, _)) -> let pos = i + length b posAfter = pos + length m in (content !! pos, content !! posAfter, m) : matchUrls regex (drop posAfter content) posAfter --showUrls :: (Input a) => Terminal -> a -> IO () --showUrls term a = do -- attrs <- findUrls term "http:" -- selector a attrs -- showInput a attrs launchUrl -- hideInput a -- spawn :: String -> IO () spawn x = spawnPID x >> return () -- | Like 'spawn', but returns the 'ProcessID' of the launched application spawnPID :: String -> IO ThreadId spawnPID x = forkIO $ executeFile "/bin/sh" False ["-c", encodeString x] Nothing launchUrl :: String -> IO () launchUrl str = spawn $ "firefox " ++ str --scrolled :: Int -> [(Attr, Attr, String)] -> [(Attr, Attr, String)] -- More helper functions etc. -- when widgets are done (should be located in widgets)
dagle/hermite
src/System/Termutils/Url.hs
bsd-3-clause
1,727
0
15
420
417
226
191
29
2
module System.Build.Access.Encoding where class Encoding r where encoding :: Maybe String -> r -> r getEncoding :: r -> Maybe String
tonymorris/lastik
System/Build/Access/Encoding.hs
bsd-3-clause
159
0
8
47
45
24
21
9
0
-- | -- Module : Crypto.Random.Entropy.Backend -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : stable -- Portability : good -- {-# LANGUAGE CPP #-} {-# LANGUAGE ExistentialQuantification #-} module Crypto.Random.Entropy.Backend ( EntropyBackend , supportedBackends , gatherBackend ) where import Foreign.Ptr import Data.Word (Word8) import Crypto.Internal.Proxy import Crypto.Random.Entropy.Source #ifdef SUPPORT_RDRAND import Crypto.Random.Entropy.RDRand #endif #ifdef WINDOWS import Crypto.Random.Entropy.Windows #else import Crypto.Random.Entropy.Unix #endif -- | All supported backends supportedBackends :: [IO (Maybe EntropyBackend)] supportedBackends = [ #ifdef SUPPORT_RDRAND openBackend (Proxy :: Proxy RDRand), #endif #ifdef WINDOWS openBackend (Proxy :: Proxy WinCryptoAPI) #else openBackend (Proxy :: Proxy DevRandom), openBackend (Proxy :: Proxy DevURandom) #endif ] -- | Any Entropy Backend data EntropyBackend = forall b . EntropySource b => EntropyBackend b -- | Open a backend handle openBackend :: EntropySource b => Proxy b -> IO (Maybe EntropyBackend) openBackend b = fmap EntropyBackend `fmap` callOpen b where callOpen :: EntropySource b => Proxy b -> IO (Maybe b) callOpen _ = entropyOpen -- | Gather randomness from an open handle gatherBackend :: EntropyBackend -- ^ An open Entropy Backend -> Ptr Word8 -- ^ Pointer to a buffer to write to -> Int -- ^ number of bytes to write -> IO Int -- ^ return the number of bytes actually written gatherBackend (EntropyBackend backend) ptr n = entropyGather backend ptr n
tekul/cryptonite
Crypto/Random/Entropy/Backend.hs
bsd-3-clause
1,708
0
11
353
295
171
124
25
1
module T6056 where import T6056a foo1 :: Int -> (Maybe Int, [Int]) foo1 x = smallerAndRest x [x] foo2 :: Integer -> (Maybe Integer, [Integer]) foo2 x = smallerAndRest x [x]
spacekitteh/smcghc
testsuite/tests/simplCore/should_compile/T6056.hs
bsd-3-clause
175
0
7
33
81
45
36
6
1
module AmbitiousSignature where hServer :: String hServer = "Server"
phischu/fragnix
tests/quick/AmbiguousSignature/AmbitiousSignature.hs
bsd-3-clause
71
0
4
11
14
9
5
3
1
module Petri.Roll where import Petri.Type import Autolib.Util.Zufall import qualified Data.Map as M import qualified Data.Set as S import Control.Monad ( forM ) net :: ( Ord s , Ord t ) => [s] -> [t] -> Capacity s -> IO ( Net s t ) net ps ts cap = do s <- state ps cs <- conn ps ts return $ Net { places = S.fromList ps , transitions = S.fromList ts , connections = cs , capacity = cap , start = s } state ps = do qs <- selection ps return $ State $ M.fromList $ do p <- ps return ( p, if p `elem` qs then 1 else 0 ) conn :: ( Ord s , Ord t ) => [s] -> [t] -> IO [ Connection s t ] conn ps ts = forM ts $ \ t -> do vor <- selection ps nach <- selection ps return ( vor, t, nach ) -- | pick a non-empty subset, -- size s with probability 2^-s selection :: [a] -> IO [a] selection [] = return [] selection xs = do i <- randomRIO ( 0, length xs - 1 ) let ( pre, x : post ) = splitAt i xs f <- randomRIO ( False, True ) xs <- if f then selection $ pre ++ post else return [] return $ x : xs
Erdwolf/autotool-bonn
src/Petri/Roll.hs
gpl-2.0
1,189
0
13
436
494
257
237
38
2
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad import Control.Monad.Trans import qualified Data.ByteString as ByteString import qualified Data.ByteString as BS import Data.Monoid ((<>)) import Foreign.Lua (Lua, runLua) import qualified Foreign.Lua as Lua import Options.Applicative import qualified System.Console.Haskeline as Haskeline import System.FilePath (takeDirectory) import GrLang (initialize) import Util.Lua data Options = Options { repl :: Bool , scriptToRun :: Maybe String } shouldRunRepl :: Options -> Bool shouldRunRepl (Options _ Nothing) = True shouldRunRepl (Options repl (Just _)) = repl options :: Parser Options options = Options <$> switch ( long "repl" <> help "Open a REPL even if given a script, in which case the script is run before entering the REPL.") <*> optional (strArgument ( metavar "FILE" <> help "Lua script to run before entering the REPL.")) fullOptions :: ParserInfo Options fullOptions = info (options <**> helper) ( fullDesc <> progDesc "Lua interpreter with bindings to Verigraph." ) main :: IO () main = runLua $ do Lua.openlibs initialize options <- liftIO $ execParser fullOptions when (shouldRunRepl options) $ do liftIO $ putStrLn "Verigraph REPL" liftIO $ putStrLn "" case scriptToRun options of Just script -> do loaded <- checkStatus =<< Lua.loadfile script when loaded . addingToPath (takeDirectory script) . void $ checkStatus =<< Lua.pcall 0 Lua.multret Nothing Nothing -> return () when (shouldRunRepl options) readEvalPrintLoop where readEvalPrintLoop = do hasRead <- read' case hasRead of RError -> readEvalPrintLoop REnd -> return () ROk -> do hasEvaled <- eval' when hasEvaled print' readEvalPrintLoop addingToPath dir action = do Lua.getglobal "package" Lua.getfield Lua.stackTop "path" oldPath <- Lua.tostring Lua.stackTop let newPath = stringToByteString (dir ++ "/?.lua;") <> oldPath Lua.pushstring newPath Lua.setfield (Lua.nthFromTop 3) "path" Lua.pop 2 result <- action Lua.getglobal "package" Lua.pushstring oldPath Lua.setfield (Lua.nthFromTop 2) "path" return result stringToByteString :: String -> BS.ByteString stringToByteString = BS.pack . map (fromIntegral . fromEnum) data ReaderResult = ROk | RError | REnd getInputLine :: String -> Lua (Maybe String) getInputLine = liftIO . Haskeline.runInputT settings . Haskeline.getInputLine where settings = Haskeline.defaultSettings { Haskeline.historyFile = Just ".verigraph-repl-history" } read' :: Lua ReaderResult read' = do input <- getInputLine "> " case input of Nothing -> return REnd Just line -> do status <- Lua.loadstring ("return " ++ line) case status of Lua.OK -> return ROk _ -> do Lua.pop 1 readMultilineCommand line where readMultilineCommand content = do status <- Lua.loadstring content case status of Lua.OK -> return ROk Lua.ErrSyntax -> do isIncomplete <- testIfIncomplete if isIncomplete then do Lua.pop 1 input <- getInputLine ">> " case input of Nothing -> return REnd Just line -> readMultilineCommand (content ++ '\n':line) else checkStatus status >> return RError _ -> checkStatus status >> return RError testIfIncomplete = ("<eof>" `ByteString.isSuffixOf`) <$> Lua.tostring Lua.stackTop eval' :: Lua Bool eval' = Lua.pcall 0 Lua.multret Nothing >>= checkStatus print' :: Lua () print' = do stackTop <- Lua.gettop let numValues = fromIntegral (fromEnum stackTop) when (numValues > 0) $ do Lua.getglobal "print" Lua.insert Lua.stackBottom status <- Lua.pcall numValues 0 Nothing case status of Lua.OK -> return () _ -> showError "Error calling print: "
rodrigo-machado/verigraph
src/repl/Main.hs
gpl-3.0
4,208
0
23
1,188
1,189
576
613
117
7
-- A primes algorithm as posted to Haskell Cafe by "oleg" -- http://www.haskell.org/pipermail/haskell-cafe/2007-February/022437.html module OlegPrimes where -- repl_every_n n l replaces every (n+1)-th element in a list (_:l) -- with False repl_every_n :: Int -> [Bool] -> [Bool] repl_every_n n l = repl_every_n' n l where repl_every_n' 0 (_:t) = False: repl_every_n n t repl_every_n' i (h:t) = h: repl_every_n' (pred i) t primes = 2:(loop 3 (repeat True)) where loop n (False:t) = loop (succ (succ n)) t loop n (_:t) = n:(loop (succ (succ n)) (repl_every_n (pred n) t))
dkensinger/haskell
haskell-primes/OlegPrimes.hs
gpl-3.0
594
0
13
115
216
113
103
8
2
{-# OPTIONS_GHC -fno-warn-orphans #-} module Main where import Data.Foldable as F import Data.Map as M import Data.Maybe import Data.Vector.Map as V import Control.DeepSeq import Control.Monad.Random import Control.Monad import Criterion.Config import Criterion.Main instance NFData (V.Map k v) buildV :: Int -> V.Map Int Int buildV n = F.foldl' (flip (join V.insert)) V.empty $ take n $ randoms (mkStdGen 1) buildM :: Int -> M.Map Int Int buildM n = F.foldl' (flip (join M.insert)) M.empty $ take n $ randoms (mkStdGen 1) lookupV :: V.Map Int Int -> Int -> Int lookupV m n = F.foldl' (+) 0 $ catMaybes $ fmap (`V.lookup` m) $ take n $ randoms (mkStdGen 1) lookupM :: M.Map Int Int -> Int -> Int lookupM m n = F.foldl' (+) 0 $ catMaybes $ fmap (`M.lookup` m) $ take n $ randoms (mkStdGen 1) main :: IO () main = do nfIO (return v10) nfIO (return m10) nfIO (return v100) nfIO (return m100) nfIO (return v1000) nfIO (return m1000) defaultMainWith defaultConfig { cfgSamples = ljust 10 } (return ()) [ bench "COLA lookup 10k from 10k" $ nf (lookupV v10) 10000 , bench "Data.Map lookup 10k from 10k" $ nf (lookupM m10) 10000 , bench "COLA lookup 10k from 100k" $ nf (lookupV v100) 10000 , bench "Data.Map lookup 10k from 100k" $ nf (lookupM m100) 10000 , bench "COLA lookup 10k from 1m" $ nf (lookupV v1000) 10000 , bench "Data.Map lookup 10k from 1m" $ nf (lookupM m1000) 10000 ] where v10 = buildV 10000 m10 = buildM 10000 v100 = buildV 100000 m100 = buildM 100000 v1000 = buildV 1000000 m1000 = buildM 1000000
ekmett/structures
benchmarks/lookups.hs
bsd-2-clause
1,642
0
12
404
657
328
329
41
1
module Cards where import Global import System.Random import Test.HUnit hiding (Path) {- REPRESENTATION CONVENTION: Represents the rank/value of the playing card. REPRESENTATION INVARIANT: True -} data Rank = One | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving(Eq, Ord, Show) {- REPRESENTATION CONVENTION: Represents the suit of the playing card. REPRESENTATION INVARIANT: True -} data Suit = Diamonds | Clubs | Heart | Spades deriving(Eq,Ord,Show) {- REPRESENTATION CONVENTION: Holds to datatypes that represents the value of the playing card. REPRESENTATION INVARIANT: True -} data Card = Card Suit Rank deriving (Eq, Ord, Show) {- cardList [Card] -> Card Purpose: Appends the card to the given list. Pre: True Post: List of Cards. Side-effect: -} cardList :: [Card] -> Card -> IO [Card] -- Tar in en lista och en kort och retunerar en ny lista med kortet i den cardList l c = do return (l ++ [c]) {- genCard Purpose: Generates a random Card. Pre: True Post: True Side-effect: -} genCard :: IO Card genCard = do -- Genererar ett random kort s <- (randomRIO (1,4)) r <- (randomRIO (2,14)) return (Card (intToSuit s) (intToRank r)) {- genCardList Int [Card] Purpose: generates a list of unique Cards with the lenght of the given Int. Pre: True Post: List of Cards. Side-effect: -} genCardList :: Int -> [Card]-> IO [Card] genCardList 0 l = do return l genCardList i l = do x <- genCard -- y <- Global.exists l x -- Kollar om det nya kortet finns i listan if Global.exists l x then do -- Om det gör det körs denna kod genCardList (i) l -- Kör om funktionen utan att ta -1 på i else do -- om det är unikt lägg in i listan och kör om funktionen på i-1 z <- cardList l x genCardList (i-1) z {- intToRank Int Purpose: Translates the given Int to a Rank Pre: 0 < i < 15 Post: True Side-effect: -} intToRank :: Int -> Rank intToRank i = case i of -- Håller i vilket värde korten ska ha med en 1 -> One 2 -> Two 3 -> Three 4 -> Four 5 -> Five 6 -> Six 7 -> Seven 8 -> Eight 9 -> Nine 10 -> Ten 11 -> Jack 12 -> Queen 13 -> King 14 -> Ace {- intToSuit Int Purpose: Translates the given Int to a Suit Pre: 0 < i < 5 Post: True Side-effect: -} intToSuit :: Int -> Suit intToSuit i = case i of -- Håller i vilken färg kortet ska ha med en Int 1 -> Diamonds 2 -> Clubs 3 -> Heart 4 -> Spades class CTI a where bjPoints :: a -> Int {- bjPoints Card Purpose: Translates the Card Rank to an Int. Pre: True Post: True Side-effect: -} instance CTI Card where -- Värdet för alla kort i Blackjack bjPoints (Card s One) = 1 bjPoints (Card s Two) = 2 bjPoints (Card s Three) = 3 bjPoints (Card s Four) = 4 bjPoints (Card s Five) = 5 bjPoints (Card s Six) = 6 bjPoints (Card s Seven) = 7 bjPoints (Card s Eight) = 8 bjPoints (Card s Nine) = 9 bjPoints (Card s Ten) = 10 bjPoints (Card s Jack) = 10 bjPoints (Card s Queen) = 10 bjPoints (Card s King) = 10 bjPoints (Card s Ace) = 11 {- bjPoints [Card] Purpose: Get the value of the whole deck as an Int. Pre: True Post: True Side-effect: -} instance CTI a => CTI [a] where bjPoints [] = 0 bjPoints (c:cs) = bjPoints c + bjPoints cs {- first [Card] Purpose: Gets the first element in the Card list. Pre: True Post: True Side-effect: -} first :: [Card] -> IO Card first (x:xs) = do return x {- first [Card] Purpose: Gets a list of Card excluding the first element of the given list. Pre: True Post: True Side-effect: -} rest :: [Card] -> IO [Card] rest (x:xs) = do return xs {- first [Card] Int Purpose: Drops the first i cards in the list. Pre: True Post: True Side-effect: -} dropFirst :: [Card] -> Int -> IO [Card] dropFirst (x:xs) 0 = do return (x:xs) dropFirst (x:xs) i = do dropFirst xs (i-1) -- test cases test0 = TestCase $ assertBool "True" (intToRank 2 == Two) test1 = TestCase $ assertEqual "bjPoints [Card Spades One, Card Spades Two, Card Heart Nine]" 12 (bjPoints [Card Spades One, Card Spades Two, Card Heart Nine]) test2 = TestCase $ assertEqual "bjPoints [Card Spades Ace, Card Spades Seven, Card Heart Queen]" 28 (bjPoints [Card Spades Ace, Card Spades Seven, Card Heart Queen]) test3 = TestCase $ assertEqual "bjPoints (Card Diamonds Five)" 5 (bjPoints (Card Diamonds Five)) runTests = runTestTT $ TestList [test0, test1, test2, test3]
DeeLaiD/project_megadeal
cards.hs
bsd-3-clause
4,633
0
12
1,202
1,182
620
562
91
14
{-# LANGUAGE ForeignFunctionInterface #-} module Main where import Control.Monad (when) import System.Exit (ExitCode(ExitFailure), exitWith) import System.Mem import qualified Spec import GDAL import GDAL.Internal.GDAL (openDatasetCount) import Test.Hspec (hspec) main :: IO () main = withGDAL $ do hspec Spec.spec revertCAFs performGC performMajorGC dsCount <- openDatasetCount when (dsCount>0) $ do print ("open datasets at exit:", dsCount) exitWith (ExitFailure 1) foreign import ccall "revertCAFs" revertCAFs :: IO ()
meteogrid/bindings-gdal
tests/Main.hs
bsd-3-clause
548
0
13
91
166
89
77
20
1
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1996-1998 TcHsSyn: Specialisations of the @HsSyn@ syntax for the typechecker This module is an extension of @HsSyn@ syntax, for use in the type checker. -} {-# LANGUAGE CPP #-} module TcHsSyn ( mkHsConApp, mkHsDictLet, mkHsApp, hsLitType, hsLPatType, hsPatType, mkHsAppTy, mkSimpleHsAlt, nlHsIntLit, shortCutLit, hsOverLitName, conLikeResTy, -- re-exported from TcMonad TcId, TcIdSet, zonkTopDecls, zonkTopExpr, zonkTopLExpr, zonkTopBndrs, zonkTyBndrsX, emptyZonkEnv, mkEmptyZonkEnv, mkTyVarZonkEnv, zonkTcTypeToType, zonkTcTypeToTypes, zonkTyVarOcc, ) where #include "HsVersions.h" import HsSyn import Id import TcRnMonad import PrelNames import TypeRep -- We can see the representation of types import TcType import RdrName ( RdrName, rdrNameOcc ) import TcMType ( defaultKindVarToStar, zonkQuantifiedTyVar, writeMetaTyVar ) import TcEvidence import Coercion import TysPrim import TysWiredIn import Type import ConLike import DataCon import PatSyn( patSynInstResTy ) import Name import NameSet import Var import VarSet import VarEnv import DynFlags import Literal import BasicTypes import Maybes import SrcLoc import Bag import FastString import Outputable import Util #if __GLASGOW_HASKELL__ < 709 import Data.Traversable ( traverse ) #endif {- ************************************************************************ * * \subsection[mkFailurePair]{Code for pattern-matching and other failures} * * ************************************************************************ Note: If @hsLPatType@ doesn't bear a strong resemblance to @exprType@, then something is wrong. -} hsLPatType :: OutPat Id -> Type hsLPatType (L _ pat) = hsPatType pat hsPatType :: Pat Id -> Type hsPatType (ParPat pat) = hsLPatType pat hsPatType (WildPat ty) = ty hsPatType (VarPat var) = idType var hsPatType (BangPat pat) = hsLPatType pat hsPatType (LazyPat pat) = hsLPatType pat hsPatType (LitPat lit) = hsLitType lit hsPatType (AsPat var _) = idType (unLoc var) hsPatType (ViewPat _ _ ty) = ty hsPatType (ListPat _ ty Nothing) = mkListTy ty hsPatType (ListPat _ _ (Just (ty,_))) = ty hsPatType (PArrPat _ ty) = mkPArrTy ty hsPatType (TuplePat _ bx tys) = mkTupleTy bx tys hsPatType (ConPatOut { pat_con = L _ con, pat_arg_tys = tys }) = conLikeResTy con tys hsPatType (SigPatOut _ ty) = ty hsPatType (NPat (L _ lit) _ _) = overLitType lit hsPatType (NPlusKPat id _ _ _) = idType (unLoc id) hsPatType (CoPat _ _ ty) = ty hsPatType p = pprPanic "hsPatType" (ppr p) conLikeResTy :: ConLike -> [Type] -> Type conLikeResTy (RealDataCon con) tys = mkTyConApp (dataConTyCon con) tys conLikeResTy (PatSynCon ps) tys = patSynInstResTy ps tys hsLitType :: HsLit -> TcType hsLitType (HsChar _ _) = charTy hsLitType (HsCharPrim _ _) = charPrimTy hsLitType (HsString _ _) = stringTy hsLitType (HsStringPrim _ _) = addrPrimTy hsLitType (HsInt _ _) = intTy hsLitType (HsIntPrim _ _) = intPrimTy hsLitType (HsWordPrim _ _) = wordPrimTy hsLitType (HsInt64Prim _ _) = int64PrimTy hsLitType (HsWord64Prim _ _) = word64PrimTy hsLitType (HsInteger _ _ ty) = ty hsLitType (HsRat _ ty) = ty hsLitType (HsFloatPrim _) = floatPrimTy hsLitType (HsDoublePrim _) = doublePrimTy -- Overloaded literals. Here mainly because it uses isIntTy etc shortCutLit :: DynFlags -> OverLitVal -> TcType -> Maybe (HsExpr TcId) shortCutLit dflags (HsIntegral src i) ty | isIntTy ty && inIntRange dflags i = Just (HsLit (HsInt src i)) | isWordTy ty && inWordRange dflags i = Just (mkLit wordDataCon (HsWordPrim src i)) | isIntegerTy ty = Just (HsLit (HsInteger src i ty)) | otherwise = shortCutLit dflags (HsFractional (integralFractionalLit i)) ty -- The 'otherwise' case is important -- Consider (3 :: Float). Syntactically it looks like an IntLit, -- so we'll call shortCutIntLit, but of course it's a float -- This can make a big difference for programs with a lot of -- literals, compiled without -O shortCutLit _ (HsFractional f) ty | isFloatTy ty = Just (mkLit floatDataCon (HsFloatPrim f)) | isDoubleTy ty = Just (mkLit doubleDataCon (HsDoublePrim f)) | otherwise = Nothing shortCutLit _ (HsIsString src s) ty | isStringTy ty = Just (HsLit (HsString src s)) | otherwise = Nothing mkLit :: DataCon -> HsLit -> HsExpr Id mkLit con lit = HsApp (nlHsVar (dataConWrapId con)) (nlHsLit lit) ------------------------------ hsOverLitName :: OverLitVal -> Name -- Get the canonical 'fromX' name for a particular OverLitVal hsOverLitName (HsIntegral {}) = fromIntegerName hsOverLitName (HsFractional {}) = fromRationalName hsOverLitName (HsIsString {}) = fromStringName {- ************************************************************************ * * \subsection[BackSubst-HsBinds]{Running a substitution over @HsBinds@} * * ************************************************************************ The rest of the zonking is done *after* typechecking. The main zonking pass runs over the bindings a) to convert TcTyVars to TyVars etc, dereferencing any bindings etc b) convert unbound TcTyVar to Void c) convert each TcId to an Id by zonking its type The type variables are converted by binding mutable tyvars to immutable ones and then zonking as normal. The Ids are converted by binding them in the normal Tc envt; that way we maintain sharing; eg an Id is zonked at its binding site and they all occurrences of that Id point to the common zonked copy It's all pretty boring stuff, because HsSyn is such a large type, and the environment manipulation is tiresome. -} type UnboundTyVarZonker = TcTyVar-> TcM Type -- How to zonk an unbound type variable -- Note [Zonking the LHS of a RULE] data ZonkEnv = ZonkEnv UnboundTyVarZonker (TyVarEnv TyVar) -- (IdEnv Var) -- What variables are in scope -- Maps an Id or EvVar to its zonked version; both have the same Name -- Note that all evidence (coercion variables as well as dictionaries) -- are kept in the ZonkEnv -- Only *type* abstraction is done by side effect -- Is only consulted lazily; hence knot-tying instance Outputable ZonkEnv where ppr (ZonkEnv _ _ty_env var_env) = vcat (map ppr (varEnvElts var_env)) emptyZonkEnv :: ZonkEnv emptyZonkEnv = mkEmptyZonkEnv zonkTypeZapping mkEmptyZonkEnv :: UnboundTyVarZonker -> ZonkEnv mkEmptyZonkEnv zonker = ZonkEnv zonker emptyVarEnv emptyVarEnv extendIdZonkEnv :: ZonkEnv -> [Var] -> ZonkEnv extendIdZonkEnv (ZonkEnv zonk_ty ty_env id_env) ids = ZonkEnv zonk_ty ty_env (extendVarEnvList id_env [(id,id) | id <- ids]) extendIdZonkEnv1 :: ZonkEnv -> Var -> ZonkEnv extendIdZonkEnv1 (ZonkEnv zonk_ty ty_env id_env) id = ZonkEnv zonk_ty ty_env (extendVarEnv id_env id id) extendTyZonkEnv1 :: ZonkEnv -> TyVar -> ZonkEnv extendTyZonkEnv1 (ZonkEnv zonk_ty ty_env id_env) ty = ZonkEnv zonk_ty (extendVarEnv ty_env ty ty) id_env mkTyVarZonkEnv :: [TyVar] -> ZonkEnv mkTyVarZonkEnv tvs = ZonkEnv zonkTypeZapping (mkVarEnv [(tv,tv) | tv <- tvs]) emptyVarEnv setZonkType :: ZonkEnv -> UnboundTyVarZonker -> ZonkEnv setZonkType (ZonkEnv _ ty_env id_env) zonk_ty = ZonkEnv zonk_ty ty_env id_env zonkEnvIds :: ZonkEnv -> [Id] zonkEnvIds (ZonkEnv _ _ id_env) = varEnvElts id_env zonkIdOcc :: ZonkEnv -> TcId -> Id -- Ids defined in this module should be in the envt; -- ignore others. (Actually, data constructors are also -- not LocalVars, even when locally defined, but that is fine.) -- (Also foreign-imported things aren't currently in the ZonkEnv; -- that's ok because they don't need zonking.) -- -- Actually, Template Haskell works in 'chunks' of declarations, and -- an earlier chunk won't be in the 'env' that the zonking phase -- carries around. Instead it'll be in the tcg_gbl_env, already fully -- zonked. There's no point in looking it up there (except for error -- checking), and it's not conveniently to hand; hence the simple -- 'orElse' case in the LocalVar branch. -- -- Even without template splices, in module Main, the checking of -- 'main' is done as a separate chunk. zonkIdOcc (ZonkEnv _zonk_ty _ty_env env) id | isLocalVar id = lookupVarEnv env id `orElse` id | otherwise = id zonkIdOccs :: ZonkEnv -> [TcId] -> [Id] zonkIdOccs env ids = map (zonkIdOcc env) ids -- zonkIdBndr is used *after* typechecking to get the Id's type -- to its final form. The TyVarEnv give zonkIdBndr :: ZonkEnv -> TcId -> TcM Id zonkIdBndr env id = do ty' <- zonkTcTypeToType env (idType id) return (Id.setIdType id ty') zonkIdBndrs :: ZonkEnv -> [TcId] -> TcM [Id] zonkIdBndrs env ids = mapM (zonkIdBndr env) ids zonkTopBndrs :: [TcId] -> TcM [Id] zonkTopBndrs ids = zonkIdBndrs emptyZonkEnv ids zonkEvBndrsX :: ZonkEnv -> [EvVar] -> TcM (ZonkEnv, [Var]) zonkEvBndrsX = mapAccumLM zonkEvBndrX zonkEvBndrX :: ZonkEnv -> EvVar -> TcM (ZonkEnv, EvVar) -- Works for dictionaries and coercions zonkEvBndrX env var = do { var' <- zonkEvBndr env var ; return (extendIdZonkEnv1 env var', var') } zonkEvBndr :: ZonkEnv -> EvVar -> TcM EvVar -- Works for dictionaries and coercions -- Does not extend the ZonkEnv zonkEvBndr env var = do { let var_ty = varType var ; ty <- {-# SCC "zonkEvBndr_zonkTcTypeToType" #-} zonkTcTypeToType env var_ty ; return (setVarType var ty) } zonkEvVarOcc :: ZonkEnv -> EvVar -> EvVar zonkEvVarOcc env v = zonkIdOcc env v zonkTyBndrsX :: ZonkEnv -> [TyVar] -> TcM (ZonkEnv, [TyVar]) zonkTyBndrsX = mapAccumLM zonkTyBndrX zonkTyBndrX :: ZonkEnv -> TyVar -> TcM (ZonkEnv, TyVar) -- This guarantees to return a TyVar (not a TcTyVar) -- then we add it to the envt, so all occurrences are replaced zonkTyBndrX env tv = do { ki <- zonkTcTypeToType env (tyVarKind tv) ; let tv' = mkTyVar (tyVarName tv) ki ; return (extendTyZonkEnv1 env tv', tv') } zonkTopExpr :: HsExpr TcId -> TcM (HsExpr Id) zonkTopExpr e = zonkExpr emptyZonkEnv e zonkTopLExpr :: LHsExpr TcId -> TcM (LHsExpr Id) zonkTopLExpr e = zonkLExpr emptyZonkEnv e zonkTopDecls :: Bag EvBind -> LHsBinds TcId -> Maybe (Located [LIE RdrName]) -> NameSet -> [LRuleDecl TcId] -> [LVectDecl TcId] -> [LTcSpecPrag] -> [LForeignDecl TcId] -> TcM ([Id], Bag EvBind, LHsBinds Id, [LForeignDecl Id], [LTcSpecPrag], [LRuleDecl Id], [LVectDecl Id]) zonkTopDecls ev_binds binds export_ies sig_ns rules vects imp_specs fords = do { (env1, ev_binds') <- zonkEvBinds emptyZonkEnv ev_binds -- Warn about missing signatures -- Do this only when we we have a type to offer ; warn_missing_sigs <- woptM Opt_WarnMissingSigs ; warn_only_exported <- woptM Opt_WarnMissingExportedSigs ; let export_occs = maybe emptyBag (listToBag . map (rdrNameOcc . ieName . unLoc) . unLoc) export_ies sig_warn | warn_only_exported = topSigWarnIfExported export_occs sig_ns | warn_missing_sigs = topSigWarn sig_ns | otherwise = noSigWarn ; (env2, binds') <- zonkRecMonoBinds env1 sig_warn binds -- Top level is implicitly recursive ; rules' <- zonkRules env2 rules ; vects' <- zonkVects env2 vects ; specs' <- zonkLTcSpecPrags env2 imp_specs ; fords' <- zonkForeignExports env2 fords ; return (zonkEnvIds env2, ev_binds', binds', fords', specs', rules', vects') } --------------------------------------------- zonkLocalBinds :: ZonkEnv -> HsLocalBinds TcId -> TcM (ZonkEnv, HsLocalBinds Id) zonkLocalBinds env EmptyLocalBinds = return (env, EmptyLocalBinds) zonkLocalBinds _ (HsValBinds (ValBindsIn {})) = panic "zonkLocalBinds" -- Not in typechecker output zonkLocalBinds env (HsValBinds vb@(ValBindsOut binds sigs)) = do { warn_missing_sigs <- woptM Opt_WarnMissingLocalSigs ; let sig_warn | not warn_missing_sigs = noSigWarn | otherwise = localSigWarn sig_ns sig_ns = getTypeSigNames vb ; (env1, new_binds) <- go env sig_warn binds ; return (env1, HsValBinds (ValBindsOut new_binds sigs)) } where go env _ [] = return (env, []) go env sig_warn ((r,b):bs) = do { (env1, b') <- zonkRecMonoBinds env sig_warn b ; (env2, bs') <- go env1 sig_warn bs ; return (env2, (r,b'):bs') } zonkLocalBinds env (HsIPBinds (IPBinds binds dict_binds)) = do new_binds <- mapM (wrapLocM zonk_ip_bind) binds let env1 = extendIdZonkEnv env [ n | L _ (IPBind (Right n) _) <- new_binds] (env2, new_dict_binds) <- zonkTcEvBinds env1 dict_binds return (env2, HsIPBinds (IPBinds new_binds new_dict_binds)) where zonk_ip_bind (IPBind n e) = do n' <- mapIPNameTc (zonkIdBndr env) n e' <- zonkLExpr env e return (IPBind n' e') --------------------------------------------- zonkRecMonoBinds :: ZonkEnv -> SigWarn -> LHsBinds TcId -> TcM (ZonkEnv, LHsBinds Id) zonkRecMonoBinds env sig_warn binds = fixM (\ ~(_, new_binds) -> do { let env1 = extendIdZonkEnv env (collectHsBindsBinders new_binds) ; binds' <- zonkMonoBinds env1 sig_warn binds ; return (env1, binds') }) --------------------------------------------- type SigWarn = Bool -> [Id] -> TcM () -- Missing-signature warning -- The Bool is True for an AbsBinds, False otherwise noSigWarn :: SigWarn noSigWarn _ _ = return () topSigWarnIfExported :: Bag OccName -> NameSet -> SigWarn topSigWarnIfExported exported sig_ns _ ids = mapM_ (topSigWarnIdIfExported exported sig_ns) ids topSigWarnIdIfExported :: Bag OccName -> NameSet -> Id -> TcM () topSigWarnIdIfExported exported sig_ns id | getOccName id `elemBag` exported = topSigWarnId sig_ns id | otherwise = return () topSigWarn :: NameSet -> SigWarn topSigWarn sig_ns _ ids = mapM_ (topSigWarnId sig_ns) ids topSigWarnId :: NameSet -> Id -> TcM () -- The NameSet is the Ids that *lack* a signature -- We have to do it this way round because there are -- lots of top-level bindings that are generated by GHC -- and that don't have signatures topSigWarnId sig_ns id | idName id `elemNameSet` sig_ns = warnMissingSig msg id | otherwise = return () where msg = ptext (sLit "Top-level binding with no type signature:") localSigWarn :: NameSet -> SigWarn localSigWarn sig_ns is_abs_bind ids | not is_abs_bind = return () | otherwise = mapM_ (localSigWarnId sig_ns) ids localSigWarnId :: NameSet -> Id -> TcM () -- NameSet are the Ids that *have* type signatures localSigWarnId sig_ns id | not (isSigmaTy (idType id)) = return () | idName id `elemNameSet` sig_ns = return () | otherwise = warnMissingSig msg id where msg = ptext (sLit "Polymorphic local binding with no type signature:") warnMissingSig :: SDoc -> Id -> TcM () warnMissingSig msg id = do { env0 <- tcInitTidyEnv ; let (env1, tidy_ty) = tidyOpenType env0 (idType id) ; addWarnTcM (env1, mk_msg tidy_ty) } where mk_msg ty = sep [ msg, nest 2 $ pprPrefixName (idName id) <+> dcolon <+> ppr ty ] --------------------------------------------- zonkMonoBinds :: ZonkEnv -> SigWarn -> LHsBinds TcId -> TcM (LHsBinds Id) zonkMonoBinds env sig_warn binds = mapBagM (zonk_lbind env sig_warn) binds zonk_lbind :: ZonkEnv -> SigWarn -> LHsBind TcId -> TcM (LHsBind Id) zonk_lbind env sig_warn = wrapLocM (zonk_bind env sig_warn) zonk_bind :: ZonkEnv -> SigWarn -> HsBind TcId -> TcM (HsBind Id) zonk_bind env sig_warn bind@(PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty}) = do { (_env, new_pat) <- zonkPat env pat -- Env already extended ; sig_warn False (collectPatBinders new_pat) ; new_grhss <- zonkGRHSs env zonkLExpr grhss ; new_ty <- zonkTcTypeToType env ty ; return (bind { pat_lhs = new_pat, pat_rhs = new_grhss, pat_rhs_ty = new_ty }) } zonk_bind env sig_warn (VarBind { var_id = var, var_rhs = expr, var_inline = inl }) = do { new_var <- zonkIdBndr env var ; sig_warn False [new_var] ; new_expr <- zonkLExpr env expr ; return (VarBind { var_id = new_var, var_rhs = new_expr, var_inline = inl }) } zonk_bind env sig_warn bind@(FunBind { fun_id = L loc var, fun_matches = ms , fun_co_fn = co_fn }) = do { new_var <- zonkIdBndr env var ; sig_warn False [new_var] ; (env1, new_co_fn) <- zonkCoFn env co_fn ; new_ms <- zonkMatchGroup env1 zonkLExpr ms ; return (bind { fun_id = L loc new_var, fun_matches = new_ms , fun_co_fn = new_co_fn }) } zonk_bind env sig_warn (AbsBinds { abs_tvs = tyvars, abs_ev_vars = evs , abs_ev_binds = ev_binds , abs_exports = exports , abs_binds = val_binds }) = ASSERT( all isImmutableTyVar tyvars ) do { (env0, new_tyvars) <- zonkTyBndrsX env tyvars ; (env1, new_evs) <- zonkEvBndrsX env0 evs ; (env2, new_ev_binds) <- zonkTcEvBinds_s env1 ev_binds ; (new_val_bind, new_exports) <- fixM $ \ ~(new_val_binds, _) -> do { let env3 = extendIdZonkEnv env2 (collectHsBindsBinders new_val_binds) ; new_val_binds <- zonkMonoBinds env3 noSigWarn val_binds ; new_exports <- mapM (zonkExport env3) exports ; return (new_val_binds, new_exports) } ; sig_warn True (map abe_poly new_exports) ; return (AbsBinds { abs_tvs = new_tyvars, abs_ev_vars = new_evs , abs_ev_binds = new_ev_binds , abs_exports = new_exports, abs_binds = new_val_bind }) } where zonkExport env (ABE{ abe_wrap = wrap, abe_poly = poly_id , abe_mono = mono_id, abe_prags = prags }) = do new_poly_id <- zonkIdBndr env poly_id (_, new_wrap) <- zonkCoFn env wrap new_prags <- zonkSpecPrags env prags return (ABE{ abe_wrap = new_wrap, abe_poly = new_poly_id , abe_mono = zonkIdOcc env mono_id , abe_prags = new_prags }) zonk_bind env _sig_warn (PatSynBind bind@(PSB { psb_id = L loc id , psb_args = details , psb_def = lpat , psb_dir = dir })) = do { id' <- zonkIdBndr env id ; details' <- zonkPatSynDetails env details ;(env1, lpat') <- zonkPat env lpat ; (_env2, dir') <- zonkPatSynDir env1 dir ; return $ PatSynBind $ bind { psb_id = L loc id' , psb_args = details' , psb_def = lpat' , psb_dir = dir' } } zonkPatSynDetails :: ZonkEnv -> HsPatSynDetails (Located TcId) -> TcM (HsPatSynDetails (Located Id)) zonkPatSynDetails env = traverse (wrapLocM $ zonkIdBndr env) zonkPatSynDir :: ZonkEnv -> HsPatSynDir TcId -> TcM (ZonkEnv, HsPatSynDir Id) zonkPatSynDir env Unidirectional = return (env, Unidirectional) zonkPatSynDir env ImplicitBidirectional = return (env, ImplicitBidirectional) zonkPatSynDir env (ExplicitBidirectional mg) = do mg' <- zonkMatchGroup env zonkLExpr mg return (env, ExplicitBidirectional mg') zonkSpecPrags :: ZonkEnv -> TcSpecPrags -> TcM TcSpecPrags zonkSpecPrags _ IsDefaultMethod = return IsDefaultMethod zonkSpecPrags env (SpecPrags ps) = do { ps' <- zonkLTcSpecPrags env ps ; return (SpecPrags ps') } zonkLTcSpecPrags :: ZonkEnv -> [LTcSpecPrag] -> TcM [LTcSpecPrag] zonkLTcSpecPrags env ps = mapM zonk_prag ps where zonk_prag (L loc (SpecPrag id co_fn inl)) = do { (_, co_fn') <- zonkCoFn env co_fn ; return (L loc (SpecPrag (zonkIdOcc env id) co_fn' inl)) } {- ************************************************************************ * * \subsection[BackSubst-Match-GRHSs]{Match and GRHSs} * * ************************************************************************ -} zonkMatchGroup :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> MatchGroup TcId (Located (body TcId)) -> TcM (MatchGroup Id (Located (body Id))) zonkMatchGroup env zBody (MG { mg_alts = ms, mg_arg_tys = arg_tys, mg_res_ty = res_ty, mg_origin = origin }) = do { ms' <- mapM (zonkMatch env zBody) ms ; arg_tys' <- zonkTcTypeToTypes env arg_tys ; res_ty' <- zonkTcTypeToType env res_ty ; return (MG { mg_alts = ms', mg_arg_tys = arg_tys', mg_res_ty = res_ty', mg_origin = origin }) } zonkMatch :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> LMatch TcId (Located (body TcId)) -> TcM (LMatch Id (Located (body Id))) zonkMatch env zBody (L loc (Match mf pats _ grhss)) = do { (env1, new_pats) <- zonkPats env pats ; new_grhss <- zonkGRHSs env1 zBody grhss ; return (L loc (Match mf new_pats Nothing new_grhss)) } ------------------------------------------------------------------------- zonkGRHSs :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> GRHSs TcId (Located (body TcId)) -> TcM (GRHSs Id (Located (body Id))) zonkGRHSs env zBody (GRHSs grhss binds) = do (new_env, new_binds) <- zonkLocalBinds env binds let zonk_grhs (GRHS guarded rhs) = do (env2, new_guarded) <- zonkStmts new_env zonkLExpr guarded new_rhs <- zBody env2 rhs return (GRHS new_guarded new_rhs) new_grhss <- mapM (wrapLocM zonk_grhs) grhss return (GRHSs new_grhss new_binds) {- ************************************************************************ * * \subsection[BackSubst-HsExpr]{Running a zonkitution over a TypeCheckedExpr} * * ************************************************************************ -} zonkLExprs :: ZonkEnv -> [LHsExpr TcId] -> TcM [LHsExpr Id] zonkLExpr :: ZonkEnv -> LHsExpr TcId -> TcM (LHsExpr Id) zonkExpr :: ZonkEnv -> HsExpr TcId -> TcM (HsExpr Id) zonkLExprs env exprs = mapM (zonkLExpr env) exprs zonkLExpr env expr = wrapLocM (zonkExpr env) expr zonkExpr env (HsVar id) = return (HsVar (zonkIdOcc env id)) zonkExpr _ (HsIPVar id) = return (HsIPVar id) zonkExpr env (HsLit (HsRat f ty)) = do new_ty <- zonkTcTypeToType env ty return (HsLit (HsRat f new_ty)) zonkExpr _ (HsLit lit) = return (HsLit lit) zonkExpr env (HsOverLit lit) = do { lit' <- zonkOverLit env lit ; return (HsOverLit lit') } zonkExpr env (HsLam matches) = do new_matches <- zonkMatchGroup env zonkLExpr matches return (HsLam new_matches) zonkExpr env (HsLamCase arg matches) = do new_arg <- zonkTcTypeToType env arg new_matches <- zonkMatchGroup env zonkLExpr matches return (HsLamCase new_arg new_matches) zonkExpr env (HsApp e1 e2) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 return (HsApp new_e1 new_e2) zonkExpr _ e@(HsRnBracketOut _ _) = pprPanic "zonkExpr: HsRnBracketOut" (ppr e) zonkExpr env (HsTcBracketOut body bs) = do bs' <- mapM zonk_b bs return (HsTcBracketOut body bs') where zonk_b (PendingTcSplice n e) = do e' <- zonkLExpr env e return (PendingTcSplice n e') zonkExpr _ (HsSpliceE s) = WARN( True, ppr s ) -- Should not happen return (HsSpliceE s) zonkExpr env (OpApp e1 op fixity e2) = do new_e1 <- zonkLExpr env e1 new_op <- zonkLExpr env op new_e2 <- zonkLExpr env e2 return (OpApp new_e1 new_op fixity new_e2) zonkExpr env (NegApp expr op) = do new_expr <- zonkLExpr env expr new_op <- zonkExpr env op return (NegApp new_expr new_op) zonkExpr env (HsPar e) = do new_e <- zonkLExpr env e return (HsPar new_e) zonkExpr env (SectionL expr op) = do new_expr <- zonkLExpr env expr new_op <- zonkLExpr env op return (SectionL new_expr new_op) zonkExpr env (SectionR op expr) = do new_op <- zonkLExpr env op new_expr <- zonkLExpr env expr return (SectionR new_op new_expr) zonkExpr env (ExplicitTuple tup_args boxed) = do { new_tup_args <- mapM zonk_tup_arg tup_args ; return (ExplicitTuple new_tup_args boxed) } where zonk_tup_arg (L l (Present e)) = do { e' <- zonkLExpr env e ; return (L l (Present e')) } zonk_tup_arg (L l (Missing t)) = do { t' <- zonkTcTypeToType env t ; return (L l (Missing t')) } zonkExpr env (HsCase expr ms) = do new_expr <- zonkLExpr env expr new_ms <- zonkMatchGroup env zonkLExpr ms return (HsCase new_expr new_ms) zonkExpr env (HsIf e0 e1 e2 e3) = do { new_e0 <- fmapMaybeM (zonkExpr env) e0 ; new_e1 <- zonkLExpr env e1 ; new_e2 <- zonkLExpr env e2 ; new_e3 <- zonkLExpr env e3 ; return (HsIf new_e0 new_e1 new_e2 new_e3) } zonkExpr env (HsMultiIf ty alts) = do { alts' <- mapM (wrapLocM zonk_alt) alts ; ty' <- zonkTcTypeToType env ty ; return $ HsMultiIf ty' alts' } where zonk_alt (GRHS guard expr) = do { (env', guard') <- zonkStmts env zonkLExpr guard ; expr' <- zonkLExpr env' expr ; return $ GRHS guard' expr' } zonkExpr env (HsLet binds expr) = do (new_env, new_binds) <- zonkLocalBinds env binds new_expr <- zonkLExpr new_env expr return (HsLet new_binds new_expr) zonkExpr env (HsDo do_or_lc stmts ty) = do (_, new_stmts) <- zonkStmts env zonkLExpr stmts new_ty <- zonkTcTypeToType env ty return (HsDo do_or_lc new_stmts new_ty) zonkExpr env (ExplicitList ty wit exprs) = do new_ty <- zonkTcTypeToType env ty new_wit <- zonkWit env wit new_exprs <- zonkLExprs env exprs return (ExplicitList new_ty new_wit new_exprs) where zonkWit _ Nothing = return Nothing zonkWit env (Just fln) = do new_fln <- zonkExpr env fln return (Just new_fln) zonkExpr env (ExplicitPArr ty exprs) = do new_ty <- zonkTcTypeToType env ty new_exprs <- zonkLExprs env exprs return (ExplicitPArr new_ty new_exprs) zonkExpr env (RecordCon data_con con_expr rbinds) = do { new_con_expr <- zonkExpr env con_expr ; new_rbinds <- zonkRecFields env rbinds ; return (RecordCon data_con new_con_expr new_rbinds) } zonkExpr env (RecordUpd expr rbinds cons in_tys out_tys) = do { new_expr <- zonkLExpr env expr ; new_in_tys <- mapM (zonkTcTypeToType env) in_tys ; new_out_tys <- mapM (zonkTcTypeToType env) out_tys ; new_rbinds <- zonkRecFields env rbinds ; return (RecordUpd new_expr new_rbinds cons new_in_tys new_out_tys) } zonkExpr env (ExprWithTySigOut e ty) = do { e' <- zonkLExpr env e ; return (ExprWithTySigOut e' ty) } zonkExpr _ (ExprWithTySig _ _ _) = panic "zonkExpr env:ExprWithTySig" zonkExpr env (ArithSeq expr wit info) = do new_expr <- zonkExpr env expr new_wit <- zonkWit env wit new_info <- zonkArithSeq env info return (ArithSeq new_expr new_wit new_info) where zonkWit _ Nothing = return Nothing zonkWit env (Just fln) = do new_fln <- zonkExpr env fln return (Just new_fln) zonkExpr env (PArrSeq expr info) = do new_expr <- zonkExpr env expr new_info <- zonkArithSeq env info return (PArrSeq new_expr new_info) zonkExpr env (HsSCC src lbl expr) = do new_expr <- zonkLExpr env expr return (HsSCC src lbl new_expr) zonkExpr env (HsTickPragma src info expr) = do new_expr <- zonkLExpr env expr return (HsTickPragma src info new_expr) -- hdaume: core annotations zonkExpr env (HsCoreAnn src lbl expr) = do new_expr <- zonkLExpr env expr return (HsCoreAnn src lbl new_expr) -- arrow notation extensions zonkExpr env (HsProc pat body) = do { (env1, new_pat) <- zonkPat env pat ; new_body <- zonkCmdTop env1 body ; return (HsProc new_pat new_body) } -- StaticPointers extension zonkExpr env (HsStatic expr) = HsStatic <$> zonkLExpr env expr zonkExpr env (HsWrap co_fn expr) = do (env1, new_co_fn) <- zonkCoFn env co_fn new_expr <- zonkExpr env1 expr return (HsWrap new_co_fn new_expr) zonkExpr _ (HsUnboundVar v) = return (HsUnboundVar v) zonkExpr _ expr = pprPanic "zonkExpr" (ppr expr) ------------------------------------------------------------------------- zonkLCmd :: ZonkEnv -> LHsCmd TcId -> TcM (LHsCmd Id) zonkCmd :: ZonkEnv -> HsCmd TcId -> TcM (HsCmd Id) zonkLCmd env cmd = wrapLocM (zonkCmd env) cmd zonkCmd env (HsCmdCast co cmd) = do { co' <- zonkTcCoToCo env co ; cmd' <- zonkCmd env cmd ; return (HsCmdCast co' cmd') } zonkCmd env (HsCmdArrApp e1 e2 ty ho rl) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 new_ty <- zonkTcTypeToType env ty return (HsCmdArrApp new_e1 new_e2 new_ty ho rl) zonkCmd env (HsCmdArrForm op fixity args) = do new_op <- zonkLExpr env op new_args <- mapM (zonkCmdTop env) args return (HsCmdArrForm new_op fixity new_args) zonkCmd env (HsCmdApp c e) = do new_c <- zonkLCmd env c new_e <- zonkLExpr env e return (HsCmdApp new_c new_e) zonkCmd env (HsCmdLam matches) = do new_matches <- zonkMatchGroup env zonkLCmd matches return (HsCmdLam new_matches) zonkCmd env (HsCmdPar c) = do new_c <- zonkLCmd env c return (HsCmdPar new_c) zonkCmd env (HsCmdCase expr ms) = do new_expr <- zonkLExpr env expr new_ms <- zonkMatchGroup env zonkLCmd ms return (HsCmdCase new_expr new_ms) zonkCmd env (HsCmdIf eCond ePred cThen cElse) = do { new_eCond <- fmapMaybeM (zonkExpr env) eCond ; new_ePred <- zonkLExpr env ePred ; new_cThen <- zonkLCmd env cThen ; new_cElse <- zonkLCmd env cElse ; return (HsCmdIf new_eCond new_ePred new_cThen new_cElse) } zonkCmd env (HsCmdLet binds cmd) = do (new_env, new_binds) <- zonkLocalBinds env binds new_cmd <- zonkLCmd new_env cmd return (HsCmdLet new_binds new_cmd) zonkCmd env (HsCmdDo stmts ty) = do (_, new_stmts) <- zonkStmts env zonkLCmd stmts new_ty <- zonkTcTypeToType env ty return (HsCmdDo new_stmts new_ty) zonkCmdTop :: ZonkEnv -> LHsCmdTop TcId -> TcM (LHsCmdTop Id) zonkCmdTop env cmd = wrapLocM (zonk_cmd_top env) cmd zonk_cmd_top :: ZonkEnv -> HsCmdTop TcId -> TcM (HsCmdTop Id) zonk_cmd_top env (HsCmdTop cmd stack_tys ty ids) = do new_cmd <- zonkLCmd env cmd new_stack_tys <- zonkTcTypeToType env stack_tys new_ty <- zonkTcTypeToType env ty new_ids <- mapSndM (zonkExpr env) ids return (HsCmdTop new_cmd new_stack_tys new_ty new_ids) ------------------------------------------------------------------------- zonkCoFn :: ZonkEnv -> HsWrapper -> TcM (ZonkEnv, HsWrapper) zonkCoFn env WpHole = return (env, WpHole) zonkCoFn env (WpCompose c1 c2) = do { (env1, c1') <- zonkCoFn env c1 ; (env2, c2') <- zonkCoFn env1 c2 ; return (env2, WpCompose c1' c2') } zonkCoFn env (WpFun c1 c2 t1 t2) = do { (env1, c1') <- zonkCoFn env c1 ; (env2, c2') <- zonkCoFn env1 c2 ; t1' <- zonkTcTypeToType env2 t1 ; t2' <- zonkTcTypeToType env2 t2 ; return (env2, WpFun c1' c2' t1' t2') } zonkCoFn env (WpCast co) = do { co' <- zonkTcCoToCo env co ; return (env, WpCast co') } zonkCoFn env (WpEvLam ev) = do { (env', ev') <- zonkEvBndrX env ev ; return (env', WpEvLam ev') } zonkCoFn env (WpEvApp arg) = do { arg' <- zonkEvTerm env arg ; return (env, WpEvApp arg') } zonkCoFn env (WpTyLam tv) = ASSERT( isImmutableTyVar tv ) do { (env', tv') <- zonkTyBndrX env tv ; return (env', WpTyLam tv') } zonkCoFn env (WpTyApp ty) = do { ty' <- zonkTcTypeToType env ty ; return (env, WpTyApp ty') } zonkCoFn env (WpLet bs) = do { (env1, bs') <- zonkTcEvBinds env bs ; return (env1, WpLet bs') } ------------------------------------------------------------------------- zonkOverLit :: ZonkEnv -> HsOverLit TcId -> TcM (HsOverLit Id) zonkOverLit env lit@(OverLit { ol_witness = e, ol_type = ty }) = do { ty' <- zonkTcTypeToType env ty ; e' <- zonkExpr env e ; return (lit { ol_witness = e', ol_type = ty' }) } ------------------------------------------------------------------------- zonkArithSeq :: ZonkEnv -> ArithSeqInfo TcId -> TcM (ArithSeqInfo Id) zonkArithSeq env (From e) = do new_e <- zonkLExpr env e return (From new_e) zonkArithSeq env (FromThen e1 e2) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 return (FromThen new_e1 new_e2) zonkArithSeq env (FromTo e1 e2) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 return (FromTo new_e1 new_e2) zonkArithSeq env (FromThenTo e1 e2 e3) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 new_e3 <- zonkLExpr env e3 return (FromThenTo new_e1 new_e2 new_e3) ------------------------------------------------------------------------- zonkStmts :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> [LStmt TcId (Located (body TcId))] -> TcM (ZonkEnv, [LStmt Id (Located (body Id))]) zonkStmts env _ [] = return (env, []) zonkStmts env zBody (s:ss) = do { (env1, s') <- wrapLocSndM (zonkStmt env zBody) s ; (env2, ss') <- zonkStmts env1 zBody ss ; return (env2, s' : ss') } zonkStmt :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> Stmt TcId (Located (body TcId)) -> TcM (ZonkEnv, Stmt Id (Located (body Id))) zonkStmt env _ (ParStmt stmts_w_bndrs mzip_op bind_op) = do { new_stmts_w_bndrs <- mapM zonk_branch stmts_w_bndrs ; let new_binders = [b | ParStmtBlock _ bs _ <- new_stmts_w_bndrs, b <- bs] env1 = extendIdZonkEnv env new_binders ; new_mzip <- zonkExpr env1 mzip_op ; new_bind <- zonkExpr env1 bind_op ; return (env1, ParStmt new_stmts_w_bndrs new_mzip new_bind) } where zonk_branch (ParStmtBlock stmts bndrs return_op) = do { (env1, new_stmts) <- zonkStmts env zonkLExpr stmts ; new_return <- zonkExpr env1 return_op ; return (ParStmtBlock new_stmts (zonkIdOccs env1 bndrs) new_return) } zonkStmt env zBody (RecStmt { recS_stmts = segStmts, recS_later_ids = lvs, recS_rec_ids = rvs , recS_ret_fn = ret_id, recS_mfix_fn = mfix_id, recS_bind_fn = bind_id , recS_later_rets = later_rets, recS_rec_rets = rec_rets , recS_ret_ty = ret_ty }) = do { new_rvs <- zonkIdBndrs env rvs ; new_lvs <- zonkIdBndrs env lvs ; new_ret_ty <- zonkTcTypeToType env ret_ty ; new_ret_id <- zonkExpr env ret_id ; new_mfix_id <- zonkExpr env mfix_id ; new_bind_id <- zonkExpr env bind_id ; let env1 = extendIdZonkEnv env new_rvs ; (env2, new_segStmts) <- zonkStmts env1 zBody segStmts -- Zonk the ret-expressions in an envt that -- has the polymorphic bindings in the envt ; new_later_rets <- mapM (zonkExpr env2) later_rets ; new_rec_rets <- mapM (zonkExpr env2) rec_rets ; return (extendIdZonkEnv env new_lvs, -- Only the lvs are needed RecStmt { recS_stmts = new_segStmts, recS_later_ids = new_lvs , recS_rec_ids = new_rvs, recS_ret_fn = new_ret_id , recS_mfix_fn = new_mfix_id, recS_bind_fn = new_bind_id , recS_later_rets = new_later_rets , recS_rec_rets = new_rec_rets, recS_ret_ty = new_ret_ty }) } zonkStmt env zBody (BodyStmt body then_op guard_op ty) = do new_body <- zBody env body new_then <- zonkExpr env then_op new_guard <- zonkExpr env guard_op new_ty <- zonkTcTypeToType env ty return (env, BodyStmt new_body new_then new_guard new_ty) zonkStmt env zBody (LastStmt body noret ret_op) = do new_body <- zBody env body new_ret <- zonkExpr env ret_op return (env, LastStmt new_body noret new_ret) zonkStmt env _ (TransStmt { trS_stmts = stmts, trS_bndrs = binderMap , trS_by = by, trS_form = form, trS_using = using , trS_ret = return_op, trS_bind = bind_op, trS_fmap = liftM_op }) = do { (env', stmts') <- zonkStmts env zonkLExpr stmts ; binderMap' <- mapM (zonkBinderMapEntry env') binderMap ; by' <- fmapMaybeM (zonkLExpr env') by ; using' <- zonkLExpr env using ; return_op' <- zonkExpr env' return_op ; bind_op' <- zonkExpr env' bind_op ; liftM_op' <- zonkExpr env' liftM_op ; let env'' = extendIdZonkEnv env' (map snd binderMap') ; return (env'', TransStmt { trS_stmts = stmts', trS_bndrs = binderMap' , trS_by = by', trS_form = form, trS_using = using' , trS_ret = return_op', trS_bind = bind_op', trS_fmap = liftM_op' }) } where zonkBinderMapEntry env (oldBinder, newBinder) = do let oldBinder' = zonkIdOcc env oldBinder newBinder' <- zonkIdBndr env newBinder return (oldBinder', newBinder') zonkStmt env _ (LetStmt binds) = do (env1, new_binds) <- zonkLocalBinds env binds return (env1, LetStmt new_binds) zonkStmt env zBody (BindStmt pat body bind_op fail_op) = do { new_body <- zBody env body ; (env1, new_pat) <- zonkPat env pat ; new_bind <- zonkExpr env bind_op ; new_fail <- zonkExpr env fail_op ; return (env1, BindStmt new_pat new_body new_bind new_fail) } zonkStmt env _zBody (ApplicativeStmt args mb_join body_ty) = do { (env', args') <- zonk_args env args ; new_mb_join <- traverse (zonkExpr env) mb_join ; new_body_ty <- zonkTcTypeToType env' body_ty ; return (env', ApplicativeStmt args' new_mb_join new_body_ty) } where zonk_args env [] = return (env, []) zonk_args env ((op, arg) : groups) = do { (env1, arg') <- zonk_arg env arg ; op' <- zonkExpr env1 op ; (env2, ss) <- zonk_args env1 groups ; return (env2, (op', arg') : ss) } zonk_arg env (ApplicativeArgOne pat expr) = do { (env1, new_pat) <- zonkPat env pat ; new_expr <- zonkLExpr env expr ; return (env1, ApplicativeArgOne new_pat new_expr) } zonk_arg env (ApplicativeArgMany stmts ret pat) = do { (env1, new_stmts) <- zonkStmts env zonkLExpr stmts ; new_ret <- zonkExpr env1 ret ; (env2, new_pat) <- zonkPat env pat ; return (env2, ApplicativeArgMany new_stmts new_ret new_pat) } ------------------------------------------------------------------------- zonkRecFields :: ZonkEnv -> HsRecordBinds TcId -> TcM (HsRecordBinds TcId) zonkRecFields env (HsRecFields flds dd) = do { flds' <- mapM zonk_rbind flds ; return (HsRecFields flds' dd) } where zonk_rbind (L l fld) = do { new_id <- wrapLocM (zonkIdBndr env) (hsRecFieldId fld) ; new_expr <- zonkLExpr env (hsRecFieldArg fld) ; return (L l (fld { hsRecFieldId = new_id , hsRecFieldArg = new_expr })) } ------------------------------------------------------------------------- mapIPNameTc :: (a -> TcM b) -> Either (Located HsIPName) a -> TcM (Either (Located HsIPName) b) mapIPNameTc _ (Left x) = return (Left x) mapIPNameTc f (Right x) = do r <- f x return (Right r) {- ************************************************************************ * * \subsection[BackSubst-Pats]{Patterns} * * ************************************************************************ -} zonkPat :: ZonkEnv -> OutPat TcId -> TcM (ZonkEnv, OutPat Id) -- Extend the environment as we go, because it's possible for one -- pattern to bind something that is used in another (inside or -- to the right) zonkPat env pat = wrapLocSndM (zonk_pat env) pat zonk_pat :: ZonkEnv -> Pat TcId -> TcM (ZonkEnv, Pat Id) zonk_pat env (ParPat p) = do { (env', p') <- zonkPat env p ; return (env', ParPat p') } zonk_pat env (WildPat ty) = do { ty' <- zonkTcTypeToType env ty ; return (env, WildPat ty') } zonk_pat env (VarPat v) = do { v' <- zonkIdBndr env v ; return (extendIdZonkEnv1 env v', VarPat v') } zonk_pat env (LazyPat pat) = do { (env', pat') <- zonkPat env pat ; return (env', LazyPat pat') } zonk_pat env (BangPat pat) = do { (env', pat') <- zonkPat env pat ; return (env', BangPat pat') } zonk_pat env (AsPat (L loc v) pat) = do { v' <- zonkIdBndr env v ; (env', pat') <- zonkPat (extendIdZonkEnv1 env v') pat ; return (env', AsPat (L loc v') pat') } zonk_pat env (ViewPat expr pat ty) = do { expr' <- zonkLExpr env expr ; (env', pat') <- zonkPat env pat ; ty' <- zonkTcTypeToType env ty ; return (env', ViewPat expr' pat' ty') } zonk_pat env (ListPat pats ty Nothing) = do { ty' <- zonkTcTypeToType env ty ; (env', pats') <- zonkPats env pats ; return (env', ListPat pats' ty' Nothing) } zonk_pat env (ListPat pats ty (Just (ty2,wit))) = do { wit' <- zonkExpr env wit ; ty2' <- zonkTcTypeToType env ty2 ; ty' <- zonkTcTypeToType env ty ; (env', pats') <- zonkPats env pats ; return (env', ListPat pats' ty' (Just (ty2',wit'))) } zonk_pat env (PArrPat pats ty) = do { ty' <- zonkTcTypeToType env ty ; (env', pats') <- zonkPats env pats ; return (env', PArrPat pats' ty') } zonk_pat env (TuplePat pats boxed tys) = do { tys' <- mapM (zonkTcTypeToType env) tys ; (env', pats') <- zonkPats env pats ; return (env', TuplePat pats' boxed tys') } zonk_pat env p@(ConPatOut { pat_arg_tys = tys, pat_tvs = tyvars , pat_dicts = evs, pat_binds = binds , pat_args = args, pat_wrap = wrapper }) = ASSERT( all isImmutableTyVar tyvars ) do { new_tys <- mapM (zonkTcTypeToType env) tys ; (env0, new_tyvars) <- zonkTyBndrsX env tyvars -- Must zonk the existential variables, because their -- /kind/ need potential zonking. -- cf typecheck/should_compile/tc221.hs ; (env1, new_evs) <- zonkEvBndrsX env0 evs ; (env2, new_binds) <- zonkTcEvBinds env1 binds ; (env3, new_wrapper) <- zonkCoFn env2 wrapper ; (env', new_args) <- zonkConStuff env3 args ; return (env', p { pat_arg_tys = new_tys, pat_tvs = new_tyvars, pat_dicts = new_evs, pat_binds = new_binds, pat_args = new_args, pat_wrap = new_wrapper}) } zonk_pat env (LitPat lit) = return (env, LitPat lit) zonk_pat env (SigPatOut pat ty) = do { ty' <- zonkTcTypeToType env ty ; (env', pat') <- zonkPat env pat ; return (env', SigPatOut pat' ty') } zonk_pat env (NPat (L l lit) mb_neg eq_expr) = do { lit' <- zonkOverLit env lit ; mb_neg' <- fmapMaybeM (zonkExpr env) mb_neg ; eq_expr' <- zonkExpr env eq_expr ; return (env, NPat (L l lit') mb_neg' eq_expr') } zonk_pat env (NPlusKPat (L loc n) (L l lit) e1 e2) = do { n' <- zonkIdBndr env n ; lit' <- zonkOverLit env lit ; e1' <- zonkExpr env e1 ; e2' <- zonkExpr env e2 ; return (extendIdZonkEnv1 env n', NPlusKPat (L loc n') (L l lit') e1' e2') } zonk_pat env (CoPat co_fn pat ty) = do { (env', co_fn') <- zonkCoFn env co_fn ; (env'', pat') <- zonkPat env' (noLoc pat) ; ty' <- zonkTcTypeToType env'' ty ; return (env'', CoPat co_fn' (unLoc pat') ty') } zonk_pat _ pat = pprPanic "zonk_pat" (ppr pat) --------------------------- zonkConStuff :: ZonkEnv -> HsConDetails (OutPat TcId) (HsRecFields id (OutPat TcId)) -> TcM (ZonkEnv, HsConDetails (OutPat Id) (HsRecFields id (OutPat Id))) zonkConStuff env (PrefixCon pats) = do { (env', pats') <- zonkPats env pats ; return (env', PrefixCon pats') } zonkConStuff env (InfixCon p1 p2) = do { (env1, p1') <- zonkPat env p1 ; (env', p2') <- zonkPat env1 p2 ; return (env', InfixCon p1' p2') } zonkConStuff env (RecCon (HsRecFields rpats dd)) = do { (env', pats') <- zonkPats env (map (hsRecFieldArg . unLoc) rpats) ; let rpats' = zipWith (\(L l rp) p' -> L l (rp { hsRecFieldArg = p' })) rpats pats' ; return (env', RecCon (HsRecFields rpats' dd)) } -- Field selectors have declared types; hence no zonking --------------------------- zonkPats :: ZonkEnv -> [OutPat TcId] -> TcM (ZonkEnv, [OutPat Id]) zonkPats env [] = return (env, []) zonkPats env (pat:pats) = do { (env1, pat') <- zonkPat env pat ; (env', pats') <- zonkPats env1 pats ; return (env', pat':pats') } {- ************************************************************************ * * \subsection[BackSubst-Foreign]{Foreign exports} * * ************************************************************************ -} zonkForeignExports :: ZonkEnv -> [LForeignDecl TcId] -> TcM [LForeignDecl Id] zonkForeignExports env ls = mapM (wrapLocM (zonkForeignExport env)) ls zonkForeignExport :: ZonkEnv -> ForeignDecl TcId -> TcM (ForeignDecl Id) zonkForeignExport env (ForeignExport i _hs_ty co spec) = return (ForeignExport (fmap (zonkIdOcc env) i) undefined co spec) zonkForeignExport _ for_imp = return for_imp -- Foreign imports don't need zonking zonkRules :: ZonkEnv -> [LRuleDecl TcId] -> TcM [LRuleDecl Id] zonkRules env rs = mapM (wrapLocM (zonkRule env)) rs zonkRule :: ZonkEnv -> RuleDecl TcId -> TcM (RuleDecl Id) zonkRule env (HsRule name act (vars{-::[RuleBndr TcId]-}) lhs fv_lhs rhs fv_rhs) = do { unbound_tkv_set <- newMutVar emptyVarSet ; let env_rule = setZonkType env (zonkTvCollecting unbound_tkv_set) -- See Note [Zonking the LHS of a RULE] ; (env_inside, new_bndrs) <- mapAccumLM zonk_bndr env_rule vars ; new_lhs <- zonkLExpr env_inside lhs ; new_rhs <- zonkLExpr env_inside rhs ; unbound_tkvs <- readMutVar unbound_tkv_set ; let final_bndrs :: [LRuleBndr Var] final_bndrs = map (noLoc . RuleBndr . noLoc) (varSetElemsKvsFirst unbound_tkvs) ++ new_bndrs ; return $ HsRule name act final_bndrs new_lhs fv_lhs new_rhs fv_rhs } where zonk_bndr env (L l (RuleBndr (L loc v))) = do { (env', v') <- zonk_it env v ; return (env', L l (RuleBndr (L loc v'))) } zonk_bndr _ (L _ (RuleBndrSig {})) = panic "zonk_bndr RuleBndrSig" zonk_it env v | isId v = do { v' <- zonkIdBndr env v ; return (extendIdZonkEnv1 env v', v') } | otherwise = ASSERT( isImmutableTyVar v) zonkTyBndrX env v -- DV: used to be return (env,v) but that is plain -- wrong because we may need to go inside the kind -- of v and zonk there! zonkVects :: ZonkEnv -> [LVectDecl TcId] -> TcM [LVectDecl Id] zonkVects env = mapM (wrapLocM (zonkVect env)) zonkVect :: ZonkEnv -> VectDecl TcId -> TcM (VectDecl Id) zonkVect env (HsVect s v e) = do { v' <- wrapLocM (zonkIdBndr env) v ; e' <- zonkLExpr env e ; return $ HsVect s v' e' } zonkVect env (HsNoVect s v) = do { v' <- wrapLocM (zonkIdBndr env) v ; return $ HsNoVect s v' } zonkVect _env (HsVectTypeOut s t rt) = return $ HsVectTypeOut s t rt zonkVect _ (HsVectTypeIn _ _ _ _) = panic "TcHsSyn.zonkVect: HsVectTypeIn" zonkVect _env (HsVectClassOut c) = return $ HsVectClassOut c zonkVect _ (HsVectClassIn _ _) = panic "TcHsSyn.zonkVect: HsVectClassIn" zonkVect _env (HsVectInstOut i) = return $ HsVectInstOut i zonkVect _ (HsVectInstIn _) = panic "TcHsSyn.zonkVect: HsVectInstIn" {- ************************************************************************ * * Constraints and evidence * * ************************************************************************ -} zonkEvTerm :: ZonkEnv -> EvTerm -> TcM EvTerm zonkEvTerm env (EvId v) = ASSERT2( isId v, ppr v ) return (EvId (zonkIdOcc env v)) zonkEvTerm env (EvCoercion co) = do { co' <- zonkTcCoToCo env co ; return (EvCoercion co') } zonkEvTerm env (EvCast tm co) = do { tm' <- zonkEvTerm env tm ; co' <- zonkTcCoToCo env co ; return (mkEvCast tm' co') } zonkEvTerm _ (EvLit l) = return (EvLit l) zonkEvTerm env (EvTypeable ev) = fmap EvTypeable $ case ev of EvTypeableTyCon tc ks -> return (EvTypeableTyCon tc ks) EvTypeableTyApp t1 t2 -> do e1 <- zonk t1 e2 <- zonk t2 return (EvTypeableTyApp e1 e2) EvTypeableTyLit t -> EvTypeableTyLit `fmap` zonk t where zonk (ev,t) = do ev' <- zonkEvTerm env ev t' <- zonkTcTypeToType env t return (ev',t') zonkEvTerm env (EvCallStack cs) = case cs of EvCsEmpty -> return (EvCallStack cs) EvCsTop n l tm -> do { tm' <- zonkEvTerm env tm ; return (EvCallStack (EvCsTop n l tm')) } EvCsPushCall n l tm -> do { tm' <- zonkEvTerm env tm ; return (EvCallStack (EvCsPushCall n l tm')) } zonkEvTerm env (EvSuperClass d n) = do { d' <- zonkEvTerm env d ; return (EvSuperClass d' n) } zonkEvTerm env (EvDFunApp df tys tms) = do { tys' <- zonkTcTypeToTypes env tys ; return (EvDFunApp (zonkIdOcc env df) tys' (zonkIdOccs env tms)) } zonkEvTerm env (EvDelayedError ty msg) = do { ty' <- zonkTcTypeToType env ty ; return (EvDelayedError ty' msg) } zonkTcEvBinds_s :: ZonkEnv -> [TcEvBinds] -> TcM (ZonkEnv, [TcEvBinds]) zonkTcEvBinds_s env bs = do { (env, bs') <- mapAccumLM zonk_tc_ev_binds env bs ; return (env, [EvBinds (unionManyBags bs')]) } zonkTcEvBinds :: ZonkEnv -> TcEvBinds -> TcM (ZonkEnv, TcEvBinds) zonkTcEvBinds env bs = do { (env', bs') <- zonk_tc_ev_binds env bs ; return (env', EvBinds bs') } zonk_tc_ev_binds :: ZonkEnv -> TcEvBinds -> TcM (ZonkEnv, Bag EvBind) zonk_tc_ev_binds env (TcEvBinds var) = zonkEvBindsVar env var zonk_tc_ev_binds env (EvBinds bs) = zonkEvBinds env bs zonkEvBindsVar :: ZonkEnv -> EvBindsVar -> TcM (ZonkEnv, Bag EvBind) zonkEvBindsVar env (EvBindsVar ref _) = do { bs <- readMutVar ref ; zonkEvBinds env (evBindMapBinds bs) } zonkEvBinds :: ZonkEnv -> Bag EvBind -> TcM (ZonkEnv, Bag EvBind) zonkEvBinds env binds = {-# SCC "zonkEvBinds" #-} fixM (\ ~( _, new_binds) -> do { let env1 = extendIdZonkEnv env (collect_ev_bndrs new_binds) ; binds' <- mapBagM (zonkEvBind env1) binds ; return (env1, binds') }) where collect_ev_bndrs :: Bag EvBind -> [EvVar] collect_ev_bndrs = foldrBag add [] add (EvBind { eb_lhs = var }) vars = var : vars zonkEvBind :: ZonkEnv -> EvBind -> TcM EvBind zonkEvBind env (EvBind { eb_lhs = var, eb_rhs = term, eb_is_given = is_given }) = do { var' <- {-# SCC "zonkEvBndr" #-} zonkEvBndr env var -- Optimise the common case of Refl coercions -- See Note [Optimise coercion zonking] -- This has a very big effect on some programs (eg Trac #5030) ; term' <- case getEqPredTys_maybe (idType var') of Just (r, ty1, ty2) | ty1 `eqType` ty2 -> return (EvCoercion (mkTcReflCo r ty1)) _other -> zonkEvTerm env term ; return (EvBind { eb_lhs = var', eb_rhs = term', eb_is_given = is_given }) } {- ************************************************************************ * * Zonking types * * ************************************************************************ Note [Zonking the LHS of a RULE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We need to gather the type variables mentioned on the LHS so we can quantify over them. Example: data T a = C foo :: T a -> Int foo C = 1 {-# RULES "myrule" foo C = 1 #-} After type checking the LHS becomes (foo a (C a)) and we do not want to zap the unbound tyvar 'a' to (), because that limits the applicability of the rule. Instead, we want to quantify over it! It's easiest to get zonkTvCollecting to gather the free tyvars here. Attempts to do so earlier are tiresome, because (a) the data type is big and (b) finding the free type vars of an expression is necessarily monadic operation. (consider /\a -> f @ b, where b is side-effected to a) And that in turn is why ZonkEnv carries the function to use for type variables! Note [Zonking mutable unbound type or kind variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In zonkTypeZapping, we zonk mutable but unbound type or kind variables to an arbitrary type. We know if they are unbound even though we don't carry an environment, because at the binding site for a variable we bind the mutable var to a fresh immutable one. So the mutable store plays the role of an environment. If we come across a mutable variable that isn't so bound, it must be completely free. We zonk the expected kind to make sure we don't get some unbound meta variable as the kind. Note that since we have kind polymorphism, zonk_unbound_tyvar will handle both type and kind variables. Consider the following datatype: data Phantom a = Phantom Int The type of Phantom is (forall (k : BOX). forall (a : k). Int). Both `a` and `k` are unbound variables. We want to zonk this to (forall (k : AnyK). forall (a : Any AnyK). Int). For that we have to check if we have a type or a kind variable; for kind variables we just return AnyK (and not the ill-kinded Any BOX). Note [Optimise coercion zonkind] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When optimising evidence binds we may come across situations where a coercion looks like cv = ReflCo ty or cv1 = cv2 where the type 'ty' is big. In such cases it is a waste of time to zonk both * The variable on the LHS * The coercion on the RHS Rather, we can zonk the variable, and if its type is (ty ~ ty), we can just use Refl on the right, ignoring the actual coercion on the RHS. This can have a very big effect, because the constraint solver sometimes does go to a lot of effort to prove Refl! (Eg when solving 10+3 = 10+3; cf Trac #5030) -} zonkTyVarOcc :: ZonkEnv -> TyVar -> TcM TcType zonkTyVarOcc env@(ZonkEnv zonk_unbound_tyvar tv_env _) tv | isTcTyVar tv = case tcTyVarDetails tv of SkolemTv {} -> lookup_in_env RuntimeUnk {} -> lookup_in_env FlatSkol ty -> zonkTcTypeToType env ty MetaTv { mtv_ref = ref } -> do { cts <- readMutVar ref ; case cts of Flexi -> do { kind <- {-# SCC "zonkKind1" #-} zonkTcTypeToType env (tyVarKind tv) ; zonk_unbound_tyvar (setTyVarKind tv kind) } Indirect ty -> do { zty <- zonkTcTypeToType env ty -- Small optimisation: shortern-out indirect steps -- so that the old type may be more easily collected. ; writeMutVar ref (Indirect zty) ; return zty } } | otherwise = lookup_in_env where lookup_in_env -- Look up in the env just as we do for Ids = case lookupVarEnv tv_env tv of Nothing -> return (mkTyVarTy tv) Just tv' -> return (mkTyVarTy tv') zonkTcTypeToType :: ZonkEnv -> TcType -> TcM Type zonkTcTypeToType env ty = go ty where go (TyConApp tc tys) = do tys' <- mapM go tys return (mkTyConApp tc tys') -- Establish Type invariants -- See Note [Zonking inside the knot] in TcHsType go (LitTy n) = return (LitTy n) go (FunTy arg res) = do arg' <- go arg res' <- go res return (FunTy arg' res') go (AppTy fun arg) = do fun' <- go fun arg' <- go arg return (mkAppTy fun' arg') -- NB the mkAppTy; we might have instantiated a -- type variable to a type constructor, so we need -- to pull the TyConApp to the top. -- The two interesting cases! go (TyVarTy tv) = zonkTyVarOcc env tv go (ForAllTy tv ty) = ASSERT( isImmutableTyVar tv ) do { (env', tv') <- zonkTyBndrX env tv ; ty' <- zonkTcTypeToType env' ty ; return (ForAllTy tv' ty') } zonkTcTypeToTypes :: ZonkEnv -> [TcType] -> TcM [Type] zonkTcTypeToTypes env tys = mapM (zonkTcTypeToType env) tys zonkCoToCo :: ZonkEnv -> Coercion -> TcM Coercion zonkCoToCo env co = go co where go (Refl r ty) = mkReflCo r <$> zonkTcTypeToType env ty go (TyConAppCo r tc args) = mkTyConAppCo r tc <$> mapM go args go (AppCo co arg) = mkAppCo <$> go co <*> go arg go (AxiomInstCo ax ind args) = AxiomInstCo ax ind <$> mapM go args go (UnivCo s r ty1 ty2) = mkUnivCo s r <$> zonkTcTypeToType env ty1 <*> zonkTcTypeToType env ty2 go (SymCo co) = mkSymCo <$> go co go (TransCo co1 co2) = mkTransCo <$> go co1 <*> go co2 go (NthCo n co) = mkNthCo n <$> go co go (LRCo lr co) = mkLRCo lr <$> go co go (InstCo co arg) = mkInstCo <$> go co <*> zonkTcTypeToType env arg go (SubCo co) = mkSubCo <$> go co go (AxiomRuleCo ax ts cs) = AxiomRuleCo ax <$> mapM (zonkTcTypeToType env) ts <*> mapM go cs -- The two interesting cases! go (CoVarCo cv) = return (mkCoVarCo $ zonkIdOcc env cv) go (ForAllCo tv co) = ASSERT( isImmutableTyVar tv ) do { (env', tv') <- zonkTyBndrX env tv ; co' <- zonkCoToCo env' co ; return (mkForAllCo tv' co') } zonkTvCollecting :: TcRef TyVarSet -> UnboundTyVarZonker -- This variant collects unbound type variables in a mutable variable -- Works on both types and kinds zonkTvCollecting unbound_tv_set tv = do { poly_kinds <- xoptM Opt_PolyKinds ; if isKindVar tv && not poly_kinds then defaultKindVarToStar tv else do { tv' <- zonkQuantifiedTyVar tv ; tv_set <- readMutVar unbound_tv_set ; writeMutVar unbound_tv_set (extendVarSet tv_set tv') ; return (mkTyVarTy tv') } } zonkTypeZapping :: UnboundTyVarZonker -- This variant is used for everything except the LHS of rules -- It zaps unbound type variables to (), or some other arbitrary type -- Works on both types and kinds zonkTypeZapping tv = do { let ty = if isKindVar tv -- ty is actually a kind, zonk to AnyK then anyKind else anyTypeOfKind (defaultKind (tyVarKind tv)) ; writeMetaTyVar tv ty ; return ty } zonkTcCoToCo :: ZonkEnv -> TcCoercion -> TcM TcCoercion -- NB: zonking often reveals that the coercion is an identity -- in which case the Refl-ness can propagate up to the top -- which in turn gives more efficient desugaring. So it's -- worth using the 'mk' smart constructors on the RHS zonkTcCoToCo env co = go co where go (TcLetCo bs co) = do { (env', bs') <- zonkTcEvBinds env bs ; co' <- zonkTcCoToCo env' co ; return (TcLetCo bs' co') } go (TcCoVarCo cv) = return (mkTcCoVarCo (zonkEvVarOcc env cv)) go (TcRefl r ty) = do { ty' <- zonkTcTypeToType env ty ; return (TcRefl r ty') } go (TcTyConAppCo r tc cos) = do { cos' <- mapM go cos; return (mkTcTyConAppCo r tc cos') } go (TcAxiomInstCo ax ind cos) = do { cos' <- mapM go cos; return (TcAxiomInstCo ax ind cos') } go (TcAppCo co1 co2) = do { co1' <- go co1; co2' <- go co2 ; return (mkTcAppCo co1' co2') } go (TcCastCo co1 co2) = do { co1' <- go co1; co2' <- go co2 ; return (TcCastCo co1' co2') } go (TcPhantomCo ty1 ty2) = do { ty1' <- zonkTcTypeToType env ty1 ; ty2' <- zonkTcTypeToType env ty2 ; return (TcPhantomCo ty1' ty2') } go (TcSymCo co) = do { co' <- go co; return (mkTcSymCo co') } go (TcNthCo n co) = do { co' <- go co; return (mkTcNthCo n co') } go (TcLRCo lr co) = do { co' <- go co; return (mkTcLRCo lr co') } go (TcTransCo co1 co2) = do { co1' <- go co1; co2' <- go co2 ; return (mkTcTransCo co1' co2') } go (TcForAllCo tv co) = ASSERT( isImmutableTyVar tv ) do { co' <- go co; return (mkTcForAllCo tv co') } go (TcSubCo co) = do { co' <- go co; return (mkTcSubCo co') } go (TcAxiomRuleCo co ts cs) = do { ts' <- zonkTcTypeToTypes env ts ; cs' <- mapM go cs ; return (TcAxiomRuleCo co ts' cs') } go (TcCoercion co) = do { co' <- zonkCoToCo env co ; return (TcCoercion co') }
ml9951/ghc
compiler/typecheck/TcHsSyn.hs
bsd-3-clause
64,653
2
19
19,179
18,719
9,364
9,355
-1
-1
module Lang.LamIf.Semantics where import FP import MAAM import Lang.LamIf.Syntax hiding (PreExp(..)) import Lang.LamIf.CPS import Lang.LamIf.StateSpace type Ψ = LocNum -- These are the raw constraints that must hold for: -- - time lτ and dτ -- - values val -- - the monad m type TimeC τ = ( Time Ψ τ , Bot τ , Ord τ , Pretty τ ) type ValC lτ dτ val = ( Val lτ dτ val , Ord val , PartialOrder val , JoinLattice val , Difference val , Pretty val ) type MonadC val lτ dτ m = ( Monad m, MonadBot m, MonadPlus m , MonadState (𝒮 val lτ dτ) m ) -- This type class aids type inference. The functional dependencies tell the -- type checker that choices for val, lτ, dτ and 𝓈 are unique for a given -- m. class ( TimeC lτ , TimeC dτ , ValC lτ dτ val , MonadC val lτ dτ m ) => Analysis val lτ dτ m | m -> val , m -> lτ , m -> dτ where -- Some helper types type GC m = Call -> m () type CreateClo lτ dτ m = LocNum -> [Name] -> Call -> m (Clo lτ dτ) type TimeFilter = Call -> Bool -- Generate a new address new :: (Analysis val lτ dτ m) => Name -> m (Addr lτ dτ) new x = do lτ <- getL 𝓈lτL dτ <- getL 𝓈dτL return $ Addr x lτ dτ -- bind a name to a value in an environment bind :: (Analysis val lτ dτ m) => Name -> val -> Map Name (Addr lτ dτ) -> m (Map Name (Addr lτ dτ)) bind x vD ρ = do l <- new x modifyL 𝓈σL $ mapInsertWith (\/) l vD return $ mapInsert x l ρ -- bind a name to a value in _the_ environment bindM :: (Analysis val lτ dτ m) => Name -> val -> m () bindM x vD = do ρ <- getL 𝓈ρL ρ' <- bind x vD ρ putL 𝓈ρL ρ' -- rebinds the value assigned to a name rebind :: (Analysis val lτ dτ m) => Name -> val -> m () rebind x vD = do ρ <- getL 𝓈ρL let l = ρ #! x modifyL 𝓈σL $ mapInsert l vD -- rebinds the value assigned to a pico if it is a name rebindPico :: (Analysis val lτ dτ m) => PrePico Name -> val -> m () rebindPico (Lit _) _ = return () rebindPico (Var x) vD = rebind x vD -- the denotation for addresses addr :: (Analysis val lτ dτ m) => Addr lτ dτ -> m val addr 𝓁 = do σ <- getL 𝓈σL maybeZero $ σ # 𝓁 -- the denotation for variables var :: (Analysis val lτ dτ m) => Name -> m val var x = do ρ <- getL 𝓈ρL 𝓁 <- maybeZero $ ρ # x addr 𝓁 -- the denotation for lambdas lam :: (Analysis val lτ dτ m) => CreateClo lτ dτ m -> LocNum -> [Name] -> Call -> m val lam createClo = clo ^..: createClo -- the partial denotation for pico (for storing in values) picoRef :: (Analysis val lτ dτ m) => Pico -> m (PicoVal lτ dτ) picoRef (Lit l) = return $ LitPicoVal l picoRef (Var x) = do ρ <- getL 𝓈ρL AddrPicoVal ^$ maybeZero $ ρ # x picoVal :: (Analysis val lτ dτ m) => PicoVal lτ dτ -> m val picoVal (LitPicoVal l) = return $ lit l picoVal (AddrPicoVal 𝓁) = addr 𝓁 -- the denotation for the pico syntactic category pico :: (Analysis val lτ dτ m) => Pico -> m val pico = picoVal *. picoRef -- the denotation for the atom syntactic category atom :: (Analysis val lτ dτ m) => CreateClo lτ dτ m -> Atom -> m val atom createClo a = case stamped a of Pico p -> pico p Prim o a1 a2 -> return (binop $ lbinOpOp o) <@> pico a1 <@> pico a2 LamF x kx c -> lam createClo (stampedID a) [x, kx] c LamK x c -> lam createClo (stampedID a) [x] c Tup p1 p2 -> pure (curry tup) <@> picoRef p1 <@> picoRef p2 Pi1 p -> picoVal *. fst ^. mset . elimTup *$ pico p Pi2 p -> picoVal *. snd ^. mset . elimTup *$ pico p apply :: (Analysis val lτ dτ m) => TimeFilter -> Call -> PrePico Name -> val -> [val] -> m Call apply timeFilter c fx fv avs = do fclo@(Clo cid' xs c' ρ lτ) <- mset $ elimClo fv rebindPico fx $ clo fclo xvs <- maybeZero $ zip xs avs putL 𝓈ρL ρ traverseOn xvs $ uncurry $ bindM putL 𝓈lτL lτ when (timeFilter c) $ modifyL 𝓈lτL $ tick cid' return c' call :: (Analysis val lτ dτ m) => GC m -> CreateClo lτ dτ m -> TimeFilter -> TimeFilter -> Call -> m Call call gc createClo ltimeFilter dtimeFilter c = do when (dtimeFilter c) $ modifyL 𝓈dτL $ tick $ stampedFixID c c' <- case stampedFix c of Let x a c' -> do v <- atom createClo a bindM x v return c' If ax tc fc -> do b <- mset . elimBool *$ pico ax rebindPico ax $ lit $ B b return $ if b then tc else fc AppF fx ax ka -> do fv <- pico fx av <- pico ax kv <- pico ka apply ltimeFilter c fx fv [av, kv] AppK kx ax -> do kv <- pico kx av <- pico ax apply ltimeFilter c kx kv [av] Halt _ -> return c gc c' return c' onlyStuck :: (MonadStep ς m, Analysis val lτ dτ m) => GC m -> CreateClo lτ dτ m -> TimeFilter -> TimeFilter -> Call -> m Call onlyStuck gc createClo ltimeFilter dtimeFilter e = do e' <- call gc createClo ltimeFilter dtimeFilter e if e == e' then return e else mbot -- Execution {{{ type StateSpaceC ς' = ( PartialOrder (ς' Call) , JoinLattice (ς' Call) , Difference (ς' Call) , Pretty (ς' Call) ) class (MonadStep ς m, Inject ς, Isomorphism (ς Call) (ς' Call), StateSpaceC ς') => Execution ς ς' m | m -> ς, m -> ς' liftς :: (Execution ς ς' m) => (Call -> m Call) -> (ς' Call -> ς' Call) liftς f = isoto . mstepγ f . isofrom injectς :: forall ς ς' a. (Inject ς, Isomorphism (ς a) (ς' a)) => P ς -> a -> ς' a injectς P = isoto . (inj :: a -> ς a) execς :: forall val lτ dτ m ς ς'. (Analysis val lτ dτ m, Execution ς ς' m) => GC m -> CreateClo lτ dτ m -> TimeFilter -> TimeFilter -> Call -> ς' Call execς gc createClo ltimeFilter dtimeFilter = poiter (liftς $ call gc createClo ltimeFilter dtimeFilter) . injectς (P :: P ς) execCollect :: forall val lτ dτ m ς ς'. (Analysis val lτ dτ m, Execution ς ς' m) => GC m -> CreateClo lτ dτ m -> TimeFilter -> TimeFilter -> Call -> ς' Call execCollect gc createClo ltimeFilter dtimeFilter = collect (liftς $ call gc createClo ltimeFilter dtimeFilter) . injectς (P :: P ς) execCollectHistory :: forall val lτ dτ m ς ς'. (Analysis val lτ dτ m, Execution ς ς' m) => GC m -> CreateClo lτ dτ m -> TimeFilter -> TimeFilter -> Call -> [ς' Call] execCollectHistory gc createClo ltimeFilter dtimeFilter = collectHistory (liftς $ call gc createClo ltimeFilter dtimeFilter) . injectς (P :: P ς) execCollectDiffs :: forall val lτ dτ m ς ς'. (Analysis val lτ dτ m, Execution ς ς' m) => GC m -> CreateClo lτ dτ m -> TimeFilter -> TimeFilter -> Call -> [ς' Call] execCollectDiffs gc createClo ltimeFilter dtimeFilter = collectDiffs (liftς $ call gc createClo ltimeFilter dtimeFilter) . injectς (P :: P ς) execOnlyStuck :: (Analysis val lτ dτ m, Execution ς ς' m) => GC m -> CreateClo lτ dτ m -> TimeFilter -> TimeFilter -> Call -> ς' Call execOnlyStuck gc createClo ltimeFilter dtimeFilter = liftς (onlyStuck gc createClo ltimeFilter dtimeFilter) . execCollect gc createClo ltimeFilter dtimeFilter -- }}} -- GC {{{ nogc :: (Monad m) => Call -> m () nogc _ = return () yesgc :: (Analysis val lτ dτ m) => Call -> m () yesgc c = do ρ <- getL 𝓈ρL σ <- getL 𝓈σL let live0 = callTouched ρ $ freeVarsLam empty [] c let live = collect (extend $ addrTouched σ) live0 modifyL 𝓈σL $ onlyKeys live callTouched :: (TimeC lτ, TimeC dτ) => Env lτ dτ -> Set Name -> Set (Addr lτ dτ) callTouched ρ xs = maybeSet . index ρ *$ xs closureTouched :: (TimeC lτ, TimeC dτ) => Clo lτ dτ -> Set (Addr lτ dτ) closureTouched (Clo _ xs c ρ _) = callTouched ρ $ freeVarsLam empty xs c picoValTouched :: (TimeC lτ, TimeC dτ) => PicoVal lτ dτ -> Set (Addr lτ dτ) picoValTouched (LitPicoVal _) = empty picoValTouched (AddrPicoVal 𝓁) = single 𝓁 tupleTouched :: (TimeC lτ, TimeC dτ) => (PicoVal lτ dτ, PicoVal lτ dτ) -> Set (Addr lτ dτ) tupleTouched (pv1, pv2) = picoValTouched pv1 \/ picoValTouched pv2 addrTouched :: (TimeC lτ, TimeC dτ, ValC lτ dτ val) => Map (Addr lτ dτ) val -> Addr lτ dτ -> Set (Addr lτ dτ) addrTouched σ 𝓁 = do v <- maybeSet $ σ # 𝓁 msum [ closureTouched *$ elimClo v , tupleTouched *$ elimTup v ] -- }}} -- CreateClo {{{ linkClo :: (Analysis val lτ dτ m) => LocNum -> [Name] -> Call -> m (Clo lτ dτ) linkClo cid xs c = do ρ <- getL 𝓈ρL lτ <- getL 𝓈lτL return $ Clo cid xs c ρ lτ copyClo :: (Analysis val lτ dτ m) => LocNum -> [Name] -> Call -> m (Clo lτ dτ) copyClo cid xs c = do let ys = toList $ freeVarsLam empty xs c vs <- var ^*$ ys yvs <- maybeZero $ zip ys vs ρ <- runKleisliEndo mapEmpty *$ execWriterT $ do traverseOn yvs $ tell . KleisliEndo . uncurry bind lτ <- getL 𝓈lτL return $ Clo cid xs c ρ lτ -- }}} -- Parametric Execution {{{ type UniTime τ = W (TimeC τ) data ExTime where ExTime :: forall τ. UniTime τ -> ExTime type UniVal val = forall lτ dτ. (TimeC lτ, TimeC dτ) => W (ValC lτ dτ (val lτ dτ)) data ExVal where ExVal :: forall val. UniVal val -> ExVal type UniMonad ς ς' m = forall val lτ dτ. (TimeC lτ, TimeC dτ, ValC lτ dτ val) => W (Analysis val lτ dτ (m val lτ dτ), Execution (ς val lτ dτ) (ς' val lτ dτ) (m val lτ dτ)) data ExMonad where ExMonad :: forall ς ς' m. UniMonad ς ς' m -> ExMonad newtype AllGC = AllGC { runAllGC :: forall val lτ dτ m. (Analysis val lτ dτ m) => GC m } newtype AllCreateClo = AllCreateClo { runAllCreateClo :: forall val lτ dτ m. (Analysis val lτ dτ m) => CreateClo lτ dτ m } data Options = Options { ltimeOp :: ExTime , dtimeOp :: ExTime , valOp :: ExVal , monadOp :: ExMonad , gcOp :: AllGC , createCloOp :: AllCreateClo , ltimeFilterOp :: TimeFilter , dtimeFilterOp :: TimeFilter } withOptions :: forall a. Options -> ((Analysis val lτ dτ m, Execution ς ς' m) => GC m -> CreateClo lτ dτ m -> TimeFilter -> TimeFilter -> a) -> a withOptions o f = case o of Options (ExTime (W :: UniTime lτ)) (ExTime (W :: UniTime dτ)) (ExVal (W :: W (ValC lτ dτ (val lτ dτ)))) (ExMonad (W :: W ( Analysis (val lτ dτ) lτ dτ (m (val lτ dτ) lτ dτ) , Execution (ς (val lτ dτ) lτ dτ) (ς' (val lτ dτ) lτ dτ) (m (val lτ dτ) lτ dτ)))) (AllGC (gc :: GC (m (val lτ dτ) lτ dτ))) (AllCreateClo (createClo :: CreateClo lτ dτ (m (val lτ dτ) lτ dτ))) (ltimeFilter :: TimeFilter) (dtimeFilter :: TimeFilter) -> f gc createClo ltimeFilter dtimeFilter -- }}}
FranklinChen/maam
src/Lang/LamIf/Semantics.hs
bsd-3-clause
10,617
184
29
2,569
4,958
2,517
2,441
-1
-1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Macro.PkgAesonGeneric where import Macro.Types import Data.Aeson as Aeson import Data.ByteString.Lazy as BS import Data.Maybe serialise :: [GenericPackageDescription] -> BS.ByteString serialise pkgs = Aeson.encode pkgs deserialise :: BS.ByteString -> [GenericPackageDescription] deserialise = fromJust . Aeson.decode' instance ToJSON Version instance ToJSON PackageName instance ToJSON PackageId instance ToJSON VersionRange instance ToJSON Dependency instance ToJSON CompilerFlavor instance ToJSON License instance ToJSON SourceRepo instance ToJSON RepoKind instance ToJSON RepoType instance ToJSON BuildType instance ToJSON Library instance ToJSON Executable instance ToJSON TestSuite instance ToJSON TestSuiteInterface instance ToJSON TestType instance ToJSON Benchmark instance ToJSON BenchmarkInterface instance ToJSON BenchmarkType instance ToJSON BuildInfo instance ToJSON ModuleName instance ToJSON Language instance ToJSON Extension instance ToJSON KnownExtension instance ToJSON PackageDescription instance ToJSON OS instance ToJSON Arch instance ToJSON Flag instance ToJSON FlagName instance (ToJSON a, ToJSON b, ToJSON c) => ToJSON (CondTree a b c) instance ToJSON ConfVar instance ToJSON a => ToJSON (Condition a) instance ToJSON GenericPackageDescription instance FromJSON Version instance FromJSON PackageName instance FromJSON PackageId instance FromJSON VersionRange instance FromJSON Dependency instance FromJSON CompilerFlavor instance FromJSON License instance FromJSON SourceRepo instance FromJSON RepoKind instance FromJSON RepoType instance FromJSON BuildType instance FromJSON Library instance FromJSON Executable instance FromJSON TestSuite instance FromJSON TestSuiteInterface instance FromJSON TestType instance FromJSON Benchmark instance FromJSON BenchmarkInterface instance FromJSON BenchmarkType instance FromJSON BuildInfo instance FromJSON ModuleName instance FromJSON Language instance FromJSON Extension instance FromJSON KnownExtension instance FromJSON PackageDescription instance FromJSON OS instance FromJSON Arch instance FromJSON Flag instance FromJSON FlagName instance (FromJSON a, FromJSON b, FromJSON c) => FromJSON (CondTree a b c) instance FromJSON ConfVar instance FromJSON a => FromJSON (Condition a) instance FromJSON GenericPackageDescription
arianvp/binary-serialise-cbor
bench/Macro/PkgAesonGeneric.hs
bsd-3-clause
2,344
0
7
270
634
292
342
76
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module Ros.Sensor_msgs.Illuminance where import qualified Prelude as P import Prelude ((.), (+), (*)) import qualified Data.Typeable as T import Control.Applicative import Ros.Internal.RosBinary import Ros.Internal.Msg.MsgInfo import qualified GHC.Generics as G import qualified Data.Default.Generics as D import Ros.Internal.Msg.HeaderSupport import qualified Ros.Std_msgs.Header as Header import Lens.Family.TH (makeLenses) import Lens.Family (view, set) data Illuminance = Illuminance { _header :: Header.Header , _illuminance :: P.Double , _variance :: P.Double } deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic) $(makeLenses ''Illuminance) instance RosBinary Illuminance where put obj' = put (_header obj') *> put (_illuminance obj') *> put (_variance obj') get = Illuminance <$> get <*> get <*> get putMsg = putStampedMsg instance HasHeader Illuminance where getSequence = view (header . Header.seq) getFrame = view (header . Header.frame_id) getStamp = view (header . Header.stamp) setSequence = set (header . Header.seq) instance MsgInfo Illuminance where sourceMD5 _ = "8cf5febb0952fca9d650c3d11a81a188" msgTypeName _ = "sensor_msgs/Illuminance" instance D.Default Illuminance
acowley/roshask
msgs/Sensor_msgs/Ros/Sensor_msgs/Illuminance.hs
bsd-3-clause
1,451
1
10
287
380
221
159
35
0
module Language.Haskell.Liquid.Constraint.ToFixpoint ( cgInfoFInfo ) where import qualified Language.Fixpoint.Types as F import Language.Haskell.Liquid.Constraint.Types import Language.Haskell.Liquid.Types hiding ( binds ) import Language.Fixpoint.Misc ( mapSnd ) import Language.Fixpoint.Interface ( parseFInfo ) import Control.Applicative ((<$>)) import qualified Data.HashMap.Strict as M import Data.Monoid import Language.Haskell.Liquid.Qualifier import Language.Haskell.Liquid.RefType ( rTypeSortedReft ) cgInfoFInfo :: GhcInfo -> CGInfo -> IO (F.FInfo Cinfo) cgInfoFInfo info cgi = do let tgtFI = targetFInfo info cgi impFI <- parseFInfo $ hqFiles info return $ tgtFI <> impFI targetFInfo :: GhcInfo -> CGInfo -> F.FInfo Cinfo targetFInfo info cgi = F.FI { F.cm = M.fromList $ F.addIds $ fixCs cgi , F.ws = fixWfs cgi , F.bs = binds cgi , F.gs = F.fromListSEnv . map mkSort $ meas spc , F.lits = lits cgi , F.kuts = kuts cgi , F.quals = targetQuals info , F.bindInfo = (`Ci` Nothing) <$> bindSpans cgi } where spc = spec info tce = tcEmbeds spc mkSort = mapSnd (rTypeSortedReft tce . val) targetQuals :: GhcInfo -> [F.Qualifier] targetQuals info = spcQs ++ genQs where spcQs = qualifiers spc genQs = specificationQualifiers n info n = maxParams $ config spc spc = spec info
mightymoose/liquidhaskell
src/Language/Haskell/Liquid/Constraint/ToFixpoint.hs
bsd-3-clause
1,572
0
10
482
441
246
195
36
1
{- | Module : $Id$ Description : testing mere CASL basic specs Copyright : (c) Christian Maeder, Uni Bremen 2002-2004 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : experimental Portability : portable test some parsers (and printers) -} module Main where import CASL.Formula import CASL.AS_Basic_CASL import CASL.ToDoc () import CASL.Parse_AS_Basic import Common.AnnoState import Common.RunParsers import CASL.RunMixfixParser import CASL.RunStaticAna main :: IO () main = exec lineParser fileParser lineParser, fileParser :: [(String, StringParser)] lineParser = [ ("Terms", fromAParser (term [] :: AParser () (TERM ()))), ("Formula", fromAParser (formula [] :: AParser () (FORMULA ()))), ("SortItem", fromAParser (sortItems [] :: AParser () (SIG_ITEMS () ()))), ("OpItem", fromAParser (opItems [] :: AParser () (SIG_ITEMS () ()))), ("PredItem", fromAParser (predItems [] :: AParser () (SIG_ITEMS () ()))), ("MixfixTerms", toStringParser resolveTerm), ("MixfixFormula", toStringParser resolveForm), ("ShowTerms", fromAParser testTerm), ("ShowTermsMix", toStringParser testTermMix), ("ShowForm", fromAParser testFormula), ("ShowFormMix", toStringParser testFormulaMix)] fileParser = [("BasicSpec", fromAParser (plainBasicSpec :: AParser () (BASIC_SPEC () () ()))) , ("analysis", toStringParser runAna) , ("signature", toStringParser getSign) , ("sentences", toStringParser getProps) ]
keithodulaigh/Hets
CASL/capa.hs
gpl-2.0
1,565
0
12
305
445
248
197
29
1
module Main where import Build_doctests (deps) import Control.Applicative import Control.Monad import Data.List import System.Directory import System.FilePath import Test.DocTest import Prelude main :: IO () main = getSources >>= \sources -> doctest $ "-isrc" : "-idist/build/autogen" : "-optP-include" : "-optPdist/build/autogen/cabal_macros.h" : "-hide-all-packages" : map ("-package="++) deps ++ sources getSources :: IO [FilePath] getSources = filter (isSuffixOf ".hs") <$> go "src" where go dir = do (dirs, files) <- getFilesAndDirectories dir (files ++) . concat <$> mapM go dirs getFilesAndDirectories :: FilePath -> IO ([FilePath], [FilePath]) getFilesAndDirectories dir = do c <- map (dir </>) . filter (`notElem` ["..", "."]) <$> getDirectoryContents dir (,) <$> filterM doesDirectoryExist c <*> filterM doesFileExist c
fumieval/machines
tests/doctests.hs
bsd-3-clause
870
0
13
150
280
150
130
26
1
module A6 where data T a = T1 a | T3 a | T2 a data S = C1 | C2 | C3 addedT3 = error "added T3 a to T" over :: S -> (T Int) -> Int over a (T3 b) = addedT3 over x (T1 y) = 42 over x (T2 y) = 42
kmate/HaRe
old/testing/addCon/A6AST.hs
bsd-3-clause
201
0
8
66
112
61
51
8
1
-- From nhc13/src/comiler13/Unlit.hs module Unlit(CommentClass(..),unlit,readHaskellFile,writeHaskellFile, optUnlit,isLiterateFile) where import Prelude hiding (readFile) import AbstractIO import MUtils(apFst,pairWith) -- Part of the following code is from "Report on the Programming Language Haskell", -- version 1.2, appendix C. import Data.Char readHaskellFile cpp path = optUnlit path =<< cppFile cpp path writeHaskellFile path code = AbstractIO.writeFile path $ optRelit path code cppFile Nothing path = readFile path cppFile (Just cpp) path = do let tmpname = "hi/readHaskellFile.cpp.tmp" -- Use a unique name!!! ExitSuccess <- system (cpp++" "++path++" >"++tmpname) -- improve error message! src <- readFile tmpname removeFile tmpname return src optRelit path = if isLiterateFile path then relit else id optUnlit path = if isLiterateFile path then \ s -> let ((litcmnts,code),es) = unlit path s in if null es then return (litcmnts,unlines code) else fail (unlines es) else \ s -> return ([],s) isLiterateFile path = last4 path == ".lhs" where last4 = reverse . take 4 . reverse -------------------------------------------------------------------------------- -- basic re-literation hack -- assume {-+\t starts encoded literate comment -- assume > for code by default (lines starting with ' '), -- begin/end only if code starts in first column -- (will keep adding empty lines before \begin{code}..) relit = unlines . inCode False . lines where inCode False [] = [] inCode True [] = ["\\end{code}"] inCode False (x:xs) | take 4 x=="{-+\t" = (drop 4 x):(inComment xs) inCode True (x:xs) | take 4 x=="{-+\t" = "\\end{code}":((drop 4 x):(inComment xs)) inCode False (x:xs) | x=="{-+" = "":(inComment xs) inCode True (x:xs) | x=="{-+" = "\\end{code}":("":(inComment xs)) inCode True (x:xs) = x:(inCode True xs) inCode False (x:xs) | all isSpace x = x:(inCode False xs) inCode False ((' ':x):xs) = ('>':x):(inCode False xs) inCode False (('#':x):xs) = ('#':x):(inCode False xs) inCode False xs@(_:_) = "\\begin{code}":(inCode True xs) inComment [] = [] inComment (x:xs) | x=="-}" = "":(inCode False xs) inComment (x:xs) = x:(inComment xs) -------------------------------------------------------------------------------- --unlit :: String -> String -> String unlit file = --apFst new_unclassify . -- put literate text in nested comments apFst (unzip . map unclassify1) . -- return comment text and code separately pairWith (adjacent (Blank "") . addpos file 0) . -- error checking classify . lines -------------------------------------------------------------------------------- data Classified = Program String String | Blank String | Comment String | Include Int String | Pre String classify :: [String] -> [Classified] classify [] = [] classify (l@('\\':x):xs) | x == "begin{code}" = Blank l : allProg xs where allProg [] = [] -- Should give an error message, but I have no good position information. allProg (l@('\\':x):xs) | x == "end{code}" = Blank l : classify xs allProg (x:xs) = Program "" x:allProg xs classify (('>':x):xs) = Program ">" (' ':x) : classify xs classify (('!':x):xs) = Program "!" (' ':x) : classify xs -- Programatica extra classify (('#':x):xs) = (case words x of (line:file:_) | all isDigit line -> Include (read line) file _ -> Pre x ) : classify xs classify (x:xs) | all isSpace x = Blank x:classify xs classify (x:xs) = Comment x:classify xs -- Old version: put literate comment lines in one-line comments --old_unclassify = unlines . map unclassify1 data CommentClass = CodePrefix | Directive | BlankLine | LitCmnt unclassify1 :: Classified -> ((CommentClass,String),String) unclassify1 (Program cmnt code) = ((CodePrefix,cmnt),code) unclassify1 (Pre s) = ((Directive,'#':s),"") unclassify1 (Include i f) = ((Directive,'#':' ':show i ++ ' ':f),"") unclassify1 (Blank cmnt) = ((BlankLine,cmnt),"") unclassify1 (Comment cmnt) = ((LitCmnt,cmnt),"") -- New version: put literate comment blocks in nested comments -- (Drawback: these can potentially interfere with other comments) new_unclassify = unclassify0 where unclassify0 (Comment s:xs) = "{-+\t"++s++"\n"++unc xs -- -} unclassify0 xs = un xs -- Normal state, inside code block un [] = [] un (Blank cmnt:Comment s:xs) = "{-+"++cmnt++"\n"++s++"\n"++unc xs -- -} un (x:xs) = snd (unclassify1 x)++"\n"++un xs -- ?? -- Comment state, inside a literate comment unc [] = "-}\n" unc (Comment s:xs) = s++"\n"++unc xs unc (Blank s:xs) = s++"\n"++unb xs -- ?? -- Blank line state, inside a literate comment, after a blank line unb [] = "-}\n" unb (Blank s:xs) = s++"\n"++unb xs -- ?? unb xs@(Comment _:_) = "\n"++unc xs unb xs = "-}\n"++un xs --adjacent :: Classified -> [((FilePath,Int),Classified)] -> [String] adjacent _ [] = [] adjacent y ((pos,x):xs) = case (y,x) of (_ , Pre _ ) -> adjacent y xs (_ , Include _ _) -> adjacent y xs (Program _ _, Comment _) -> message pos "program" "comment":adjacent x xs (Comment _, Program _ _) -> message pos "comment" "program":adjacent x xs _ -> adjacent x xs addpos file n [] = [] addpos file n (x:xs) = case x of Include i f -> l:addpos f i xs _ -> l:addpos file (n+1) xs where l = ((file,n),x) message pos p c = showpos pos++": "++p++ " line before "++c++" line.\n" where showpos ([],n) = "Line "++show n showpos ("\"\"",n) = "Line "++show n showpos (file,n) = "In file " ++ file ++ " at line "++show n
kmate/HaRe
old/tools/base/lib/Unlit.hs
bsd-3-clause
6,011
5
14
1,516
2,231
1,149
1,082
108
13
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.JSON (testJSON) where import Control.Monad import Data.List import Test.HUnit import Test.QuickCheck import qualified Text.JSON as J import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.Types () import qualified Ganeti.BasicTypes as BasicTypes import Ganeti.JSON (nestedAccessByKey, nestedAccessByKeyDotted) import qualified Ganeti.JSON as JSON {-# ANN module "HLint: ignore Use camelCase" #-} instance (Arbitrary a) => Arbitrary (JSON.MaybeForJSON a) where arbitrary = liftM JSON.MaybeForJSON arbitrary instance Arbitrary JSON.TimeAsDoubleJSON where arbitrary = liftM JSON.TimeAsDoubleJSON arbitrary prop_toArray :: [Int] -> Property prop_toArray intarr = let arr = map J.showJSON intarr in case JSON.toArray (J.JSArray arr) of BasicTypes.Ok arr' -> arr ==? arr' BasicTypes.Bad err -> failTest $ "Failed to parse array: " ++ err prop_toArrayFail :: Int -> String -> Bool -> Property prop_toArrayFail i s b = -- poor man's instance Arbitrary JSValue forAll (elements [J.showJSON i, J.showJSON s, J.showJSON b]) $ \item -> case JSON.toArray item::BasicTypes.Result [J.JSValue] of BasicTypes.Bad _ -> passTest BasicTypes.Ok result -> failTest $ "Unexpected parse, got " ++ show result arrayMaybeToJson :: (J.JSON a) => [Maybe a] -> String -> JSON.JSRecord arrayMaybeToJson xs k = [(k, J.JSArray $ map sh xs)] where sh x = case x of Just v -> J.showJSON v Nothing -> J.JSNull prop_arrayMaybeFromObj :: String -> [Maybe Int] -> String -> Property prop_arrayMaybeFromObj t xs k = case JSON.tryArrayMaybeFromObj t (arrayMaybeToJson xs k) k of BasicTypes.Ok xs' -> xs' ==? xs BasicTypes.Bad e -> failTest $ "Parsing failing, got: " ++ show e prop_arrayMaybeFromObjFail :: String -> String -> Property prop_arrayMaybeFromObjFail t k = case JSON.tryArrayMaybeFromObj t [] k of BasicTypes.Ok r -> property (fail $ "Unexpected result, got: " ++ show (r::[Maybe Int]) :: Gen Property) BasicTypes.Bad e -> conjoin [ Data.List.isInfixOf t e ==? True , Data.List.isInfixOf k e ==? True ] prop_MaybeForJSON_serialisation :: JSON.MaybeForJSON String -> Property prop_MaybeForJSON_serialisation = testSerialisation prop_TimeAsDoubleJSON_serialisation :: JSON.TimeAsDoubleJSON -> Property prop_TimeAsDoubleJSON_serialisation = testSerialisation isJError :: J.Result a -> Bool isJError (J.Error _) = True isJError _ = False case_nestedAccessByKey :: Assertion case_nestedAccessByKey = do J.Ok v <- return $ J.decode "{\"key1\": {\"key2\": \"val\"}}" nestedAccessByKey [] v @?= J.Ok v nestedAccessByKey ["key1", "key2"] v @?= J.Ok (J.JSString $ J.toJSString "val") assertBool "access to nonexistent key should fail" . isJError $ nestedAccessByKey ["key1", "nonexistent"] v case_nestedAccessByKeyDotted :: Assertion case_nestedAccessByKeyDotted = do J.Ok v <- return $ J.decode "{\"key1\": {\"key2\": \"val\"}}" assertBool "access to empty key should fail" . isJError $ nestedAccessByKeyDotted "" v nestedAccessByKeyDotted "key1.key2" v @?= J.Ok (J.JSString $ J.toJSString "val") assertBool "access to nonexistent key should fail" . isJError $ nestedAccessByKeyDotted "key1.nonexistent" v testSuite "JSON" [ 'prop_toArray , 'prop_toArrayFail , 'prop_arrayMaybeFromObj , 'prop_arrayMaybeFromObjFail , 'prop_MaybeForJSON_serialisation , 'prop_TimeAsDoubleJSON_serialisation , 'case_nestedAccessByKey , 'case_nestedAccessByKeyDotted ]
grnet/snf-ganeti
test/hs/Test/Ganeti/JSON.hs
bsd-2-clause
5,088
0
14
960
1,014
523
491
82
2
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Init.Heuristics -- Copyright : (c) Benedikt Huber 2009 -- License : BSD-like -- -- Maintainer : cabal-devel@haskell.org -- Stability : provisional -- Portability : portable -- -- Heuristics for creating initial cabal files. -- ----------------------------------------------------------------------------- module Distribution.Client.Init.Heuristics ( guessPackageName, scanForModules, SourceFileEntry(..), neededBuildPrograms, guessMainFileCandidates, guessAuthorNameMail, knownCategories, ) where import Prelude () import Distribution.Client.Compat.Prelude import Distribution.Text (simpleParse) import Distribution.Simple.Setup (Flag(..), flagToMaybe) import Distribution.ModuleName ( ModuleName, toFilePath ) import qualified Distribution.Package as P import qualified Distribution.PackageDescription as PD ( category, packageDescription ) import Distribution.Client.Utils ( tryCanonicalizePath ) import Language.Haskell.Extension ( Extension ) import Distribution.Solver.Types.PackageIndex ( allPackagesByName ) import Distribution.Solver.Types.SourcePackage ( packageDescription ) import Distribution.Client.Types ( SourcePackageDb(..) ) import Control.Monad ( mapM ) import Data.Char ( isNumber, isLower ) import Data.Either ( partitionEithers ) import Data.List ( isInfixOf ) import Data.Ord ( comparing ) import qualified Data.Set as Set ( fromList, toList ) import System.Directory ( getCurrentDirectory, getDirectoryContents, doesDirectoryExist, doesFileExist, getHomeDirectory, ) import Distribution.Compat.Environment ( getEnvironment ) import System.FilePath ( takeExtension, takeBaseName, dropExtension, (</>), (<.>), splitDirectories, makeRelative ) import Distribution.Client.Init.Types ( InitFlags(..) ) import Distribution.Client.Compat.Process ( readProcessWithExitCode ) import System.Exit ( ExitCode(..) ) -- | Return a list of candidate main files for this executable: top-level -- modules including the word 'Main' in the file name. The list is sorted in -- order of preference, shorter file names are preferred. 'Right's are existing -- candidates and 'Left's are those that do not yet exist. guessMainFileCandidates :: InitFlags -> IO [Either FilePath FilePath] guessMainFileCandidates flags = do dir <- maybe getCurrentDirectory return (flagToMaybe $ packageDir flags) files <- getDirectoryContents dir let existingCandidates = filter isMain files -- We always want to give the user at least one default choice. If either -- Main.hs or Main.lhs has already been created, then we don't want to -- suggest the other; however, if neither has been created, then we -- suggest both. newCandidates = if any (`elem` existingCandidates) ["Main.hs", "Main.lhs"] then [] else ["Main.hs", "Main.lhs"] candidates = sortBy (\x y -> comparing (length . either id id) x y `mappend` compare x y) (map Left newCandidates ++ map Right existingCandidates) return candidates where isMain f = (isInfixOf "Main" f || isInfixOf "main" f) && (isSuffixOf ".hs" f || isSuffixOf ".lhs" f) -- | Guess the package name based on the given root directory. guessPackageName :: FilePath -> IO P.PackageName guessPackageName = liftM (P.mkPackageName . repair . last . splitDirectories) . tryCanonicalizePath where -- Treat each span of non-alphanumeric characters as a hyphen. Each -- hyphenated component of a package name must contain at least one -- alphabetic character. An arbitrary character ('x') will be prepended if -- this is not the case for the first component, and subsequent components -- will simply be run together. For example, "1+2_foo-3" will become -- "x12-foo3". repair = repair' ('x' :) id repair' invalid valid x = case dropWhile (not . isAlphaNum) x of "" -> repairComponent "" x' -> let (c, r) = first repairComponent $ break (not . isAlphaNum) x' in c ++ repairRest r where repairComponent c | all isNumber c = invalid c | otherwise = valid c repairRest = repair' id ('-' :) -- |Data type of source files found in the working directory data SourceFileEntry = SourceFileEntry { relativeSourcePath :: FilePath , moduleName :: ModuleName , fileExtension :: String , imports :: [ModuleName] , extensions :: [Extension] } deriving Show sfToFileName :: FilePath -> SourceFileEntry -> FilePath sfToFileName projectRoot (SourceFileEntry relPath m ext _ _) = projectRoot </> relPath </> toFilePath m <.> ext -- |Search for source files in the given directory -- and return pairs of guessed Haskell source path and -- module names. scanForModules :: FilePath -> IO [SourceFileEntry] scanForModules rootDir = scanForModulesIn rootDir rootDir scanForModulesIn :: FilePath -> FilePath -> IO [SourceFileEntry] scanForModulesIn projectRoot srcRoot = scan srcRoot [] where scan dir hierarchy = do entries <- getDirectoryContents (projectRoot </> dir) (files, dirs) <- liftM partitionEithers (mapM (tagIsDir dir) entries) let modules = catMaybes [ guessModuleName hierarchy file | file <- files , isUpper (head file) ] modules' <- mapM (findImportsAndExts projectRoot) modules recMods <- mapM (scanRecursive dir hierarchy) dirs return $ concat (modules' : recMods) tagIsDir parent entry = do isDir <- doesDirectoryExist (parent </> entry) return $ (if isDir then Right else Left) entry guessModuleName hierarchy entry | takeBaseName entry == "Setup" = Nothing | ext `elem` sourceExtensions = SourceFileEntry <$> pure relRoot <*> modName <*> pure ext <*> pure [] <*> pure [] | otherwise = Nothing where relRoot = makeRelative projectRoot srcRoot unqualModName = dropExtension entry modName = simpleParse $ intercalate "." . reverse $ (unqualModName : hierarchy) ext = case takeExtension entry of '.':e -> e; e -> e scanRecursive parent hierarchy entry | isUpper (head entry) = scan (parent </> entry) (entry : hierarchy) | isLower (head entry) && not (ignoreDir entry) = scanForModulesIn projectRoot $ foldl (</>) srcRoot (reverse (entry : hierarchy)) | otherwise = return [] ignoreDir ('.':_) = True ignoreDir dir = dir `elem` ["dist", "_darcs"] findImportsAndExts :: FilePath -> SourceFileEntry -> IO SourceFileEntry findImportsAndExts projectRoot sf = do s <- readFile (sfToFileName projectRoot sf) let modules = mapMaybe ( getModName . drop 1 . filter (not . null) . dropWhile (/= "import") . words ) . filter (not . ("--" `isPrefixOf`)) -- poor man's comment filtering . lines $ s -- TODO: We should probably make a better attempt at parsing -- comments above. Unfortunately we can't use a full-fledged -- Haskell parser since cabal's dependencies must be kept at a -- minimum. -- A poor man's LANGUAGE pragma parser. exts = mapMaybe simpleParse . concatMap getPragmas . filter isLANGUAGEPragma . map fst . drop 1 . takeWhile (not . null . snd) . iterate (takeBraces . snd) $ ("",s) takeBraces = break (== '}') . dropWhile (/= '{') isLANGUAGEPragma = ("{-# LANGUAGE " `isPrefixOf`) getPragmas = map trim . splitCommas . takeWhile (/= '#') . drop 13 splitCommas "" = [] splitCommas xs = x : splitCommas (drop 1 y) where (x,y) = break (==',') xs return sf { imports = modules , extensions = exts } where getModName :: [String] -> Maybe ModuleName getModName [] = Nothing getModName ("qualified":ws) = getModName ws getModName (ms:_) = simpleParse ms -- Unfortunately we cannot use the version exported by Distribution.Simple.Program knownSuffixHandlers :: [(String,String)] knownSuffixHandlers = [ ("gc", "greencard") , ("chs", "chs") , ("hsc", "hsc2hs") , ("x", "alex") , ("y", "happy") , ("ly", "happy") , ("cpphs", "cpp") ] sourceExtensions :: [String] sourceExtensions = "hs" : "lhs" : map fst knownSuffixHandlers neededBuildPrograms :: [SourceFileEntry] -> [String] neededBuildPrograms entries = [ handler | ext <- nubSet (map fileExtension entries) , handler <- maybeToList (lookup ext knownSuffixHandlers) ] -- | Guess author and email using darcs and git configuration options. Use -- the following in decreasing order of preference: -- -- 1. vcs env vars ($DARCS_EMAIL, $GIT_AUTHOR_*) -- 2. Local repo configs -- 3. Global vcs configs -- 4. The generic $EMAIL -- -- Name and email are processed separately, so the guess might end up being -- a name from DARCS_EMAIL and an email from git config. -- -- Darcs has preference, for tradition's sake. guessAuthorNameMail :: IO (Flag String, Flag String) guessAuthorNameMail = fmap authorGuessPure authorGuessIO -- Ordered in increasing preference, since Flag-as-monoid is identical to -- Last. authorGuessPure :: AuthorGuessIO -> AuthorGuess authorGuessPure (AuthorGuessIO { authorGuessEnv = env , authorGuessLocalDarcs = darcsLocalF , authorGuessGlobalDarcs = darcsGlobalF , authorGuessLocalGit = gitLocal , authorGuessGlobalGit = gitGlobal }) = mconcat [ emailEnv env , gitGlobal , darcsCfg darcsGlobalF , gitLocal , darcsCfg darcsLocalF , gitEnv env , darcsEnv env ] authorGuessIO :: IO AuthorGuessIO authorGuessIO = AuthorGuessIO <$> getEnvironment <*> (maybeReadFile $ "_darcs" </> "prefs" </> "author") <*> (maybeReadFile =<< liftM (</> (".darcs" </> "author")) getHomeDirectory) <*> gitCfg Local <*> gitCfg Global -- Types and functions used for guessing the author are now defined: type AuthorGuess = (Flag String, Flag String) type Enviro = [(String, String)] data GitLoc = Local | Global data AuthorGuessIO = AuthorGuessIO { authorGuessEnv :: Enviro, -- ^ Environment lookup table authorGuessLocalDarcs :: (Maybe String), -- ^ Contents of local darcs author info authorGuessGlobalDarcs :: (Maybe String), -- ^ Contents of global darcs author info authorGuessLocalGit :: AuthorGuess, -- ^ Git config --local authorGuessGlobalGit :: AuthorGuess -- ^ Git config --global } darcsEnv :: Enviro -> AuthorGuess darcsEnv = maybe mempty nameAndMail . lookup "DARCS_EMAIL" gitEnv :: Enviro -> AuthorGuess gitEnv env = (name, mail) where name = maybeFlag "GIT_AUTHOR_NAME" env mail = maybeFlag "GIT_AUTHOR_EMAIL" env darcsCfg :: Maybe String -> AuthorGuess darcsCfg = maybe mempty nameAndMail emailEnv :: Enviro -> AuthorGuess emailEnv env = (mempty, mail) where mail = maybeFlag "EMAIL" env gitCfg :: GitLoc -> IO AuthorGuess gitCfg which = do name <- gitVar which "user.name" mail <- gitVar which "user.email" return (name, mail) gitVar :: GitLoc -> String -> IO (Flag String) gitVar which = fmap happyOutput . gitConfigQuery which happyOutput :: (ExitCode, a, t) -> Flag a happyOutput v = case v of (ExitSuccess, s, _) -> Flag s _ -> mempty gitConfigQuery :: GitLoc -> String -> IO (ExitCode, String, String) gitConfigQuery which key = fmap trim' $ readProcessWithExitCode "git" ["config", w, key] "" where w = case which of Local -> "--local" Global -> "--global" trim' (a, b, c) = (a, trim b, c) maybeFlag :: String -> Enviro -> Flag String maybeFlag k = maybe mempty Flag . lookup k -- | Read the first non-comment, non-trivial line of a file, if it exists maybeReadFile :: String -> IO (Maybe String) maybeReadFile f = do exists <- doesFileExist f if exists then fmap getFirstLine $ readFile f else return Nothing where getFirstLine content = let nontrivialLines = dropWhile (\l -> (null l) || ("#" `isPrefixOf` l)) . lines $ content in case nontrivialLines of [] -> Nothing (l:_) -> Just l -- |Get list of categories used in Hackage. NOTE: Very slow, needs to be cached knownCategories :: SourcePackageDb -> [String] knownCategories (SourcePackageDb sourcePkgIndex _) = nubSet [ cat | pkg <- map head (allPackagesByName sourcePkgIndex) , let catList = (PD.category . PD.packageDescription . packageDescription) pkg , cat <- splitString ',' catList ] -- Parse name and email, from darcs pref files or environment variable nameAndMail :: String -> (Flag String, Flag String) nameAndMail str | all isSpace nameOrEmail = mempty | null erest = (mempty, Flag $ trim nameOrEmail) | otherwise = (Flag $ trim nameOrEmail, Flag mail) where (nameOrEmail,erest) = break (== '<') str (mail,_) = break (== '>') (tail erest) trim :: String -> String trim = removeLeadingSpace . reverse . removeLeadingSpace . reverse where removeLeadingSpace = dropWhile isSpace -- split string at given character, and remove whitespace splitString :: Char -> String -> [String] splitString sep str = go str where go s = if null s' then [] else tok : go rest where s' = dropWhile (\c -> c == sep || isSpace c) s (tok,rest) = break (==sep) s' nubSet :: (Ord a) => [a] -> [a] nubSet = Set.toList . Set.fromList {- test db testProjectRoot = do putStrLn "Guessed package name" (guessPackageName >=> print) testProjectRoot putStrLn "Guessed name and email" guessAuthorNameMail >>= print mods <- scanForModules testProjectRoot putStrLn "Guessed modules" mapM_ print mods putStrLn "Needed build programs" print (neededBuildPrograms mods) putStrLn "List of known categories" print $ knownCategories db -}
mydaum/cabal
cabal-install/Distribution/Client/Init/Heuristics.hs
bsd-3-clause
14,521
0
20
3,656
3,391
1,833
1,558
253
4
{-# LANGUAGE CPP, TypeFamilies, MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts, FlexibleInstances, UndecidableInstances, OverlappingInstances, TypeSynonymInstances, GeneralizedNewtypeDeriving #-} ----------------------------------------------------------------------------- -- | -- Module : HSX.XMLGenerator -- Copyright : (c) Niklas Broberg 2008 -- License : BSD-style (see the file LICENSE.txt) -- -- Maintainer : Niklas Broberg, niklas.broberg@chalmers.se -- Stability : experimental -- Portability : requires newtype deriving and MPTCs with fundeps -- -- The class and monad transformer that forms the basis of the literal XML -- syntax translation. Literal tags will be translated into functions of -- the GenerateXML class, and any instantiating monads with associated XML -- types can benefit from that syntax. ----------------------------------------------------------------------------- module T4809_XMLGenerator where import Control.Applicative import Control.Monad import Control.Monad.Trans import Control.Monad.Cont (MonadCont) import Control.Monad.Error (MonadError) import Control.Monad.Reader(MonadReader) import Control.Monad.Writer(MonadWriter) import Control.Monad.State (MonadState) import Control.Monad.RWS (MonadRWS) import Control.Monad (MonadPlus(..),liftM) ---------------------------------------------- -- General XML Generation -- | The monad transformer that allows a monad to generate XML values. newtype XMLGenT m a = XMLGenT (m a) deriving (Monad, Functor, MonadIO, MonadPlus, MonadWriter w, MonadReader r, MonadState s, MonadRWS r w s, MonadCont, MonadError e) instance Monad m => Applicative (XMLGenT m) where pure = return (<*>) = ap instance Monad m => Alternative (XMLGenT m) where -- | un-lift. unXMLGenT :: XMLGenT m a -> m a unXMLGenT (XMLGenT ma) = ma instance MonadTrans XMLGenT where lift = XMLGenT type Name = (Maybe String, String) -- | Generate XML values in some XMLGenerator monad. class Monad m => XMLGen m where type XML m data Child m genElement :: Name -> [XMLGenT m [Int]] -> [XMLGenT m [Child m]] -> XMLGenT m (XML m) genEElement :: Name -> [XMLGenT m [Int]] -> XMLGenT m (XML m) genEElement n ats = genElement n ats [] -- | Embed values as child nodes of an XML element. The parent type will be clear -- from the context so it is not mentioned. class XMLGen m => EmbedAsChild m c where asChild :: c -> XMLGenT m [Child m] instance (MonadIO m, EmbedAsChild m c, m ~ n) => EmbedAsChild m (XMLGenT n c) where asChild m = do liftIO $ putStrLn "EmbedAsChild m (XMLGenT n c)" a <- m asChild a instance (MonadIO m, EmbedAsChild m c) => EmbedAsChild m [c] where asChild cs = do liftIO $ putStrLn "EmbedAsChild m [c]" liftM concat . mapM asChild $ cs instance (MonadIO m, XMLGen m) => EmbedAsChild m (Child m) where asChild c = do liftIO $ putStrLn "EmbedAsChild m (Child m)" return . return $ c
oldmanmike/ghc
testsuite/tests/typecheck/should_run/T4809_XMLGenerator.hs
bsd-3-clause
3,011
0
13
566
680
367
313
47
1
-- !!! rn001: super-simple set of bindings, -- !!! incl wildcard pattern-bindings and *duplicates* x = [] y = [] y = [] _ = [] _ = 1 z = [] _ = []
wxwxwwxxx/ghc
testsuite/tests/rename/should_fail/rnfail002.hs
bsd-3-clause
148
0
5
36
53
29
24
7
1
{-# LANGUAGE MagicHash, BangPatterns #-} import Foreign.C import Data.Word import Foreign.Ptr import GHC.Exts import Control.Exception hashStr :: Ptr Word8 -> Int -> Int hashStr (Ptr a#) (I# len#) = loop 0# 0# where loop h n | isTrue# (n GHC.Exts.==# len#) = I# h | otherwise = loop h2 (n GHC.Exts.+# 1#) where !c = ord# (indexCharOffAddr# a# n) !h2 = (c GHC.Exts.+# (h GHC.Exts.*# 128#)) `remInt#` 4091# -- Infinite loops with new code generator + C-- optimizations main = do withCStringLen "ff" $ \(ptr, l) -> do print (hashStr (castPtr ptr) l)
urbanslug/ghc
testsuite/tests/codeGen/should_run/cgrun066.hs
bsd-3-clause
611
0
15
157
228
117
111
15
1
module CrackEgg where -- unpack zipped egg files into directories -- compile: -- ghc --make CrackEgg -main-is CrackEgg.main -- run: -- find ~/eggs/ -maxdepth 1 -type f -name '*.egg' -exec ./CrackEgg {} + import System.Environment (getArgs) import System.Process import System.Directory import System.IO import Text.Printf import Control.Exception import System.IO.Error import System.Exit import Foreign.C.Types import Foreign.Marshal import Foreign.Ptr foreign import ccall unsafe "mkdtemp" mkdtemp_ :: Ptr CUChar -> IO (Ptr CUChar) mkdtemp :: FilePath -> IO FilePath mkdtemp fp = allocaBytes (1 + length fp) $ \p -> do pokeArray0 0 p $ map (toEnum . (`mod` 256) . fromEnum) fp rp <- mkdtemp_ p if rp == nullPtr then throwIO (userError "mkdtemp") else return () rs <- peekArray0 0 rp return . map (toEnum . fromEnum) $ rs mkdtempX = mkdtemp . (++"XXXXXX") main :: IO () main = getArgs >>= mapM_ ((>>= crackEgg) . canonicalizePath) crackEgg :: String -> IO () crackEgg eggname = dir_t eggname where dir_t = test doesDirectoryExist (printf "%s is a directory.\n") file_t file_t = test doesFileExist goAhead (printf "%s does not exist.\n") goAhead eggname = do tmp <- mkdtempX "/tmp/egg" runProcTmp tmp "unzip" [eggname] runProcTmp tmp "mv" [eggname, "/tmp"] runProcTmp tmp "mv" [tmp, eggname] runProcTmp tmp prog args = do let cm = (proc prog args){ cwd = Just tmp } (_, _, _, ph) <- createProcess cm ExitSuccess <- waitForProcess ph return () test ioPred kYes kNo param = do yn <- ioPred param (if yn then kYes else kNo) param
RichardBarrell/snippets
CrackEgg.hs
isc
1,844
0
14
564
542
279
263
37
2
{- Problem 7 Flatten a nested list structure. -} module Problems.Seven where data NestedList a = Elem a | List [NestedList a] flatten (Elem x) = [x] flatten (List x) = concatMap flatten x problemSeven = do putStrLn "Problem 7" putStrLn "Flatten a nested list structure." putStrLn "> flatten (Elem 5)" print $ flatten (Elem 5) putStrLn "> flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])" print $ flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]]) putStrLn "> flatten (List [])" print $ flatten (List ([] :: [NestedList ()]))
maxdeviant/99-haskell
src/Problems/Seven.hs
mit
609
0
16
145
205
99
106
13
1
module Lib ( main ) where import qualified Study1 import qualified Catalan {- TODO: - find example for zygo? - references: + https://github.com/willtim/recursion-schemes + https://stackoverflow.com/q/36851766/315302 + https://blog.sumtypeofway.com/posts/introduction-to-recursion-schemes.html -} main = Catalan.main main2 :: IO () main2 = do putStrLn "# Study1" Study1.main putStrLn "" putStrLn "# Study2" Catalan.main putStrLn ""
Javran/misc
recursion-schemes-playground/src/Lib.hs
mit
472
0
7
91
74
37
37
13
1
{-# htermination union :: (Eq a, Eq k) => [(Either a k)] -> [(Either a k)] -> [(Either a k)] #-} import List
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/List_union_11.hs
mit
109
0
3
23
5
3
2
1
0
module Test.Framework where import Test.Hspec.Core.Spec import Test.Hspec.Runner import Test.Framework.Providers.API defaultMain :: [Test] -> IO () defaultMain = hspec . parallel . fromSpecList testGroup :: TestName -> [Test] -> Test testGroup = specGroup
sol/hspec-test-framework
src/Test/Framework.hs
mit
290
0
7
66
77
46
31
8
1
-- Welcome to the City -- https://www.codewars.com/kata/5302d846be2a9189af0001e4 module Welcome where sayhello :: [String] -> String -> String -> String sayhello ns c s = "Hello, " ++ unwords ns ++ "! Welcome to " ++ c ++ ", " ++ s ++ "!"
gafiatulin/codewars
src/8 kyu/Welcome.hs
mit
240
0
11
44
65
35
30
3
1
{-# LANGUAGE OverloadedStrings #-} module Ch26.HitCounter where import Control.Monad.Trans.Class import Control.Monad.Trans.Reader import Control.Monad.IO.Class import Data.IORef import qualified Data.Map as M import Data.Maybe (fromMaybe) import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as TL import Web.Scotty.Trans data Config = Config { counts :: IORef (M.Map Text Integer) , prefix :: Text } type Scotty = ScottyT Text (ReaderT Config IO) type Handler = ActionT Text (ReaderT Config IO) bumpBoomp :: Text -> M.Map Text Integer -> (M.Map Text Integer, Integer) bumpBoomp k m = case M.lookup k m of Just a -> (M.adjust (+1) k m, a + 1) Nothing -> (M.insert k 1 m, 1) app :: Scotty () app = get "/:key" $ do unprefixed <- param "key" config <- lift ask let key' = (prefix config) `mappend` unprefixed ref = counts config (updatedMap, count) <- liftIO $ (bumpBoomp key') <$> (readIORef ref) liftIO $ writeIORef ref updatedMap html $ mconcat [ "<h1>Success! Count was: " , TL.pack $ show count , "</h1>" ] main :: IO () main = do counter <- newIORef M.empty let config = Config counter "blah-" runR r = runReaderT r config scottyT 3000 runR app
andrewMacmurray/haskell-book-solutions
src/ch26/HitCounter.hs
mit
1,302
0
13
334
464
246
218
43
2
module Solar.Cast.Client where
Cordite-Studios/solar-wind
Solar/Cast/Client.hs
mit
31
0
3
3
7
5
2
1
0
{-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} module ASP ( ) where import Text.PrettyPrint import Control.Applicative hiding (empty) import Data.Char data Fact = Fact data Rule = Rule -- starts lowercase data Constant = ConstNot Constant | Constant String deriving Show -- starts uppercase data Variable = VarNot Variable | Variable String deriving Show data Simpleterm a where SimplInt :: Int -> Simpleterm Int SimplConst :: Constant -> Simpleterm Constant SimplVar :: Variable -> Simpleterm Variable SimplNot :: Simpleterm a -> Simpleterm () deriving instance Show (Simpleterm a) type family Inv f where Inv (Simpleterm Int) = Int Inv (Simpleterm ()) = () Inv (Simpleterm Constant) = Constant Inv (Simpleterm Variable) = Variable instance Num (Simpleterm Int) where (SimplInt a) + (SimplInt b) = SimplInt (a + b) abs (SimplInt a) = SimplInt (abs a) signum (SimplInt a) = SimplInt (signum a) (SimplInt a) * (SimplInt b) = SimplInt (a * b) negate (SimplInt a) = SimplInt (-a) fromInteger (a) = SimplInt (fromInteger a) data Function = Function { fConst :: Constant , fTerms :: [Simpleterm'] } deriving (Show) data Simpleterm' where Simpleterm :: Simpleterm a -> Simpleterm' data Term' where T :: Term a -> Term' deriving instance Show Term' deriving instance Show Simpleterm' data Term a = TermSimple (Simpleterm a) | TermFunc Function deriving (Show) data ASP = ASP ([Term']) deriving Show ppSimpleterm :: Simpleterm a -> Doc ppSimpleterm (SimplInt i) = int i ppSimpleterm (SimplConst const) = ppConst const ppSimpleterm (SimplVar var) = ppVar var ppSimpleterm (SimplNot simpleterm) = text "-" <> ppSimpleterm simpleterm ppSimpleterm' (Simpleterm s) = ppSimpleterm s ppVar (VarNot var) = text "-" <> ppVar var ppVar (Variable str) = text str ppTerm (TermSimple _) = text "Simpleterm" ppTerm (TermFunc func) = ppFunc func ppTerm' (T t) = ppTerm t ppFunc (Function const terms) = ppConst const <> parens (hcat $ punctuate comma $ map ppSimpleterm' terms) ppConst (ConstNot const) = text "-" <> ppConst const ppConst (Constant str) = text str ppASP (ASP terms) = foldr ($+$) empty (map (\d -> d <> text ".") $ map ppTerm' terms) class Negatable v where not :: v -> v instance Negatable Constant where not constant = ConstNot constant instance Negatable Variable where not var = VarNot var const name | length name == 0 = error "Constant without name" | isLower (head name) == False = error "Constant must start with lowercase letter" | otherwise = Constant name var name | length name == 0 = error "Variable without name" | isLower (head name) == True = error "Variable must start with uppercase letter" | otherwise = Variable name function :: String -> [Simpleterm'] -> Function function = Function . ASP.const def :: ([Simpleterm'] -> Function) -> [Simpleterm'] -> Term' def a b = T $ TermFunc (a b) n :: Int -> Simpleterm Int n x = SimplInt x instance Num Simpleterm' where (Simpleterm (SimplInt x)) + (Simpleterm (SimplInt y)) = Simpleterm (SimplInt (x + y)) _ + _ = error "can't add non integers" fromInteger (x) = Simpleterm (SimplInt (fromInteger x)) c = Simpleterm . SimplConst . ASP.const v = Simpleterm . SimplVar . ASP.var t :: [Term'] t = do let polygon = function "polygon" let a = function "a" [def a [c "atom", v "X"], def polygon [0, 20, 40]]
mfpi/hsys
src/ASP.hs
mit
3,701
0
12
869
1,334
673
661
92
1
{-@ LIQUID "--no-termination" @-} import Euterpea {-@ measure len @-} len :: Music a -> Int len m = case m of Prim _ -> 1 m1 :+: m2 -> len m1 + len m2 m1 :=: m2 -> len m1 + len m2 Modify c m -> len m third :: Pitch -> Pitch third=trans 3 n = c 4 qn :+: d 3 qn {-@ exs :: [(Music Pitch,Music Pitch)<{\i o -> (len i) = (len o)}>] @-} exs :: [(Music Pitch,Music Pitch)] exs = [ (n, mMap third n) ]
santolucito/ives
tests/musicNoSize.hs
mit
443
0
9
141
169
85
84
14
4
{-# LANGUAGE FlexibleContexts #-} module Language.Haskell.Exts.PrettyAst ( PrettyAst(..) , renderWithMode , renderWithDefMode , renderWithTrace , PrettyMode(..) , defPrettyMode , PR.Style(..) , PR.style , PR.PPHsMode(..) , PR.defaultMode , DocM ) where import Language.Haskell.Exts.Annotated import qualified Language.Haskell.Exts.Pretty as PR import Control.Monad.State import Control.Monad.Reader import Control.Monad.Writer import Control.Applicative import Data.Maybe import Data.List hiding (intersperse) import Data.Traversable as Tr import Data.Char (isSpace) data DocState = DocState { pos :: !SrcLoc, nestSize :: !Int, prettifyingTrace :: ![String] } deriving Show defDocState fl = DocState (SrcLoc fl 1 1) 0 [] data PrettyMode = PrettyMode PR.PPHsMode PR.Style defPrettyMode = PrettyMode PR.defaultMode PR.style type DocM = ReaderT PrettyMode (State DocState) -- | render the document with a given file name and mode. renderWithMode :: PrettyAst ast => String -> PrettyMode -> ast a -> ast SrcSpanInfo renderWithMode fl mode doc = evalState (runReaderT (astPretty doc) mode) (defDocState fl) -- | render the document with a given file name and 'defaultMode'. renderWithDefMode :: PrettyAst ast => String -> ast a -> ast SrcSpanInfo renderWithDefMode fl doc = renderWithMode fl defPrettyMode doc -- | render the document with a given file name and mode. renderWithTrace :: PrettyAst ast => String -> PrettyMode -> ast a -> (ast SrcSpanInfo, [String]) renderWithTrace fl mode doc = (res, prettifyingTrace s) where (res, s) = runState (runReaderT (astPretty doc) mode) (defDocState fl) -- -------------------------------------------------------------------------- class PrettyAst ast where -- | Pretty-print something in isolation. astPretty :: ast a -> DocM (ast SrcSpanInfo) -- | Pretty-print something in a precedence context. astPrettyPrec :: Int -> ast a -> DocM (ast SrcSpanInfo) astPretty = astPrettyPrec 0 astPrettyPrec _ = astPretty ------------------------- Pretty-Print a Module -------------------- instance PrettyAst Module where astPretty (Module _ mbHead os imp decls) | null imp && null decls = resultPretty $ pragmaBrace os *> vcatBody imp decls | isNothing mbHead = resultPretty $ pragmaBrace os *> vcatBody imp decls | otherwise = resultPretty $ pragmaBrace os *> do PrettyMode mode _ <- ask case layout mode of PPOffsideRule -> (vcatBody imp decls) PPSemiColon -> semiColonBody PPInLine -> semiColonBody PPNoLayout -> noLayoutBody where body = pure (\os h i d -> Module annStub h os i d) <*> pragmaRes os <*> traverse (annNoInfoElem . astPretty) mbHead <* (getLayout >>= sepElemIf (isJust mbHead) . layoutCat) pragmaRes (x:xs) = implicitElem "{" *> annNoInfoList os <* finalCat <* implicitSep ";" <* implicitSep "}" pragmaRes [] = pure [] pragmaBrace [] = implicitSep "{" *> implicitSep "}" pragmaBrace _ = pure () vcatBody [] [] = body <* implicitElem "{" <*> pure [] <*> pure [] <* implicitElem "}" vcatBody is ds = body <* implicitSep "{" <*> annNoInfoList imp <* (if null imp then pure () else finalCat <* implicitElem ";") <*> declList decls <* (if null decls then pure () else finalCat <* implicitElem ";") <* implicitSep "}" semiColonBody = body <* nestMode onsideIndent (infoElem "{" <* sepElem vcat) <*> nestMode onsideIndent (annNoInfoList imp) <* finalSemiColon getLayout imp <*> nestMode onsideIndent (declList decls) <* finalSemiColon getLayout decls <* infoElem "}" noLayoutBody = body <* infoElem "{" <* (getLayout >>= sepElem . layoutCat) <*> annNoInfoList imp <* finalSemiColon getLayout imp <*> declList decls <* infoElem "}" pragmaFinalSep p = getLayout >>= if null imp && null decls then sepElem . layoutCat else semiColon annNoInfoList xs = intersperse (getLayout >>= semiColon) $ annListElem annNoInfoElem xs declList xs = intersperse (finalCat *> implicitSep ";") $ map declFn xs finalCat = do emptyLine <- lift isEmptyLine sepElemIf (not emptyLine) vcat declFn d@(FunBind _ _) = prettyFunBind $ astPretty d declFn d = annNoInfoElem $ astPretty d finalSemiColon f xs = if null xs then pure () else f >>= semiColon getLayout = do PrettyMode mode _ <- ask return $ layout mode semiColon m = do emptyLine <- lift isEmptyLine let sep = if isNothing mbHead then implicitElem else infoElem case m of PPOffsideRule -> sepElemIf (not emptyLine) vcat <* implicitElem ";" PPNoLayout -> sep ";" *> sepElem hsep PPSemiColon -> sep ";" *> sepElem vcat PPInLine -> sep ";" *> sepElem vcat layoutCat m = case m of PPOffsideRule -> vcat PPNoLayout -> hsep PPSemiColon -> vcat PPInLine -> vcat prettyFunBind fb = do (FunBind span ms) <- lift fb if null ms then return $ FunBind span [] else do let startFb@(SrcSpan fl ln cl _ _) = srcInfoSpan . ann $ head ms endFb = srcInfoSpan .ann $ last ms -- read all points from Math matchPs = concatMap (srcInfoPoints.ann) ms fbPs = srcInfoPoints span span' = mergeSrcSpan startFb endFb tell $ AstElemInfo (Just $ SrcSpanInfo span' fbPs) [] return $ FunBind (SrcSpanInfo span' matchPs) ms astPretty (XmlPage _ _mn os n attrs mattr cs) = unimplemented astPretty (XmlHybrid _ mbHead os imp decls n attrs mattr cs) = unimplemented -------------------------- Module Header ------------------------------ instance PrettyAst ModuleHead where -- mySep astPretty (ModuleHead _ m mbWarn mbExportList) = resultPretty.(nestMode onsideIndent) $ constrElem ModuleHead -- MySep <* infoElem "module" <* sepElem fsep <*> (annNoInfoElem $ astPretty m) <*> traverse (\x -> sepElem fsep *> (annNoInfoElem $ astPretty x)) mbWarn <*> traverse (\x -> sepElem fsep *> (annNoInfoElem $ astPretty x)) mbExportList <* sepElem fsep <* infoElem "where" -- -------------------------------------------------------------------------- instance PrettyAst WarningText where astPretty w = case w of (DeprText _ s) -> impl DeprText "{-# DEPRECATED" s (WarnText _ s) -> impl WarnText "{-# WARNING" s where -- mySep impl f c s = resultPretty.(nestMode onsideIndent) $ constrElem f <* infoElem c <* sepElem fsep <*> infoElem s <* sepElem fsep <* infoElem "#}" -- -------------------------------------------------------------------------- instance PrettyAst ModuleName where astPretty (ModuleName _ s) = resultPretty $ constrElem ModuleName <*> noInfoElem s -- -------------------------------------------------------------------------- instance PrettyAst ExportSpecList where astPretty (ExportSpecList _ especs) = resultPretty $ constrElem ExportSpecList <*> parenList (annListElem annNoInfoElem especs) -- -------------------------------------------------------------------------- instance PrettyAst ExportSpec where astPretty (EVar _ name) = resultPretty $ constrElem EVar <*> (annNoInfoElem $ astPretty name) astPretty (EAbs _ name) = resultPretty $ constrElem EAbs <*> (annNoInfoElem $ astPretty name) astPretty (EThingAll _ name) = resultPretty $ constrElem EThingAll <*> (annNoInfoElem $ astPretty name) <* infoElem "(" <* infoElem ".." <* infoElem ")" astPretty (EThingWith _ name nameList) = resultPretty $ constrElem EThingWith <*> (annNoInfoElem $ astPretty name) <*> parenList (annListElem annNoInfoElem nameList) astPretty (EModuleContents _ m) = resultPretty $ constrElem EModuleContents <*> (annNoInfoElem $ astPretty m) -- -------------------------------------------------------------------------- instance PrettyAst ImportDecl where astPretty (ImportDecl _ mod qual src mbPkg mbName mbSpecs) = resultPretty.(nestMode onsideIndent) $ pure impl -- mySep <* infoElem "import" <* sepElem fsep <*> (if src then pure src <* infoElem "{-# SOURCE #-}" <* sepElem fsep else pure src) <*> (if qual then pure qual <* infoElem "qualified" <* sepElem fsep else pure qual) <*> traverse (\x -> quoteStringElem x <* sepElem fsep) mbPkg <*> (annNoInfoElem $ astPretty mod) <*> traverse (\ x -> sepElem fsep *> infoElem "as" *> sepElem hsep *> (annNoInfoElem $ astPretty x)) mbName <*> traverse (\ x -> sepElem fsep *> (annNoInfoElem $ astPretty x)) mbSpecs where impl s q p m n sp = ImportDecl annStub m q s p n sp -- -------------------------------------------------------------------------- instance PrettyAst ImportSpecList where astPretty (ImportSpecList _ b ispecs) = resultPretty $ constrElem ImportSpecList <*> (if b then pure b <* infoElem "hiding" else pure b) <* sepElemIf (not $ null ispecs) hsep <* infoElem "(" <*> intersperse parenListSep (annListElem annNoInfoElem ispecs) <* infoElem ")" -- -------------------------------------------------------------------------- instance PrettyAst ImportSpec where astPretty (IVar _ name) = resultPretty $ constrElem IVar <*> annNoInfoElem (astPretty name) astPretty (IAbs _ name) = resultPretty $ constrElem IAbs <*> pointsInfoElem (astPretty name) astPretty (IThingAll _ name) = resultPretty $ constrElem IThingAll <*> (annNoInfoElem $ astPretty name) <* infoElem "(..)" astPretty (IThingWith _ name nameList) = resultPretty $ constrElem IThingWith <*> (annNoInfoElem $ astPretty name) <*> parenList (annListElem annNoInfoElem nameList) ------------------------- Declarations ------------------------------ instance PrettyAst Decl where astPretty (TypeDecl _ head htype) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem TypeDecl -- mySep <* infoElem "type" <* sepElem fsep <*> (annNoInfoElem $ astPretty head) <* sepElem fsep <* infoElem "=" <* sepElem fsep <*> (annNoInfoElem $ astPretty htype) astPretty (TypeFamDecl _ head mkind) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem TypeFamDecl <* infoElem "type" <* sepElem fsep <* infoElem "family" <* sepElem fsep <*> ppFsepDhead head <* sepElemIf (isJust mkind) fsep <*> ppOptKind mkind astPretty (DataDecl _ don mContext head constrList mDeriving) = blankline.resultPretty $ constrElem DataDecl <*> (annNoInfoElem $ astPretty don) <* sepElem fsep <*> traverse (\ c -> (annNoInfoElem $ astPretty c) <* sepElem fsep) mContext <*> ppFsepDhead head <* sepElem hsep <*> ppConstrList constrList <*> traverse (\x -> (nestMode onsideIndent) $ sepElem myVcat *> ppDeriving x) mDeriving astPretty (GDataDecl _ don mContext hd mkind gadtDecl mDeriving) = blankline.resultPretty $ constrElem GDataDecl -- mySep <*> (annNoInfoElem $ astPretty don) <* sepElem fsep <*> traverse (\ c -> (annNoInfoElem $ astPretty c) <* sepElem fsep) mContext <*> ppFsepDhead hd <* sepElemIf (isJust mkind) fsep <*> ppOptKind mkind <* sepElem fsep <* infoElem "where" <*> ppBody classIndent (annListElem annNoInfoElem gadtDecl) <*> traverse identDeriving mDeriving where identDeriving d = (nestMode letIndent) $ sepElem myVcat *> ppDeriving d astPretty (DataFamDecl _ mContext head mKind) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem DataFamDecl -- mySep <* infoElem "data" <* sepElem fsep <* infoElem "family" <* sepElem fsep <*> traverse (\ c -> (annNoInfoElem $ astPretty c) <* sepElem fsep) mContext <*> ppFsepDhead head <* sepElemIf (isJust mKind) fsep <*> ppOptKind mKind astPretty (TypeInsDecl _ tl tr) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem TypeInsDecl -- mySep <* infoElem "type" <* sepElem fsep <* infoElem "instance" <* sepElem fsep <*> (annNoInfoElem $ astPretty tl) <* sepElem fsep <* infoElem "=" <* sepElem fsep <*> (annNoInfoElem $ astPretty tr) astPretty (DataInsDecl _ don t qConDecl mDeriving) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem DataInsDecl -- mySep <*> (annNoInfoElem $ astPretty don) <* sepElem fsep <* infoElem "instance" <* sepElem fsep <*> (annNoInfoElem $ astPretty t) <* sepElem hsep <*> ppConstrList qConDecl <*> traverse (\x -> (nestMode onsideIndent) $ sepElem myVcat *> ppDeriving x) mDeriving astPretty (GDataInsDecl _ don t mKind gadtDecl mDeriving) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem GDataInsDecl <*> (annNoInfoElem $ astPretty don) <* sepElem fsep <* infoElem "instance" <* sepElem fsep <*> (annNoInfoElem $ astPretty t) <* sepElemIf (isJust mKind) fsep <*> ppOptKind mKind <* infoElem "where" <*> ppBody classIndent (annListElem annNoInfoElem gadtDecl) <*> traverse (\x -> (nestMode onsideIndent) $sepElem myVcat *> ppDeriving x) mDeriving astPretty (ClassDecl _ mContext head funDep mClassDecl) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem ClassDecl <* infoElem "class" <* sepElem fsep <*> traverse (\ c -> (annNoInfoElem $ astPretty c) <* sepElem fsep) mContext <*> ppFsepDhead head <* sepElem fsep <*> ppFunDeps funDep <* (if null $ fromMaybe [] mClassDecl then infoElem "" else sepElem fsep *> infoElem "where") <*> traverse cDecl mClassDecl where cDecl cd = ppBody classIndent (annListElem annNoInfoElem cd) astPretty (InstDecl _ mContext instHead mInstDecl) = blankline.resultPretty $ constrElem InstDecl <* infoElem "instance" <* sepElem fsep <*> traverse (\ c -> (annNoInfoElem $ astPretty c) <* sepElem fsep) mContext <*> ppInstHeadInDecl instHead <*> traverse instDecl mInstDecl where instDecl is = sepElem fsep *> infoElem "where" *> ppBody classIndent (annListElem annNoInfoElem is) astPretty (DerivDecl _ mContext instHead) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem DerivDecl -- mySep <* infoElem "deriving" <* sepElem fsep <* infoElem "instance" <* sepElem fsep <*> traverse (\ c -> (annNoInfoElem $ astPretty c) <* sepElem fsep) mContext <*> ppInstHeadInDecl instHead astPretty (InfixDecl _ assoc mInt op) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem InfixDecl -- mySep <*> (annNoInfoElem $ astPretty assoc) <* sepElem fsep <*> traverse (\x -> infoElem (show x) *> pure x <* sepElem fsep) mInt <*> intersperse (sepElem fsep) (annListElem annNoInfoElem op) astPretty (DefaultDecl _ t) = blankline.resultPretty $ constrElem DefaultDecl <* infoElem "default" <* sepElem hsep <*> parenList (annListElem annNoInfoElem t) astPretty (SpliceDecl _ e) = blankline.resultPretty $ constrElem SpliceDecl <*> annNoInfoElem (astPretty e) astPretty (TypeSig _ ns t) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem TypeSig -- mySep <*> intersperse (infoElem "," <* sepElem fsep) (annListElem annNoInfoElem ns) <* (sepElem $ case ns of [n] -> hsep; _ -> fsep) <* infoElem "::" <* sepElem fsep <*> (annNoInfoElem $ astPretty t) astPretty (FunBind _ ms) = resultPretty $ constrElem FunBind <*> intersperse (sep <* sepElem myVcat) (annListElem annNoInfoElem ms) <* (if null ms then pure "" else sep) where sep = do PrettyMode mode _ <- ask if layout mode == PPOffsideRule then (pure "") else (infoElem ";") astPretty (PatBind _ pat mType rhs mBinds) = resultPretty $ ( (nestMode onsideIndent) $ constrElem PatBind -- myFsep <*> (annNoInfoElem $ astPretty pat) <*> traverse (\x -> (sepElem myFsep) *> infoElem "::" *> sepElem hsep *> (annNoInfoElem.astPretty) x) mType <* sepElem myFsep <*> (annNoInfoElem $ astPretty rhs) ) <*> ppWhere mBinds astPretty (ForImp _ callConv mSafety mStr n t) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem ForImp -- mySep <* infoElem "foreign import" <* sepElem fsep <*> (annNoInfoElem $ astPretty callConv) <*> traverse (\ x -> sepElem fsep *> (annNoInfoElem $ astPretty x)) mSafety <*> traverse (\ x -> sepElem fsep *> infoElem x) mStr <* sepElem fsep <*> (annNoInfoElem $ astPretty n) <* sepElem fsep <* infoElem "::" <*> (annNoInfoElem $ astPretty t) astPretty (ForExp _ callConv mStr n t) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem ForExp -- mySep <* infoElem "foreign export" <* sepElem fsep <*> (annNoInfoElem $ astPretty callConv) <*> traverse (\ x -> sepElem fsep *> infoElem x) mStr <* sepElem fsep <*> (annNoInfoElem $ astPretty n) <* sepElem fsep <* infoElem "::" <*> (annNoInfoElem $ astPretty t) astPretty (RulePragmaDecl _ rs) = blankline.resultPretty $ constrElem RulePragmaDecl -- myVcat <* infoElem "{-# RULES" <* sepElem myVcat <*> intersperse (sepElem myVcat) (annListElem annNoInfoElem rs) <* sepElem myVcat <* sepElem hsep <* infoElem "#-}" astPretty (DeprPragmaDecl _ ds) = blankline.resultPretty $ constrElem DeprPragmaDecl -- myVcat <* infoElem "{-# DEPRECATED" <* sepElem myVcat <*> intersperse (sepElem myVcat) (map ppWarnDepr ds) <* sepElem myVcat <* sepElem hsep <* infoElem "#-}" astPretty (WarnPragmaDecl _ ws) = blankline.resultPretty $ constrElem WarnPragmaDecl -- myVcat <* infoElem "{-# WARNING" <* sepElem myVcat <*> intersperse (sepElem myVcat) (map ppWarnDepr ws) <* sepElem myVcat <* sepElem hsep <* infoElem "#-}" astPretty (InlineSig _ b mActivation qName) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem InlineSig -- mySep <*> pure b <* (infoElem $ if b then "{-# INLINE" else "{-# NOINLINE") <*> traverse (\ x -> sepElem fsep *> (annNoInfoElem $ astPretty x)) mActivation <* sepElem fsep <*> (annNoInfoElem $ astPretty qName) <* sepElem hsep <* infoElem "#-}" astPretty (InlineConlikeSig _ mActivation qName) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem InlineConlikeSig -- mySep <* infoElem "{-# INLINE_CONLIKE" <*> traverse (\ x -> sepElem fsep *> annNoInfoElem (astPretty x)) mActivation <* sepElem fsep <*> (annNoInfoElem $ astPretty qName) <* infoElem "#-}" astPretty (SpecSig _ mActivation qName ts) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem SpecSig -- mySep <* infoElem "{-# SPECIALISE" <*> traverse (\ x -> sepElem fsep *> annNoInfoElem (astPretty x)) mActivation <* sepElem fsep <*> (annNoInfoElem $ astPretty qName) <* sepElem fsep <* infoElem "::" <* sepElem fsep <*> intersperse (infoElem "," <* sepElem fsep) (annListElem annNoInfoElem ts) <* sepElem fsep <* infoElem "#-}" astPretty (SpecInlineSig _ b mActivation qName ts) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem SpecInlineSig -- mySep <* infoElem "{-# SPECIALISE" <* sepElem fsep <*> pure b <* (infoElem $ if b then "INLINE" else "NOINLINE") <*> traverse (\ x -> sepElem fsep *> (annNoInfoElem $ astPretty x)) mActivation <* sepElem fsep <*> (annNoInfoElem $ astPretty qName) <* sepElem fsep <* infoElem "::" <* sepElem fsep <*> intersperse (infoElem "," <* sepElem fsep) (annListElem annNoInfoElem ts) <* sepElem fsep <* infoElem "#-}" astPretty (InstSig _ mContext ih ) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem InstSig -- mySep <* infoElem "{-# SPECIALISE" <* sepElem fsep <* infoElem "instance" <*> traverse (\ x -> sepElem fsep *> (annNoInfoElem $ astPretty x)) mContext <* sepElem fsep <*> ppInstHeadInDecl ih <* sepElem fsep <* infoElem "#-}" astPretty (AnnPragma _ annotation) = blankline.resultPretty.(nestMode onsideIndent) $ constrElem AnnPragma -- mySep <* infoElem "{-# ANN" <* sepElem fsep <*> (annNoInfoElem $ astPretty annotation) <* sepElem fsep <* infoElem "#-}" ppConstrList :: (Annotated ast, PrettyAst ast) => [ast a] -> AstElem [ast SrcSpanInfo] ppConstrList [] = sequenceA [] ppConstrList cs = infoElem "=" *> sepElem hsep *> intersperse (sepElem hsep *> infoElem "|" *> sepElem myVcat) (annListElem annNoInfoElem cs) ppFsepDhead :: DeclHead a -> AstElem (DeclHead SrcSpanInfo) ppFsepDhead dh = annNoInfoElem.resultPretty $ constrElem DHead <*> pointsInfoElem (astPretty name) <* sepElemIf (not $ null tvs) fsep <*> intersperse (sepElem fsep) (annListElem annNoInfoElem tvs) where (name, tvs) = sDeclHead dh ppInstHeadInDecl :: InstHead a -> AstElem (InstHead SrcSpanInfo) ppInstHeadInDecl ih = annNoInfoElem.resultPretty $ constrElem IHead <*> annNoInfoElem (astPretty qn) <* sepElemIf (not $ null ts) fsep <*> intersperse (sepElem fsep) (map (annNoInfoElem.ppAType) ts) where (qn, ts) = sInstHead ih -- -------------------------------------------------------------------------- ppWarnDepr :: (Annotated ast, PrettyAst ast) => ([ast a], String) -> AstElem ([ast SrcSpanInfo], String) ppWarnDepr ([], txt) = pure (,) <*> pure [] <*> infoElem txt ppWarnDepr (ns, txt) = pure (,) <*> intersperse (infoElem "," <* sepElem fsep) (annListElem annNoInfoElem ns) <* sep ns <*> infoElem txt where sep [n] = sepElem hsep sep _ = sepElem fsep -- -------------------------------------------------------------------------- instance PrettyAst DeclHead where astPretty (DHead _ n tvs) = -- mySep resultPretty.(nestMode onsideIndent) $ constrElem DHead <*> pointsInfoElem (astPretty n) <* sepElem fsep <*> intersperse (sepElem fsep) (annListElem annNoInfoElem tvs) astPretty (DHInfix _ tva n tvb) = -- mySep resultPretty.(nestMode onsideIndent) $ constrElem DHInfix <*> (annInfoElem $ astPretty tva) <* sepElem fsep <*> (annInfoElem $ astPretty n) <* sepElem fsep <*> (annInfoElem $ astPretty tvb) astPretty (DHParen _ dh) = -- parens (pretty dh) resultPretty.parens $ constrElem DHParen <*> (annNoInfoElem $ astPretty dh) -- -------------------------------------------------------------------------- instance PrettyAst InstHead where astPretty (IHead _ qn ts) = resultPretty.(nestMode onsideIndent) $ constrElem IHead -- mySep <*> annNoInfoElem (astPretty qn) <* sepElemIf (not $ null ts) fsep <*> intersperse (sepElem fsep) (annListElem annNoInfoElem ts) astPretty (IHInfix _ ta qn tb) = resultPretty.(nestMode onsideIndent) $ constrElem IHInfix -- mySep <*> annNoInfoElem (astPretty ta) <* sepElem fsep <*> annNoInfoElem (astPretty qn) <* sepElem fsep <*> annInfoElem (astPretty tb) astPretty (IHParen _ ih) = resultPretty.parens $ constrElem IHParen <*> (annNoInfoElem $ astPretty ih) -- -------------------------------------------------------------------------- instance PrettyAst DataOrNew where astPretty (DataType _) = resultPretty $ constrElem DataType <* noInfoElem "data" astPretty (NewType _) = resultPretty $ constrElem NewType <* noInfoElem "newtype" -- -------------------------------------------------------------------------- instance PrettyAst Assoc where astPretty (AssocNone _) = resultPretty $ constrElem AssocNone <* noInfoElem "infix" astPretty (AssocLeft _) = resultPretty $ constrElem AssocLeft <* noInfoElem "infixl" astPretty (AssocRight _) = resultPretty $ constrElem AssocRight <* noInfoElem "infixr" -- -------------------------------------------------------------------------- instance PrettyAst Match where astPretty m = case m of (InfixMatch _ pa n pbs rhs mWhere) -> resultPretty.(nestMode onsideIndent) $ constrElem InfixMatch <*> annNoInfoElem (astPretty pa) <* sepElem myFsep <*> annNoInfoElem (ppNameInfix n) <* sepElem myFsep <*> ppPbs pbs <*> annNoInfoElem (astPretty rhs) <*> ppWhere mWhere (Match _ n pbs rhs mWhere) -> resultPretty $ constrElem Match <*> ppName n <* sepElem myFsep <*> ppPbs pbs <*> annNoInfoElem (astPretty rhs) <*> ppWhere mWhere where ppName n@(Symbol _ _) = pointsInfoElem (ppNameInfix n) ppName n = annNoInfoElem (astPretty n) ppPbs ps = intersperse (sepElem myFsep) (map (annNoInfoElem.astPrettyPrec 2) ps) <* sepElemIf (not $ null ps) myFsep ppWhere :: Maybe (Binds a) -> AstElem (Maybe (Binds SrcSpanInfo)) ppWhere mWhere = traverse (\x -> (nestMode onsideIndent) $ sepElem myVcat *> infoElem "where" *> impl x) mWhere where impl (BDecls _ []) = annNoInfoElem.resultPretty $ constrElem BDecls <* implicitElem "{" <*> pure [] <* implicitElem "}" impl (BDecls _ l) = annNoInfoElem.resultPretty $ constrElem BDecls <*> ppBody whereIndent (annListElem annNoInfoElem l) impl (IPBinds _ b) = annNoInfoElem.resultPretty $ constrElem IPBinds <*> ppBody whereIndent (annListElem annNoInfoElem b) -- -------------------------------------------------------------------------- instance PrettyAst ClassDecl where astPretty (ClsDecl _ d) = resultPretty $ constrElem ClsDecl <*> (annInfoElem $ astPretty d) astPretty (ClsDataFam _ context dh mkind) = resultPretty.(nestMode onsideIndent) $ constrElem ClsDataFam -- mySep <* infoElem "data" <* sepElem fsep <*> traverse (\ c -> (annNoInfoElem $ astPretty c) <* sepElem fsep) context <*> ppFsepDhead dh <* sepElemIf (isJust mkind) fsep <*> ppOptKind mkind astPretty (ClsTyFam _ dh mkind) = resultPretty.(nestMode onsideIndent) $ constrElem ClsTyFam -- mySep <* infoElem "type" <* sepElem fsep <*> ppFsepDhead dh <* sepElemIf (isJust mkind) fsep <*> ppOptKind mkind astPretty (ClsTyDef _ ntype htype) = resultPretty.(nestMode onsideIndent) $ constrElem ClsTyDef -- mySep <*> (annInfoElem $ astPretty ntype) <* sepElem fsep <* infoElem "=" <* sepElem fsep <*> (annInfoElem $ astPretty htype) -- -------------------------------------------------------------------------- instance PrettyAst InstDecl where astPretty (InsDecl _ decl) = resultPretty $ constrElem InsDecl <*> pointsInfoElem (astPretty decl) astPretty (InsType _ ntype htype) = resultPretty.(nestMode onsideIndent) $ constrElem InsType -- mySep <* infoElem "type" <* sepElem fsep <*> (annInfoElem $ astPretty ntype) <* sepElem fsep <* infoElem "=" <* sepElem fsep <*> (annInfoElem $ astPretty htype) astPretty (InsData _ don ntype constrList derives) = resultPretty $ onsideHead (constrElem InsData) <* sepElem hsep <*> constrList' (annListElem annNoInfoElem constrList) <*> traverse (\x -> sepElem myVcat *> ppDeriving x) derives where onsideHead f = (nestMode onsideIndent) $ f <*> (annInfoElem $ astPretty don) <* sepElem fsep <*> (annInfoElem $ astPretty ntype) cSep1 = infoElem "=" <* sepElem hsep cSep2 = sepElem myVcat <* infoElem "|" <* sepElem hsep constrList' (e1:e2:es) = sequenceA $ (e1 <* cSep1) : e2 : (map (cSep2 *>) es) constrList' es = sequenceA es astPretty (InsGData _ don ntype mkind gadtList derives) = resultPretty.(nestMode onsideIndent) $ onsideHead (constrElem InsGData) <*> ppBody classIndent (annListElem annNoInfoElem gadtList) <*> traverse (\x -> sepElem myVcat *> ppDeriving x) derives where onsideHead f = (nestMode onsideIndent) $ f -- mySep <*> (annInfoElem $ astPretty don) <* sepElem fsep <*> (annInfoElem $ astPretty ntype) <* sepElemIf (isJust mkind) fsep <*> ppOptKind mkind <* sepElem fsep <* infoElem "where" ------------------------- FFI stuff ------------------------------------- instance PrettyAst Safety where astPretty (PlayRisky _) = resultPretty $ constrElem PlayRisky <* infoElem "unsafe" astPretty (PlaySafe _ b) = resultPretty $ constrElem PlaySafe <*> pure b <* (infoElem $ if b then "threadsafe" else "safe") -- -------------------------------------------------------------------------- instance PrettyAst CallConv where astPretty (StdCall _) = resultPretty $ constrElem StdCall <* infoElem "stdcall" astPretty (CCall _) = resultPretty $ constrElem CCall <* infoElem "ccall" astPretty (CPlusPlus _) = resultPretty $ constrElem CPlusPlus <* infoElem "cplusplus" astPretty (DotNet _) = resultPretty $ constrElem DotNet <* infoElem "dotnet" astPretty (Jvm _) = resultPretty $ constrElem Jvm <* infoElem "jvm" astPretty (Js _) = resultPretty $ constrElem Js <* infoElem "js" ------------------------- Pragmas --------------------------------------- instance PrettyAst Rule where astPretty (Rule _ tag activ rvs rhs lhs) = resultPretty.(nestMode onsideIndent) $ constrElem Rule -- mySep <*> infoElem tag <*> traverse (\x -> sepElem fsep *> (annInfoElem $ astPretty x)) activ <*> traverse (\x -> sepElem fsep *> ppRuleVars x) rvs <* sepElem fsep <*> (annInfoElem $ astPretty rhs) <* sepElem fsep <* infoElem "=" <* sepElem fsep <*> (annInfoElem $ astPretty lhs) ppRuleVars [] = pure [] ppRuleVars rvs = (nestMode onsideIndent) $ infoElem "forall" *> sepElem fsep *> intersperse (sepElem fsep) (annListElem annNoInfoElem rvs) <* infoElem "." -- -------------------------------------------------------------------------- instance PrettyAst Activation where astPretty (ActiveFrom _ i) = resultPretty $ constrElem ActiveFrom <* infoElem "[" <*> pure i <* (infoElem $ show i) <* infoElem "]" astPretty (ActiveUntil _ i) = resultPretty $ constrElem ActiveUntil <* infoElem "[~" <*> pure i <* (infoElem $ show i) <* infoElem "]" -- -------------------------------------------------------------------------- instance PrettyAst RuleVar where astPretty (RuleVar _ n) = resultPretty $ constrElem RuleVar <*> (annInfoElem $ astPretty n) astPretty (TypedRuleVar _ n t) = resultPretty.(nestMode onsideIndent).parens $ constrElem TypedRuleVar -- mySep <* sepElem fsep <*> (annInfoElem $ astPretty n) <* sepElem fsep <* infoElem "::" <* sepElem fsep <*> (annInfoElem $ astPretty t) <* sepElem fsep -- -------------------------------------------------------------------------- instance PrettyAst ModulePragma where astPretty (LanguagePragma _ ns) = resultPretty.(nestMode onsideIndent) $ constrElem LanguagePragma -- myFsep <* infoElem "{-# LANGUAGE" <* sepElem myFsep <*> intersperse (infoElem "," <* sepElem myFsep) (annListElem annNoInfoElem ns) <* sepElem myFsep <* infoElem "#-}" astPretty (OptionsPragma _ mbTool s) = do -- myFsep let opt = "{-# OPTIONS" ++ case mbTool of Nothing -> " " Just (UnknownTool u) -> "_" ++ show u Just tool -> "_" ++ show tool in resultPretty.(nestMode onsideIndent) $ constrElem OptionsPragma <*> pure mbTool <* infoElem opt <*> encloseIf (not $ null s) (sepElem myFsep ) (sepElem myFsep) (noInfoElem s) <* infoElem "#-}" astPretty (AnnModulePragma _ ann) = resultPretty.(nestMode onsideIndent) $ constrElem AnnModulePragma -- myFsep <* infoElem "{-# ANN" <* sepElem myFsep <*> (annNoInfoElem $ astPretty ann) <* sepElem myFsep <* infoElem "#-}" -- -------------------------------------------------------------------------- instance PrettyAst Annotation where astPretty (Ann _ n e) = resultPretty.(nestMode onsideIndent) $ constrElem Ann -- myFsep <*> (annNoInfoElem $ astPretty n) <* sepElem myFsep <*> (annNoInfoElem $ astPretty e) astPretty (TypeAnn _ n e) = resultPretty.(nestMode onsideIndent) $ constrElem TypeAnn -- myFsep <* infoElem "type" <* sepElem myFsep <*> (annNoInfoElem $ astPretty n) <* sepElem myFsep <*> (annNoInfoElem $ astPretty e) astPretty (ModuleAnn _ e) = resultPretty.(nestMode onsideIndent) $ constrElem ModuleAnn -- myFsep <* infoElem "module" <* sepElem myFsep <*> (annNoInfoElem $ astPretty e) ------------------------- Data & Newtype Bodies ------------------------- instance PrettyAst QualConDecl where astPretty (QualConDecl _ mtvs mContext con) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem QualConDecl <*> traverse (\ x -> (ppForall $ annListElem annNoInfoElem x) <* sepElem myFsep) mtvs <*> traverse (\ c -> (annNoInfoElem $ astPretty c) <* sepElem fsep) mContext <*> pointsInfoElem (astPretty con) -- -------------------------------------------------------------------------- instance PrettyAst GadtDecl where astPretty (GadtDecl _ name ty) = resultPretty $ constrElem GadtDecl <*> annNoInfoElem (astPretty name) <* sepElem myFsep <* infoElem "::" <* sepElem myFsep <*> annNoInfoElem (astPretty ty) -- -------------------------------------------------------------------------- instance PrettyAst ConDecl where astPretty (RecDecl _ name fieldList) = resultPretty $ constrElem RecDecl <*> annNoInfoElem (astPretty name) <* infoElem "{" <*> intersperse parenListSep (annListElem annNoInfoElem fieldList) <* infoElem "}" astPretty (ConDecl _ name typeList) = resultPretty.(nestMode onsideIndent) $ constrElem ConDecl -- mySep <*> annNoInfoElem (astPretty name) <* sepElemIf (not $ null typeList) fsep <*> intersperse (sepElem fsep) (map (annNoInfoElem.astPrettyPrec prec_atype) typeList) astPretty (InfixConDecl _ l name r) = resultPretty.(nestMode onsideIndent) $ constrElem InfixConDecl -- myFsep <*> annInfoElem (astPrettyPrec prec_btype l) <* sepElem myFsep <*> annNoInfoElem (ppNameInfix name) <* sepElem myFsep <*> annInfoElem (astPrettyPrec prec_btype r) -- -------------------------------------------------------------------------- instance PrettyAst FieldDecl where astPretty (FieldDecl _ names ty) = resultPretty $ constrElem FieldDecl <*> intersperse (noInfoElem "," <* sepElem myFsepSimple) (annListElem annNoInfoElem names) <* sepElem myFsepSimple <* infoElem "::" <* sepElem myFsepSimple <*> annNoInfoElem (astPretty ty) -- -------------------------------------------------------------------------- instance PrettyAst BangType where astPrettyPrec _ (BangedTy _ ty) = resultPretty $ constrElem BangedTy <* infoElem "!" <*> (annInfoElem $ ppAType ty) astPrettyPrec p (UnBangedTy _ ty) = resultPretty $ constrElem UnBangedTy <*> pointsInfoElem (ppType p ty) astPrettyPrec p (UnpackedTy _ ty) = resultPretty $ constrElem UnpackedTy <* infoElem "{-# UNPACK #-}" <* sepElem hsep <* infoElem "!" <*> (annInfoElem $ ppType p ty) -- -------------------------------------------------------------------------- instance PrettyAst Deriving where astPretty (Deriving _ ihs) = case ihs of [] -> resultPretty $ dheads <* infoElem "(" <*> pure [] <* infoElem ")" [ih@(IHead _ d [])] -> resultPretty $ dheads <*> ilist _ -> resultPretty $ dheads <* infoElem "(" <*> ilist <* infoElem ")" where dheads = constrElem Deriving <* infoElem "deriving" <* sepElem hsep ilist = intersperse parenListSep (annListElem annNoInfoElem ihs) ppDeriving :: Deriving a -> AstElem (Deriving SrcSpanInfo) ppDeriving d = annNoInfoElem (astPretty d) ------------------------- Types ------------------------- ppType :: Int -> Type a -> DocM (Type SrcSpanInfo) ppType p a = astPrettyPrec p a ppBType :: Type a -> DocM (Type SrcSpanInfo) ppBType = ppType prec_btype ppAType :: Type a -> DocM (Type SrcSpanInfo) ppAType = ppType prec_atype -- precedences for types prec_btype, prec_atype :: Int prec_btype = 1 -- left argument of ->, -- or either argument of an infix data constructor prec_atype = 2 -- argument of type or data constructor, or of a class instance PrettyAst Type where astPrettyPrec p (TyForall _ mtvs ctxt htype) = resultPretty.(nestMode onsideIndent) $ parensIf (p > 0) $ constrElem TyForall -- myFsep <*> traverse (\ x -> (ppForall $ annListElem annNoInfoElem x) <* sepElem myFsep) mtvs <*> traverse (\ c -> (annNoInfoElem $ astPretty c) <* sepElem myFsep) ctxt <*> (annNoInfoElem $ astPretty htype) astPrettyPrec p (TyFun _ a b) = resultPretty $ (nestMode onsideIndent) t where t = parensIf (p > 0) $ constrElem TyFun <*> (annNoInfoElem $ ppBType a) <* sepElem myFsep <* infoElem "->" <* sepElem myFsep <*> (annNoInfoElem $ astPretty b) astPrettyPrec _ (TyTuple _ bxd l) = resultPretty $ constrElem TyTuple <*> pure bxd <*> tupleParen bxd (annListElem annNoInfoElem l) astPrettyPrec _ (TyList _ t) = resultPretty $ constrElem TyList <*> t' where t' = enclose (infoElem "[") (infoElem "]") ((annNoInfoElem $ astPretty t)) astPrettyPrec p (TyApp _ a b) = resultPretty.(nestMode onsideIndent) $ encloseIf (p > prec_btype) (noInfoElem "(") (noInfoElem ")")$ constrElem TyApp <*> (annNoInfoElem $ astPretty a) <* sepElem myFsep <*> (annNoInfoElem $ ppAType b) astPrettyPrec _ (TyVar _ t) = resultPretty $ constrElem TyVar <*> (annNoInfoElem $ astPretty t) astPrettyPrec _ (TyCon _ t) = resultPretty $ constrElem TyCon <*> pointsInfoElem (astPretty t) astPrettyPrec _ (TyParen _ t) = resultPretty $ constrElem TyParen <*> t' where t' = enclose (infoElem "(") (infoElem ")") ((annNoInfoElem $ astPretty t)) astPrettyPrec _ (TyInfix _ a op b) = resultPretty.(nestMode onsideIndent) $ constrElem TyInfix <*> (annNoInfoElem $ astPretty a) <* sepElem myFsep <*> annNoInfoElem (ppQNameInfix op) <* sepElem myFsep <*> (annNoInfoElem $ astPretty b) astPrettyPrec _ (TyKind _ t k) = resultPretty $ (nestMode onsideIndent) t' where t' = parens $ constrElem TyKind -- myFsep <* sepElem myFsep <*> (annNoInfoElem $ astPretty t) <* sepElem myFsep <* infoElem "::" <*> (annNoInfoElem $ astPretty k) <* sepElem myFsep -- -------------------------------------------------------------------------- instance PrettyAst TyVarBind where astPretty (KindedVar _ var kind) = resultPretty.(nestMode onsideIndent) $ constrElem KindedVar -- myFsep <* infoElem "(" <*> annNoInfoElem (astPretty var) <* sepElem myFsep <* infoElem "::" <* sepElem myFsep <*> annNoInfoElem (astPretty kind) <* infoElem ")" astPretty (UnkindedVar _ var) = resultPretty $ constrElem UnkindedVar <*> annNoInfoElem (astPretty var) ppForall :: [AstElem a] -> AstElem [a] ppForall [] = pure [] ppForall vs = (nestMode onsideIndent) $ infoElem "forall" *> sepElem myFsep *> intersperse (sepElem myFsep) vs <* sepElem myFsep <* infoElem "." ---------------------------- Kinds ---------------------------- instance PrettyAst Kind where astPrettyPrec _ (KindStar _) = resultPretty $ constrElem KindStar <* noInfoElem "*" astPrettyPrec _ (KindBang _) = resultPretty $ constrElem KindBang <* noInfoElem "!" astPrettyPrec n (KindFn _ a b) = resultPretty.(nestMode onsideIndent).parensIf (n > 0) $ constrElem KindFn -- myFsep <*> annNoInfoElem (astPrettyPrec 1 a) <* sepElem myFsep <* infoElem "->" <* sepElem myFsep <*> annNoInfoElem (astPretty b) astPrettyPrec _ (KindParen _ k) = resultPretty.parens $ constrElem KindParen <*> annNoInfoElem (astPretty k) astPrettyPrec _ (KindVar _ n) = resultPretty $ constrElem KindVar <*> annNoInfoElem (astPretty n) ppOptKind :: Maybe (Kind a) -> AstElem (Maybe (Kind SrcSpanInfo)) ppOptKind k = traverse (\ x -> infoElem "::" *> sepElem fsep *> annNoInfoElem (astPretty x)) k ------------------- Functional Dependencies ------------------- instance PrettyAst FunDep where astPretty (FunDep _ from to) = resultPretty $ constrElem FunDep <*> intersperse (sepElem myFsep) (annListElem annNoInfoElem from) <* sepElem myFsep <* infoElem "->" <*> intersperse (sepElem myFsep) (annListElem annNoInfoElem to) ppFunDeps :: (Annotated ast, PrettyAst ast) => [ast a] -> AstElem [ast SrcSpanInfo] ppFunDeps [] = sequenceA [] ppFunDeps fds = (nestMode onsideIndent) $ infoElem "|" *> sepElem myFsep *> intersperse (infoElem "," <* sepElem myFsep) (annListElem annNoInfoElem fds) ------------------------- Expressions ------------------------- instance PrettyAst Rhs where astPretty (UnGuardedRhs _ e) = resultPretty $ constrElem UnGuardedRhs <* infoElem "=" <* sepElem hsep <*> (annNoInfoElem $ astPretty e) astPretty (GuardedRhss _ guardList) = resultPretty $ constrElem GuardedRhss <*> intersperse (sepElem myVcat) (annListElem annNoInfoElem guardList) -- -------------------------------------------------------------------------- instance PrettyAst GuardedRhs where astPretty (GuardedRhs _ guards ppBody) = resultPretty.(nestMode onsideIndent) $ constrElem GuardedRhs -- myFsep <* infoElem "|" <* sepElem myFsep <*> intersperse (infoElem "," <* sepElem myFsep) (annListElem annNoInfoElem guards) <* sepElem myFsep <* infoElem "=" <* sepElem myFsep <*> (annInfoElem $ astPretty ppBody) -- -------------------------------------------------------------------------- instance PrettyAst Literal where astPretty (Int _ i s) = resultPretty $ constrElem Int <*> pure i <* (noInfoElem $ show i) <*> pure s astPretty (Char _ c s) = resultPretty $ constrElem Char <*> pure c <* (noInfoElem $ show c) <*> pure s astPretty (String _ s s') = resultPretty $ constrElem String <*> pure s <* (noInfoElem $ show s) <*> pure s' astPretty (Frac _ r s) = resultPretty $ constrElem Frac <*> pure r <* (noInfoElem.show $ fromRational r) <*> pure s -- GHC unboxed literals: astPretty (PrimChar _ c s) = resultPretty $ constrElem PrimChar <*> pure c <* (infoElem $ show c ++ "#") <*> pure s astPretty (PrimString _ s s') = resultPretty $ constrElem PrimString <*> pure s <* (infoElem $ show s ++ "#") <*> pure s' astPretty (PrimInt _ i s) = resultPretty $ constrElem PrimInt <*> pure i <* (infoElem $ show i ++ "#") <*> pure s astPretty (PrimWord _ w s) = resultPretty $ constrElem PrimWord <*> pure w <* (infoElem $ show w ++ "##") <*> pure s astPretty (PrimFloat _ r s) = resultPretty $ constrElem PrimFloat <*> pure r <* (infoElem $ (show $ fromRational r) ++ "#") <*> pure s astPretty (PrimDouble _ r s) = resultPretty $ constrElem PrimFloat <*> pure r <* (infoElem $ (show $ fromRational r) ++ "##") <*> pure s -- -------------------------------------------------------------------------- instance PrettyAst Exp where astPrettyPrec _ (Lit _ l) = resultPretty $ constrElem Lit <*> (annNoInfoElem $ astPretty l) -- lambda stuff astPrettyPrec p (InfixApp _ a op b) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 2) $ constrElem InfixApp <*> annNoInfoElem (astPrettyPrec 2 a) <* sepElem myFsep <*> (annNoInfoElem $ astPretty op) <* sepElem myFsep <*> annNoInfoElem (astPrettyPrec 1 b) astPrettyPrec p (NegApp _ e) = resultPretty . parensIf (p > 0) $ constrElem NegApp <* infoElem "-" <*> annInfoElem (astPrettyPrec 4 e) astPrettyPrec p (App _ a b) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 3) $ constrElem App <*> annNoInfoElem (astPrettyPrec 3 a) <* sepElem myFsep <*> annNoInfoElem (astPrettyPrec 4 b) astPrettyPrec p (Lambda _ patList body) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 1) $ constrElem Lambda <* infoElem "\\" <* sepElem myFsep <*> intersperse (sepElem myFsep) (map (annNoInfoElem . astPrettyPrec 2) patList) <* sepElem myFsep <* infoElem "->" <*> annNoInfoElem (astPretty body) -- keywords -- two cases for lets astPrettyPrec p (Let _ (BDecls _ declList) letBody) = resultPretty.parensIf (p > 1) $ ppLetExp BDecls declList letBody astPrettyPrec p (Let _ (IPBinds _ bindList) letBody) = resultPretty.parensIf (p > 1) $ ppLetExp IPBinds bindList letBody astPrettyPrec p (If _ cond thenexp elsexp) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 1) $ constrElem If <* infoElem "if" <* sepElem myFsep <*> (annNoInfoElem $ astPretty cond) <* sepElem myFsep <* infoElem "then" <* sepElem myFsep <*> (annNoInfoElem $ astPretty thenexp) <* sepElem myFsep <* infoElem "else" <* sepElem myFsep <*> (annNoInfoElem $ astPretty elsexp) astPrettyPrec p (Case _ cond altList) = -- myFsep resultPretty.parensIf (p > 1) $ ( (nestMode onsideIndent) $ constrElem Case <* infoElem "case" <* sepElem myFsep <*> (annNoInfoElem $ astPretty cond) <* sepElem myFsep <* infoElem "of" ) <*> ppBody caseIndent (annListElem annNoInfoElem altList) astPrettyPrec p (Do _ stmtList) = resultPretty.parensIf (p > 1) $ constrElem Do <* infoElem "do" <*> ppBody doIndent (annListElem annNoInfoElem stmtList) astPrettyPrec p (MDo _ stmtList) = resultPretty.parensIf (p > 1) $ constrElem MDo <* infoElem "mdo" <*> ppBody doIndent (annListElem annNoInfoElem stmtList) -- Constructors & Vars astPrettyPrec _ (Var _ name) = resultPretty $ constrElem Var <*> (pointsInfoElem $ astPretty name) astPrettyPrec _ (IPVar _ ipname) = resultPretty $ constrElem IPVar <*> (annInfoElem $ astPretty ipname) astPrettyPrec _ (Con _ name) = resultPretty $ constrElem Con <*> (pointsInfoElem $ astPretty name) astPrettyPrec _ (Tuple _ bxd expList) = resultPretty $ constrElem Tuple <*> pure bxd <*> tupleParen bxd (annListElem annNoInfoElem expList) astPrettyPrec _ (TupleSection _ bxd mExpList) = resultPretty $ constrElem TupleSection <*> pure bxd <*> tupleParen bxd (tuples mExpList) where tuples [] = [] tuples (x:[]) = [tupleItem x] tuples (x:xs) = tupleItem x : impl xs where impl (x:[]) = (infoElem "," *> (if isJust x then sepElem myFsepSimple else pure ()) *> tupleItem x) : [] impl (x:xs) = (infoElem "," *> sepElem myFsepSimple *> tupleItem x) : impl xs tupleItem = traverse $ annNoInfoElem.astPretty -- weird stuff astPrettyPrec _ (Paren _ e) = resultPretty $ constrElem Paren <* infoElem "(" <*> annNoInfoElem (astPretty e) <* infoElem ")" astPrettyPrec _ (LeftSection _ e op) = resultPretty $ constrElem LeftSection <* infoElem "(" <*> annNoInfoElem (astPretty e) <* sepElem hsep <*> annNoInfoElem (astPretty op) <* infoElem ")" astPrettyPrec _ (RightSection _ op e) = resultPretty $ constrElem RightSection <*> (annInfoElem $ astPretty op) <* sepElem hsep <*> (annInfoElem $ astPretty e) astPrettyPrec _ (RecConstr _ c fieldList) = resultPretty $ constrElem RecConstr <*> annNoInfoElem (astPretty c) <* infoElem "{" <*> intersperse parenListSep (annListElem annNoInfoElem fieldList) <* infoElem "}" astPrettyPrec _ (RecUpdate _ e fieldList) = resultPretty $ constrElem RecUpdate <*> (annInfoElem $ astPretty e) <*> braceList (annListElem annNoInfoElem fieldList) -- Lists astPrettyPrec _ (List _ list) = resultPretty $ constrElem List <* infoElem "[" <*> intersperse (infoElem "," <* sepElem myFsepSimple) (annListElem annNoInfoElem list) <* infoElem "]" astPrettyPrec _ (EnumFrom _ e) = resultPretty $ constrElem EnumFrom <* infoElem "[" <*> (annInfoElem $ astPretty e) <* sepElem myFsepSimple <* infoElem ".." <* infoElem "]" astPrettyPrec _ (EnumFromTo _ from to) = resultPretty $ constrElem EnumFromTo <* infoElem "[" <*> annNoInfoElem (astPretty from) <* sepElem myFsepSimple <* infoElem ".." <* sepElem myFsepSimple <*> annNoInfoElem (astPretty to) <* infoElem "]" astPrettyPrec _ (EnumFromThen _ from thenE) = resultPretty $ constrElem EnumFromThen <* infoElem "[" <*> (annInfoElem $ astPretty from) <* infoElem "," <* sepElem myFsepSimple <*> (annInfoElem $ astPretty thenE) <* sepElem myFsepSimple <* infoElem ".." <* infoElem "]" astPrettyPrec _ (EnumFromThenTo _ from thenE to) = resultPretty $ constrElem EnumFromThenTo <* infoElem "[" <*> (annInfoElem $ astPretty from) <* infoElem "," <* sepElem myFsepSimple <*> (annInfoElem $ astPretty thenE) <* sepElem myFsepSimple <* infoElem ".." <* sepElem myFsepSimple <*> (annInfoElem $ astPretty to) <* infoElem "]" astPrettyPrec _ (ListComp _ e qualList) = resultPretty $ constrElem ListComp <* infoElem "[" <*> annNoInfoElem (astPretty e) <* sepElem myFsepSimple <* infoElem "|" <* sepElem myFsepSimple <*> intersperse (infoElem "," <* sepElem myFsepSimple) (annListElem annNoInfoElem qualList) <* infoElem "]" astPrettyPrec _ (ParComp _ e qualLists) = resultPretty $ constrElem ParComp <* infoElem "[" <*> (annInfoElem $ astPretty e) <* sepElem myFsepSimple <* infoElem "|" <* sepElem myFsepSimple <*> sequenceA (map qList qualLists) where qsSep = infoElem "," <* sepElem myFsepSimple <* infoElem "|" <* sepElem myFsepSimple qList qs = intersperse qsSep (annListElem annNoInfoElem qs) astPrettyPrec p (ExpTypeSig _ e ty) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem ExpTypeSig <*> (annInfoElem $ astPretty e) <* sepElem myFsep <* infoElem "::" <*> (annInfoElem $ astPretty ty) -- Template Haskell astPrettyPrec _ (BracketExp _ b) = resultPretty $ constrElem BracketExp <*> (annInfoElem $ astPretty b) astPrettyPrec _ (SpliceExp _ s) = resultPretty $ constrElem SpliceExp <*> (annInfoElem $ astPretty s) astPrettyPrec _ (TypQuote _ t) = resultPretty $ constrElem TypQuote <* infoElem "\'\'" <*> (annInfoElem $ astPretty t) astPrettyPrec _ (VarQuote _ x) = resultPretty $ constrElem VarQuote <* infoElem "\'" <*> (annInfoElem $ astPretty x) astPrettyPrec _ (QuasiQuote _ n qt) = resultPretty $ constrElem QuasiQuote <* noInfoElem "[" <*> noInfoElem n <* noInfoElem "|" <*> noInfoElem qt <* noInfoElem "|]" -- Hsx astPrettyPrec _ (XTag _ n attrs mattr cs) = unimplemented astPrettyPrec _ (XETag _ n attrs mattr) = resultPretty.(nestMode onsideIndent) $ constrElem XETag -- myFsep <* infoElem "<" <* sepElem myFsep <*> (annInfoElem $ astPretty n) <* sepElem myFsep <*> intersperse (sepElem myFsep) (annListElem annNoInfoElem attrs) <*> traverse (\x -> sepElem myFsep *> (annInfoElem $ astPretty x)) mattr <* sepElem myFsep <* infoElem "/>" astPrettyPrec _ (XPcdata _ s) = resultPretty $ constrElem XPcdata <*> infoElem s astPrettyPrec _ (XExpTag _ e) = resultPretty.(nestMode onsideIndent) $ constrElem XExpTag -- myFsep <* infoElem "<%" <* sepElem myFsep <*> (annInfoElem $ astPretty e) <* sepElem myFsep <* infoElem "%>" astPrettyPrec _ (XChildTag _ cs) = resultPretty.(nestMode onsideIndent) $ constrElem XChildTag -- myFsep <* infoElem "<%>" <* sepElem myFsep <*> intersperse (sepElem myFsep) (annListElem annNoInfoElem cs) <* sepElem myFsep <* infoElem "</%>" -- Pragmas astPrettyPrec p (CorePragma _ s e) = resultPretty.(nestMode onsideIndent) $ constrElem CorePragma -- myFsep <* noInfoElem "{-# CORE" <* sepElem myFsep <*> quoteStringElem s <* sepElem myFsep <* infoElem "#-}" <* sepElem myFsep <*> (annInfoElem $ astPretty e) astPrettyPrec _ (SCCPragma _ s e) = resultPretty.(nestMode onsideIndent) $ constrElem SCCPragma -- myFsep <* noInfoElem "{-# SCC" <* sepElem myFsep <*> quoteStringElem s <* sepElem myFsep <* infoElem "#-}" <* sepElem myFsep <*> (annNoInfoElem $ astPretty e) astPrettyPrec _ (GenPragma _ s (a,b) (c,d) e) = resultPretty.(nestMode onsideIndent) $ constrElem GenPragma -- myFsep <* noInfoElem "{-# GENERATED" <* sepElem myFsep <*> quoteStringElem s <* sepElem myFsep <*> tpl(a, b) <* sepElem myFsep <*> tpl(c, d) <* sepElem myFsep <* infoElem "#-}" <* sepElem myFsep <*> (annInfoElem $ astPretty e) where tpl (x, y) = pure (x, y) <* noInfoElem (show x) <* sepElem myFsep <* infoElem ":" <* sepElem myFsep <* noInfoElem (show y) -- Arrows astPrettyPrec p (Proc _ pat e) = resultPretty.(nestMode onsideIndent).parensIf (p > 1) $ constrElem Proc -- myFsep <* infoElem "proc" <* sepElem myFsep <*> (annInfoElem $ astPretty pat) <* sepElem myFsep <* infoElem "->" <* sepElem myFsep <*> (annInfoElem $ astPretty e) astPrettyPrec p (LeftArrApp _ l r) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem LeftArrApp <*> (annInfoElem $ astPretty l) <* sepElem myFsep <* infoElem "-<" <* sepElem myFsep <*> (annInfoElem $ astPretty r) astPrettyPrec p (RightArrApp _ l r) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem RightArrApp <*> (annInfoElem $ astPretty l) <* sepElem myFsep <* infoElem ">-" <* sepElem myFsep <*> (annInfoElem $ astPretty r) astPrettyPrec p (LeftArrHighApp _ l r) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem LeftArrHighApp <*> (annInfoElem $ astPretty l) <* sepElem myFsep <* infoElem "-<<" <* sepElem myFsep <*> (annInfoElem $ astPretty r) astPrettyPrec p (RightArrHighApp _ l r) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem RightArrHighApp <*> (annInfoElem $ astPretty l) <* sepElem myFsep <* infoElem ">>-" <* sepElem myFsep <*> (annInfoElem $ astPretty r) -- -------------------------------------------------------------------------- instance PrettyAst XAttr where astPretty (XAttr _ n v) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem XAttr <*> (annInfoElem $ astPretty n) <* sepElem myFsep <* infoElem "=" <* sepElem myFsep <*> (annInfoElem $ astPretty v) -- -------------------------------------------------------------------------- instance PrettyAst XName where astPretty (XName _ n) = resultPretty $ constrElem XName <*> infoElem n astPretty (XDomName _ d n) = resultPretty $ constrElem XDomName <*> infoElem d <* infoElem ":" <*> infoElem n ppLetExp f l b = (nestMode onsideIndent) $ constrElem Let -- myFsep <* infoElem "let" <* sepElem hsep <*> (constrElem f <*> ppBody letIndent (annListElem annNoInfoElem l)) <* sepElem myFsep <* infoElem "in" <*> (annInfoElem $ astPretty b) --------------------- Template Haskell ------------------------- instance PrettyAst Bracket where astPretty (ExpBracket _ e) = resultPretty $ constrElem ExpBracket <*> ppBracket "[|" ((annInfoElem $ astPretty e)) astPretty (PatBracket _ p) = resultPretty $ constrElem PatBracket <*> ppBracket "[p|" ((annInfoElem $ astPretty p)) astPretty (TypeBracket _ t) = resultPretty $ constrElem TypeBracket <*> ppBracket "[t|" ((annInfoElem $ astPretty t)) astPretty (DeclBracket _ d) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem DeclBracket <*> ppBracket "[d|" d' where d' = intersperse (sepElem myFsep) (annListElem annInfoElem d) ppBracket :: String -> AstElem a -> AstElem a ppBracket o x = (nestMode onsideIndent) $ infoElem o -- myFsep *> sepElem myFsep *> x <* sepElem myFsep <* infoElem "|]" -- -------------------------------------------------------------------------- instance PrettyAst Splice where astPretty (IdSplice _ s) = resultPretty $ constrElem IdSplice <* infoElem "$" <*> infoElem s astPretty (ParenSplice _ e) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem ParenSplice <* infoElem "$(" <* sepElem myFsep <*> (annInfoElem $ astPretty e) <* sepElem myFsep <* infoElem ")" ------------------------- Patterns ----------------------------- instance PrettyAst Pat where astPrettyPrec _ (PVar _ name) = resultPretty $ constrElem PVar <*> (annNoInfoElem $ astPretty name) astPrettyPrec _ (PLit _ lit) = resultPretty $ constrElem PLit <*> (annInfoElem $ astPretty lit) astPrettyPrec p (PNeg _ pat) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem PNeg <* infoElem "-" <* sepElem myFsep <*> (annInfoElem $ astPretty pat) astPrettyPrec p (PInfixApp _ a op b) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem PInfixApp <*> annNoInfoElem (astPrettyPrec 1 a) <* sepElem myFsep <*> annNoInfoElem (ppQNameInfix op) <* sepElem myFsep <*> annNoInfoElem (astPrettyPrec 1 b) astPrettyPrec p (PApp _ n ps) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 1 && not (null ps)) $ constrElem PApp <*> annNoInfoElem (astPretty n) <* sepElem myFsep <*> intersperse (sepElem myFsep) (map (annNoInfoElem.astPrettyPrec 2) ps) astPrettyPrec _ (PTuple _ bxd ps) = resultPretty $ constrElem PTuple <*> pure bxd <*> tupleParen bxd (annListElem annNoInfoElem ps) astPrettyPrec _ (PList _ ps) = resultPretty $ constrElem PList <* infoElem "[" <*> intersperse parenListSep (annListElem annNoInfoElem ps) <* infoElem "]" astPrettyPrec _ (PParen _ pat) = resultPretty $ constrElem PParen <* infoElem "(" <*> annNoInfoElem (astPretty pat) <* infoElem ")" astPrettyPrec _ (PRec _ c fields) = resultPretty $ constrElem PRec <*> annNoInfoElem (astPretty c) <* infoElem "{" <*> intersperse parenListSep (annListElem annNoInfoElem fields) <* infoElem "}" -- special case that would otherwise be buggy astPrettyPrec _ (PAsPat _ name (PIrrPat _ pat)) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem PAsPat <*> annNoInfoElem (astPretty name) <* infoElem "@" <* sepElem myFsep <* infoElem "~" <*> annNoInfoElem pat' where pat' = resultPretty $ constrElem PIrrPat <*> annNoInfoElem (astPrettyPrec 2 pat) astPrettyPrec _ (PAsPat _ name pat) = resultPretty $ constrElem PAsPat -- hcat <*> annNoInfoElem (astPretty name) <* infoElem "@" <*> annNoInfoElem (astPrettyPrec 2 pat) astPrettyPrec _ (PWildCard _) = resultPretty$ constrElem PWildCard <* noInfoElem "_" astPrettyPrec _ (PIrrPat _ pat) = resultPretty $ constrElem PIrrPat <* infoElem "~" <*> annInfoElem (astPrettyPrec 2 pat) astPrettyPrec p (PatTypeSig _ pat ty) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem PatTypeSig <*> (annInfoElem $ astPretty pat) <* sepElem myFsep <* infoElem "::" <* sepElem myFsep <*> (annInfoElem $ astPretty ty) astPrettyPrec p (PViewPat _ e pat) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem PViewPat <*> (annInfoElem $ astPretty e) <* sepElem myFsep <* infoElem "->" <* sepElem myFsep <*> (annInfoElem $ astPretty pat) astPrettyPrec p (PNPlusK _ n k) = -- myFsep resultPretty.(nestMode onsideIndent).parensIf (p > 0) $ constrElem PNPlusK <*> annNoInfoElem (astPretty n) <* sepElem myFsep <* infoElem "+" <* sepElem myFsep <*> pure k <* infoElem (show k) -- HaRP astPrettyPrec _ (PRPat _ rs) = resultPretty $ constrElem PRPat <*> bracketList (annListElem annNoInfoElem rs) astPrettyPrec _ (PXTag _ n attrs mattr cp) = unimplemented astPrettyPrec _ (PXETag _ n attrs mattr) = resultPretty.(nestMode onsideIndent) $ constrElem PXETag -- myFsep <* infoElem "<" <*> (annInfoElem $ astPretty n) <* sepElem myFsep <*> intersperse (sepElem myFsep) (map (annInfoElem.astPretty) attrs) <*> traverse (\x -> sepElem myFsep *> (annInfoElem $ astPretty x)) mattr <* sepElem myFsep <* infoElem "/>" astPrettyPrec _ (PXPcdata _ s) = resultPretty $ constrElem PXPcdata <*> infoElem s astPrettyPrec _ (PXPatTag _ p) = resultPretty.(nestMode onsideIndent) $ constrElem PXPatTag -- myFsep <* infoElem "<%" <* sepElem myFsep <*> (annInfoElem $ astPretty p) <* sepElem myFsep <* infoElem "%>" astPrettyPrec _ (PXRPats _ ps) = resultPretty.(nestMode onsideIndent) $ constrElem PXRPats -- myFsep <* infoElem "<[" <* sepElem myFsep <*> intersperse (sepElem myFsep) (map (annInfoElem.astPretty) ps) <* sepElem myFsep <* infoElem "]>" -- Generics astPrettyPrec _ (PExplTypeArg _ qn t) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem PExplTypeArg <*> (annInfoElem $ astPretty qn) <* sepElem myFsep <* infoElem "{|" <* sepElem myFsep <*> (annInfoElem $ astPretty t) <* sepElem myFsep <* infoElem "|}" astPrettyPrec _ (PBangPat _ pat) = resultPretty $ constrElem PBangPat <* infoElem "!" <*> annInfoElem (astPrettyPrec 2 pat) tupleParen bxd ls = infoElem openParen *> sequenceA ls <* infoElem closeParen where openParen = if bxd == Boxed then "(" else "{#" closeParen = if bxd == Boxed then ")" else "#}" -- -------------------------------------------------------------------------- instance PrettyAst PXAttr where astPretty (PXAttr _ n p) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem PXAttr <*> (annInfoElem $ astPretty n) <* sepElem myFsep <* infoElem "=" <* sepElem myFsep <*> (annInfoElem $ astPretty p) -- -------------------------------------------------------------------------- instance PrettyAst PatField where astPretty (PFieldPat _ n p) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem PFieldPat <*> (annInfoElem $ astPretty n) <* sepElem myFsep <* infoElem "=" <* sepElem myFsep <*> (annInfoElem $ astPretty p) astPretty (PFieldPun _ name) = resultPretty $ constrElem PFieldPun <*> annNoInfoElem (astPretty name) astPretty (PFieldWildcard _) = resultPretty $ constrElem PFieldWildcard <* noInfoElem ".." --------------------- Regular Patterns ------------------------- instance PrettyAst RPat where astPretty (RPOp _ r op) = resultPretty $ constrElem RPOp <*> (annInfoElem $ astPretty r) <*> (annInfoElem $ astPretty op) astPretty (RPEither _ r1 r2) = resultPretty.(nestMode onsideIndent).parens $ constrElem RPEither -- myFsep <*> (annInfoElem $ astPretty r1) <* sepElem myFsep <* infoElem "|" <* sepElem myFsep <*> (annInfoElem $ astPretty r2) astPretty (RPSeq _ rs) = resultPretty.(nestMode onsideIndent).parens $ constrElem RPSeq -- myFsep <* infoElem "(/" <* sepElem myFsep <*> intersperse (sepElem myFsep) (annListElem annNoInfoElem rs) <* sepElem myFsep <* infoElem "/)" astPretty (RPGuard _ r gs) = resultPretty.(nestMode onsideIndent).parens $ constrElem RPGuard -- myFsep <* infoElem "(|" <* sepElem myFsep <*> (annInfoElem $ astPretty r) <* sepElem myFsep <*> intersperse (sepElem myFsep) (annListElem annNoInfoElem gs) <* sepElem myFsep <* infoElem "/)" -- special case that would otherwise be buggy astPretty (RPAs _ n (RPPat _ (PIrrPat _ p))) = let ip = annInfoElem.resultPretty $ constrElem PIrrPat <*> (annInfoElem $ astPretty p) rp = annInfoElem.resultPretty $ constrElem RPPat <*> ip in resultPretty.(nestMode onsideIndent) $ constrElem RPAs -- myFsep <*> (annInfoElem $ astPretty n) <* infoElem "@:" <* sepElem myFsep <* infoElem "~" <*> rp astPretty (RPAs _ n r) = resultPretty $ constrElem RPAs -- hcat <*> (annInfoElem $ astPretty n) <* infoElem "@" <*> (annInfoElem $ astPretty r) astPretty (RPPat _ p) = resultPretty $ constrElem RPPat <*> (annInfoElem $ astPretty p) astPretty (RPParen _ rp) = resultPretty.parens $ constrElem RPParen <*> (annInfoElem $ astPretty rp) -- -------------------------------------------------------------------------- instance PrettyAst RPatOp where astPretty (RPStar _) = resultPretty $ constrElem RPStar <* infoElem "*" astPretty (RPStarG _) = resultPretty $ constrElem RPStarG <* infoElem "*!" astPretty (RPPlus _) = resultPretty $ constrElem RPPlus <* infoElem "+" astPretty (RPPlusG _) = resultPretty $ constrElem RPPlusG <* infoElem "+!" astPretty (RPOpt _) = resultPretty $ constrElem RPOpt <* infoElem "?" astPretty (RPOptG _) = resultPretty $ constrElem RPOptG <* infoElem "?!" ------------------------- Case bodies ------------------------- instance PrettyAst Alt where astPretty (Alt _ e gAlts mBinds) = resultPretty $ constrElem Alt <*> (annNoInfoElem $ astPretty e) <* sepElem hsep <*> (annNoInfoElem $ astPretty gAlts) <*> ppWhere mBinds -- -------------------------------------------------------------------------- instance PrettyAst GuardedAlts where astPretty (UnGuardedAlt _ e) = resultPretty $ constrElem UnGuardedAlt <* infoElem "->" <* sepElem hsep <*> (annNoInfoElem $ astPretty e) astPretty (GuardedAlts _ altList) = resultPretty $ constrElem GuardedAlts <*> intersperse (sepElem myVcat) (annListElem annNoInfoElem altList) -- -------------------------------------------------------------------------- instance PrettyAst GuardedAlt where astPretty (GuardedAlt _ guards body) = resultPretty.(nestMode onsideIndent) $ constrElem GuardedAlt -- myFsep <* infoElem "|" <* sepElem myFsep <*> intersperse (infoElem "," <* sepElem myFsep) (annListElem annNoInfoElem guards) <* sepElem myFsep <* infoElem "->" <* sepElem myFsep <*> (annInfoElem $ astPretty body) ------------------------- Statements in monads, guards & list comprehensions ----- instance PrettyAst Stmt where astPretty (Generator _ e from) = resultPretty $ constrElem Generator <*> annNoInfoElem (astPretty e) <* sepElem hsep <* infoElem "<-" <* sepElem hsep <*> annNoInfoElem (astPretty from) -- ListComp1.hs - Qualifier has empty info points astPretty (Qualifier _ e) = resultPretty $ constrElem Qualifier <*> annNoInfoElem (astPretty e) astPretty (LetStmt _ (BDecls _ declList)) = resultPretty $ constrElem LetStmt <*> ppLetStmt (constrElem BDecls) declList astPretty (LetStmt _ (IPBinds _ bindList)) = resultPretty $ constrElem LetStmt <*> ppLetStmt (constrElem IPBinds) bindList astPretty (RecStmt _ stmtList) = resultPretty $ constrElem RecStmt <* infoElem "rec" <*> ppBody letIndent (annListElem annNoInfoElem stmtList) ppLetStmt f ls = f <* infoElem "let" <*> ppBody letIndent (annListElem annInfoElem ls) -- -------------------------------------------------------------------------- instance PrettyAst QualStmt where astPretty (QualStmt _ s) = resultPretty $ constrElem QualStmt <*> annNoInfoElem (astPretty s) astPretty (ThenTrans _ f) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem ThenTrans <* infoElem "then" <* sepElem myFsep <*> annNoInfoElem (astPretty f) astPretty (ThenBy _ f e) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem ThenBy <* infoElem "then" <* sepElem myFsep <*> annNoInfoElem (astPretty f) <* sepElem myFsep <* infoElem "by" <* sepElem myFsep <*> annNoInfoElem (astPretty e) astPretty (GroupBy _ e) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem GroupBy <* infoElem "then" <* sepElem myFsep <* infoElem "group" <* sepElem myFsep <* infoElem "by" <* sepElem myFsep <*> annNoInfoElem (astPretty e) astPretty (GroupUsing _ f) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem GroupUsing <* infoElem "then" <* sepElem myFsep <* infoElem "group" <* sepElem myFsep <* infoElem "using" <* sepElem myFsep <*> annNoInfoElem (astPretty f) astPretty (GroupByUsing _ e f) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem GroupByUsing <* infoElem "then" <* sepElem myFsep <* infoElem "group" <* sepElem myFsep <* infoElem "by" <* sepElem myFsep <*> annNoInfoElem (astPretty e) <* sepElem myFsep <* infoElem "using" <* sepElem myFsep <*> annNoInfoElem (astPretty f) ------------------------- Record updates instance PrettyAst FieldUpdate where astPretty (FieldUpdate _ name e) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem FieldUpdate <*> annNoInfoElem (astPretty name) <* sepElem myFsep <* infoElem "=" <* sepElem myFsep <*> annNoInfoElem (astPretty e) astPretty (FieldPun _ name) = resultPretty $ constrElem FieldPun <*> (annInfoElem $ astPretty name) astPretty (FieldWildcard _) = resultPretty $ constrElem FieldWildcard <* infoElem ".." ------------------------- Names ------------------------- instance PrettyAst QOp where astPretty (QVarOp _ n) = resultPretty $ constrElem QVarOp <*> pointsInfoElem (ppQNameInfix n) astPretty (QConOp _ n) = resultPretty $ constrElem QConOp <*> pointsInfoElem (ppQNameInfix n) -- -------------------------------------------------------------------------- instance PrettyAst SpecialCon where astPretty (UnitCon _) = resultPretty $ constrElem UnitCon <* infoElem "(" <* infoElem ")" astPretty (ListCon _) = resultPretty $ constrElem ListCon <* infoElem "[" <* infoElem "]" astPretty (FunCon _) = resultPretty $ constrElem FunCon <* infoElem "->" astPretty (TupleCon _ b n) = let hash = if b == Unboxed then "#" else "" point = "(" ++ hash ++ replicate (n-1) ',' ++ hash ++ ")" in resultPretty $ constrElem TupleCon <* infoElem point <*> pure b <*> pure n astPretty (Cons _) = resultPretty $ constrElem Cons <* noInfoElem ":" astPretty (UnboxedSingleCon _) = resultPretty $ constrElem UnboxedSingleCon <* infoElem "(# #)" -- -------------------------------------------------------------------------- instance PrettyAst QName where astPretty (Qual _ (ModuleName _ mn) (Symbol _ s)) = do op <- format "(" ss <- getPos mn' <- format mn p <- format "." s' <- format s es <- getPos cp <- format ")" let si = SrcSpanInfo (mergeSrcSpan op cp) [op, (mkSrcSpan ss es), cp] return $ Qual si (ModuleName si mn) (Symbol si s) astPretty (Qual _ mn n) = resultPretty $ constrElem Qual <*> annNoInfoElem (astPretty mn) <* infoElem "." <*> pointsInfoElem (astPretty n) astPretty (UnQual _ n) = resultPretty $ constrElem UnQual <*> pointsInfoElem (astPretty n) astPretty (Special _ sc) = resultPretty $ constrElem Special <*> pointsInfoElem (astPretty sc) -- -------------------------------------------------------------------------- -- QName utils ppQNameInfix :: QName a -> DocM (QName SrcSpanInfo) ppQNameInfix (Qual _ mn n) = resultPretty $ constrElem Qual <*> annNoInfoElem (astPretty mn) <* infoElem "." <*> pointsInfoElem (astPretty n) ppQNameInfix (UnQual _ n) = resultPretty $ constrElem UnQual <*> pointsInfoElem (ppNameInfix n) ppQNameInfix (Special _ sc) = resultPretty $ constrElem Special <*> (pointsInfoElem $ astPretty sc) -- -------------------------------------------------------------------------- instance PrettyAst Op where astPretty (VarOp _ n) = resultPretty $ constrElem VarOp <*> pointsInfoElem (ppNameInfix n) astPretty (ConOp _ n) = resultPretty $ constrElem ConOp <*> pointsInfoElem (ppNameInfix n) -- -------------------------------------------------------------------------- ppNameInfix :: Name a -> DocM (Name SrcSpanInfo) ppNameInfix (Symbol _ s) = resultPretty $ constrElem Symbol <*> noInfoElem s ppNameInfix (Ident _ s) = resultPretty $ constrElem Ident <* infoElem "'" <*> infoElem s <* infoElem "'" instance PrettyAst Name where astPretty (Ident _ s) = resultPretty $ constrElem Ident <*> noInfoElem s astPretty (Symbol _ s) = resultPretty $ constrElem Symbol <* infoElem "(" <*> infoElem s <* infoElem ")" -- -------------------------------------------------------------------------- isSymbolName :: Name l -> Bool isSymbolName (Symbol _ _) = True isSymbolName _ = False getName :: QName l -> Name l getName (UnQual _ s) = s getName (Qual _ _ s) = s getName (Special _ (Cons _)) = Symbol annStub ":" getName (Special _ (FunCon _)) = Symbol annStub "->" getName (Special _ s) = Ident annStub (specialName s) specialName :: SpecialCon l -> String specialName (UnitCon _) = "()" specialName (ListCon _) = "[]" specialName (FunCon _) = "->" specialName (TupleCon _ b n) = "(" ++ hash ++ replicate (n-1) ',' ++ hash ++ ")" where hash = if b == Unboxed then "#" else "" specialName (Cons _) = ":" specialName (UnboxedSingleCon _) = "(# #)" -- -------------------------------------------------------------------------- instance PrettyAst IPName where astPretty (IPDup _ s) = resultPretty $ constrElem IPDup <* infoElem "?" <*> infoElem s astPretty (IPLin _ s) = resultPretty $ constrElem IPLin <* infoElem "%" <*> infoElem s -- -------------------------------------------------------------------------- instance PrettyAst IPBind where astPretty (IPBind _ ipname exp) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem IPBind <*> (annInfoElem $ astPretty ipname) <* sepElem myFsep <* infoElem "=" <* sepElem myFsep <*> (annInfoElem $ astPretty exp) -- -------------------------------------------------------------------------- instance PrettyAst CName where astPretty (VarName _ name) = resultPretty $ constrElem VarName <*> (annNoInfoElem $ astPretty name) astPretty (ConName _ name) = resultPretty $ constrElem ConName <*> (annNoInfoElem $ astPretty name) -- -------------------------------------------------------------------------- instance PrettyAst Context where astPretty (CxEmpty _) = resultPretty.(nestMode onsideIndent) $ constrElem CxEmpty <* infoElem "(" <* infoElem ")" <* sepElem fsep <* infoElem "=>" astPretty (CxSingle _ asst) = resultPretty.(nestMode onsideIndent) $ constrElem CxSingle <*> annNoInfoElem (astPretty asst) <* sepElem fsep <* infoElem "=>" astPretty (CxTuple _ assts) = resultPretty.(nestMode onsideIndent) $ constrElem CxTuple <*> parenList (annListElem annNoInfoElem assts) -- myFsep and parenList -> myFsep and myFsepSimple ??? <* sepElem myFsep <* infoElem "=>" astPretty (CxParen _ ctxt) = resultPretty $ constrElem CxParen <* infoElem "(" <*> annNoInfoElem (parenContext ctxt) <* infoElem ")" <* sepElem myFsep <* infoElem "=>" where parenContext (CxEmpty _) = resultPretty.(nestMode onsideIndent) $ constrElem CxEmpty parenContext (CxSingle _ asst) = resultPretty.(nestMode onsideIndent) $ constrElem CxSingle <*> annNoInfoElem (astPretty asst) parenContext (CxTuple _ assts) = resultPretty.(nestMode onsideIndent) $ constrElem CxTuple <*> intersperse parenListSep (annListElem annNoInfoElem assts) -- -------------------------------------------------------------------------- -- hacked for multi-parameter type classes instance PrettyAst Asst where astPretty (ClassA _ a ts) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem ClassA <*> (annNoInfoElem $ astPretty a) <* sepElem myFsep <*> intersperse (sepElem myFsep) (map (annNoInfoElem.ppAType) ts) astPretty (InfixA _ a op b) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem InfixA <*> (annNoInfoElem $ astPretty a) <* sepElem myFsep <*> annNoInfoElem (ppQNameInfix op) <* sepElem myFsep <*> (annNoInfoElem $ astPretty b) astPretty (IParam _ i t) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem IParam <*> (annInfoElem $ astPretty i) <* sepElem myFsep <* infoElem "::" <*> (annInfoElem $ astPretty t) astPretty (EqualP _ t1 t2) = -- myFsep resultPretty.(nestMode onsideIndent) $ constrElem EqualP <*> (annInfoElem $ astPretty t1) <* sepElem myFsep <* infoElem "~" <*> (annInfoElem $ astPretty t2) ------------------------- pp utils ------------------------- format :: String -> DocM SrcSpan format s = do SrcLoc f l c <- getPos let newColumn = c + length s putPos $ SrcLoc f l newColumn return $ SrcSpan f l c l newColumn getPos :: MonadState DocState m => m SrcLoc getPos = gets pos putPos :: MonadState DocState m => SrcLoc -> m SrcLoc putPos l = do DocState _ n t <- get put $! DocState l n t return l line :: MonadState DocState m => m () line = do DocState (SrcLoc f l c) n _ <- get putPos $! SrcLoc f (l + 1) (n + 1) return () isEmptyLine :: DocM Bool isEmptyLine = do DocState (SrcLoc f l c) n _ <- get return $ c <= n + 1 traceAst :: MonadState DocState m => String -> m () traceAst s = do DocState l n t <- get let msg = "l = " ++ show (srcLine l) ++ " c = " ++ show (srcColumn l) ++ " n = " ++ show n ++ " : " ++ s put $! DocState l n (t ++ [msg]) return () space :: MonadState DocState m => Int -> m () space x = do SrcLoc f l c <- getPos putPos $! SrcLoc f l $! c + x return () -- -------------------------------------------------------------------------- -- AstElem definition data ImplicitSep = ShiftedSep | CloseSep deriving (Show, Eq) data AstElemInfo = AstElemInfo { spanInfo :: Maybe SrcSpanInfo, implicitLs :: [ImplicitSep] } deriving Show traceImplicit :: String -> Maybe SrcSpanInfo -> Int -> Int traceImplicit s a x = x -- if x == 0 then x else traceShow ("~~~", s, a, x) x instance Monoid AstElemInfo where mempty = AstElemInfo Nothing [] mappend (AstElemInfo Nothing aes) (AstElemInfo Nothing bes) = AstElemInfo Nothing (aes ++ bes) mappend (AstElemInfo (Just a) aes) (AstElemInfo Nothing bes) = AstElemInfo (Just a) (aes ++ bes) mappend (AstElemInfo Nothing aes) (AstElemInfo (Just b) bes) = AstElemInfo (Just $ addImplicitPoint aes b) bes mappend (AstElemInfo (Just a) aes) (AstElemInfo (Just b) bes) = AstElemInfo (Just $ mergeSpan a (addImplicitPoint aes b)) bes where mergeSpan a b = SrcSpanInfo (mergeSrcSpan (srcInfoSpan a) (srcInfoSpan b)) (srcInfoPoints a ++ srcInfoPoints b) addImplicitPoint ips (SrcSpanInfo s ps) = SrcSpanInfo s $ (map (ipoint s) ips) ++ ps where ipoint (SrcSpan f sl sc _ _) ShiftedSep = SrcSpan f sl sc sl sc ipoint (SrcSpan f sl sc _ _) CloseSep = SrcSpan f sl sc sl 0 type AstElem = WriterT AstElemInfo DocM -- -------------------------------------------------------------------------- -- AstElem utils spanFromString :: String -> DocM SrcSpan spanFromString s = do sp <- getPos _ <- format s ep <- getPos return $ mkSrcSpan sp ep stringElem ::(SrcSpanInfo -> [SrcSpan]) -> String -> AstElem String stringElem fPoints s = do span <- lift $ spanFromString s tell $ AstElemInfo (Just $ SrcSpanInfo span (fPoints $ SrcSpanInfo span [span])) [] let lstrip = dropWhile isSpace rstrip = reverse . lstrip . reverse strip = lstrip . rstrip return $ strip s noPoints, mainPoint, allPoints :: SrcSpanInfo -> [SrcSpan] noPoints _ = [] mainPoint (SrcSpanInfo s _) = [s] allPoints (SrcSpanInfo _ ps) = ps annElem :: (Annotated ast) => (SrcSpanInfo -> [SrcSpan]) -> (SrcSpanInfo -> SrcSpanInfo) -> DocM (ast SrcSpanInfo) -> AstElem (ast SrcSpanInfo) annElem pointFn spanFn el = do e <- lift el let span = ann e tell $ AstElemInfo (Just $ SrcSpanInfo (srcInfoSpan span) (pointFn span)) [] return $ amap spanFn e infoElem :: String -> AstElem String infoElem s = stringElem mainPoint s quoteStringElem :: String -> AstElem String quoteStringElem s = stringElem mainPoint (" " ++ s ++ " ") -- " " ++ s ++ " " we jast add two symbols to SrcSpanInfo for quotes noInfoElem :: String -> AstElem String noInfoElem s = stringElem noPoints s implicitElem :: String -> AstElem String implicitElem s = stringElem mainPoint "" >> return s sepElem :: DocM() -> AstElem () sepElem s = lift s sepElemIf :: Bool -> DocM() -> AstElem() sepElemIf p s = sepElem $ if p then s else pure () annNoInfoElem, annInfoElem, pointsInfoElem :: (Annotated ast) => DocM (ast SrcSpanInfo) -> AstElem (ast SrcSpanInfo) annNoInfoElem a = annElem noPoints id a annInfoElem a = annElem mainPoint id a pointsInfoElem a = annElem allPoints id a takeAllPointsInfoElem a = annElem allPoints (noInfoSpan . srcInfoSpan) a annStub = undefined unimplemented = undefined constrElem :: (a -> b) -> AstElem b constrElem f = lift.return $ f annStub annListElem :: PrettyAst ast => (DocM (ast SrcSpanInfo) -> AstElem (ast SrcSpanInfo)) -> [ast a] -> [AstElem (ast SrcSpanInfo)] annListElem f xs = map (f.astPretty) xs intersperse :: Applicative f => f a1 -> [f a] -> f [a] intersperse _ [] = pure [] intersperse sep (e:es) = sequenceA $ e : (map (sep *>) es) nest :: Int -> AstElem a -> AstElem a nest n a = (sepElem $ impl n) *> a <* (sepElem $ impl (-n)) where impl x = do DocState l n t <- get put $! DocState l (n + x) t return () nestMode f a = do PrettyMode m _ <- ask nest (f m) a resultPretty :: Annotated ast => AstElem (ast SrcSpanInfo) -> DocM (ast SrcSpanInfo) resultPretty a = do (a', AstElemInfo (Just (SrcSpanInfo span ps)) ies) <- runWriterT a let ipoint (SrcSpan f _ _ el ec) ShiftedSep = SrcSpan f el ec el ec ipoint (SrcSpan f _ _ el ec) CloseSep = SrcSpan f el 1 el 0 return $ amap (const $ SrcSpanInfo span (ps ++ map (ipoint span) ies)) a' implicitSep :: String -> AstElem () implicitSep _ = do tell $ AstElemInfo Nothing [ShiftedSep] return () implicitCloseSep :: String -> AstElem () implicitCloseSep _ = do isEmpty <- lift isEmptyLine sepElemIf (not isEmpty) baseLine *> implicitItem where implicitItem :: AstElem () implicitItem = do DocState (SrcLoc f l c) n _ <- get let span = SrcSpan f l c l 0 tell $ AstElemInfo (Just $ SrcSpanInfo span []) [CloseSep] return () baseLine :: DocM () baseLine = do DocState (SrcLoc f l c) n _ <- get putPos $! SrcLoc f (l + 1) 1 return () -- -------------------------------------------------------------------------- -- separators vcat :: DocM () vcat = do DocState (SrcLoc f l c) n _ <- get let s = if n < c then line else space $ n - c + 1 _ <- s return () hsep :: DocM () hsep = space 1 hcat :: DocM () hcat = pure () -- fsep prototype fsep :: DocM () fsep = do PrettyMode mode style <- ask c <- getPos if layout mode == PPOffsideRule || layout mode == PPSemiColon then if srcColumn c >= lineLength style then line else hsep else hsep {- a $$$ b = layoutChoice (a vcat) (a <+>) b mySep = layoutChoice mySep' hsep where -- ensure paragraph fills with indentation. mySep' [x] = x mySep' (x:xs) = x <+> fsep xs mySep' [] = error "Internal error: mySep" -} myVcat = layoutChoice vcat hsep myFsepSimple = layoutChoice fsep hsep -- same, except that continuation lines are indented, -- which is necessary to avoid triggering the offside rule. -- myFsep prototype myFsep = myFsepSimple -- -------------------------------------------------------------------------- -- paren related functions parenListSep :: AstElem String parenListSep = infoElem "," <* sepElem myFsepSimple parenList :: [AstElem a] -> AstElem [a] parenList xs = parens $ intersperse parenListSep xs hashParenList :: [AstElem a] -> AstElem [a] hashParenList xs = infoElem "(#" *> intersperse parenListSep xs <* infoElem "#)" braceList :: [AstElem a] -> AstElem [a] braceList xs = braces $ intersperse parenListSep xs bracketList :: [AstElem a] -> AstElem [a] bracketList xs = brackets $ intersperse (sepElem myFsepSimple) xs enclose ob cb x = ob *> x <* cb encloseIf p ob cb x = if p then ob *> x <* cb else x parens :: AstElem a -> AstElem a parens d = noInfoElem "(" *> d <* noInfoElem ")" braces :: AstElem a -> AstElem a braces d = noInfoElem "{" *> d <* noInfoElem "}" brackets :: AstElem a -> AstElem a brackets d = noInfoElem "[" *> d <* noInfoElem "]" parensIf :: Bool -> AstElem a -> AstElem a parensIf p d = if p then parens d else d -- -------------------------------------------------------------------------- -- general utils layoutChoice a b = do PrettyMode mode _ <- ask if layout mode == PPOffsideRule || layout mode == PPSemiColon then a else b layoutSep :: String -> AstElem String layoutSep s = do (PrettyMode mode _) <- ask case layout mode of PPOffsideRule -> implicitElem s PPSemiColon -> infoElem s _ -> implicitElem s blankline :: Annotated ast => DocM (ast SrcSpanInfo) -> DocM (ast SrcSpanInfo) blankline x = newLine >> x where newLine = do PrettyMode mode _ <- ask if spacing mode && layout mode /= PPNoLayout then line else return () ppBody :: (PR.PPHsMode -> Int) -> [AstElem a] -> AstElem [a] ppBody _ [] = sepElem vcat *> implicitElem "{" --implicitOpenSep "{ - just begin of body" *> pure [] <* implicitElem ";" <* implicitCloseSep "}" ppBody f dl = do (PrettyMode mode _) <- ask nest (f mode) $ case layout mode of PPOffsideRule -> sepElem vcat *> implicitSep "{ - just begin of body" *> intersperse (sepElem vcat <* implicitElem ";") dl <* implicitCloseSep "}" PPSemiColon -> sepElem vcat *> infoElem "{" *> sepElem hsep *> nestMode onsideIndent (intersperse (infoElem ";" <* sepElem vcat) dl) <* infoElem "}" _ -> sepElem hsep *> infoElem "{" *> sepElem hsep *> intersperse (infoElem ";" <* sepElem hsep) dl <* infoElem "}" -- -------------------------------------------------------------------------- -- simplify utils sDeclHead dh = case dh of DHead _ n tvs -> (n, tvs) (DHInfix _ tva n tvb) -> (n, [tva, tvb]) (DHParen _ dh) -> sDeclHead dh sInstHead ih = case ih of IHead _ qn ts -> (qn, ts) IHInfix _ ta qn tb -> (qn, [ta,tb]) IHParen _ ih -> sInstHead ih
Pnom/haskell-ast-pretty
Language/Haskell/Exts/PrettyAst.hs
mit
89,513
103
22
21,568
28,683
13,825
14,858
1,879
3
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Chart.Bar as Bar import qualified Chart.BarW as BarW import qualified Chart.Combo as Combo import qualified Chart.Heatmap as Heatmap import qualified Chart.Line as Line import Chart.Render import qualified Chart.Scatter as Scatter import qualified Chart.Text as ChartText import Chart.Types import Control.Applicative import Control.Lens import Control.Monad import Data.Default import Data.Text (Text) import Data.XY import Happstack.Server import Lucid import Lucid.Server import MVC import Pipes import Web.Play main :: IO () main = serve testCharts testCharts :: ServerPart Response testCharts = msum [ dir "text" textChart , dir "line" lineChart , dir "circle" circleChart , dir "scroll" scrollChart , dir "scatter" scatterChart , dir "heatmap" heatmapChart , dir "bar" barChart , dir "hist" histChart , dir "histadapt" histAdaptChart , dir "combo" comboChart , homePage ] template :: Text -> Html () -> Response template title' body' = toResponse (html_ (head_ (title_ (toHtml title')) <> body_ (body' <> p_ (with a_ [href_ "/"] "home"))) :: Html ()) homePage :: ServerPart Response homePage = ok $ template "home page" $ mconcat [ h1_ "Chart tests" , p_ (with a_ [href_ "/text"] "text") , p_ (with a_ [href_ "/line" ] "line chart") , p_ (with a_ [href_ "/scroll" ] "scroll chart") , p_ (with a_ [href_ "/circle" ] "circle") , p_ (with a_ [href_ "/scatter" ] "scatter chart") , p_ (with a_ [href_ "/heatmap" ] "heatmap chart") , p_ (with a_ [href_ "/bar"] "bar chart") , p_ (with a_ [href_ "/hist"] "hist chart") , p_ (with a_ [href_ "/histadapt"] "histadapt chart") , p_ (with a_ [href_ "/combo" ] "combo test") ] textChart :: ServerPartT IO Response textChart = responsePlay ChartText.testProducer (Chart.Render.render (chartCss "chart") ChartText.testCharts) def lineChart :: ServerPart Response lineChart = responsePlay Line.testProducer (Chart.Render.render (chartCss "chart") [defaultChart [Line.testElement]]) def circleChart :: ServerPart Response circleChart = responsePlay (Pipes.each $ zipWith (\a b -> [a,b]) ((\x -> XY (cos x) (sin x)) <$> (/20) <$> [0..]) ((\x -> XY (sin (x + pi/2)) (sin (3*x))) <$> (/20) <$> [0..])) (Chart.Render.render (chartCss "chart") Line.testChart2) def scrollChart :: ServerPart Response scrollChart = responsePlay Line.testProducer (Chart.Render.render (chartCss "chart") [defaultChart [Line.testElementScroll]]) def scatterChart :: ServerPart Response scatterChart = responsePlay Scatter.testProducer (Chart.Render.render (chartCss "chart") [defaultChart [Scatter.testElement]]) def heatmapChart :: ServerPart Response heatmapChart = responsePlay (Heatmap.heatmapProducer def) (Chart.Render.render (chartCss "chart") [ ucChart . cDims .~ [ Dim "x" Nothing Nothing , Dim "y" Nothing Nothing , Dim "z" Nothing Nothing ] $ defaultChart [Heatmap.testElement]]) def barChart :: ServerPart Response barChart = responsePlay Bar.testProducer (Chart.Render.render (chartCss "chart") [defaultChart [eCreate .~ Bar.barCreate (Bar.bcSeed .~ [1, 2, 3, 4] $ Bar.bcTickStyle .~ Just (TickStyle Ends (Just ["zero","one","two"])) $ def) $ Bar.testElement]]) def histChart :: ServerPart Response histChart = responsePlay BarW.testProducer (Chart.Render.render (chartCss "chart") [defaultChart [BarW.testElement]]) def histAdaptChart :: ServerPart Response histAdaptChart = responsePlay BarW.histAdaptProducer (Chart.Render.render (chartCss "chart") [BarW.testChartAdapt]) def comboChart :: ServerPart Response comboChart = responsePlay (Combo.comboProducer def) Combo.comboPage def
tonyday567/hdcharts
test/example.hs
mit
4,142
0
22
1,029
1,310
696
614
-1
-1
module HsSearch.Paths_hssearch where import System.FilePath ((</>)) import HsSearch.Config (getDataPath) -- NOTE: this path is only used for testing/development, after cabal install -- the path will be overridden by the data-files setting in the cabal file getDataFileName :: FilePath -> IO FilePath getDataFileName f = do dataPath <- getDataPath return $ dataPath </> f
clarkcb/xsearch
haskell/hssearch/src/HsSearch/Paths_hssearch.hs
mit
377
0
8
59
68
38
30
7
1
module Interface.Top ( topMenue ) where import Interface.General import Interface.ArGeo import Interface.Special import Control.Monad import System.IO topMenue :: IO () topMenue = do putStrLn "<1> Operationen mit arithmetischen und geometrischen Zahlenfolgen" putStrLn "<2> Operationen mit speziellen Zahlenfolgen" putStrLn "<3> Beenden" putStr "Auswahl: " hFlush stdout option <- getLine putChar '\n' state <- handleOption option when (state == Redo) topMenue handleOption :: String -> IO MenueState handleOption ('1':_) = do arGeoMenue return Redo handleOption ('2':_) = do specialMenue return Redo handleOption _ = return Done
DevWurm/numeric-sequences-haskell
src/Interface/Top.hs
mit
872
0
9
326
190
89
101
26
1