code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
------------------------------------------------------------------------ -- | -- Module : ALife.Creatur.Wain.UIVector.Cluster.GeneratePopulation -- Copyright : (c) Amy de Buitléir 2012-2016 -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- ??? -- ------------------------------------------------------------------------ {-# LANGUAGE TypeFamilies #-} import ALife.Creatur (agentId) import ALife.Creatur.Wain.UIVector.Cluster.Experiment (PatternWain, randomPatternWain, printStats) import ALife.Creatur.Wain (adjustEnergy) import ALife.Creatur.Wain.Pretty (pretty) import ALife.Creatur.Wain.PersistentStatistics (clearStats) import ALife.Creatur.Wain.Statistics (Statistic, stats, summarise) import ALife.Creatur.Wain.UIVector.Cluster.Universe (Universe(..), writeToLog, store, loadUniverse, uClassifierSizeRange, uInitialPopulationSize, uStatsFile) import Control.Lens import Control.Monad.IO.Class (liftIO) import Control.Monad.Random (evalRandIO) import Control.Monad.Random.Class (getRandomR) import Control.Monad.State.Lazy (StateT, evalStateT, get) introduceRandomAgent :: String -> StateT (Universe PatternWain) IO [Statistic] introduceRandomAgent name = do u <- get classifierSize <- liftIO . evalRandIO . getRandomR . view uClassifierSizeRange $ u agent <- liftIO . evalRandIO $ randomPatternWain name u classifierSize -- Make the first generation a little hungry so they start learning -- immediately. -- TODO: Make the amount configurable. let (agent', _) = adjustEnergy 0.8 agent writeToLog $ "GeneratePopulation: Created " ++ agentId agent' writeToLog $ "GeneratePopulation: Stats " ++ pretty (stats agent') store agent' return (stats agent') introduceRandomAgents :: [String] -> StateT (Universe PatternWain) IO () introduceRandomAgents ns = do xs <- mapM introduceRandomAgent ns let yss = summarise xs printStats yss statsFile <- use uStatsFile clearStats statsFile main :: IO () main = do u <- loadUniverse let ns = map (("Founder" ++) . show) [1..(view uInitialPopulationSize u)] print ns evalStateT (introduceRandomAgents ns) u
mhwombat/exp-uivector-cluster-wains
src/ALife/Creatur/Wain/UIVector/Cluster/GeneratePopulation.hs
bsd-3-clause
2,203
0
13
322
528
286
242
44
1
{-# LANGUAGE QuasiQuotes #-} module Cauterize.GHC7.Generate.GenStack ( generateOutput ) where import Cauterize.GHC7.Options import Cauterize.GHC7.Generate.Utils import qualified Cauterize.Specification as Spec import System.FilePath.Posix import Data.String.Interpolate.Util import Data.String.Interpolate.IsString generateOutput :: Spec.Specification -> CautGHC7Opts -> IO () generateOutput _ opts = do stackDir <- createPath [out] let stackPath = stackDir `combine` "stack.yaml" let stackData = stackYamlTempl writeFile stackPath stackData where out = outputDirectory opts stackYamlTempl :: String stackYamlTempl = unindent [i| flags: {} packages: - '.' - location: git: https://github.com/cauterize-tools/cauterize.git commit: cff794399744a4038c0f2b2dfbc4c43593d2bcbd - location: git: https://github.com/aisamanra/s-cargot.git commit: 1628a7c2913fc5e72ab6ea9a813762bf86d47d49 - location: git: https://github.com/cauterize-tools/crucible.git commit: 7f8147e0fbfe210df9e6c83f4c0d48c3de4ed9f7 - location: git: https://github.com/cauterize-tools/caut-ghc7-ref.git commit: 36f28786cd97cf9e810649d75270b2ac0cb8d1a5 extra-deps: - cereal-plus-0.4.0 resolver: lts-2.21|]
cauterize-tools/caut-ghc7-ref
src/Cauterize/GHC7/Generate/GenStack.hs
bsd-3-clause
1,274
0
10
210
157
91
66
18
1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} module Singletons.BoxUnBox where import Data.Singletons.TH import Data.Singletons.SuppressUnusedWarnings $(singletons [d| data Box a = FBox a unBox :: Box a -> a unBox (FBox a) = a |])
int-index/singletons
tests/compile-and-dump/Singletons/BoxUnBox.hs
bsd-3-clause
240
0
7
41
33
21
12
-1
-1
-- © 2001, 2002 Peter Thiemann module Main where import WASH.CGI.CGI hiding (head, map, span, div) main = run $ standardQuery "Upload File" $ do text "Enter file to upload " fileH <- checkedFileInputField refuseUnnamed empty submit fileH display (fieldVALUE "UPLOAD") refuseUnnamed mf = do FileReference {fileReferenceExternalName=frn} <- mf if null frn then fail "" else mf display :: InputField FileReference VALID -> CGI () display fileH = let fileRef = value fileH in standardQuery "Upload Successful" $ do p (text (show fileRef)) p (do text "Check file contents " submit0 (tell fileRef) (fieldVALUE "Show contents"))
nh2/WashNGo
Examples/old/Upload.hs
bsd-3-clause
667
0
15
141
217
105
112
18
2
module IptAdmin.Config where import Control.Monad.Error import Data.ConfigFile import IptAdmin.Types import System.FilePath.Posix cONFpATHd :: String cONFpATHd = "/etc/iptadmin" cONFIGURATIONf :: String cONFIGURATIONf = "iptadmin.conf" getConfig :: ErrorT String IO IptAdminConfig getConfig = do configE <- liftIO $ runErrorT $ do cp <- join $ liftIO $ readfile emptyCP (cONFpATHd </> cONFIGURATIONf) saveCommand <- get cp "DEFAULT" "save command" port <- get cp "DEFAULT" "port" pamName <- get cp "DEFAULT" "pam name" sslEnabled <- get cp "DEFAULT" "ssl" if sslEnabled then do createPair <- get cp "SSL" "create pair if does not exist" crtPath <- get cp "SSL" "crt path" keyPath <- get cp "SSL" "key path" return $ IptAdminConfig saveCommand port pamName $ Just $ SSLConfig createPair crtPath keyPath else return $ IptAdminConfig saveCommand port pamName Nothing case configE of Left (_, err) -> throwError ("Error on reading " ++ cONFpATHd </> cONFIGURATIONf ++ "\n" ++ err) Right config -> return config
etarasov/iptadmin
src/IptAdmin/Config.hs
bsd-3-clause
1,482
0
17
626
314
153
161
34
3
{-# LANGUAGE CPP, FlexibleInstances, OverloadedStrings, Rank2Types #-} #ifdef GENERICS {-# LANGUAGE DefaultSignatures, TypeOperators, KindSignatures, FlexibleContexts, MultiParamTypeClasses, UndecidableInstances, ScopedTypeVariables #-} #endif module Data.Csv.Conversion ( -- * Type conversion Only(..) , FromRecord(..) , FromNamedRecord(..) , ToNamedRecord(..) , FromField(..) , ToRecord(..) , ToField(..) -- * Parser , Result(..) , Parser , parse -- * Accessors , (.!) , (.:) , (.=) , record , namedRecord -- * Util , lengthMismatch ) where import Control.Applicative import Control.Monad import Data.Attoparsec.Char8 (double, number, parseOnly) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy as L import qualified Data.HashMap.Lazy as HM import Data.Int import qualified Data.Map as M import Data.Monoid import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as LT import qualified Data.Text.Lazy.Encoding as LT import Data.Traversable import Data.Vector (Vector, (!)) import qualified Data.Vector as V import Data.Word import GHC.Float (double2Float) import Prelude hiding (takeWhile) import Data.Csv.Conversion.Internal import Data.Csv.Types #ifdef GENERICS import GHC.Generics import qualified Data.IntMap as IM #endif ------------------------------------------------------------------------ -- Type conversion ------------------------------------------------------------------------ -- Index-based conversion -- | A type that can be converted from a single CSV record, with the -- possibility of failure. -- -- When writing an instance, use 'empty', 'mzero', or 'fail' to make a -- conversion fail, e.g. if a 'Record' has the wrong number of -- columns. -- -- Given this example data: -- -- > John,56 -- > Jane,55 -- -- here's an example type and instance: -- -- @data Person = Person { name :: Text, age :: Int } -- -- instance FromRecord Person where -- parseRecord v -- | 'V.length' v == 2 = Person '<$>' -- v '.!' 0 '<*>' -- v '.!' 1 -- | otherwise = mzero -- @ class FromRecord a where parseRecord :: Record -> Parser a #ifdef GENERICS default parseRecord :: (Generic a, GFromRecord (Rep a)) => Record -> Parser a parseRecord r = to <$> gparseRecord r #endif -- | Haskell lacks a single-element tuple type, so if you CSV data -- with just one column you can use the 'Only' type to represent a -- single-column result. newtype Only a = Only { fromOnly :: a } deriving (Eq, Ord, Read, Show) -- | A type that can be converted to a single CSV record. -- -- An example type and instance: -- -- @data Person = Person { name :: Text, age :: Int } -- -- instance ToRecord Person where -- toRecord (Person name age) = 'record' [ -- 'toField' name, 'toField' age] -- @ -- -- Outputs data on this form: -- -- > John,56 -- > Jane,55 class ToRecord a where toRecord :: a -> Record #ifdef GENERICS default toRecord :: (Generic a, GToRecord (Rep a) Field) => a -> Record toRecord = V.fromList . gtoRecord . from #endif instance FromField a => FromRecord (Only a) where parseRecord v | n == 1 = Only <$> parseField (V.unsafeIndex v 0) | otherwise = lengthMismatch 1 v where n = V.length v -- TODO: Check if we want all toRecord conversions to be stricter. instance ToField a => ToRecord (Only a) where toRecord = V.singleton . toField . fromOnly instance (FromField a, FromField b) => FromRecord (a, b) where parseRecord v | n == 2 = (,) <$> parseField (V.unsafeIndex v 0) <*> parseField (V.unsafeIndex v 1) | otherwise = lengthMismatch 2 v where n = V.length v instance (ToField a, ToField b) => ToRecord (a, b) where toRecord (a, b) = V.fromList [toField a, toField b] instance (FromField a, FromField b, FromField c) => FromRecord (a, b, c) where parseRecord v | n == 3 = (,,) <$> parseField (V.unsafeIndex v 0) <*> parseField (V.unsafeIndex v 1) <*> parseField (V.unsafeIndex v 2) | otherwise = lengthMismatch 3 v where n = V.length v instance (ToField a, ToField b, ToField c) => ToRecord (a, b, c) where toRecord (a, b, c) = V.fromList [toField a, toField b, toField c] instance (FromField a, FromField b, FromField c, FromField d) => FromRecord (a, b, c, d) where parseRecord v | n == 4 = (,,,) <$> parseField (V.unsafeIndex v 0) <*> parseField (V.unsafeIndex v 1) <*> parseField (V.unsafeIndex v 2) <*> parseField (V.unsafeIndex v 3) | otherwise = lengthMismatch 4 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d) => ToRecord (a, b, c, d) where toRecord (a, b, c, d) = V.fromList [ toField a, toField b, toField c, toField d] instance (FromField a, FromField b, FromField c, FromField d, FromField e) => FromRecord (a, b, c, d, e) where parseRecord v | n == 5 = (,,,,) <$> parseField (V.unsafeIndex v 0) <*> parseField (V.unsafeIndex v 1) <*> parseField (V.unsafeIndex v 2) <*> parseField (V.unsafeIndex v 3) <*> parseField (V.unsafeIndex v 4) | otherwise = lengthMismatch 5 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d, ToField e) => ToRecord (a, b, c, d, e) where toRecord (a, b, c, d, e) = V.fromList [ toField a, toField b, toField c, toField d, toField e] instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f) => FromRecord (a, b, c, d, e, f) where parseRecord v | n == 6 = (,,,,,) <$> parseField (V.unsafeIndex v 0) <*> parseField (V.unsafeIndex v 1) <*> parseField (V.unsafeIndex v 2) <*> parseField (V.unsafeIndex v 3) <*> parseField (V.unsafeIndex v 4) <*> parseField (V.unsafeIndex v 5) | otherwise = lengthMismatch 6 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f) => ToRecord (a, b, c, d, e, f) where toRecord (a, b, c, d, e, f) = V.fromList [ toField a, toField b, toField c, toField d, toField e, toField f] instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g) => FromRecord (a, b, c, d, e, f, g) where parseRecord v | n == 7 = (,,,,,,) <$> parseField (V.unsafeIndex v 0) <*> parseField (V.unsafeIndex v 1) <*> parseField (V.unsafeIndex v 2) <*> parseField (V.unsafeIndex v 3) <*> parseField (V.unsafeIndex v 4) <*> parseField (V.unsafeIndex v 5) <*> parseField (V.unsafeIndex v 6) | otherwise = lengthMismatch 7 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f, ToField g) => ToRecord (a, b, c, d, e, f, g) where toRecord (a, b, c, d, e, f, g) = V.fromList [ toField a, toField b, toField c, toField d, toField e, toField f, toField g] lengthMismatch :: Int -> Record -> Parser a lengthMismatch expected v = fail $ "cannot unpack array of length " ++ show n ++ " into a " ++ desired ++ ". Input record: " ++ show v where n = V.length v desired | expected == 1 = "Only" | expected == 2 = "pair" | otherwise = show expected ++ "-tuple" instance FromField a => FromRecord [a] where parseRecord = traverse parseField . V.toList instance ToField a => ToRecord [a] where toRecord = V.fromList . map toField instance FromField a => FromRecord (V.Vector a) where parseRecord = traverse parseField instance ToField a => ToRecord (Vector a) where toRecord = V.map toField ------------------------------------------------------------------------ -- Name-based conversion -- | A type that can be converted from a single CSV record, with the -- possibility of failure. -- -- When writing an instance, use 'empty', 'mzero', or 'fail' to make a -- conversion fail, e.g. if a 'Record' has the wrong number of -- columns. -- -- Given this example data: -- -- > name,age -- > John,56 -- > Jane,55 -- -- here's an example type and instance: -- -- @{-\# LANGUAGE OverloadedStrings \#-} -- -- data Person = Person { name :: Text, age :: Int } -- -- instance FromRecord Person where -- parseNamedRecord m = Person '<$>' -- m '.:' \"name\" '<*>' -- m '.:' \"age\" -- @ -- -- Note the use of the @OverloadedStrings@ language extension which -- enables 'B8.ByteString' values to be written as string literals. class FromNamedRecord a where parseNamedRecord :: NamedRecord -> Parser a #ifdef GENERICS default parseNamedRecord :: (Generic a, GFromNamedRecord (Rep a)) => NamedRecord -> Parser a parseNamedRecord r = to <$> gparseNamedRecord r #endif -- | A type that can be converted to a single CSV record. -- -- An example type and instance: -- -- @data Person = Person { name :: Text, age :: Int } -- -- instance ToRecord Person where -- toNamedRecord (Person name age) = 'namedRecord' [ -- \"name\" '.=' name, \"age\" '.=' age] -- @ class ToNamedRecord a where toNamedRecord :: a -> NamedRecord #ifdef GENERICS default toNamedRecord :: (Generic a, GToRecord (Rep a) (B.ByteString, B.ByteString)) => a -> NamedRecord toNamedRecord = namedRecord . gtoRecord . from #endif instance FromField a => FromNamedRecord (M.Map B.ByteString a) where parseNamedRecord m = M.fromList <$> (traverse parseSnd $ HM.toList m) where parseSnd (name, s) = (,) <$> pure name <*> parseField s instance ToField a => ToNamedRecord (M.Map B.ByteString a) where toNamedRecord = HM.fromList . map (\ (k, v) -> (k, toField v)) . M.toList instance FromField a => FromNamedRecord (HM.HashMap B.ByteString a) where parseNamedRecord m = traverse (\ s -> parseField s) m instance ToField a => ToNamedRecord (HM.HashMap B.ByteString a) where toNamedRecord = HM.map toField ------------------------------------------------------------------------ -- Individual field conversion -- | A type that can be converted from a single CSV field, with the -- possibility of failure. -- -- When writing an instance, use 'empty', 'mzero', or 'fail' to make a -- conversion fail, e.g. if a 'Field' can't be converted to the given -- type. -- -- Example type and instance: -- -- @{-\# LANGUAGE OverloadedStrings \#-} -- -- data Color = Red | Green | Blue -- -- instance FromField Color where -- parseField s -- | s == \"R\" = pure Red -- | s == \"G\" = pure Green -- | s == \"B\" = pure Blue -- | otherwise = mzero -- @ class FromField a where parseField :: Field -> Parser a -- | A type that can be converted to a single CSV field. -- -- Example type and instance: -- -- @{-\# LANGUAGE OverloadedStrings \#-} -- -- data Color = Red | Green | Blue -- -- instance ToField Color where -- toField Red = \"R\" -- toField Green = \"G\" -- toField Blue = \"B\" -- @ class ToField a where toField :: a -> Field instance FromField Char where parseField s | T.compareLength t 1 == EQ = pure (T.head t) | otherwise = typeError "Char" s Nothing where t = T.decodeUtf8 s {-# INLINE parseField #-} instance ToField Char where toField = toField . T.encodeUtf8 . T.singleton {-# INLINE toField #-} instance FromField Double where parseField = parseDouble {-# INLINE parseField #-} instance ToField Double where toField = realFloat {-# INLINE toField #-} instance FromField Float where parseField s = double2Float <$> parseDouble s {-# INLINE parseField #-} instance ToField Float where toField = realFloat {-# INLINE toField #-} parseDouble :: B.ByteString -> Parser Double parseDouble s = case parseOnly double s of Left err -> typeError "Double" s (Just err) Right n -> pure n {-# INLINE parseDouble #-} instance FromField Int where parseField = parseIntegral "Int" {-# INLINE parseField #-} instance ToField Int where toField = decimal {-# INLINE toField #-} instance FromField Integer where parseField = parseIntegral "Integer" {-# INLINE parseField #-} instance ToField Integer where toField = decimal {-# INLINE toField #-} instance FromField Int8 where parseField = parseIntegral "Int8" {-# INLINE parseField #-} instance ToField Int8 where toField = decimal {-# INLINE toField #-} instance FromField Int16 where parseField = parseIntegral "Int16" {-# INLINE parseField #-} instance ToField Int16 where toField = decimal {-# INLINE toField #-} instance FromField Int32 where parseField = parseIntegral "Int32" {-# INLINE parseField #-} instance ToField Int32 where toField = decimal {-# INLINE toField #-} instance FromField Int64 where parseField = parseIntegral "Int64" {-# INLINE parseField #-} instance ToField Int64 where toField = decimal {-# INLINE toField #-} instance FromField Word where parseField = parseIntegral "Word" {-# INLINE parseField #-} instance ToField Word where toField = decimal {-# INLINE toField #-} instance FromField Word8 where parseField = parseIntegral "Word8" {-# INLINE parseField #-} instance ToField Word8 where toField = decimal {-# INLINE toField #-} instance FromField Word16 where parseField = parseIntegral "Word16" {-# INLINE parseField #-} instance ToField Word16 where toField = decimal {-# INLINE toField #-} instance FromField Word32 where parseField = parseIntegral "Word32" {-# INLINE parseField #-} instance ToField Word32 where toField = decimal {-# INLINE toField #-} instance FromField Word64 where parseField = parseIntegral "Word64" {-# INLINE parseField #-} instance ToField Word64 where toField = decimal {-# INLINE toField #-} -- TODO: Optimize escape :: B.ByteString -> B.ByteString escape s | B.find (\ b -> b == dquote || b == comma || b == nl || b == cr || b == sp) s == Nothing = s | otherwise = B.concat ["\"", B.concatMap (\ b -> if b == dquote then "\"\"" else B.singleton b) s, "\""] where dquote = 34 comma = 44 nl = 10 cr = 13 sp = 32 instance FromField B.ByteString where parseField = pure {-# INLINE parseField #-} instance ToField B.ByteString where toField = escape {-# INLINE toField #-} instance FromField L.ByteString where parseField s = pure (L.fromChunks [s]) {-# INLINE parseField #-} instance ToField L.ByteString where toField = toField . B.concat . L.toChunks {-# INLINE toField #-} -- | Assumes UTF-8 encoding. instance FromField T.Text where parseField = pure . T.decodeUtf8 {-# INLINE parseField #-} -- | Uses UTF-8 encoding. instance ToField T.Text where toField = toField . T.encodeUtf8 {-# INLINE toField #-} -- | Assumes UTF-8 encoding. instance FromField LT.Text where parseField s = pure (LT.fromChunks [T.decodeUtf8 s]) {-# INLINE parseField #-} -- | Uses UTF-8 encoding. instance ToField LT.Text where toField = toField . B.concat . L.toChunks . LT.encodeUtf8 {-# INLINE toField #-} -- | Assumes UTF-8 encoding. instance FromField [Char] where parseField = fmap T.unpack . parseField {-# INLINE parseField #-} -- | Uses UTF-8 encoding. instance ToField [Char] where toField = toField . T.pack {-# INLINE toField #-} parseIntegral :: Integral a => String -> B.ByteString -> Parser a parseIntegral typ s = case parseOnly number s of Left err -> typeError typ s (Just err) Right n -> pure (floor n) {-# INLINE parseIntegral #-} typeError :: String -> B.ByteString -> Maybe String -> Parser a typeError typ s mmsg = fail $ "expected " ++ typ ++ ", got " ++ show (B8.unpack s) ++ cause where cause = case mmsg of Just msg -> " (" ++ msg ++ ")" Nothing -> "" ------------------------------------------------------------------------ -- Constructors and accessors -- | Retrieve the /n/th field in the given record. The result is -- 'empty' if the value cannot be converted to the desired type. -- Raises an exception if the index is out of bounds. (.!) :: FromField a => Record -> Int -> Parser a v .! idx = parseField (v ! idx) {-# INLINE (.!) #-} -- | Retrieve a field in the given record by name. The result is -- 'empty' if the field is missing or if the value cannot be converted -- to the desired type. (.:) :: FromField a => NamedRecord -> B.ByteString -> Parser a m .: name = maybe (fail err) parseField $ HM.lookup name m where err = "no field named " ++ show (B8.unpack name) {-# INLINE (.:) #-} -- | Construct a pair from a name and a value. For use with -- 'namedRecord'. (.=) :: ToField a => B.ByteString -> a -> (B.ByteString, B.ByteString) name .= val = (name, toField val) {-# INLINE (.=) #-} -- | Construct a record from a list of 'B.ByteString's. Use 'toField' -- to convert values to 'B.ByteString's for use with 'record'. record :: [B.ByteString] -> Record record = V.fromList -- | Construct a named record from a list of name-value 'B.ByteString' -- pairs. Use '.=' to construct such a pair from a name and a value. namedRecord :: [(B.ByteString, B.ByteString)] -> NamedRecord namedRecord = HM.fromList ------------------------------------------------------------------------ -- Parser for converting records to data types -- | The result of running a 'Parser'. data Result a = Error String | Success a deriving (Eq, Show) instance Functor Result where fmap f (Success a) = Success (f a) fmap _ (Error err) = Error err {-# INLINE fmap #-} instance Monad Result where return = Success {-# INLINE return #-} Success a >>= k = k a Error err >>= _ = Error err {-# INLINE (>>=) #-} instance Applicative Result where pure = return {-# INLINE pure #-} (<*>) = ap {-# INLINE (<*>) #-} instance MonadPlus Result where mzero = fail "mzero" {-# INLINE mzero #-} mplus a@(Success _) _ = a mplus _ b = b {-# INLINE mplus #-} instance Alternative Result where empty = mzero {-# INLINE empty #-} (<|>) = mplus {-# INLINE (<|>) #-} instance Monoid (Result a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = mplus {-# INLINE mappend #-} -- | Failure continuation. type Failure f r = String -> f r -- | Success continuation. type Success a f r = a -> f r -- | Conversion of a field to a value might fail e.g. if the field is -- malformed. This possibility is captured by the 'Parser' type, which -- lets you compose several field conversions together in such a way -- that if any of them fail, the whole record conversion fails. newtype Parser a = Parser { runParser :: forall f r. Failure f r -> Success a f r -> f r } instance Monad Parser where m >>= g = Parser $ \kf ks -> let ks' a = runParser (g a) kf ks in runParser m kf ks' {-# INLINE (>>=) #-} return a = Parser $ \_kf ks -> ks a {-# INLINE return #-} fail msg = Parser $ \kf _ks -> kf msg {-# INLINE fail #-} instance Functor Parser where fmap f m = Parser $ \kf ks -> let ks' a = ks (f a) in runParser m kf ks' {-# INLINE fmap #-} instance Applicative Parser where pure = return {-# INLINE pure #-} (<*>) = apP {-# INLINE (<*>) #-} instance Alternative Parser where empty = fail "empty" {-# INLINE empty #-} (<|>) = mplus {-# INLINE (<|>) #-} instance MonadPlus Parser where mzero = fail "mzero" {-# INLINE mzero #-} mplus a b = Parser $ \kf ks -> let kf' _ = runParser b kf ks in runParser a kf' ks {-# INLINE mplus #-} instance Monoid (Parser a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = mplus {-# INLINE mappend #-} apP :: Parser (a -> b) -> Parser a -> Parser b apP d e = do b <- d a <- e return (b a) {-# INLINE apP #-} -- | Run a 'Parser'. parse :: Parser a -> Result a parse p = runParser p Error Success {-# INLINE parse #-} #ifdef GENERICS class GFromRecord f where gparseRecord :: Record -> Parser (f p) instance GFromRecordSum f Record => GFromRecord (M1 i n f) where gparseRecord v = case (IM.lookup n gparseRecordSum) of Nothing -> lengthMismatch n v Just p -> M1 <$> p v where n = V.length v class GFromNamedRecord f where gparseNamedRecord :: NamedRecord -> Parser (f p) instance GFromRecordSum f NamedRecord => GFromNamedRecord (M1 i n f) where gparseNamedRecord v = foldr (\f p -> p <|> M1 <$> f v) empty (IM.elems gparseRecordSum) class GFromRecordSum f r where gparseRecordSum :: IM.IntMap (r -> Parser (f p)) instance (GFromRecordSum a r, GFromRecordSum b r) => GFromRecordSum (a :+: b) r where gparseRecordSum = IM.unionWith (\a b r -> a r <|> b r) (fmap (L1 <$>) <$> gparseRecordSum) (fmap (R1 <$>) <$> gparseRecordSum) instance GFromRecordProd f r => GFromRecordSum (M1 i n f) r where gparseRecordSum = IM.singleton n (fmap (M1 <$>) f) where (n, f) = gparseRecordProd 0 class GFromRecordProd f r where gparseRecordProd :: Int -> (Int, r -> Parser (f p)) instance GFromRecordProd U1 r where gparseRecordProd n = (n, const (pure U1)) instance (GFromRecordProd a r, GFromRecordProd b r) => GFromRecordProd (a :*: b) r where gparseRecordProd n0 = (n2, f) where f r = (:*:) <$> fa r <*> fb r (n1, fa) = gparseRecordProd n0 (n2, fb) = gparseRecordProd n1 instance GFromRecordProd f Record => GFromRecordProd (M1 i n f) Record where gparseRecordProd n = fmap (M1 <$>) <$> gparseRecordProd n instance FromField a => GFromRecordProd (K1 i a) Record where gparseRecordProd n = (n + 1, \v -> K1 <$> parseField (V.unsafeIndex v n)) data Proxy s (f :: * -> *) a = Proxy instance (FromField a, Selector s) => GFromRecordProd (M1 S s (K1 i a)) NamedRecord where gparseRecordProd n = (n + 1, \v -> (M1 . K1) <$> v .: name) where name = T.encodeUtf8 (T.pack (selName (Proxy :: Proxy s f a))) class GToRecord a f where gtoRecord :: a p -> [f] instance GToRecord U1 f where gtoRecord U1 = [] instance (GToRecord a f, GToRecord b f) => GToRecord (a :*: b) f where gtoRecord (a :*: b) = gtoRecord a ++ gtoRecord b instance (GToRecord a f, GToRecord b f) => GToRecord (a :+: b) f where gtoRecord (L1 a) = gtoRecord a gtoRecord (R1 b) = gtoRecord b instance GToRecord a f => GToRecord (M1 D c a) f where gtoRecord (M1 a) = gtoRecord a instance GToRecord a f => GToRecord (M1 C c a) f where gtoRecord (M1 a) = gtoRecord a instance GToRecord a Field => GToRecord (M1 S c a) Field where gtoRecord (M1 a) = gtoRecord a instance ToField a => GToRecord (K1 i a) Field where gtoRecord (K1 a) = [toField a] instance (ToField a, Selector s) => GToRecord (M1 S s (K1 i a)) (B.ByteString, B.ByteString) where gtoRecord m@(M1 (K1 a)) = [T.encodeUtf8 (T.pack (selName m)) .= toField a] #endif
sjoerdvisscher/cassava
Data/Csv/Conversion.hs
bsd-3-clause
24,266
0
20
6,582
6,582
3,522
3,060
414
2
{-# OPTIONS_GHC -F -pgmF htfpp #-} module Ebitor.Rope.CursorTest (htf_thisModulesTests) where import Data.List (intercalate) import Data.Maybe (fromJust) import Test.Framework import Ebitor.Rope (Rope) import Ebitor.Rope.Cursor import Ebitor.RopeUtils import qualified Ebitor.Rope as R madWorld = "it's a mad mad mad mad world" patchOfOldSnow = packRope $ intercalate "\n" [ "\tA Patch of Old Snow" -- 20 , "" -- 0 , "There's a patch of old snow in a corner" -- 39 , "That I should have guessed" -- 26 , "Was a blow-away paper the rain" -- 30 , "Had brought to rest." -- 20 , "" -- 0 , "It is speckled with grime as if" -- 31 , "Small print overspread it," -- 26 , "The news of a day I've forgotten--" -- 34 , "If I ever read it." -- 18 , "" -- 0 , "- Robert Frost" -- 14 ] test_positionForCursorLF = assertEqual (27, Cursor (3, 6)) (R.positionForCursor patchOfOldSnow (Cursor (3, 6))) test_positionForIndexLF = assertEqual (27, Cursor (3, 6)) (R.positionForIndex patchOfOldSnow 27) test_positionForCursorPastEOL = assertEqual (61, Cursor (3, 40)) (R.positionForCursor patchOfOldSnow (Cursor (3, 100))) test_positionForCursorAtEOL = assertEqual (61, Cursor (3, 40)) (R.positionForCursor patchOfOldSnow (Cursor (3, 40))) test_positionForCursorBeforeLine1 = assertEqual (0, Cursor (1, 1)) (R.positionForCursor patchOfOldSnow (Cursor (1, 0))) test_positionForCursorBeforeLine2 = assertEqual (21, Cursor (2, 1)) (R.positionForCursor patchOfOldSnow (Cursor (2, -1000))) test_positionForCursorInTab = assertEqual (1, Cursor (1, 9)) (R.positionForCursor patchOfOldSnow (Cursor (1, 4))) test_positionForCursorBeforeDocument = assertEqual (0, Cursor (1, 1)) (R.positionForCursor patchOfOldSnow (Cursor (0, 4))) test_positionForIndexBeforeDocument = assertEqual (0, Cursor (1, 1)) (R.positionForIndex patchOfOldSnow (-10)) test_positionForCursorPastDocument = assertEqual (R.length patchOfOldSnow, Cursor (13, 15)) (R.positionForCursor patchOfOldSnow (Cursor (1000, 1))) test_positionForIndexPastDocument = assertEqual (R.length patchOfOldSnow, Cursor (13, 15)) (R.positionForIndex patchOfOldSnow (R.length patchOfOldSnow + 50))
benekastah/ebitor
test/Ebitor/Rope/CursorTest.hs
bsd-3-clause
2,415
0
11
570
648
371
277
57
1
{-# LANGUAGE OverloadedStrings #-} module Themes ( InternalTheme(..) , defaultTheme , internalThemes , lookupTheme , themeDocs -- * Attribute names , timeAttr , channelHeaderAttr , channelListHeaderAttr , currentChannelNameAttr , unreadChannelAttr , mentionsChannelAttr , urlAttr , codeAttr , emailAttr , emojiAttr , channelNameAttr , clientMessageAttr , clientHeaderAttr , clientEmphAttr , clientStrongAttr , dateTransitionAttr , newMessageTransitionAttr , gapMessageAttr , errorMessageAttr , helpAttr , helpEmphAttr , channelSelectPromptAttr , channelSelectMatchAttr , completionAlternativeListAttr , completionAlternativeCurrentAttr , dialogAttr , dialogEmphAttr , recentMarkerAttr , replyParentAttr , loadMoreAttr , urlListSelectedAttr , messageSelectAttr , messageSelectStatusAttr , misspellingAttr , editedMarkingAttr , editedRecentlyMarkingAttr -- * Username formatting , colorUsername ) where import Prelude () import Prelude.MH import Brick import Brick.Themes import Brick.Widgets.List import Brick.Widgets.Skylighting ( attrNameForTokenType , attrMappingsForStyle , highlightedCodeBlockAttr ) import Data.Hashable ( hash ) import qualified Data.Map as M import qualified Data.Text as T import Graphics.Vty import qualified Skylighting.Styles as Sky import Skylighting.Types ( TokenType(..) ) helpAttr :: AttrName helpAttr = "help" helpEmphAttr :: AttrName helpEmphAttr = "helpEmphasis" recentMarkerAttr :: AttrName recentMarkerAttr = "recentChannelMarker" replyParentAttr :: AttrName replyParentAttr = "replyParentPreview" loadMoreAttr :: AttrName loadMoreAttr = "loadMoreMessages" urlListSelectedAttr :: AttrName urlListSelectedAttr = "urlListCursor" messageSelectAttr :: AttrName messageSelectAttr = "messageSelectCursor" editedMarkingAttr :: AttrName editedMarkingAttr = "editedMarking" editedRecentlyMarkingAttr :: AttrName editedRecentlyMarkingAttr = "editedRecentlyMarking" dialogAttr :: AttrName dialogAttr = "dialog" dialogEmphAttr :: AttrName dialogEmphAttr = "dialogEmphasis" channelSelectMatchAttr :: AttrName channelSelectMatchAttr = "channelSelectMatch" channelSelectPromptAttr :: AttrName channelSelectPromptAttr = "channelSelectPrompt" completionAlternativeListAttr :: AttrName completionAlternativeListAttr = "tabCompletionAlternative" completionAlternativeCurrentAttr :: AttrName completionAlternativeCurrentAttr = "tabCompletionCursor" timeAttr :: AttrName timeAttr = "time" channelHeaderAttr :: AttrName channelHeaderAttr = "channelHeader" channelListHeaderAttr :: AttrName channelListHeaderAttr = "channelListSectionHeader" currentChannelNameAttr :: AttrName currentChannelNameAttr = "currentChannelName" channelNameAttr :: AttrName channelNameAttr = "channelName" unreadChannelAttr :: AttrName unreadChannelAttr = "unreadChannel" mentionsChannelAttr :: AttrName mentionsChannelAttr = "channelWithMentions" dateTransitionAttr :: AttrName dateTransitionAttr = "dateTransition" newMessageTransitionAttr :: AttrName newMessageTransitionAttr = "newMessageTransition" urlAttr :: AttrName urlAttr = "url" codeAttr :: AttrName codeAttr = "codeBlock" emailAttr :: AttrName emailAttr = "email" emojiAttr :: AttrName emojiAttr = "emoji" clientMessageAttr :: AttrName clientMessageAttr = "clientMessage" clientHeaderAttr :: AttrName clientHeaderAttr = "markdownHeader" clientEmphAttr :: AttrName clientEmphAttr = "markdownEmph" clientStrongAttr :: AttrName clientStrongAttr = "markdownStrong" errorMessageAttr :: AttrName errorMessageAttr = "errorMessage" gapMessageAttr :: AttrName gapMessageAttr = "gapMessage" misspellingAttr :: AttrName misspellingAttr = "misspelling" messageSelectStatusAttr :: AttrName messageSelectStatusAttr = "messageSelectStatus" data InternalTheme = InternalTheme { internalThemeName :: Text , internalTheme :: Theme } lookupTheme :: Text -> Maybe InternalTheme lookupTheme n = find ((== n) . internalThemeName) internalThemes internalThemes :: [InternalTheme] internalThemes = validateInternalTheme <$> [ darkColorTheme , lightColorTheme ] validateInternalTheme :: InternalTheme -> InternalTheme validateInternalTheme it = let un = undocumentedAttrNames (internalTheme it) in if not $ null un then error $ "Internal theme " <> show (T.unpack (internalThemeName it)) <> " references undocumented attribute names: " <> show un else it undocumentedAttrNames :: Theme -> [AttrName] undocumentedAttrNames t = let noDocs k = isNothing $ attrNameDescription themeDocs k in filter noDocs (M.keys $ themeDefaultMapping t) defaultTheme :: InternalTheme defaultTheme = darkColorTheme lightColorTheme :: InternalTheme lightColorTheme = InternalTheme name theme where theme = newTheme def lightAttrs name = "builtin:light" def = black `on` white lightAttrs :: [(AttrName, Attr)] lightAttrs = let sty = Sky.kate in [ (timeAttr, fg black) , (channelHeaderAttr, fg black `withStyle` underline) , (channelListHeaderAttr, fg cyan) , (currentChannelNameAttr, black `on` yellow `withStyle` bold) , (unreadChannelAttr, black `on` cyan `withStyle` bold) , (mentionsChannelAttr, black `on` red `withStyle` bold) , (urlAttr, fg brightYellow) , (emailAttr, fg yellow) , (codeAttr, fg magenta) , (emojiAttr, fg yellow) , (channelNameAttr, fg blue) , (clientMessageAttr, fg black) , (clientEmphAttr, fg black `withStyle` bold) , (clientStrongAttr, fg black `withStyle` bold `withStyle` underline) , (clientHeaderAttr, fg red `withStyle` bold) , (dateTransitionAttr, fg green) , (newMessageTransitionAttr, black `on` yellow) , (errorMessageAttr, fg red) , (gapMessageAttr, fg red) , (helpAttr, black `on` cyan) , (helpEmphAttr, fg white) , (channelSelectMatchAttr, black `on` magenta) , (channelSelectPromptAttr, fg black) , (completionAlternativeListAttr, white `on` blue) , (completionAlternativeCurrentAttr, black `on` yellow) , (dialogAttr, black `on` cyan) , (dialogEmphAttr, fg white) , (listSelectedFocusedAttr, black `on` yellow) , (recentMarkerAttr, fg black `withStyle` bold) , (loadMoreAttr, black `on` cyan) , (urlListSelectedAttr, black `on` yellow) , (messageSelectAttr, black `on` yellow) , (messageSelectStatusAttr, fg black) , (misspellingAttr, fg red `withStyle` underline) , (editedMarkingAttr, fg yellow) , (editedRecentlyMarkingAttr, black `on` yellow) ] <> ((\(i, a) -> (usernameAttr i, a)) <$> zip [0..] usernameColors) <> (filter skipBaseCodeblockAttr $ attrMappingsForStyle sty) darkAttrs :: [(AttrName, Attr)] darkAttrs = let sty = Sky.espresso in [ (timeAttr, fg white) , (channelHeaderAttr, fg white `withStyle` underline) , (channelListHeaderAttr, fg cyan) , (currentChannelNameAttr, black `on` yellow `withStyle` bold) , (unreadChannelAttr, black `on` cyan `withStyle` bold) , (mentionsChannelAttr, black `on` brightMagenta `withStyle` bold) , (urlAttr, fg yellow) , (emailAttr, fg yellow) , (codeAttr, fg magenta) , (emojiAttr, fg yellow) , (channelNameAttr, fg cyan) , (clientMessageAttr, fg white) , (clientEmphAttr, fg white `withStyle` bold) , (clientStrongAttr, fg white `withStyle` bold `withStyle` underline) , (clientHeaderAttr, fg red `withStyle` bold) , (dateTransitionAttr, fg green) , (newMessageTransitionAttr, fg yellow `withStyle` bold) , (errorMessageAttr, fg red) , (gapMessageAttr, black `on` yellow) , (helpAttr, black `on` cyan) , (helpEmphAttr, fg white) , (channelSelectMatchAttr, black `on` magenta) , (channelSelectPromptAttr, fg white) , (completionAlternativeListAttr, white `on` blue) , (completionAlternativeCurrentAttr, black `on` yellow) , (dialogAttr, black `on` cyan) , (dialogEmphAttr, fg white) , (listSelectedFocusedAttr, black `on` yellow) , (recentMarkerAttr, fg yellow `withStyle` bold) , (loadMoreAttr, black `on` cyan) , (urlListSelectedAttr, black `on` yellow) , (messageSelectAttr, black `on` yellow) , (messageSelectStatusAttr, fg white) , (misspellingAttr, fg red `withStyle` underline) , (editedMarkingAttr, fg yellow) , (editedRecentlyMarkingAttr, black `on` yellow) ] <> ((\(i, a) -> (usernameAttr i, a)) <$> zip [0..] usernameColors) <> (filter skipBaseCodeblockAttr $ attrMappingsForStyle sty) skipBaseCodeblockAttr :: (AttrName, Attr) -> Bool skipBaseCodeblockAttr = ((/= highlightedCodeBlockAttr) . fst) darkColorTheme :: InternalTheme darkColorTheme = InternalTheme name theme where theme = newTheme def darkAttrs name = "builtin:dark" def = defAttr usernameAttr :: Int -> AttrName usernameAttr i = "username" <> (attrName $ show i) colorUsername :: Text -> Text -> Widget a colorUsername username display = withDefAttr (usernameAttr h) $ txt (display) where h = hash username `mod` length usernameColors usernameColors :: [Attr] usernameColors = [ fg red , fg green , fg yellow , fg blue , fg magenta , fg cyan , fg brightRed , fg brightGreen , fg brightYellow , fg brightBlue , fg brightMagenta , fg brightCyan ] -- Functions for dealing with Skylighting styles attrNameDescription :: ThemeDocumentation -> AttrName -> Maybe Text attrNameDescription td an = M.lookup an (themeDescriptions td) themeDocs :: ThemeDocumentation themeDocs = ThemeDocumentation $ M.fromList $ [ ( timeAttr , "Timestamps on chat messages" ) , ( channelHeaderAttr , "Channel headers displayed above chat message lists" ) , ( channelListHeaderAttr , "The heading of the channel list sections" ) , ( currentChannelNameAttr , "The currently selected channel in the channel list" ) , ( unreadChannelAttr , "A channel in the channel list with unread messages" ) , ( mentionsChannelAttr , "A channel in the channel list with unread mentions" ) , ( urlAttr , "A URL in a chat message" ) , ( codeAttr , "A code block in a chat message with no language indication" ) , ( emailAttr , "An e-mail address in a chat message" ) , ( emojiAttr , "A text emoji indication in a chat message" ) , ( channelNameAttr , "A channel name in a chat message" ) , ( clientMessageAttr , "A Matterhorn diagnostic or informative message" ) , ( clientHeaderAttr , "Markdown heading" ) , ( clientEmphAttr , "Markdown 'emphasized' text" ) , ( clientStrongAttr , "Markdown 'strong' text" ) , ( dateTransitionAttr , "Date transition lines between chat messages on different days" ) , ( newMessageTransitionAttr , "The 'New Messages' line that appears above unread messages" ) , ( errorMessageAttr , "Matterhorn error messages" ) , ( gapMessageAttr , "Matterhorn message gap information" ) , ( helpAttr , "The help screen text" ) , ( helpEmphAttr , "The help screen's emphasized text" ) , ( channelSelectPromptAttr , "Channel selection: prompt" ) , ( channelSelectMatchAttr , "Channel selection: the portion of a channel name that matches" ) , ( completionAlternativeListAttr , "Tab completion alternatives" ) , ( completionAlternativeCurrentAttr , "The currently-selected tab completion alternative" ) , ( dialogAttr , "Dialog box text" ) , ( dialogEmphAttr , "Dialog box emphasized text" ) , ( recentMarkerAttr , "The marker indicating the channel last visited" ) , ( replyParentAttr , "The first line of parent messages appearing above reply messages" ) , ( loadMoreAttr , "The 'Load More' line that appears at the top of a chat message list" ) , ( urlListSelectedAttr , "URL list: the selected URL" ) , ( messageSelectAttr , "Message selection: the currently-selected message" ) , ( messageSelectStatusAttr , "Message selection: the message selection actions" ) , ( misspellingAttr , "A misspelled word in the chat message editor" ) , ( editedMarkingAttr , "The 'edited' marking that appears on edited messages" ) , ( editedRecentlyMarkingAttr , "The 'edited' marking that appears on newly-edited messages" ) , ( highlightedCodeBlockAttr , "The base attribute for syntax-highlighted code blocks" ) , ( attrNameForTokenType KeywordTok , "Syntax highlighting: Keyword" ) , ( attrNameForTokenType DataTypeTok , "Syntax highlighting: DataType" ) , ( attrNameForTokenType DecValTok , "Syntax highlighting: Declaration" ) , ( attrNameForTokenType BaseNTok , "Syntax highlighting: BaseN" ) , ( attrNameForTokenType FloatTok , "Syntax highlighting: Float" ) , ( attrNameForTokenType ConstantTok , "Syntax highlighting: Constant" ) , ( attrNameForTokenType CharTok , "Syntax highlighting: Char" ) , ( attrNameForTokenType SpecialCharTok , "Syntax highlighting: Special Char" ) , ( attrNameForTokenType StringTok , "Syntax highlighting: String" ) , ( attrNameForTokenType VerbatimStringTok , "Syntax highlighting: Verbatim String" ) , ( attrNameForTokenType SpecialStringTok , "Syntax highlighting: Special String" ) , ( attrNameForTokenType ImportTok , "Syntax highlighting: Import" ) , ( attrNameForTokenType CommentTok , "Syntax highlighting: Comment" ) , ( attrNameForTokenType DocumentationTok , "Syntax highlighting: Documentation" ) , ( attrNameForTokenType AnnotationTok , "Syntax highlighting: Annotation" ) , ( attrNameForTokenType CommentVarTok , "Syntax highlighting: Comment" ) , ( attrNameForTokenType OtherTok , "Syntax highlighting: Other" ) , ( attrNameForTokenType FunctionTok , "Syntax highlighting: Function" ) , ( attrNameForTokenType VariableTok , "Syntax highlighting: Variable" ) , ( attrNameForTokenType ControlFlowTok , "Syntax highlighting: Control Flow" ) , ( attrNameForTokenType OperatorTok , "Syntax highlighting: Operator" ) , ( attrNameForTokenType BuiltInTok , "Syntax highlighting: Built-In" ) , ( attrNameForTokenType ExtensionTok , "Syntax highlighting: Extension" ) , ( attrNameForTokenType PreprocessorTok , "Syntax highlighting: Preprocessor" ) , ( attrNameForTokenType AttributeTok , "Syntax highlighting: Attribute" ) , ( attrNameForTokenType RegionMarkerTok , "Syntax highlighting: Region Marker" ) , ( attrNameForTokenType InformationTok , "Syntax highlighting: Information" ) , ( attrNameForTokenType WarningTok , "Syntax highlighting: Warning" ) , ( attrNameForTokenType AlertTok , "Syntax highlighting: Alert" ) , ( attrNameForTokenType ErrorTok , "Syntax highlighting: Error" ) , ( attrNameForTokenType NormalTok , "Syntax highlighting: Normal text" ) , ( listSelectedFocusedAttr , "The selected channel" ) ] <> [ (usernameAttr i, T.pack $ "Username color " <> show i) | i <- [0..(length usernameColors)-1] ]
aisamanra/matterhorn
src/Themes.hs
bsd-3-clause
17,282
0
15
5,079
3,205
1,927
1,278
412
2
module Opaleye.Internal.NEList where data NEList a = NEList a [a] deriving Show singleton :: a -> NEList a singleton = flip NEList [] toList :: NEList a -> [a] toList (NEList a as) = a:as neCat :: NEList a -> NEList a -> NEList a neCat (NEList a as) bs = NEList a (as ++ toList bs) instance Functor NEList where fmap f (NEList a as) = NEList (f a) (fmap f as) instance Monad NEList where return = flip NEList [] NEList a as >>= f = NEList b (bs ++ (as >>= (toList . f))) where NEList b bs = f a
k0001/haskell-opaleye
Opaleye/Internal/NEList.hs
bsd-3-clause
511
0
12
120
262
132
130
14
1
import Control.Monad import Codec.Compression.GZip import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy as L import System.FilePath import System.FilePath.Find import System.FilePath.Glob import System.FilePath.Manip import Text.Regex.Posix ((=~)) -- Get a list of all symlinks. getDanglingLinks :: FilePath -> IO [FilePath] getDanglingLinks = find always (fileType ==? SymbolicLink &&? followStatus ==? Nothing) -- Rename all ".cpp" files to ".C". renameCppToC :: FilePath -> IO () renameCppToC path = find always (extension ==? ".cpp") path >>= mapM_ (renameWith (replaceExtension ".C")) -- A recursion control predicate that will avoid recursing into -- directories commonly used by revision control tools. noRCS :: RecursionPredicate noRCS = (`notElem` ["_darcs","SCCS","CVS",".svn",".hg",".git"]) `liftM` fileName cSources :: FilePath -> IO [FilePath] cSources = find noRCS (extension ==? ".c" ||? extension ==? ".h") -- Replace all uses of "monkey" with "simian", saving the original copy -- of the file with a ".bak" extension: monkeyAround :: FilePath -> IO () monkeyAround = modifyWithBackup (<.> "bak") (unwords . map reMonkey . words) where reMonkey x = if x == "monkey" then "simian" else x -- Given a simple grep, it's easy to construct a recursive grep. grep :: (Int -> S.ByteString -> a) -> String -> S.ByteString -> [a] grep f pat s = consider 0 (S.lines s) where consider _ [] = [] consider n (l:ls) | S.null l = consider (n+1) ls consider n (l:ls) | l =~ pat = (f n l):ls' | otherwise = ls' where ls' = consider (n+1) ls grepFile :: (Int -> S.ByteString -> a) -> String -> FilePath -> IO [a] grepFile f pat name = grep f pat `liftM` S.readFile name recGrep :: String -> FilePath -> IO [(FilePath, Int, S.ByteString)] recGrep pat top = find always (fileType ==? RegularFile) top >>= mapM ((,,) >>= flip grepFile pat) >>= return . concat -- Decompress all gzip files matching a fixed glob pattern, and return -- the results as a single huge lazy ByteString. decomp :: IO L.ByteString decomp = namesMatching "*/*.gz" >>= fmap L.concat . mapM (fmap decompress . L.readFile)
bos/filemanip
examples/Simple.hs
bsd-3-clause
2,319
0
11
536
692
375
317
38
3
module Avg where {-@ measure sumD :: [Double] -> Double sumD([]) = 0.0 sumD(x:xs) = x + (sumD xs) @-} {-@ measure lenD :: [Double] -> Double lenD([]) = 0.0 lenD(x:xs) = (1.0) + (lenD xs) @-} {-@ expression Avg Xs = ((sumD Xs) / (lenD Xs)) @-} {-@ meansD :: xs:{v:[Double] | ((lenD v) > 0.0)} -> {v:Double | v = Avg xs} @-} meansD :: [Double] -> Double meansD xs = sumD xs / lenD xs {-@ lenD :: xs:[Double] -> {v:Double | v = (lenD xs)} @-} lenD :: [Double] -> Double lenD [] = 0.0 lenD (x:xs) = 1.0 + lenD xs {-@ sumD :: xs:[Double] -> {v:Double | v = (sumD xs)} @-} sumD :: [Double] -> Double sumD [] = 0.0 sumD (x:xs) = x + sumD xs
ssaavedra/liquidhaskell
tests/pos/Avg.hs
bsd-3-clause
673
0
7
173
128
70
58
9
1
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-} {-# OPTIONS_GHC -fcontext-stack42 #-} module Games.Chaos2010.Database.Database_constraints where import Games.Chaos2010.Database.Fields import Database.HaskellDB.DBLayout type Database_constraints = Record (HCons (LVPair Constraint_name (Expr String)) (HCons (LVPair Expression (Expr String)) HNil)) database_constraints :: Table Database_constraints database_constraints = baseTable "database_constraints"
JakeWheat/Chaos-2010
Games/Chaos2010/Database/Database_constraints.hs
bsd-3-clause
487
0
13
65
92
52
40
11
1
module MapDeclM where import Recursive import IdM {-+ A class to apply a monadic function to all declarations in a structure. The type of the structure is #s#, the type of the declarations is #d#. The functional dependency ensures that we can determine the type of declarations from the type of the structure. -} class MapDeclM s d | s -> d where mapDeclM :: (Functor m, Monad m) => (d -> m d) -> s -> m s instance MapDeclM s ds => MapDeclM [s] ds where mapDeclM = mapM . mapDeclM {- A convinient function, when the definition is in terms of the underlying structure. -} std_mapDeclM f = fmap r . mapDeclM f . struct mapDecls f m = removeId $ mapDeclM (return.map f) m
forste/haReFork
tools/base/transforms/MapDeclM.hs
bsd-3-clause
686
0
11
145
150
78
72
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP, DeriveDataTypeable #-} -- | -- #name_types# -- GHC uses several kinds of name internally: -- -- * 'OccName.OccName': see "OccName#name_types" -- -- * 'RdrName.RdrName' is the type of names that come directly from the parser. They -- have not yet had their scoping and binding resolved by the renamer and can be -- thought of to a first approximation as an 'OccName.OccName' with an optional module -- qualifier -- -- * 'Name.Name': see "Name#name_types" -- -- * 'Id.Id': see "Id#name_types" -- -- * 'Var.Var': see "Var#name_types" module RdrName ( -- * The main type RdrName(..), -- Constructors exported only to BinIface -- ** Construction mkRdrUnqual, mkRdrQual, mkUnqual, mkVarUnqual, mkQual, mkOrig, nameRdrName, getRdrName, -- ** Destruction rdrNameOcc, rdrNameSpace, setRdrNameSpace, demoteRdrName, isRdrDataCon, isRdrTyVar, isRdrTc, isQual, isQual_maybe, isUnqual, isOrig, isOrig_maybe, isExact, isExact_maybe, isSrcRdrName, -- * Local mapping of 'RdrName' to 'Name.Name' LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv, extendLocalRdrEnvList, lookupLocalRdrEnv, lookupLocalRdrOcc, elemLocalRdrEnv, inLocalRdrEnvScope, localRdrEnvElts, delLocalRdrEnvList, -- * Global mapping of 'RdrName' to 'GlobalRdrElt's GlobalRdrEnv, emptyGlobalRdrEnv, mkGlobalRdrEnv, plusGlobalRdrEnv, lookupGlobalRdrEnv, extendGlobalRdrEnv, pprGlobalRdrEnv, globalRdrEnvElts, lookupGRE_RdrName, lookupGRE_Name, getGRE_NameQualifier_maybes, transformGREs, findLocalDupsRdrEnv, pickGREs, -- * GlobalRdrElts gresFromAvails, gresFromAvail, -- ** Global 'RdrName' mapping elements: 'GlobalRdrElt', 'Provenance', 'ImportSpec' GlobalRdrElt(..), isLocalGRE, unQualOK, qualSpecOK, unQualSpecOK, Provenance(..), pprNameProvenance, Parent(..), ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..), importSpecLoc, importSpecModule, isExplicitItem ) where #include "HsVersions.h" import Module import Name import Avail import NameSet import Maybes import SrcLoc import FastString import Outputable import Unique import Util import StaticFlags( opt_PprStyle_Debug ) import Data.Data {- ************************************************************************ * * \subsection{The main data type} * * ************************************************************************ -} -- | Do not use the data constructors of RdrName directly: prefer the family -- of functions that creates them, such as 'mkRdrUnqual' -- -- - Note: A Located RdrName will only have API Annotations if it is a -- compound one, -- e.g. -- -- > `bar` -- > ( ~ ) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType', -- 'ApiAnnotation.AnnOpen' @'('@ or @'['@ or @'[:'@, -- 'ApiAnnotation.AnnClose' @')'@ or @']'@ or @':]'@,, -- 'ApiAnnotation.AnnBackquote' @'`'@, -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnTildehsh', -- 'ApiAnnotation.AnnTilde', data RdrName = Unqual OccName -- ^ Used for ordinary, unqualified occurrences, e.g. @x@, @y@ or @Foo@. -- Create such a 'RdrName' with 'mkRdrUnqual' | Qual ModuleName OccName -- ^ A qualified name written by the user in -- /source/ code. The module isn't necessarily -- the module where the thing is defined; -- just the one from which it is imported. -- Examples are @Bar.x@, @Bar.y@ or @Bar.Foo@. -- Create such a 'RdrName' with 'mkRdrQual' | Orig Module OccName -- ^ An original name; the module is the /defining/ module. -- This is used when GHC generates code that will be fed -- into the renamer (e.g. from deriving clauses), but where -- we want to say \"Use Prelude.map dammit\". One of these -- can be created with 'mkOrig' | Exact Name -- ^ We know exactly the 'Name'. This is used: -- -- (1) When the parser parses built-in syntax like @[]@ -- and @(,)@, but wants a 'RdrName' from it -- -- (2) By Template Haskell, when TH has generated a unique name -- -- Such a 'RdrName' can be created by using 'getRdrName' on a 'Name' deriving (Data, Typeable) {- ************************************************************************ * * \subsection{Simple functions} * * ************************************************************************ -} instance HasOccName RdrName where occName = rdrNameOcc rdrNameOcc :: RdrName -> OccName rdrNameOcc (Qual _ occ) = occ rdrNameOcc (Unqual occ) = occ rdrNameOcc (Orig _ occ) = occ rdrNameOcc (Exact name) = nameOccName name rdrNameSpace :: RdrName -> NameSpace rdrNameSpace = occNameSpace . rdrNameOcc setRdrNameSpace :: RdrName -> NameSpace -> RdrName -- ^ This rather gruesome function is used mainly by the parser. -- When parsing: -- -- > data T a = T | T1 Int -- -- we parse the data constructors as /types/ because of parser ambiguities, -- so then we need to change the /type constr/ to a /data constr/ -- -- The exact-name case /can/ occur when parsing: -- -- > data [] a = [] | a : [a] -- -- For the exact-name case we return an original name. setRdrNameSpace (Unqual occ) ns = Unqual (setOccNameSpace ns occ) setRdrNameSpace (Qual m occ) ns = Qual m (setOccNameSpace ns occ) setRdrNameSpace (Orig m occ) ns = Orig m (setOccNameSpace ns occ) setRdrNameSpace (Exact n) ns | isExternalName n = Orig (nameModule n) occ | otherwise -- This can happen when quoting and then splicing a fixity -- declaration for a type = Exact $ mkSystemNameAt (nameUnique n) occ (nameSrcSpan n) where occ = setOccNameSpace ns (nameOccName n) -- demoteRdrName lowers the NameSpace of RdrName. -- see Note [Demotion] in OccName demoteRdrName :: RdrName -> Maybe RdrName demoteRdrName (Unqual occ) = fmap Unqual (demoteOccName occ) demoteRdrName (Qual m occ) = fmap (Qual m) (demoteOccName occ) demoteRdrName (Orig _ _) = panic "demoteRdrName" demoteRdrName (Exact _) = panic "demoteRdrName" -- These two are the basic constructors mkRdrUnqual :: OccName -> RdrName mkRdrUnqual occ = Unqual occ mkRdrQual :: ModuleName -> OccName -> RdrName mkRdrQual mod occ = Qual mod occ mkOrig :: Module -> OccName -> RdrName mkOrig mod occ = Orig mod occ --------------- -- These two are used when parsing source files -- They do encode the module and occurrence names mkUnqual :: NameSpace -> FastString -> RdrName mkUnqual sp n = Unqual (mkOccNameFS sp n) mkVarUnqual :: FastString -> RdrName mkVarUnqual n = Unqual (mkVarOccFS n) -- | Make a qualified 'RdrName' in the given namespace and where the 'ModuleName' and -- the 'OccName' are taken from the first and second elements of the tuple respectively mkQual :: NameSpace -> (FastString, FastString) -> RdrName mkQual sp (m, n) = Qual (mkModuleNameFS m) (mkOccNameFS sp n) getRdrName :: NamedThing thing => thing -> RdrName getRdrName name = nameRdrName (getName name) nameRdrName :: Name -> RdrName nameRdrName name = Exact name -- Keep the Name even for Internal names, so that the -- unique is still there for debug printing, particularly -- of Types (which are converted to IfaceTypes before printing) nukeExact :: Name -> RdrName nukeExact n | isExternalName n = Orig (nameModule n) (nameOccName n) | otherwise = Unqual (nameOccName n) isRdrDataCon :: RdrName -> Bool isRdrTyVar :: RdrName -> Bool isRdrTc :: RdrName -> Bool isRdrDataCon rn = isDataOcc (rdrNameOcc rn) isRdrTyVar rn = isTvOcc (rdrNameOcc rn) isRdrTc rn = isTcOcc (rdrNameOcc rn) isSrcRdrName :: RdrName -> Bool isSrcRdrName (Unqual _) = True isSrcRdrName (Qual _ _) = True isSrcRdrName _ = False isUnqual :: RdrName -> Bool isUnqual (Unqual _) = True isUnqual _ = False isQual :: RdrName -> Bool isQual (Qual _ _) = True isQual _ = False isQual_maybe :: RdrName -> Maybe (ModuleName, OccName) isQual_maybe (Qual m n) = Just (m,n) isQual_maybe _ = Nothing isOrig :: RdrName -> Bool isOrig (Orig _ _) = True isOrig _ = False isOrig_maybe :: RdrName -> Maybe (Module, OccName) isOrig_maybe (Orig m n) = Just (m,n) isOrig_maybe _ = Nothing isExact :: RdrName -> Bool isExact (Exact _) = True isExact _ = False isExact_maybe :: RdrName -> Maybe Name isExact_maybe (Exact n) = Just n isExact_maybe _ = Nothing {- ************************************************************************ * * \subsection{Instances} * * ************************************************************************ -} instance Outputable RdrName where ppr (Exact name) = ppr name ppr (Unqual occ) = ppr occ ppr (Qual mod occ) = ppr mod <> dot <> ppr occ ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod occ <> ppr occ) instance OutputableBndr RdrName where pprBndr _ n | isTvOcc (rdrNameOcc n) = char '@' <+> ppr n | otherwise = ppr n pprInfixOcc rdr = pprInfixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr) pprPrefixOcc rdr | Just name <- isExact_maybe rdr = pprPrefixName name -- pprPrefixName has some special cases, so -- we delegate to them rather than reproduce them | otherwise = pprPrefixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr) instance Eq RdrName where (Exact n1) == (Exact n2) = n1==n2 -- Convert exact to orig (Exact n1) == r2@(Orig _ _) = nukeExact n1 == r2 r1@(Orig _ _) == (Exact n2) = r1 == nukeExact n2 (Orig m1 o1) == (Orig m2 o2) = m1==m2 && o1==o2 (Qual m1 o1) == (Qual m2 o2) = m1==m2 && o1==o2 (Unqual o1) == (Unqual o2) = o1==o2 _ == _ = False instance Ord RdrName 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 } -- Exact < Unqual < Qual < Orig -- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig -- before comparing so that Prelude.map == the exact Prelude.map, but -- that meant that we reported duplicates when renaming bindings -- generated by Template Haskell; e.g -- do { n1 <- newName "foo"; n2 <- newName "foo"; -- <decl involving n1,n2> } -- I think we can do without this conversion compare (Exact n1) (Exact n2) = n1 `compare` n2 compare (Exact _) _ = LT compare (Unqual _) (Exact _) = GT compare (Unqual o1) (Unqual o2) = o1 `compare` o2 compare (Unqual _) _ = LT compare (Qual _ _) (Exact _) = GT compare (Qual _ _) (Unqual _) = GT compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) compare (Qual _ _) (Orig _ _) = LT compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) compare (Orig _ _) _ = GT {- ************************************************************************ * * LocalRdrEnv * * ************************************************************************ -} -- | This environment is used to store local bindings (@let@, @where@, lambda, @case@). -- It is keyed by OccName, because we never use it for qualified names -- We keep the current mapping, *and* the set of all Names in scope -- Reason: see Note [Splicing Exact Names] in RnEnv data LocalRdrEnv = LRE { lre_env :: OccEnv Name , lre_in_scope :: NameSet } instance Outputable LocalRdrEnv where ppr (LRE {lre_env = env, lre_in_scope = ns}) = hang (ptext (sLit "LocalRdrEnv {")) 2 (vcat [ ptext (sLit "env =") <+> pprOccEnv ppr_elt env , ptext (sLit "in_scope =") <+> braces (pprWithCommas ppr (nameSetElems ns)) ] <+> char '}') where ppr_elt name = parens (ppr (getUnique (nameOccName name))) <+> ppr name -- So we can see if the keys line up correctly emptyLocalRdrEnv :: LocalRdrEnv emptyLocalRdrEnv = LRE { lre_env = emptyOccEnv, lre_in_scope = emptyNameSet } extendLocalRdrEnv :: LocalRdrEnv -> Name -> LocalRdrEnv -- The Name should be a non-top-level thing extendLocalRdrEnv (LRE { lre_env = env, lre_in_scope = ns }) name = WARN( isExternalName name, ppr name ) LRE { lre_env = extendOccEnv env (nameOccName name) name , lre_in_scope = extendNameSet ns name } extendLocalRdrEnvList :: LocalRdrEnv -> [Name] -> LocalRdrEnv extendLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) names = WARN( any isExternalName names, ppr names ) LRE { lre_env = extendOccEnvList env [(nameOccName n, n) | n <- names] , lre_in_scope = extendNameSetList ns names } lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name lookupLocalRdrEnv (LRE { lre_env = env }) (Unqual occ) = lookupOccEnv env occ lookupLocalRdrEnv _ _ = Nothing lookupLocalRdrOcc :: LocalRdrEnv -> OccName -> Maybe Name lookupLocalRdrOcc (LRE { lre_env = env }) occ = lookupOccEnv env occ elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool elemLocalRdrEnv rdr_name (LRE { lre_env = env, lre_in_scope = ns }) = case rdr_name of Unqual occ -> occ `elemOccEnv` env Exact name -> name `elemNameSet` ns -- See Note [Local bindings with Exact Names] Qual {} -> False Orig {} -> False localRdrEnvElts :: LocalRdrEnv -> [Name] localRdrEnvElts (LRE { lre_env = env }) = occEnvElts env inLocalRdrEnvScope :: Name -> LocalRdrEnv -> Bool -- This is the point of the NameSet inLocalRdrEnvScope name (LRE { lre_in_scope = ns }) = name `elemNameSet` ns delLocalRdrEnvList :: LocalRdrEnv -> [OccName] -> LocalRdrEnv delLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) occs = LRE { lre_env = delListFromOccEnv env occs , lre_in_scope = ns } {- Note [Local bindings with Exact Names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With Template Haskell we can make local bindings that have Exact Names. Computing shadowing etc may use elemLocalRdrEnv (at least it certainly does so in RnTpes.bindHsTyVars), so for an Exact Name we must consult the in-scope-name-set. ************************************************************************ * * GlobalRdrEnv * * ************************************************************************ -} type GlobalRdrEnv = OccEnv [GlobalRdrElt] -- ^ Keyed by 'OccName'; when looking up a qualified name -- we look up the 'OccName' part, and then check the 'Provenance' -- to see if the appropriate qualification is valid. This -- saves routinely doubling the size of the env by adding both -- qualified and unqualified names to the domain. -- -- The list in the codomain is required because there may be name clashes -- These only get reported on lookup, not on construction -- -- INVARIANT: All the members of the list have distinct -- 'gre_name' fields; that is, no duplicate Names -- -- INVARIANT: Imported provenance => Name is an ExternalName -- However LocalDefs can have an InternalName. This -- happens only when type-checking a [d| ... |] Template -- Haskell quotation; see this note in RnNames -- Note [Top-level Names in Template Haskell decl quotes] -- | An element of the 'GlobalRdrEnv' data GlobalRdrElt = GRE { gre_name :: Name, gre_par :: Parent, gre_prov :: Provenance -- ^ Why it's in scope } -- | The children of a Name are the things that are abbreviated by the ".." -- notation in export lists. See Note [Parents] data Parent = NoParent | ParentIs Name deriving (Eq) instance Outputable Parent where ppr NoParent = empty ppr (ParentIs n) = ptext (sLit "parent:") <> ppr n plusParent :: Parent -> Parent -> Parent -- See Note [Combining parents] plusParent (ParentIs n) p2 = hasParent n p2 plusParent p1 (ParentIs n) = hasParent n p1 plusParent _ _ = NoParent hasParent :: Name -> Parent -> Parent #ifdef DEBUG hasParent n (ParentIs n') | n /= n' = pprPanic "hasParent" (ppr n <+> ppr n') -- Parents should agree #endif hasParent n _ = ParentIs n {- Note [Parents] ~~~~~~~~~~~~~~~~~ Parent Children ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ data T Data constructors Record-field ids data family T Data constructors and record-field ids of all visible data instances of T class C Class operations Associated type constructors Note [Combining parents] ~~~~~~~~~~~~~~~~~~~~~~~~ With an associated type we might have module M where class C a where data T a op :: T a -> a instance C Int where data T Int = TInt instance C Bool where data T Bool = TBool Then: C is the parent of T T is the parent of TInt and TBool So: in an export list C(..) is short for C( op, T ) T(..) is short for T( TInt, TBool ) Module M exports everything, so its exports will be AvailTC C [C,T,op] AvailTC T [T,TInt,TBool] On import we convert to GlobalRdrElt and the combine those. For T that will mean we have one GRE with Parent C one GRE with NoParent That's why plusParent picks the "best" case. -} -- | make a 'GlobalRdrEnv' where all the elements point to the same -- Provenance (useful for "hiding" imports, or imports with -- no details). gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt] gresFromAvails prov avails = concatMap (gresFromAvail (const prov)) avails gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt] gresFromAvail prov_fn avail = [ GRE {gre_name = n, gre_par = mkParent n avail, gre_prov = prov_fn n} | n <- availNames avail ] where mkParent :: Name -> AvailInfo -> Parent mkParent _ (Avail _) = NoParent mkParent n (AvailTC m _) | n == m = NoParent | otherwise = ParentIs m emptyGlobalRdrEnv :: GlobalRdrEnv emptyGlobalRdrEnv = emptyOccEnv globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt] globalRdrEnvElts env = foldOccEnv (++) [] env instance Outputable GlobalRdrElt where ppr gre = hang (ppr (gre_name gre) <+> ppr (gre_par gre)) 2 (pprNameProvenance gre) pprGlobalRdrEnv :: Bool -> GlobalRdrEnv -> SDoc pprGlobalRdrEnv locals_only env = vcat [ ptext (sLit "GlobalRdrEnv") <+> ppWhen locals_only (ptext (sLit "(locals only)")) <+> lbrace , nest 2 (vcat [ pp (remove_locals gre_list) | gre_list <- occEnvElts env ] <+> rbrace) ] where remove_locals gres | locals_only = filter isLocalGRE gres | otherwise = gres pp [] = empty pp gres = hang (ppr occ <+> parens (ptext (sLit "unique") <+> ppr (getUnique occ)) <> colon) 2 (vcat (map ppr gres)) where occ = nameOccName (gre_name (head gres)) lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt] lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of Nothing -> [] Just gres -> gres lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt] lookupGRE_RdrName rdr_name env = case lookupOccEnv env (rdrNameOcc rdr_name) of Nothing -> [] Just gres -> pickGREs rdr_name gres lookupGRE_Name :: GlobalRdrEnv -> Name -> [GlobalRdrElt] lookupGRE_Name env name = [ gre | gre <- lookupGlobalRdrEnv env (nameOccName name), gre_name gre == name ] getGRE_NameQualifier_maybes :: GlobalRdrEnv -> Name -> [Maybe [ModuleName]] -- Returns all the qualifiers by which 'x' is in scope -- Nothing means "the unqualified version is in scope" -- [] means the thing is not in scope at all getGRE_NameQualifier_maybes env = map (qualifier_maybe . gre_prov) . lookupGRE_Name env where qualifier_maybe LocalDef = Nothing qualifier_maybe (Imported iss) = Just $ map (is_as . is_decl) iss isLocalGRE :: GlobalRdrElt -> Bool isLocalGRE (GRE {gre_prov = LocalDef}) = True isLocalGRE _ = False unQualOK :: GlobalRdrElt -> Bool -- ^ Test if an unqualifed version of this thing would be in scope unQualOK (GRE {gre_prov = LocalDef}) = True unQualOK (GRE {gre_prov = Imported is}) = any unQualSpecOK is pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt] -- ^ Take a list of GREs which have the right OccName -- Pick those GREs that are suitable for this RdrName -- And for those, keep only only the Provenances that are suitable -- Only used for Qual and Unqual, not Orig or Exact -- -- Consider: -- -- @ -- module A ( f ) where -- import qualified Foo( f ) -- import Baz( f ) -- f = undefined -- @ -- -- Let's suppose that @Foo.f@ and @Baz.f@ are the same entity really. -- The export of @f@ is ambiguous because it's in scope from the local def -- and the import. The lookup of @Unqual f@ should return a GRE for -- the locally-defined @f@, and a GRE for the imported @f@, with a /single/ -- provenance, namely the one for @Baz(f)@. pickGREs rdr_name gres | (_ : _ : _) <- candidates -- This is usually false, so we don't have to -- even look at internal_candidates , (gre : _) <- internal_candidates = [gre] -- For this internal_candidate stuff, -- see Note [Template Haskell binders in the GlobalRdrEnv] -- If there are multiple Internal candidates, pick the -- first one (ie with the (innermost binding) | otherwise = ASSERT2( isSrcRdrName rdr_name, ppr rdr_name ) candidates where candidates = mapMaybe pick gres internal_candidates = filter (isInternalName . gre_name) candidates rdr_is_unqual = isUnqual rdr_name rdr_is_qual = isQual_maybe rdr_name pick :: GlobalRdrElt -> Maybe GlobalRdrElt pick gre@(GRE {gre_prov = LocalDef, gre_name = n}) -- Local def | rdr_is_unqual = Just gre | Just (mod,_) <- rdr_is_qual -- Qualified name , Just n_mod <- nameModule_maybe n -- Binder is External , mod == moduleName n_mod = Just gre | otherwise = Nothing pick gre@(GRE {gre_prov = Imported [is]}) -- Single import (efficiency) | rdr_is_unqual, not (is_qual (is_decl is)) = Just gre | Just (mod,_) <- rdr_is_qual, mod == is_as (is_decl is) = Just gre | otherwise = Nothing pick gre@(GRE {gre_prov = Imported is}) -- Multiple import | null filtered_is = Nothing | otherwise = Just (gre {gre_prov = Imported filtered_is}) where filtered_is | rdr_is_unqual = filter (not . is_qual . is_decl) is | Just (mod,_) <- rdr_is_qual = filter ((== mod) . is_as . is_decl) is | otherwise = [] -- Building GlobalRdrEnvs plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv mkGlobalRdrEnv gres = foldr add emptyGlobalRdrEnv gres where add gre env = extendOccEnv_Acc insertGRE singleton env (nameOccName (gre_name gre)) gre insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt] insertGRE new_g [] = [new_g] insertGRE new_g (old_g : old_gs) | gre_name new_g == gre_name old_g = new_g `plusGRE` old_g : old_gs | otherwise = old_g : insertGRE new_g old_gs plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt -- Used when the gre_name fields match plusGRE g1 g2 = GRE { gre_name = gre_name g1, gre_prov = gre_prov g1 `plusProv` gre_prov g2, gre_par = gre_par g1 `plusParent` gre_par g2 } transformGREs :: (GlobalRdrElt -> GlobalRdrElt) -> [OccName] -> GlobalRdrEnv -> GlobalRdrEnv -- ^ Apply a transformation function to the GREs for these OccNames transformGREs trans_gre occs rdr_env = foldr trans rdr_env occs where trans occ env = case lookupOccEnv env occ of Just gres -> extendOccEnv env occ (map trans_gre gres) Nothing -> env extendGlobalRdrEnv :: Bool -> GlobalRdrEnv -> [AvailInfo] -> GlobalRdrEnv -- Extend with new LocalDef GREs from the AvailInfos. -- -- If do_shadowing is True, first remove name clashes between the new -- AvailInfos and the existing GlobalRdrEnv. -- This is used by the GHCi top-level -- -- E.g. Adding a LocalDef "x" when there is an existing GRE for Q.x -- should remove any unqualified import of Q.x, -- leaving only the qualified one -- -- However do *not* remove name clashes between the AvailInfos themselves, -- so that (say) data T = A | A -- will still give a duplicate-binding error. -- Same thing if there are multiple AvailInfos (don't remove clashes), -- though I'm not sure this ever happens with do_shadowing=True extendGlobalRdrEnv do_shadowing env avails = foldl add_avail env1 avails where names = concatMap availNames avails env1 | do_shadowing = foldl shadow_name env names | otherwise = env -- By doing the removal first, we ensure that the new AvailInfos -- don't shadow each other; that would conceal genuine errors -- E.g. in GHCi data T = A | A add_avail env avail = foldl (add_name avail) env (availNames avail) add_name avail env name = extendOccEnv_Acc (:) singleton env occ gre where occ = nameOccName name gre = GRE { gre_name = name , gre_par = mkParent name avail , gre_prov = LocalDef } shadow_name :: GlobalRdrEnv -> Name -> GlobalRdrEnv shadow_name env name = alterOccEnv (fmap alter_fn) env (nameOccName name) where alter_fn :: [GlobalRdrElt] -> [GlobalRdrElt] alter_fn gres = mapMaybe (shadow_with name) gres shadow_with :: Name -> GlobalRdrElt -> Maybe GlobalRdrElt shadow_with new_name old_gre@(GRE { gre_name = old_name, gre_prov = LocalDef }) = case (nameModule_maybe old_name, nameModule_maybe new_name) of (Nothing, _) -> Nothing (Just old_mod, Just new_mod) | new_mod == old_mod -> Nothing (Just old_mod, _) -> Just (old_gre { gre_prov = Imported [fake_imp_spec] }) where fake_imp_spec = ImpSpec id_spec ImpAll -- Urgh! old_mod_name = moduleName old_mod id_spec = ImpDeclSpec { is_mod = old_mod_name , is_as = old_mod_name , is_qual = True , is_dloc = nameSrcSpan old_name } shadow_with new_name old_gre@(GRE { gre_prov = Imported imp_specs }) | null imp_specs' = Nothing | otherwise = Just (old_gre { gre_prov = Imported imp_specs' }) where imp_specs' = mapMaybe (shadow_is new_name) imp_specs shadow_is :: Name -> ImportSpec -> Maybe ImportSpec shadow_is new_name is@(ImpSpec { is_decl = id_spec }) | Just new_mod <- nameModule_maybe new_name , is_as id_spec == moduleName new_mod = Nothing -- Shadow both qualified and unqualified | otherwise -- Shadow unqualified only = Just (is { is_decl = id_spec { is_qual = True } }) {- Note [Template Haskell binders in the GlobalRdrEnv] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For reasons described in Note [Top-level Names in Template Haskell decl quotes] in RnNames, a GRE with an Internal gre_name (i.e. one generated by a TH decl quote) should *shadow* a GRE with an External gre_name. Hence some faffing around in pickGREs and findLocalDupsRdrEnv -} findLocalDupsRdrEnv :: GlobalRdrEnv -> [Name] -> [[GlobalRdrElt]] -- ^ For each 'OccName', see if there are multiple local definitions -- for it; return a list of all such -- and return a list of the duplicate bindings findLocalDupsRdrEnv rdr_env occs = go rdr_env [] occs where go _ dups [] = dups go rdr_env dups (name:names) = case filter (pick name) gres of [] -> go rdr_env dups names [_] -> go rdr_env dups names -- The common case dup_gres -> go rdr_env' (dup_gres : dups) names where occ = nameOccName name gres = lookupOccEnv rdr_env occ `orElse` [] rdr_env' = delFromOccEnv rdr_env occ -- The delFromOccEnv avoids repeating the same -- complaint twice, when names itself has a duplicate -- which is a common case -- See Note [Template Haskell binders in the GlobalRdrEnv] pick name (GRE { gre_name = n, gre_prov = LocalDef }) | isInternalName name = isInternalName n | otherwise = True pick _ _ = False {- ************************************************************************ * * Provenance * * ************************************************************************ -} -- | The 'Provenance' of something says how it came to be in scope. -- It's quite elaborate so that we can give accurate unused-name warnings. data Provenance = LocalDef -- ^ The thing was defined locally | Imported [ImportSpec] -- ^ The thing was imported. -- -- INVARIANT: the list of 'ImportSpec' is non-empty data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec, is_item :: ImpItemSpec } deriving( Eq, Ord ) -- | Describes a particular import declaration and is -- shared among all the 'Provenance's for that decl data ImpDeclSpec = ImpDeclSpec { is_mod :: ModuleName, -- ^ Module imported, e.g. @import Muggle@ -- Note the @Muggle@ may well not be -- the defining module for this thing! -- TODO: either should be Module, or there -- should be a Maybe PackageKey here too. is_as :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause) is_qual :: Bool, -- ^ Was this import qualified? is_dloc :: SrcSpan -- ^ The location of the entire import declaration } -- | Describes import info a particular Name data ImpItemSpec = ImpAll -- ^ The import had no import list, -- or had a hiding list | ImpSome { is_explicit :: Bool, is_iloc :: SrcSpan -- Location of the import item } -- ^ The import had an import list. -- The 'is_explicit' field is @True@ iff the thing was named -- /explicitly/ in the import specs rather -- than being imported as part of a "..." group. Consider: -- -- > import C( T(..) ) -- -- Here the constructors of @T@ are not named explicitly; -- only @T@ is named explicitly. unQualSpecOK :: ImportSpec -> Bool -- ^ Is in scope unqualified? unQualSpecOK is = not (is_qual (is_decl is)) qualSpecOK :: ModuleName -> ImportSpec -> Bool -- ^ Is in scope qualified with the given module? qualSpecOK mod is = mod == is_as (is_decl is) importSpecLoc :: ImportSpec -> SrcSpan importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl importSpecLoc (ImpSpec _ item) = is_iloc item importSpecModule :: ImportSpec -> ModuleName importSpecModule is = is_mod (is_decl is) isExplicitItem :: ImpItemSpec -> Bool isExplicitItem ImpAll = False isExplicitItem (ImpSome {is_explicit = exp}) = exp -- Note [Comparing provenance] -- Comparison of provenance is just used for grouping -- error messages (in RnEnv.warnUnusedBinds) instance Eq Provenance where p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False instance Eq ImpDeclSpec where p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False instance Eq ImpItemSpec where p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False instance Ord Provenance where compare LocalDef LocalDef = EQ compare LocalDef (Imported _) = LT compare (Imported _ ) LocalDef = GT compare (Imported is1) (Imported is2) = compare (head is1) {- See Note [Comparing provenance] -} (head is2) instance Ord ImpDeclSpec where compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp` (is_dloc is1 `compare` is_dloc is2) instance Ord ImpItemSpec where compare is1 is2 = is_iloc is1 `compare` is_iloc is2 plusProv :: Provenance -> Provenance -> Provenance -- Choose LocalDef over Imported -- There is an obscure bug lurking here; in the presence -- of recursive modules, something can be imported *and* locally -- defined, and one might refer to it with a qualified name from -- the import -- but I'm going to ignore that because it makes -- the isLocalGRE predicate so much nicer this way plusProv LocalDef LocalDef = panic "plusProv" plusProv LocalDef _ = LocalDef plusProv _ LocalDef = LocalDef plusProv (Imported is1) (Imported is2) = Imported (is1++is2) pprNameProvenance :: GlobalRdrElt -> SDoc -- ^ Print out the place where the name was imported pprNameProvenance (GRE {gre_name = name, gre_prov = LocalDef}) = ptext (sLit "defined at") <+> ppr (nameSrcLoc name) pprNameProvenance (GRE {gre_name = name, gre_prov = Imported whys}) = case whys of (why:_) | opt_PprStyle_Debug -> vcat (map pp_why whys) | otherwise -> pp_why why [] -> panic "pprNameProvenance" where pp_why why = sep [ppr why, ppr_defn_site why name] -- If we know the exact definition point (which we may do with GHCi) -- then show that too. But not if it's just "imported from X". ppr_defn_site :: ImportSpec -> Name -> SDoc ppr_defn_site imp_spec name | same_module && not (isGoodSrcSpan loc) = empty -- Nothing interesting to say | otherwise = parens $ hang (ptext (sLit "and originally defined") <+> pp_mod) 2 (pprLoc loc) where loc = nameSrcSpan name defining_mod = nameModule name same_module = importSpecModule imp_spec == moduleName defining_mod pp_mod | same_module = empty | otherwise = ptext (sLit "in") <+> quotes (ppr defining_mod) instance Outputable ImportSpec where ppr imp_spec = ptext (sLit "imported") <+> qual <+> ptext (sLit "from") <+> quotes (ppr (importSpecModule imp_spec)) <+> pprLoc (importSpecLoc imp_spec) where qual | is_qual (is_decl imp_spec) = ptext (sLit "qualified") | otherwise = empty pprLoc :: SrcSpan -> SDoc pprLoc (RealSrcSpan s) = ptext (sLit "at") <+> ppr s pprLoc (UnhelpfulSpan {}) = empty
green-haskell/ghc
compiler/basicTypes/RdrName.hs
bsd-3-clause
36,400
0
16
10,219
7,365
3,920
3,445
472
5
module Board ( Board (..) , mkBoard , isEmptyCell , isValidUnit , lockUnit , clearFullRows ) where import Control.Arrow ((&&&)) import Data.Ix (inRange,range) import Data.List (foldl') import Data.Set (Set(..)) import qualified Data.Set as Set import Cell import Unit import Types data Board = Board { cols :: Number, rows :: Number, fulls :: Set Cell } deriving (Show,Eq) mkBoard :: Number -> Number -> [Cell] -> Board mkBoard width height cs = Board { cols = width, rows = height, fulls = Set.fromList cs } isEmptyCell :: Board -> Cell -> Bool isEmptyCell b c = c `Set.notMember` fulls b isValidUnit :: Board -> Unit -> Bool isValidUnit b u = notBatting && withinRange where notBatting = Set.null $ fs `Set.intersection` cs withinRange = all (inRange (cell (0,0), cell (cols b -1, rows b -1))) (Set.toList cs) fs = fulls b cs = members u lockUnit :: Board -> Unit -> Board lockUnit b u = b { fulls = fulls b `Set.union` members u } findFullRows :: Board -> [Number] findFullRows b = filter fullRow [0 .. h-1] where w = cols b h = rows b fs = fulls b -- fullRow r = Set.size (Set.filter ((r==) . y) fs) == w fullRow r = b1 && b2 && Set.size fs2 == w-2 where (_,b1,fs1) = Set.splitMember (Cell 0 r) fs (fs2,b2,_) = Set.splitMember (Cell (w-1) r) fs1 clearFullRows :: Board -> (Int, Board) clearFullRows b = (length &&& foldl' clearRow b) cleared where cleared = findFullRows b clearRow :: Board -> Number -> Board clearRow b r = case Set.split (Cell { x = 0, y = r }) fs of (ps,qs) -> b { fulls = Set.mapMonotonic (\ c -> c { y = y c + 1 }) ps `Set.union` qs } where fs = Set.filter ((r /=) . y) (fulls b) -- sampleBoard :: Board sampleBoard = Board { cols = 5, rows = 10 , fulls = Set.fromList (range (cell (1,0), cell (3,4))) `Set.union` Set.fromList (range (cell (0,1),cell (4,3))) }
msakai/icfpc2015
src/Board.hs
bsd-3-clause
1,995
0
17
545
854
476
378
49
1
{-# LANGUAGE DoAndIfThenElse #-} module Term(Term(..), TermClass(..), Substitution(..), parse, act, makeUniqueVars, betaReduction) where import Text.Parsec hiding (parse) import qualified Text.Parsec as Parsec import Control.Applicative hiding ((<|>)) import Control.Monad import Data.List import VarEnvironment data Substitution a = AssignTo String a deriving Show instance Functor Substitution where fmap f (x `AssignTo` t) = x `AssignTo` f t class TermClass t where freeVars :: t -> [String] substitute :: Substitution t -> t -> t substituteAll :: (Eq t) => [Substitution t] -> t -> t substituteAll subs t = if t == t' then t else substituteAll subs t' where t' = foldr substitute t subs data Term = Lambda String Term | App Term Term | Var String instance Eq Term where (Var x) == (Var y) = x == y (App n1 m1) == (App n2 m2) = n1 == n2 && m1 == m2 (Lambda x n) == (Lambda y m) | x == y = n == m | otherwise = n == substitute (y `AssignTo` Var x) m _ == _ = False instance TermClass Term where freeVars (Lambda x t) = filter (/= x) $ freeVars t freeVars (App x y) = nub $ freeVars x ++ freeVars y freeVars (Var x) = [x] substitute (v `AssignTo` t) (Var x) | v == x = t | otherwise = Var x substitute (v `AssignTo` t) (App x y) = App (substitute (v `AssignTo` t) x) (substitute (v `AssignTo` t) y) substitute (v `AssignTo` t) (Lambda x y) | v == x = Lambda x y | otherwise = Lambda x (substitute (v `AssignTo` t) y) act :: Term -> [String] act (Var _) = [] act (Lambda x m) = x : act m act (App m _) | null (act m) = [] | otherwise = tail (act m) betaReduction :: Term -> Term betaReduction t = evalInEnvironment (freeVars t) (betaReduction' <$> makeUniqueVars t) where betaReduction' (Lambda x n `App` m) = betaReduction' $ substitute (x `AssignTo` m) n betaReduction' (Var x) = Var x betaReduction' (Lambda x n) = Lambda x $ betaReduction' n betaReduction' (App n m) = let n' = betaReduction' n in if n == n' then App n $ betaReduction' m else betaReduction' (App n' m) makeUniqueVars :: Term -> Environment Term makeUniqueVars t = do mapM_ addToEnvironment $ freeVars t go t where go (Var x) = return $ Var x go (App m n) = App <$> go m <*> go n go (Lambda x m) = do (x', m') <- renameVariable x m addToEnvironment x' Lambda x' <$> go m' renameVariable x m = do inEnv <- inEnvironment x if inEnv then do y <- newVar "var" return (y, substitute (x `AssignTo` Var y) m) else return (x, m) ------ Printing ------ brackets :: Int -> String -> String brackets p str = if p > 0 then "(" ++ str ++ ")" else str lambdaSymb :: String lambdaSymb = "λ" --lambdaSymb = "\\" showTerm :: Int -> Term -> String showTerm _ (Var x) = x showTerm prec (App t1 t2) = brackets (prec - 1) (showTerm 1 t1 ++ " " ++ showTerm 2 t2) showTerm prec t@(Lambda _ _) = brackets prec $ lambdaSymb ++ showLambda t where showLambda (Lambda x n@(Lambda _ _)) = x ++ " " ++ showLambda n showLambda (Lambda x n) = x ++ ". " ++ showTerm 0 n showLambda _ = error "showLambda: Argument is not Lambda. Couldn't happen." instance Show Term where show = showTerm 0 ------ Parsing ------ type Parser = Parsec String () varname :: Parser String varname = many1 (alphaNum <|> oneOf "_") bracketExpr :: Parser Term -> Parser Term bracketExpr = between (char '(' *> spaces) (spaces *> char ')') lambdaExpr :: Parser Term lambdaExpr = do void $ char '\\' <|> char 'λ' spaces vs <- many1 (varname <* spaces) void $ char '.' spaces t <- termExpr return $ foldr Lambda t vs termExpr :: Parser Term termExpr = try appExpr <|> noAppTermExpr noAppTermExpr :: Parser Term noAppTermExpr = choice [ lambdaExpr -- Precedes variable parser because λ is a proper variable name , Var <$> varname , bracketExpr termExpr ] appExpr :: Parser Term appExpr = do t1 <- noAppTermExpr ts <- many1 (spaces *> noAppTermExpr) return $ foldl App t1 ts fullExpr :: Parser Term fullExpr = spaces *> termExpr <* spaces <* eof parse :: String -> Either ParseError Term parse = Parsec.parse fullExpr ""
projedi/type-inference-rank2
src/Term.hs
bsd-3-clause
4,308
0
17
1,124
1,794
908
886
115
5
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-} module FreeAgentSpec (main, spec) where import FreeAgent.AgentPrelude import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = describe "FreeAgent" $ do it "goes out in the world and does a thing" $ True `shouldBe` True
jeremyjh/free-agent
core/test/FreeAgentSpec.hs
bsd-3-clause
334
0
10
92
74
41
33
11
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.UI.GLUT.Callbacks -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/GLUT/LICENSE) -- -- Maintainer : [email protected] -- Stability : stable -- Portability : portable -- -- -- GLUT supports a number of callbacks to respond to events. There are three -- types of callbacks: window, menu, and global. Window callbacks indicate when -- to redisplay or reshape a window, when the visibility of the window changes, -- and when input is available for the window. Menu callbacks are described in -- "Graphics.UI.GLUT.Menu". The global callbacks manage the passing of time and -- menu usage. The calling order of callbacks between different windows is -- undefined. -- -- Callbacks for input events should be delivered to the window the event occurs -- in. Events should not propagate to parent windows. -- -- A callback of type @Foo@ can registered by setting @fooCallback@ to 'Just' -- the callback. Almost all callbacks can be de-registered by setting -- the corresponding @fooCallback@ to 'Nothing', the only exceptions being -- 'Graphics.UI.GLUT.Callbacks.Window.DisplayCallback' (can only be -- re-registered) and 'Graphics.UI.GLUT.Callbacks.Global.TimerCallback' (can\'t -- be unregistered). -- -- /X Implementation Notes:/ The X GLUT implementation uses the X Input -- extension to support sophisticated input devices: Spaceball, dial & button -- box, and digitizing tablet. Because the X Input extension does not mandate -- how particular types of devices are advertised through the extension, it is -- possible GLUT for X may not correctly support input devices that would -- otherwise be of the correct type. The X GLUT implementation will support the -- Silicon Graphics Spaceball, dial & button box, and digitizing tablet as -- advertised through the X Input extension. -- -------------------------------------------------------------------------------- module Graphics.UI.GLUT.Callbacks ( module Graphics.UI.GLUT.Callbacks.Window, module Graphics.UI.GLUT.Callbacks.Global ) where import Graphics.UI.GLUT.Callbacks.Window import Graphics.UI.GLUT.Callbacks.Global
FranklinChen/hugs98-plus-Sep2006
packages/GLUT/Graphics/UI/GLUT/Callbacks.hs
bsd-3-clause
2,245
0
5
329
83
72
11
5
0
{-# LANGUAGE OverloadedStrings #-} -- | XSD @dateTime@ data structure <http://www.w3.org/TR/xmlschema-2/#dateTime> module Text.XML.XSD.DateTime ( DateTime(..) , isZoned , isUnzoned , dateTime' , dateTime , toText , fromZonedTime , toUTCTime , fromUTCTime , toLocalTime , fromLocalTime , utcTime' , utcTime , localTime' , localTime ) where import Control.Applicative (pure, (<$>), (*>), (<|>)) import Control.Monad (when) import Data.Attoparsec.Text (Parser, char, digit) import qualified Data.Attoparsec.Text as A import Data.Char (isDigit, ord) import Data.Fixed (Pico, showFixed) import Data.Maybe (maybeToList) import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as TB import qualified Data.Text.Lazy.Builder.Int as TBI import qualified Data.Text.Read as TR import Data.Time import Data.Time.Calendar.MonthDay (monthLength) -- | XSD @dateTime@ data structure -- <http://www.w3.org/TR/xmlschema-2/#dateTime>. Briefly, a @dateTime@ -- uses the Gregorian calendar and may or may not have an associated -- timezone. If it has a timezone, then the canonical representation -- of that date time is in UTC. -- -- Note, it is not possible to establish a total order on @dateTime@ -- since non-timezoned are considered to belong to some unspecified -- timezone. data DateTime = DtZoned UTCTime | DtUnzoned LocalTime deriving (Eq) -- | Internal helper that creates a date time. Note, if the given hour -- is 24 then the minutes and seconds are assumed to be 0. mkDateTime :: Integer -- ^ Year -> Int -- ^ Month -> Int -- ^ Day -> Int -- ^ Hours -> Int -- ^ Minutes -> Pico -- ^ Seconds -> Maybe Pico -- ^ Time zone offset -> DateTime mkDateTime y m d hh mm ss mz = case mz of Just z -> DtZoned $ addUTCTime (negate $ realToFrac z) uTime Nothing -> DtUnzoned lTime where day = addDays (if hh == 24 then 1 else 0) (fromGregorian y m d) tod = TimeOfDay (if hh == 24 then 0 else hh) mm ss lTime = LocalTime day tod uTime = UTCTime day (timeOfDayToTime tod) instance Show DateTime where show = T.unpack . toText instance Read DateTime where readList s = [(maybeToList (dateTime . T.pack $ s), [])] -- | Parses the string into a @dateTime@ or may fail with a parse error. dateTime' :: Text -> Either String DateTime dateTime' = A.parseOnly (parseDateTime <|> fail "bad date time") -- | Parses the string into a @dateTime@ or may fail. dateTime :: Text -> Maybe DateTime dateTime = either (const Nothing) Just . dateTime' toText :: DateTime -> Text toText = TL.toStrict . TB.toLazyText . dtBuilder where dtBuilder (DtZoned uTime) = ltBuilder (utcToLocalTime utc uTime) <> "Z" dtBuilder (DtUnzoned lTime) = ltBuilder lTime ltBuilder (LocalTime day (TimeOfDay hh mm sss)) = let (y, m, d) = toGregorian day in buildInt4 y <> "-" <> buildUInt2 m <> "-" <> buildUInt2 d <> "T" <> buildUInt2 hh <> ":" <> buildUInt2 mm <> ":" <> buildSeconds sss buildInt4 :: Integer -> TB.Builder buildInt4 year = let absYear = abs year k x = if absYear < x then ("0" <>) else id in k 1000 . k 100 . k 10 $ TBI.decimal year buildUInt2 :: Int -> TB.Builder buildUInt2 x = (if x < 10 then ("0" <>) else id) $ TBI.decimal x buildSeconds :: Pico -> TB.Builder buildSeconds secs = (if secs < 10 then ("0" <>) else id) $ TB.fromString (showFixed True secs) -- | Converts a zoned time to a @dateTime@. fromZonedTime :: ZonedTime -> DateTime fromZonedTime = fromUTCTime . zonedTimeToUTC -- | Whether the given @dateTime@ is timezoned. isZoned :: DateTime -> Bool isZoned (DtZoned _) = True isZoned (DtUnzoned _) = False -- | Whether the given @dateTime@ is non-timezoned. isUnzoned :: DateTime -> Bool isUnzoned = not . isZoned -- | Attempts to convert a @dateTime@ to a UTC time. The attempt fails -- if the given @dateTime@ is non-timezoned. toUTCTime :: DateTime -> Maybe UTCTime toUTCTime (DtZoned time) = Just time toUTCTime _ = Nothing -- | Converts a UTC time to a timezoned @dateTime@. fromUTCTime :: UTCTime -> DateTime fromUTCTime = DtZoned -- | Attempts to convert a @dateTime@ to a local time. The attempt -- fails if the given @dateTime@ is timezoned. toLocalTime :: DateTime -> Maybe LocalTime toLocalTime (DtUnzoned time) = Just time toLocalTime _ = Nothing -- | Converts a local time to an non-timezoned @dateTime@. fromLocalTime :: LocalTime -> DateTime fromLocalTime = DtUnzoned -- | Parses the string in a @dateTime@ then converts to a UTC time and -- may fail with a parse error. utcTime' :: Text -> Either String UTCTime utcTime' txt = dateTime' txt >>= maybe (Left err) Right . toUTCTime where err = "input time is non-timezoned" -- | Parses the string in a @dateTime@ then converts to a UTC time and -- may fail. utcTime :: Text -> Maybe UTCTime utcTime txt = dateTime txt >>= toUTCTime -- | Parses the string in a @dateTime@ then converts to a local time -- and may fail with a parse error. localTime' :: Text -> Either String LocalTime localTime' txt = dateTime' txt >>= maybe (Left err) Right . toLocalTime where err = "input time is non-timezoned" -- | Parses the string in a @dateTime@ then converts to a local time -- time and may fail. localTime :: Text -> Maybe LocalTime localTime txt = dateTime txt >>= toLocalTime -- | Parser of the @dateTime@ lexical representation. parseDateTime :: Parser DateTime parseDateTime = do yy <- yearParser _ <- char '-' mm <- p2imax 12 _ <- char '-' dd <- p2imax (monthLength (isLeapYear $ fromIntegral yy) mm) _ <- char 'T' hhh <- p2imax 24 _ <- char ':' mmm <- p2imax 59 _ <- char ':' sss <- secondParser when (hhh == 24 && (mmm /= 0 || sss /= 0)) $ fail "invalid time, past 24:00:00" o <- parseOffset return $ mkDateTime yy mm dd hhh mmm sss o -- | Parse timezone offset. parseOffset :: Parser (Maybe Pico) parseOffset = (A.endOfInput *> pure Nothing) <|> (char 'Z' *> pure (Just 0)) <|> (do sign <- (char '+' *> pure 1) <|> (char '-' *> pure (-1)) hh <- fromIntegral <$> p2imax 14 _ <- char ':' mm <- fromIntegral <$> p2imax (if hh == 14 then 0 else 59) return . Just $ sign * (hh * 3600 + mm * 60)) yearParser :: Parser Integer yearParser = do sign <- (char '-' *> pure (-1)) <|> pure 1 ds <- A.takeWhile isDigit when (T.length ds < 4) $ fail "need at least four digits in year" when (T.length ds > 4 && T.head ds == '0') $ fail "leading zero in year" let Right (absyear, _) = TR.decimal ds when (absyear == 0) $ fail "year zero disallowed" return $ sign * absyear secondParser :: Parser Pico secondParser = do d1 <- digit d2 <- digit frac <- readFrac <$> (char '.' *> A.takeWhile isDigit) <|> pure 0 return (read [d1, d2] + frac) where readFrac ds = read $ '0' : '.' : T.unpack ds p2imax :: Int -> Parser Int p2imax m = do a <- digit b <- digit let n = 10 * val a + val b if n > m then fail $ "value " ++ show n ++ " exceeded maximum " ++ show m else return n where val c = ord c - ord '0'
skogsbaer/xsd
Text/XML/XSD/DateTime.hs
bsd-3-clause
8,178
0
19
2,577
2,107
1,099
1,008
166
4
{-# LANGUAGE FlexibleContexts #-} module Data.Stack ( Stack , evalStack , push , pop ) where import Control.Applicative import Control.Monad.State.Strict type Stack a = State [a] pop :: (Applicative m, MonadState [a] m) => m a pop = gets head <* modify tail push :: (Applicative m, MonadState [a] m) => a -> m () push a = modify (a:) evalStack = evalState
kirbyfan64/sodium
src/Data/Stack.hs
bsd-3-clause
367
4
8
74
147
83
64
14
1
-- !!! Testing Read (assuming that Eq, Show and Enum work!) module TestRead where import Ratio(Ratio,Rational,(%)) import List(zip4,zip5,zip6,zip7) import Char(isLatin1) -- test that expected equality holds tst :: (Read a, Show a, Eq a) => a -> Bool tst x = read (show x) == x -- measure degree of error diff :: (Read a, Show a, Num a) => a -> a diff x = read (show x) - x ---------------------------------------------------------------- -- Tests for hand-written instances ---------------------------------------------------------------- test1 = tst () test2 = all tst [False,True] test3 = all tst $ takeWhile isLatin1 [minBound::Char ..] test4 = all tst [Nothing, Just (Just True)] test5 = all tst [Left True, Right (Just True)] test6 = all tst [LT .. GT] test7 = all tst [[],['a'..'z'],['A'..'Z']] test8 = all tst $ [minBound,maxBound] ++ [-100..100 :: Int] test9 = all tst $ [(fromIntegral (minBound::Int))-1, (fromIntegral (maxBound::Int))+1] ++ [-100..100 :: Integer] -- we don't test fractional Floats/Doubles because they don't work test10 = all tst $ [-100..100 :: Float] test11 = all tst $ [-100..100 :: Double] test12 = all tst $ [-2%2,-1%2,0%2,1%2,2%2] ++ [-10.0,-9.9..10.0 :: Ratio Int] test13 = all tst $ [-2%2,-1%2,0%2,1%2,2%2] ++ [-10.0,-9.9..10.0 :: Rational] ---------------------------------------------------------------- -- Tests for derived instances ---------------------------------------------------------------- -- Tuples test21 = all tst $ [-1..1] test22 = all tst $ zip [-1..1] [-1..1] test23 = all tst $ zip3 [-1..1] [-1..1] [-1..1] test24 = all tst $ zip4 [-1..1] [-1..1] [-1..1] [-1..1] test25 = all tst $ zip5 [-1..1] [-1..1] [-1..1] [-1..1] [-1..1] {- Not derived automatically test26 = all tst $ zip6 [-1..1] [-1..1] [-1..1] [-1..1] [-1..1] [-1..1] test27 = all tst $ zip7 [-1..1] [-1..1] [-1..1] [-1..1] [-1..1] [-1..1] [-1..1] -} -- Enumeration data T1 = C1 | C2 | C3 | C4 | C5 | C6 | C7 deriving (Eq, Enum, Read, Show) test30 = all tst [C1 .. C7] -- Records data T2 = A Int | B {x,y::Int, z::Bool} | C Bool deriving (Eq, Read, Show) test31 = all tst [A 1, B 1 2 True, C True] -- newtype newtype T3 = T3 Int deriving (Eq, Read, Show) test32 = all tst [ T3 i | i <- [-10..10] ] ---------------------------------------------------------------- -- Random tests for things which have failed in the past ---------------------------------------------------------------- test100 = read "(True)" :: Bool test101 = tst (pi :: Float) test102 = diff (pi :: Float) test103 = tst (pi :: Double) test104 = diff (pi :: Double)
FranklinChen/Hugs
tests/rts/read.hs
bsd-3-clause
2,665
0
11
521
1,056
589
467
44
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE DeriveFunctor #-} -- | Abstract Haskell syntax for expressions. module HsExpr where #include "HsVersions.h" -- friends: import GhcPrelude import HsDecls import HsPat import HsLit import PlaceHolder ( NameOrRdrName ) import HsExtension import HsTypes import HsBinds -- others: import TcEvidence import CoreSyn import DynFlags ( gopt, GeneralFlag(Opt_PrintExplicitCoercions) ) import Name import NameSet import RdrName ( GlobalRdrEnv ) import BasicTypes import ConLike import SrcLoc import Util import Outputable import FastString import Type -- libraries: import Data.Data hiding (Fixity(..)) import qualified Data.Data as Data (Fixity(..)) import Data.Maybe (isNothing) import GHCi.RemoteTypes ( ForeignRef ) import qualified Language.Haskell.TH as TH (Q) {- ************************************************************************ * * \subsection{Expressions proper} * * ************************************************************************ -} -- * Expressions proper -- | Located Haskell Expression type LHsExpr p = Located (HsExpr p) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when -- in a list -- For details on above see note [Api annotations] in ApiAnnotation ------------------------- -- | Post-Type checking Expression -- -- PostTcExpr is an evidence expression attached to the syntax tree by the -- type checker (c.f. postTcType). type PostTcExpr = HsExpr GhcTc -- | Post-Type checking Table -- -- We use a PostTcTable where there are a bunch of pieces of evidence, more -- than is convenient to keep individually. type PostTcTable = [(Name, PostTcExpr)] noPostTcExpr :: PostTcExpr noPostTcExpr = HsLit (HsString noSourceText (fsLit "noPostTcExpr")) noPostTcTable :: PostTcTable noPostTcTable = [] ------------------------- -- | Syntax Expression -- -- SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier, -- by the renamer. It's used for rebindable syntax. -- -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for -- @(>>=)@, and then instantiated by the type checker with its type args -- etc -- -- This should desugar to -- -- > syn_res_wrap $ syn_expr (syn_arg_wraps[0] arg0) -- > (syn_arg_wraps[1] arg1) ... -- -- where the actual arguments come from elsewhere in the AST. -- This could be defined using @PostRn@ and @PostTc@ and such, but it's -- harder to get it all to work out that way. ('noSyntaxExpr' is hard to -- write, for example.) data SyntaxExpr p = SyntaxExpr { syn_expr :: HsExpr p , syn_arg_wraps :: [HsWrapper] , syn_res_wrap :: HsWrapper } deriving instance (DataId p) => Data (SyntaxExpr p) -- | This is used for rebindable-syntax pieces that are too polymorphic -- for tcSyntaxOp (trS_fmap and the mzip in ParStmt) noExpr :: SourceTextX p => HsExpr p noExpr = HsLit (HsString (sourceText "noExpr") (fsLit "noExpr")) noSyntaxExpr :: SourceTextX p => SyntaxExpr p -- Before renaming, and sometimes after, -- (if the syntax slot makes no sense) noSyntaxExpr = SyntaxExpr { syn_expr = HsLit (HsString noSourceText (fsLit "noSyntaxExpr")) , syn_arg_wraps = [] , syn_res_wrap = WpHole } -- | Make a 'SyntaxExpr Name' (the "rn" is because this is used in the -- renamer), missing its HsWrappers. mkRnSyntaxExpr :: Name -> SyntaxExpr GhcRn mkRnSyntaxExpr name = SyntaxExpr { syn_expr = HsVar $ noLoc name , syn_arg_wraps = [] , syn_res_wrap = WpHole } -- don't care about filling in syn_arg_wraps because we're clearly -- not past the typechecker instance (SourceTextX p, OutputableBndrId p) => Outputable (SyntaxExpr p) where ppr (SyntaxExpr { syn_expr = expr , syn_arg_wraps = arg_wraps , syn_res_wrap = res_wrap }) = sdocWithDynFlags $ \ dflags -> getPprStyle $ \s -> if debugStyle s || gopt Opt_PrintExplicitCoercions dflags then ppr expr <> braces (pprWithCommas ppr arg_wraps) <> braces (ppr res_wrap) else ppr expr -- | Command Syntax Table (for Arrow syntax) type CmdSyntaxTable p = [(Name, HsExpr p)] -- See Note [CmdSyntaxTable] {- Note [CmdSyntaxtable] ~~~~~~~~~~~~~~~~~~~~~ Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps track of the methods needed for a Cmd. * Before the renamer, this list is an empty list * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@ For example, for the 'arr' method * normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr) * with rebindable syntax: (GHC.Control.Arrow.arr, arr_22) where @arr_22@ is whatever 'arr' is in scope * After the type checker, it takes the form [(std_name, <expression>)] where <expression> is the evidence for the method. This evidence is instantiated with the class, but is still polymorphic in everything else. For example, in the case of 'arr', the evidence has type forall b c. (b->c) -> a b c where 'a' is the ambient type of the arrow. This polymorphism is important because the desugarer uses the same evidence at multiple different types. This is Less Cool than what we normally do for rebindable syntax, which is to make fully-instantiated piece of evidence at every use site. The Cmd way is Less Cool because * The renamer has to predict which methods are needed. See the tedious RnExpr.methodNamesCmd. * The desugarer has to know the polymorphic type of the instantiated method. This is checked by Inst.tcSyntaxName, but is less flexible than the rest of rebindable syntax, where the type is less pre-ordained. (And this flexibility is useful; for example we can typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.) -} -- | An unbound variable; used for treating out-of-scope variables as -- expression holes data UnboundVar = OutOfScope OccName GlobalRdrEnv -- ^ An (unqualified) out-of-scope -- variable, together with the GlobalRdrEnv -- with respect to which it is unbound -- See Note [OutOfScope and GlobalRdrEnv] | TrueExprHole OccName -- ^ A "true" expression hole (_ or _x) deriving Data instance Outputable UnboundVar where ppr (OutOfScope occ _) = text "OutOfScope" <> parens (ppr occ) ppr (TrueExprHole occ) = text "ExprHole" <> parens (ppr occ) unboundVarOcc :: UnboundVar -> OccName unboundVarOcc (OutOfScope occ _) = occ unboundVarOcc (TrueExprHole occ) = occ {- Note [OutOfScope and GlobalRdrEnv] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To understand why we bundle a GlobalRdrEnv with an out-of-scope variable, consider the following module: module A where foo :: () foo = bar bat :: [Double] bat = [1.2, 3.4] $(return []) bar = () bad = False When A is compiled, the renamer determines that `bar` is not in scope in the declaration of `foo` (since `bar` is declared in the following inter-splice group). Once it has finished typechecking the entire module, the typechecker then generates the associated error message, which specifies both the type of `bar` and a list of possible in-scope alternatives: A.hs:6:7: error: • Variable not in scope: bar :: () • ‘bar’ (line 13) is not in scope before the splice on line 11 Perhaps you meant ‘bat’ (line 9) When it calls RnEnv.unknownNameSuggestions to identify these alternatives, the typechecker must provide a GlobalRdrEnv. If it provided the current one, which contains top-level declarations for the entire module, the error message would incorrectly suggest the out-of-scope `bar` and `bad` as possible alternatives for `bar` (see Trac #11680). Instead, the typechecker must use the same GlobalRdrEnv the renamer used when it determined that `bar` is out-of-scope. To obtain this GlobalRdrEnv, can the typechecker simply use the out-of-scope `bar`'s location to either reconstruct it (from the current GlobalRdrEnv) or to look it up in some global store? Unfortunately, no. The problem is that location information is not always sufficient for this task. This is most apparent when dealing with the TH function addTopDecls, which adds its declarations to the FOLLOWING inter-splice group. Consider these declarations: ex9 = cat -- cat is NOT in scope here $(do ------------------------------------------------------------- ds <- [d| f = cab -- cat and cap are both in scope here cat = () |] addTopDecls ds [d| g = cab -- only cap is in scope here cap = True |]) ex10 = cat -- cat is NOT in scope here $(return []) ----------------------------------------------------- ex11 = cat -- cat is in scope Here, both occurrences of `cab` are out-of-scope, and so the typechecker needs the GlobalRdrEnvs which were used when they were renamed. These GlobalRdrEnvs are different (`cat` is present only in the GlobalRdrEnv for f's `cab'), but the locations of the two `cab`s are the same (they are both created in the same splice). Thus, we must include some additional information with each `cab` to allow the typechecker to obtain the correct GlobalRdrEnv. Clearly, the simplest information to use is the GlobalRdrEnv itself. -} -- | A Haskell expression. data HsExpr p = HsVar (Located (IdP p)) -- ^ Variable -- See Note [Located RdrNames] | HsUnboundVar UnboundVar -- ^ Unbound variable; also used for "holes" -- (_ or _x). -- Turned from HsVar to HsUnboundVar by the -- renamer, when it finds an out-of-scope -- variable or hole. -- Turned into HsVar by type checker, to support -- deferred type errors. | HsConLikeOut ConLike -- ^ After typechecker only; must be different -- HsVar for pretty printing | HsRecFld (AmbiguousFieldOcc p) -- ^ Variable pointing to record selector -- Not in use after typechecking | HsOverLabel (Maybe (IdP p)) FastString -- ^ Overloaded label (Note [Overloaded labels] in GHC.OverloadedLabels) -- @Just id@ means @RebindableSyntax@ is in use, and gives the id of the -- in-scope 'fromLabel'. -- NB: Not in use after typechecking | HsIPVar HsIPName -- ^ Implicit parameter (not in use after typechecking) | HsOverLit (HsOverLit p) -- ^ Overloaded literals | HsLit (HsLit p) -- ^ Simple (non-overloaded) literals | HsLam (MatchGroup p (LHsExpr p)) -- ^ Lambda abstraction. Currently always a single match -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsLamCase (MatchGroup p (LHsExpr p)) -- ^ Lambda-case -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsApp (LHsExpr p) (LHsExpr p) -- ^ Application | HsAppType (LHsExpr p) (LHsWcType p) -- ^ Visible type application -- -- Explicit type argument; e.g f @Int x y -- NB: Has wildcards, but no implicit quantification -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt', -- TODO:AZ: Sort out Name | HsAppTypeOut (LHsExpr p) (LHsWcType GhcRn) -- just for pretty-printing -- | Operator applications: -- NB Bracketed ops such as (+) come out as Vars. -- NB We need an expr for the operator in an OpApp/Section since -- the typechecker may need to apply the operator to a few types. | OpApp (LHsExpr p) -- left operand (LHsExpr p) -- operator (PostRn p Fixity) -- Renamer adds fixity; bottom until then (LHsExpr p) -- right operand -- | Negation operator. Contains the negated expression and the name -- of 'negate' -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus' -- For details on above see note [Api annotations] in ApiAnnotation | NegApp (LHsExpr p) (SyntaxExpr p) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsPar (LHsExpr p) -- ^ Parenthesised expr; see Note [Parens in HsSyn] | SectionL (LHsExpr p) -- operand; see Note [Sections in HsSyn] (LHsExpr p) -- operator | SectionR (LHsExpr p) -- operator; see Note [Sections in HsSyn] (LHsExpr p) -- operand -- | Used for explicit tuples and sections thereof -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitTuple [LHsTupArg p] Boxity -- | Used for unboxed sum types -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@, -- 'ApiAnnotation.AnnVbar', 'ApiAnnotation.AnnClose' @'#)'@, -- -- There will be multiple 'ApiAnnotation.AnnVbar', (1 - alternative) before -- the expression, (arity - alternative) after it | ExplicitSum ConTag -- Alternative (one-based) Arity -- Sum arity (LHsExpr p) (PostTc p [Type]) -- the type arguments -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCase (LHsExpr p) (MatchGroup p (LHsExpr p)) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsIf (Maybe (SyntaxExpr p)) -- cond function -- Nothing => use the built-in 'if' -- See Note [Rebindable if] (LHsExpr p) -- predicate (LHsExpr p) -- then part (LHsExpr p) -- else part -- | Multi-way if -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf' -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation | HsMultiIf (PostTc p Type) [LGRHS p (LHsExpr p)] -- | let(rec) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsLet (LHsLocalBinds p) (LHsExpr p) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsDo (HsStmtContext Name) -- The parameterisation is unimportant -- because in this context we never use -- the PatGuard or ParStmt variant (Located [ExprLStmt p]) -- "do":one or more stmts (PostTc p Type) -- Type of the whole expression -- | Syntactic list: [a,b,c,...] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitList (PostTc p Type) -- Gives type of components of list (Maybe (SyntaxExpr p)) -- For OverloadedLists, the fromListN witness [LHsExpr p] -- | Syntactic parallel array: [:e1, ..., en:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma', -- 'ApiAnnotation.AnnVbar' -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitPArr (PostTc p Type) -- type of elements of the parallel array [LHsExpr p] -- | Record construction -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordCon { rcon_con_name :: Located (IdP p) -- The constructor name; -- not used after type checking , rcon_con_like :: PostTc p ConLike -- The data constructor or pattern synonym , rcon_con_expr :: PostTcExpr -- Instantiated constructor function , rcon_flds :: HsRecordBinds p } -- The fields -- | Record update -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordUpd { rupd_expr :: LHsExpr p , rupd_flds :: [LHsRecUpdField p] , rupd_cons :: PostTc p [ConLike] -- Filled in by the type checker to the -- _non-empty_ list of DataCons that have -- all the upd'd fields , rupd_in_tys :: PostTc p [Type] -- Argument types of *input* record type , rupd_out_tys :: PostTc p [Type] -- and *output* record type -- The original type can be reconstructed -- with conLikeResTy , rupd_wrap :: PostTc p HsWrapper -- See note [Record Update HsWrapper] } -- For a type family, the arg types are of the *instance* tycon, -- not the family tycon -- | Expression with an explicit type signature. @e :: type@ -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | ExprWithTySig (LHsExpr p) (LHsSigWcType p) | ExprWithTySigOut -- Post typechecking (LHsExpr p) (LHsSigWcType GhcRn) -- Retain the signature, -- as HsSigType Name, for -- round-tripping purposes -- | Arithmetic sequence -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ArithSeq PostTcExpr (Maybe (SyntaxExpr p)) -- For OverloadedLists, the fromList witness (ArithSeqInfo p) -- | Arithmetic sequence for parallel array -- -- > [:e1..e2:] or [:e1, e2..e3:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | PArrSeq PostTcExpr (ArithSeqInfo p) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@, -- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsSCC SourceText -- Note [Pragma source text] in BasicTypes StringLiteral -- "set cost centre" SCC pragma (LHsExpr p) -- expr whose cost is to be measured -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@, -- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes StringLiteral -- hdaume: core annotation (LHsExpr p) ----------------------------------------------------------- -- MetaHaskell Extensions -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpenE','ApiAnnotation.AnnOpenEQ', -- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnCloseQ' -- For details on above see note [Api annotations] in ApiAnnotation | HsBracket (HsBracket p) -- See Note [Pending Splices] | HsRnBracketOut (HsBracket GhcRn) -- Output of the renamer is the *original* renamed -- expression, plus [PendingRnSplice] -- _renamed_ splices to be type checked | HsTcBracketOut (HsBracket GhcRn) -- Output of the type checker is the *original* -- renamed expression, plus [PendingTcSplice] -- _typechecked_ splices to be -- pasted back in by the desugarer -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsSpliceE (HsSplice p) ----------------------------------------------------------- -- Arrow notation extension -- | @proc@ notation for Arrows -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc', -- 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | HsProc (LPat p) -- arrow abstraction, proc (LHsCmdTop p) -- body of the abstraction -- always has an empty stack --------------------------------------- -- static pointers extension -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic', -- For details on above see note [Api annotations] in ApiAnnotation | HsStatic (PostRn p NameSet) -- Free variables of the body (LHsExpr p) -- Body --------------------------------------- -- The following are commands, not expressions proper -- They are only used in the parsing stage and are removed -- immediately in parser.RdrHsSyn.checkCommand -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation | HsArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr p) -- arrow expression, f (LHsExpr p) -- input expression, arg (PostTc p Type) -- type of the arrow expressions f, -- of the form a t t', where arg :: t HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpenB' @'(|'@, -- 'ApiAnnotation.AnnCloseB' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr p) -- the operator -- after type-checking, a type abstraction to be -- applied to the type of the local environment tuple (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop p] -- argument commands --------------------------------------- -- Haskell program coverage (Hpc) Support | HsTick (Tickish (IdP p)) (LHsExpr p) -- sub-expression | HsBinTick Int -- module-local tick number for True Int -- module-local tick number for False (LHsExpr p) -- sub-expression -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@, -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnMinus', -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon', -- 'ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsTickPragma -- A pragma introduced tick SourceText -- Note [Pragma source text] in BasicTypes (StringLiteral,(Int,Int),(Int,Int)) -- external span for this tick ((SourceText,SourceText),(SourceText,SourceText)) -- Source text for the four integers used in the span. -- See note [Pragma source text] in BasicTypes (LHsExpr p) --------------------------------------- -- These constructors only appear temporarily in the parser. -- The renamer translates them into the Right Thing. | EWildPat -- wildcard -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt' -- For details on above see note [Api annotations] in ApiAnnotation | EAsPat (Located (IdP p)) -- as pattern (LHsExpr p) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | EViewPat (LHsExpr p) -- view pattern (LHsExpr p) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde' -- For details on above see note [Api annotations] in ApiAnnotation | ELazyPat (LHsExpr p) -- ~ pattern --------------------------------------- -- Finally, HsWrap appears only in typechecker output -- The contained Expr is *NOT* itself an HsWrap. -- See Note [Detecting forced eta expansion] in DsExpr. This invariant -- is maintained by HsUtils.mkHsWrap. | HsWrap HsWrapper -- TRANSLATION (HsExpr p) deriving instance (DataId p) => Data (HsExpr p) -- | Located Haskell Tuple Argument -- -- 'HsTupArg' is used for tuple sections -- @(,a,)@ is represented by -- @ExplicitTuple [Missing ty1, Present a, Missing ty3]@ -- Which in turn stands for @(\x:ty1 \y:ty2. (x,a,y))@ type LHsTupArg id = Located (HsTupArg id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' -- For details on above see note [Api annotations] in ApiAnnotation -- | Haskell Tuple Argument data HsTupArg id = Present (LHsExpr id) -- ^ The argument | Missing (PostTc id Type) -- ^ The argument is missing, but this is its type deriving instance (DataId id) => Data (HsTupArg id) tupArgPresent :: LHsTupArg id -> Bool tupArgPresent (L _ (Present {})) = True tupArgPresent (L _ (Missing {})) = False {- Note [Parens in HsSyn] ~~~~~~~~~~~~~~~~~~~~~~ HsPar (and ParPat in patterns, HsParTy in types) is used as follows * HsPar is required; the pretty printer does not add parens. * HsPars are respected when rearranging operator fixities. So a * (b + c) means what it says (where the parens are an HsPar) * For ParPat and HsParTy the pretty printer does add parens but this should be a no-op for ParsedSource, based on the pretty printer round trip feature introduced in https://phabricator.haskell.org/rGHC499e43824bda967546ebf95ee33ec1f84a114a7c * ParPat and HsParTy are pretty printed as '( .. )' regardless of whether or not they are strictly necessary. This should be addressed when #13238 is completed, to be treated the same as HsPar. Note [Sections in HsSyn] ~~~~~~~~~~~~~~~~~~~~~~~~ Sections should always appear wrapped in an HsPar, thus HsPar (SectionR ...) The parser parses sections in a wider variety of situations (See Note [Parsing sections]), but the renamer checks for those parens. This invariant makes pretty-printing easier; we don't need a special case for adding the parens round sections. Note [Rebindable if] ~~~~~~~~~~~~~~~~~~~~ The rebindable syntax for 'if' is a bit special, because when rebindable syntax is *off* we do not want to treat (if c then t else e) as if it was an application (ifThenElse c t e). Why not? Because we allow an 'if' to return *unboxed* results, thus if blah then 3# else 4# whereas that would not be possible using a all to a polymorphic function (because you can't call a polymorphic function at an unboxed type). So we use Nothing to mean "use the old built-in typing rule". Note [Record Update HsWrapper] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is a wrapper in RecordUpd which is used for the *required* constraints for pattern synonyms. This wrapper is created in the typechecking and is then directly used in the desugaring without modification. For example, if we have the record pattern synonym P, pattern P :: (Show a) => a -> Maybe a pattern P{x} = Just x foo = (Just True) { x = False } then `foo` desugars to something like foo = case Just True of P x -> P False hence we need to provide the correct dictionaries to P's matcher on the RHS so that we can build the expression. Note [Located RdrNames] ~~~~~~~~~~~~~~~~~~~~~~~ A number of syntax elements have seemingly redundant locations attached to them. This is deliberate, to allow transformations making use of the API Annotations to easily correlate a Located Name in the RenamedSource with a Located RdrName in the ParsedSource. There are unfortunately enough differences between the ParsedSource and the RenamedSource that the API Annotations cannot be used directly with RenamedSource, so this allows a simple mapping to be used based on the location. -} instance (SourceTextX p, OutputableBndrId p) => Outputable (HsExpr p) where ppr expr = pprExpr expr ----------------------- -- pprExpr, pprLExpr, pprBinds call pprDeeper; -- the underscore versions do not pprLExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc pprLExpr (L _ e) = pprExpr e pprExpr :: (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e | otherwise = pprDeeper (ppr_expr e) isQuietHsExpr :: HsExpr id -> Bool -- Parentheses do display something, but it gives little info and -- if we go deeper when we go inside them then we get ugly things -- like (...) isQuietHsExpr (HsPar _) = True -- applications don't display anything themselves isQuietHsExpr (HsApp _ _) = True isQuietHsExpr (HsAppType _ _) = True isQuietHsExpr (HsAppTypeOut _ _) = True isQuietHsExpr (OpApp _ _ _ _) = True isQuietHsExpr _ = False pprBinds :: (SourceTextX idL, SourceTextX idR, OutputableBndrId idL, OutputableBndrId idR) => HsLocalBindsLR idL idR -> SDoc pprBinds b = pprDeeper (ppr b) ----------------------- ppr_lexpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc ppr_lexpr e = ppr_expr (unLoc e) ppr_expr :: forall p. (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc ppr_expr (HsVar (L _ v)) = pprPrefixOcc v ppr_expr (HsUnboundVar uv)= pprPrefixOcc (unboundVarOcc uv) ppr_expr (HsConLikeOut c) = pprPrefixOcc c ppr_expr (HsIPVar v) = ppr v ppr_expr (HsOverLabel _ l)= char '#' <> ppr l ppr_expr (HsLit lit) = ppr lit ppr_expr (HsOverLit lit) = ppr lit ppr_expr (HsPar e) = parens (ppr_lexpr e) ppr_expr (HsCoreAnn stc (StringLiteral sta s) e) = vcat [pprWithSourceText stc (text "{-# CORE") <+> pprWithSourceText sta (doubleQuotes $ ftext s) <+> text "#-}" , ppr_lexpr e] ppr_expr e@(HsApp {}) = ppr_apps e [] ppr_expr e@(HsAppType {}) = ppr_apps e [] ppr_expr e@(HsAppTypeOut {}) = ppr_apps e [] ppr_expr (OpApp e1 op _ e2) | Just pp_op <- should_print_infix (unLoc op) = pp_infixly pp_op | otherwise = pp_prefixly where should_print_infix (HsVar (L _ v)) = Just (pprInfixOcc v) should_print_infix (HsConLikeOut c)= Just (pprInfixOcc (conLikeName c)) should_print_infix (HsRecFld f) = Just (pprInfixOcc f) should_print_infix (HsUnboundVar h@TrueExprHole{}) = Just (pprInfixOcc (unboundVarOcc h)) should_print_infix EWildPat = Just (text "`_`") should_print_infix (HsWrap _ e) = should_print_infix e should_print_infix _ = Nothing pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens pp_e2 = pprDebugParendExpr e2 -- to make precedence clear pp_prefixly = hang (ppr op) 2 (sep [pp_e1, pp_e2]) pp_infixly pp_op = hang pp_e1 2 (sep [pp_op, nest 2 pp_e2]) ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e ppr_expr (SectionL expr op) = case unLoc op of HsVar (L _ v) -> pp_infixly v HsConLikeOut c -> pp_infixly (conLikeName c) _ -> pp_prefixly where pp_expr = pprDebugParendExpr expr pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op]) 4 (hsep [pp_expr, text "x_ )"]) pp_infixly v = (sep [pp_expr, pprInfixOcc v]) ppr_expr (SectionR op expr) = case unLoc op of HsVar (L _ v) -> pp_infixly v HsConLikeOut c -> pp_infixly (conLikeName c) _ -> pp_prefixly where pp_expr = pprDebugParendExpr expr pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"]) 4 (pp_expr <> rparen) pp_infixly v = sep [pprInfixOcc v, pp_expr] ppr_expr (ExplicitTuple exprs boxity) = tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs)) where ppr_tup_args [] = [] ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es punc (Present {} : _) = comma <> space punc (Missing {} : _) = comma punc [] = empty ppr_expr (ExplicitSum alt arity expr _) = text "(#" <+> ppr_bars (alt - 1) <+> ppr expr <+> ppr_bars (arity - alt) <+> text "#)" where ppr_bars n = hsep (replicate n (char '|')) ppr_expr (HsLam matches) = pprMatches matches ppr_expr (HsLamCase matches) = sep [ sep [text "\\case"], nest 2 (pprMatches matches) ] ppr_expr (HsCase expr matches@(MG { mg_alts = L _ [_] })) = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")], nest 2 (pprMatches matches) <+> char '}'] ppr_expr (HsCase expr matches) = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")], nest 2 (pprMatches matches) ] ppr_expr (HsIf _ e1 e2 e3) = sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")], nest 4 (ppr e2), text "else", nest 4 (ppr e3)] ppr_expr (HsMultiIf _ alts) = hang (text "if") 3 (vcat (map ppr_alt alts)) where ppr_alt (L _ (GRHS guards expr)) = hang vbar 2 (ppr_one one_alt) where ppr_one [] = panic "ppr_exp HsMultiIf" ppr_one (h:t) = hang h 2 (sep t) one_alt = [ interpp'SP guards , text "->" <+> pprDeeper (ppr expr) ] -- special case: let ... in let ... ppr_expr (HsLet (L _ binds) expr@(L _ (HsLet _ _))) = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]), ppr_lexpr expr] ppr_expr (HsLet (L _ binds) expr) = sep [hang (text "let") 2 (pprBinds binds), hang (text "in") 2 (ppr expr)] ppr_expr (HsDo do_or_list_comp (L _ stmts) _) = pprDo do_or_list_comp stmts ppr_expr (ExplicitList _ _ exprs) = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs))) ppr_expr (ExplicitPArr _ exprs) = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs))) ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds }) = hang (ppr con_id) 2 (ppr rbinds) ppr_expr (RecordUpd { rupd_expr = L _ aexp, rupd_flds = rbinds }) = hang (ppr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds)))) ppr_expr (ExprWithTySig expr sig) = hang (nest 2 (ppr_lexpr expr) <+> dcolon) 4 (ppr sig) ppr_expr (ExprWithTySigOut expr sig) = hang (nest 2 (ppr_lexpr expr) <+> dcolon) 4 (ppr sig) ppr_expr (ArithSeq _ _ info) = brackets (ppr info) ppr_expr (PArrSeq _ info) = paBrackets (ppr info) ppr_expr EWildPat = char '_' ppr_expr (ELazyPat e) = char '~' <> ppr e ppr_expr (EAsPat v e) = ppr v <> char '@' <> ppr e ppr_expr (EViewPat p e) = ppr p <+> text "->" <+> ppr e ppr_expr (HsSCC st (StringLiteral stl lbl) expr) = sep [ pprWithSourceText st (text "{-# SCC") -- no doublequotes if stl empty, for the case where the SCC was written -- without quotes. <+> pprWithSourceText stl (ftext lbl) <+> text "#-}", ppr expr ] ppr_expr (HsWrap co_fn e) = pprHsWrapper co_fn (\parens -> if parens then pprExpr e else pprExpr e) ppr_expr (HsSpliceE s) = pprSplice s ppr_expr (HsBracket b) = pprHsBracket b ppr_expr (HsRnBracketOut e []) = ppr e ppr_expr (HsRnBracketOut e ps) = ppr e $$ text "pending(rn)" <+> ppr ps ppr_expr (HsTcBracketOut e []) = ppr e ppr_expr (HsTcBracketOut e ps) = ppr e $$ text "pending(tc)" <+> ppr ps ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _))) = hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd] ppr_expr (HsStatic _ e) = hsep [text "static", ppr e] ppr_expr (HsTick tickish exp) = pprTicks (ppr exp) $ ppr tickish <+> ppr_lexpr exp ppr_expr (HsBinTick tickIdTrue tickIdFalse exp) = pprTicks (ppr exp) $ hcat [text "bintick<", ppr tickIdTrue, text ",", ppr tickIdFalse, text ">(", ppr exp, text ")"] ppr_expr (HsTickPragma _ externalSrcLoc _ exp) = pprTicks (ppr exp) $ hcat [text "tickpragma<", pprExternalSrcLoc externalSrcLoc, text ">(", ppr exp, text ")"] ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True) = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg] ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False) = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow] ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True) = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg] ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False) = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow] ppr_expr (HsArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2]) = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]] ppr_expr (HsArrForm (L _ (HsConLikeOut c)) (Just _) [arg1, arg2]) = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc (conLikeName c), pprCmdArg (unLoc arg2)]] ppr_expr (HsArrForm op _ args) = hang (text "(|" <+> ppr_lexpr op) 4 (sep (map (pprCmdArg.unLoc) args) <+> text "|)") ppr_expr (HsRecFld f) = ppr f -- We must tiresomely make the "id" parameter to the LHsWcType existential -- because it's different in the HsAppType case and the HsAppTypeOut case -- | Located Haskell Wildcard Type Expression data LHsWcTypeX = forall p. (SourceTextX p, OutputableBndrId p) => LHsWcTypeX (LHsWcType p) ppr_apps :: (SourceTextX p, OutputableBndrId p) => HsExpr p -> [Either (LHsExpr p) LHsWcTypeX] -> SDoc ppr_apps (HsApp (L _ fun) arg) args = ppr_apps fun (Left arg : args) ppr_apps (HsAppType (L _ fun) arg) args = ppr_apps fun (Right (LHsWcTypeX arg) : args) ppr_apps (HsAppTypeOut (L _ fun) arg) args = ppr_apps fun (Right (LHsWcTypeX arg) : args) ppr_apps fun args = hang (ppr_expr fun) 2 (sep (map pp args)) where pp (Left arg) = ppr arg pp (Right (LHsWcTypeX (HsWC { hswc_body = L _ arg }))) = char '@' <> pprHsType arg pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc pprExternalSrcLoc (StringLiteral _ src,(n1,n2),(n3,n4)) = ppr (src,(n1,n2),(n3,n4)) {- HsSyn records exactly where the user put parens, with HsPar. So generally speaking we print without adding any parens. However, some code is internally generated, and in some places parens are absolutely required; so for these places we use pprParendLExpr (but don't print double parens of course). For operator applications we don't add parens, because the operator fixities should do the job, except in debug mode (-dppr-debug) so we can see the structure of the parse tree. -} pprDebugParendExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc pprDebugParendExpr expr = getPprStyle (\sty -> if debugStyle sty then pprParendLExpr expr else pprLExpr expr) pprParendLExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc pprParendLExpr (L _ e) = pprParendExpr e pprParendExpr :: (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc pprParendExpr expr | hsExprNeedsParens expr = parens (pprExpr expr) | otherwise = pprExpr expr -- Using pprLExpr makes sure that we go 'deeper' -- I think that is usually (always?) right hsExprNeedsParens :: HsExpr id -> Bool -- True of expressions for which '(e)' and 'e' -- mean the same thing hsExprNeedsParens (ArithSeq {}) = False hsExprNeedsParens (PArrSeq {}) = False hsExprNeedsParens (HsLit {}) = False hsExprNeedsParens (HsOverLit {}) = False hsExprNeedsParens (HsVar {}) = False hsExprNeedsParens (HsUnboundVar {}) = False hsExprNeedsParens (HsConLikeOut {}) = False hsExprNeedsParens (HsIPVar {}) = False hsExprNeedsParens (HsOverLabel {}) = False hsExprNeedsParens (ExplicitTuple {}) = False hsExprNeedsParens (ExplicitList {}) = False hsExprNeedsParens (ExplicitPArr {}) = False hsExprNeedsParens (HsPar {}) = False hsExprNeedsParens (HsBracket {}) = False hsExprNeedsParens (HsRnBracketOut {}) = False hsExprNeedsParens (HsTcBracketOut {}) = False hsExprNeedsParens (HsDo sc _ _) | isListCompExpr sc = False hsExprNeedsParens (HsRecFld{}) = False hsExprNeedsParens (RecordCon{}) = False hsExprNeedsParens (HsSpliceE{}) = False hsExprNeedsParens (RecordUpd{}) = False hsExprNeedsParens (HsWrap _ e) = hsExprNeedsParens e hsExprNeedsParens _ = True isAtomicHsExpr :: HsExpr id -> Bool -- True of a single token isAtomicHsExpr (HsVar {}) = True isAtomicHsExpr (HsConLikeOut {}) = True isAtomicHsExpr (HsLit {}) = True isAtomicHsExpr (HsOverLit {}) = True isAtomicHsExpr (HsIPVar {}) = True isAtomicHsExpr (HsOverLabel {}) = True isAtomicHsExpr (HsUnboundVar {}) = True isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e) isAtomicHsExpr (HsRecFld{}) = True isAtomicHsExpr _ = False {- ************************************************************************ * * \subsection{Commands (in arrow abstractions)} * * ************************************************************************ We re-use HsExpr to represent these. -} -- | Located Haskell Command (for arrow syntax) type LHsCmd id = Located (HsCmd id) -- | Haskell Command (e.g. a "statement" in an Arrow proc block) data HsCmd id -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr id) -- arrow expression, f (LHsExpr id) -- input expression, arg (PostTc id Type) -- type of the arrow expressions f, -- of the form a t t', where arg :: t HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpenB' @'(|'@, -- 'ApiAnnotation.AnnCloseB' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr id) -- The operator. -- After type-checking, a type abstraction to be -- applied to the type of the local environment tuple LexicalFixity -- Whether the operator appeared prefix or infix when -- parsed. (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop id] -- argument commands | HsCmdApp (LHsCmd id) (LHsExpr id) | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdPar (LHsCmd id) -- parenthesised command -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdCase (LHsExpr id) (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdIf (Maybe (SyntaxExpr id)) -- cond function (LHsExpr id) -- predicate (LHsCmd id) -- then part (LHsCmd id) -- else part -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdLet (LHsLocalBinds id) -- let(rec) (LHsCmd id) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdDo (Located [CmdLStmt id]) (PostTc id Type) -- Type of the whole expression -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdWrap HsWrapper (HsCmd id) -- If cmd :: arg1 --> res -- wrap :: arg1 "->" arg2 -- Then (HsCmdWrap wrap cmd) :: arg2 --> res deriving instance (DataId id) => Data (HsCmd id) -- | Haskell Array Application Type data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp deriving Data {- | Top-level command, introducing a new arrow. This may occur inside a proc (where the stack is empty) or as an argument of a command-forming operator. -} -- | Located Haskell Top-level Command type LHsCmdTop p = Located (HsCmdTop p) -- | Haskell Top-level Command data HsCmdTop p = HsCmdTop (LHsCmd p) (PostTc p Type) -- Nested tuple of inputs on the command's stack (PostTc p Type) -- return type of the command (CmdSyntaxTable p) -- See Note [CmdSyntaxTable] deriving instance (DataId p) => Data (HsCmdTop p) instance (SourceTextX p, OutputableBndrId p) => Outputable (HsCmd p) where ppr cmd = pprCmd cmd ----------------------- -- pprCmd and pprLCmd call pprDeeper; -- the underscore versions do not pprLCmd :: (SourceTextX p, OutputableBndrId p) => LHsCmd p -> SDoc pprLCmd (L _ c) = pprCmd c pprCmd :: (SourceTextX p, OutputableBndrId p) => HsCmd p -> SDoc pprCmd c | isQuietHsCmd c = ppr_cmd c | otherwise = pprDeeper (ppr_cmd c) isQuietHsCmd :: HsCmd id -> Bool -- Parentheses do display something, but it gives little info and -- if we go deeper when we go inside them then we get ugly things -- like (...) isQuietHsCmd (HsCmdPar _) = True -- applications don't display anything themselves isQuietHsCmd (HsCmdApp _ _) = True isQuietHsCmd _ = False ----------------------- ppr_lcmd :: (SourceTextX p, OutputableBndrId p) => LHsCmd p -> SDoc ppr_lcmd c = ppr_cmd (unLoc c) ppr_cmd :: forall p. (SourceTextX p, OutputableBndrId p) => HsCmd p -> SDoc ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c) ppr_cmd (HsCmdApp c e) = let (fun, args) = collect_args c [e] in hang (ppr_lcmd fun) 2 (sep (map ppr args)) where collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args) collect_args fun args = (fun, args) ppr_cmd (HsCmdLam matches) = pprMatches matches ppr_cmd (HsCmdCase expr matches) = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")], nest 2 (pprMatches matches) ] ppr_cmd (HsCmdIf _ e ct ce) = sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")], nest 4 (ppr ct), text "else", nest 4 (ppr ce)] -- special case: let ... in let ... ppr_cmd (HsCmdLet (L _ binds) cmd@(L _ (HsCmdLet _ _))) = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]), ppr_lcmd cmd] ppr_cmd (HsCmdLet (L _ binds) cmd) = sep [hang (text "let") 2 (pprBinds binds), hang (text "in") 2 (ppr cmd)] ppr_cmd (HsCmdDo (L _ stmts) _) = pprDo ArrowExpr stmts ppr_cmd (HsCmdWrap w cmd) = pprHsWrapper w (\_ -> parens (ppr_cmd cmd)) ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True) = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg] ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False) = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow] ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True) = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg] ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False) = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow] ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) _ (Just _) [arg1, arg2]) = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v , pprCmdArg (unLoc arg2)]) ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) Infix _ [arg1, arg2]) = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v , pprCmdArg (unLoc arg2)]) ppr_cmd (HsCmdArrForm (L _ (HsConLikeOut c)) _ (Just _) [arg1, arg2]) = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c) , pprCmdArg (unLoc arg2)]) ppr_cmd (HsCmdArrForm (L _ (HsConLikeOut c)) Infix _ [arg1, arg2]) = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c) , pprCmdArg (unLoc arg2)]) ppr_cmd (HsCmdArrForm op _ _ args) = hang (text "(|" <> ppr_lexpr op) 4 (sep (map (pprCmdArg.unLoc) args) <> text "|)") pprCmdArg :: (SourceTextX p, OutputableBndrId p) => HsCmdTop p -> SDoc pprCmdArg (HsCmdTop cmd _ _ _) = ppr_lcmd cmd instance (SourceTextX p, OutputableBndrId p) => Outputable (HsCmdTop p) where ppr = pprCmdArg {- ************************************************************************ * * \subsection{Record binds} * * ************************************************************************ -} -- | Haskell Record Bindings type HsRecordBinds p = HsRecFields p (LHsExpr p) {- ************************************************************************ * * \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes} * * ************************************************************************ @Match@es are sets of pattern bindings and right hand sides for functions, patterns or case branches. For example, if a function @g@ is defined as: \begin{verbatim} g (x,y) = y g ((x:ys),y) = y+1, \end{verbatim} then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@. It is always the case that each element of an @[Match]@ list has the same number of @pats@s inside it. This corresponds to saying that a function defined by pattern matching must have the same number of patterns in each equation. -} data MatchGroup p body = MG { mg_alts :: Located [LMatch p body] -- The alternatives , mg_arg_tys :: [PostTc p Type] -- Types of the arguments, t1..tn , mg_res_ty :: PostTc p Type -- Type of the result, tr , mg_origin :: Origin } -- The type is the type of the entire group -- t1 -> ... -> tn -> tr -- where there are n patterns deriving instance (Data body,DataId p) => Data (MatchGroup p body) -- | Located Match type LMatch id body = Located (Match id body) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a -- list -- For details on above see note [Api annotations] in ApiAnnotation data Match p body = Match { m_ctxt :: HsMatchContext (NameOrRdrName (IdP p)), -- See note [m_ctxt in Match] m_pats :: [LPat p], -- The patterns m_grhss :: (GRHSs p body) } deriving instance (Data body,DataId p) => Data (Match p body) instance (SourceTextX idR, OutputableBndrId idR, Outputable body) => Outputable (Match idR body) where ppr = pprMatch {- Note [m_ctxt in Match] ~~~~~~~~~~~~~~~~~~~~~~ A Match can occur in a number of contexts, such as a FunBind, HsCase, HsLam and so on. In order to simplify tooling processing and pretty print output, the provenance is captured in an HsMatchContext. This is particularly important for the API Annotations for a multi-equation FunBind. The parser initially creates a FunBind with a single Match in it for every function definition it sees. These are then grouped together by getMonoBind into a single FunBind, where all the Matches are combined. In the process, all the original FunBind fun_id's bar one are discarded, including the locations. This causes a problem for source to source conversions via API Annotations, so the original fun_ids and infix flags are preserved in the Match, when it originates from a FunBind. Example infix function definition requiring individual API Annotations (&&& ) [] [] = [] xs &&& [] = xs ( &&& ) [] ys = ys -} isInfixMatch :: Match id body -> Bool isInfixMatch match = case m_ctxt match of FunRhs {mc_fixity = Infix} -> True _ -> False isEmptyMatchGroup :: MatchGroup id body -> Bool isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms -- | Is there only one RHS in this list of matches? isSingletonMatchGroup :: [LMatch id body] -> Bool isSingletonMatchGroup matches | [L _ match] <- matches , Match { m_grhss = GRHSs { grhssGRHSs = [_] } } <- match = True | otherwise = False matchGroupArity :: MatchGroup id body -> Arity -- Precondition: MatchGroup is non-empty -- This is called before type checking, when mg_arg_tys is not set matchGroupArity (MG { mg_alts = alts }) | L _ (alt1:_) <- alts = length (hsLMatchPats alt1) | otherwise = panic "matchGroupArity" hsLMatchPats :: LMatch id body -> [LPat id] hsLMatchPats (L _ (Match { m_pats = pats })) = pats -- | Guarded Right-Hand Sides -- -- GRHSs are used both for pattern bindings and for Matches -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose' -- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi' -- For details on above see note [Api annotations] in ApiAnnotation data GRHSs p body = GRHSs { grhssGRHSs :: [LGRHS p body], -- ^ Guarded RHSs grhssLocalBinds :: LHsLocalBinds p -- ^ The where clause } deriving instance (Data body,DataId p) => Data (GRHSs p body) -- | Located Guarded Right-Hand Side type LGRHS id body = Located (GRHS id body) -- | Guarded Right Hand Side. data GRHS id body = GRHS [GuardLStmt id] -- Guards body -- Right hand side deriving instance (Data body,DataId id) => Data (GRHS id body) -- We know the list must have at least one @Match@ in it. pprMatches :: (SourceTextX idR, OutputableBndrId idR, Outputable body) => MatchGroup idR body -> SDoc pprMatches MG { mg_alts = matches } = vcat (map pprMatch (map unLoc (unLoc matches))) -- Don't print the type; it's only a place-holder before typechecking -- Exported to HsBinds, which can't see the defn of HsMatchContext pprFunBind :: (SourceTextX idR, OutputableBndrId idR, Outputable body) => MatchGroup idR body -> SDoc pprFunBind matches = pprMatches matches -- Exported to HsBinds, which can't see the defn of HsMatchContext pprPatBind :: forall bndr p body. (SourceTextX p, SourceTextX bndr, OutputableBndrId bndr, OutputableBndrId p, Outputable body) => LPat bndr -> GRHSs p body -> SDoc pprPatBind pat (grhss) = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext (IdP p)) grhss)] pprMatch :: (SourceTextX idR, OutputableBndrId idR, Outputable body) => Match idR body -> SDoc pprMatch match = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats) , nest 2 (pprGRHSs ctxt (m_grhss match)) ] where ctxt = m_ctxt match (herald, other_pats) = case ctxt of FunRhs {mc_fun=L _ fun, mc_fixity=fixity, mc_strictness=strictness} | strictness == SrcStrict -> ASSERT(null $ m_pats match) (char '!'<>pprPrefixOcc fun, m_pats match) -- a strict variable binding | fixity == Prefix -> (pprPrefixOcc fun, m_pats match) -- f x y z = e -- Not pprBndr; the AbsBinds will -- have printed the signature | null pats2 -> (pp_infix, []) -- x &&& y = e | otherwise -> (parens pp_infix, pats2) -- (x &&& y) z = e where pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2 LambdaExpr -> (char '\\', m_pats match) _ -> ASSERT2( null pats1, ppr ctxt $$ ppr pat1 $$ ppr pats1 ) (ppr pat1, []) -- No parens around the single pat (pat1:pats1) = m_pats match (pat2:pats2) = pats1 pprGRHSs :: (SourceTextX idR, OutputableBndrId idR, Outputable body) => HsMatchContext idL -> GRHSs idR body -> SDoc pprGRHSs ctxt (GRHSs grhss (L _ binds)) = vcat (map (pprGRHS ctxt . unLoc) grhss) -- Print the "where" even if the contents of the binds is empty. Only -- EmptyLocalBinds means no "where" keyword $$ ppUnless (eqEmptyLocalBinds binds) (text "where" $$ nest 4 (pprBinds binds)) pprGRHS :: (SourceTextX idR, OutputableBndrId idR, Outputable body) => HsMatchContext idL -> GRHS idR body -> SDoc pprGRHS ctxt (GRHS [] body) = pp_rhs ctxt body pprGRHS ctxt (GRHS guards body) = sep [vbar <+> interpp'SP guards, pp_rhs ctxt body] pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs) {- ************************************************************************ * * \subsection{Do stmts and list comprehensions} * * ************************************************************************ -} -- | Located @do@ block Statement type LStmt id body = Located (StmtLR id id body) -- | Located Statement with separate Left and Right id's type LStmtLR idL idR body = Located (StmtLR idL idR body) -- | @do@ block Statement type Stmt id body = StmtLR id id body -- | Command Located Statement type CmdLStmt id = LStmt id (LHsCmd id) -- | Command Statement type CmdStmt id = Stmt id (LHsCmd id) -- | Expression Located Statement type ExprLStmt id = LStmt id (LHsExpr id) -- | Expression Statement type ExprStmt id = Stmt id (LHsExpr id) -- | Guard Located Statement type GuardLStmt id = LStmt id (LHsExpr id) -- | Guard Statement type GuardStmt id = Stmt id (LHsExpr id) -- | Ghci Located Statement type GhciLStmt id = LStmt id (LHsExpr id) -- | Ghci Statement type GhciStmt id = Stmt id (LHsExpr id) -- The SyntaxExprs in here are used *only* for do-notation and monad -- comprehensions, which have rebindable syntax. Otherwise they are unused. -- | API Annotations when in qualifier lists or guards -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen', -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy', -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing' -- For details on above see note [Api annotations] in ApiAnnotation data StmtLR idL idR body -- body should always be (LHs**** idR) = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp, -- and (after the renamer) DoExpr, MDoExpr -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff body Bool -- True <=> return was stripped by ApplicativeDo (SyntaxExpr idR) -- The return operator, used only for -- MonadComp For ListComp, PArrComp, we -- use the baked-in 'return' For DoExpr, -- MDoExpr, we don't apply a 'return' at -- all See Note [Monad Comprehensions] | -- - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnLarrow' -- For details on above see note [Api annotations] in ApiAnnotation | BindStmt (LPat idL) body (SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts] (SyntaxExpr idR) -- The fail operator -- The fail operator is noSyntaxExpr -- if the pattern match can't fail (PostTc idR Type) -- result type of the function passed to bind; -- that is, S in (>>=) :: Q -> (R -> S) -> T -- | 'ApplicativeStmt' represents an applicative expression built with -- <$> and <*>. It is generated by the renamer, and is desugared into the -- appropriate applicative expression by the desugarer, but it is intended -- to be invisible in error messages. -- -- For full details, see Note [ApplicativeDo] in RnExpr -- | ApplicativeStmt [ ( SyntaxExpr idR , ApplicativeArg idL idR) ] -- [(<$>, e1), (<*>, e2), ..., (<*>, en)] (Maybe (SyntaxExpr idR)) -- 'join', if necessary (PostTc idR Type) -- Type of the body | BodyStmt body -- See Note [BodyStmt] (SyntaxExpr idR) -- The (>>) operator (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp -- See notes [Monad Comprehensions] (PostTc idR Type) -- Element type of the RHS (used for arrows) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet' -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@, -- For details on above see note [Api annotations] in ApiAnnotation | LetStmt (LHsLocalBindsLR idL idR) -- ParStmts only occur in a list/monad comprehension | ParStmt [ParStmtBlock idL idR] (HsExpr idR) -- Polymorphic `mzip` for monad comprehensions (SyntaxExpr idR) -- The `>>=` operator -- See notes [Monad Comprehensions] (PostTc idR Type) -- S in (>>=) :: Q -> (R -> S) -> T -- After renaming, the ids are the binders -- bound by the stmts and used after themp | TransStmt { trS_form :: TransForm, trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group' -- which generates the tuples to be grouped trS_bndrs :: [(IdP idR, IdP idR)], -- See Note [TransStmt binder map] trS_using :: LHsExpr idR, trS_by :: Maybe (LHsExpr idR), -- "by e" (optional) -- Invariant: if trS_form = GroupBy, then grp_by = Just e trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for -- the inner monad comprehensions trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator trS_bind_arg_ty :: PostTc idR Type, -- R in (>>=) :: Q -> (R -> S) -> T trS_fmap :: HsExpr idR -- The polymorphic 'fmap' function for desugaring -- Only for 'group' forms -- Just a simple HsExpr, because it's -- too polymorphic for tcSyntaxOp } -- See Note [Monad Comprehensions] -- Recursive statement (see Note [How RecStmt works] below) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec' -- For details on above see note [Api annotations] in ApiAnnotation | RecStmt { recS_stmts :: [LStmtLR idL idR body] -- The next two fields are only valid after renaming , recS_later_ids :: [IdP idR] -- The ids are a subset of the variables bound by the -- stmts that are used in stmts that follow the RecStmt , recS_rec_ids :: [IdP idR] -- Ditto, but these variables are the "recursive" ones, -- that are used before they are bound in the stmts of -- the RecStmt. -- An Id can be in both groups -- Both sets of Ids are (now) treated monomorphically -- See Note [How RecStmt works] for why they are separate -- Rebindable syntax , recS_bind_fn :: SyntaxExpr idR -- The bind function , recS_ret_fn :: SyntaxExpr idR -- The return function , recS_mfix_fn :: SyntaxExpr idR -- The mfix function , recS_bind_ty :: PostTc idR Type -- S in (>>=) :: Q -> (R -> S) -> T -- These fields are only valid after typechecking , recS_later_rets :: [PostTcExpr] -- (only used in the arrow version) , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1 -- with recS_later_ids and recS_rec_ids, -- and are the expressions that should be -- returned by the recursion. -- They may not quite be the Ids themselves, -- because the Id may be *polymorphic*, but -- the returned thing has to be *monomorphic*, -- so they may be type applications , recS_ret_ty :: PostTc idR Type -- The type of -- do { stmts; return (a,b,c) } -- With rebindable syntax the type might not -- be quite as simple as (m (tya, tyb, tyc)). } deriving instance (Data body, DataId idL, DataId idR) => Data (StmtLR idL idR body) data TransForm -- The 'f' below is the 'using' function, 'e' is the by function = ThenForm -- then f or then f by e (depending on trS_by) | GroupForm -- then group using f or then group by e using f (depending on trS_by) deriving Data -- | Parenthesised Statement Block data ParStmtBlock idL idR = ParStmtBlock [ExprLStmt idL] [IdP idR] -- The variables to be returned (SyntaxExpr idR) -- The return operator deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR) -- | Applicative Argument data ApplicativeArg idL idR = ApplicativeArgOne -- A single statement (BindStmt or BodyStmt) (LPat idL) -- WildPat if it was a BodyStmt (see below) (LHsExpr idL) Bool -- True <=> was a BodyStmt -- False <=> was a BindStmt -- See Note [Applicative BodyStmt] | ApplicativeArgMany -- do { stmts; return vars } [ExprLStmt idL] -- stmts (HsExpr idL) -- return (v1,..,vn), or just (v1,..,vn) (LPat idL) -- (v1,...,vn) deriving instance (DataId idL, DataId idR) => Data (ApplicativeArg idL idR) {- Note [The type of bind in Stmts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some Stmts, notably BindStmt, keep the (>>=) bind operator. We do NOT assume that it has type (>>=) :: m a -> (a -> m b) -> m b In some cases (see Trac #303, #1537) it might have a more exotic type, such as (>>=) :: m i j a -> (a -> m j k b) -> m i k b So we must be careful not to make assumptions about the type. In particular, the monad may not be uniform throughout. Note [TransStmt binder map] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The [(idR,idR)] in a TransStmt behaves as follows: * Before renaming: [] * After renaming: [ (x27,x27), ..., (z35,z35) ] These are the variables bound by the stmts to the left of the 'group' and used either in the 'by' clause, or in the stmts following the 'group' Each item is a pair of identical variables. * After typechecking: [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ] Each pair has the same unique, but different *types*. Note [BodyStmt] ~~~~~~~~~~~~~~~ BodyStmts are a bit tricky, because what they mean depends on the context. Consider the following contexts: A do expression of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E any_ty: do { ....; E; ... } E :: m any_ty Translation: E >> ... A list comprehensions of type [elt_ty] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] [ .. | ..., E, ... ] [ .. | .... | ..., E | ... ] E :: Bool Translation: if E then fail else ... A guard list, guarding a RHS of type rhs_ty ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs... E :: Bool Translation: if E then fail else ... A monad comprehension of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] E :: Bool Translation: guard E >> ... Array comprehensions are handled like list comprehensions. Note [How RecStmt works] ~~~~~~~~~~~~~~~~~~~~~~~~ Example: HsDo [ BindStmt x ex , RecStmt { recS_rec_ids = [a, c] , recS_stmts = [ BindStmt b (return (a,c)) , LetStmt a = ...b... , BindStmt c ec ] , recS_later_ids = [a, b] , return (a b) ] Here, the RecStmt binds a,b,c; but - Only a,b are used in the stmts *following* the RecStmt, - Only a,c are used in the stmts *inside* the RecStmt *before* their bindings Why do we need *both* rec_ids and later_ids? For monads they could be combined into a single set of variables, but not for arrows. That follows from the types of the respective feedback operators: mfix :: MonadFix m => (a -> m a) -> m a loop :: ArrowLoop a => a (b,d) (c,d) -> a b c * For mfix, the 'a' covers the union of the later_ids and the rec_ids * For 'loop', 'c' is the later_ids and 'd' is the rec_ids Note [Typing a RecStmt] ~~~~~~~~~~~~~~~~~~~~~~~ A (RecStmt stmts) types as if you had written (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) -> do { stmts ; return (v1,..vn, r1, ..., rm) }) where v1..vn are the later_ids r1..rm are the rec_ids Note [Monad Comprehensions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monad comprehensions require separate functions like 'return' and '>>=' for desugaring. These functions are stored in the statements used in monad comprehensions. For example, the 'return' of the 'LastStmt' expression is used to lift the body of the monad comprehension: [ body | stmts ] => stmts >>= \bndrs -> return body In transform and grouping statements ('then ..' and 'then group ..') the 'return' function is required for nested monad comprehensions, for example: [ body | stmts, then f, rest ] => f [ env | stmts ] >>= \bndrs -> [ body | rest ] BodyStmts require the 'Control.Monad.guard' function for boolean expressions: [ body | exp, stmts ] => guard exp >> [ body | stmts ] Parallel statements require the 'Control.Monad.Zip.mzip' function: [ body | stmts1 | stmts2 | .. ] => mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body In any other context than 'MonadComp', the fields for most of these 'SyntaxExpr's stay bottom. Note [Applicative BodyStmt] (#12143) For the purposes of ApplicativeDo, we treat any BodyStmt as if it was a BindStmt with a wildcard pattern. For example, do x <- A B return x is transformed as if it were do x <- A _ <- B return x so it transforms to (\(x,_) -> x) <$> A <*> B But we have to remember when we treat a BodyStmt like a BindStmt, because in error messages we want to emit the original syntax the user wrote, not our internal representation. So ApplicativeArgOne has a Bool flag that is True when the original statement was a BodyStmt, so that we can pretty-print it correctly. -} instance (SourceTextX idL, OutputableBndrId idL) => Outputable (ParStmtBlock idL idR) where ppr (ParStmtBlock stmts _ _) = interpp'SP stmts instance (SourceTextX idL, SourceTextX idR, OutputableBndrId idL, OutputableBndrId idR, Outputable body) => Outputable (StmtLR idL idR body) where ppr stmt = pprStmt stmt pprStmt :: forall idL idR body . (SourceTextX idL, SourceTextX idR, OutputableBndrId idL, OutputableBndrId idR, Outputable body) => (StmtLR idL idR body) -> SDoc pprStmt (LastStmt expr ret_stripped _) = whenPprDebug (text "[last]") <+> (if ret_stripped then text "return" else empty) <+> ppr expr pprStmt (BindStmt pat expr _ _ _) = hsep [ppr pat, larrow, ppr expr] pprStmt (LetStmt (L _ binds)) = hsep [text "let", pprBinds binds] pprStmt (BodyStmt expr _ _ _) = ppr expr pprStmt (ParStmt stmtss _ _ _) = sep (punctuate (text " | ") (map ppr stmtss)) pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form }) = sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form]) pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids , recS_later_ids = later_ids }) = text "rec" <+> vcat [ ppr_do_stmts segment , whenPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids , text "later_ids=" <> ppr later_ids])] pprStmt (ApplicativeStmt args mb_join _) = getPprStyle $ \style -> if userStyle style then pp_for_user else pp_debug where -- make all the Applicative stuff invisible in error messages by -- flattening the whole ApplicativeStmt nest back to a sequence -- of statements. pp_for_user = vcat $ concatMap flattenArg args -- ppr directly rather than transforming here, because we need to -- inject a "return" which is hard when we're polymorphic in the id -- type. flattenStmt :: ExprLStmt idL -> [SDoc] flattenStmt (L _ (ApplicativeStmt args _ _)) = concatMap flattenArg args flattenStmt stmt = [ppr stmt] flattenArg (_, ApplicativeArgOne pat expr isBody) | isBody = -- See Note [Applicative BodyStmt] [ppr (BodyStmt expr noSyntaxExpr noSyntaxExpr (panic "pprStmt") :: ExprStmt idL)] | otherwise = [ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt") :: ExprStmt idL)] flattenArg (_, ApplicativeArgMany stmts _ _) = concatMap flattenStmt stmts pp_debug = let ap_expr = sep (punctuate (text " |") (map pp_arg args)) in if isNothing mb_join then ap_expr else text "join" <+> parens ap_expr pp_arg (_, ApplicativeArgOne pat expr isBody) | isBody = -- See Note [Applicative BodyStmt] ppr (BodyStmt expr noSyntaxExpr noSyntaxExpr (panic "pprStmt") :: ExprStmt idL) | otherwise = ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt") :: ExprStmt idL) pp_arg (_, ApplicativeArgMany stmts return pat) = ppr pat <+> text "<-" <+> ppr (HsDo DoExpr (noLoc (stmts ++ [noLoc (LastStmt (noLoc return) False noSyntaxExpr)])) (error "pprStmt")) pprTransformStmt :: (SourceTextX p, OutputableBndrId p) => [IdP p] -> LHsExpr p -> Maybe (LHsExpr p) -> SDoc pprTransformStmt bndrs using by = sep [ text "then" <+> whenPprDebug (braces (ppr bndrs)) , nest 2 (ppr using) , nest 2 (pprBy by)] pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc pprTransStmt by using ThenForm = sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)] pprTransStmt by using GroupForm = sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)] pprBy :: Outputable body => Maybe body -> SDoc pprBy Nothing = empty pprBy (Just e) = text "by" <+> ppr e pprDo :: (SourceTextX p, OutputableBndrId p, Outputable body) => HsStmtContext any -> [LStmt p body] -> SDoc pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts pprDo ListComp stmts = brackets $ pprComp stmts pprDo PArrComp stmts = paBrackets $ pprComp stmts pprDo MonadComp stmts = brackets $ pprComp stmts pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt ppr_do_stmts :: (SourceTextX idL, SourceTextX idR, OutputableBndrId idL, OutputableBndrId idR, Outputable body) => [LStmtLR idL idR body] -> SDoc -- Print a bunch of do stmts ppr_do_stmts stmts = pprDeeperList vcat (map ppr stmts) pprComp :: (SourceTextX p, OutputableBndrId p, Outputable body) => [LStmt p body] -> SDoc pprComp quals -- Prints: body | qual1, ..., qualn | Just (initStmts, L _ (LastStmt body _ _)) <- snocView quals = if null initStmts -- If there are no statements in a list comprehension besides the last -- one, we simply treat it like a normal list. This does arise -- occasionally in code that GHC generates, e.g., in implementations of -- 'range' for derived 'Ix' instances for product datatypes with exactly -- one constructor (e.g., see Trac #12583). then ppr body else hang (ppr body <+> vbar) 2 (pprQuals initStmts) | otherwise = pprPanic "pprComp" (pprQuals quals) pprQuals :: (SourceTextX p, OutputableBndrId p, Outputable body) => [LStmt p body] -> SDoc -- Show list comprehension qualifiers separated by commas pprQuals quals = interpp'SP quals {- ************************************************************************ * * Template Haskell quotation brackets * * ************************************************************************ -} -- | Haskell Splice data HsSplice id = HsTypedSplice -- $$z or $$(f 4) SpliceDecoration -- Whether $$( ) variant found, for pretty printing (IdP id) -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsUntypedSplice -- $z or $(f 4) SpliceDecoration -- Whether $( ) variant found, for pretty printing (IdP id) -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice (IdP id) -- Splice point (IdP id) -- Quoter SrcSpan -- The span of the enclosed string FastString -- The enclosed string | HsSpliced -- See Note [Delaying modFinalizers in untyped splices] in -- RnSplice. -- This is the result of splicing a splice. It is produced by -- the renamer and consumed by the typechecker. It lives only -- between the two. ThModFinalizers -- TH finalizers produced by the splice. (HsSplicedThing id) -- The result of splicing deriving Typeable deriving instance (DataId id) => Data (HsSplice id) -- | A splice can appear with various decorations wrapped around it. This data -- type captures explicitly how it was originally written, for use in the pretty -- printer. data SpliceDecoration = HasParens -- ^ $( splice ) or $$( splice ) | HasDollar -- ^ $splice or $$splice | NoParens -- ^ bare splice deriving (Data, Eq, Show) instance Outputable SpliceDecoration where ppr x = text $ show x isTypedSplice :: HsSplice id -> Bool isTypedSplice (HsTypedSplice {}) = True isTypedSplice _ = False -- Quasi-quotes are untyped splices -- | Finalizers produced by a splice with -- 'Language.Haskell.TH.Syntax.addModFinalizer' -- -- See Note [Delaying modFinalizers in untyped splices] in RnSplice. For how -- this is used. -- newtype ThModFinalizers = ThModFinalizers [ForeignRef (TH.Q ())] -- A Data instance which ignores the argument of 'ThModFinalizers'. instance Data ThModFinalizers where gunfold _ z _ = z $ ThModFinalizers [] toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a] -- | Haskell Spliced Thing -- -- Values that can result from running a splice. data HsSplicedThing id = HsSplicedExpr (HsExpr id) -- ^ Haskell Spliced Expression | HsSplicedTy (HsType id) -- ^ Haskell Spliced Type | HsSplicedPat (Pat id) -- ^ Haskell Spliced Pattern deriving Typeable deriving instance (DataId id) => Data (HsSplicedThing id) -- See Note [Pending Splices] type SplicePointName = Name -- | Pending Renamer Splice data PendingRnSplice -- AZ:TODO: The hard-coded GhcRn feels wrong. How to force the PostRn? = PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr GhcRn) deriving Data data UntypedSpliceFlavour = UntypedExpSplice | UntypedPatSplice | UntypedTypeSplice | UntypedDeclSplice deriving Data -- | Pending Type-checker Splice data PendingTcSplice -- AZ:TODO: The hard-coded GhcTc feels wrong. How to force the PostTc? = PendingTcSplice SplicePointName (LHsExpr GhcTc) deriving Data {- Note [Pending Splices] ~~~~~~~~~~~~~~~~~~~~~~ When we rename an untyped bracket, we name and lift out all the nested splices, so that when the typechecker hits the bracket, it can typecheck those nested splices without having to walk over the untyped bracket code. So for example [| f $(g x) |] looks like HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x))) which the renamer rewrites to HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x))) [PendingRnSplice UntypedExpSplice sn (g x)] * The 'sn' is the Name of the splice point, the SplicePointName * The PendingRnExpSplice gives the splice that splice-point name maps to; and the typechecker can now conveniently find these sub-expressions * The other copy of the splice, in the second argument of HsSpliceE in the renamed first arg of HsRnBracketOut is used only for pretty printing There are four varieties of pending splices generated by the renamer, distinguished by their UntypedSpliceFlavour * Pending expression splices (UntypedExpSplice), e.g., [|$(f x) + 2|] UntypedExpSplice is also used for * quasi-quotes, where the pending expression expands to $(quoter "...blah...") (see RnSplice.makePending, HsQuasiQuote case) * cross-stage lifting, where the pending expression expands to $(lift x) (see RnSplice.checkCrossStageLifting) * Pending pattern splices (UntypedPatSplice), e.g., [| \$(f x) -> x |] * Pending type splices (UntypedTypeSplice), e.g., [| f :: $(g x) |] * Pending declaration (UntypedDeclSplice), e.g., [| let $(f x) in ... |] There is a fifth variety of pending splice, which is generated by the type checker: * Pending *typed* expression splices, (PendingTcSplice), e.g., [||1 + $$(f 2)||] It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the output of the renamer. However, when pretty printing the output of the renamer, e.g., in a type error message, we *do not* want to print out the pending splices. In contrast, when pretty printing the output of the type checker, we *do* want to print the pending splices. So splitting them up seems to make sense, although I hate to add another constructor to HsExpr. -} instance (SourceTextX p, OutputableBndrId p) => Outputable (HsSplicedThing p) where ppr (HsSplicedExpr e) = ppr_expr e ppr (HsSplicedTy t) = ppr t ppr (HsSplicedPat p) = ppr p instance (SourceTextX p, OutputableBndrId p) => Outputable (HsSplice p) where ppr s = pprSplice s pprPendingSplice :: (SourceTextX p, OutputableBndrId p) => SplicePointName -> LHsExpr p -> SDoc pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e) pprSpliceDecl :: (SourceTextX p, OutputableBndrId p) => HsSplice p -> SpliceExplicitFlag -> SDoc pprSpliceDecl e@HsQuasiQuote{} _ = pprSplice e pprSpliceDecl e ExplicitSplice = text "$(" <> ppr_splice_decl e <> text ")" pprSpliceDecl e ImplicitSplice = ppr_splice_decl e ppr_splice_decl :: (SourceTextX p, OutputableBndrId p) => HsSplice p -> SDoc ppr_splice_decl (HsUntypedSplice _ n e) = ppr_splice empty n e empty ppr_splice_decl e = pprSplice e pprSplice :: (SourceTextX p, OutputableBndrId p) => HsSplice p -> SDoc pprSplice (HsTypedSplice HasParens n e) = ppr_splice (text "$$(") n e (text ")") pprSplice (HsTypedSplice HasDollar n e) = ppr_splice (text "$$") n e empty pprSplice (HsTypedSplice NoParens n e) = ppr_splice empty n e empty pprSplice (HsUntypedSplice HasParens n e) = ppr_splice (text "$(") n e (text ")") pprSplice (HsUntypedSplice HasDollar n e) = ppr_splice (text "$") n e empty pprSplice (HsUntypedSplice NoParens n e) = ppr_splice empty n e empty pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s pprSplice (HsSpliced _ thing) = ppr thing ppr_quasi :: OutputableBndr p => p -> p -> FastString -> SDoc ppr_quasi n quoter quote = whenPprDebug (brackets (ppr n)) <> char '[' <> ppr quoter <> vbar <> ppr quote <> text "|]" ppr_splice :: (SourceTextX p, OutputableBndrId p) => SDoc -> (IdP p) -> LHsExpr p -> SDoc -> SDoc ppr_splice herald n e trail = herald <> whenPprDebug (brackets (ppr n)) <> ppr e <> trail -- | Haskell Bracket data HsBracket p = ExpBr (LHsExpr p) -- [| expr |] | PatBr (LPat p) -- [p| pat |] | DecBrL [LHsDecl p] -- [d| decls |]; result of parser | DecBrG (HsGroup p) -- [d| decls |]; result of renamer | TypBr (LHsType p) -- [t| type |] | VarBr Bool (IdP p) -- True: 'x, False: ''T -- (The Bool flag is used only in pprHsBracket) | TExpBr (LHsExpr p) -- [|| expr ||] deriving instance (DataId p) => Data (HsBracket p) isTypedBracket :: HsBracket id -> Bool isTypedBracket (TExpBr {}) = True isTypedBracket _ = False instance (SourceTextX p, OutputableBndrId p) => Outputable (HsBracket p) where ppr = pprHsBracket pprHsBracket :: (SourceTextX p, OutputableBndrId p) => HsBracket p -> SDoc pprHsBracket (ExpBr e) = thBrackets empty (ppr e) pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p) pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp) pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds)) pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t) pprHsBracket (VarBr True n) = char '\'' <> pprPrefixOcc n pprHsBracket (VarBr False n) = text "''" <> pprPrefixOcc n pprHsBracket (TExpBr e) = thTyBrackets (ppr e) thBrackets :: SDoc -> SDoc -> SDoc thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+> pp_body <+> text "|]" thTyBrackets :: SDoc -> SDoc thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]") instance Outputable PendingRnSplice where ppr (PendingRnSplice _ n e) = pprPendingSplice n e instance Outputable PendingTcSplice where ppr (PendingTcSplice n e) = pprPendingSplice n e {- ************************************************************************ * * \subsection{Enumerations and list comprehensions} * * ************************************************************************ -} -- | Arithmetic Sequence Information data ArithSeqInfo id = From (LHsExpr id) | FromThen (LHsExpr id) (LHsExpr id) | FromTo (LHsExpr id) (LHsExpr id) | FromThenTo (LHsExpr id) (LHsExpr id) (LHsExpr id) deriving instance (DataId id) => Data (ArithSeqInfo id) instance (SourceTextX p, OutputableBndrId p) => Outputable (ArithSeqInfo p) where ppr (From e1) = hcat [ppr e1, pp_dotdot] ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot] ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3] ppr (FromThenTo e1 e2 e3) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3] pp_dotdot :: SDoc pp_dotdot = text " .. " {- ************************************************************************ * * \subsection{HsMatchCtxt} * * ************************************************************************ -} -- | Haskell Match Context -- -- Context of a pattern match. This is more subtle than it would seem. See Note -- [Varieties of pattern matches]. data HsMatchContext id -- Not an extensible tag = FunRhs { mc_fun :: Located id -- ^ function binder of @f@ , mc_fixity :: LexicalFixity -- ^ fixing of @f@ , mc_strictness :: SrcStrictness -- ^ was @f@ banged? -- See Note [FunBind vs PatBind] } -- ^A pattern matching on an argument of a -- function binding | LambdaExpr -- ^Patterns of a lambda | CaseAlt -- ^Patterns and guards on a case alternative | IfAlt -- ^Guards of a multi-way if alternative | ProcExpr -- ^Patterns of a proc | PatBindRhs -- ^A pattern binding eg [y] <- e = e | RecUpd -- ^Record update [used only in DsExpr to -- tell matchWrapper what sort of -- runtime error message to generate] | StmtCtxt (HsStmtContext id) -- ^Pattern of a do-stmt, list comprehension, -- pattern guard, etc | ThPatSplice -- ^A Template Haskell pattern splice | ThPatQuote -- ^A Template Haskell pattern quotation [p| (a,b) |] | PatSyn -- ^A pattern synonym declaration deriving Functor deriving instance (Data id) => Data (HsMatchContext id) instance OutputableBndr id => Outputable (HsMatchContext id) where ppr m@(FunRhs{}) = text "FunRhs" <+> ppr (mc_fun m) <+> ppr (mc_fixity m) ppr LambdaExpr = text "LambdaExpr" ppr CaseAlt = text "CaseAlt" ppr IfAlt = text "IfAlt" ppr ProcExpr = text "ProcExpr" ppr PatBindRhs = text "PatBindRhs" ppr RecUpd = text "RecUpd" ppr (StmtCtxt _) = text "StmtCtxt _" ppr ThPatSplice = text "ThPatSplice" ppr ThPatQuote = text "ThPatQuote" ppr PatSyn = text "PatSyn" isPatSynCtxt :: HsMatchContext id -> Bool isPatSynCtxt ctxt = case ctxt of PatSyn -> True _ -> False -- | Haskell Statement Context. It expects to be parameterised with one of -- 'RdrName', 'Name' or 'Id' data HsStmtContext id = ListComp | MonadComp | PArrComp -- ^Parallel array comprehension | DoExpr -- ^do { ... } | MDoExpr -- ^mdo { ... } ie recursive do-expression | ArrowExpr -- ^do-notation in an arrow-command context | GhciStmtCtxt -- ^A command-line Stmt in GHCi pat <- rhs | PatGuard (HsMatchContext id) -- ^Pattern guard for specified thing | ParStmtCtxt (HsStmtContext id) -- ^A branch of a parallel stmt | TransStmtCtxt (HsStmtContext id) -- ^A branch of a transform stmt deriving Functor deriving instance (Data id) => Data (HsStmtContext id) isListCompExpr :: HsStmtContext id -> Bool -- Uses syntax [ e | quals ] isListCompExpr ListComp = True isListCompExpr PArrComp = True isListCompExpr MonadComp = True isListCompExpr (ParStmtCtxt c) = isListCompExpr c isListCompExpr (TransStmtCtxt c) = isListCompExpr c isListCompExpr _ = False isMonadCompExpr :: HsStmtContext id -> Bool isMonadCompExpr MonadComp = True isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt isMonadCompExpr _ = False -- | Should pattern match failure in a 'HsStmtContext' be desugared using -- 'MonadFail'? isMonadFailStmtContext :: HsStmtContext id -> Bool isMonadFailStmtContext MonadComp = True isMonadFailStmtContext DoExpr = True isMonadFailStmtContext MDoExpr = True isMonadFailStmtContext GhciStmtCtxt = True isMonadFailStmtContext _ = False matchSeparator :: HsMatchContext id -> SDoc matchSeparator (FunRhs {}) = text "=" matchSeparator CaseAlt = text "->" matchSeparator IfAlt = text "->" matchSeparator LambdaExpr = text "->" matchSeparator ProcExpr = text "->" matchSeparator PatBindRhs = text "=" matchSeparator (StmtCtxt _) = text "<-" matchSeparator RecUpd = text "=" -- This can be printed by the pattern -- match checker trace matchSeparator ThPatSplice = panic "unused" matchSeparator ThPatQuote = panic "unused" matchSeparator PatSyn = panic "unused" pprMatchContext :: (Outputable (NameOrRdrName id),Outputable id) => HsMatchContext id -> SDoc pprMatchContext ctxt | want_an ctxt = text "an" <+> pprMatchContextNoun ctxt | otherwise = text "a" <+> pprMatchContextNoun ctxt where want_an (FunRhs {}) = True -- Use "an" in front want_an ProcExpr = True want_an _ = False pprMatchContextNoun :: (Outputable (NameOrRdrName id),Outputable id) => HsMatchContext id -> SDoc pprMatchContextNoun (FunRhs {mc_fun=L _ fun}) = text "equation for" <+> quotes (ppr fun) pprMatchContextNoun CaseAlt = text "case alternative" pprMatchContextNoun IfAlt = text "multi-way if alternative" pprMatchContextNoun RecUpd = text "record-update construct" pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice" pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation" pprMatchContextNoun PatBindRhs = text "pattern binding" pprMatchContextNoun LambdaExpr = text "lambda abstraction" pprMatchContextNoun ProcExpr = text "arrow abstraction" pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in" $$ pprStmtContext ctxt pprMatchContextNoun PatSyn = text "pattern synonym declaration" ----------------- pprAStmtContext, pprStmtContext :: (Outputable id, Outputable (NameOrRdrName id)) => HsStmtContext id -> SDoc pprAStmtContext ctxt = article <+> pprStmtContext ctxt where pp_an = text "an" pp_a = text "a" article = case ctxt of MDoExpr -> pp_an PArrComp -> pp_an GhciStmtCtxt -> pp_an _ -> pp_a ----------------- pprStmtContext GhciStmtCtxt = text "interactive GHCi command" pprStmtContext DoExpr = text "'do' block" pprStmtContext MDoExpr = text "'mdo' block" pprStmtContext ArrowExpr = text "'do' block in an arrow command" pprStmtContext ListComp = text "list comprehension" pprStmtContext MonadComp = text "monad comprehension" pprStmtContext PArrComp = text "array comprehension" pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt -- Drop the inner contexts when reporting errors, else we get -- Unexpected transform statement -- in a transformed branch of -- transformed branch of -- transformed branch of monad comprehension pprStmtContext (ParStmtCtxt c) = ifPprDebug (sep [text "parallel branch of", pprAStmtContext c]) (pprStmtContext c) pprStmtContext (TransStmtCtxt c) = ifPprDebug (sep [text "transformed branch of", pprAStmtContext c]) (pprStmtContext c) instance (Outputable p, Outputable (NameOrRdrName p)) => Outputable (HsStmtContext p) where ppr = pprStmtContext -- Used to generate the string for a *runtime* error message matchContextErrString :: Outputable id => HsMatchContext id -> SDoc matchContextErrString (FunRhs{mc_fun=L _ fun}) = text "function" <+> ppr fun matchContextErrString CaseAlt = text "case" matchContextErrString IfAlt = text "multi-way if" matchContextErrString PatBindRhs = text "pattern binding" matchContextErrString RecUpd = text "record update" matchContextErrString LambdaExpr = text "lambda" matchContextErrString ProcExpr = text "proc" matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c) matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c) matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard" matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command" matchContextErrString (StmtCtxt DoExpr) = text "'do' block" matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block" matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block" matchContextErrString (StmtCtxt ListComp) = text "list comprehension" matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension" matchContextErrString (StmtCtxt PArrComp) = text "array comprehension" pprMatchInCtxt :: (SourceTextX idR, OutputableBndrId idR, -- TODO:AZ these constraints do not make sense Outputable (NameOrRdrName (NameOrRdrName (IdP idR))), Outputable body) => Match idR body -> SDoc pprMatchInCtxt match = hang (text "In" <+> pprMatchContext (m_ctxt match) <> colon) 4 (pprMatch match) pprStmtInCtxt :: (SourceTextX idL, SourceTextX idR, OutputableBndrId idL, OutputableBndrId idR, Outputable body) => HsStmtContext (IdP idL) -> StmtLR idL idR body -> SDoc pprStmtInCtxt ctxt (LastStmt e _ _) | isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts" = hang (text "In the expression:") 2 (ppr e) pprStmtInCtxt ctxt stmt = hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon) 2 (ppr_stmt stmt) where -- For Group and Transform Stmts, don't print the nested stmts! ppr_stmt (TransStmt { trS_by = by, trS_using = using , trS_form = form }) = pprTransStmt by using form ppr_stmt stmt = pprStmt stmt
ezyang/ghc
compiler/hsSyn/HsExpr.hs
bsd-3-clause
104,032
0
20
29,307
17,702
9,354
8,348
1,161
17
module J ( module J , module J.Store ) where import J.Store data J = J { key :: String , dst :: String }
KenetJervet/j
src/J.hs
bsd-3-clause
147
0
8
67
42
27
15
5
0
module Diag.Util.RecursiveContents (getRecursiveContents) where import Control.Monad (forM) import System.Directory (doesDirectoryExist, getDirectoryContents) import System.FilePath ((</>)) getRecursiveContents :: FilePath -> IO [FilePath] getRecursiveContents topdir = do names <- getDirectoryContents topdir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do let path = topdir </> name isDirectory <- doesDirectoryExist path if isDirectory then getRecursiveContents path else return [path] return (concat paths)
marcmo/hsDiagnosis
src/Diag/Util/RecursiveContents.hs
bsd-3-clause
593
0
15
100
180
95
85
15
2
{-# LANGUAGE RankNTypes, TypeOperators, DefaultSignatures #-} -- | No comparison that I'm aware of module MHask.Indexed.Layered where import MHask.Arrow import qualified MHask.Indexed.Join as MHask import qualified MHask.Indexed.Duplicate as MHask -- | IxLayered is its own dual. class (MHask.IxJoin t, MHask.IxDuplicate t) => IxLayered t where -- | Any instances must satisfy the following laws: -- -- > iduplicate ~>~ ijoin ≡ identityArrow ∷ t i j m -> t i j m -- -- Custom implementations should be equivalent to the -- default implementation -- -- iwithLayer f ≡ iduplicate ~>~ f ~>~ ijoin -- -- From all laws required so far, it follows that: -- -- > iwithLayer (imap (imap f)) ≡ imap f -- > iwithLayer (imap ijoin) ≡ join -- > iwithLayer (imap iduplicate) ≡ duplicate -- > iwithLayer identityArrow ≡ identityArrow -- -- However, take note that the following are not guaranteed, -- and are usually not true: -- -- > ijoin ~>~ iduplicate ≟ identityArrow -- > iwithLayer (f ~>~ g) ≟ iwithLayer f ~>~ iwithLayer g iwithLayer :: (Monad m, Monad n) => (t i j (t j k m) ~> t i' j' (t j' k' n)) -> (t i k m ~> t i' k' n ) default iwithLayer :: (Monad m, Monad n, Monad (t i k m), Monad (t i' k' n), Monad (t i j (t j k m)), Monad (t i' j' (t j' k' n))) => (t i j (t j k m) ~> t i' j' (t j' k' n)) -> (t i k m ~> t i' k' n ) iwithLayer f = MHask.iduplicate ~>~ f ~>~ MHask.ijoin
DanBurton/MHask
MHask/Indexed/Layered.hs
bsd-3-clause
1,543
0
14
422
360
199
161
17
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Servant.FileUpload.Client.GHC where import Data.Proxy (Proxy (..)) import Data.Void (Void, absurd) import Servant.API ((:>)) import Servant.Client (HasClient (..)) import Servant.FileUpload.API instance (HasClient sublayout) => HasClient (MultiPartBody a :> sublayout) where type Client (MultiPartBody a :> sublayout) = Void -> Client sublayout clientWithRoute Proxy req void = absurd void
rimmington/servant-file-upload
servant-file-upload-client/src/Servant/FileUpload/Client/GHC.hs
bsd-3-clause
550
0
8
83
139
82
57
14
0
module Chapter9Exercises where import Data.Maybe import Data.Char -- exercise 2 str = "HbEfLrLxO" onlyUpperHello = filter isUpper str -- exercise 3 julie = "julie" capitalize :: [Char] -> [Char] capitalize [] = [] capitalize (a:as) = toUpper a : as -- exercise 4 toAllUpper :: [Char] -> [Char] toAllUpper [] = [] toAllUpper (a:as) = toUpper a : toAllUpper as -- exercise 5 capitalizeFirst :: [Char] -> Maybe Char capitalizeFirst [] = Nothing capitalizeFirst (a:as) = Just $ toUpper a capitalizeFirst' :: [Char] -> [Char] capitalizeFirst' [] = [] capitalizeFirst' (a:as) = [toUpper a] -- exercise 6 -- as composed capitalizeFirst'' :: [Char] -> [Char] capitalizeFirst'' [] = [] capitalizeFirst'' as = [(toUpper . head) as] -- as composed point-free -- I can't figure out how to make this point-free -- *and* total. If I include [] = [] and the -- point-free version together (without the case -- version) I get: -- Chapter9.hs:45:1: error: -- Equations for `capitalizeFirst_' have different numbers of arguments -- Chapter9.hs:45:1-24 -- Chapter9.hs:46:1-47 -- Failed, modules loaded: none. -- but if I change it to handle the empty list -- it's not point-free... capitalizeFirst_ :: [Char] -> [Char] -- capitalizeFirst_ [] = [] capitalizeFirst_ xs = case length xs of 0 -> [] _ -> ((\c -> [c]) . toUpper . head) xs --capitalizeFirst_ = (\c -> [c]) . toUpper . head
brodyberg/Notes
ProjectRosalind.hsproj/LearnHaskell/lib/HaskellBook/Chapter9.hs
mit
1,403
0
14
265
367
206
161
26
2
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : ./Syntax/AS_Architecture.der.hs Description : abstract syntax of CASL architectural specifications Copyright : (c) Klaus Luettich, Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable(imports Syntax.AS_Structured) Abstract syntax of (Het)CASL architectural specifications Follows Sect. II:2.2.4 of the CASL Reference Manual. -} module Syntax.AS_Architecture where -- DrIFT command: {-! global: GetRange !-} import Common.Id import Common.IRI import Common.AS_Annotation import Syntax.AS_Structured import Data.Typeable -- for arch-spec-defn and unit-spec-defn see AS_Library data ARCH_SPEC = Basic_arch_spec [Annoted UNIT_DECL_DEFN] (Annoted UNIT_EXPRESSION) Range -- pos: "unit","result" | Arch_spec_name ARCH_SPEC_NAME | Group_arch_spec (Annoted ARCH_SPEC) Range -- pos: "{","}" deriving (Show, Typeable) data UNIT_DECL_DEFN = Unit_decl UNIT_NAME REF_SPEC [Annoted UNIT_TERM] Range -- pos: ":", opt ("given"; Annoted holds pos of commas) | Unit_defn UNIT_NAME UNIT_EXPRESSION Range -- pos: "=" deriving (Show, Typeable) data UNIT_SPEC = Unit_type [Annoted SPEC] (Annoted SPEC) Range -- pos: opt "*"s , "->" | Spec_name SPEC_NAME | Closed_unit_spec UNIT_SPEC Range -- pos: "closed" deriving (Show, Typeable) data REF_SPEC = Unit_spec UNIT_SPEC | Refinement Bool UNIT_SPEC [G_mapping] REF_SPEC Range -- false means "behaviourally" | Arch_unit_spec (Annoted ARCH_SPEC) Range {- pos: "arch","spec" The ARCH_SPEC has to be surrounded with braces and after the opening brace is a [Annotation] allowed -} | Compose_ref [REF_SPEC] Range -- pos: "then" | Component_ref [UNIT_REF] Range -- pos "{", commas and "}" deriving (Show, Typeable) data UNIT_REF = Unit_ref UNIT_NAME REF_SPEC Range -- pos: ":" deriving (Show, Typeable) data UNIT_EXPRESSION = Unit_expression [UNIT_BINDING] (Annoted UNIT_TERM) Range -- pos: opt "lambda",semi colons, "." deriving (Show, Typeable) data UNIT_BINDING = Unit_binding UNIT_NAME UNIT_SPEC Range -- pos: ":" deriving (Show, Typeable) data UNIT_TERM = Unit_reduction (Annoted UNIT_TERM) RESTRICTION | Unit_translation (Annoted UNIT_TERM) RENAMING | Amalgamation [Annoted UNIT_TERM] Range -- pos: "and"s | Local_unit [Annoted UNIT_DECL_DEFN] (Annoted UNIT_TERM) Range -- pos: "local", "within" | Unit_appl UNIT_NAME [FIT_ARG_UNIT] Range -- pos: many of "[","]" | Group_unit_term (Annoted UNIT_TERM) Range -- pos: "{","}" deriving (Show, Typeable) data FIT_ARG_UNIT = Fit_arg_unit (Annoted UNIT_TERM) [G_mapping] Range -- pos: opt "fit" deriving (Show, Typeable) type ARCH_SPEC_NAME = IRI type UNIT_NAME = IRI
spechub/Hets
Syntax/AS_Architecture.der.hs
gpl-2.0
3,505
0
8
1,164
492
282
210
42
0
-- Compiler Toolkit: compiler state management -- -- Author : Manuel M. T. Chakravarty -- Created: 2 November 95 -- -- Version $Revision: 1.1.1.1 $ from $Date: 2004/11/13 16:42:45 $ -- -- Copyright (c) [1995..1999] Manuel M. T. Chakravarty -- -- This file 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 file 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. -- --- DESCRIPTION --------------------------------------------------------------- -- -- This module forms the interface to the state base of the compiler. It is -- used by all modules that are not directly involved in implementing the -- state base. It provides a state transformer that is capable of doing I/O -- and provides facilities such as error handling and compiler switch -- management. -- --- DOCU ---------------------------------------------------------------------- -- -- language: Haskell 98 -- -- * The monad `PreCST' is reexported abstractly. -- -- * Errors are dumped to `stdout' to facilitate communication with other -- processes (see `Interact'). -- --- TODO ---------------------------------------------------------------------- -- module State (-- the PreCST monad -- PreCST, -- reexport ABSTRACT nop, yield, (+>=), (+>), fixCST, -- reexport throwExc, fatal, catchExc, fatalsHandledBy, -- reexport lifted readCST, writeCST, transCST, run, runCST, StateTrans.MVar, -- reexport newMV, readMV, assignMV, -- reexport lifted -- -- reexport compiler I/O -- module CIO, liftIO, -- -- identification -- getId, -- -- error management -- raise, raiseWarning, raiseError, raiseFatal, showErrors, errorsPresent, -- -- extra state management -- readExtra, updExtra, -- -- name supplies -- getNameSupply) where import Data.Ix import Control.Monad (when) import Data.List (sort) import BaseVersion (version, copyright, disclaimer) import Config (errorLimit) import Position (Position) import UNames (NameSupply, rootSupply, splitSupply) import StateTrans (STB, readBase, transBase, runSTB) import qualified StateTrans (interleave, throwExc, fatal, catchExc, fatalsHandledBy, MVar, newMV, readMV, assignMV) import StateBase (PreCST(..), ErrorState(..), BaseState(..), nop, yield, (+>=), (+>), fixCST, unpackCST, readCST, writeCST, transCST, liftIO) import CIO import Errors (ErrorLvl(..), Error, makeError, errorLvl, showError) -- state used in the whole compiler -- -------------------------------- -- initialization -- -- * it gets the version information and the initial extra state as arguments -- initialBaseState :: (String, String, String) -> e -> BaseState e initialBaseState vcd es = BaseState { idTKBS = (version, copyright, disclaimer), idBS = vcd, errorsBS = initialErrorState, suppliesBS = splitSupply rootSupply, extraBS = es } -- executing state transformers -- ---------------------------- -- initiate a complete run of the ToolKit represented by a PreCST with a void -- generic component (type `()') (EXPORTED) -- -- * fatals errors are explicitly caught and reported (instead of letting them -- through to the runtime system) -- run :: (String, String, String) -> e -> PreCST e () a -> IO a run vcd es cst = runSTB m (initialBaseState vcd es) () where m = unpackCST ( cst `fatalsHandledBy` \err -> putStrCIO ("Uncaught fatal error: " ++ show err) >> exitWithCIO (ExitFailure 1) ) -- run a PreCST in the context of another PreCST (EXPORTED) -- -- the generic state of the enclosing PreCST is preserved while the -- computation of the PreCST passed as an argument is interleaved in the -- execution of the enclosing one -- runCST :: PreCST e s a -> s -> PreCST e s' a runCST m s = CST $ StateTrans.interleave (unpackCST m) s -- exception handling -- ------------------ -- throw an exception with the given tag and message (EXPORTED) -- throwExc :: String -> String -> PreCST e s a throwExc s1 s2 = CST $ StateTrans.throwExc s1 s2 -- raise a fatal user-defined error (EXPORTED) -- -- * such an error my be caught and handled using `fatalsHandeledBy' -- fatal :: String -> PreCST e s a fatal = CST . StateTrans.fatal -- the given state transformer is executed and exceptions with the given tag -- are caught using the provided handler, which expects to get the exception -- message (EXPORTED) -- -- * the state observed by the exception handler is *modified* by the failed -- state transformer upto the point where the exception was thrown (this -- semantics is the only reasonable when it should be possible to use -- updating for maintaining the state) -- catchExc :: PreCST e s a -> (String, String -> PreCST e s a) -> PreCST e s a catchExc m (s, h) = CST $ StateTrans.catchExc (unpackCST m) (s, unpackCST . h) -- given a state transformer that may raise fatal errors and an error handler -- for fatal errors, execute the state transformer and apply the error handler -- when a fatal error occurs (EXPORTED) -- -- * fatal errors are IO monad errors and errors raised by `fatal' as well as -- uncaught exceptions -- -- * the base and generic state observed by the error handler is *in contrast -- to `catch'* the state *before* the state transformer is applied -- fatalsHandledBy :: PreCST e s a -> (IOError -> PreCST e s a) -> PreCST e s a fatalsHandledBy m h = CST $ StateTrans.fatalsHandledBy m' h' where m' = unpackCST m h' = unpackCST . h -- mutable variables -- ----------------- -- lifted mutable variable functions (EXPORTED) -- newMV :: a -> PreCST e s (StateTrans.MVar a) newMV = CST . StateTrans.newMV readMV :: StateTrans.MVar a -> PreCST e s a readMV = CST . StateTrans.readMV assignMV :: StateTrans.MVar a -> a -> PreCST e s () assignMV m a = CST $ StateTrans.assignMV m a -- read identification -- ------------------- -- read identification information (EXPORT) -- getId :: PreCST e s (String, String, String) getId = CST $ readBase (idBS) -- manipulating the error state -- ---------------------------- -- the lowest level of errors is `WarningErr', but it is meaningless as long as -- the the list of errors is empty -- initialErrorState :: ErrorState initialErrorState = ErrorState WarningErr 0 [] -- raise an error (EXPORTED) -- -- * a fatal error is reported immediately; see `raiseFatal' -- raise :: Error -> PreCST e s () raise err = case errorLvl err of WarningErr -> raise0 err ErrorErr -> raise0 err FatalErr -> raiseFatal0 "Generic fatal error." err -- raise a warning (see `raiseErr') (EXPORTED) -- raiseWarning :: Position -> [String] -> PreCST e s () raiseWarning pos msg = raise0 (makeError WarningErr pos msg) -- raise an error (see `raiseErr') (EXPORTED) -- raiseError :: Position -> [String] -> PreCST e s () raiseError pos msg = raise0 (makeError ErrorErr pos msg) -- raise a fatal compilation error (EXPORTED) -- -- * the error is together with the up-to-now accumulated errors are reported -- as part of the error message of the fatal error exception -- -- * the current thread of control is discarded and control is passed to the -- innermost handler for fatal errors -- -- * the first argument must contain a short description of the error, while -- the second and third argument are like the two arguments to `raise' -- raiseFatal :: String -> Position -> [String] -> PreCST e s a raiseFatal short pos long = raiseFatal0 short (makeError FatalErr pos long) -- raise a fatal error; internal version that gets an abstract error -- raiseFatal0 :: String -> Error -> PreCST e s a raiseFatal0 short err = do raise0 err errmsgs <- showErrors fatal (short ++ "\n\n" ++ errmsgs) -- raise an error; internal version, doesn't check whether the error is fatal -- -- * the error is entered into the compiler state and a fatal error is -- triggered if the `errorLimit' is reached -- raise0 :: Error -> PreCST e s () raise0 err = do noOfErrs <- CST $ transBase doRaise when (noOfErrs >= errorLimit) $ do errmsgs <- showErrors fatal ("Error limit of " ++ show errorLimit ++ " errors has been reached.\n" ++ errmsgs) where doRaise :: BaseState e -> (BaseState e, Int) doRaise bs = let lvl = errorLvl err ErrorState wlvl no errs = errorsBS bs wlvl' = max wlvl lvl no' = no + if lvl > WarningErr then 1 else 0 errs' = err : errs in (bs {errorsBS = (ErrorState wlvl' no' errs')}, no') -- yield a string containing the collected error messages (EXPORTED) -- -- * the error state is reset in this process -- showErrors :: PreCST e s String showErrors = CST $ do ErrorState wlvl no errs <- transBase extractErrs return $ foldr (.) id (map showString (errsToStrs errs)) "" where extractErrs :: BaseState e -> (BaseState e, ErrorState) extractErrs bs = (bs {errorsBS = initialErrorState}, errorsBS bs) errsToStrs :: [Error] -> [String] errsToStrs errs = (map showError . sort) errs -- inquire if there was already an error of at least level `ErrorErr' raised -- (EXPORTED) -- errorsPresent :: PreCST e s Bool errorsPresent = CST $ do ErrorState wlvl no _ <- readBase errorsBS return $ wlvl >= ErrorErr -- manipulating the extra state -- ---------------------------- -- apply a reader function to the extra state and yield the reader's result -- (EXPORTED) -- readExtra :: (e -> a) -> PreCST e s a readExtra rf = CST $ readBase (\bs -> (rf . extraBS) bs ) -- apply an update function to the extra state (EXPORTED) -- updExtra :: (e -> e) -> PreCST e s () updExtra uf = CST $ transBase (\bs -> let es = extraBS bs in (bs {extraBS = uf es}, ()) ) -- name supplies -- ------------- -- Get a name supply out of the base state (EXPORTED) -- getNameSupply :: PreCST e s NameSupply getNameSupply = CST $ transBase (\bs -> let supply : supplies = suppliesBS bs in (bs {suppliesBS = supplies}, supply) )
k0001/gtk2hs
tools/c2hs/base/state/State.hs
gpl-3.0
12,092
0
15
3,880
2,022
1,156
866
130
3
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ParallelListComp #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RecordWildCards #-} -- | A very simple Graphical User Interface (GUI) for user interaction with -- buttons, checkboxes, sliders and a few others. module Extras.Widget( -- $intro guiDrawingOf, guiActivityOf -- * Widgets , Widget, toggle, button, slider, randomBox, timer, counter -- * Convenience functions , withConversion, setConversion -- * Examples , widgetExample1, widgetExample2, widgetExample3, widgetExample4 ) where import Prelude -------------------------------------------------------------------------------- -- $intro -- = Widget API -- -- To use the extra features in this module, you must begin your code with this -- line: -- -- > import Extras.Widget -- | The function @guiDrawingOf@ is an entry point for drawing that allows -- access to a simple GUI. It needs two arguments: a list of -- Widgets and a function to create your drawing. This user-supplied drawing -- function will have access to the list of the current values of the widgets, -- which is passed as an argument. -- -- Example of use: -- -- > program = guiDrawingOf(widgets,draw) -- > where -- > widgets = [ withConversion(\v -> 1 + 19 * v , slider("width" ,-7,-7)) -- > , withConversion(\v -> 1 + 19 * v , slider("height" ,-7,-9)) -- > , withConversion(flipflop , toggle("show circle" ,-7,-5)) -- > , withConversion(flipflop , button("show in green",-7,-3)) -- > , withConversion(\v -> 0.2 + 0.8 * v, randomBox("radius" ,-7,-1)) -- > ] -- > -- > flipflop(v) = truncation(1 + 2 * v) -- > -- > draw(values) = blank -- > & [blank, circle(r)]#s -- > & colored(solidRectangle(w,h),[red,green]#c) -- > where -- > w = values#1 -- > h = values#2 -- > s = values#3 -- > c = values#4 -- > r = values#5 -- -- Note that the order in which the widgets are defined is important, -- because it determines how to access the correct value. -- Each widget fits in a box 4 units wide and 1 unit high. guiDrawingOf :: ([Widget],[Number] -> Picture) -> Program guiDrawingOf(widgetsUser,drawUser) = activityOf(initAll,updateAll,drawAll) where initAll(rs) = initRandom(widgetsUser,rs) updateAll(ws,event) = ws.$updateWidget(event) drawAll(ws) = pictures(ws.$drawWidget) & drawUser(ws.$value) -- | The function @guiActivityOf@ is similar to @activityOf@, but it also -- takes in a list of widgets. The updating and drawing functions also -- receive a list of the current values of the widgets. -- -- Example of use: -- -- > program = guiActivityOf(widgets,init,update,draw) -- > where -- > widgets = [ withConversion(\v -> 20 * v, slider("width",-7,-7)) -- > , withConversion(\v -> 2 + 3 * v, slider("height",-7,-9)) -- > , withConversion -- > (\v -> truncation(1 + 2*v), toggle("show circle",-7,-5)) -- > , button("restart",-7,-3) -- > , randomBox("new color",-7,-1) -- > ] -- > -- > draw(values,(color@(RGB(r1,r2,r3)),angle,_)) = colored(base,color) -- > & [blank, circle(5)]#s -- > & translated(lettering(msg),0,9) -- > where -- > msg = joined(["(",printed(r1),",",printed(r2),",",printed(r3),")"]) -- > base = rotated(solidRectangle(w,h),angle) -- > w = values#1 -- > h = values#2 -- > s = values#3 -- > -- > init(rs) = (RGB(rs#1,rs#2,rs#3),0,0) -- > -- > update(values,(color@(RGB(r1,r2,r3)),angle,wait),TimePassing(_)) -- > | values#4 > 0 , wait == 0 = (RGB(r2,r3,r),0,values#4) -- > | otherwise = (color,angle+1,wait) -- > where -- > r = values#5 -- > -- > update(values,(color,angle,wait),PointerRelease(_)) = (color,angle,0) -- > -- > update(values,state,event) = state -- -- Note that pre-defined actions on the widgets take precedence over -- anything that you define in your updating function, so you cannot -- alter the default behavior of the widgets. guiActivityOf :: ( [Widget] , [Number] -> state , ([Number],state,Event) -> state , ([Number],state) -> Picture) -> Program guiActivityOf(widgetsUser,initUser,updateUser,drawUser) = activityOf(initAll,updateAll,drawAll) where initAll(rs) = ( initRandom(widgetsUser,rest(rs,1)) , initUser(randomNumbers(rs#1))) updateAll((widgets,state),event) = (newWidgets,updateUser(widgets.$value,state,event)) where newWidgets = widgets.$updateWidget(event) drawAll(widgets,state) = pictures(widgets.$drawWidget) & drawUser(widgets.$value,state) initRandom(ws,rs) = [ t(w,r) | w <- ws | r <- rs ] where t(w,r) | isRandom(w) = let rp = randomNumbers(r) in w { value_ = rp#1, randomPool = rest(rp,1) } | otherwise = w isRandom(Widget{widget = Random}) = True isRandom(_ ) = False -- | A button placed at the given location. While -- the button is pressed, the value produced is 0.5, -- but when the button is released, the value reverts -- back to 0. button :: (Text,Number,Number) -> Widget button(p) = (newWidget(p)) { widget = Button } -- | A toggle (checkbox) with the given label at the given location. -- When the box is not set, the value produced is 0. When the -- box is set, the value produced is 0.5 toggle :: (Text,Number,Number) -> Widget toggle(p) = (newWidget(p)) { widget = Toggle } -- | A slider with the given label at the given location. -- The possible values will range from 0 to 1, and the initial -- value will be 0. slider :: (Text,Number,Number) -> Widget slider(p) = (newWidget(p)) { widget = Slider } -- | A box that produces a random number between 0 and 1. -- Each time you click on it, the value will change. The -- value 1 is never produced, so the actual range of -- values is 0 to 0.99999... randomBox :: (Text,Number,Number) -> Widget randomBox(p) = (newWidget(p)) { widget = Random } -- | A button that keeps incrementing the value each time you press it. -- The initial value is 1. counter :: (Text,Number,Number) -> Widget counter(p) = (newWidget(p)) { widget = Counter, value_ = 1 } -- | A toggle that counts time up when you set it. When you click on -- the left side of the widget, the current value is reset to 0. -- You can stop the timer and start it again, and the value will increase -- from where it was when you stopped it. -- -- Example: -- -- > program = guiDrawingOf(widgets,draw) -- > where -- > widgets = [ withConversion(\v -> 1 + 9 * v , slider("length",-7,-7)) -- > , withConversion(\v -> v * 30 , timer("angle" ,-7,-9)) ] -- > -- > draw([l,a]) = rotated(translated(colored(solidRectangle(l,0.25),red),l/2,0),a) -- -- The timer operates in seconds, including decimals. However, the precision -- of the timer is not guaranteed beyond one or two decimals. -- timer :: (Text,Number,Number) -> Widget timer(p) = (newWidget(p)) { widget = Timer } -- | Make the widget use the provided function to convert values from -- the default range of a widget to a different range. -- -- Example: -- -- > newSlider = withConversion(\v -> 20 * v - 10, oldSlider) -- -- Assuming that the old slider did not have any conversion function applied -- to it, the example above will make the new slider produce values -- between -10 and 10, while the old slider will still produce values -- between 0 and 1 withConversion :: (Number -> Number, Widget) -> Widget withConversion(conv,w) = w { conversion = conv } -- | Same functionality as @withConversion@, but using a different convention -- for the arguments. setConversion :: (Number -> Number) -> Widget -> Widget setConversion(conv)(w) = w { conversion = conv } -- | This is the example shown in the documentation for @guiDrawingOf@ widgetExample1 :: Program widgetExample1 = guiDrawingOf(widgets,draw) where widgets = [ withConversion(\v -> 1 + 19 * v , slider("width" ,-7,-7)) , withConversion(\v -> 1 + 19 * v , slider("height" ,-7,-9)) , withConversion(flipflop , toggle("show circle" ,-7,-5)) , withConversion(flipflop , button("show in green",-7,-3)) , withConversion(\v -> 0.2 + 0.8 * v, randomBox("radius" ,-7,-1)) ] flipflop(v) = truncation(1 + 2 * v) draw(values) = blank & [blank, circle(r)]#s & colored(solidRectangle(w,h),[red,green]#c) where w = values#1 h = values#2 s = values#3 c = values#4 r = values#5 -- | This is the example shown in the documentation for @guiActivityOf@ widgetExample2 :: Program widgetExample2 = guiActivityOf(widgets,init,update,draw) where widgets = [ withConversion(\v -> 20 * v, slider("width",-7,-7)) , withConversion(\v -> 2 + 3 * v, slider("height",-7,-9)) , withConversion (\v -> truncation(1 + 2*v), toggle("show circle",-7,-5)) , button("restart",-7,-3) , randomBox("new color",-7,-1) ] draw(values,(color@(RGB(r1,r2,r3)),angle,_)) = colored(base,color) & [blank, circle(5)]#s & translated(lettering(msg),0,9) where msg = joined(["(",printed(r1),",",printed(r2),",",printed(r3),")"]) base = rotated(solidRectangle(w,h),angle) w = values#1 h = values#2 s = values#3 init(rs) = (RGB(rs#1,rs#2,rs#3),0,0) update(values,(color@(RGB(r1,r2,r3)),angle,wait),TimePassing(_)) | values#4 > 0 , wait == 0 = (RGB(r2,r3,r),0,values#4) | otherwise = (color,angle+1,wait) where r = values#5 update(values,(color,angle,wait),PointerRelease(_)) = (color,angle,0) update(values,state,event) = state -- | This is the example shown in the documentation for @timer@ widgetExample3 = guiDrawingOf(widgets,draw) where widgets = [ withConversion(\v -> 1 + 9 * v , slider("length",-7,-7)) , withConversion(\v -> v * 30 , timer("angle" ,-7,-9)) ] draw([l,a]) = rotated(translated(colored(solidRectangle(l,0.25),red),l/2,0),a) -- | This example shows a tree created by a recursive function widgetExample4 = guiDrawingOf(widgets,draw) -- Example copied from code shared by cdsmith where -- depth = 6 : 6 levels of detail -- decay = 0.5 : Each smaller branch decreases in size by 50%. -- stem = 0.5 : Branches occur 50% of the way up the stem. -- angle = 30 : Branches point 30 degrees away from the stem. widgets = [ slider("depth",-8,9.5).#setConversion(\p -> truncation(3 + 4*p)) , timer("decay",-8,8).#setConversion(\p -> 0.3 + 0.25*saw(p,5)) , timer("stem",-8,6.5).#setConversion(\p -> saw(p,17)) , slider("angle",-8,5).#setConversion(\p -> 5 + 30*p) ] draw([depth,decay,stem,angle]) = translated(scaled(branch(depth,decay,stem,angle), 2*decay, 2*decay),0,-5) branch(0, _, _, _) = polyline[(0,0), (0,5)] branch(depth, decay, stem, angle) = blank & polyline[(0,0), (0, 5)] & translated(smallBranch, 0, 5) & translated(rotated(smallBranch, angle), 0, stem * 5) & translated(rotated(smallBranch, -angle), 0, stem * 5) where smallBranch = scaled(branch(depth-1, decay, stem, angle), 1-decay, 1-decay) saw(t,p) = 1 - abs(2*abs(remainder(t,p))/p - 1) -------------------------------------------------------------------------------- -- Internal -------------------------------------------------------------------------------- data WidgetType = Button | Toggle | Slider | Random | Counter | Timer -- | The internal structure of a @Widget@ is not exposed in the user interface. You -- have access only to the current value of each widget. data Widget = Widget { selected :: Truth , highlight :: Truth , width :: Number , height :: Number , centerAt :: (Number,Number) , label :: Text , conversion :: Number -> Number , value_ :: Number , widget :: WidgetType , randomPool :: [Number] } newWidget(l,x,y) = Widget { selected = False, highlight = False, width = 4, height = 1 , centerAt = (x,y), label = l , value_ = 0, conversion = (\v -> v) , widget = Button, randomPool = [] } -- The value, adjusted according to the conversion function value :: Widget -> Number value(Widget{..}) = value_.#conversion -- The current value of a widget is set as follows. -- For sliders, the value is a Number -- between 0 and 1 (both included). For buttons and checkboxes, -- the value is 0 when they are not set and 0.5 when they are set. -- These values allow user programs to work with either -- @guiDrawingOf@ or @randomDrawingOf@ interchangeably, without having -- to alter the calculations in the code. hit(mx,my,Widget {..}) = abs(mx-x) < width/2 && abs(my-y) < height/2 where (x,y) = centerAt hitReset(mx,my,Widget {..}) = mx - xmin < 0.3 && abs(my - y) < height/2 where (x,y) = centerAt xmin = x - width/2 drawWidget(w) = case w.#widget of Button -> drawButton(w) Toggle -> drawToggle(w) Slider -> drawSlider(w) Random -> drawRandom(w) Counter -> drawCounter(w) Timer -> drawTimer(w) drawButton(Widget{..}) = drawLabel & drawSelection & drawHighlight where solid = scaled(solidCircle(0.5),w,h) outline = scaled(circle(0.5),w,h) (x,y) = centerAt msg = dilated(lettering(label),0.5) w = 0.9 * width h = 0.9 * height drawLabel = translated(msg,x,y) drawSelection | selected = translated(colored(solid,grey),x,y) | otherwise = translated(outline,x,y) drawHighlight | highlight = translated(colored(rectangle(width,height),light(grey)),x,y) | otherwise = blank drawCounter(Widget{..}) = drawLabel & drawSelection where solid = scaled(solidPolygon(points),w,h) outline = scaled(polygon(points),w,h) points = [(0.5,0.3),(0,0.5),(-0.5,0.3),(-0.5,-0.3),(0,-0.5),(0.5,-0.3)] (x,y) = centerAt msg(txt) = translated(dilated(lettering(txt),0.5),x,y) w = 0.9 * width h = 0.9 * height drawLabel | highlight = msg(printed(value_.#conversion)) | otherwise = msg(label) drawSelection | selected = translated(colored(solid,grey),x,y) | highlight = translated(colored(outline,black),x,y) | otherwise = translated(colored(outline,grey),x,y) drawToggle(Widget{..}) = drawSelection & drawLabel & drawHighlight where w = 0.5 h = 0.5 x' = x + 2/5*width drawSelection | selected = translated(colored(solidRectangle(w,h),grey),x',y) | otherwise = translated(rectangle(0.9*w,0.9*h),x',y) drawLabel = translated(msg,x - width/10,y) drawHighlight | highlight = colored(outline,light(grey)) & translated(rectangle(w,h),x',y) | otherwise = colored(outline,light(light(grey))) outline = translated(rectangle(width,height),x,y) (x,y) = centerAt msg = dilated(lettering(label),0.5) drawTimer(Widget{..}) = drawLabel & drawSelection & drawReset & drawHighlight where x' = x + 2/5*width xmin = x - width/2 drawLabel | highlight = msg(printed(value_.#conversion)) | otherwise = msg(label) drawSelection | selected = translated(box(0.5,0.5), x', y) | otherwise = translated(rectangle(0.45,0.45),x',y) drawReset = translated(box(0.3,height), xmin+0.15, y) drawHighlight | highlight = outline & translated(rectangle(0.5,0.5),x',y) | otherwise = colored(outline,light(grey)) outline = translated(rectangle(width,height),x,y) (x,y) = centerAt msg(txt) = translated(dilated(lettering(txt),0.5), x-width/10, y) box(w,h) = colored(solidRectangle(w,h),grey) drawSlider(Widget{..}) = info & foreground & background where info = translated(infoMsg,x,y-height/4) foreground = translated(solidCircle(height/4),x',y') & translated(colored(solidRectangle(width,height/4),grey),x,y') x' = x - width/2 + value_ * width y' = y + height/4 background | highlight = translated(colored(rectangle(width,height),light(grey)),x,y) | otherwise = blank (x,y) = centerAt infoMsg = dilated(lettering(label<>": "<>printed(value_.#conversion)),0.5) drawRandom(Widget{..}) = drawLabel & drawSelection & drawHighlight where solid = scaled(solidRectangle(1,1),width,height) outline = scaled(rectangle(1,1),width,height) (x,y) = centerAt msg(txt) = translated(dilated(lettering(txt),0.5),x,y) drawLabel | highlight = msg(printed(value_.#conversion)) | otherwise = msg(label) drawSelection | selected = translated(colored(solid,grey),x,y) | otherwise = blank drawHighlight | highlight = translated(outline,x,y) | otherwise = colored(translated(outline,x,y),grey) updateWidget(PointerPress(mx,my))(w@Widget{..}) | widget == Button, hit(mx,my,w) = w { selected = True, highlight = False , value_ = 0.5 } | widget == Button = w { selected = False, highlight = False , value_ = 0 } | widget == Counter, hit(mx,my,w) = w { selected = True, highlight = True , value_ = 1 + value_ } | widget == Toggle, hit(mx,my,w) = w { selected = not(selected) , value_ = 0.5 - value_ , highlight = True } | widget == Timer, hitReset(mx,my,w) = w { value_ = 0 } | widget == Timer, hit(mx,my,w) = w { selected = not(selected) , highlight = True } | widget == Slider, hit(mx,my,w) = w { selected = True, highlight = True , value_ = updateSliderValue(mx,w) } | widget == Random, hit(mx,my,w) = w { selected = True, highlight = True , value_ = randomPool#1 , randomPool = rest(randomPool,1) } | otherwise = w updateWidget(PointerMovement(mx,my))(w) = w.#updateHighlight(mx,my).#updateSlider(mx) updateWidget(PointerRelease(_))(w@Widget{..}) | widget == Toggle = w | widget == Timer = w | selected = w { selected = False, highlight = False , value_ = if widget == Button then 0 else value_ } | otherwise = w updateWidget(TimePassing(dt))(w@Widget{..}) | widget == Timer, selected = w { value_ = dt + value_ } | otherwise = w updateWidget(_)(widget) = widget updateHighlight(mx,my)(w) | hit(mx,my,w) = w { highlight = True } | otherwise = w { highlight = False } updateSlider(mx)(w@Widget{..}) | widget == Slider, selected = w { value_ = updateSliderValue(mx,w) } | otherwise = w updateSliderValue(mx,s@Widget{..}) = (mx' - x + width/2) / width where mx' = max(x-width/2,min(x+width/2,mx)) (x,_) = centerAt x .# f = f(x) xs .$ f = [f(x) | x <- xs]
alphalambda/codeworld
codeworld-base/src/Extras/Widget.hs
apache-2.0
19,161
3
16
4,551
5,943
3,374
2,569
272
6
{- Teak synthesiser for the Balsa language Copyright (C) 2007-2010 The University of Manchester 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 3 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, see <http://www.gnu.org/licenses/>. Andrew Bardsley <[email protected]> (and others, see AUTHORS) School of Computer Science, The University of Manchester Oxford Road, MANCHESTER, M13 9PL, UK -} module Type ( TypeClass (..), arrayInterval, arrayElemType, bitArrayType, bitType, intervalFromRange, intervalIndex, intervalIndices, intervalSize, builtinTypeWidth, classOfType, consTypeElemTypes, constExpr, constImpExpr, constImpOrIntExpr, constIndexExpr, exprValue, findRecElemByName, intCoercable, isStructType, isTokenValueExpr, makeConsValue, numTypeUnsignedWidth, rangeOfEnumType, rangeOfIndexType, rangeOfNumType, recoverValue, showTypeName, smallestNumTypeEnclosing, typeBuiltinOffsets, typeCoercable, typeEquiv, typeExpr, typeForInt, typeGetUnaliasedBody, typeIsSigned, typeLvalue, typeOfChan, typeOfDecl, typeOfExpr, typeOfLvalue, typeOfRange, typeOfRef, typeToStructType, unaliasType, widthOfType ) where import ParseTree import Context import Report import Bits import qualified Data.Ix as Ix import Data.List import Data.Maybe import Data.Bits bitType :: Type bitType = Bits 1 builtinTypeWidth :: Int builtinTypeWidth = 64 bitArrayType :: Int -> Type bitArrayType n = ArrayType (Interval (0, n' - 1) (typeForInt (n' - 1))) bitType where n' = toInteger n isTokenValueExpr :: [Context Decl] -> Expr -> Bool isTokenValueExpr cs (ValueExpr _ typ (IntValue 0)) = widthOfType cs typ == 0 isTokenValueExpr _ _ = False typeForInt :: Integer -> Type typeForInt int | int == -1 = SignedBits 1 | int < -1 = SignedBits $ 1 + intWidth (-int - 1) | otherwise = Bits $ intWidth int notNumeric :: [Type] -> a notNumeric [t] = error $ "`" ++ show t ++ "' is not a numeric type" notNumeric ts = error $ "one of" ++ types ++ " is not a numeric type" where types = concatMap showType ts showType t = " `" ++ show t ++ "'" rangeOfNumType :: Type -> (Integer, Integer) rangeOfNumType (Bits width) = (0, bit width - 1) rangeOfNumType (SignedBits width) = (- (bit (width - 1)), bit (width - 1) - 1) rangeOfNumType t = notNumeric [t] typeOfRange :: (Integer, Integer) -> Type typeOfRange (low, high) = smallestNumTypeEnclosing (typeForInt high) (typeForInt low) rangeOfEnumType :: TypeBody -> (Integer, Integer) rangeOfEnumType (EnumType _ es _) = range where range = (minimum values, maximum values) values = map enumElemValue $ contextBindingsList es enumElemValue binding = fromJust $ constExpr $ declExpr $ bindingValue binding rangeOfEnumType typ = error $ "rangeOfEnumType: not an enum type `" ++ show typ ++ "'" rangeOfIndexType :: [Context Decl] -> Type -> (Integer, Integer) rangeOfIndexType cs typ = body $ typeGetUnaliasedBody cs typ where body typ@(EnumType {}) = rangeOfEnumType typ body (AliasType _ typ@(Bits {})) = rangeOfNumType typ body (AliasType _ typ@(SignedBits {})) = rangeOfNumType typ body typ = error $ "rangeOfIndexType: not an index type `" ++ show typ ++ "'" smallestNumTypeEnclosing :: Type -> Type -> Type smallestNumTypeEnclosing (Bits uw1) (Bits uw2) = Bits $ max uw1 uw2 smallestNumTypeEnclosing (SignedBits w1) (Bits uw2) = SignedBits $ 1 + max (w1 - 1) uw2 smallestNumTypeEnclosing (Bits uw1) (SignedBits w2) = SignedBits $ 1 + max uw1 (w2 - 1) smallestNumTypeEnclosing (SignedBits w1) (SignedBits w2) = SignedBits $ max w1 w2 smallestNumTypeEnclosing t1 t2 = notNumeric [t1, t2] widthOfType :: [Context Decl] -> Type -> Int widthOfType _ (Bits width) = width widthOfType _ (SignedBits width) = width widthOfType cs (ArrayType interval elemType) = (widthOfType cs elemType) * (intervalSize interval) widthOfType cs (StructArrayType interval elemType) = (widthOfType cs elemType) * (intervalSize interval) widthOfType _ (BuiltinType _) = builtinTypeWidth widthOfType cs (StructRecordType _ _ overType) = widthOfType cs overType widthOfType cs (StructEnumType _ _ overType) = widthOfType cs overType widthOfType _ NoType = 0 widthOfType cs typ = widthOfTypeBody cs $ typeGetUnaliasedBody cs typ widthOfTypeBody :: [Context Decl] -> TypeBody -> Int widthOfTypeBody cs (AliasType _ typ) = widthOfType cs typ widthOfTypeBody cs (RecordType _ _ typ) = widthOfType cs typ widthOfTypeBody cs (EnumType _ _ typ) = widthOfType cs typ typeIsSigned :: [Context Decl] -> Type -> Bool typeIsSigned _ (SignedBits {}) = True typeIsSigned _ (Bits {}) = False typeIsSigned _ (ArrayType {}) = False typeIsSigned _ (StructArrayType {}) = False typeIsSigned _ (StructRecordType {}) = False typeIsSigned cs (StructEnumType _ _ overType) = typeIsSigned cs overType typeIsSigned _ NoType = False typeIsSigned cs typ = typeBodyIsSigned cs $ typeGetUnaliasedBody cs typ typeBodyIsSigned :: [Context Decl] -> TypeBody -> Bool typeBodyIsSigned cs (AliasType _ typ) = typeIsSigned cs typ typeBodyIsSigned cs (EnumType _ _ typ) = typeIsSigned cs typ typeBodyIsSigned _ _ = False data TypeClass = NumClass | EnumClass | ArrayClass | RecordClass | BuiltinClass | NoTypeClass deriving (Eq, Show, Read) classOfType :: [Context Decl] -> Type -> TypeClass classOfType _ NoType = NoTypeClass classOfType _ (Bits {}) = NumClass classOfType _ (SignedBits {}) = NumClass classOfType _ (ArrayType {}) = ArrayClass classOfType _ (BuiltinType {}) = BuiltinClass classOfType cs typ = classOfTypeBody cs $ typeGetUnaliasedBody cs typ classOfTypeBody :: [Context Decl] -> TypeBody -> TypeClass classOfTypeBody cs (AliasType _ typ) = classOfType cs typ classOfTypeBody _ (EnumType {}) = EnumClass classOfTypeBody _ (RecordType {}) = RecordClass intInWidth :: Integer -> Int -> Integer intInWidth i w = if i < 0 then bit w + i else i makeConsValue :: [Context Decl] -> Type -> [Expr] -> Value makeConsValue cs typ es | dcs == 0 = IntValue value | otherwise = ImpValue $ Imp value dcs where valueDcPairs = map getImpPairs es valueDcPairs' = map insertValue $ zip3 offsets valueDcPairs widths (value, dcs) = foldl' addImp (0, 0) valueDcPairs' addImp (v1, dc1) (v2, dc2) = (v1 + v2, dc1 + dc2) widths = map (widthOfType cs) $ fromJust $ consTypeElemTypes cs typ getImpPairs expr | isJust int = (fromJust int, 0) | otherwise = (value, dcs) where int = constExpr expr Just (Imp value dcs) = constImpExpr expr offsets = scanl (+) 0 widths insertValue (offset, (value, dcs), width) = (insert value, insert dcs) where insert value = (intInWidth value width) `shiftL` offset consTypeElemTypes :: [Context Decl] -> Type -> Maybe [Type] consTypeElemTypes cs typ = elemTypes $ typeGetUnaliasedBody cs typ where elemTypes (RecordType _ formals _) = Just $ map recordElemType formals where recordElemType (RecordElem _ _ elemType) = elemType elemTypes (AliasType _ (ArrayType interval elemType)) = Just $ map (const elemType) $ intervalIndices interval elemTypes _ = Nothing arrayElemType :: Type -> Type arrayElemType (ArrayType _ elemType) = elemType arrayElemType typ = error $ "arrayElemType: not an array type `" ++ show typ ++ "'" arrayInterval :: Type -> Interval arrayInterval (ArrayType interval _) = interval arrayInterval typ = error $ "arrayInterval: not an array type `" ++ show typ ++ "'" typeCoercable :: [Context Decl] -> Type -> Type -> Bool typeCoercable cs fromType toType = coercable (unaliasType cs fromType) (unaliasType cs toType) where coercable (SignedBits _) (Bits _) = False coercable (Bits wFrom) (SignedBits wTo) = wTo > wFrom coercable (Bits wFrom) (Bits wTo) = wTo >= wFrom coercable (SignedBits wFrom) (SignedBits wTo) = wTo >= wFrom -- coercable fromType toType = typeEquiv cs fromType toType coercable _ _ = False intCoercable :: [Context Decl] -> Integer -> Type -> Bool intCoercable cs int toType = coercable (unaliasType cs toType) where coercable (Bits wTo) = int >= 0 && int <= maxInt wTo coercable (SignedBits wTo) | int >= 0 = int <= maxInt (wTo - 1) | int < 0 = int >= (-1 - maxInt (wTo - 1)) coercable _ = False maxInt width = bit width - 1 typeEquiv :: [Context Decl] -> Type -> Type -> Bool typeEquiv cs typ1 typ2 = equiv (unaliasType cs typ1) (unaliasType cs typ2) where equiv (Bits w1) (Bits w2) = w1 == w2 equiv (SignedBits w1) (SignedBits w2) = w1 == w2 equiv (Type ref1) (Type ref2) = ref1 == ref2 -- for the same context path equiv (BuiltinType name1) (BuiltinType name2) = name1 == name2 equiv (ArrayType interval1 elemType1) (ArrayType interval2 elemType2) = interval1 == interval2 && elemType1 `equiv` elemType2 equiv _ _ = False unaliasType :: [Context Decl] -> Type -> Type unaliasType cs (ArrayType interval elemType) = ArrayType interval $ unaliasType cs elemType unaliasType cs (Type ref) = case decl of TypeDecl {} -> unaliasedType TypeParamDecl {} -> Type ref _ -> error $ "unaliasType: not a type decl: " ++ show decl ++ " " ++ show ref where decl = bindingValue $ findBindingByRef cs ref unaliasedType = case declTypeBody decl of AliasType _ typ -> unaliasType cs typ _ -> Type ref unaliasType _ typ = typ typeExpr :: Type -> Expr -> Expr typeExpr typ (BinExpr pos _ op left right) = BinExpr pos typ op left right typeExpr typ (AppendExpr pos _ left right) = AppendExpr pos typ left right typeExpr typ (UnExpr pos _ op expr) = UnExpr pos typ op expr typeExpr typ (ConsExpr pos _ consType es) = ConsExpr pos typ consType es typeExpr typ (BuiltinCallExpr pos callable ctx actuals _) = BuiltinCallExpr pos callable ctx actuals typ typeExpr typ (BitfieldExpr pos _ range expr) = BitfieldExpr pos typ range expr typeExpr typ (ExtendExpr pos _ width signedness expr) = ExtendExpr pos typ width signedness expr typeExpr typ (ValueExpr pos _ value) = ValueExpr pos typ value typeExpr typ (CaseExpr pos expr impss exprs) = CaseExpr pos expr impss (map (typeExpr typ) exprs) typeExpr typ (VarRead pos _ range ref) = VarRead pos typ range ref typeExpr typ (OpenChanRead pos _ range ref) = OpenChanRead pos typ range ref typeExpr _ expr = expr typeOfRef :: [Context Decl] -> Ref -> Type typeOfRef cs ref = typeOfDecl $ bindingValue $ findBindingByRef cs ref typeOfExpr :: [Context Decl] -> Expr -> Type typeOfExpr _ (BinExpr _ typ _ _ _) = typ typeOfExpr _ (AppendExpr _ typ _ _) = typ typeOfExpr _ (UnExpr _ typ _ _) = typ typeOfExpr _ (CastExpr _ typ _) = typ typeOfExpr _ (TypeCheckExpr _ _ typ _) = typ typeOfExpr cs (ConstCheckExpr _ expr) = typeOfExpr cs expr typeOfExpr cs (ArrayElemTypeCheckExpr _ _ expr) = typeOfExpr cs expr typeOfExpr _ (BuiltinCallExpr _ _ _ _ typ) = typ typeOfExpr _ (ConsExpr _ typ _ _) = typ typeOfExpr _ (BitfieldExpr _ typ _ _) = typ typeOfExpr _ (ExtendExpr _ typ _ _ _) = typ typeOfExpr _ (ValueExpr _ typ _) = typ typeOfExpr _ (VarRead _ typ _ _) = typ typeOfExpr _ (OpenChanRead _ typ _ _) = typ typeOfExpr cs (PartialArrayedRead _ ref) = typeOfRef cs ref typeOfExpr cs (MaybeTypeExpr _ ref) = typeOfRef cs ref typeOfExpr cs (MaybeOtherExpr _ ref) = typeOfRef cs ref typeOfExpr cs (Expr _ ref) = typeOfRef cs ref typeOfExpr cs (CaseExpr _ _ _ (expr:_)) = typeOfExpr cs expr typeOfExpr _ expr = error $ "can't type " ++ show expr typeOfChan :: [Context Decl] -> Chan -> Type typeOfChan cs (Chan _ ref) = typeOfRef cs ref typeOfChan cs (CheckChan _ _ chan) = typeOfChan cs chan typeOfChan _ _ = NoType typeOfDecl :: Decl -> Type typeOfDecl decl = declType decl typeLvalue :: Type -> Lvalue -> Lvalue typeLvalue typ (BitfieldLvalue pos _ range lvalue) = BitfieldLvalue pos typ range lvalue typeLvalue typ (VarWrite pos _ range ref) = VarWrite pos typ range ref typeLvalue typ (CaseLvalue pos expr impss lvalues) = CaseLvalue pos expr impss (map (typeLvalue typ) lvalues) typeLvalue _ lvalue = lvalue typeOfLvalue :: [Context Decl] -> Lvalue -> Type typeOfLvalue _ (BitfieldLvalue _ typ _ _) = typ typeOfLvalue _ (VarWrite _ typ _ _) = typ typeOfLvalue cs (CaseLvalue _ _ _ (lvalue:_)) = typeOfLvalue cs lvalue typeOfLvalue _ lvalue = error $ "can't type " ++ show lvalue exprValue :: Expr -> Maybe Value exprValue (ValueExpr _ _ value) = Just value exprValue _ = Nothing constExpr :: Expr -> Maybe Integer constExpr (ValueExpr _ _ (IntValue int)) = Just int constExpr _ = Nothing constImpExpr :: Expr -> Maybe Implicant constImpExpr (ValueExpr _ _ (ImpValue imp)) = Just imp constImpExpr _ = Nothing constImpOrIntExpr :: Expr -> Maybe Implicant constImpOrIntExpr (ValueExpr _ _ (IntValue int)) = Just $ Imp int 0 constImpOrIntExpr (ValueExpr _ _ (ImpValue imp)) = Just imp constImpOrIntExpr _ = Nothing constIndexExpr :: [Context Decl] -> Expr -> Maybe Integer constIndexExpr cs (ValueExpr _ typ (IntValue int)) = case classOfType cs typ of EnumClass -> Just int NumClass -> Just int _ -> Nothing constIndexExpr _ _ = Nothing typeGetUnaliasedBody :: [Context Decl] -> Type -> TypeBody typeGetUnaliasedBody cs typ = typeGetBody cs $ unaliasType cs typ typeGetBody :: [Context Decl] -> Type -> TypeBody typeGetBody cs (Type ref) = body where body = declBody $ bindingValue $ findBindingByRef cs ref declBody (TypeDecl _ typeBody) = typeBody declBody decl = error $ "Huh2? " ++ show decl typeGetBody _ typ = AliasType NoPos typ intervalIndices :: Interval -> [Integer] intervalIndices = Ix.range . intervalRange intervalSize :: Interval -> Int intervalSize = Ix.rangeSize . intervalRange intervalIndex :: Interval -> Integer -> Int intervalIndex = Ix.index . intervalRange -- intervalFromRange : make an Interval over the given range. This involves synthesising the interval range type. intervalFromRange :: (Integer, Integer) -> Interval intervalFromRange range = Interval range (typeOfRange range) showTypeName :: [Context Decl] -> Type -> String showTypeName cs (Type ref) = string where binding = findBindingByRef cs ref name = bindingName $ binding decl = bindingValue $ binding string = name ++ case decl of TypeDecl _ (AliasType _ typ) -> " (" ++ showTypeName cs typ ++ ")" _ -> "" showTypeName _ (Bits width) = show width ++ " bits" showTypeName _ (SignedBits width) = show width ++ " signed bits" showTypeName cs (ArrayType (Interval (low, high) ivType) elemType) = "array " ++ intervalStr ++ " of " ++ elemTypeStr where asStr val typ = "(" ++ show val ++ " as " ++ showTypeName cs typ ++ ")" intervalStr = if classOfType cs ivType == EnumClass then asStr low ivType ++ " .. " ++ asStr high ivType else show low ++ " .. " ++ show high elemTypeStr = showTypeName cs elemType showTypeName _ (StructRecordType name _ _) = name showTypeName _ (StructEnumType name _ _) = name showTypeName cs (StructArrayType interval elemType) = showTypeName cs (ArrayType interval elemType) showTypeName _ other = show other numTypeUnsignedWidth :: Type -> Int numTypeUnsignedWidth (Bits width) = width numTypeUnsignedWidth (SignedBits width) = width - 1 numTypeUnsignedWidth _ = error "numTypeUnsignedWidth: not a numeric type" findRecElemByName :: [Context Decl] -> TypeBody -> String -> Maybe (Int, Type) findRecElemByName cs (RecordType _ es _) name = findRecElem es 0 where findRecElem [] _ = Nothing findRecElem ((RecordElem _ name' typ):recElems) offset | name' == name = Just (offset, typ) | otherwise = findRecElem recElems (offset + (widthOfType cs typ)) findRecElemByName _ _ _ = error "findRecElemByName: not a RecordType" typeToStructType :: [Context Decl] -> Type -> Type typeToStructType cs typ = body $ unaliasType cs typ where self = typeToStructType cs body (Type ref) = typeBodyToStructType cs name $ declTypeBody decl where decl = bindingValue binding name = bindingName binding binding = findBindingByRef cs ref body (ArrayType interval subType) = StructArrayType interval $ self subType body otherType = otherType isStructType :: Type -> Bool isStructType (StructRecordType {}) = True isStructType (StructArrayType {}) = True isStructType (StructEnumType {}) = True isStructType _ = False typeBodyToStructType :: [Context Decl] -> String -> TypeBody -> Type typeBodyToStructType _ _ (AliasType _ typ) = typ typeBodyToStructType cs typeName (RecordType _ es overType) = StructRecordType typeName (map (recElemToST cs) es) (typeToStructType cs overType) typeBodyToStructType cs typeName (EnumType _ context overType) = StructEnumType typeName (mapMaybe bindingToEnumPair bindings) (typeToStructType cs overType) where bindings = contextBindingsList context bindingToEnumPair (Binding _ name _ _ (ExprDecl _ (ValueExpr _ _ (IntValue int)))) = Just (SimpleBinding name int) bindingToEnumPair _ = Nothing -- typeBuiltinOffsets : produces a list of bit offsets for the given type which identify -- each builtin typed element of a value of that type. `offset' is added to each offset in the returned list typeBuiltinOffsets :: [Context Decl] -> Int -> Type -> [Int] typeBuiltinOffsets cs offset typ = body $ unaliasType cs typ where body (Type ref) = typeBodyBuiltinOffsets cs offset $ declTypeBody decl where decl = bindingValue binding binding = findBindingByRef cs ref body (ArrayType interval subType) = array interval subType body (StructArrayType interval subType) = array interval subType body (StructRecordType _ es overType) = typeBodyBuiltinOffsets cs offset (RecordType undefined es overType) body (BuiltinType {}) = [offset] body _ = [] array interval subType = concatMap offsetElemRanges elemOffsets where offsetElemRanges elemOffset = map (+ elemOffset) elemRanges elemOffsets = map (* elemWidth) [0..intervalSize interval - 1] elemWidth = widthOfType cs subType elemRanges = typeBuiltinOffsets cs offset subType typeBodyBuiltinOffsets :: [Context Decl] -> Int -> TypeBody -> [Int] typeBodyBuiltinOffsets cs offset (AliasType _ typ) = typeBuiltinOffsets cs offset typ typeBodyBuiltinOffsets cs offset0 (RecordType _ es _) = concat elemRangess where (_, elemRangess) = mapAccumL elemRanges offset0 es elemRanges offset (RecordElem _ _ elemType) = (offset + width, typeBuiltinOffsets cs offset elemType) where width = widthOfType cs elemType typeBodyBuiltinOffsets _ _ (EnumType {}) = [] recElemToST :: [Context Decl] -> RecordElem -> RecordElem recElemToST cs (RecordElem pos name typ) = RecordElem pos name (typeToStructType cs typ) recoverValue :: [Context Decl] -> Type -> Integer -> Integer recoverValue cs typ val | typeIsSigned cs typ = recoverSign (widthOfType cs typ) val | otherwise = val
Mahdi89/eTeak
src/Type.hs
bsd-3-clause
21,407
0
15
5,813
6,632
3,349
3,283
378
6
module State.TreeSpec (treeSpec) where import State.Tree import Test.Hspec import Control.Monad.Identity testTree :: Integer -> Identity ([Integer], String) testTree 0 = return ([1, 2], "0") testTree 1 = return ([3], "1") testTree 2 = return ([], "2") testTree 3 = return ([], "3") testTree _ = error "No node" loopTree1 :: Integer -> Identity ([Integer], String) loopTree1 0 = return ([1], "0") loopTree1 1 = return ([0], "1") loopTree1 _ = error "No node" loopTree2 :: Integer -> Identity ([Integer], String) loopTree2 0 = return ([1], "0") loopTree2 1 = return ([0, 2, 3], "1") loopTree2 2 = return ([3], "2") loopTree2 3 = return ([2], "3") loopTree2 _ = error "No node" treeSpec :: Spec treeSpec = do describe "Tree" $ do dfFlattenTreeSpec dfFlattenTreeSpec :: Spec dfFlattenTreeSpec = do describe "dfFlattenTree" $ do it "flattens the tree using DFS" $ do let expected = return ["3", "1", "2", "0"] dfFlattenTree testTree [0] `shouldBe` expected it "does not include data in loops more than once" $ do let expected = return ["1", "0"] dfFlattenTree loopTree1 [0] `shouldBe` expected it "visits braches of loops" $ do let expected = return ["3", "2", "1", "0"] dfFlattenTree loopTree2 [0] `shouldBe` expected
BakerSmithA/Turing
test/State/TreeSpec.hs
bsd-3-clause
1,334
0
17
317
520
277
243
36
1
{-# LANGUAGE GeneralizedNewtypeDeriving, ScopedTypeVariables, BangPatterns #-} module Halfs.Inode ( InodeRef(..) , blockAddrToInodeRef , buildEmptyInodeEnc , decLinkCount , fileStat , incLinkCount , inodeKey , inodeRefToBlockAddr , isNilIR , nilIR , readStream , writeStream -- * for internal use only! , atomicModifyInode , atomicReadInode , bsReplicate , drefInode , expandExts -- for use by fsck , fileStat_lckd , freeInode , withLockedInode , writeStream_lckd -- * for testing: ought not be used by actual clients of this module! , Inode(..) , Ext(..) , ExtRef(..) , bsDrop , bsTake , computeMinimalInodeSize , computeNumAddrs , computeNumInodeAddrsM , computeNumExtAddrsM , computeSizes , decodeExt , decodeInode , minimalExtSize , minInodeBlocks , minExtBlocks , nilER , safeToInt , truncSentinel ) where import Control.Exception import Data.ByteString(ByteString) import qualified Data.ByteString as BS import Data.Char import Data.List (genericDrop, genericLength, genericTake) import Data.Serialize import qualified Data.Serialize.Get as G import Data.Word import Halfs.BlockMap (BlockMap) import qualified Halfs.BlockMap as BM import Halfs.Classes import Halfs.Errors import Halfs.HalfsState import Halfs.Protection import Halfs.Monad import Halfs.MonadUtils import Halfs.Types import Halfs.Utils import System.Device.BlockDevice -- import System.IO.Unsafe (unsafePerformIO) dbug :: String -> a -> a -- dbug = seq . unsafePerformIO . putStrLn dbug _ = id dbugM :: Monad m => String -> m () --dbugM s = dbug s $ return () dbugM _ = return () type HalfsM b r l m a = HalfsT HalfsError (Maybe (HalfsState b r l m)) m a -------------------------------------------------------------------------------- -- Inode/Ext constructors, geometry calculation, and helpful constructors type StreamIdx = (Word64, Word64, Word64) -- | Obtain a 64 bit "key" for an inode; useful for building maps etc. -- For now, this is the same as inodeRefToBlockAddr, but clients should -- be using this function rather than inodeRefToBlockAddr in case the -- underlying inode representation changes. inodeKey :: InodeRef -> Word64 inodeKey = inodeRefToBlockAddr -- | Convert a disk block address into an Inode reference. blockAddrToInodeRef :: Word64 -> InodeRef blockAddrToInodeRef = IR -- | Convert an inode reference into a block address inodeRefToBlockAddr :: InodeRef -> Word64 inodeRefToBlockAddr = unIR -- | The nil Inode reference. With the current Word64 representation and the -- block layout assumptions, block 0 is the superblock, and thus an invalid -- Inode reference. nilIR :: InodeRef nilIR = IR 0 isNilIR :: InodeRef -> Bool isNilIR = (==) nilIR -- | The nil Ext reference. With the current Word64 representation and -- the block layout assumptions, block 0 is the superblock, and thus an -- invalid Ext reference. nilER :: ExtRef nilER = ER 0 isNilER :: ExtRef -> Bool isNilER = (==) nilER -- | The sentinel byte written to partial blocks when doing truncating writes truncSentinel :: Word8 truncSentinel = 0xBA -- | The sentinel byte written to the padded region at the end of Inodes/Exts padSentinel :: Word8 padSentinel = 0xAD -- We semi-arbitrarily state that an Inode must be capable of maintaining a -- minimum of 35 block addresses in its embedded Ext while the Ext must be -- capable of maintaining 57 block addresses. These values, together with -- specific padding values for inodes and exts (4 and 0, respectively), give us -- a minimum inode AND ext size of 512 bytes each (in the IO monad variant, -- which uses the our Serialize instance for the UTCTime when writing the time -- fields). -- -- These can be adjusted as needed according to inode metadata sizes, but it's -- very important that (computeMinimalInodeSize =<< getTime) and minimalExtSize yield -- the same value! -- | The size, in bytes, of the padding region at the end of Inodes iPadSize :: Int iPadSize = 4 -- | The size, in bytes, of the padding region at the end of Exts cPadSize :: Int cPadSize = 0 minInodeBlocks :: Word64 minInodeBlocks = 35 minExtBlocks :: Word64 minExtBlocks = 57 -- | The structure of an Inode. Pretty standard, except that we use the Ext -- structure (the first of which is embedded in the inode) to hold block -- references and use its ext field to allow multiple runs of block -- addresses. data Inode t = Inode { inoParent :: InodeRef -- ^ block addr of parent directory -- inode: This is nilIR for the -- root directory inode , inoLastExt :: (ExtRef, Word64) -- ^ The last-accessed ER and its ext -- idx. For the "faster end-of-stream -- access" hack. -- begin fstat metadata , inoAddress :: InodeRef -- ^ block addr of this inode , inoFileSize :: Word64 -- ^ in bytes , inoAllocBlocks :: Word64 -- ^ number of blocks allocated to this inode -- (includes its own allocated block, blocks -- allocated for Exts, and and all blocks in -- the ext chain itself) , inoFileType :: FileType , inoMode :: FileMode , inoNumLinks :: Word64 -- ^ number of hardlinks to this inode , inoCreateTime :: t -- ^ time of creation , inoModifyTime :: t -- ^ time of last data modification , inoAccessTime :: t -- ^ time of last data access , inoChangeTime :: t -- ^ time of last change to inode data , inoUser :: UserID -- ^ userid of inode's owner , inoGroup :: GroupID -- ^ groupid of inode's owner -- end fstat metadata , inoExt :: Ext -- The "embedded" inode extension ("ext") } deriving (Show, Eq) -- An "Inode extension" datatype data Ext = Ext { address :: ExtRef -- ^ Address of this Ext (nilER for an -- inode's embedded Ext) , nextExt :: ExtRef -- ^ Next Ext in the chain; nilER terminates , blockCount :: Word64 , blockAddrs :: [Word64] -- ^ references to blocks governed by this Ext -- Fields below here are not persisted, and are populated via decodeExt , numAddrs :: Word64 -- ^ Maximum number of blocks addressable by *this* -- Ext. NB: Does not include blocks further down -- the chain. } deriving (Show, Eq) -- | Size of a minimal inode structure when serialized, in bytes. This will -- vary based on the space required for type t when serialized. Note that -- minimal inode structure always contains minInodeBlocks InodeRefs in -- its blocks region. -- -- You can check this value interactively in ghci by doing, e.g. -- computeMinimalInodeSize =<< (getTime :: IO UTCTime) computeMinimalInodeSize :: (Monad m, Ord t, Serialize t, Show t) => t -> m Word64 computeMinimalInodeSize t = do return $ fromIntegral $ BS.length $ encode $ let e = emptyInode minInodeBlocks t RegularFile (FileMode [] [] []) nilIR nilIR rootUser rootGroup c = inoExt e in e{ inoExt = c{ blockAddrs = replicate (safeToInt minInodeBlocks) 0 } } -- | The size of a minimal Ext structure when serialized, in bytes. minimalExtSize :: Monad m => m (Word64) minimalExtSize = return $ fromIntegral $ BS.length $ encode $ (emptyExt minExtBlocks nilER){ blockAddrs = replicate (safeToInt minExtBlocks) 0 } -- | Computes the number of block addresses storable by an inode/ext computeNumAddrs :: Monad m => Word64 -- ^ block size, in bytes -> Word64 -- ^ minimum number of blocks for inode/ext -> Word64 -- ^ minimum inode/ext total size, in bytes -> m Word64 computeNumAddrs blkSz minBlocks minSize = do unless (minSize <= blkSz) $ fail "computeNumAddrs: Block size too small to accomodate minimal inode" let -- # bytes required for the blocks region of the minimal inode padding = minBlocks * refSize -- # bytes of the inode excluding the blocks region notBlocksSize = minSize - padding -- # bytes available for storing the blocks region blkSz' = blkSz - notBlocksSize unless (0 == blkSz' `mod` refSize) $ fail "computeNumAddrs: Inexplicably bad block size" return $ blkSz' `div` refSize computeNumInodeAddrsM :: (Serialize t, Timed t m, Show t) => Word64 -> m Word64 computeNumInodeAddrsM blkSz = computeNumAddrs blkSz minInodeBlocks =<< computeMinimalInodeSize =<< getTime computeNumExtAddrsM :: (Serialize t, Timed t m) => Word64 -> m Word64 computeNumExtAddrsM blkSz = do minSize <- minimalExtSize computeNumAddrs blkSz minExtBlocks minSize computeSizes :: (Serialize t, Timed t m, Show t) => Word64 -> m ( Word64 -- #inode bytes , Word64 -- #ext bytes , Word64 -- #inode addrs , Word64 -- #ext addrs ) computeSizes blkSz = do startExtAddrs <- computeNumInodeAddrsM blkSz extAddrs <- computeNumExtAddrsM blkSz return (startExtAddrs * blkSz, extAddrs * blkSz, startExtAddrs, extAddrs) -- Builds and encodes an empty inode buildEmptyInodeEnc :: (Serialize t, Timed t m, Show t) => BlockDevice m -- ^ The block device -> FileType -- ^ This inode's filetype -> FileMode -- ^ This inode's access mode -> InodeRef -- ^ This inode's block address -> InodeRef -- ^ Parent's block address -> UserID -> GroupID -> m ByteString buildEmptyInodeEnc bd ftype fmode me mommy usr grp = liftM encode $ buildEmptyInode bd ftype fmode me mommy usr grp buildEmptyInode :: (Serialize t, Timed t m, Show t) => BlockDevice m -> FileType -- ^ This inode's filetype -> FileMode -- ^ This inode's access mode -> InodeRef -- ^ This inode's block address -> InodeRef -- ^ Parent block's address -> UserID -- ^ This inode's owner's userid -> GroupID -- ^ This inode's owner's groupid -> m (Inode t) buildEmptyInode bd ftype fmode me mommy usr grp = do now <- getTime minSize <- computeMinimalInodeSize =<< return now minimalExtSize >>= (`assert` return ()) . (==) minSize nAddrs <- computeNumAddrs (bdBlockSize bd) minInodeBlocks minSize return $ emptyInode nAddrs now ftype fmode me mommy usr grp emptyInode :: (Ord t, Serialize t) => Word64 -- ^ number of block addresses -> t -- ^ creation timestamp -> FileType -- ^ inode's filetype -> FileMode -- ^ inode's access mode -> InodeRef -- ^ block addr for this inode -> InodeRef -- ^ parent block address -> UserID -> GroupID -> Inode t emptyInode nAddrs now ftype fmode me mommy usr grp = Inode { inoParent = mommy , inoLastExt = (nilER, 0) , inoAddress = me , inoFileSize = 0 , inoAllocBlocks = 1 , inoFileType = ftype , inoMode = fmode , inoNumLinks = 1 , inoCreateTime = now , inoModifyTime = now , inoAccessTime = now , inoChangeTime = now , inoUser = usr , inoGroup = grp , inoExt = emptyExt nAddrs nilER } buildEmptyExt :: (Serialize t, Timed t m) => BlockDevice m -- ^ The block device -> ExtRef -- ^ This ext's block address -> m Ext buildEmptyExt bd me = do minSize <- minimalExtSize nAddrs <- computeNumAddrs (bdBlockSize bd) minExtBlocks minSize return $ emptyExt nAddrs me emptyExt :: Word64 -- ^ number of block addresses -> ExtRef -- ^ block addr for this ext -> Ext emptyExt nAddrs me = Ext { address = me , nextExt = nilER , blockCount = 0 , blockAddrs = [] , numAddrs = nAddrs } -------------------------------------------------------------------------------- -- Inode stream functions -- | Provides a stream over the bytes governed by a given Inode and its -- extensions (exts). This function performs a write to update inode metadata -- (e.g., access time). readStream :: HalfsCapable b t r l m => InodeRef -- ^ Starting inode reference -> Word64 -- ^ Starting stream (byte) offset -> Maybe Word64 -- ^ Stream length (Nothing => read -- until end of stream, including -- entire last block) -> HalfsM b r l m ByteString -- ^ Stream contents readStream startIR start mlen = withLockedInode startIR $ do -- ====================== Begin inode critical section ====================== dev <- hasks hsBlockDev startInode <- drefInode startIR let bs = bdBlockSize dev readB c b = lift $ readBlock dev c b fileSz = inoFileSize startInode gsi = getStreamIdx (bdBlockSize dev) fileSz if 0 == blockCount (inoExt startInode) then return BS.empty else dbug ("==== readStream begin ===") $ do (sExtI, sBlkOff, sByteOff) <- gsi start sExt <- findExt startInode sExtI (eExtI, _, _) <- gsi $ case mlen of Nothing -> fileSz - 1 Just len -> start + len - 1 dbugM ("start = " ++ show start) dbugM ("(sExtI, sBlkOff, sByteOff) = " ++ show (sExtI, sBlkOff, sByteOff)) dbugM ("eExtI = " ++ show eExtI) rslt <- case mlen of Just len | len == 0 -> return BS.empty _ -> do assert (maybe True (> 0) mlen) $ return () -- 'hdr' is the (possibly partial) first block hdr <- bsDrop sByteOff `fmap` readB sExt sBlkOff -- 'rest' is the list of block-sized bytestrings containing the -- requested content from blocks in subsequent conts, accounting for -- the (Maybe) maximum length requested. rest <- do let hdrLen = fromIntegral (BS.length hdr) totalToRead = maybe (fileSz - start) id mlen -- howManyBlks ext bsf blkOff = let bc = blockCount ext - blkOff in maybe bc (\len -> min bc ((len - bsf) `divCeil` bs)) mlen -- readExt (_, [], _) = error "The impossible happened" readExt ((cExt, cExtI), blkOff:boffs, bytesSoFar) | cExtI > eExtI = assert (bytesSoFar >= totalToRead) $ return Nothing | bytesSoFar >= totalToRead = return Nothing | otherwise = do let remBlks = howManyBlks cExt bytesSoFar blkOff range = if remBlks > 0 then [blkOff .. blkOff + remBlks - 1] else [] theData <- BS.concat `fmap` mapM (readB cExt) range assert (fromIntegral (BS.length theData) == remBlks * bs) $ return () let rslt c = return $ Just $ ( theData -- accumulated by unfoldr , ( (c, cExtI+1) , boffs , bytesSoFar + remBlks * bs ) ) if isNilER (nextExt cExt) then rslt (error "Ext DNE and expected termination!") else rslt =<< drefExt (nextExt cExt) -- ==> Bulk reading starts here <== if (sBlkOff + 1 < blockCount sExt || sExtI < eExtI) then unfoldrM readExt ((sExt, sExtI), (sBlkOff+1):repeat 0, hdrLen) else return [] return $ bsTake (maybe (fileSz - start) id mlen) $ hdr `BS.append` BS.concat rest now <- getTime lift $ writeInode dev $ startInode { inoAccessTime = now, inoChangeTime = now } dbug ("==== readStream end ===") $ return () return rslt -- ======================= End inode critical section ======================= -- | Writes to the inode stream at the given starting inode and starting byte -- offset, overwriting data and allocating new space on disk as needed. If the -- write is a truncating write, all resources after the end of the written data -- are freed. Whenever the data to be written exceeds the the end of the -- stream, the trunc flag is ignored. writeStream :: HalfsCapable b t r l m => InodeRef -- ^ Starting inode ref -> Word64 -- ^ Starting stream (byte) offset -> Bool -- ^ Truncating write? -> ByteString -- ^ Data to write -> HalfsM b r l m () writeStream _ _ False bytes | 0 == BS.length bytes = return () writeStream startIR start trunc bytes = do withLockedInode startIR $ writeStream_lckd startIR start trunc bytes writeStream_lckd :: HalfsCapable b t r l m => InodeRef -- ^ Starting inode ref -> Word64 -- ^ Starting stream (byte) offset -> Bool -- ^ Truncating write? -> ByteString -- ^ Data to write -> HalfsM b r l m () writeStream_lckd _ _ False bytes | 0 == BS.length bytes = return () writeStream_lckd startIR start trunc bytes = do -- ====================== Begin inode critical section ====================== -- NB: This implementation currently 'flattens' Contig/Discontig block groups -- from the BlockMap allocator (see allocFill and truncUnalloc below), which -- will force us to treat them as Discontig when we unallocate, which is more -- expensive. We may want to have the Exts hold onto these block groups -- directly and split/merge them as needed to reduce the number of -- unallocation actions required, but we leave this as a TODO for now. startInode@Inode{ inoLastExt = lcInfo } <- drefInode startIR dev <- hasks hsBlockDev let bs = bdBlockSize dev len = fromIntegral $ BS.length bytes fileSz = inoFileSize startInode newFileSz = if trunc then start + len else max (start + len) fileSz fszRndBlk = (fileSz `divCeil` bs) * bs availBlks c = numAddrs c - blockCount c bytesToAlloc = if newFileSz > fszRndBlk then newFileSz - fszRndBlk else 0 blksToAlloc = bytesToAlloc `divCeil` bs (_, _, _, apc) <- hasks hsSizes sIdx@(sExtI, sBlkOff, sByteOff) <- getStreamIdx bs fileSz start sExt <- findExt startInode sExtI lastExt <- getLastExt Nothing sExt -- TODO: Track a ptr to this? Traversing -- the allocated region is yucky. let extsToAlloc = (blksToAlloc - availBlks lastExt) `divCeil` apc ------------------------------------------------------------------------------ -- Debugging miscellany dbugM ("\nwriteStream: " ++ show (sExtI, sBlkOff, sByteOff) ++ " (start=" ++ show start ++ ")" ++ " len = " ++ show len ++ ", trunc = " ++ show trunc ++ ", fileSz/newFileSz = " ++ show fileSz ++ "/" ++ show newFileSz ++ ", toAlloc(exts/blks/bytes) = " ++ show extsToAlloc ++ "/" ++ show blksToAlloc ++ "/" ++ show bytesToAlloc) -- dbug ("inoLastExt startInode = " ++ show (lcInfo) ) $ return () -- dbug ("inoExt startInode = " ++ show (inoExt startInode)) $ return () -- dbug ("Exts on entry, from inode ext:") $ return () -- dumpExts (inoExt startInode) ------------------------------------------------------------------------------ -- Allocation: -- Allocate if needed and obtain (1) the post-alloc start ext and (2) -- possibly a dirty ext to write back into the inode (ie, when its -- nextExt field is modified as a result of allocation -- all other -- modified exts are written by allocFill, but the inode write is the last -- thing we do, so we defer the update). (sExt', minodeExt) <- do if blksToAlloc == 0 then return (sExt, Nothing) else do lastExt' <- allocFill availBlks blksToAlloc extsToAlloc lastExt let st = if address lastExt' == address sExt then lastExt' else sExt -- Our starting location remains the same, but in case of an -- update of the start ext, we can use lastExt' instead of -- re-reading. lci = snd lcInfo st' <- if lci < sExtI then getLastExt (Just $ sExtI - lci + 1) st -- NB: We need to start ahead of st, but couldn't adjust -- until after we allocated. This is to catch a corner case -- where the "start" ext coming into writeStream_lckd -- refers to a ext that hasn't been allocated yet. else return st return (st', if isEmbedded st then Just st else Nothing) -- dbug ("sExt' = " ++ show sExt') $ return () -- dbug ("minodeExt = " ++ show minodeExt) $ return () -- dbug ("Exts immediately after alloc, from sExt'") $ return () -- dumpExts (sExt') assert (sBlkOff < blockCount sExt') $ return () ------------------------------------------------------------------------------ -- Truncation -- Truncate if needed and obtain (1) the new start ext at which to start -- writing data and (2) possibly a dirty ext to write back into the inode (sExt'', numBlksFreed, minodeExt') <- if trunc && bytesToAlloc == 0 then do (ext, nbf) <- truncUnalloc start len (sExt', sExtI) return ( ext , nbf , if isEmbedded ext then case minodeExt of Nothing -> Just ext Just _ -> -- This "can't happen" ... error $ "Internal: dirty inode ext from " ++ "both allocFill & truncUnalloc!?" else Nothing ) else return (sExt', 0, minodeExt) assert (blksToAlloc + extsToAlloc == 0 || numBlksFreed == 0) $ return () ------------------------------------------------------------------------------ -- Data streaming (eExtI, _, _) <- decomp (bdBlockSize dev) (bytesToEnd start len) eExt <- getLastExt (Just $ (eExtI - sExtI) + 1) sExt'' when (len > 0) $ writeInodeData (sIdx, sExt'') eExtI trunc bytes -------------------------------------------------------------------------------- -- Inode metadata adjustments & persist now <- getTime lift $ writeInode dev $ startInode { inoLastExt = if eExtI == sExtI then (address sExt'', sExtI) else (address eExt, eExtI) , inoFileSize = newFileSz , inoAllocBlocks = inoAllocBlocks startInode + blksToAlloc + extsToAlloc - numBlksFreed , inoAccessTime = now , inoModifyTime = now , inoChangeTime = now , inoExt = maybe (inoExt startInode) id minodeExt' } -- ======================= End inode critical section ======================= -------------------------------------------------------------------------------- -- Inode operations incLinkCount :: HalfsCapable b t r l m => InodeRef -- ^ Source inode ref -> HalfsM b r l m () incLinkCount inr = atomicModifyInode inr $ \nd -> return $ nd{ inoNumLinks = inoNumLinks nd + 1 } decLinkCount :: HalfsCapable b t r l m => InodeRef -- ^ Source inode ref -> HalfsM b r l m () decLinkCount inr = atomicModifyInode inr $ \nd -> return $ nd{ inoNumLinks = inoNumLinks nd - 1 } -- | Atomically modifies an inode; always updates inoChangeTime, but -- callers are responsible for other metadata modifications. atomicModifyInode :: HalfsCapable b t r l m => InodeRef -> (Inode t -> HalfsM b r l m (Inode t)) -> HalfsM b r l m () atomicModifyInode inr f = withLockedInode inr $ do dev <- hasks hsBlockDev inode <- drefInode inr now <- getTime inode' <- setChangeTime now `fmap` f inode lift $ writeInode dev inode' atomicReadInode :: HalfsCapable b t r l m => InodeRef -> (Inode t -> a) -> HalfsM b r l m a atomicReadInode inr f = withLockedInode inr $ f `fmap` drefInode inr fileStat :: HalfsCapable b t r l m => InodeRef -> HalfsM b r l m (FileStat t) fileStat inr = withLockedInode inr $ fileStat_lckd inr fileStat_lckd :: HalfsCapable b t r l m => InodeRef -> HalfsM b r l m (FileStat t) fileStat_lckd inr = do inode <- drefInode inr return $ FileStat { fsInode = inr , fsType = inoFileType inode , fsMode = inoMode inode , fsNumLinks = inoNumLinks inode , fsUID = inoUser inode , fsGID = inoGroup inode , fsSize = inoFileSize inode , fsNumBlocks = inoAllocBlocks inode , fsAccessTime = inoAccessTime inode , fsModifyTime = inoModifyTime inode , fsChangeTime = inoChangeTime inode } -------------------------------------------------------------------------------- -- Inode/Ext stream helper & utility functions isEmbedded :: Ext -> Bool isEmbedded = isNilER . address freeInode :: HalfsCapable b t r l m => InodeRef -- ^ reference to the inode to remove -> HalfsM b r l m () freeInode inr@(IR addr) = withLockedInode inr $ do bm <- hasks hsBlockMap start <- inoExt `fmap` drefInode inr freeBlocks bm (blockAddrs start) _numFreed :: Word64 <- freeExts bm start BM.unalloc1 bm addr freeBlocks :: HalfsCapable b t r l m => BlockMap b r l -> [Word64] -> HalfsM b r l m () freeBlocks _ [] = return () freeBlocks bm addrs = lift $ BM.unallocBlocks bm $ BM.Discontig $ map (`BM.Extent` 1) addrs -- NB: Freeing all of the blocks this way (as unit extents) is ugly and -- inefficient, but we need to be tracking BlockGroups (or reconstitute them -- here by digging for contiguous address subsequences in addrs) before we can -- do better. -- | Frees all exts after the given ext, returning the number of blocks freed. freeExts :: (HalfsCapable b t r l m, Num a) => BlockMap b r l -> Ext -> HalfsM b r l m a freeExts bm Ext{ nextExt = cr } | isNilER cr = return $ fromInteger 0 | otherwise = drefExt cr >>= extFoldM freeExt (fromInteger 0) where freeExt !acc c = freeBlocks bm toFree >> return (acc + genericLength toFree) where toFree = unER (address c) : blockAddrs c withLockedInode :: HalfsCapable b t r l m => InodeRef -- ^ reference to inode to lock -> HalfsM b r l m a -- ^ action to take while holding lock -> HalfsM b r l m a withLockedInode inr act = -- Inode locking: We currently use a single reader/writer lock tracked by the -- InodeRef -> (lock, ref count) map in HalfsState. Reference counting is used -- to determine when it is safe to remove a lock from the map. -- -- We use the map to track lock info so that we don't hold locks for lengthy -- intervals when we have access requests for disparate inode refs. hbracket before after (const act {- inode lock doesn't escape! -}) where before = do -- When the InodeRef is already in the map, atomically increment its -- reference count and acquire; otherwise, create a new lock and acquire. inodeLock <- do lm <- hasks hsInodeLockMap withLockedRscRef lm $ \mapRef -> do -- begin inode lock map critical section lockInfo <- lookupRM inr mapRef case lockInfo of Nothing -> do l <- newLock insertRM inr (l, 1) mapRef return l Just (l, r) -> do insertRM inr (l, r + 1) mapRef return l -- end inode lock map critical section lock inodeLock return inodeLock -- after inodeLock = do -- Atomically decrement the reference count for the InodeRef and then -- release the lock lm <- hasks hsInodeLockMap withLockedRscRef lm $ \mapRef -> do -- begin inode lock map critical section lockInfo <- lookupRM inr mapRef case lockInfo of Nothing -> fail "withLockedInode internal: No InodeRef in lock map" Just (l, r) | r == 1 -> deleteRM inr mapRef | otherwise -> insertRM inr (l, r - 1) mapRef -- end inode lock map critical section release inodeLock -- | A wrapper around Data.Serialize.decode that populates transient fields. We -- do this to avoid occupying valuable on-disk inode space where possible. Bare -- applications of 'decode' should not occur when deserializing inodes! decodeInode :: HalfsCapable b t r l m => ByteString -> HalfsM b r l m (Inode t) decodeInode bs = do (_, _, numAddrs', _) <- hasks hsSizes case decode bs of Left s -> throwError $ HE_DecodeFail_Inode s Right n -> do return n{ inoExt = (inoExt n){ numAddrs = numAddrs' } } -- | A wrapper around Data.Serialize.decode that populates transient fields. We -- do this to avoid occupying valuable on-disk Ext space where possible. Bare -- applications of 'decode' should not occur when deserializing Exts! decodeExt :: HalfsCapable b t r l m => Word64 -> ByteString -> HalfsM b r l m Ext decodeExt blkSz bs = do numAddrs' <- computeNumExtAddrsM blkSz case decode bs of Left s -> throwError $ HE_DecodeFail_Ext s Right c -> return c{ numAddrs = numAddrs' } -- | Obtain the ext with the given ext index in the ext chain. -- Currently traverses Exts from either the inode's embedded ext or -- from the (saved) ext from the last operation, whichever is -- closest. findExt :: HalfsCapable b t r l m => Inode t -> Word64 -> HalfsM b r l m Ext findExt Inode{ inoLastExt = (ler, lci), inoExt = defExt } sci | isNilER ler || lci > sci = getLastExt (Just $ sci + 1) defExt | otherwise = getLastExt (Just $ sci - lci + 1) =<< drefExt ler -- | Allocate the given number of Exts and blocks, and fill blocks into the -- ext chain starting at the given ext. Persists dirty exts and yields a new -- start ext to use. allocFill :: HalfsCapable b t r l m => (Ext -> Word64) -- ^ Available blocks function -> Word64 -- ^ Number of blocks to allocate -> Word64 -- ^ Number of exts to allocate -> Ext -- ^ Last allocated ext -> HalfsM b r l m Ext -- ^ Updated last ext allocFill _ 0 _ eExt = return eExt allocFill avail blksToAlloc extsToAlloc eExt = do dev <- hasks hsBlockDev bm <- hasks hsBlockMap newExts <- allocExts dev bm blks <- allocBlocks bm -- Fill nextExt fields to form the region that we'll fill with the newly -- allocated blocks (i.e., starting at the end of the already-allocated region -- from the start ext, but including the newly allocated exts as well). let (_, region) = foldr (\c (er, !acc) -> ( address c , c{ nextExt = er } : acc ) ) (nilER, []) (eExt : newExts) -- "Spill" the allocated blocks into the empty region let (blks', k) = foldl fillBlks (blks, id) region dirtyExts@(eExt':_) = k [] fillBlks (remBlks, k') c = let cnt = min (safeToInt $ avail c) (length remBlks) c' = c { blockCount = blockCount c + fromIntegral cnt , blockAddrs = blockAddrs c ++ take cnt remBlks } in (drop cnt remBlks, k' . (c':)) assert (null blks') $ return () forM_ (dirtyExts) $ \c -> unless (isEmbedded c) $ lift $ writeExt dev c return eExt' where allocBlocks bm = do -- currently "flattens" BlockGroup; see comment in writeStream mbg <- lift $ BM.allocBlocks bm blksToAlloc case mbg of Nothing -> throwError HE_AllocFailed Just bg -> return $ BM.blkRangeBG bg -- allocExts dev bm = if 0 == extsToAlloc then return [] else do -- TODO: Unalloc partial allocs on HE_AllocFailed? mexts <- fmap sequence $ replicateM (safeToInt extsToAlloc) $ do mcr <- fmap ER `fmap` BM.alloc1 bm case mcr of Nothing -> return Nothing Just cr -> Just `fmap` lift (buildEmptyExt dev cr) maybe (throwError HE_AllocFailed) (return) mexts -- | Truncates the stream at the given a stream index and length offset, and -- unallocates all resources in the corresponding free region, yielding a new -- Ext for the truncated chain. truncUnalloc :: HalfsCapable b t r l m => Word64 -- ^ Starting stream byte index -> Word64 -- ^ Length from start at which to truncate -> (Ext, Word64) -- ^ Start ext of chain to truncate, start ext idx -> HalfsM b r l m (Ext, Word64) -- ^ new start ext, number of blocks freed truncUnalloc start len (stExt, sExtI) = do dev <- hasks hsBlockDev bm <- hasks hsBlockMap (eExtI, eBlkOff, _) <- decomp (bdBlockSize dev) (bytesToEnd start len) assert (eExtI >= sExtI) $ return () -- Get the (new) end of the ext chain. Retain all exts in [sExtI, eExtI]. eExt <- getLastExt (Just $ eExtI - sExtI + 1) stExt let keepBlkCnt = if start + len == 0 then 0 else eBlkOff + 1 endExtRem = genericDrop keepBlkCnt (blockAddrs eExt) freeBlocks bm endExtRem numFreed <- (+ (genericLength endExtRem)) `fmap` freeExts bm eExt -- Currently, only eExt is considered dirty; we do *not* do any writes to any -- of the Exts that are detached from the chain & freed (we just toss them -- out); this may have implications for fsck. let dirtyExts@(firstDirty:_) = [ -- eExt, adjusted to discard the freed blocks and clear the -- nextExt field. eExt { blockCount = keepBlkCnt , blockAddrs = genericTake keepBlkCnt (blockAddrs eExt) , nextExt = nilER } ] stExt' = if sExtI == eExtI then firstDirty else stExt forM_ (dirtyExts) $ \c -> unless (isEmbedded c) $ lift $ writeExt dev c return (stExt', numFreed) -- | Write the given bytes to the already-allocated/truncated inode data stream -- starting at the given start indices (ext/blk/byte offsets) and ending when -- we have traversed up (and including) to the end ext index. Assumes the -- inode lock is held. writeInodeData :: HalfsCapable b t r l m => (StreamIdx, Ext) -> Word64 -> Bool -> ByteString -> HalfsM b r l m () writeInodeData ((sExtI, sBlkOff, sByteOff), sExt) eExtI trunc bytes = do dev <- hasks hsBlockDev sBlk <- lift $ readBlock dev sExt sBlkOff let bs = bdBlockSize dev toWrite = -- The first block-sized chunk to write is the region in the start block -- prior to the start byte offset (header), followed by the first bytes -- of the data. The trailer is nonempty and must be included when -- BS.length bytes < bs. We adjust the input bytestring by this -- first-block padding below. let (sData, bytes') = bsSplitAt (bs - sByteOff) bytes header = bsTake sByteOff sBlk trailLen = sByteOff + fromIntegral (BS.length sData) trailer = if trunc then bsReplicate (bs - trailLen) truncSentinel else bsDrop trailLen sBlk fstBlk = header `BS.append` sData `BS.append` trailer in assert (fromIntegral (BS.length fstBlk) == bs) $ fstBlk `BS.append` bytes' -- The unfoldr seed is: current ext/idx, a block offset "supply", and the -- data that remains to be written. unfoldrM_ (fillExt dev) ((sExt, sExtI), sBlkOff : repeat 0, toWrite) where fillExt _ (_, [], _) = error "The impossible happened" fillExt dev ((cExt, cExtI), blkOff:boffs, toWrite) | cExtI > eExtI || BS.null toWrite = return Nothing | otherwise = do let blkAddrs = genericDrop blkOff (blockAddrs cExt) split crs = let (cs, rems) = unzip crs in (cs, last rems) gbc = lift . getBlockContents dev trunc (chunks, remBytes) <- split `fmap` unfoldrM gbc (toWrite, blkAddrs) assert (let lc = length chunks; lb = length blkAddrs in lc == lb || (BS.length remBytes == 0 && lc < lb)) $ return () mapM_ (lift . uncurry (bdWriteBlock dev)) (blkAddrs `zip` chunks) if isNilER (nextExt cExt) then assert (BS.null remBytes) $ return Nothing else do nextExt' <- drefExt (nextExt cExt) return $ Just $ ((), ((nextExt', cExtI+1), boffs, remBytes)) -- | Splits the input bytestring into block-sized chunks; may read from the -- block device in order to preserve contents of blocks if needed. getBlockContents :: (Monad m, Functor m) => BlockDevice m -- ^ The block device -> Bool -- ^ Truncating write? (Impacts partial block retention) -> (ByteString, [Word64]) -- ^ Input bytestring, block addresses for each chunk (for retention) -> m (Maybe ((ByteString, ByteString), (ByteString, [Word64]))) -- ^ When unfolding, the collected result type here of (ByteString, -- ByteString) is (chunk, remaining data), in case the entire input bytestring -- is not consumed. The seed value is (bytestring for all data, block -- addresses for each chunk). getBlockContents _ _ (s, _) | BS.null s = return Nothing getBlockContents _ _ (_, []) = return Nothing getBlockContents dev trunc (s, blkAddr:blkAddrs) = do let (newBlkData, remBytes) = bsSplitAt bs s bs = bdBlockSize dev if BS.null remBytes then do -- Last block; retain the relevant portion of its data trailer <- if trunc then return $ bsReplicate bs truncSentinel else bsDrop (BS.length newBlkData) `fmap` bdReadBlock dev blkAddr let rslt = bsTake bs $ newBlkData `BS.append` trailer return $ Just ((rslt, remBytes), (remBytes, blkAddrs)) else do -- Full block; nothing to see here return $ Just ((newBlkData, remBytes), (remBytes, blkAddrs)) -- | Reads the contents of the given exts's ith block readBlock :: (Monad m) => BlockDevice m -> Ext -> Word64 -> m ByteString readBlock dev c i = do assert (i < blockCount c) $ return () bdReadBlock dev (blockAddrs c !! safeToInt i) writeExt :: Monad m => BlockDevice m -> Ext -> m () writeExt dev c = dbug (" ==> Writing ext: " ++ show c ) $ bdWriteBlock dev (unER $ address c) (encode c) writeInode :: (Monad m, Ord t, Serialize t, Show t) => BlockDevice m -> Inode t -> m () writeInode dev n = bdWriteBlock dev (unIR $ inoAddress n) (encode n) -- | Expands the given Ext into a Ext list containing itself followed by zero -- or more Exts; can be bounded by a positive nonzero value to only retrieve -- (up to) the given number of exts. expandExts :: HalfsCapable b t r l m => Maybe Word64 -> Ext -> HalfsM b r l m [Ext] expandExts (Just bnd) start@Ext{ nextExt = cr } | bnd == 0 = throwError HE_InvalidExtIdx | isNilER cr || bnd == 1 = return [start] | otherwise = do (start:) `fmap` (drefExt cr >>= expandExts (Just (bnd - 1))) expandExts Nothing start@Ext{ nextExt = cr } | isNilER cr = return [start] | otherwise = do (start:) `fmap` (drefExt cr >>= expandExts Nothing) getLastExt :: HalfsCapable b t r l m => Maybe Word64 -> Ext -> HalfsM b r l m Ext getLastExt mbnd c = last `fmap` expandExts mbnd c extFoldM :: HalfsCapable b t r l m => (a -> Ext -> HalfsM b r l m a) -> a -> Ext -> HalfsM b r l m a extFoldM f a c@Ext{ nextExt = cr } | isNilER cr = f a c | otherwise = f a c >>= \fac -> drefExt cr >>= extFoldM f fac extMapM :: HalfsCapable b t r l m => (Ext -> HalfsM b r l m a) -> Ext -> HalfsM b r l m [a] extMapM f c@Ext{ nextExt = cr } | isNilER cr = liftM (:[]) (f c) | otherwise = liftM2 (:) (f c) (drefExt cr >>= extMapM f) drefExt :: HalfsCapable b t r l m => ExtRef -> HalfsM b r l m Ext drefExt cr@(ER addr) | isNilER cr = throwError HE_InvalidExtIdx | otherwise = do dev <- hasks hsBlockDev lift (bdReadBlock dev addr) >>= decodeExt (bdBlockSize dev) drefInode :: HalfsCapable b t r l m => InodeRef -> HalfsM b r l m (Inode t) drefInode (IR addr) = do dev <- hasks hsBlockDev lift (bdReadBlock dev addr) >>= decodeInode setChangeTime :: (Ord t, Serialize t) => t -> Inode t -> Inode t setChangeTime t nd = nd{ inoChangeTime = t } -- | Decompose the given absolute byte offset into an inode's data stream into -- Ext index (i.e., 0-based index into the ext chain), a block offset within -- that Ext, and a byte offset within that block. decomp :: (Serialize t, Timed t m, Monad m, Show t) => Word64 -- ^ Block size, in bytes -> Word64 -- ^ Offset into the data stream -> HalfsM b r l m StreamIdx decomp blkSz streamOff = do -- Note that the first Ext in a Ext chain always gets embedded in an Inode, -- and thus has differing capacity than the rest of the Exts, which are of -- uniform size. (stExtBytes, extBytes, _, _) <- hasks hsSizes let (extIdx, extByteIdx) = if streamOff >= stExtBytes then fmapFst (+1) $ (streamOff - stExtBytes) `divMod` extBytes else (0, streamOff) (blkOff, byteOff) = extByteIdx `divMod` blkSz return (extIdx, blkOff, byteOff) getStreamIdx :: HalfsCapable b t r l m => Word64 -- block size in bytse -> Word64 -- file size in bytes -> Word64 -- start byte index -> HalfsM b r l m StreamIdx getStreamIdx blkSz fileSz start = do when (start > fileSz) $ throwError $ HE_InvalidStreamIndex start decomp blkSz start bytesToEnd :: Word64 -> Word64 -> Word64 bytesToEnd start len | start + len == 0 = 0 | otherwise = max (start + len - 1) start -- "Safe" (i.e., emits runtime assertions on overflow) versions of -- BS.{take,drop,replicate}. We want the efficiency of these functions without -- the danger of an unguarded fromIntegral on the Word64 types we use throughout -- this module, as this could overflow for absurdly large device geometries. We -- may need to revisit some implementation decisions should this occur (e.g., -- because many Prelude and Data.ByteString functions yield and take values of -- type Int). safeToInt :: Integral a => a -> Int safeToInt n = assert (toInteger n <= toInteger (maxBound :: Int)) $ fromIntegral n makeSafeIntF :: Integral a => (Int -> b) -> a -> b makeSafeIntF f n = f $ safeToInt n -- | "Safe" version of Data.ByteString.take bsTake :: Integral a => a -> ByteString -> ByteString bsTake = makeSafeIntF BS.take -- | "Safe" version of Data.ByteString.drop bsDrop :: Integral a => a -> ByteString -> ByteString bsDrop = makeSafeIntF BS.drop -- | "Safe" version of Data.ByteString.replicate bsReplicate :: Integral a => a -> Word8 -> ByteString bsReplicate = makeSafeIntF BS.replicate bsSplitAt :: Integral a => a -> ByteString -> (ByteString, ByteString) bsSplitAt = makeSafeIntF BS.splitAt -------------------------------------------------------------------------------- -- Magic numbers magicStr :: String magicStr = "This is a halfs Inode structure!" magicBytes :: [Word8] magicBytes = assert (length magicStr == 32) $ map (fromIntegral . ord) magicStr magic1, magic2, magic3, magic4 :: ByteString magic1 = BS.pack $ take 8 $ drop 0 magicBytes magic2 = BS.pack $ take 8 $ drop 8 magicBytes magic3 = BS.pack $ take 8 $ drop 16 magicBytes magic4 = BS.pack $ take 8 $ drop 24 magicBytes magicExtStr :: String magicExtStr = "!!erutcurts tnoC sflah a si sihT" magicExtBytes :: [Word8] magicExtBytes = assert (length magicExtStr == 32) $ map (fromIntegral . ord) magicExtStr cmagic1, cmagic2, cmagic3, cmagic4 :: ByteString cmagic1 = BS.pack $ take 8 $ drop 0 magicExtBytes cmagic2 = BS.pack $ take 8 $ drop 8 magicExtBytes cmagic3 = BS.pack $ take 8 $ drop 16 magicExtBytes cmagic4 = BS.pack $ take 8 $ drop 24 magicExtBytes -------------------------------------------------------------------------------- -- Typeclass instances instance (Show t, Eq t, Ord t, Serialize t) => Serialize (Inode t) where put n = do putByteString $ magic1 put $ inoParent n put $ inoLastExt n put $ inoAddress n putWord64be $ inoFileSize n putWord64be $ inoAllocBlocks n put $ inoFileType n put $ inoMode n putByteString $ magic2 putWord64be $ inoNumLinks n put $ inoCreateTime n put $ inoModifyTime n put $ inoAccessTime n put $ inoChangeTime n put $ inoUser n put $ inoGroup n putByteString $ magic3 put $ inoExt n -- NB: For Exts that are inside inodes, the Serialize instance for Ext -- relies on only 8 + iPadSize bytes beyond this point (the inode magic -- number and some padding). If you change this, you'll need to update the -- related calculations in Serialize Ext's get function! putByteString magic4 replicateM_ iPadSize $ putWord8 padSentinel get = do checkMagic magic1 par <- get lcr <- get addr <- get fsz <- getWord64be blks <- getWord64be ftype <- get fmode <- get checkMagic magic2 nlnks <- getWord64be ctm <- get mtm <- get atm <- get chtm <- get unless (ctm <= mtm && ctm <= atm) $ fail "Inode: Incoherent modified / creation / access times." usr <- get grp <- get checkMagic magic3 c <- get checkMagic magic4 padding <- replicateM iPadSize $ getWord8 assert (all (== padSentinel) padding) $ return () return Inode { inoParent = par , inoLastExt = lcr , inoAddress = addr , inoFileSize = fsz , inoAllocBlocks = blks , inoFileType = ftype , inoMode = fmode , inoNumLinks = nlnks , inoCreateTime = ctm , inoModifyTime = mtm , inoAccessTime = atm , inoChangeTime = chtm , inoUser = usr , inoGroup = grp , inoExt = c } where checkMagic x = do magic <- getBytes 8 unless (magic == x) $ fail "Invalid Inode: magic number mismatch" instance Serialize Ext where put c = do unless (numBlocks <= numAddrs') $ fail $ "Corrupted Ext structure put: too many blocks" -- dbugM $ "Ext.put: numBlocks = " ++ show numBlocks -- dbugM $ "Ext.put: blocks = " ++ show blocks -- dbugM $ "Ext.put: fillBlocks = " ++ show fillBlocks putByteString $ cmagic1 put $ address c put $ nextExt c putByteString $ cmagic2 putWord64be $ blockCount c putByteString $ cmagic3 forM_ blocks put replicateM_ fillBlocks $ put nilIR putByteString cmagic4 replicateM_ cPadSize $ putWord8 padSentinel where blocks = blockAddrs c numBlocks = length blocks numAddrs' = safeToInt $ numAddrs c fillBlocks = numAddrs' - numBlocks get = do checkMagic cmagic1 addr <- get dbugM $ "decodeExt: addr = " ++ show addr ext <- get dbugM $ "decodeExt: ext = " ++ show ext checkMagic cmagic2 blkCnt <- getWord64be dbugM $ "decodeExt: blkCnt = " ++ show blkCnt checkMagic cmagic3 -- Some calculations differ slightly based on whether or not this Ext is -- embedded in an inode; in particular, the Inode writes a terminating magic -- number after the end of the serialized Ext, so we must account for that -- when calculating the number of blocks to read below. let isEmbeddedExt = addr == nilER dbugM $ "decodeExt: isEmbeddedExt = " ++ show isEmbeddedExt numBlockBytes <- do remb <- fmap fromIntegral G.remaining dbugM $ "decodeExt: remb = " ++ show remb dbugM $ "--" let numTrailingBytes = if isEmbeddedExt then 8 + fromIntegral cPadSize + 8 + fromIntegral iPadSize -- cmagic4, padding, inode's magic4, inode's padding <EOS> else 8 + fromIntegral cPadSize -- cmagic4, padding, <EOS> dbugM $ "decodeExt: numTrailingBytes = " ++ show numTrailingBytes return (remb - numTrailingBytes) dbugM $ "decodeExt: numBlockBytes = " ++ show numBlockBytes let (numBlocks, check) = numBlockBytes `divMod` refSize dbugM $ "decodeExt: numBlocks = " ++ show numBlocks -- dbugM $ "decodeExt: numBlockBytes = " ++ show numBlockBytes -- dbugM $ "decodeExt: refSzie = " ++ show refSize -- dbugM $ "decodeExt: check = " ++ show check unless (check == 0) $ fail "Ext: Bad remaining byte count for block list." unless (not isEmbeddedExt && numBlocks >= minExtBlocks || isEmbeddedExt && numBlocks >= minInodeBlocks) $ fail "Ext: Not enough space left for minimum number of blocks." blks <- filter (/= 0) `fmap` replicateM (safeToInt numBlocks) get checkMagic cmagic4 padding <- replicateM cPadSize $ getWord8 assert (all (== padSentinel) padding) $ return () let na = error $ "numAddrs has not been populated via Data.Serialize.get " ++ "for Ext; did you forget to use the " ++ "Inode.decodeExt wrapper?" return Ext { address = addr , nextExt = ext , blockCount = blkCnt , blockAddrs = blks , numAddrs = na } where checkMagic x = do magic <- getBytes 8 unless (magic == x) $ fail "Invalid Ext: magic number mismatch" -------------------------------------------------------------------------------- -- Debugging cruft _dumpExts :: HalfsCapable b t r l m => Ext -> HalfsM b r l m () _dumpExts stExt = do exts <- expandExts Nothing stExt if null exts then dbug ("=== No exts ===") $ return () else do dbug ("=== Exts ===") $ return () mapM_ (\c -> dbug (" " ++ show c) $ return ()) exts _allowNoUsesOf :: HalfsCapable b t r l m => HalfsM b r l m () _allowNoUsesOf = do extMapM undefined undefined >> return ()
hackern/halfs
Halfs/Inode.hs
bsd-3-clause
51,840
7
35
15,924
11,465
5,928
5,537
885
11
module RAM ( module RAM.Type , module RAM.State , Builtin (..) ) where -- $Id$ import RAM.Type import RAM.Machine import RAM.State import RAM.Builtin
Erdwolf/autotool-bonn
src/RAM.hs
gpl-2.0
156
0
5
29
46
30
16
8
0
---------------------------------------------------------------------------- -- | -- Module : Prelude -- Copyright : (c) Sergey Vinokurov 2017 -- License : BSD3-style (see LICENSE) -- -- Maintainer : [email protected] -- Created : 17 June 2017 -- Stability : -- Portability : -- -- ---------------------------------------------------------------------------- module Prelude (foo) where import Prelude () foo :: a -> a foo x = x
emacsmirror/flycheck-haskell
test/test-data/project-with-prelude-module/Prelude.hs
gpl-3.0
455
0
5
82
45
32
13
4
1
{-# LANGUAGE Rank2Types, RecordWildCards #-} module OS.Internal ( OS(..) , genericOS ) where import Data.Version (showVersion) import Development.Shake import Development.Shake.FilePath import Dirs import Paths import Types import Utils data OS = OS { -- These paths are all on the target machine. -- They should all be absolute paths. -- During the build, they will be made relative to targetDir -- | Where HP will be installed osHpPrefix :: FilePath -- | Where GHC will be installed , osGhcPrefix :: FilePath -- | Platform-specific actions needed to finish the ghc-bindist/local -- install step (and before any HP packages are built) , osGhcLocalInstall :: GhcInstall -- | Platform-specific actions needed to finish the target-ghc -- install step , osGhcTargetInstall :: GhcInstall -- | Where each package is installed , osPackageTargetDir :: forall p. (PackagePattern p) => p -> FilePath -- | Set True if GHC in this build supports creating shared libs , osDoShared :: Bool -- | Any action to take, after creation of the package conf file, -- before the package's haddock files are created. , osPackagePostRegister :: Package -> Action () -- | Extra action to install the package from the build dir to the -- target image. , osPackageInstallAction :: Package -> Action () -- | Extra actions run after GHC and the packages have been assembled -- into the target image. , osTargetAction :: Action () -- | Directory relative to ghc install for package.conf.d -- (e.g., "lib/7.8.2/package.conf.d") , osGhcDbDir :: FilePath -- | Additional switches/options for "ghc-pkg" -- querying the 'haddock-html' field with ghc-pkg. , osGhcPkgHtmlFieldExtras :: [String] -- | If needed by the platform, make needed changes to the path -- which will be used for the relative urls for platform packages -- when referenced by other packages. The first argument is the -- base path, to which the 2nd argument should be made relative -- (after munging). , osPlatformPkgPathMunge :: FilePath -> HaddockPkgLoc -> HaddockPkgLoc -- | If needed by the platform, make needed changes to the path -- which will be used for the relative urls for GHC packages when -- referenced by other packages. The first argument is the -- base path, to which the 2nd argument should be made relative -- (after munging). , osGhcPkgPathMunge :: FilePath -> HaddockPkgLoc -> HaddockPkgLoc -- | Path, relative to targetDir, expanded for the given package, -- where that package's html docs are installed. , osPkgHtmlDir :: Package -> FilePath -- | Extra actions run after haddock has built the master doc , osDocAction :: Action () -- | Final, OS specific, product. Usually a tarball or installer. -- Should be located in productDir , osProduct :: FilePath -- | Rules for building the product and anything from osTargetExtraNeeds , osRules :: Release -> BuildConfig -> Rules () -- | Extra arguments that are needed for "cabal configure" , osPackageConfigureExtraArgs :: Package -> [String] } genericOS :: BuildConfig -> OS genericOS BuildConfig{..} = OS{..} where HpVersion{..} = bcHpVersion GhcVersion{..} = bcGhcVersion osHpPrefix = "/usr/local/haskell-platform" </> showVersion hpVersion osGhcPrefix = "/usr/local/ghc" </> showVersion ghcVersion osGhcLocalInstall = GhcInstallConfigure osGhcTargetInstall = GhcInstallConfigure osPackageTargetDir p = osHpPrefix </> "lib" </> packagePattern p osDoShared = True osPackagePostRegister _ = return () osPackageInstallAction p = do let confFile = packageTargetConf p let regDir = targetDir </+> osHpPrefix </> "etc" </> "registrations" let regFile = regDir </> show p makeDirectory regDir hasReg <- doesFileExist confFile if hasReg then command_ [] "cp" [confFile, regFile] else command_ [] "rm" ["-f", regFile] osTargetAction = return () osGhcDbDir = "lib" </> show bcGhcVersion </> "package.conf.d" osGhcPkgHtmlFieldExtras = [] osPlatformPkgPathMunge = flip const osGhcPkgPathMunge = flip const osPkgHtmlDir pkg = osPackageTargetDir pkg </> "doc" </> "html" osDocAction = return () osProduct = productDir </> "generic.tar.gz" osRules _hpRelease _bc = osProduct %> \out -> do need [phonyTargetDir, vdir ghcVirtualTarget] command_ [Cwd buildRoot] "tar" ["czf", out `relativeToDir` buildRoot, targetDir `relativeToDir` buildRoot] osPackageConfigureExtraArgs _pkg = []
erantapaa/haskell-platform
hptool/src/OS/Internal.hs
bsd-3-clause
4,934
0
14
1,311
703
398
305
64
2
module SDL.Raw.Basic ( -- * Initialization and Shutdown init, initSubSystem, quit, quitSubSystem, setMainReady, wasInit, -- * Configuration Variables addHintCallback, clearHints, delHintCallback, getHint, setHint, setHintWithPriority, -- * Log Handling log, logCritical, logDebug, logError, logGetOutputFunction, logGetPriority, logInfo, logMessage, logResetPriorities, logSetAllPriority, logSetOutputFunction, logSetPriority, logVerbose, logWarn, -- * Assertions -- | Use Haskell's own assertion primitives rather than SDL's. -- * Querying SDL Version getRevision, getRevisionNumber, getVersion ) where import Control.Monad.IO.Class import Foreign.C.String import Foreign.C.Types import Foreign.Ptr import SDL.Raw.Enum import SDL.Raw.Types import Prelude hiding (init, log) foreign import ccall "SDL.h SDL_Init" initFFI :: InitFlag -> IO CInt foreign import ccall "SDL.h SDL_InitSubSystem" initSubSystemFFI :: InitFlag -> IO CInt foreign import ccall "SDL.h SDL_Quit" quitFFI :: IO () foreign import ccall "SDL.h SDL_QuitSubSystem" quitSubSystemFFI :: InitFlag -> IO () foreign import ccall "SDL.h SDL_SetMainReady" setMainReadyFFI :: IO () foreign import ccall "SDL.h SDL_WasInit" wasInitFFI :: InitFlag -> IO InitFlag foreign import ccall "SDL.h SDL_AddHintCallback" addHintCallbackFFI :: CString -> HintCallback -> Ptr () -> IO () foreign import ccall "SDL.h SDL_ClearHints" clearHintsFFI :: IO () foreign import ccall "SDL.h SDL_DelHintCallback" delHintCallbackFFI :: CString -> HintCallback -> Ptr () -> IO () foreign import ccall "SDL.h SDL_GetHint" getHintFFI :: CString -> IO CString foreign import ccall "SDL.h SDL_SetHint" setHintFFI :: CString -> CString -> IO Bool foreign import ccall "SDL.h SDL_SetHintWithPriority" setHintWithPriorityFFI :: CString -> CString -> HintPriority -> IO Bool foreign import ccall "SDL.h SDL_LogGetOutputFunction" logGetOutputFunctionFFI :: Ptr LogOutputFunction -> Ptr (Ptr ()) -> IO () foreign import ccall "SDL.h SDL_LogGetPriority" logGetPriorityFFI :: CInt -> IO LogPriority foreign import ccall "sdlhelper.c SDLHelper_LogMessage" logMessageFFI :: CInt -> LogPriority -> CString -> IO () foreign import ccall "SDL.h SDL_LogResetPriorities" logResetPrioritiesFFI :: IO () foreign import ccall "SDL.h SDL_LogSetAllPriority" logSetAllPriorityFFI :: LogPriority -> IO () foreign import ccall "SDL.h SDL_LogSetOutputFunction" logSetOutputFunctionFFI :: LogOutputFunction -> Ptr () -> IO () foreign import ccall "SDL.h SDL_LogSetPriority" logSetPriorityFFI :: CInt -> LogPriority -> IO () foreign import ccall "SDL.h SDL_GetRevision" getRevisionFFI :: IO CString foreign import ccall "SDL.h SDL_GetRevisionNumber" getRevisionNumberFFI :: IO CInt foreign import ccall "SDL.h SDL_GetVersion" getVersionFFI :: Ptr Version -> IO () init :: MonadIO m => InitFlag -> m CInt init v1 = liftIO $ initFFI v1 {-# INLINE init #-} initSubSystem :: MonadIO m => InitFlag -> m CInt initSubSystem v1 = liftIO $ initSubSystemFFI v1 {-# INLINE initSubSystem #-} quit :: MonadIO m => m () quit = liftIO quitFFI {-# INLINE quit #-} quitSubSystem :: MonadIO m => InitFlag -> m () quitSubSystem v1 = liftIO $ quitSubSystemFFI v1 {-# INLINE quitSubSystem #-} setMainReady :: MonadIO m => m () setMainReady = liftIO setMainReadyFFI {-# INLINE setMainReady #-} wasInit :: MonadIO m => InitFlag -> m InitFlag wasInit v1 = liftIO $ wasInitFFI v1 {-# INLINE wasInit #-} addHintCallback :: MonadIO m => CString -> HintCallback -> Ptr () -> m () addHintCallback v1 v2 v3 = liftIO $ addHintCallbackFFI v1 v2 v3 {-# INLINE addHintCallback #-} clearHints :: MonadIO m => m () clearHints = liftIO clearHintsFFI {-# INLINE clearHints #-} delHintCallback :: MonadIO m => CString -> HintCallback -> Ptr () -> m () delHintCallback v1 v2 v3 = liftIO $ delHintCallbackFFI v1 v2 v3 {-# INLINE delHintCallback #-} getHint :: MonadIO m => CString -> m CString getHint v1 = liftIO $ getHintFFI v1 {-# INLINE getHint #-} setHint :: MonadIO m => CString -> CString -> m Bool setHint v1 v2 = liftIO $ setHintFFI v1 v2 {-# INLINE setHint #-} setHintWithPriority :: MonadIO m => CString -> CString -> HintPriority -> m Bool setHintWithPriority v1 v2 v3 = liftIO $ setHintWithPriorityFFI v1 v2 v3 {-# INLINE setHintWithPriority #-} log :: CString -> IO () log = logMessage SDL_LOG_CATEGORY_APPLICATION SDL_LOG_PRIORITY_INFO {-# INLINE log #-} logCritical :: CInt -> CString -> IO () logCritical category = logMessage category SDL_LOG_PRIORITY_CRITICAL {-# INLINE logCritical #-} logDebug :: CInt -> CString -> IO () logDebug category = logMessage category SDL_LOG_PRIORITY_DEBUG {-# INLINE logDebug #-} logError :: CInt -> CString -> IO () logError category = logMessage category SDL_LOG_PRIORITY_ERROR {-# INLINE logError #-} logGetOutputFunction :: MonadIO m => Ptr LogOutputFunction -> Ptr (Ptr ()) -> m () logGetOutputFunction v1 v2 = liftIO $ logGetOutputFunctionFFI v1 v2 {-# INLINE logGetOutputFunction #-} logGetPriority :: MonadIO m => CInt -> m LogPriority logGetPriority v1 = liftIO $ logGetPriorityFFI v1 {-# INLINE logGetPriority #-} logInfo :: CInt -> CString -> IO () logInfo category = logMessage category SDL_LOG_PRIORITY_INFO {-# INLINE logInfo #-} logMessage :: MonadIO m => CInt -> LogPriority -> CString -> m () logMessage v1 v2 v3 = liftIO $ logMessageFFI v1 v2 v3 {-# INLINE logMessage #-} logResetPriorities :: MonadIO m => m () logResetPriorities = liftIO logResetPrioritiesFFI {-# INLINE logResetPriorities #-} logSetAllPriority :: MonadIO m => LogPriority -> m () logSetAllPriority v1 = liftIO $ logSetAllPriorityFFI v1 {-# INLINE logSetAllPriority #-} logSetOutputFunction :: MonadIO m => LogOutputFunction -> Ptr () -> m () logSetOutputFunction v1 v2 = liftIO $ logSetOutputFunctionFFI v1 v2 {-# INLINE logSetOutputFunction #-} logSetPriority :: MonadIO m => CInt -> LogPriority -> m () logSetPriority v1 v2 = liftIO $ logSetPriorityFFI v1 v2 {-# INLINE logSetPriority #-} logVerbose :: CInt -> CString -> IO () logVerbose category = logMessage category SDL_LOG_PRIORITY_VERBOSE {-# INLINE logVerbose #-} logWarn :: CInt -> CString -> IO () logWarn category = logMessage category SDL_LOG_PRIORITY_WARN {-# INLINE logWarn #-} getRevision :: MonadIO m => m CString getRevision = liftIO getRevisionFFI {-# INLINE getRevision #-} getRevisionNumber :: MonadIO m => m CInt getRevisionNumber = liftIO getRevisionNumberFFI {-# INLINE getRevisionNumber #-} getVersion :: MonadIO m => Ptr Version -> m () getVersion v1 = liftIO $ getVersionFFI v1 {-# INLINE getVersion #-}
Velro/sdl2
src/SDL/Raw/Basic.hs
bsd-3-clause
6,592
0
11
1,039
1,725
887
838
146
1
{-# LANGUAGE DeriveGeneric, DeriveDataTypeable #-} -- | Types used while planning how to build everything in a project. -- -- Primarily this is the 'ElaboratedInstallPlan'. -- module Distribution.Client.ProjectPlanning.Types ( SolverInstallPlan, -- * Elaborated install plan types ElaboratedInstallPlan, ElaboratedConfiguredPackage(..), ElaboratedPlanPackage, ElaboratedSharedConfig(..), ElaboratedReadyPackage, BuildStyle(..), CabalFileText, -- * Types used in executing an install plan --TODO: [code cleanup] these types should live with execution, not with -- plan definition. Need to better separate InstallPlan definition. GenericBuildResult(..), BuildResult, BuildSuccess(..), BuildFailure(..), DocsResult(..), TestsResult(..), -- * Build targets PackageTarget(..), ComponentTarget(..), SubComponentTarget(..), -- * Setup script SetupScriptStyle(..), ) where import Distribution.Client.PackageHash import Distribution.Client.Types hiding ( BuildResult, BuildSuccess(..), BuildFailure(..) , DocsResult(..), TestsResult(..) ) import Distribution.Client.InstallPlan ( GenericInstallPlan, SolverInstallPlan, GenericPlanPackage ) import Distribution.Package hiding (InstalledPackageId, installedPackageId) import Distribution.System import qualified Distribution.PackageDescription as Cabal import Distribution.InstalledPackageInfo (InstalledPackageInfo) import Distribution.Simple.Compiler import Distribution.Simple.Program.Db import Distribution.ModuleName (ModuleName) import Distribution.Simple.LocalBuildInfo (ComponentName(..)) import qualified Distribution.Simple.InstallDirs as InstallDirs import Distribution.Simple.InstallDirs (PathTemplate) import Distribution.Version import Distribution.Solver.Types.ComponentDeps (ComponentDeps) import Distribution.Solver.Types.OptionalStanza import Distribution.Solver.Types.PackageFixedDeps import Data.Map (Map) import Data.Set (Set) import qualified Data.ByteString.Lazy as LBS import Distribution.Compat.Binary import GHC.Generics (Generic) import Data.Typeable (Typeable) import Control.Exception -- | The combination of an elaborated install plan plus a -- 'ElaboratedSharedConfig' contains all the details necessary to be able -- to execute the plan without having to make further policy decisions. -- -- It does not include dynamic elements such as resources (such as http -- connections). -- type ElaboratedInstallPlan = GenericInstallPlan InstalledPackageInfo ElaboratedConfiguredPackage BuildSuccess BuildFailure type ElaboratedPlanPackage = GenericPlanPackage InstalledPackageInfo ElaboratedConfiguredPackage BuildSuccess BuildFailure --TODO: [code cleanup] decide if we really need this, there's not much in it, and in principle -- even platform and compiler could be different if we're building things -- like a server + client with ghc + ghcjs data ElaboratedSharedConfig = ElaboratedSharedConfig { pkgConfigPlatform :: Platform, pkgConfigCompiler :: Compiler, --TODO: [code cleanup] replace with CompilerInfo -- | The programs that the compiler configured (e.g. for GHC, the progs -- ghc & ghc-pkg). Once constructed, only the 'configuredPrograms' are -- used. pkgConfigCompilerProgs :: ProgramDb } deriving (Show, Generic) --TODO: [code cleanup] no Eq instance instance Binary ElaboratedSharedConfig data ElaboratedConfiguredPackage = ElaboratedConfiguredPackage { pkgInstalledId :: InstalledPackageId, pkgSourceId :: PackageId, -- | TODO: [code cleanup] we don't need this, just a few bits from it: -- build type, spec version pkgDescription :: Cabal.PackageDescription, -- | A total flag assignment for the package pkgFlagAssignment :: Cabal.FlagAssignment, -- | The original default flag assignment, used only for reporting. pkgFlagDefaults :: Cabal.FlagAssignment, -- | The exact dependencies (on other plan packages) -- pkgDependencies :: ComponentDeps [ConfiguredId], -- | Which optional stanzas (ie testsuites, benchmarks) can be built. -- This means the solver produced a plan that has them available. -- This doesn't necessary mean we build them by default. pkgStanzasAvailable :: Set OptionalStanza, -- | Which optional stanzas the user explicitly asked to enable or -- to disable. This tells us which ones we build by default, and -- helps with error messages when the user asks to build something -- they explicitly disabled. -- -- TODO: The 'Bool' here should be refined into an ADT with three -- cases: NotRequested, ExplicitlyRequested and -- ImplicitlyRequested. A stanza is explicitly requested if -- the user asked, for this *specific* package, that the stanza -- be enabled; it's implicitly requested if the user asked for -- all global packages to have this stanza enabled. The -- difference between an explicit and implicit request is -- error reporting behavior: if a user asks for tests to be -- enabled for a specific package that doesn't have any tests, -- we should warn them about it, but we shouldn't complain -- that a user enabled tests globally, and some local packages -- just happen not to have any tests. (But perhaps we should -- warn if ALL local packages don't have any tests.) pkgStanzasRequested :: Map OptionalStanza Bool, -- | Which optional stanzas (ie testsuites, benchmarks) will actually -- be enabled during the package configure step. pkgStanzasEnabled :: Set OptionalStanza, -- | Where the package comes from, e.g. tarball, local dir etc. This -- is not the same as where it may be unpacked to for the build. pkgSourceLocation :: PackageLocation (Maybe FilePath), -- | The hash of the source, e.g. the tarball. We don't have this for -- local source dir packages. pkgSourceHash :: Maybe PackageSourceHash, --pkgSourceDir ? -- currently passed in later because they can use temp locations --pkgBuildDir ? -- but could in principle still have it here, with optional instr to use temp loc pkgBuildStyle :: BuildStyle, pkgSetupPackageDBStack :: PackageDBStack, pkgBuildPackageDBStack :: PackageDBStack, pkgRegisterPackageDBStack :: PackageDBStack, -- | The package contains a library and so must be registered pkgRequiresRegistration :: Bool, pkgDescriptionOverride :: Maybe CabalFileText, pkgVanillaLib :: Bool, pkgSharedLib :: Bool, pkgDynExe :: Bool, pkgGHCiLib :: Bool, pkgProfLib :: Bool, pkgProfExe :: Bool, pkgProfLibDetail :: ProfDetailLevel, pkgProfExeDetail :: ProfDetailLevel, pkgCoverage :: Bool, pkgOptimization :: OptimisationLevel, pkgSplitObjs :: Bool, pkgStripLibs :: Bool, pkgStripExes :: Bool, pkgDebugInfo :: DebugInfoLevel, pkgProgramPaths :: Map String FilePath, pkgProgramArgs :: Map String [String], pkgProgramPathExtra :: [FilePath], pkgConfigureScriptArgs :: [String], pkgExtraLibDirs :: [FilePath], pkgExtraFrameworkDirs :: [FilePath], pkgExtraIncludeDirs :: [FilePath], pkgProgPrefix :: Maybe PathTemplate, pkgProgSuffix :: Maybe PathTemplate, pkgInstallDirs :: InstallDirs.InstallDirs FilePath, pkgHaddockHoogle :: Bool, pkgHaddockHtml :: Bool, pkgHaddockHtmlLocation :: Maybe String, pkgHaddockExecutables :: Bool, pkgHaddockTestSuites :: Bool, pkgHaddockBenchmarks :: Bool, pkgHaddockInternal :: Bool, pkgHaddockCss :: Maybe FilePath, pkgHaddockHscolour :: Bool, pkgHaddockHscolourCss :: Maybe FilePath, pkgHaddockContents :: Maybe PathTemplate, -- Setup.hs related things: -- | One of four modes for how we build and interact with the Setup.hs -- script, based on whether it's a build-type Custom, with or without -- explicit deps and the cabal spec version the .cabal file needs. pkgSetupScriptStyle :: SetupScriptStyle, -- | The version of the Cabal command line interface that we are using -- for this package. This is typically the version of the Cabal lib -- that the Setup.hs is built against. pkgSetupScriptCliVersion :: Version, -- Build time related: pkgBuildTargets :: [ComponentTarget], pkgReplTarget :: Maybe ComponentTarget, pkgBuildHaddocks :: Bool } deriving (Eq, Show, Generic) instance Binary ElaboratedConfiguredPackage instance Package ElaboratedConfiguredPackage where packageId = pkgSourceId instance HasUnitId ElaboratedConfiguredPackage where installedUnitId = pkgInstalledId instance PackageFixedDeps ElaboratedConfiguredPackage where depends = fmap (map installedPackageId) . pkgDependencies -- | This is used in the install plan to indicate how the package will be -- built. -- data BuildStyle = -- | The classic approach where the package is built, then the files -- installed into some location and the result registered in a package db. -- -- If the package came from a tarball then it's built in a temp dir and -- the results discarded. BuildAndInstall -- | The package is built, but the files are not installed anywhere, -- rather the build dir is kept and the package is registered inplace. -- -- Such packages can still subsequently be installed. -- -- Typically 'BuildAndInstall' packages will only depend on other -- 'BuildAndInstall' style packages and not on 'BuildInplaceOnly' ones. -- | BuildInplaceOnly deriving (Eq, Show, Generic) instance Binary BuildStyle type CabalFileText = LBS.ByteString type ElaboratedReadyPackage = GenericReadyPackage ElaboratedConfiguredPackage --TODO: [code cleanup] this duplicates the InstalledPackageInfo quite a bit in an install plan -- because the same ipkg is used by many packages. So the binary file will be big. -- Could we keep just (ipkgid, deps) instead of the whole InstalledPackageInfo? -- or transform to a shared form when serialising / deserialising data GenericBuildResult ipkg iresult ifailure = BuildFailure ifailure | BuildSuccess [ipkg] iresult deriving (Eq, Show, Generic) instance (Binary ipkg, Binary iresult, Binary ifailure) => Binary (GenericBuildResult ipkg iresult ifailure) type BuildResult = GenericBuildResult InstalledPackageInfo BuildSuccess BuildFailure data BuildSuccess = BuildOk DocsResult TestsResult deriving (Eq, Show, Generic) data DocsResult = DocsNotTried | DocsFailed | DocsOk deriving (Eq, Show, Generic) data TestsResult = TestsNotTried | TestsOk deriving (Eq, Show, Generic) data BuildFailure = PlanningFailed --TODO: [required eventually] not yet used | DependentFailed PackageId | DownloadFailed String --TODO: [required eventually] not yet used | UnpackFailed String --TODO: [required eventually] not yet used | ConfigureFailed String | BuildFailed String | TestsFailed String --TODO: [required eventually] not yet used | InstallFailed String deriving (Eq, Show, Typeable, Generic) instance Exception BuildFailure instance Binary BuildFailure instance Binary BuildSuccess instance Binary DocsResult instance Binary TestsResult --------------------------- -- Build targets -- -- | The various targets within a package. This is more of a high level -- specification than a elaborated prescription. -- data PackageTarget = -- | Build the default components in this package. This usually means -- just the lib and exes, but it can also mean the testsuites and -- benchmarks if the user explicitly requested them. BuildDefaultComponents -- | Build a specific component in this package. | BuildSpecificComponent ComponentTarget | ReplDefaultComponent | ReplSpecificComponent ComponentTarget | HaddockDefaultComponents deriving (Eq, Show, Generic) data ComponentTarget = ComponentTarget ComponentName SubComponentTarget deriving (Eq, Show, Generic) data SubComponentTarget = WholeComponent | ModuleTarget ModuleName | FileTarget FilePath deriving (Eq, Show, Generic) instance Binary PackageTarget instance Binary ComponentTarget instance Binary SubComponentTarget --------------------------- -- Setup.hs script policy -- -- | There are four major cases for Setup.hs handling: -- -- 1. @build-type@ Custom with a @custom-setup@ section -- 2. @build-type@ Custom without a @custom-setup@ section -- 3. @build-type@ not Custom with @cabal-version > $our-cabal-version@ -- 4. @build-type@ not Custom with @cabal-version <= $our-cabal-version@ -- -- It's also worth noting that packages specifying @cabal-version: >= 1.23@ -- or later that have @build-type@ Custom will always have a @custom-setup@ -- section. Therefore in case 2, the specified @cabal-version@ will always be -- less than 1.23. -- -- In cases 1 and 2 we obviously have to build an external Setup.hs script, -- while in case 4 we can use the internal library API. In case 3 we also have -- to build an external Setup.hs script because the package needs a later -- Cabal lib version than we can support internally. -- data SetupScriptStyle = SetupCustomExplicitDeps | SetupCustomImplicitDeps | SetupNonCustomExternalLib | SetupNonCustomInternalLib deriving (Eq, Show, Generic) instance Binary SetupScriptStyle
bennofs/cabal
cabal-install/Distribution/Client/ProjectPlanning/Types.hs
bsd-3-clause
14,755
0
11
3,862
1,548
978
570
187
0
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} -- Determine which packages are already installed module Stack.Build.Installed ( InstalledMap , Installed (..) , GetInstalledOpts (..) , getInstalled ) where import Control.Applicative import Control.Monad import Control.Monad.Catch (MonadCatch, MonadMask) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import Data.Conduit import qualified Data.Conduit.List as CL import Data.Function import qualified Data.HashSet as HashSet import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import qualified Data.Map.Strict as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Prelude hiding (FilePath, writeFile) import Stack.Build.Cache import Stack.Types.Build import Stack.Constants import Stack.GhcPkg import Stack.PackageDump import Stack.Types import Stack.Types.Internal type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasEnvConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env) data LoadHelper = LoadHelper { lhId :: !GhcPkgId , lhDeps :: ![GhcPkgId] , lhPair :: !(PackageName, (Version, InstallLocation, Installed)) -- TODO Version is now redundant and can be gleaned from Installed } deriving Show type InstalledMap = Map PackageName (Version, InstallLocation, Installed) -- TODO Version is now redundant and can be gleaned from Installed -- | Options for 'getInstalled'. data GetInstalledOpts = GetInstalledOpts { getInstalledProfiling :: !Bool -- ^ Require profiling libraries? , getInstalledHaddock :: !Bool -- ^ Require haddocks? } -- | Returns the new InstalledMap and all of the locally registered packages. getInstalled :: (M env m, PackageInstallInfo pii) => EnvOverride -> GetInstalledOpts -> Map PackageName pii -- ^ does not contain any installed information -> m (InstalledMap, Set GhcPkgId) getInstalled menv opts sourceMap = do snapDBPath <- packageDatabaseDeps localDBPath <- packageDatabaseLocal bconfig <- asks getBuildConfig mcache <- if getInstalledProfiling opts || getInstalledHaddock opts then liftM Just $ loadInstalledCache $ configInstalledCache bconfig else return Nothing let loadDatabase' = loadDatabase menv opts mcache sourceMap (installedLibs', localInstalled) <- loadDatabase' Nothing [] >>= loadDatabase' (Just (Snap, snapDBPath)) . fst >>= loadDatabase' (Just (Local, localDBPath)) . fst let installedLibs = M.fromList $ map lhPair installedLibs' case mcache of Nothing -> return () Just pcache -> saveInstalledCache (configInstalledCache bconfig) pcache -- Add in the executables that are installed, making sure to only trust a -- listed installation under the right circumstances (see below) let exesToSM loc = Map.unions . map (exeToSM loc) exeToSM loc (PackageIdentifier name version) = case Map.lookup name sourceMap of -- Doesn't conflict with anything, so that's OK Nothing -> m Just pii -- Not the version we want, ignore it | version /= piiVersion pii || loc /= piiLocation pii -> Map.empty | otherwise -> m where m = Map.singleton name (version, loc, Executable $ PackageIdentifier name version) exesSnap <- getInstalledExes Snap exesLocal <- getInstalledExes Local let installedMap = Map.unions [ exesToSM Local exesLocal , exesToSM Snap exesSnap , installedLibs ] return (installedMap, localInstalled) -- | Outputs both the modified InstalledMap and the Set of all installed packages in this database -- -- The goal is to ascertain that the dependencies for a package are present, -- that it has profiling if necessary, and that it matches the version and -- location needed by the SourceMap loadDatabase :: (M env m, PackageInstallInfo pii) => EnvOverride -> GetInstalledOpts -> Maybe InstalledCache -- ^ if Just, profiling or haddock is required -> Map PackageName pii -- ^ to determine which installed things we should include -> Maybe (InstallLocation, Path Abs Dir) -- ^ package database, Nothing for global -> [LoadHelper] -- ^ from parent databases -> m ([LoadHelper], Set GhcPkgId) loadDatabase menv opts mcache sourceMap mdb lhs0 = do (lhs1, gids) <- ghcPkgDump menv (fmap snd mdb) $ conduitDumpPackage =$ sink let lhs = pruneDeps (packageIdentifierName . ghcPkgIdPackageIdentifier) lhId lhDeps const (lhs0 ++ lhs1) return (map (\lh -> lh { lhDeps = [] }) $ Map.elems lhs, Set.fromList gids) where conduitProfilingCache = case mcache of Just cache | getInstalledProfiling opts -> addProfiling cache -- Just an optimization to avoid calculating the profiling -- values when they aren't necessary _ -> CL.map (\dp -> dp { dpProfiling = False }) conduitHaddockCache = case mcache of Just cache | getInstalledHaddock opts -> addHaddock cache -- Just an optimization to avoid calculating the haddock -- values when they aren't necessary _ -> CL.map (\dp -> dp { dpHaddock = False }) sinkDP = conduitProfilingCache =$ conduitHaddockCache =$ CL.mapMaybe (isAllowed opts mcache sourceMap (fmap fst mdb)) =$ CL.consume sinkGIDs = CL.map dpGhcPkgId =$ CL.consume sink = getZipSink $ (,) <$> ZipSink sinkDP <*> ZipSink sinkGIDs -- | Check if a can be included in the set of installed packages or not, based -- on the package selections made by the user. This does not perform any -- dirtiness or flag change checks. isAllowed :: PackageInstallInfo pii => GetInstalledOpts -> Maybe InstalledCache -> Map PackageName pii -> Maybe InstallLocation -> DumpPackage Bool Bool -> Maybe LoadHelper isAllowed opts mcache sourceMap mloc dp -- Check that it can do profiling if necessary | getInstalledProfiling opts && isJust mcache && not (dpProfiling dp) = Nothing -- Check that it has haddocks if necessary | getInstalledHaddock opts && isJust mcache && not (dpHaddock dp) = Nothing | toInclude = Just LoadHelper { lhId = gid , lhDeps = -- We always want to consider the wired in packages as having all -- of their dependencies installed, since we have no ability to -- reinstall them. This is especially important for using different -- minor versions of GHC, where the dependencies of wired-in -- packages may change slightly and therefore not match the -- snapshot. if name `HashSet.member` wiredInPackages then [] else dpDepends dp , lhPair = (name, (version, fromMaybe Snap mloc, Library gid)) } | otherwise = Nothing where toInclude = case Map.lookup name sourceMap of Nothing -> case mloc of -- The sourceMap has nothing to say about this global -- package, so we can use it Nothing -> True -- For non-global packages, don't include unknown packages. -- See: -- https://github.com/commercialhaskell/stack/issues/292 Just _ -> False Just pii -> version == piiVersion pii -- only accept the desired version && checkLocation (piiLocation pii) -- Ensure that the installed location matches where the sourceMap says it -- should be installed checkLocation Snap = mloc /= Just Local -- we can allow either global or snap checkLocation Local = mloc == Just Local gid = dpGhcPkgId dp PackageIdentifier name version = ghcPkgIdPackageIdentifier gid
duplode/stack
src/Stack/Build/Installed.hs
bsd-3-clause
8,898
0
19
2,751
1,677
895
782
159
5
main = drawingOf(thing(1) & thing(2)) thing(n) = if n > 1 rectangle(n, n) else circle(n)
venkat24/codeworld
codeworld-compiler/test/testcase/test_ifCondition/source.hs
apache-2.0
89
2
9
15
65
34
31
-1
-1
-- | This module provides numerical routines for minimizing linear and nonlinear multidimensional functions. -- Multidimensional optimization is significantly harder than one dimensional optimization. -- In general, there are no black box routines that work well on every function, -- even if the function has only a single local minimum. -- -- FIXME: better documentation module HLearn.Optimization.Multivariate ( -- * Simple interface -- * Advanced interface -- ** Conjugate gradient descent -- | A great introduction is: -- "An introduction to the conjugate gradient method without the pain" by Jonathan Richard Shewchuk -- -- NOTE: Does this paper has a mistake in the calculation of the optimal step size; -- it should be multiplied by 1/2? fminunc_cgd_ , Iterator_cgd -- *** Conjugation methods , ConjugateMethod , steepestDescent , fletcherReeves , polakRibiere , hestenesStiefel -- ** Newton-Raphson (quadratic gradient descent) , Iterator_nr , fminunc_nr_ -- ** Quasi Newton methods , Iterator_bfgs , fminunc_bfgs_ -- ** Multivariate line search , LineSearch , mkLineSearch , lineSearch_brent , lineSearch_gss -- *** Backtracking -- | Backtracking is much faster than univariate line search methods. -- It typically requires 1-3 function evaluations, whereas the univariate optimizations typically require 5-50. -- The downside is that backtracking is not guaranteed to converge to the minimum along the line search. -- In many cases, however, this is okay. -- We make up for the lack of convergence by being able to run many more iterations of the multivariate optimization. , Backtracking (..) , backtracking , wolfe , amijo , weakCurvature , strongCurvature -- * Test functions -- | See <https://en.wikipedia.org/wiki/Test_functions_for_optimization wikipedia> for more detail. -- -- FIXME: Include graphs in documentation. -- -- FIXME: Implement the rest of the functions. , sphere , ackley , beale , rosenbrock ) where import SubHask import SubHask.Algebra.Vector import SubHask.Category.Trans.Derivative import HLearn.History import HLearn.Optimization.Univariate ------------------------------------------------------------------------------- type MultivariateMinimizer (n::Nat) cxt opt v = LineSearch cxt v -> StopCondition (opt v) -> v -> Diff n v (Scalar v) -> History cxt (opt v) ------------------------------------------------------------------------------- -- generic transforms -- FIXME: broken by new History -- projectOrthant opt1 = do -- mopt0 <- prevValueOfType opt1 -- return $ case mopt0 of -- Nothing -> opt1 -- Just opt0 -> set x1 (VG.zipWith go (opt0^.x1) (opt1^.x1)) $ opt1 -- where -- go a0 a1 = if (a1>=0 && a0>=0) || (a1<=0 && a0<=0) -- then a1 -- else 0 ------------------------------------------------------------------------------- -- Conjugate gradient descent data Iterator_cgd a = Iterator_cgd { _cgd_x1 :: !a , _cgd_fx1 :: !(Scalar a) , _cgd_f'x1 :: !a , _cgd_alpha :: !(Scalar a) , _cgd_f'x0 :: !a , _cgd_s0 :: !a , _cgd_f :: !(a -> Scalar a) } deriving (Typeable) type instance Scalar (Iterator_cgd a) = Scalar a type instance Logic (Iterator_cgd a) = Bool instance (Eq (Scalar a), Eq a) => Eq_ (Iterator_cgd a) where a1==a2 = (_cgd_x1 a1 == _cgd_x1 a2) && (_cgd_fx1 a1 == _cgd_fx1 a2) && (_cgd_f'x1 a1 == _cgd_f'x1 a2) -- && (_cgd_alpha a1 == _cgd_alpha a2) -- && (_cgd_f'x0 a1 == _cgd_f'x0 a2) -- && (_cgd_s0 a1 == _cgd_s0 a2) instance (Hilbert a, Show a, Show (Scalar a)) => Show (Iterator_cgd a) where -- show cgd = "CGD; x="++show (_cgd_x1 cgd)++"; f'x="++show (_cgd_f'x1 cgd)++"; fx="++show (_cgd_fx1 cgd) show cgd = "CGD; |f'x|="++show (size $ _cgd_f'x1 cgd)++"; fx="++show (_cgd_fx1 cgd) instance Has_x1 Iterator_cgd v where x1 = _cgd_x1 instance Has_fx1 Iterator_cgd v where fx1 = _cgd_fx1 --------------------------------------- -- | method for determining the conjugate direction; -- See <https://en.wikipedia.org/wiki/Nonlinear_conjugate_gradient wikipedia> for more details. type ConjugateMethod v = Module v => v -> v -> v -> Scalar v {-# INLINABLE steepestDescent #-} steepestDescent :: ConjugateMethod v steepestDescent _ _ _ = 0 {-# INLINABLE fletcherReeves #-} fletcherReeves :: Hilbert v => ConjugateMethod v fletcherReeves f'x1 f'x0 _ = f'x1 <> f'x1 / f'x0 <> f'x0 {-# INLINABLE polakRibiere #-} polakRibiere :: Hilbert v => ConjugateMethod v polakRibiere f'x1 f'x0 _ = (f'x1 <> (f'x1 - f'x0)) / (f'x0 <> f'x0) {-# INLINABLE hestenesStiefel #-} hestenesStiefel :: Hilbert v => ConjugateMethod v hestenesStiefel f'x1 f'x0 s0 = -(f'x1 <> (f'x1 - f'x0)) / (s0 <> (f'x1 - f'x0)) ---------------------------------------- -- | A generic method for conjugate gradient descent that gives you more control over the optimization parameters {-# INLINEABLE fminunc_cgd_ #-} fminunc_cgd_ :: ( Hilbert v , ClassicalLogic v ) => ConjugateMethod v -> MultivariateMinimizer 1 cxt Iterator_cgd v fminunc_cgd_ conj lineSearch stop x0 f = {-# SCC fminunc_cgd #-} iterate (step_cgd lineSearch conj f) stop $ Iterator_cgd { _cgd_x1 = x0 , _cgd_fx1 = f $ x0 , _cgd_f'x1 = f' $ x0 , _cgd_alpha = 1e-2 , _cgd_f'x0 = 2 *. f' x0 , _cgd_s0 = f' x0 , _cgd_f = (f $) } where f' = (derivative f $) step_cgd :: ( Hilbert v , ClassicalLogic v ) => LineSearch cxt v -> ConjugateMethod v -> C1 (v -> Scalar v) -> Iterator_cgd v -> History cxt (Iterator_cgd v) step_cgd stepMethod conjMethod f (Iterator_cgd x1 fx1 f'x1 alpha1 f'x0 s0 _) = {-# SCC step_cgd #-} do let f' = (derivative f $) -- This test on beta ensures that conjugacy will be reset when it is lost. -- The formula is taken from equation 1.174 of the book "Nonlinear Programming". -- -- FIXME: -- This test isn't needed in linear optimization, and the inner products are mildly expensive. -- It also makes CGD work only in a Hilbert space. -- Is the restriction worth it? -- let beta = if abs (f'x1<>f'x0) > 0.2*(f'x0<>f'x0) -- then 0 -- else max 0 $ conjMethod f'x1 f'x0 s0 let beta = conjMethod f'x1 f'x0 s0 let s1 = -f'x1 + beta *. s0 alpha <- stepMethod (f $) f' x1 s1 alpha1 let x = x1 + alpha *. s1 return $ Iterator_cgd { _cgd_x1 = x , _cgd_fx1 = f $ x , _cgd_f'x1 = f' $ x , _cgd_alpha = alpha , _cgd_f'x0 = f'x1 , _cgd_s0 = s1 , _cgd_f = (f $) } ------------------------------------------------------------------------------- -- The Newton-Raphson method (quadratic gradient descent) data Iterator_nr v = Iterator_nr { _nr_x1 :: !v , _nr_fx1 :: !(Scalar v) , _nr_fx0 :: !(Scalar v) , _nr_f'x1 :: !v , _nr_alpha1 :: !(Scalar v) } deriving (Typeable) instance Show (Iterator_nr v) where show _ = "Iterator_nr" type instance Scalar (Iterator_nr a) = Scalar a instance Has_x1 Iterator_nr a where x1 = _nr_x1 instance Has_fx1 Iterator_nr a where fx1 = _nr_fx1 ---------------------------------------- {-# INLINEABLE fminunc_nr_ #-} fminunc_nr_ :: ( Hilbert v , BoundedField (Scalar v) ) => MultivariateMinimizer 2 cxt Iterator_nr v fminunc_nr_ _ stop x0 f = iterate (step_nr f) stop $ Iterator_nr { _nr_x1 = x0 , _nr_fx1 = f $ x0 , _nr_fx0 = infinity , _nr_f'x1 = derivative f $ x0 , _nr_alpha1 = 1 } step_nr :: forall v cxt. ( Hilbert v , BoundedField (Scalar v) ) => C2 (v -> Scalar v) -> Iterator_nr v -> History cxt (Iterator_nr v) step_nr f (Iterator_nr x0 fx0 _ f'x0 alpha0) = do let f' = (derivative f $) f'' = ((derivative . derivative $ f) $) -- FIXME: We need regularization when the 2nd derivative is degenerate let dir = reciprocal (f'' x0) `mXv` f'x0 -- FIXME: We should have the option to do line searches using any method -- alpha <- do -- let g :: v -> Scalar v -- g y = f $ x0 + (y .* dir) -- -- bracket <- LineMin.lineBracket g (alpha0/2) (alpha0*2) -- brent <- LineMin.fminuncM_brent_ (return.g) bracket -- ( maxIterations 100 -- -- + fx1grows -- ) -- return $ LineMin._brent_x brent let alpha=1 let x1 = x0 + alpha*.dir return $ Iterator_nr { _nr_x1 = x1 , _nr_fx1 = f $ x1 , _nr_fx0 = fx0 , _nr_f'x1 = f' $ x1 , _nr_alpha1 = 1 -- alpha } ------------------------------------------------------------------------------- -- The BFGS quasi-newton method -- | FIXME: -- We currently build the full matrix, making things slower than they need to be. -- Fixing this probably requires extending the linear algebra in subhask. -- -- FIXME: -- Also, the code converges much slower than I would expect for some reason. data Iterator_bfgs v = Iterator_bfgs { _bfgs_x1 :: !v , _bfgs_fx1 :: !(Scalar v) , _bfgs_fx0 :: !(Scalar v) , _bfgs_f'x1 :: !v , _bfgs_f''x1 :: !((v><v)) , _bfgs_alpha1 :: !(Scalar v) } deriving (Typeable) type instance Scalar (Iterator_bfgs v) = Scalar v instance (Show v, Show (Scalar v)) => Show (Iterator_bfgs v) where show i = "BFGS; x="++show (_bfgs_x1 i)++"; f'x="++show (_bfgs_f'x1 i)++"; fx="++show (_bfgs_fx1 i) instance Has_x1 Iterator_bfgs a where x1 = _bfgs_x1 instance Has_fx1 Iterator_bfgs a where fx1 = _bfgs_fx1 {-# INLINEABLE fminunc_bfgs_ #-} fminunc_bfgs_ :: ( Hilbert v , BoundedField (Scalar v) ) => MultivariateMinimizer 1 cxt Iterator_bfgs v fminunc_bfgs_ linesearch stop x0 f = iterate (step_bfgs f linesearch) stop $ Iterator_bfgs { _bfgs_x1 = x0 , _bfgs_fx1 = f $ x0 , _bfgs_fx0 = infinity , _bfgs_f'x1 = derivative f $ x0 , _bfgs_f''x1 = 1 , _bfgs_alpha1 = 1e-10 } step_bfgs :: forall v cxt. ( Hilbert v , BoundedField (Scalar v) ) => C1 ( v -> Scalar v) -> LineSearch cxt v -> Iterator_bfgs v -> History cxt (Iterator_bfgs v) step_bfgs f linesearch opt = do let f' = (derivative f $) let x0 = _bfgs_x1 opt fx0 = _bfgs_fx1 opt f'x0 = _bfgs_f'x1 opt f''x0 = _bfgs_f''x1 opt alpha0 = _bfgs_alpha1 opt let d = -f''x0 `mXv` f'x0 -- g alpha = f $ x0 + alpha *. d -- g' alpha = f' $ x0 + alpha *. d -- bracket <- lineBracket g (alpha0/2) (alpha0*2) -- brent <- fminuncM_brent_ (return.g) bracket (maxIterations 200 || stop_brent 1e-6) -- let alpha = x1 brent alpha <- linesearch (f $) f' x0 f'x0 alpha0 let x1 = x0 - alpha *. d f'x1 = f' x1 let p = x1 - x0 q = f'x1 - f'x0 let xsi = 1 tao = q <> (f''x0 `mXv` q) v = p ./ (p<>q) - (f''x0 `mXv` q) ./ tao f''x1 = f''x0 + (p >< p) ./ (p<>q) - (f''x0 * (q><q) * f''x0) ./ tao + (xsi*tao) *. (v><v) -- let go a1 a0 = if (a1>=0 && a0 >=0) || (a1<=0&&a0<=0) -- then a1 -- else a1 -- x1mod = VG.zipWith go x1 x0 let x1mod = x1 return $ Iterator_bfgs { _bfgs_x1 = x1mod , _bfgs_fx1 = f $ x1mod , _bfgs_fx0 = fx0 , _bfgs_f'x1 = f' $ x1mod , _bfgs_f''x1 = f''x1 , _bfgs_alpha1 = alpha } ------------------------------------------------------------------------------- -- Line search -- | Functions of this type determine how far to go in a particular direction. -- These functions perform the same task as "UnivariateMinimizer", -- but the arguments are explicitly multidimensional. type LineSearch cxt v = (v -> Scalar v) -- ^ f = function -> (v -> v) -- ^ f' = derivative of the function -> v -- ^ x0 = starting position -> v -- ^ f'(x0) = direction -> Scalar v -- ^ initial guess at distance to minimum -> History cxt (Scalar v) -- | Convert a "UnivariateMinimizer" into a "LineSearch". {-# INLINEABLE mkLineSearch #-} mkLineSearch :: ( Has_x1 opt (Scalar v) , VectorSpace v , OrdField (Scalar v) , cxt (LineBracket (Scalar v)) , cxt (opt (Scalar v)) , cxt (Scalar (opt (Scalar v))) ) => proxy opt -- ^ required for type checking -> UnivariateMinimizer cxt opt (Scalar v) -> StopCondition (opt (Scalar v)) -- ^ controls the number of iterations -> LineSearch cxt v mkLineSearch _ fminuncM stops f _ x0 dir stepGuess = {-# SCC uni2multiLineSearch #-} do let g y = f $ x0 + dir.*y opt <- fminuncM stops stepGuess (return . g) return $ x1 opt -- | Brent's method promoted to work on a one dimension subspace. {-# INLINEABLE lineSearch_brent #-} lineSearch_brent :: ( VectorSpace v , OrdField (Scalar v) , cxt (LineBracket (Scalar v)) , cxt (Iterator_brent (Scalar v)) ) => StopCondition (Iterator_brent (Scalar v)) -> LineSearch cxt v lineSearch_brent stops = mkLineSearch (Proxy::Proxy Iterator_brent) fminuncM_brent stops -- | Golden section search promoted to work on a one dimension subspace. {-# INLINEABLE lineSearch_gss #-} lineSearch_gss :: ( VectorSpace v , OrdField (Scalar v) , cxt (LineBracket (Scalar v)) , cxt (Iterator_gss (Scalar v)) ) => StopCondition (Iterator_gss (Scalar v)) -> LineSearch cxt v lineSearch_gss stops = mkLineSearch (Proxy::Proxy Iterator_gss) fminuncM_gss stops ------------------------------------------------------------------------------- -- backtracking data Backtracking v = Backtracking { _bt_x :: !(Scalar v) , _bt_fx :: !(Scalar v) , _bt_f'x :: !v , _init_dir :: !v , _init_f'x :: !v , _init_fx :: !(Scalar v) , _init_x :: !v } deriving (Typeable) type instance Scalar (Backtracking v) = Scalar v instance Show (Backtracking v) where show _ = "Backtracking" instance Has_fx1 Backtracking v where fx1 = _bt_fx -- | Backtracking linesearch is NOT guaranteed to converge. -- It is frequently used as the linesearch for multidimensional problems. -- In this case, the overall minimization problem can converge significantly -- faster than if one of the safer methods is used. {-# INLINABLE backtracking #-} backtracking :: ( Hilbert v , cxt (Backtracking v) ) => StopCondition (Backtracking v) -> LineSearch cxt v backtracking stop f f' x0 f'x0 stepGuess = {-# SCC backtracking #-} beginFunction "backtracking" $ do let g y = f $ x0 + y *. f'x0 let grow=1.65 fmap _bt_x $ iterate (step_backtracking 0.85 f f') stop $ Backtracking { _bt_x = (grow*stepGuess) , _bt_fx = g (grow*stepGuess) , _bt_f'x = grow *. (f' $ x0 + grow*stepGuess *. f'x0) , _init_dir = f'x0 , _init_x = x0 , _init_fx = f x0 , _init_f'x = f'x0 } step_backtracking :: ( Module v ) => Scalar v -> (v -> Scalar v) -> (v -> v) -> Backtracking v -> History cxt (Backtracking v) step_backtracking !tao !f !f' !bt = {-# SCC step_backtracking #-} do let x1 = tao * _bt_x bt return $ bt { _bt_x = x1 , _bt_fx = g x1 , _bt_f'x = g' x1 } where g alpha = f (_init_x bt + alpha *. _init_dir bt) g' alpha = alpha *. f' (_init_x bt + alpha *. _init_dir bt) --------------------------------------- -- stop conditions {-# INLINABLE wolfe #-} wolfe :: Hilbert v => Scalar v -> Scalar v -> StopCondition (Backtracking v) wolfe !c1 !c2 !bt0 !bt1 = {-# SCC wolfe #-} do a <- amijo c1 bt0 bt1 b <- strongCurvature c2 bt0 bt1 return $ a && b {-# INLINABLE amijo #-} amijo :: Hilbert v => Scalar v -> StopCondition (Backtracking v) amijo !c1 _ !bt = {-# SCC amijo #-} return $ _bt_fx bt <= _init_fx bt + c1 * (_bt_x bt) * ((_init_f'x bt) <> (_init_dir bt)) {-# INLINABLE weakCurvature #-} weakCurvature :: Hilbert v => Scalar v -> StopCondition (Backtracking v) weakCurvature !c2 _ !bt = {-# SCC weakCurvature #-} return $ _init_dir bt <> _bt_f'x bt >= c2 * (_init_dir bt <> _init_f'x bt) {-# INLINABLE strongCurvature #-} strongCurvature :: Hilbert v => Scalar v -> StopCondition (Backtracking v) strongCurvature !c2 _ !bt = {-# SCC strongCurvature #-} return $ abs (_init_dir bt <> _bt_f'x bt) <= c2 * abs (_init_dir bt <> _init_f'x bt) -------------------------------------------------------------------------------- -- | The simplest quadratic function {-# INLINEABLE sphere #-} sphere :: Hilbert v => C1 (v -> Scalar v) sphere = unsafeProveC1 f f' -- f'' where f v = v<>v+3 f' v = 2*.v -- f'' _ = 2 -- | -- -- > ackley [0,0] == 0 -- -- ackley :: (IsScalar r, Field r) => SVector 2 r -> r {-# INLINEABLE ackley #-} ackley :: SVector 2 Double -> Double ackley v = -20 * exp (-0.2 * sqrt $ 0.5 * (x*x + y*y)) - exp(0.5*cos(2*pi*x)+0.5*cos(2*pi*y)) + exp 1 + 20 where x=v!0 y=v!1 -- | -- -- > beale [3,0.5] = 0 {-# INLINEABLE beale #-} beale :: SVector 2 Double -> Double beale v = (1.5-x+x*y)**2 + (2.25-x+x*y*y)**2 + (2.625-x+x*y*y*y)**2 where x=v!0 y=v!1 -- | The Rosenbrock function is hard to optimize because it has a narrow quadratically shaped valley. -- -- See <https://en.wikipedia.org/wiki/Rosenbrock_function wikipedia> for more details. -- -- FIXME: -- The derivatives of this function are rather nasty. -- We need to expand "SubHask.Category.Trans.Derivative" to handle these harder cases automatically. {-# INLINEABLE rosenbrock #-} rosenbrock :: (ValidElem v (Scalar v), ExpRing (Scalar v), FiniteModule v) => C1 (v -> Scalar v) rosenbrock = unsafeProveC1 f f' where f v = sum [ 100*(v!(i+1) - (v!i)**2)**2 + (v!i - 1)**2 | i <- [0..dim v-2] ] f' v = imap go v where go i x = if i==dim v-1 then pt2 else if i== 0 then pt1 else pt1+pt2 where pt1 = 400*x*x*x - 400*xp1*x + 2*x -2 pt2 = 200*x - 200*xm1*xm1 xp1 = v!(i+1) xm1 = v!(i-1)
arnabgho/HLearn
src/HLearn/Optimization/Multivariate.hs
bsd-3-clause
18,644
0
19
5,117
4,575
2,449
2,126
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hu-HU"> <title>Front-End Scanner | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/frontendscanner/src/main/javahelp/org/zaproxy/zap/extension/frontendscanner/resources/help_hu_HU/helpset_hu_HU.hs
apache-2.0
978
78
67
159
417
211
206
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE CPP #-} -- Copyright 2008 JP Bernardy -- | Basic types useful everywhere we play with buffers. module Yi.Buffer.Basic where import Data.Binary import Data.Typeable import GHC.Generics (Generic) import Data.Ix import Data.Default import Yi.Utils -- | Direction of movement inside a buffer data Direction = Backward | Forward deriving (Eq, Ord, Typeable, Show, Bounded, Enum, Generic) instance Binary Direction reverseDir :: Direction -> Direction reverseDir Forward = Backward reverseDir Backward = Forward -- | reverse if Backward mayReverse :: Direction -> [a] -> [a] mayReverse Forward = id mayReverse Backward = reverse -- | 'direction' is in the same style of 'maybe' or 'either' functions, -- It takes one argument per direction (backward, then forward) and a -- direction to select the output. directionElim :: Direction -> a -> a -> a directionElim Backward b _ = b directionElim Forward _ f = f -- | A mark in a buffer newtype Mark = Mark {markId::Int} deriving (Eq, Ord, Show, Typeable, Binary) -- | Reference to a buffer. newtype BufferRef = BufferRef Int deriving (Eq, Ord, Typeable, Binary, Num) instance Show BufferRef where show (BufferRef r) = "B#" ++ show r -- | A point in a buffer newtype Point = Point {fromPoint :: Int} -- offset in the buffer (#codepoints, NOT bytes) deriving (Eq, Ord, Enum, Bounded, Typeable, Binary, Ix, Num, Real, Integral) instance Show Point where show (Point p) = show p -- | Size of a buffer region newtype Size = Size {fromSize :: Int} -- size in bytes (#bytes, NOT codepoints) deriving (Show, Eq, Ord, Num, Enum, Real, Integral, Binary) instance SemiNum Point Size where Point p +~ Size s = Point (p + s) Point p -~ Size s = Point (p - s) Point p ~- Point q = Size (abs (p - q)) -- | Window references newtype WindowRef = WindowRef { unWindowRef :: Int } deriving(Eq, Ord, Enum, Show, Typeable, Binary) instance Default WindowRef where def = WindowRef (-1)
siddhanathan/yi
yi-language/src/Yi/Buffer/Basic.hs
gpl-2.0
2,288
0
10
463
596
326
270
47
1
module SDL.Raw.Platform ( -- * Platform Detection getPlatform ) where import Control.Monad.IO.Class import Foreign.C.String foreign import ccall "SDL.h SDL_GetPlatform" getPlatformFFI :: IO CString getPlatform :: MonadIO m => m CString getPlatform = liftIO getPlatformFFI {-# INLINE getPlatform #-}
dalaing/sdl2
src/SDL/Raw/Platform.hs
bsd-3-clause
306
0
6
45
65
38
27
8
1
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} #if __GLASGOW_HASKELL__ >= 707 {-# LANGUAGE RoleAnnotations #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.Internal.Magma -- Copyright : (C) 2012-2015 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable -- ---------------------------------------------------------------------------- module Control.Lens.Internal.Magma ( -- * Magma Magma(..) , runMagma -- * Molten , Molten(..) -- * Mafic , Mafic(..) , runMafic -- * TakingWhile , TakingWhile(..) , runTakingWhile ) where import Control.Applicative import Control.Category import Control.Comonad import Control.Lens.Internal.Bazaar import Control.Lens.Internal.Context import Control.Lens.Internal.Indexed import Data.Foldable import Data.Functor.Apply import Data.Functor.Contravariant import Data.Monoid import Data.Profunctor.Rep import Data.Profunctor.Sieve import Data.Profunctor.Unsafe import Data.Traversable import Prelude hiding ((.),id) ------------------------------------------------------------------------------ -- Magma ------------------------------------------------------------------------------ -- | This provides a way to peek at the internal structure of a -- 'Control.Lens.Traversal.Traversal' or 'Control.Lens.Traversal.IndexedTraversal' data Magma i t b a where MagmaAp :: Magma i (x -> y) b a -> Magma i x b a -> Magma i y b a MagmaPure :: x -> Magma i x b a MagmaFmap :: (x -> y) -> Magma i x b a -> Magma i y b a Magma :: i -> a -> Magma i b b a #if __GLASGOW_HASKELL__ >= 707 -- note the 3rd argument infers as phantom, but that would be unsound type role Magma representational nominal nominal nominal #endif instance Functor (Magma i t b) where fmap f (MagmaAp x y) = MagmaAp (fmap f x) (fmap f y) fmap _ (MagmaPure x) = MagmaPure x fmap f (MagmaFmap xy x) = MagmaFmap xy (fmap f x) fmap f (Magma i a) = Magma i (f a) instance Foldable (Magma i t b) where foldMap f (MagmaAp x y) = foldMap f x `mappend` foldMap f y foldMap _ MagmaPure{} = mempty foldMap f (MagmaFmap _ x) = foldMap f x foldMap f (Magma _ a) = f a instance Traversable (Magma i t b) where traverse f (MagmaAp x y) = MagmaAp <$> traverse f x <*> traverse f y traverse _ (MagmaPure x) = pure (MagmaPure x) traverse f (MagmaFmap xy x) = MagmaFmap xy <$> traverse f x traverse f (Magma i a) = Magma i <$> f a instance (Show i, Show a) => Show (Magma i t b a) where showsPrec d (MagmaAp x y) = showParen (d > 4) $ showsPrec 4 x . showString " <*> " . showsPrec 5 y showsPrec d (MagmaPure _) = showParen (d > 10) $ showString "pure .." showsPrec d (MagmaFmap _ x) = showParen (d > 4) $ showString ".. <$> " . showsPrec 5 x showsPrec d (Magma i a) = showParen (d > 10) $ showString "Magma " . showsPrec 11 i . showChar ' ' . showsPrec 11 a -- | Run a 'Magma' where all the individual leaves have been converted to the -- expected type runMagma :: Magma i t a a -> t runMagma (MagmaAp l r) = runMagma l (runMagma r) runMagma (MagmaFmap f r) = f (runMagma r) runMagma (MagmaPure x) = x runMagma (Magma _ a) = a ------------------------------------------------------------------------------ -- Molten ------------------------------------------------------------------------------ -- | This is a a non-reassociating initially encoded version of 'Bazaar'. newtype Molten i a b t = Molten { runMolten :: Magma i t b a } instance Functor (Molten i a b) where fmap f (Molten xs) = Molten (MagmaFmap f xs) {-# INLINE fmap #-} instance Apply (Molten i a b) where (<.>) = (<*>) {-# INLINE (<.>) #-} instance Applicative (Molten i a b) where pure = Molten #. MagmaPure {-# INLINE pure #-} Molten xs <*> Molten ys = Molten (MagmaAp xs ys) {-# INLINE (<*>) #-} instance Sellable (Indexed i) (Molten i) where sell = Indexed (\i -> Molten #. Magma i) {-# INLINE sell #-} instance Bizarre (Indexed i) (Molten i) where bazaar f (Molten (MagmaAp x y)) = bazaar f (Molten x) <*> bazaar f (Molten y) bazaar f (Molten (MagmaFmap g x)) = g <$> bazaar f (Molten x) bazaar _ (Molten (MagmaPure x)) = pure x bazaar f (Molten (Magma i a)) = indexed f i a instance IndexedFunctor (Molten i) where ifmap f (Molten xs) = Molten (MagmaFmap f xs) {-# INLINE ifmap #-} instance IndexedComonad (Molten i) where iextract (Molten (MagmaAp x y)) = iextract (Molten x) (iextract (Molten y)) iextract (Molten (MagmaFmap f y)) = f (iextract (Molten y)) iextract (Molten (MagmaPure x)) = x iextract (Molten (Magma _ a)) = a iduplicate (Molten (Magma i a)) = Molten #. Magma i <$> Molten (Magma i a) iduplicate (Molten (MagmaPure x)) = pure (pure x) iduplicate (Molten (MagmaFmap f y)) = iextend (fmap f) (Molten y) iduplicate (Molten (MagmaAp x y)) = iextend (<*>) (Molten x) <*> iduplicate (Molten y) iextend k (Molten (Magma i a)) = (k .# Molten) . Magma i <$> Molten (Magma i a) iextend k (Molten (MagmaPure x)) = pure (k (pure x)) iextend k (Molten (MagmaFmap f y)) = iextend (k . fmap f) (Molten y) iextend k (Molten (MagmaAp x y)) = iextend (\x' y' -> k $ x' <*> y') (Molten x) <*> iduplicate (Molten y) instance a ~ b => Comonad (Molten i a b) where extract = iextract {-# INLINE extract #-} extend = iextend {-# INLINE extend #-} duplicate = iduplicate {-# INLINE duplicate #-} ------------------------------------------------------------------------------ -- Mafic ------------------------------------------------------------------------------ -- | This is used to generate an indexed magma from an unindexed source -- -- By constructing it this way we avoid infinite reassociations in sums where possible. data Mafic a b t = Mafic Int (Int -> Magma Int t b a) -- | Generate a 'Magma' using from a prefix sum. runMafic :: Mafic a b t -> Magma Int t b a runMafic (Mafic _ k) = k 0 instance Functor (Mafic a b) where fmap f (Mafic w k) = Mafic w (MagmaFmap f . k) {-# INLINE fmap #-} instance Apply (Mafic a b) where Mafic wf mf <.> ~(Mafic wa ma) = Mafic (wf + wa) $ \o -> MagmaAp (mf o) (ma (o + wf)) {-# INLINE (<.>) #-} instance Applicative (Mafic a b) where pure a = Mafic 0 $ \_ -> MagmaPure a {-# INLINE pure #-} Mafic wf mf <*> ~(Mafic wa ma) = Mafic (wf + wa) $ \o -> MagmaAp (mf o) (ma (o + wf)) {-# INLINE (<*>) #-} instance Sellable (->) Mafic where sell a = Mafic 1 $ \ i -> Magma i a {-# INLINE sell #-} instance Bizarre (Indexed Int) Mafic where bazaar (pafb :: Indexed Int a (f b)) (Mafic _ k) = go (k 0) where go :: Magma Int t b a -> f t go (MagmaAp x y) = go x <*> go y go (MagmaFmap f x) = f <$> go x go (MagmaPure x) = pure x go (Magma i a) = indexed pafb (i :: Int) a {-# INLINE bazaar #-} instance IndexedFunctor Mafic where ifmap f (Mafic w k) = Mafic w (MagmaFmap f . k) {-# INLINE ifmap #-} ------------------------------------------------------------------------------ -- TakingWhile ------------------------------------------------------------------------------ -- | This is used to generate an indexed magma from an unindexed source -- -- By constructing it this way we avoid infinite reassociations where possible. -- -- In @'TakingWhile' p g a b t@, @g@ has a @nominal@ role to avoid exposing an illegal _|_ via 'Contravariant', -- while the remaining arguments are degraded to a @nominal@ role by the invariants of 'Magma' data TakingWhile p (g :: * -> *) a b t = TakingWhile Bool t (Bool -> Magma () t b (Corep p a)) #if __GLASGOW_HASKELL__ >= 707 type role TakingWhile nominal nominal nominal nominal nominal #endif -- | Generate a 'Magma' with leaves only while the predicate holds from left to right. runTakingWhile :: TakingWhile p f a b t -> Magma () t b (Corep p a) runTakingWhile (TakingWhile _ _ k) = k True instance Functor (TakingWhile p f a b) where fmap f (TakingWhile w t k) = let ft = f t in TakingWhile w ft $ \b -> if b then MagmaFmap f (k b) else MagmaPure ft {-# INLINE fmap #-} instance Apply (TakingWhile p f a b) where TakingWhile wf tf mf <.> ~(TakingWhile wa ta ma) = TakingWhile (wf && wa) (tf ta) $ \o -> if o then MagmaAp (mf True) (ma wf) else MagmaPure (tf ta) {-# INLINE (<.>) #-} instance Applicative (TakingWhile p f a b) where pure a = TakingWhile True a $ \_ -> MagmaPure a {-# INLINE pure #-} TakingWhile wf tf mf <*> ~(TakingWhile wa ta ma) = TakingWhile (wf && wa) (tf ta) $ \o -> if o then MagmaAp (mf True) (ma wf) else MagmaPure (tf ta) {-# INLINE (<*>) #-} instance Corepresentable p => Bizarre p (TakingWhile p g) where bazaar (pafb :: p a (f b)) ~(TakingWhile _ _ k) = go (k True) where go :: Magma () t b (Corep p a) -> f t go (MagmaAp x y) = go x <*> go y go (MagmaFmap f x) = f <$> go x go (MagmaPure x) = pure x go (Magma _ wa) = cosieve pafb wa {-# INLINE bazaar #-} -- This constraint is unused intentionally, it protects TakingWhile instance Contravariant f => Contravariant (TakingWhile p f a b) where contramap _ = (<$) (error "contramap: TakingWhile") {-# INLINE contramap #-} instance IndexedFunctor (TakingWhile p f) where ifmap = fmap {-# INLINE ifmap #-}
rpglover64/lens
src/Control/Lens/Internal/Magma.hs
bsd-3-clause
9,589
0
13
1,992
3,322
1,709
1,613
168
1
{-# LANGUAGE UnboxedSums #-} module UbxSumLevPoly where -- this failed thinking that (# Any | True #) :: TYPE (SumRep [LiftedRep, b]) -- But of course that b should be Lifted! -- It was due to silliness in TysWiredIn using the same uniques for different -- things in mk_sum. p = True where (# _x | #) = (# | True #)
ezyang/ghc
testsuite/tests/unboxedsums/UbxSumLevPoly.hs
bsd-3-clause
322
0
7
68
28
19
9
4
1
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances, TypeFamilies, GeneralizedNewtypeDeriving #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module T4809_IdentityT ( evalIdentityT , IdentityT(..) , XML(..) ) where import Control.Applicative (Applicative, Alternative) import Control.Monad (MonadPlus) import Control.Monad.Trans (MonadTrans(lift), MonadIO(liftIO)) import T4809_XMLGenerator (XMLGenT(..), EmbedAsChild(..), Name) import qualified T4809_XMLGenerator as HSX data XML = Element Name [Int] [XML] | CDATA Bool String deriving Show -- * IdentityT Monad Transformer newtype IdentityT m a = IdentityT { runIdentityT :: m a } deriving (Functor, Applicative, Alternative, Monad, MonadIO, MonadPlus) instance MonadTrans IdentityT where lift = IdentityT evalIdentityT :: (Functor m, Monad m) => XMLGenT (IdentityT m) XML -> m XML evalIdentityT = runIdentityT . HSX.unXMLGenT -- * HSX.XMLGenerator for IdentityT instance (Functor m, Monad m) => HSX.XMLGen (IdentityT m) where type XML (IdentityT m) = XML newtype Child (IdentityT m) = IChild { unIChild :: XML } genElement n _attrs children = HSX.XMLGenT $ do children' <- HSX.unXMLGenT (fmap (map unIChild . concat) (sequence children)) return (Element n [] children') instance (Monad m, MonadIO m, Functor m) => EmbedAsChild (IdentityT m) String where asChild s = do liftIO $ putStrLn "EmbedAsChild (IdentityT m) String" XMLGenT . return . (:[]) . IChild . CDATA True $ s
philderbeast/ghcjs
test/ghc/typecheck/T4809_IdentityT.hs
mit
1,601
0
15
353
464
258
206
30
1
module Vectorise.Generic.PADict ( buildPADict ) where import Vectorise.Monad import Vectorise.Builtins import Vectorise.Generic.Description import Vectorise.Generic.PAMethods ( buildPAScAndMethods ) import Vectorise.Utils import BasicTypes import CoreSyn import CoreUtils import CoreUnfold import Module import TyCon import CoAxiom import Type import Id import Var import Name import FastString -- |Build the PA dictionary function for some type and hoist it to top level. -- -- The PA dictionary holds fns that convert values to and from their vectorised representations. -- -- @Recall the definition: -- class PR (PRepr a) => PA a where -- toPRepr :: a -> PRepr a -- fromPRepr :: PRepr a -> a -- toArrPRepr :: PData a -> PData (PRepr a) -- fromArrPRepr :: PData (PRepr a) -> PData a -- toArrPReprs :: PDatas a -> PDatas (PRepr a) -- fromArrPReprs :: PDatas (PRepr a) -> PDatas a -- -- Example: -- df :: forall a. PR (PRepr a) -> PA a -> PA (T a) -- df = /\a. \(c:PR (PRepr a)) (d:PA a). MkPA c ($PR_df a d) ($toPRepr a d) ... -- $dPR_df :: forall a. PA a -> PR (PRepr (T a)) -- $dPR_df = .... -- $toRepr :: forall a. PA a -> T a -> PRepr (T a) -- $toPRepr = ... -- The "..." stuff is filled in by buildPAScAndMethods -- @ -- buildPADict :: TyCon -- ^ tycon of the type being vectorised. -> CoAxiom Unbranched -- ^ Coercion between the type and -- its vectorised representation. -> TyCon -- ^ PData instance tycon -> TyCon -- ^ PDatas instance tycon -> SumRepr -- ^ representation used for the type being vectorised. -> VM Var -- ^ name of the top-level dictionary function. buildPADict vect_tc prepr_ax pdata_tc pdatas_tc repr = polyAbstract tvs $ \args -> -- The args are the dictionaries we lambda abstract over; and they -- are put in the envt, so when we need a (PA a) we can find it in -- the envt; they don't include the silent superclass args yet do { mod <- liftDs getModule ; let dfun_name = mkLocalisedOccName mod mkPADFunOcc vect_tc_name -- The superclass dictionary is a (silent) argument if the tycon is polymorphic... ; let mk_super_ty = do { r <- mkPReprType inst_ty ; pr_cls <- builtin prClass ; return $ mkClassPred pr_cls [r] } ; super_tys <- sequence [mk_super_ty | not (null tvs)] ; super_args <- mapM (newLocalVar (fsLit "pr")) super_tys ; let val_args = super_args ++ args all_args = tvs ++ val_args -- ...it is constant otherwise ; super_consts <- sequence [prDictOfPReprInstTyCon inst_ty prepr_ax [] | null tvs] -- Get ids for each of the methods in the dictionary, including superclass ; paMethodBuilders <- buildPAScAndMethods ; method_ids <- mapM (method val_args dfun_name) paMethodBuilders -- Expression to build the dictionary. ; pa_dc <- builtin paDataCon ; let dict = mkLams all_args (mkConApp pa_dc con_args) con_args = Type inst_ty : map Var super_args -- the superclass dictionary is either ++ super_consts -- lambda-bound or constant ++ map (method_call val_args) method_ids -- Build the type of the dictionary function. ; pa_cls <- builtin paClass ; let dfun_ty = mkForAllTys tvs $ mkFunTys (map varType val_args) (mkClassPred pa_cls [inst_ty]) -- Set the unfolding for the inliner. ; raw_dfun <- newExportedVar dfun_name dfun_ty ; let dfun_unf = mkDFunUnfolding all_args pa_dc con_args dfun = raw_dfun `setIdUnfolding` dfun_unf `setInlinePragma` dfunInlinePragma -- Add the new binding to the top-level environment. ; hoistBinding dfun dict ; return dfun } where tvs = tyConTyVars vect_tc arg_tys = mkTyVarTys tvs inst_ty = mkTyConApp vect_tc arg_tys vect_tc_name = getName vect_tc method args dfun_name (name, build) = localV $ do expr <- build vect_tc prepr_ax pdata_tc pdatas_tc repr let body = mkLams (tvs ++ args) expr raw_var <- newExportedVar (method_name dfun_name name) (exprType body) let var = raw_var `setIdUnfolding` mkInlineUnfolding (Just (length args)) body `setInlinePragma` alwaysInlinePragma hoistBinding var body return var method_call args id = mkApps (Var id) (map Type arg_tys ++ map Var args) method_name dfun_name name = mkVarOcc $ occNameString dfun_name ++ ('$' : name)
urbanslug/ghc
compiler/vectorise/Vectorise/Generic/PADict.hs
bsd-3-clause
4,973
0
19
1,600
819
433
386
72
1
{-# LANGUAGE Arrows #-} {-# OPTIONS -fno-warn-redundant-constraints #-} -- Test for Trac #1662 module Arrow where import Control.Arrow expr' :: Arrow a => a Int Int expr' = error "urk" term :: Arrow a => a () Int term = error "urk" expr1 :: Arrow a => a () Int expr1 = proc () -> do x <- term -< () expr' -< x expr2 :: Arrow a => a () Int expr2 = proc y -> do x <- term -< y expr' -< x
urbanslug/ghc
testsuite/tests/arrows/should_compile/arrowpat.hs
bsd-3-clause
433
2
10
133
166
82
84
16
1
-- | This is a library which colourises Haskell code. -- It currently has six output formats: -- -- * ANSI terminal codes -- -- * LaTeX macros -- -- * HTML 3.2 with font tags -- -- * HTML 4.01 with external CSS. -- -- * XHTML 1.0 with internal CSS. -- -- * mIRC chat client colour codes. -- module Language.Haskell.HsColour (Output(..), ColourPrefs(..), hscolour) where import Language.Haskell.HsColour.Colourise (ColourPrefs(..)) import qualified Language.Haskell.HsColour.TTY as TTY import qualified Language.Haskell.HsColour.HTML as HTML import qualified Language.Haskell.HsColour.CSS as CSS import qualified Language.Haskell.HsColour.ACSS as ACSS import qualified Language.Haskell.HsColour.InlineCSS as ICSS import qualified Language.Haskell.HsColour.LaTeX as LaTeX import qualified Language.Haskell.HsColour.MIRC as MIRC import Data.List(mapAccumL, isPrefixOf) import Data.Maybe import Language.Haskell.HsColour.Output --import Debug.Trace -- | Colourise Haskell source code with the given output format. hscolour :: Output -- ^ Output format. -> ColourPrefs -- ^ Colour preferences (for formats that support them). -> Bool -- ^ Whether to include anchors. -> Bool -- ^ Whether output document is partial or complete. -> String -- ^ Title for output. -> Bool -- ^ Whether input document is literate haskell or not -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour output pref anchor partial title False = (if partial then id else top'n'tail output title) . hscolour' output pref anchor hscolour output pref anchor partial title True = (if partial then id else top'n'tail output title) . concatMap chunk . joinL . classify . inlines where chunk (Code c) = hscolour' output pref anchor c chunk (Lit c) = c -- | The actual colourising worker, despatched on the chosen output format. hscolour' :: Output -- ^ Output format. -> ColourPrefs -- ^ Colour preferences (for formats that support them) -> Bool -- ^ Whether to include anchors. -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour' TTY pref _ = TTY.hscolour pref hscolour' (TTYg tt) pref _ = TTY.hscolourG tt pref hscolour' MIRC pref _ = MIRC.hscolour pref hscolour' LaTeX pref _ = LaTeX.hscolour pref hscolour' HTML pref anchor = HTML.hscolour pref anchor hscolour' CSS _ anchor = CSS.hscolour anchor hscolour' ICSS pref anchor = ICSS.hscolour pref anchor hscolour' ACSS _ anchor = ACSS.hscolour anchor -- | Choose the right headers\/footers, depending on the output format. top'n'tail :: Output -- ^ Output format -> String -- ^ Title for output -> (String->String) -- ^ Output transformer top'n'tail TTY _ = id top'n'tail (TTYg _) _ = id top'n'tail MIRC _ = id top'n'tail LaTeX title = LaTeX.top'n'tail title top'n'tail HTML title = HTML.top'n'tail title top'n'tail CSS title = CSS.top'n'tail title top'n'tail ICSS title = ICSS.top'n'tail title top'n'tail ACSS title = CSS.top'n'tail title -- | Separating literate files into code\/comment chunks. data Lit = Code {unL :: String} | Lit {unL :: String} deriving (Show) -- Re-implementation of 'lines', for better efficiency (but decreased laziness). -- Also, importantly, accepts non-standard DOS and Mac line ending characters. -- And retains the trailing '\n' character in each resultant string. inlines :: String -> [String] inlines s = lines' s id where lines' [] acc = [acc []] lines' ('\^M':'\n':s) acc = acc ['\n'] : lines' s id -- DOS --lines' ('\^M':s) acc = acc ['\n'] : lines' s id -- MacOS lines' ('\n':s) acc = acc ['\n'] : lines' s id -- Unix lines' (c:s) acc = lines' s (acc . (c:)) -- | The code for classify is largely stolen from Language.Preprocessor.Unlit. classify :: [String] -> [Lit] classify [] = [] classify (x:xs) | "\\begin{code}"`isPrefixOf`x = Lit x: allProg xs where allProg [] = [] -- Should give an error message, -- but I have no good position information. allProg (x:xs) | "\\end{code}"`isPrefixOf`x = Lit x: classify xs allProg (x:xs) = Code x: allProg xs classify (('>':x):xs) = Code ('>':x) : classify xs classify (x:xs) = Lit x: classify xs -- | Join up chunks of code\/comment that are next to each other. joinL :: [Lit] -> [Lit] joinL [] = [] joinL (Code c:Code c2:xs) = joinL (Code (c++c2):xs) joinL (Lit c :Lit c2 :xs) = joinL (Lit (c++c2):xs) joinL (any:xs) = any: joinL xs
kyoungrok0517/linguist
samples/Haskell/HsColour.hs
mit
4,949
0
11
1,333
1,173
644
529
75
4
-- Hugs failed this test Jan06 module Mod172 where import Mod172_B (f,g)
urbanslug/ghc
testsuite/tests/module/mod172.hs
bsd-3-clause
75
0
5
14
16
11
5
2
0
module Ghci025C (f, g, h) where import Ghci025D g x = f x + 1 h x = x `div` 2 data C = C {x :: Int}
urbanslug/ghc
testsuite/tests/ghci/scripts/Ghci025C.hs
bsd-3-clause
104
0
8
32
62
36
26
5
1
#!/usr/bin/env stack -- stack --install-ghc runghc --package turtle {-# LANGUAGE OverloadedStrings #-} import Turtle main = stdout $ input "README.md"
JoshuaGross/haskell-learning-log
Code/turtle/input.hs
mit
164
0
6
33
19
11
8
3
1
----------------------------------------------------------------------------- -- | -- Module : TestQueue -- Copyright : (c) Phil Hargett 2014 -- License : MIT (see LICENSE file) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (requires STM) -- -- (..... module description .....) -- ----------------------------------------------------------------------------- module TestQueue ( tests ) where -- local imports import qualified Distributed.Data.Queue as Q import Distributed.Data.Container import TestHelpers -- external imports import Control.Consensus.Raft import Data.Serialize import Network.Endpoints import Network.Transport.Memory import Prelude hiding (log) import Test.Framework import Test.HUnit import Test.Framework.Providers.HUnit -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- tests :: IO [Test.Framework.Test] tests = return [ testCase "queue-1server" $ test1Server, testCase "queue-3server" $ test3Servers -- testCase "queue-3server" $ troubleshoot $ test3Servers ] test1Server :: Assertion test1Server = timeBound (2 * 1000 * 1000) $ do let name = servers !! 0 cfg = newTestConfiguration [name] withTransport newMemoryTransport $ \transport -> withEndpoint transport name $ \endpoint -> do withQueueServer endpoint cfg name $ \vQueue -> causally $ do checkSize "Empty queue should have size 0" 0 vQueue Q.enqueue (0 :: Int) vQueue checkSize "Queue size should be 1" 1 vQueue Q.enqueue 1 vQueue checkSize "Queue size should be 2" 2 vQueue Q.enqueue 2 vQueue checkSize "Queue size should be 3" 3 vQueue value1 <- Q.dequeue vQueue checkSize "Queue size should again be 2" 2 vQueue liftIO $ assertEqual "Initial value should be 0" 0 value1 value2 <- Q.dequeue vQueue checkSize "Queue size should again be 1" 1 vQueue liftIO $ assertEqual "Second value should be 1" 1 value2 value3 <- Q.dequeue vQueue checkSize "Queue size should again be 0" 0 vQueue liftIO $ assertEqual "Third value should be 2" 2 value3 test3Servers :: Assertion test3Servers = with3QueueServers $ \vQueues -> timeBound (30 * 1000000) $ causally $ do let [vQueue1,vQueue2,vQueue3] = vQueues checkSize "Empty queue should have size 0" 0 vQueue1 Q.enqueue (0 :: Int) vQueue1 checkSize "Queue size should be 1" 1 vQueue1 Q.enqueue 1 vQueue1 checkSize "Queue size should be 2" 2 vQueue3 Q.enqueue 2 vQueue2 checkSize "Queue size should be 3" 3 vQueue2 value1 <- Q.dequeue vQueue1 checkSize "Queue size should again be 2" 2 vQueue2 liftIO $ assertEqual "Initial value should be 0" 0 value1 value2 <- Q.dequeue vQueue3 checkSize "Queue size should again be 1" 1 vQueue2 liftIO $ assertEqual "Second value should be 1" 1 value2 value3 <- Q.dequeue vQueue1 checkSize "Queue size should again be 0" 0 vQueue2 liftIO $ assertEqual "Third value should be 2" 2 value3 -------------------------------------------------------------------------------- -- Helpers -------------------------------------------------------------------------------- withQueueServer :: (Serialize v) => Endpoint -> RaftConfiguration -> Name -> (Q.Queue v -> IO ()) -> IO () withQueueServer endpoint cfg name fn = do initialLog <- Q.mkQueueLog initialState <- Q.empty name Q.withQueue endpoint cfg name initialLog initialState fn with3QueueServers :: (Serialize v) => ([Q.Queue v ] -> IO ()) -> IO () with3QueueServers fn = do let names = take 3 servers [name1,name2,name3] = names cfg = newTestConfiguration names withTransport newMemoryTransport $ \transport -> withEndpoint transport name1 $ \endpoint1 -> do withQueueServer endpoint1 cfg name1 $ \vQueue1 -> do withEndpoint transport name2 $ \endpoint2 -> do withQueueServer endpoint2 cfg name2 $ \vQueue2 -> do withEndpoint transport name3 $ \endpoint3 -> do withQueueServer endpoint3 cfg name3 $ \vQueue3 -> do fn [vQueue1,vQueue2,vQueue3] checkSize :: (Serialize v) => String -> Int -> Q.Queue v -> Causal () checkSize msg esz q = do sz <- Q.size q liftIO $ assertEqual msg esz sz
hargettp/distributed-containers
test/TestQueue.hs
mit
4,727
0
34
1,235
1,068
524
544
82
1
module ListyInstances where import Data.Monoid import Listy instance Monoid (Listy a) where mempty = Listy [] mappend (Listy l) (Listy l') = Listy $ mappend l l'
diminishedprime/.org
reading-list/haskell_programming_from_first_principles/orphan-instance/ListyInstances.hs
mit
167
0
8
32
67
35
32
6
0
import Data.List import Data.List.Extra import Data.Maybe import qualified Data.Map as Map parseLine :: String -> [Int] parseLine s = let [name, _, _, speed, "km/s", _, endurance, "seconds,", _, _, _, _, _, rest, "seconds."] = words s in concat $ repeat $ replicate (read endurance) (read speed) ++ replicate (read rest) 0 allDistances :: [String] -> [[Int]] allDistances = map parseLine totalDistance :: [Int] -> [Int] totalDistance = tail . scanl (+) 0 leadingDistance :: [[Int]] -> [Int] leadingDistance = map maximum . transpose currentScore :: [Int] -> [Int] -> [Int] currentScore = zipWith (\lead x -> if lead == x then 1 else 0) time = 2503 furthest :: [[Int]] -> Int furthest speeds = maximum $ map (sum . take time) scores where leader = leadingDistance totals totals = map totalDistance speeds scores = map (currentScore leader) totals solve :: String -> Int solve = furthest . allDistances . lines answer f = interact $ (++"\n") . show . f main = answer solve
msullivan/advent-of-code
2015/A14b.hs
mit
1,018
0
11
214
421
234
187
28
2
module Problem8 ( removeDuplicates ) where removeDuplicates :: (Eq a) => [a] -> [a] removeDuplicates [] = [] removeDuplicates [x] = [x] removeDuplicates (x:xs) = if x == head xs then removeDuplicates xs else x : removeDuplicates xs
chanind/haskell-99-problems
Problem8.hs
mit
232
0
7
38
99
54
45
5
2
lastPart :: Int -> [a] -> [a] lastPart _ [] = [] lastPart _ [x] = [x] lastPart x l@(h:t) | x > 0 = lastPart nx t | otherwise = l where nx = x - 1 firstPart :: Int -> [a] -> [a] firstPart _ [] = [] firstPart _ [x] = [x] firstPart x l@(h:t) | x > 0 = h:(firstPart nx t) | otherwise = [] where nx = x - 1 {- Rotate a list N places to the left. -} rotateList :: Int -> [a] -> [a] rotateList _ [] = [] rotateList 0 l = l rotateList x l | x > 0 = lastPart x l ++ firstPart x l | otherwise = lastPart nx l ++ firstPart nx l where nx = length l - abs x
andrewaguiar/s99-haskell
p19.hs
mit
660
0
8
251
336
170
166
18
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( getApplicationDev , appMain , develMain , makeFoundation -- * for DevelMain , getApplicationRepl , shutdownApp -- * for GHCI , handler , db ) where import Control.Monad.Logger (liftLoc, runLoggingT) import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr, pgPoolSize, runSqlPool) import Import import Language.Haskell.TH.Syntax (qLocation) import Network.Wai.Handler.Warp (Settings, defaultSettings, defaultShouldDisplayException, runSettings, setHost, setOnException, setPort, getPort) import Network.Wai.Middleware.RequestLogger (Destination (Logger), IPAddrSource (..), OutputFormat (..), destination, mkRequestLogger, outputFormat) import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet, toLogStr) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Common import Handler.Home import Handler.Readable import Handler.Record import Handler.Entry -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- | This function allocates resources (such as a database connection pool), -- performs initialization and return a foundation datatype value. This is also -- the place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeFoundation :: AppSettings -> IO App makeFoundation appSettings = do -- Some basic initializations: HTTP connection manager, logger, and static -- subsite. appHttpManager <- newManager appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger appStatic <- (if appMutableStatic appSettings then staticDevel else static) (appStaticDir appSettings) -- We need a log function to create a connection pool. We need a connection -- pool to create our foundation. And we need our foundation to get a -- logging function. To get out of this loop, we initially create a -- temporary foundation without a real connection pool, get a log function -- from there, and then create the real foundation. let mkFoundation appConnPool = App {..} tempFoundation = mkFoundation $ error "connPool forced in tempFoundation" logFunc = messageLoggerSource tempFoundation appLogger -- Create the database connection pool pool <- flip runLoggingT logFunc $ createPostgresqlPool (pgConnStr $ appDatabaseConf appSettings) (pgPoolSize $ appDatabaseConf appSettings) -- Perform database migration using our application's logging settings. runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc -- Return the foundation return $ mkFoundation pool -- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and -- applyng some additional middlewares. makeApplication :: App -> IO Application makeApplication foundation = do logWare <- mkRequestLogger def { outputFormat = if appDetailedRequestLogging $ appSettings foundation then Detailed True else Apache (if appIpFromHeader $ appSettings foundation then FromFallback else FromSocket) , destination = Logger $ loggerSet $ appLogger foundation } -- Create the WAI application and apply middlewares appPlain <- toWaiAppPlain foundation return $ logWare $ defaultMiddlewaresNoLogging appPlain -- | Warp settings for the given foundation value. warpSettings :: App -> Settings warpSettings foundation = setPort (appPort $ appSettings foundation) $ setHost (appHost $ appSettings foundation) $ setOnException (\_req e -> when (defaultShouldDisplayException e) $ messageLoggerSource foundation (appLogger foundation) $(qLocation >>= liftLoc) "yesod" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) defaultSettings -- | For yesod devel, return the Warp settings and WAI Application. getApplicationDev :: IO (Settings, Application) getApplicationDev = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app <- makeApplication foundation return (wsettings, app) getAppSettings :: IO AppSettings getAppSettings = loadAppSettings [configSettingsYml] [] useEnv -- | main function for use by yesod devel develMain :: IO () develMain = develMainHelper getApplicationDev -- | The @main@ function for an executable running this site. appMain :: IO () appMain = do -- Get the settings from all relevant sources settings <- loadAppSettingsArgs -- fall back to compile-time values, set to [] to require values at runtime [configSettingsYmlValue] -- allow environment variables to override useEnv -- Generate the foundation from the settings foundation <- makeFoundation settings -- Generate a WAI Application from the foundation app <- makeApplication foundation -- Run the application with Warp runSettings (warpSettings foundation) app -------------------------------------------------------------- -- Functions for DevelMain.hs (a way to run the app from GHCi) -------------------------------------------------------------- getApplicationRepl :: IO (Int, App, Application) getApplicationRepl = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app1 <- makeApplication foundation return (getPort wsettings, foundation, app1) shutdownApp :: App -> IO () shutdownApp _ = return () --------------------------------------------- -- Functions for use in development with GHCi --------------------------------------------- -- | Run a handler handler :: Handler a -> IO a handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h -- | Run DB queries db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a db = handler . runDB
darthdeus/reedink
Application.hs
mit
6,680
0
16
1,721
1,024
548
476
-1
-1
{-# LANGUAGE TypeFamilies, ScopedTypeVariables #-} import Data.Acid import Data.Acid.Centered import Control.Monad (when) import Control.Concurrent (threadDelay) import System.Exit (exitSuccess, exitFailure) import System.Directory (doesDirectoryExist, removeDirectoryRecursive) import Control.Exception (catch, SomeException) -- state structures import IntCommon -- helpers delaySec :: Int -> IO () delaySec n = threadDelay $ n*1000*1000 cleanup :: FilePath -> IO () cleanup path = do sp <- doesDirectoryExist path when sp $ removeDirectoryRecursive path -- actual test slave :: IO () slave = do acid <- enslaveStateFrom "state/SyncTimeout/s1" "localhost" 3333 (IntState 0) delaySec 11 -- SyncTimeout happens at 10 seconds closeAcidState acid main :: IO () main = do cleanup "state/SyncTimeout" catch slave $ \(e :: SomeException) -> if show e == "Data.Acid.Centered.Slave: Took too long to sync. Timeout." then exitSuccess else exitFailure
sdx23/acid-state-dist
test/SyncTimeout.hs
mit
1,014
0
11
196
265
138
127
27
2
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} module Init ( (@/=), (@==), (==@) , assertNotEqual , assertNotEmpty , assertEmpty , isTravis , BackendMonad , runConn , MonadIO , persistSettings , MkPersistSettings (..) #ifdef WITH_NOSQL , dbName , db' , setup , mkPersistSettings , Action , Context #else , db , sqlite_database #endif , BackendKey(..) , generateKey -- re-exports , module Database.Persist , module Test.Hspec , module Test.HUnit , liftIO , mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase , Int32, Int64 , Text , module Control.Monad.Trans.Reader , module Control.Monad #ifndef WITH_NOSQL , module Database.Persist.Sql #else , PersistFieldSql(..) #endif ) where -- re-exports import Control.Monad.Trans.Reader import Test.Hspec import Database.Persist.TH (mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase, MkPersistSettings(..)) -- testing import Test.HUnit ((@?=),(@=?), Assertion, assertFailure, assertBool) import Test.QuickCheck import Database.Persist import Database.Persist.TH () import Data.Text (Text, unpack) import System.Environment (getEnvironment) import qualified Data.ByteString as BS #ifdef WITH_NOSQL import Language.Haskell.TH.Syntax (Type(..)) import Database.Persist.TH (mkPersistSettings) import Database.Persist.Sql (PersistFieldSql(..)) import Control.Monad (void, replicateM, liftM) # ifdef WITH_MONGODB import qualified Database.MongoDB as MongoDB import Database.Persist.MongoDB (Action, withMongoPool, runMongoDBPool, defaultMongoConf, applyDockerEnv, BackendKey(..)) # endif # ifdef WITH_ZOOKEEPER import qualified Database.Zookeeper as Z import Database.Persist.Zookeeper (Action, withZookeeperPool, runZookeeperPool, ZookeeperConf(..), defaultZookeeperConf, BackendKey(..), deleteRecursive) import Data.IORef (newIORef, IORef, writeIORef, readIORef) import System.IO.Unsafe (unsafePerformIO) import qualified Data.Text as T # endif #else import Control.Monad (liftM) import Database.Persist.Sql import Control.Monad.Trans.Resource (ResourceT, runResourceT) import Control.Monad.Logger import System.Log.FastLogger (fromLogStr) # ifdef WITH_POSTGRESQL import Control.Applicative ((<$>)) import Database.Persist.Postgresql import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) # else # ifndef WITH_MYSQL import Database.Persist.Sqlite # endif # endif # ifdef WITH_MYSQL import Database.Persist.MySQL # endif import Data.IORef (newIORef, IORef, writeIORef, readIORef) import System.IO.Unsafe (unsafePerformIO) #endif import Control.Monad (unless, (>=>)) import Control.Monad.Trans.Control (MonadBaseControl) -- Data types import Data.Int (Int32, Int64) import Control.Monad.IO.Class #ifdef WITH_MONGODB setup :: Action IO () setup = setupMongo type Context = MongoDB.MongoContext #endif #ifdef WITH_ZOOKEEPER setup :: Action IO () setup = setupZookeeper type Context = Z.Zookeeper #endif (@/=), (@==), (==@) :: (Eq a, Show a, MonadIO m) => a -> a -> m () infix 1 @/= --, /=@ actual @/= expected = liftIO $ assertNotEqual "" expected actual infix 1 @==, ==@ expected @== actual = liftIO $ expected @?= actual expected ==@ actual = liftIO $ expected @=? actual {- expected /=@ actual = liftIO $ assertNotEqual "" expected actual -} assertNotEqual :: (Eq a, Show a) => String -> a -> a -> Assertion assertNotEqual preface expected actual = unless (actual /= expected) (assertFailure msg) where msg = (if null preface then "" else preface ++ "\n") ++ "expected: " ++ show expected ++ "\n to not equal: " ++ show actual assertEmpty :: (Monad m, MonadIO m) => [a] -> m () assertEmpty xs = liftIO $ assertBool "" (null xs) assertNotEmpty :: (Monad m, MonadIO m) => [a] -> m () assertNotEmpty xs = liftIO $ assertBool "" (not (null xs)) isTravis :: IO Bool isTravis = do env <- liftIO getEnvironment return $ case lookup "TRAVIS" env of Just "true" -> True _ -> False #ifdef WITH_POSTGRESQL dockerPg :: IO (Maybe BS.ByteString) dockerPg = do env <- liftIO getEnvironment return $ case lookup "POSTGRES_NAME" env of Just _name -> Just "postgres" -- /persistent/postgres _ -> Nothing #endif #ifdef WITH_NOSQL persistSettings :: MkPersistSettings persistSettings = (mkPersistSettings $ ConT ''Context) { mpsGeneric = True } dbName :: Text dbName = "persistent" type BackendMonad = Context #ifdef WITH_MONGODB runConn :: (MonadIO m, MonadBaseControl IO m) => Action m backend -> m () runConn f = do conf <- liftIO $ applyDockerEnv $ defaultMongoConf dbName -- { mgRsPrimary = Just "replicaset" } void $ withMongoPool conf $ runMongoDBPool MongoDB.master f setupMongo :: Action IO () setupMongo = void $ MongoDB.dropDatabase dbName #endif #ifdef WITH_ZOOKEEPER runConn :: (MonadIO m, MonadBaseControl IO m) => Action m backend -> m () runConn f = do let conf = defaultZookeeperConf {zCoord = "localhost:2181/" ++ T.unpack dbName} void $ withZookeeperPool conf $ runZookeeperPool f setupZookeeper :: Action IO () setupZookeeper = do liftIO $ Z.setDebugLevel Z.ZLogError deleteRecursive "/" #endif db' :: Action IO () -> Action IO () -> Assertion db' actions cleanDB = do r <- runConn (actions >> cleanDB) return r instance Arbitrary PersistValue where arbitrary = PersistObjectId `fmap` BS.pack `fmap` replicateM 12 arbitrary #else persistSettings :: MkPersistSettings persistSettings = sqlSettings { mpsGeneric = True } type BackendMonad = SqlBackend sqlite_database :: Text sqlite_database = "test/testdb.sqlite3" -- sqlite_database = ":memory:" runConn :: (MonadIO m, MonadBaseControl IO m) => SqlPersistT (LoggingT m) t -> m () #ifdef DEBUG runConn f = flip runLoggingT (\_ _ _ s -> print $ fromLogStr s) $ do #else runConn f = flip runLoggingT (\_ _ _ s -> return ()) $ do #endif # ifdef WITH_POSTGRESQL travis <- liftIO isTravis _ <- if travis then withPostgresqlPool "host=localhost port=5432 user=postgres dbname=persistent" 1 $ runSqlPool f else do host <- fromMaybe "localhost" <$> liftIO dockerPg withPostgresqlPool ("host=" <> host <> " port=5432 user=postgres dbname=test") 1 $ runSqlPool f # else # ifdef WITH_MYSQL travis <- liftIO isTravis _ <- if not travis then withMySQLPool defaultConnectInfo { connectHost = "localhost" , connectUser = "test" , connectPassword = "test" , connectDatabase = "test" } 1 $ runSqlPool f else withMySQLPool defaultConnectInfo { connectHost = "localhost" , connectUser = "travis" , connectPassword = "" , connectDatabase = "persistent" } 1 $ runSqlPool f # else _<-withSqlitePool sqlite_database 1 $ runSqlPool f # endif # endif return () db :: SqlPersistT (LoggingT (ResourceT IO)) () -> Assertion db actions = do runResourceT $ runConn $ actions >> transactionUndo #if !MIN_VERSION_random(1,0,1) instance Random Int32 where random g = let ((i::Int), g') = random g in (fromInteger $ toInteger i, g') randomR (lo, hi) g = let ((i::Int), g') = randomR (fromInteger $ toInteger lo, fromInteger $ toInteger hi) g in (fromInteger $ toInteger i, g') instance Random Int64 where random g = let ((i0::Int32), g0) = random g ((i1::Int32), g1) = random g0 in (fromInteger (toInteger i0) + fromInteger (toInteger i1) * 2 ^ (32::Int), g1) randomR (lo, hi) g = -- TODO : generate on the whole range, and not only on a part of it let ((i::Int), g') = randomR (fromInteger $ toInteger lo, fromInteger $ toInteger hi) g in (fromInteger $ toInteger i, g') #endif instance Arbitrary PersistValue where arbitrary = PersistInt64 `fmap` choose (0, maxBound) #endif instance PersistStore backend => Arbitrary (BackendKey backend) where arbitrary = (errorLeft . fromPersistValue) `fmap` arbitrary where errorLeft x = case x of Left e -> error $ unpack e Right r -> r #ifdef WITH_NOSQL #ifdef WITH_MONGODB generateKey :: IO (BackendKey Context) generateKey = MongoKey `liftM` MongoDB.genObjectId #endif #ifdef WITH_ZOOKEEPER keyCounter :: IORef Int64 keyCounter = unsafePerformIO $ newIORef 1 {-# NOINLINE keyCounter #-} generateKey :: IO (BackendKey Context) generateKey = do i <- readIORef keyCounter writeIORef keyCounter (i + 1) return $ ZooKey $ T.pack $ show i #endif #else keyCounter :: IORef Int64 keyCounter = unsafePerformIO $ newIORef 1 {-# NOINLINE keyCounter #-} generateKey :: IO (BackendKey SqlBackend) generateKey = do i <- readIORef keyCounter writeIORef keyCounter (i + 1) return $ SqlBackendKey $ i #endif
greydot/persistent
persistent-test/Init.hs
mit
9,069
56
14
1,865
2,196
1,246
950
116
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} import Hate import Hate.Graphics import Vec2Lens (x,y) import Control.Applicative import Control.Lens import System.Random -- sample 4 data Sehe = Sehe { _pos :: Vec2, _vel :: Vec2 } makeLenses ''Sehe data SampleState = SampleState { _seheSprite :: Sprite, _sehes :: [Sehe] } makeLenses ''SampleState generateSehes :: IO [Sehe] generateSehes = replicateM 100 generateSehe generateSehe :: IO Sehe generateSehe = do px <- getStdRandom $ randomR (0,300) py <- getStdRandom $ randomR (0,300) vx <- getStdRandom $ randomR (-5, 5) vy <- getStdRandom $ randomR (-5, 5) return $ Sehe (Vec2 px py) (Vec2 vx vy) sampleLoad :: LoadFn SampleState sampleLoad = SampleState <$> loadSprite "samples/image.png" <*> generateSehes sampleDraw :: DrawFn SampleState sampleDraw s = map (\(Sehe p v) -> translate p $ sprite TopLeft (s ^. seheSprite)) $ s ^. sehes moveSehe :: Sehe -> Sehe moveSehe = updatePos . updateVel where updateVel :: Sehe -> Sehe updateVel s = s & (if bounceX then vel . x %~ negate else id) & (if bounceY then vel . y %~ negate else id) where bounceX = outOfBounds (s ^. pos . x) (0, 1024 - 128) bounceY = outOfBounds (s ^. pos . y) (0, 786 - 128) outOfBounds v (lo, hi) = v < lo || v > hi updatePos :: Sehe -> Sehe updatePos (Sehe p v) = Sehe (p + v) v sampleUpdate :: UpdateFn SampleState sampleUpdate _ = sehes . traverse %= moveSehe config :: Config config = Config { windowTitle = "Sample - Sprite" , windowSize = (1024, 768) } main :: IO () main = runApp config sampleLoad sampleUpdate sampleDraw
maque/Hate
samples/sample_sprite.hs
mit
1,876
6
13
572
537
299
238
-1
-1
import System.Environment bmiTell :: (RealFloat a) => a -> a -> String bmiTell weight height | bmi <= 18.5 = "You're underweight, you emo, you!" | bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!" | bmi <= 30.0 = "You're fat! Lose some weight, fatty!" | otherwise = "You're a whale, congratulations!" where bmi = weight / height ^ 2 main = do [weight,height] <- getArgs putStrLn (bmiTell (read weight :: Float) (read height :: Float))
dmitrinesterenko/haskell_io_examples
bmiCalc.hs
mit
503
3
11
130
147
74
73
11
1
-- Write a function that takes a list and returns the same list in reverse module Main (reverseList) where aux [] acc = acc aux (h:t) acc = aux t (h:acc) reverseList xs = aux xs []
ryanplusplus/seven-languages-in-seven-weeks
haskell/day1/reverse_list.hs
mit
189
0
7
45
66
35
31
4
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html module Stratosphere.ResourceProperties.ElasticLoadBalancingLoadBalancerPolicies where import Stratosphere.ResourceImports -- | Full data type definition for ElasticLoadBalancingLoadBalancerPolicies. -- See 'elasticLoadBalancingLoadBalancerPolicies' for a more convenient -- constructor. data ElasticLoadBalancingLoadBalancerPolicies = ElasticLoadBalancingLoadBalancerPolicies { _elasticLoadBalancingLoadBalancerPoliciesAttributes :: [Object] , _elasticLoadBalancingLoadBalancerPoliciesInstancePorts :: Maybe (ValList Text) , _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts :: Maybe (ValList Text) , _elasticLoadBalancingLoadBalancerPoliciesPolicyName :: Val Text , _elasticLoadBalancingLoadBalancerPoliciesPolicyType :: Val Text } deriving (Show, Eq) instance ToJSON ElasticLoadBalancingLoadBalancerPolicies where toJSON ElasticLoadBalancingLoadBalancerPolicies{..} = object $ catMaybes [ (Just . ("Attributes",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesAttributes , fmap (("InstancePorts",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesInstancePorts , fmap (("LoadBalancerPorts",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts , (Just . ("PolicyName",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesPolicyName , (Just . ("PolicyType",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesPolicyType ] -- | Constructor for 'ElasticLoadBalancingLoadBalancerPolicies' containing -- required fields as arguments. elasticLoadBalancingLoadBalancerPolicies :: [Object] -- ^ 'elblbpAttributes' -> Val Text -- ^ 'elblbpPolicyName' -> Val Text -- ^ 'elblbpPolicyType' -> ElasticLoadBalancingLoadBalancerPolicies elasticLoadBalancingLoadBalancerPolicies attributesarg policyNamearg policyTypearg = ElasticLoadBalancingLoadBalancerPolicies { _elasticLoadBalancingLoadBalancerPoliciesAttributes = attributesarg , _elasticLoadBalancingLoadBalancerPoliciesInstancePorts = Nothing , _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts = Nothing , _elasticLoadBalancingLoadBalancerPoliciesPolicyName = policyNamearg , _elasticLoadBalancingLoadBalancerPoliciesPolicyType = policyTypearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-attributes elblbpAttributes :: Lens' ElasticLoadBalancingLoadBalancerPolicies [Object] elblbpAttributes = lens _elasticLoadBalancingLoadBalancerPoliciesAttributes (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesAttributes = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-instanceports elblbpInstancePorts :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Maybe (ValList Text)) elblbpInstancePorts = lens _elasticLoadBalancingLoadBalancerPoliciesInstancePorts (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesInstancePorts = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-loadbalancerports elblbpLoadBalancerPorts :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Maybe (ValList Text)) elblbpLoadBalancerPorts = lens _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policyname elblbpPolicyName :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Val Text) elblbpPolicyName = lens _elasticLoadBalancingLoadBalancerPoliciesPolicyName (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesPolicyName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policytype elblbpPolicyType :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Val Text) elblbpPolicyType = lens _elasticLoadBalancingLoadBalancerPoliciesPolicyType (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesPolicyType = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/ElasticLoadBalancingLoadBalancerPolicies.hs
mit
4,306
0
13
370
536
306
230
45
1
module Book ( Book, load, compile ) where import Control.Applicative import Control.Arrow import Control.Dangerous hiding ( Exit, Warning, execute ) import Control.Monad import Control.Monad.Trans import Data.List import Data.Focus import Data.Maybe import Data.Scope import System.FilePath import System.FilePath.Utils import Text.Printf import Target hiding ( load ) import qualified Path import qualified Target import qualified Target.Config as Config import qualified Section import Options data Book = Book { _title :: String , _scope :: Scope , _root :: Section.Section , _build :: FilePath , _targets :: [Target] } -- | Loading load :: Options -> DangerousT IO Book load opts = do -- Canonicalize the root, in case we have a weird relative path start <- liftIO $ canonicalizeHere $ optRoot opts -- Detect the top if they are currently within the book let dirs = map ($ opts) [optSourceDir, optTargetDir, optBuildDir] top <- if optDetect opts then liftIO (start `ancestorWith` dirs) >>= maybe (throw $ CantDetect start dirs) return else return start -- Ensure that the other directories exist let ensure dir err = let path = top </> dir opts in do there <- liftIO $ exists path unless there $ throw (err path) return path srcDir <- ensure optSourceDir NoSource buildDir <- ensure optBuildDir NoBuild targetDir <- ensure optTargetDir NoTarget -- Load the data let title = Path.title $ takeFileName top let scope = getScope start srcDir opts root <- liftIO $ Section.load srcDir "" scope -- Load the targets conf <- Config.setValue "book-title" title <$> Config.load targetDir let conf' = if optDebug opts then Config.setDebug conf else conf -- Filter the targets included by '-t' options let inTargets path = case optTargets opts of [] -> True xs -> (dropExtension . takeFileName) path `elem` xs let included path = not (Config.isSpecial path) && inTargets path paths <- filter included <$> liftIO (ls targetDir) targets <- mapM (Target.load conf') paths -- Build the book return Book{ _title = title , _scope = scope , _root = root , _build = buildDir , _targets = targets } getScope :: FilePath -> FilePath -> Options -> Scope getScope start src opts | optDetect opts = use $ let path = start `from` src path' = if path == start then "" else path parts = splitPath path' locations = mapMaybe fromString parts location = foldr focus unfocused locations in if null path' then unfocused else location | otherwise = use unfocused where use = fromTuple . (get optStart &&& get optEnd) get = flip fromMaybe . ($ opts) -- | Writing compile :: Book -> IO () compile book = mapM_ (execute book) (_targets book) where execute :: Book -> Target -> IO () execute book target = do let d = dest book target let t = text book target putStrLn $ statusMsg d target when (debug target) $ writeTemp d t target write d t target text :: Book -> Target -> String text book target = Section.flatten (_title book) (_root book) (render target) (expand target) dest :: Book -> Target -> FilePath dest book target = let title = _title book scope = _scope book suffix = strRange scope name = fromMaybe title (theme target) in _build book </> name ++ suffix <.> ext target strRange :: Scope -> String strRange scope | isEverywhere scope = "" strRange scope = intercalate "-" [lo, hi] where (lo, hi) = both (intercalate "_" . map show . toList) (toTuple scope) both f = f *** f statusMsg :: FilePath -> Target -> String statusMsg path target = printf "%s [%s]" path (show target) -- | Errors data Error = NoSource FilePath | NoTarget FilePath | NoBuild FilePath | CantDetect FilePath [FilePath] instance Show Error where show (NoSource path) = printf "source directory '%s' not found\n" path show (NoTarget path) = printf "target directory '%s' not found\n" path show (NoBuild path) = printf "build directory '%s' not found\n" path show (CantDetect path dirs) = "can't detect book root.\n" ++ printf "\tSearched from: %s\n" path ++ printf "\tLooked for directories: %s\n" (intercalate ", " dirs)
Soares/Bookbuilder
src/Book.hs
mit
4,473
0
17
1,171
1,391
705
686
-1
-1
{-# Language ParallelListComp #-} {-# Language ViewPatterns #-} {-# Language RecordWildCards #-} {-# Language ScopedTypeVariables #-} module Symmetry.IL.Model.HaskellSpec where import Data.Generics import Data.Foldable as Fold import Data.List import Data.Maybe import Language.Haskell.Exts.Pretty import Language.Haskell.Exts.Syntax hiding (Stmt) import Language.Haskell.Exts.SrcLoc import Language.Haskell.Exts.Build import Language.Fixpoint.Types as F import Text.Printf import qualified Symmetry.IL.AST as IL hiding (Op(..)) import Symmetry.IL.AST (ident, isAbs, Stmt(..), Pid(..), Set(..), Var(..), Config(..)) import Symmetry.IL.ConfigInfo import Symmetry.IL.Model import Symmetry.IL.Model.HaskellDefs instance Symbolic Name where symbol (Ident x) = symbol x pp :: Pretty a => a -> String pp = prettyPrint eRange :: F.Expr -> F.Expr -> F.Expr -> F.Expr eRange v elow ehigh = pAnd [PAtom Le elow v, PAtom Lt v ehigh] eRangeI :: F.Expr -> F.Expr -> F.Expr -> F.Expr eRangeI v elow ehigh = pAnd [PAtom Le elow v, PAtom Le v ehigh] eEq :: F.Expr -> F.Expr -> F.Expr eEq e1 e2 = PAtom Eq e1 e2 eLe :: F.Expr -> F.Expr -> F.Expr eLe e1 e2 = PAtom Le e1 e2 eLt :: F.Expr -> F.Expr -> F.Expr eLt e1 e2 = PAtom Lt e1 e2 eGt :: F.Expr -> F.Expr -> F.Expr eGt e1 e2 = PAtom Gt e1 e2 eDec :: F.Expr -> F.Expr eDec e = EBin Minus e (F.expr (1 :: Int)) ePlus :: F.Expr -> F.Expr -> F.Expr ePlus e1 e2 = EBin Plus e1 e2 eILVar :: Var -> F.Expr eILVar (V v) = eVar v eILVar (GV v) = eVar v eZero :: F.Expr eZero = F.expr (0 :: Int) eEqZero :: F.Expr -> F.Expr eEqZero e = eEq e eZero eApp :: Symbolic a => a -> [F.Expr] -> F.Expr eApp f = eApps (F.eVar f) eMember :: F.Expr -> F.Expr -> F.Expr eMember i s = eApps mem [i, s] where mem = F.eVar "Set_mem" eImp p q = F.PImp p q pidToExpr :: IL.Pid -> F.Expr pidToExpr p@(PConc _) = eVar $ pid p pidToExpr p@(PAbs (V v) s) = eApp (pid p) [eVar $ pidIdx p] eReadState :: (Symbolic a, Symbolic b) => a -> b -> F.Expr eReadState s f = eApp (symbol f) [eVar s] eReadMap e k = eApp "Map_select" {- mapGetSpecString -} [e, k] eRdPtr, eWrPtr :: (IL.Identable i, Symbolic a) => ConfigInfo i -> IL.Pid -> IL.Type -> a -> F.Expr eRdPtr ci p t s = eReadState s (ptrR ci p t) eWrPtr ci p t s = eReadState s (ptrW ci p t) initOfPid :: forall a. (Data a, IL.Identable a) => ConfigInfo a -> IL.Process a -> F.Expr initOfPid ci (p@(PAbs _ s), stmt) = pAnd preds where preds = [ counterInit , eEq counterSum setSize ] ++ counterInits ++ counterBounds st = "v" counterInit = eEq setSize (readCtr 0) setSize = eReadState st (pidBound p) counterSum = foldl' (\e i -> ePlus e (readCtr i)) (readCtr (-1)) stmts counterInits = (\i -> eEq eZero (readCtr i)) <$> filter (/= 0) ((-1) : stmts) counterBounds= (\i -> eLe eZero (readCtr i)) <$> filter (/= 0) stmts readCtr :: Int -> F.Expr readCtr i = eReadMap (eReadState st (pidPcCounter p)) (fixE i) fixE i = if i < 0 then ECst (F.expr i) FInt else F.expr i stmts :: [Int] stmts = everything (++) (mkQ [] go) stmt go :: Stmt a -> [Int] go s = [ident s] initOfPid ci (p@(PConc _), stmt) = pAnd ([pcEqZero] ++ ptrBounds ++ loopVarBounds) where s = "v" ptrBounds = concat [[ rdEqZero t, rdGeZero t , wrEqZero t, wrGeZero t , rdLeWr t ] | t <- fst <$> tyMap ci ] loopVarBounds = [ eEqZero (eReadState s v) | (p', v) <- intVars (stateVars ci), p == p' ] pcEqZero = eEq (eReadState s (pc p)) (F.expr initStmt) rdEqZero t = eEqZero (eRdPtr ci p t s) rdGeZero t = eLe eZero (eRdPtr ci p t s) wrEqZero t = eEqZero (eWrPtr ci p t s) wrGeZero t = eLe eZero (eWrPtr ci p t s) rdLeWr t = eLe (eRdPtr ci p t s) (eWrPtr ci p t s) initStmt = firstNonBlock stmt firstNonBlock Block { blkBody = bs } = ident (head bs) firstNonBlock s = ident s schedExprOfPid :: IL.Identable a => ConfigInfo a -> IL.Process a -> Symbol -> F.Expr schedExprOfPid ci (p@(IL.PAbs v s), prog) state = subst1 (pAnd ([pcEqZero, idxBounds, isEnabledP] ++ concat [[rdEqZero t, wrEqZero t, wrGtZero t] | t <- fst <$> tyMap ci] ++ [] )) (symbol (pidIdx p), vv) where vv = eVar "v" idx = IL.setName s idxBounds = eRange vv (F.expr (0 :: Int)) (eReadState state idx) pcEqZero = eEqZero (eReadMap (eReadState state (pc p)) (eILVar v)) rdEqZero t = eRangeI eZero (eReadMap (eRdPtr ci p t state) (eILVar v)) (eReadMap (eRdPtr ci p t state) (eILVar v)) wrEqZero t = eEqZero (eReadMap (eWrPtr ci p t state) (eILVar v)) wrGtZero t = eLe eZero (eReadMap (eWrPtr ci p t state) (eILVar v)) isEnabled = eMember (eILVar v) (eReadState state (enabledSet ci p)) isEnabledP = case prog of Recv{} -> F.PNot isEnabled _ -> isEnabled schedExprsOfConfig :: IL.Identable a => ConfigInfo a -> Symbol -> [F.Expr] schedExprsOfConfig ci s = go <$> filter (isAbs . fst) ps where ps = cProcs (config ci) go p = schedExprOfPid ci p s predToString :: F.Expr -> String predToString = show . pprint lhSpec :: String -> String lhSpec x = "{-@\n" ++ x ++ "\n@-}" specBind :: String -> String -> String specBind x s = x ++ " :: " ++ s specFmt :: String specFmt = "{-@ assume %s :: {v:%s | %s} @-}" printSpec :: String -> String -> F.Expr -> String printSpec x t p = printf specFmt x t (predToString p) initStateReft :: F.Expr -> String initStateReft p = printSpec initState stateRecordCons p initSchedReft :: (Symbol -> [F.Expr]) -> String initSchedReft p = printf "{-@ assume %s :: %s:State -> [%s %s] @-}" initSched initState pidPre (unwords args) where args = printf "{v:Int | %s}" . predToString <$> p (symbol initState) nonDetSpec :: String nonDetSpec = printf "{-@ %s :: %s -> {v:Int | true} @-}" nondet (pp schedType) measuresOfConfig :: Config a -> String measuresOfConfig Config { cProcs = ps } = unlines [ printf "{-@ measure %s @-}" (pidInj p) | (p, _) <- ps] valMeasures :: String valMeasures = unlines [ printf "{-@ measure %s @-}" (valInj v) | v <- valCons ] builtinSpec :: [String] builtinSpec = [nonDetSpec] --------------------- -- Type Declarations --------------------- intType, mapTyCon :: Type intType = TyCon (UnQual (name "Int")) mapTyCon = TyCon (UnQual (name "Map_t")) mapType :: Type -> Type -> Type mapType k v = TyApp (TyApp mapTyCon k) v intSetType :: Type intSetType = TyApp (TyCon (UnQual (name "Set"))) intType stateRecord :: [([Name], Type)] -> QualConDecl stateRecord fs = QualConDecl noLoc [] [] (RecDecl (name stateRecordCons) fs) removeDerives :: Decl -> Decl removeDerives (DataDecl s d c n ts qs _) = DataDecl s d c n ts qs [] removeDerives _ = undefined --------------- -- State Fields --------------- data StateFieldVisitor a b = SFV { absF :: Pid -> String -> String -> String -> a , pcF :: Pid -> String -> a , ptrF :: Pid -> String -> String -> a , valF :: Pid -> String -> a , intF :: Pid -> String -> a , globF :: String -> a , globIntF :: String -> a , combine :: [a] -> b } defaultVisitor :: StateFieldVisitor [String] [String] defaultVisitor = SFV { absF = \_ x y z -> [x,y,z] , pcF = \_ s -> [s] , ptrF = \_ s1 s2 -> [s1,s2] , valF = \_ s -> [s] , intF = \_ s -> [s] , globF = \s -> [s] , globIntF = \s -> [s] , combine = concat } withStateFields :: ConfigInfo t -> StateFieldVisitor a b -> b withStateFields ci SFV{..} = combine (globIntFs ++ absFs ++ pcFs ++ ptrFs ++ valFs ++ intFs ++ globFs) where globIntFs = [ globIntF v | V v <- setBoundVars ci ] absFs = [ absF p (pidBound p) (pcCounter p) (enabledSet ci p) | p <- pids ci, isAbs p ] pcFs = [ pcF p (pc p) | p <- pids ci ] ptrFs = [ ptrF p (ptrR ci p t) (ptrW ci p t) | p <- pids ci, t <- fst <$> tyMap ci ] valFs = [ valF p v | (p, v) <- valVars (stateVars ci) ] intFs = [ intF p v | (p, v) <- intVars (stateVars ci) ] globFs = [ globF v | v <- globVals (stateVars ci) ] derivin ci ns = ifQC_l ci $ map (\n -> (UnQual $ name n, [])) ns stateDecl :: ConfigInfo a -> ([Decl], String) stateDecl ci = ([dataDecl], specStrings) where ds = derivin ci ["Show", "Eq"] dataDecl = DataDecl noLoc DataType [] (name stateRecordCons) [] [stateRecord fs] ds specStrings = unlines [ dataReft , "" , recQuals , "" ] -- remove deriving classes (lh fails with them) dataReft = printf "{-@ %s @-}" (pp (removeDerives dataDecl)) fs = withStateFields ci SFV { combine = concat , absF = mkAbs , pcF = mkPC , ptrF = mkPtrs , valF = mkVal , intF = mkInt , globF = mkGlob , globIntF = mkGlobInt } mkAbs _ b pcv blkd = [mkBound b, mkCounter pcv, ([name blkd], intSetType)] mkPtrs p rd wr = mkInt p rd ++ mkInt p wr mkGlob v = [([name v], valHType ci)] mkGlobInt v = [([name v], intType) | v `notElem` absPidSets] absPidSets = [ IL.setName s | PAbs _ s <- fst <$> cProcs (config ci) ] mkBound p = ([name p], intType) mkCounter p = ([name p], mapType intType intType) recQuals = unlines [ mkDeref f t ++ "\n" ++ mkEq f | ([f], t) <- fs ] mkDeref f t = printf "{-@ qualif Deref_%s(v:%s, w:%s): v = %s w @-}" (pp f) (pp (fixupQualType t)) stateRecordCons (pp f) mkEq f = printf "{-@ qualif Eq_%s(v:%s, w:%s ): %s v = %s w @-}" (pp f) stateRecordCons stateRecordCons (pp f) (pp f) mkPC = liftMap intType mkVal = liftMap (valHType ci) mkInt = liftMap intType liftMap t p v = [([name v], if isAbs p then mapType intType t else t)] fixupQualType (TyApp (TyCon (UnQual (Ident "Set"))) _) = TyApp (TyCon (UnQual (name "Set_Set"))) (TyVar (name "a")) fixupQualType t = t valHType :: ConfigInfo a -> Type valHType ci = TyApp (TyCon (UnQual (name valType))) (pidPreApp ci) pidPreApp :: ConfigInfo a -> Type pidPreApp ci = foldl' TyApp (TyCon . UnQual $ name pidPre) pidPreArgs where pidPreArgs :: [Type] pidPreArgs = const intType <$> filter isAbs (pids ci) pidDecl :: ConfigInfo a -> [Decl] pidDecl ci = [ DataDecl noLoc DataType [] (name pidPre) tvbinds cons ds , TypeDecl noLoc (name pidType) [] (pidPreApp ci) ] ++ (pidFn <$> pids ci) where mkPidCons pt = QualConDecl noLoc [] [] (mkPidCons' pt) mkPidCons' (p, t) = if isAbs p then ConDecl (name (pidConstructor p)) [TyVar t] else ConDecl (name (pidConstructor p)) [] cons = mkPidCons <$> ts tvbinds = [ UnkindedVar t | (p, t) <- ts, isAbs p ] ts = [ (p, mkTy t) | p <- pids ci | t <- [0..] ] mkTy = name . ("p" ++) . show ds = derivin ci ["Show", "Eq", "Ord"] pidFn :: IL.Pid -> Decl pidFn p = FunBind [ Match noLoc (name $ pidInj p) [pidPattern p] Nothing truerhs Nothing , Match noLoc (name $ pidInj p) [PWildCard] Nothing falserhs Nothing ] where truerhs = UnGuardedRhs (var (sym "True")) falserhs = UnGuardedRhs (var (sym "False")) boundPred :: IL.SetBound -> F.Expr boundPred (IL.Known (S s) n) = eEq (F.expr n) (eReadState "v" s) boundPred (IL.Unknown (S s) (V x)) = eEq (eReadState "v" x) (eReadState "v" s) initSpecOfConfig :: (Data a, IL.Identable a) => ConfigInfo a -> String initSpecOfConfig ci = unlines [ initStateReft concExpr , initSchedReft schedExprs , stateSpec , unlines (pp <$> stateDecls) , "" , unlines (pp <$> pidDecls) , "" , measuresOfConfig (config ci) -- , stateRecordSpec ci -- , valTypeSpec ] ++ (unlines $ scrapeQuals ci) where concExpr = pAnd ((initOfPid ci <$> cProcs (config ci)) ++ [ eEqZero (eReadState (symbol "v") (symbol v)) | V v <- iters ] ++ [ eGt (eReadState (symbol "v") (symbol v)) eZero | S v <- globSets (stateVars ci) ] ++ -- TODO do not assume this... catMaybes [ boundPred <$> setBound ci s | (PAbs _ s) <- pids ci ]) iters = everything (++) (mkQ [] goVars) (cProcs (config ci)) goVars :: IL.Stmt Int -> [Var] goVars Iter {iterVar = v} = [v] goVars _ = [] schedExprs = schedExprsOfConfig ci (stateDecls, stateSpec) = stateDecl ci pidDecls = pidDecl ci recvTy :: [IL.Stmt Int] -> [IL.Type] recvTy = everything (++) (mkQ [] go) where go :: IL.Stmt Int -> [IL.Type] go (Recv (t, _) _) = [t] go _ = [] --------------------- -- Qualifiers --------------------- mkQual :: String -> [(String, String)] -> F.Expr -> String mkQual n args e = printf "{-@ qualif %s(%s): %s @-}" n argString eString where eString = show $ pprint e argString = intercalate ", " (go <$> args) go (a,t) = printf "%s:%s" a t scrapeQuals :: (IL.Identable a, Data a) => ConfigInfo a -> [String] scrapeQuals ci = scrapeIterQuals ci ++ scrapeAssertQuals ci scrapeIterQuals :: (Data a, IL.Identable a) => ConfigInfo a -> [String] scrapeIterQuals ci = concat [ everything (++) (mkQ [] (go p)) s | (p, s) <- cProcs (config ci) ] where go :: IL.Pid -> IL.Stmt Int -> [String] go p Iter { iterVar = V v, iterSet = S set, iterBody = b, annot = a } = [mkQual "IterInv" [("v", stateRecordCons)] (eImp (eReadState "v" (pc p) `eEq` F.expr i) (eReadState "v" v `eEq` eReadState "v" set)) | i <- pcAfter (ident a)] ++ iterQuals p v set b go _ _ = [] pcAfter i = (-1) : [ j | j <- pcVals, j > i ] pcVals :: [Int] pcVals = Fold.foldl (\is (_, s) -> ident s : is) [] (cProcs $ config ci) iterQuals :: (IL.Identable a, Data a) => IL.Pid -> String -> String -> IL.Stmt a -> [String] iterQuals p@(PConc _) v set b = [mkQual "IterInv" [("v", stateRecordCons)] (eReadState "v" v `eLe` eReadState "v" set)] ++ everything (++) (mkQ [] go) b where go :: IL.Stmt Int -> [String] go s = [mkQual "Iter" [("v", stateRecordCons)] (pcImpl p (ident s) (eReadState "v" v `eLt` eReadState "v" set))] pcImpl :: IL.Pid -> Int -> F.Expr -> F.Expr pcImpl p i e = eImp (eReadState "v" (pc p) `eEq` (F.expr i)) e scrapeAssertQuals :: ConfigInfo a -> [String] scrapeAssertQuals _ = []
gokhankici/symmetry
checker/src/Symmetry/IL/Model/HaskellSpec.hs
mit
16,206
1
17
5,599
6,274
3,288
2,986
365
3
import Graphics.Rendering.Cairo data Point = Point Double Double data Vector = Vector Double Double data RGBA = RGB Double Double Double | RGBA Double Double Double Double mkVector (Point x0 y0) (Point x1 y1) = Vector (x1 - x0) (y1 - y0) points = [Point 200 100, Point 100 300, Point 300 200] segments = zip points (tail (cycle points)) vectors = map (uncurry mkVector) segments white = RGBA 1.00 1.00 1.00 1.00 red = RGB 0.88 0.29 0.22 orange = RGB 0.98 0.63 0.15 fileName = "orange-lines.png" setColor (RGBA r g b a) = do setSourceRGBA r g b a setColor (RGB r g b) = do setColor (RGBA r g b 0.8) drawOneMarker bw = do rectangle (-0.5*bw) (-0.5*bw) bw bw fill drawMarkerAt (Point x y) = do save translate x y setColor red drawOneMarker 20.0 restore drawVector (Point x y) (Vector dx dy) = do setColor orange moveTo x y relLineTo dx dy stroke paintCanvas = do setSourceRGB 1 1 1 paint mapM_ drawMarkerAt points mapM_ (uncurry drawVector) (zip points vectors) createPng fileName = do let w = 400 h = 400 img <- createImageSurface FormatARGB32 w h renderWith img paintCanvas surfaceWriteToPNG img fileName liftIO ( do putStrLn ("Created: " ++ fileName) putStrLn ("Size: " ++ show w ++ "x" ++ show h ++ " pixels") ) main = do createPng fileName
jsavatgy/xroads-game
code/orange-lines.hs
gpl-2.0
1,341
0
17
324
574
272
302
48
1
#!/usr/bin/env runghc import System.IO import System.Environment import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.AutoDecompress import Control.Concurrent main = do args <- getArgs case args of ("-t":files) -> mapM_ (fileLength True) files ("-l":files) -> lotsOfFiles (head files) ("-i":files) -> mapM_ fileLengthH files files -> mapM_ (fileLength False) files fileLength :: Bool -> FilePath -> IO () fileLength transform file = do putStr $ file ++ " : " (if transform then withDecompressFile file else withFile file ReadMode) $ \h -> do str <- B.hGetContents h print $ B.length str fileLengthH :: FilePath -> IO () fileLengthH file = do putStr $ file ++ " : " withFile file ReadMode $ \h -> withDecompressHandle h $ \h2 -> do str <- B.hGetContents h2 print $ B.length str lotsOfFiles :: FilePath -> IO () lotsOfFiles file = do lens <- mapM (\_ -> withDecompressFile file (\h -> do str <- BL.hGetContents h let c = BL.take 1 str c `seq` return c ) ) [1..100] print lens threadDelay $ 30 * 1000 * 1000
drpowell/auto-decompress
t.hs
gpl-2.0
1,302
0
20
431
440
218
222
36
4
module Exp where data Exp = Lit Int | Neg Exp | Add Exp Exp deriving (Eq, Show) ti1 = Add (Lit 8) (Neg (Add (Lit 1) (Lit 2)))
capitanbatata/sandbox
tagless/src/Exp.hs
gpl-3.0
155
0
11
58
78
42
36
6
1
import Data.List (group, sort, nub) import Text.Printf (printf) main :: IO() main = do content <- fmap lines getContents let x = map read $ words $ last content printf "%.1f\n" $ mean x printf "%.1f\n" $ median x putStrLn $ show $ mode x printf "%.1f\n" $ stdev x (\(a,b) -> printf "%.1f %.1f\n" a b) $ confidence_95int x mean :: Num a => [Int] -> Double mean x = (fromIntegral $ sum x) / (fromIntegral $ length x) mode :: [Int] -> Int mode x = mode' $ map snd $ (\a -> (\b -> filter ((==b).fst) a) $ fst $ last $ sort a) -- $ sort $ map (\z -> (length z, head z)) $ group $ sort x $ map (\y -> (length $ filter (==y) x, y)) $ nub x mode' [] = 10^10 mode' (x:xs) = min x $ mode' xs stdev :: [Int] -> Double stdev x = sqrt $ var $ map fromIntegral x var x = e (mean x) x / (fromIntegral $ length x) where e _ [] = 0.0 e u (x:xs) = (fromIntegral x - u)^2 + e u xs median :: [Int] -> Double median x = median' $ sort x median' [] = 0.0 median' x | length x == 1 = fromIntegral $ head x | length x == 2 = mean x | otherwise = median' $ init $ tail x confidence_95int :: [Int] -> (Double, Double) confidence_95int x = (a - 1.96*s/n, a + 1.96*s/n) where a = mean x s = stdev x n = sqrt $ fromIntegral $ length x
woodsjc/hackerrank-challenges
ai_section/stat_warmup.hs
gpl-3.0
1,383
3
18
447
686
341
345
35
2
module Evaluator where import qualified AST as P data Value = VBool Bool |VInt Integer deriving Show eval::P.Term -> Maybe Value eval P.STrue = Just (VBool True) eval P.SFalse = Just (VBool False) eval P.SZero = Just (VInt 0) eval (P.SIsZero t) = case eval t of Just (VInt i) -> Just (VBool (i == 0)) _ -> Nothing eval (P.SSucc t) = case eval t of Just (VInt i) -> Just (VInt (i+1)) _ -> Nothing eval (P.SPred t) = case eval t of Just (VInt i) | i>0 -> Just(VInt (i-1)) _ -> Nothing eval (P.SIfThen t1 t2 t3) = case eval t1 of Just (VBool True) -> eval t2 Just (VBool False) -> eval t3 _ -> Nothing
jmoy/pierce-arith
Evaluator.hs
gpl-3.0
673
0
13
195
357
175
182
27
6
import Test.QuickCheck import Data.Maybe import Data.List -- These functions are copied directly from problem #11. data EncodedEntry a = Multiple (Int, a) | Single a deriving (Eq, Show, Ord) listToEncodedEntry :: [a] -> Maybe (EncodedEntry a) listToEncodedEntry x = case length x of 0 -> Nothing 1 -> Just . Single . head $ x otherwise -> Just . Multiple $ (length x, head x) myEncode :: Eq a => [a] -> [EncodedEntry a] myEncode [] = [] myEncode xs = [fromJust . listToEncodedEntry $ x | x <- group xs] -- Define a decode function. encodedEntryToList :: EncodedEntry a -> [a] encodedEntryToList (Multiple (n, x)) = replicate n x encodedEntryToList (Single x) = [x] myDecode :: [EncodedEntry a] -> [a] myDecode x = concatMap encodedEntryToList x -- Define a very basic test for our decoding function. testMyDecode :: [Char] -> Bool testMyDecode x = (myDecode . myEncode $ x) == x main = quickCheck testMyDecode
CmdrMoozy/haskell99
012.hs
gpl-3.0
927
2
10
173
341
180
161
21
3
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE ViewPatterns #-} #if (__GLASGOW_HASKELL__ > 710) {-# LANGUAGE UndecidableSuperClasses #-} #endif module Youtrack.Exchanges ( Exchange(..) , ExchangeType(..) , Request(..) , Response , EProjectAll , EIssue , EIssueTTWItem , EIssueExecute , EIssueUpdate , EIssueComments ) where import Control.Lens hiding (from, Context) import Control.Monad.Reader import GHC.Exts (Constraint) import GHC.Generics (Generic) import Data.Aeson (FromJSON (..)) import Data.Monoid ((<>)) import qualified Data.Text as T import Network.Wreq (FormParam((:=))) import qualified Network.Wreq as WR import Prelude.Unicode import Text.Printf (printf) import Youtrack.Types -- * Generic Exchange/RR (request/response) machinery type family JSONC c ∷ Constraint type instance JSONC c = (FromJSON c) type family FunctorC (c ∷ * → *) ∷ Constraint type instance FunctorC c = (Functor c) type family ShowC c ∷ Constraint type instance ShowC c = (Show c) data ExchangeType = Get | Post type PreResponse q = Replies q (Reader (Context q) (Reply q)) type Response q = Replies q (Reply q) class (Functor (Replies q), JSONC (PreResponse q)) ⇒ Exchange q where type Context q ∷ * data Request q ∷ * type Replies q ∷ * → * type Reply q ∷ * request_type ∷ Request q → ExchangeType request_params ∷ Request q → WR.Options → WR.Options request_type _ = Get request_params _ = id -- Mandatory method: request_urlpath ∷ Request q → URLPath -- POST-only method: request_post_args ∷ Request q → [WR.FormParam] request_post_args _ = [] instance Exchange q ⇒ Show (Request q) where show x = printf "#{Request %s / %s}" (show $ request_urlpath x) (show $ request_post_args x) -- * /project/all?{verbose} -- https://confluence.jetbrains.com/display/YTD65/Get+Accessible+Projects data EProjectAll instance Exchange EProjectAll where type Context EProjectAll = YT data Request EProjectAll = RProjectAll type Replies EProjectAll = [] type Reply EProjectAll = Project request_urlpath RProjectAll = URLPath "/project/all" request_params RProjectAll params = params & WR.param "verbose" .~ ["true"] -- * /issue/byproject/{project}?{filter}&{after}&{max}&{updatedAfter}&{wikifyDescription} -- https://confluence.jetbrains.com/display/YTD65/Get+Issues+in+a+Project -- Note, this seems a bit useless, because it doesn't allow to get custom fields -- in one request. -- instance Exchange EIssueByProject where -- data Request EIssueByProject = RIssueByProject PAlias Filter deriving Show -- type Response EIssueByProject = [Issue] -- request_urlpath (RIssueByProject (PAlias alias) query) = -- URLPath $ "/issue/byproject/" <> alias -- request_params (RIssueByProject (PAlias alias) (Filter query)) params = -- params & if not $ Data.List.null query -- then WR.param "query" .~ [T.pack query] -- else id -- * /issue?{filter}&{with}&{max}&{after} -- https://confluence.jetbrains.com/display/YTD65/Get+the+List+of+Issues newtype RIssueWrapper = RIssueWrapper [Reader ProjectDict Issue] deriving (Generic) instance FromJSON RIssueWrapper where parseJSON = newtype_from_JSON data EIssue instance Exchange EIssue where type Context EIssue = ProjectDict data Request EIssue = RIssue Filter {-ignored-} Int {-ignored-} [Field] type Replies EIssue = [] type Reply EIssue = Issue request_urlpath (RIssue _ _ _) = URLPath $ "/issue" request_params (RIssue (Filter query) limit fields) params = params & WR.param "filter" .~ [T.pack query] & WR.param "max" .~ [T.pack $ printf "%d" limit] & WR.param "with" .~ case fmap (T.pack ∘ field) fields of [] → [""] xs → xs -- * /issue/{issue}/timetracking/workitem/ -- https://confluence.jetbrains.com/display/YTD65/Get+Available+Work+Items+of+Issue data EIssueTTWItem instance Exchange EIssueTTWItem where type Context EIssueTTWItem = Project data Request EIssueTTWItem = RIssueTTWItem PAlias IId type Replies EIssueTTWItem = [] type Reply EIssueTTWItem = WorkItem request_urlpath (RIssueTTWItem palias iid) = URLPath $ "/issue/" <> palias_iid_idstr palias iid <> "/timetracking/workitem/" -- * POST /issue/{issue}/execute?{command}&{comment}&{group}&{disableNotifications}&{runAs} -- https://confluence.jetbrains.com/display/YTD65/Apply+Command+to+an+Issue data EIssueExecute instance Exchange EIssueExecute where type Context EIssueExecute = () data Request EIssueExecute = RIssueExecute PAlias IId YTCmd Bool | RIssuePostComment PAlias IId String type Replies EIssueExecute = Identity type Reply EIssueExecute = () request_type _ = Post request_urlpath r = let p_i = case r of RIssueExecute pal' iid' _ _ → (pal', iid') RIssuePostComment pal' iid' _ → (pal', iid') in URLPath $ "/issue/" <> palias_iid_idstr (fst p_i) (snd p_i) <> "/execute" request_post_args (RIssueExecute _ _ (YTCmd cmd) quiet) = [ "command" := T.pack cmd, "disableNotifications" := (T.pack $ if quiet then "true" else "false") ] request_post_args (RIssuePostComment _ _ comment) = [ "comment" := T.pack comment ] -- * POST /issue/{issueID}?{summary}&{description} -- https://confluence.jetbrains.com/display/YTD65/Update+an+Issue data EIssueUpdate instance Exchange EIssueUpdate where type Context EIssueUpdate = () data Request EIssueUpdate = RIssueUpdate PAlias IId Summary Description type Replies EIssueUpdate = Identity type Reply EIssueUpdate = () request_type _ = Post request_urlpath (RIssueUpdate pal iid _ _) = URLPath $ "/issue/" <> palias_iid_idstr pal iid request_post_args (RIssueUpdate _ _ summ desc) = [ "summary" := (T.pack $ fromSummary summ) , "description" := (T.pack $ fromDescription desc) ] -- * GET /rest/issue/{issue}/comment&{wikifyDescription} -- https://confluence.jetbrains.com/display/YTD65/Get+Comments+of+an+Issue data EIssueComments instance Exchange EIssueComments where type Context EIssueComments = Issue data Request EIssueComments = RIssueComments PAlias IId type Replies EIssueComments = [] type Reply EIssueComments = Comment request_urlpath (RIssueComments pal iid) = URLPath $ "/issue/" <> palias_iid_idstr pal iid <> "/comment"
deepfire/youtrack
src/Youtrack/Exchanges.hs
gpl-3.0
7,677
0
13
2,069
1,498
829
669
-1
-1
module Utils where import Data.List (partition) import Types (Ingredient (..), showFrac, showUnit) safeLookup :: [a] -> Int -> Maybe a safeLookup [] _ = Nothing safeLookup (a : _) 0 = Just a safeLookup (_ : as) n = safeLookup as (n - 1) padLeft :: Int -> String -> String padLeft n xs = let d = n - length xs in if d > 0 then replicate d ' ' ++ xs else xs padRight :: Int -> String -> String padRight n xs = let d = n - length xs in if d > 0 then xs ++ replicate d ' ' else xs combineIngredientsByFilter :: -- | The predicate to filter on (Ingredient -> Bool) -> -- | How to combine ingredients (Ingredient -> Ingredient -> Ingredient) -> -- | The list to combine [Ingredient] -> [Ingredient] combineIngredientsByFilter pred comb lst = case partition pred lst of ([], rest) -> rest (x : xs, rest) -> foldl comb x xs : rest -- | @combineIngredientsByName combines all the ingredients with the same -- name and unit as the @key@. combineIngredientsByName :: Ingredient -> [Ingredient] -> [Ingredient] combineIngredientsByName key = combineIngredientsByFilter (\x -> ingredientName key == ingredientName x && unit key == unit x) addQuantities where addQuantities :: Ingredient -> Ingredient -> Ingredient addQuantities (Ingredient q1 u1 n1 a1) (Ingredient q2 u2 _ a2) = -- Show which attributes apply to what amount let attrs = if a1 /= a2 then showFrac q1 ++ " " ++ showUnit u1 ++ ": " ++ a1 ++ ", " ++ showFrac q2 ++ " " ++ showUnit u2 ++ ": " ++ a2 else a1 in Ingredient (q1 + q2) u1 n1 attrs -- | @combineIngredients combines ingredients with identical names and units. -- This is currently O(n^2), it could probably be better. combineIngredients :: [Ingredient] -> [Ingredient] combineIngredients lst = foldl (\acc x -> combineIngredientsByName x acc) lst lst
JackKiefer/herms
src/Utils.hs
gpl-3.0
2,042
0
22
602
596
312
284
48
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Schema.Model.V5 where import Data.Text (Text) import Data.Time.Clock (UTCTime) import Database.Persist.TH (persistUpperCase) import qualified Database.Persist.TH as TH import Model (Model) import Schema.Utils (Int64) import Types import Schema.Algorithm (AlgorithmId) import Schema.Platform (PlatformId) TH.share [TH.mkPersist TH.sqlSettings, TH.mkSave "schema"] [persistUpperCase| PredictionModel platformId PlatformId algorithmId AlgorithmId algorithmVersion CommitId name Text prettyName Text Maybe description Text Maybe model Model legacyTrainFraction Double trainGraphs Percentage trainVariants Percentage trainSteps Percentage trainSeed Int64 totalUnknownCount Int timestamp UTCTime UniqModel name |]
merijn/GPU-benchmarks
benchmark-analysis/src/Schema/Model/V5.hs
gpl-3.0
1,149
0
8
179
132
85
47
22
0
{-# LANGUAGE OverloadedStrings, NamedFieldPuns #-} {-# OPTIONS_GHC -fno-warn-overlapping-patterns#-} module Hash ( module Object.Hash , vhash , insert , index , keys , values , toArray ) where import Data.Foldable (toList) import qualified Data.HashMap.Strict as H import Object import Object.Hash import String import Err import qualified Array as A hkey :: Object -> HKey hkey (Prim (VInt i)) = HKInt i hkey (Prim (VString ss)) = HKString $ string ss hkey (Prim (VFloat f)) = HKFloat f hkey (Prim (VAtom s)) = HKAtom s hkey (Prim (VArray a)) = HKArray (map hkey (toList a)) hkey (Prim (VHash hash)) = HKHash $ hkey $ toArray hash hkey (Process pid) = HKProcess $ show pid hkey (TrueClass) = HKTrue hkey (FalseClass) = HKFalse hkey (Nil) = HKNil hkey (VFunction{fUID}) = HKFunction fUID hkey (Object obj) = HKObject (uid obj) hkey (VError (ErrObj a)) = HKError (hkey a) hkey (VError (Err a b _)) = HKErr a b hkey o = case getUID o of Just u -> HKSpecial u Nothing -> HKSpecial 0 vhash :: [(Object,Object)] -> Object vhash lst = Prim $ VHash $ Hash{defaultValue = Nil, h=hsh, hUID=0} where hsh = H.fromList (map (\(k,v)-> mkKeyValue k v) lst) insert :: Object -> Object -> Hash -> Hash insert k v hsh@Hash{h} = hsh{h=h'} where h' = H.insert k' v' h (k',v') = mkKeyValue k v index :: Object -> Hash -> Object index k (Hash{defaultValue,h}) = case (H.lookup (hkey k) h) of Nothing -> defaultValue Just (HValue{trueValue}) -> trueValue keys :: Hash -> Object keys Hash{h} = A.varray $ map trueKey (H.elems h) values :: Hash -> Object values Hash{h} = A.varray $ map trueValue (H.elems h) toArray :: Hash -> Object toArray Hash{h} = A.varray $ map (\(HValue{trueKey, trueValue}) -> A.varray [trueKey,trueValue]) (H.elems h) mkKeyValue :: Object -> Object -> (HKey, HValue) mkKeyValue trueKey trueValue = (hkey trueKey, HValue{trueKey,trueValue})
antarestrader/sapphire
Hash.hs
gpl-3.0
1,905
0
12
372
889
469
420
56
2
-- (c) 2002 by Martin Erwig [see file COPYRIGHT] -- | Monadic Graph Algorithms module Data.Graph.Inductive.Query.Monad( -- * Additional Graph Utilities mapFst, mapSnd, (><), orP, -- * Graph Transformer Monad GT(..), apply, apply', applyWith, applyWith', runGT, condMGT', recMGT', condMGT, recMGT, -- * Graph Computations Based on Graph Monads -- ** Monadic Graph Accessing Functions getNode, getContext, getNodes', getNodes, sucGT, sucM, -- ** Derived Graph Recursion Operators graphRec, graphRec', graphUFold, -- * Examples: Graph Algorithms as Instances of Recursion Operators -- ** Instances of graphRec graphNodesM0, graphNodesM, graphNodes, graphFilterM, graphFilter, -- * Example: Monadic DFS Algorithm(s) dfsGT, dfsM, dfsM', dffM, graphDff, graphDff', ) where -- Why all this? -- -- graph monad ensures single-threaded access -- ==> we can safely use imperative updates in the graph implementation -- import Data.Tree --import Control.Monad (liftM) import Data.Graph.Inductive.Graph import Data.Graph.Inductive.Monad -- some additional (graph) utilities -- mapFst :: (a -> b) -> (a, c) -> (b, c) mapFst f (x,y) = (f x,y) mapSnd :: (a -> b) -> (c, a) -> (c, b) mapSnd f (x,y) = (x,f y) infixr 8 >< (><) :: (a -> b) -> (c -> d) -> (a, c) -> (b, d) (f >< g) (x,y) = (f x,g y) orP :: (a -> Bool) -> (b -> Bool) -> (a,b) -> Bool orP p q (x,y) = p x || q y ---------------------------------------------------------------------- -- "wrapped" state transformer monad == -- monadic graph transformer monad ---------------------------------------------------------------------- data GT m g a = MGT (m g -> m (a,g)) apply :: GT m g a -> m g -> m (a,g) apply (MGT f) mg = f mg apply' :: Monad m => GT m g a -> g -> m (a,g) apply' gt = apply gt . return applyWith :: Monad m => (a -> b) -> GT m g a -> m g -> m (b,g) applyWith h (MGT f) gm = do {(x,g) <- f gm; return (h x,g)} applyWith' :: Monad m => (a -> b) -> GT m g a -> g -> m (b,g) applyWith' h gt = applyWith h gt . return runGT :: Monad m => GT m g a -> m g -> m a runGT gt mg = do {(x,_) <- apply gt mg; return x} instance Monad m => Monad (GT m g) where return x = MGT (\mg->do {g<-mg; return (x,g)}) f >>= h = MGT (\mg->do {(x,g)<-apply f mg; apply' (h x) g}) condMGT' :: Monad m => (s -> Bool) -> GT m s a -> GT m s a -> GT m s a condMGT' p f g = MGT (\mg->do {h<-mg; if p h then apply f mg else apply g mg}) recMGT' :: Monad m => (s -> Bool) -> GT m s a -> (a -> b -> b) -> b -> GT m s b recMGT' p mg f u = condMGT' p (return u) (do {x<-mg;y<-recMGT' p mg f u;return (f x y)}) condMGT :: Monad m => (m s -> m Bool) -> GT m s a -> GT m s a -> GT m s a condMGT p f g = MGT (\mg->do {b<-p mg; if b then apply f mg else apply g mg}) recMGT :: Monad m => (m s -> m Bool) -> GT m s a -> (a -> b -> b) -> b -> GT m s b recMGT p mg f u = condMGT p (return u) (do {x<-mg;y<-recMGT p mg f u;return (f x y)}) ---------------------------------------------------------------------- -- graph computations based on state monads/graph monads ---------------------------------------------------------------------- -- some monadic graph accessing functions -- getNode :: GraphM m gr => GT m (gr a b) Node getNode = MGT (\mg->do {((_,v,_,_),g) <- matchAnyM mg; return (v,g)}) getContext :: GraphM m gr => GT m (gr a b) (Context a b) getContext = MGT matchAnyM -- some functions defined by using the do-notation explicitly -- Note: most of these can be expressed as an instance of graphRec -- getNodes' :: (Graph gr,GraphM m gr) => GT m (gr a b) [Node] getNodes' = condMGT' isEmpty (return []) (do v <- getNode vs <- getNodes return (v:vs)) getNodes :: GraphM m gr => GT m (gr a b) [Node] getNodes = condMGT isEmptyM (return []) (do v <- getNode vs <- getNodes return (v:vs)) sucGT :: GraphM m gr => Node -> GT m (gr a b) (Maybe [Node]) sucGT v = MGT (\mg->do (c,g) <- matchM v mg case c of Just (_,_,_,s) -> return (Just (map snd s),g) Nothing -> return (Nothing,g) ) sucM :: GraphM m gr => Node -> m (gr a b) -> m (Maybe [Node]) sucM v = runGT (sucGT v) ---------------------------------------------------------------------- -- some derived graph recursion operators ---------------------------------------------------------------------- -- -- graphRec :: GraphMonad a b c -> (c -> d -> d) -> d -> GraphMonad a b d -- graphRec f g u = cond isEmpty (return u) -- (do x <- f -- y <- graphRec f g u -- return (g x y)) -- | encapsulates a simple recursion schema on graphs graphRec :: GraphM m gr => GT m (gr a b) c -> (c -> d -> d) -> d -> GT m (gr a b) d graphRec = recMGT isEmptyM graphRec' :: (Graph gr,GraphM m gr) => GT m (gr a b) c -> (c -> d -> d) -> d -> GT m (gr a b) d graphRec' = recMGT' isEmpty graphUFold :: GraphM m gr => (Context a b -> c -> c) -> c -> GT m (gr a b) c graphUFold = graphRec getContext ---------------------------------------------------------------------- -- Examples: graph algorithms as instances of recursion operators ---------------------------------------------------------------------- -- instances of graphRec -- graphNodesM0 :: GraphM m gr => GT m (gr a b) [Node] graphNodesM0 = graphRec getNode (:) [] graphNodesM :: GraphM m gr => GT m (gr a b) [Node] graphNodesM = graphUFold (\(_,v,_,_)->(v:)) [] graphNodes :: GraphM m gr => m (gr a b) -> m [Node] graphNodes = runGT graphNodesM graphFilterM :: GraphM m gr => (Context a b -> Bool) -> GT m (gr a b) [Context a b] graphFilterM p = graphUFold (\c cs->if p c then c:cs else cs) [] graphFilter :: GraphM m gr => (Context a b -> Bool) -> m (gr a b) -> m [Context a b] graphFilter p = runGT (graphFilterM p) ---------------------------------------------------------------------- -- Example: monadic dfs algorithm(s) ---------------------------------------------------------------------- -- | Monadic graph algorithms are defined in two steps: -- -- (1) define the (possibly parameterized) graph transformer (e.g., dfsGT) -- (2) run the graph transformer (applied to arguments) (e.g., dfsM) -- dfsGT :: GraphM m gr => [Node] -> GT m (gr a b) [Node] dfsGT [] = return [] dfsGT (v:vs) = MGT (\mg-> do (mc,g') <- matchM v mg case mc of Just (_,_,_,s) -> applyWith' (v:) (dfsGT (map snd s++vs)) g' Nothing -> apply' (dfsGT vs) g' ) -- | depth-first search yielding number of nodes dfsM :: GraphM m gr => [Node] -> m (gr a b) -> m [Node] dfsM vs = runGT (dfsGT vs) dfsM' :: GraphM m gr => m (gr a b) -> m [Node] dfsM' mg = do {vs <- nodesM mg; runGT (dfsGT vs) mg} -- | depth-first search yielding dfs forest dffM :: GraphM m gr => [Node] -> GT m (gr a b) [Tree Node] dffM vs = MGT (\mg-> do g<-mg b<-isEmptyM mg if b||null vs then return ([],g) else let (v:vs') = vs in do (mc,g1) <- matchM v mg case mc of Nothing -> apply (dffM vs') (return g1) Just c -> do (ts, g2) <- apply (dffM (suc' c)) (return g1) (ts',g3) <- apply (dffM vs') (return g2) return (Node (node' c) ts:ts',g3) ) graphDff :: GraphM m gr => [Node] -> m (gr a b) -> m [Tree Node] graphDff vs = runGT (dffM vs) graphDff' :: GraphM m gr => m (gr a b) -> m [Tree Node] graphDff' mg = do {vs <- nodesM mg; runGT (dffM vs) mg}
ckaestne/CIDE
CIDE_Language_Haskell/test/FGL-layout/Graph/Inductive/Query/Monad.hs
gpl-3.0
8,193
0
25
2,523
3,207
1,674
1,533
111
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} -- | -- Module : Network.AWS.Types -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : provisional -- Portability : non-portable (GHC extensions) -- module Network.AWS.Types ( -- * Authentication -- ** Credentials AccessKey (..) , SecretKey (..) , SessionToken (..) -- ** Environment , AuthEnv (..) , Auth (..) , withAuth -- * Logging , LogLevel (..) , Logger -- * Signing , Algorithm , Meta (..) , Signer (..) , Signed (..) -- * Service , Abbrev , Service (..) , serviceSigner , serviceEndpoint , serviceTimeout , serviceCheck , serviceRetry -- * Requests , AWSRequest (..) , Request (..) , rqService , rqMethod , rqHeaders , rqPath , rqQuery , rqBody , rqSign , rqPresign -- * Responses , Response -- * Retries , Retry (..) , exponentBase , exponentGrowth , retryAttempts , retryCheck -- * Errors , AsError (..) , Error (..) -- ** HTTP Errors , HttpException -- ** Serialize Errors , SerializeError (..) , serializeAbbrev , serializeStatus , serializeMessage -- ** Service Errors , ServiceError (..) , serviceAbbrev , serviceStatus , serviceHeaders , serviceCode , serviceMessage , serviceRequestId -- ** Error Types , ErrorCode , errorCode , ErrorMessage (..) , RequestId (..) -- * Regions , Region (..) -- * Endpoints , Endpoint (..) , endpointHost , endpointPort , endpointSecure , endpointScope -- * HTTP , ClientRequest , ClientResponse , ResponseBody , clientRequest -- ** Seconds , Seconds (..) , seconds , microseconds -- * Isomorphisms , _Coerce , _Default ) where import Control.Applicative import Control.Concurrent (ThreadId) import Control.Exception import Control.Exception.Lens (exception) import Control.Lens hiding (coerce) import Control.Monad.IO.Class import Control.Monad.Trans.Resource import Data.Aeson hiding (Error) import qualified Data.ByteString as BS import Data.ByteString.Builder (Builder) import Data.Coerce import Data.Conduit import Data.Data (Data, Typeable) import Data.Hashable import Data.IORef import Data.Maybe import Data.Monoid import Data.Proxy import Data.String import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time import GHC.Generics (Generic) import Network.AWS.Data.Body import Network.AWS.Data.ByteString import Network.AWS.Data.JSON import Network.AWS.Data.Log import Network.AWS.Data.Path import Network.AWS.Data.Query import Network.AWS.Data.Text import Network.AWS.Data.XML import Network.HTTP.Client hiding (Proxy, Request, Response) import qualified Network.HTTP.Client as Client import Network.HTTP.Types.Header import Network.HTTP.Types.Method import Network.HTTP.Types.Status (Status) import Text.XML (def) import Prelude -- | A convenience alias to avoid type ambiguity. type ClientRequest = Client.Request -- | A convenience alias encapsulating the common 'Response'. type ClientResponse = Client.Response ResponseBody -- | A convenience alias encapsulating the common 'Response' body. type ResponseBody = ResumableSource (ResourceT IO) ByteString -- | Abbreviated service name. newtype Abbrev = Abbrev Text deriving (Eq, Ord, Show, IsString, FromXML, FromJSON, FromText, ToText, ToLog) newtype ErrorCode = ErrorCode Text deriving (Eq, Ord, Show, ToText, ToLog) instance IsString ErrorCode where fromString = errorCode . fromString instance FromJSON ErrorCode where parseJSON = parseJSONText "ErrorCode" instance FromXML ErrorCode where parseXML = parseXMLText "ErrorCode" instance FromText ErrorCode where parser = errorCode <$> parser -- | Construct an 'ErrorCode'. errorCode :: Text -> ErrorCode errorCode = ErrorCode . strip . unnamespace where -- Common suffixes are stripped since the service definitions are ambigiuous -- as to whether the error shape's name, or the error code is present -- in the response. strip x = fromMaybe x $ Text.stripSuffix "Exception" x <|> Text.stripSuffix "Fault" x -- Removing the (potential) leading ...# namespace. unnamespace x = case Text.break (== '#') x of (ns, e) | Text.null e -> ns | otherwise -> Text.drop 1 e newtype ErrorMessage = ErrorMessage Text deriving (Eq, Ord, Show, IsString, FromXML, FromJSON, FromText, ToText, ToLog) newtype RequestId = RequestId Text deriving (Eq, Ord, Show, IsString, FromXML, FromJSON, FromText, ToText, ToLog) -- | An error type representing errors that can be attributed to this library. data Error = TransportError HttpException | SerializeError SerializeError | ServiceError ServiceError deriving (Show, Typeable) instance Exception Error instance ToLog Error where build = \case TransportError e -> build e SerializeError e -> build e ServiceError e -> build e data SerializeError = SerializeError' { _serializeAbbrev :: !Abbrev , _serializeStatus :: !Status , _serializeMessage :: String } deriving (Eq, Show, Typeable) instance ToLog SerializeError where build SerializeError'{..} = buildLines [ "[SerializeError] {" , " service = " <> build _serializeAbbrev , " status = " <> build _serializeStatus , " message = " <> build _serializeMessage , "}" ] serializeAbbrev :: Lens' SerializeError Abbrev serializeAbbrev = lens _serializeAbbrev (\s a -> s { _serializeAbbrev = a }) serializeStatus :: Lens' SerializeError Status serializeStatus = lens _serializeStatus (\s a -> s { _serializeStatus = a }) serializeMessage :: Lens' SerializeError String serializeMessage = lens _serializeMessage (\s a -> s { _serializeMessage = a }) data ServiceError = ServiceError' { _serviceAbbrev :: !Abbrev , _serviceStatus :: !Status , _serviceHeaders :: [Header] , _serviceCode :: !ErrorCode , _serviceMessage :: Maybe ErrorMessage , _serviceRequestId :: Maybe RequestId } deriving (Eq, Show, Typeable) instance ToLog ServiceError where build ServiceError'{..} = buildLines [ "[ServiceError] {" , " service = " <> build _serviceAbbrev , " status = " <> build _serviceStatus , " code = " <> build _serviceCode , " message = " <> build _serviceMessage , " request-id = " <> build _serviceRequestId , "}" ] serviceAbbrev :: Lens' ServiceError Abbrev serviceAbbrev = lens _serviceAbbrev (\s a -> s { _serviceAbbrev = a }) serviceStatus :: Lens' ServiceError Status serviceStatus = lens _serviceStatus (\s a -> s { _serviceStatus = a }) serviceHeaders :: Lens' ServiceError [Header] serviceHeaders = lens _serviceHeaders (\s a -> s { _serviceHeaders = a }) serviceCode :: Lens' ServiceError ErrorCode serviceCode = lens _serviceCode (\s a -> s { _serviceCode = a }) serviceMessage :: Lens' ServiceError (Maybe ErrorMessage) serviceMessage = lens _serviceMessage (\s a -> s { _serviceMessage = a }) serviceRequestId :: Lens' ServiceError (Maybe RequestId) serviceRequestId = lens _serviceRequestId (\s a -> s { _serviceRequestId = a }) class AsError a where -- | A general Amazonka error. _Error :: Prism' a Error {-# MINIMAL _Error #-} -- | An error occured while communicating over HTTP with a remote service. _TransportError :: Prism' a HttpException -- | A serialisation error occured when attempting to deserialise a response. _SerializeError :: Prism' a SerializeError -- | A service specific error returned by the remote service. _ServiceError :: Prism' a ServiceError _TransportError = _Error . _TransportError _SerializeError = _Error . _SerializeError _ServiceError = _Error . _ServiceError instance AsError SomeException where _Error = exception instance AsError Error where _Error = id _TransportError = prism TransportError $ \case TransportError e -> Right e x -> Left x _SerializeError = prism SerializeError $ \case SerializeError e -> Right e x -> Left x _ServiceError = prism ServiceError $ \case ServiceError e -> Right e x -> Left x data Endpoint = Endpoint { _endpointHost :: ByteString , _endpointSecure :: !Bool , _endpointPort :: !Int , _endpointScope :: ByteString } deriving (Eq, Show, Data, Typeable) endpointHost :: Lens' Endpoint ByteString endpointHost = lens _endpointHost (\s a -> s { _endpointHost = a }) endpointSecure :: Lens' Endpoint Bool endpointSecure = lens _endpointSecure (\s a -> s { _endpointSecure = a }) endpointPort :: Lens' Endpoint Int endpointPort = lens _endpointPort (\s a -> s { _endpointPort = a }) endpointScope :: Lens' Endpoint ByteString endpointScope = lens _endpointScope (\s a -> s { _endpointScope = a }) data LogLevel = Info -- ^ Info messages supplied by the user - this level is not emitted by the library. | Error -- ^ Error messages only. | Debug -- ^ Useful debug information + info + error levels. | Trace -- ^ Includes potentially sensitive signing metadata, and non-streaming response bodies. deriving (Eq, Ord, Enum, Show, Data, Typeable) instance FromText LogLevel where parser = takeLowerText >>= \case "info" -> pure Info "error" -> pure Error "debug" -> pure Debug "trace" -> pure Trace e -> fromTextError $ "Failure parsing LogLevel from " <> e instance ToText LogLevel where toText = \case Info -> "info" Error -> "error" Debug -> "debug" Trace -> "trace" instance ToByteString LogLevel -- | A function threaded through various request and serialisation routines -- to log informational and debug messages. type Logger = LogLevel -> Builder -> IO () -- | Constants and predicates used to create a 'RetryPolicy'. data Retry = Exponential { _retryBase :: !Double , _retryGrowth :: !Int , _retryAttempts :: !Int , _retryCheck :: ServiceError -> Maybe Text -- ^ Returns a descriptive name for logging -- if the request should be retried. } exponentBase :: Lens' Retry Double exponentBase = lens _retryBase (\s a -> s { _retryBase = a }) exponentGrowth :: Lens' Retry Int exponentGrowth = lens _retryGrowth (\s a -> s { _retryGrowth = a }) retryAttempts :: Lens' Retry Int retryAttempts = lens _retryAttempts (\s a -> s { _retryAttempts = a }) retryCheck :: Lens' Retry (ServiceError -> Maybe Text) retryCheck = lens _retryCheck (\s a -> s { _retryCheck = a }) -- | Signing algorithm specific metadata. data Meta where Meta :: ToLog a => a -> Meta instance ToLog Meta where build (Meta m) = build m -- | A signed 'ClientRequest' and associated metadata specific -- to the signing algorithm, tagged with the initial request type -- to be able to obtain the associated response, 'Rs a'. data Signed a = Signed { sgMeta :: !Meta , sgRequest :: !ClientRequest } type Algorithm a = Request a -> AuthEnv -> Region -> UTCTime -> Signed a data Signer = Signer { sgSign :: forall a. Algorithm a , sgPresign :: forall a. Seconds -> Algorithm a } -- | Attributes and functions specific to an AWS service. data Service = Service { _svcAbbrev :: !Abbrev , _svcSigner :: !Signer , _svcPrefix :: !ByteString , _svcVersion :: !ByteString , _svcEndpoint :: !(Region -> Endpoint) , _svcTimeout :: !(Maybe Seconds) , _svcCheck :: !(Status -> Bool) , _svcError :: !(Abbrev -> Status -> [Header] -> LazyByteString -> Error) , _svcRetry :: !Retry } serviceSigner :: Lens' Service Signer serviceSigner = lens _svcSigner (\s a -> s { _svcSigner = a }) serviceEndpoint :: Setter' Service Endpoint serviceEndpoint = sets (\f s -> s { _svcEndpoint = \r -> f (_svcEndpoint s r) }) serviceTimeout :: Lens' Service (Maybe Seconds) serviceTimeout = lens _svcTimeout (\s a -> s { _svcTimeout = a }) serviceCheck :: Lens' Service (Status -> Bool) serviceCheck = lens _svcCheck (\s a -> s { _svcCheck = a }) serviceRetry :: Lens' Service Retry serviceRetry = lens _svcRetry (\s a -> s { _svcRetry = a }) -- | Construct a 'ClientRequest' using common parameters such as TLS and prevent -- throwing errors when receiving erroneous status codes in respones. clientRequest :: Endpoint -> Maybe Seconds -> ClientRequest clientRequest e t = def { Client.secure = _endpointSecure e , Client.host = _endpointHost e , Client.port = _endpointPort e , Client.redirectCount = 0 , Client.checkStatus = \_ _ _ -> Nothing , Client.responseTimeout = microseconds <$> t } -- | An unsigned request. data Request a = Request { _rqService :: !Service , _rqMethod :: !StdMethod , _rqPath :: !RawPath , _rqQuery :: !QueryString , _rqHeaders :: ![Header] , _rqBody :: !RqBody } rqService :: Lens' (Request a) Service rqService = lens _rqService (\s a -> s { _rqService = a }) rqBody :: Lens' (Request a) RqBody rqBody = lens _rqBody (\s a -> s { _rqBody = a }) rqHeaders :: Lens' (Request a) [Header] rqHeaders = lens _rqHeaders (\s a -> s { _rqHeaders = a }) rqMethod :: Lens' (Request a) StdMethod rqMethod = lens _rqMethod (\s a -> s { _rqMethod = a }) rqPath :: Lens' (Request a) RawPath rqPath = lens _rqPath (\s a -> s { _rqPath = a }) rqQuery :: Lens' (Request a) QueryString rqQuery = lens _rqQuery (\s a -> s { _rqQuery = a }) rqSign :: Algorithm a rqSign x = sgSign (_svcSigner (_rqService x)) x rqPresign :: Seconds -> Algorithm a rqPresign ex x = sgPresign (_svcSigner (_rqService x)) ex x type Response a = (Status, Rs a) -- | Specify how a request can be de/serialised. class AWSRequest a where -- | The successful, expected response associated with a request. type Rs a :: * request :: a -> Request a response :: MonadResource m => Logger -> Service -> Proxy a -> ClientResponse -> m (Response a) -- | Access key credential. newtype AccessKey = AccessKey ByteString deriving (Eq, Show, IsString, ToText, ToByteString, ToLog) -- | Secret key credential. newtype SecretKey = SecretKey ByteString deriving (Eq, IsString, ToText, ToByteString) -- | A session token used by STS to temporarily authorise access to -- an AWS resource. newtype SessionToken = SessionToken ByteString deriving (Eq, IsString, ToText, ToByteString) -- | The authorisation environment. data AuthEnv = AuthEnv { _authAccess :: !AccessKey , _authSecret :: !SecretKey , _authToken :: Maybe SessionToken , _authExpiry :: Maybe UTCTime } instance ToLog AuthEnv where build AuthEnv{..} = buildLines [ "[Amazonka Auth] {" , " access key = ****" <> key _authAccess , " secret key = ****" , " security token = " <> build (const "****" <$> _authToken :: Maybe Builder) , " expiry = " <> build _authExpiry , "}" ] where -- An attempt to preserve sanity when debugging which keys -- have been loaded by the auth module. key (AccessKey k) = build . BS.reverse . BS.take 6 $ BS.reverse k instance FromJSON AuthEnv where parseJSON = withObject "AuthEnv" $ \o -> AuthEnv <$> f AccessKey (o .: "AccessKeyId") <*> f SecretKey (o .: "SecretAccessKey") <*> fmap (f SessionToken) (o .:? "Token") <*> o .:? "Expiration" where f g = fmap (g . Text.encodeUtf8) -- | An authorisation environment containing AWS credentials, and potentially -- a reference which can be refreshed out-of-band as temporary credentials expire. data Auth = Ref ThreadId (IORef AuthEnv) | Auth AuthEnv instance ToLog Auth where build (Ref t _) = "[Amazonka Auth] { <thread:" <> build (show t) <> "> }" build (Auth e) = build e withAuth :: MonadIO m => Auth -> (AuthEnv -> m a) -> m a withAuth (Ref _ r) f = liftIO (readIORef r) >>= f withAuth (Auth e) f = f e -- | The sum of available AWS regions. data Region = Ireland -- ^ Europe / eu-west-1 | Frankfurt -- ^ Europe / eu-central-1 | Tokyo -- ^ Asia Pacific / ap-northeast-1 | Singapore -- ^ Asia Pacific / ap-southeast-1 | Sydney -- ^ Asia Pacific / ap-southeast-2 | Beijing -- ^ China / cn-north-1 | NorthVirginia -- ^ US / us-east-1 | NorthCalifornia -- ^ US / us-west-1 | Oregon -- ^ US / us-west-2 | GovCloud -- ^ AWS GovCloud / us-gov-west-1 | GovCloudFIPS -- ^ AWS GovCloud (FIPS 140-2) S3 Only / fips-us-gov-west-1 | SaoPaulo -- ^ South America / sa-east-1 deriving (Eq, Ord, Read, Show, Data, Typeable, Generic) instance Hashable Region instance FromText Region where parser = takeLowerText >>= \case "eu-west-1" -> pure Ireland "eu-central-1" -> pure Frankfurt "ap-northeast-1" -> pure Tokyo "ap-southeast-1" -> pure Singapore "ap-southeast-2" -> pure Sydney "cn-north-1" -> pure Beijing "us-east-1" -> pure NorthVirginia "us-west-2" -> pure Oregon "us-west-1" -> pure NorthCalifornia "us-gov-west-1" -> pure GovCloud "fips-us-gov-west-1" -> pure GovCloudFIPS "sa-east-1" -> pure SaoPaulo e -> fromTextError $ "Failure parsing Region from " <> e instance ToText Region where toText = \case Ireland -> "eu-west-1" Frankfurt -> "eu-central-1" Tokyo -> "ap-northeast-1" Singapore -> "ap-southeast-1" Sydney -> "ap-southeast-2" Beijing -> "cn-north-1" NorthVirginia -> "us-east-1" NorthCalifornia -> "us-west-1" Oregon -> "us-west-2" GovCloud -> "us-gov-west-1" GovCloudFIPS -> "fips-us-gov-west-1" SaoPaulo -> "sa-east-1" instance ToByteString Region instance ToLog Region where build = build . toBS instance FromXML Region where parseXML = parseXMLText "Region" instance ToXML Region where toXML = toXMLText -- | An integral value representing seconds. newtype Seconds = Seconds Int deriving ( Eq , Ord , Read , Show , Enum , Num , Bounded , Integral , Real , Data , Typeable , Generic , ToQuery , ToByteString , ToText ) instance ToLog Seconds where build s = build (seconds s) <> "s" seconds :: Seconds -> Int seconds (Seconds n) | n < 0 = 0 | otherwise = n microseconds :: Seconds -> Int microseconds = (1000000 *) . seconds _Coerce :: (Coercible a b, Coercible b a) => Iso' a b _Coerce = iso coerce coerce -- | Invalid Iso, should be a Prism but exists for ease of composition -- with the current 'Lens . Iso' chaining to hide internal types from the user. _Default :: Monoid a => Iso' (Maybe a) a _Default = iso f Just where f (Just x) = x f Nothing = mempty
fmapfmapfmap/amazonka
core/src/Network/AWS/Types.hs
mpl-2.0
20,701
0
15
5,925
4,770
2,650
2,120
516
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Calendar.Settings.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns all user settings for the authenticated user. -- -- /See:/ <https://developers.google.com/google-apps/calendar/firstapp Calendar API Reference> for @calendar.settings.list@. module Network.Google.Resource.Calendar.Settings.List ( -- * REST Resource SettingsListResource -- * Creating a Request , settingsList , SettingsList -- * Request Lenses , slSyncToken , slPageToken , slMaxResults ) where import Network.Google.AppsCalendar.Types import Network.Google.Prelude -- | A resource alias for @calendar.settings.list@ method which the -- 'SettingsList' request conforms to. type SettingsListResource = "calendar" :> "v3" :> "users" :> "me" :> "settings" :> QueryParam "syncToken" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Int32) :> QueryParam "alt" AltJSON :> Get '[JSON] Settings -- | Returns all user settings for the authenticated user. -- -- /See:/ 'settingsList' smart constructor. data SettingsList = SettingsList' { _slSyncToken :: !(Maybe Text) , _slPageToken :: !(Maybe Text) , _slMaxResults :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SettingsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'slSyncToken' -- -- * 'slPageToken' -- -- * 'slMaxResults' settingsList :: SettingsList settingsList = SettingsList' {_slSyncToken = Nothing, _slPageToken = Nothing, _slMaxResults = Nothing} -- | Token obtained from the nextSyncToken field returned on the last page of -- results from the previous list request. It makes the result of this list -- request contain only entries that have changed since then. If the -- syncToken expires, the server will respond with a 410 GONE response code -- and the client should clear its storage and perform a full -- synchronization without any syncToken. Learn more about incremental -- synchronization. Optional. The default is to return all entries. slSyncToken :: Lens' SettingsList (Maybe Text) slSyncToken = lens _slSyncToken (\ s a -> s{_slSyncToken = a}) -- | Token specifying which result page to return. Optional. slPageToken :: Lens' SettingsList (Maybe Text) slPageToken = lens _slPageToken (\ s a -> s{_slPageToken = a}) -- | Maximum number of entries returned on one result page. By default the -- value is 100 entries. The page size can never be larger than 250 -- entries. Optional. slMaxResults :: Lens' SettingsList (Maybe Int32) slMaxResults = lens _slMaxResults (\ s a -> s{_slMaxResults = a}) . mapping _Coerce instance GoogleRequest SettingsList where type Rs SettingsList = Settings type Scopes SettingsList = '["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly", "https://www.googleapis.com/auth/calendar.settings.readonly"] requestClient SettingsList'{..} = go _slSyncToken _slPageToken _slMaxResults (Just AltJSON) appsCalendarService where go = buildClient (Proxy :: Proxy SettingsListResource) mempty
brendanhay/gogol
gogol-apps-calendar/gen/Network/Google/Resource/Calendar/Settings/List.hs
mpl-2.0
4,140
0
16
926
507
301
206
72
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ElasticTranscoder.ListJobsByPipeline -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | The ListJobsByPipeline operation gets a list of the jobs currently in a -- pipeline. -- -- Elastic Transcoder returns all of the jobs currently in the specified -- pipeline. The response body contains one element for each job that satisfies -- the search criteria. -- -- <http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/ListJobsByPipeline.html> module Network.AWS.ElasticTranscoder.ListJobsByPipeline ( -- * Request ListJobsByPipeline -- ** Request constructor , listJobsByPipeline -- ** Request lenses , ljbpAscending , ljbpPageToken , ljbpPipelineId -- * Response , ListJobsByPipelineResponse -- ** Response constructor , listJobsByPipelineResponse -- ** Response lenses , ljbprJobs , ljbprNextPageToken ) where import Network.AWS.Prelude import Network.AWS.Request.RestJSON import Network.AWS.ElasticTranscoder.Types import qualified GHC.Exts data ListJobsByPipeline = ListJobsByPipeline { _ljbpAscending :: Maybe Text , _ljbpPageToken :: Maybe Text , _ljbpPipelineId :: Text } deriving (Eq, Ord, Read, Show) -- | 'ListJobsByPipeline' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ljbpAscending' @::@ 'Maybe' 'Text' -- -- * 'ljbpPageToken' @::@ 'Maybe' 'Text' -- -- * 'ljbpPipelineId' @::@ 'Text' -- listJobsByPipeline :: Text -- ^ 'ljbpPipelineId' -> ListJobsByPipeline listJobsByPipeline p1 = ListJobsByPipeline { _ljbpPipelineId = p1 , _ljbpAscending = Nothing , _ljbpPageToken = Nothing } -- | To list jobs in chronological order by the date and time that they were -- submitted, enter 'true'. To list jobs in reverse chronological order, enter 'false'. ljbpAscending :: Lens' ListJobsByPipeline (Maybe Text) ljbpAscending = lens _ljbpAscending (\s a -> s { _ljbpAscending = a }) -- | When Elastic Transcoder returns more than one page of results, use 'pageToken' -- in subsequent 'GET' requests to get each successive page of results. ljbpPageToken :: Lens' ListJobsByPipeline (Maybe Text) ljbpPageToken = lens _ljbpPageToken (\s a -> s { _ljbpPageToken = a }) -- | The ID of the pipeline for which you want to get job information. ljbpPipelineId :: Lens' ListJobsByPipeline Text ljbpPipelineId = lens _ljbpPipelineId (\s a -> s { _ljbpPipelineId = a }) data ListJobsByPipelineResponse = ListJobsByPipelineResponse { _ljbprJobs :: List "Jobs" Job' , _ljbprNextPageToken :: Maybe Text } deriving (Eq, Read, Show) -- | 'ListJobsByPipelineResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ljbprJobs' @::@ ['Job''] -- -- * 'ljbprNextPageToken' @::@ 'Maybe' 'Text' -- listJobsByPipelineResponse :: ListJobsByPipelineResponse listJobsByPipelineResponse = ListJobsByPipelineResponse { _ljbprJobs = mempty , _ljbprNextPageToken = Nothing } -- | An array of 'Job' objects that are in the specified pipeline. ljbprJobs :: Lens' ListJobsByPipelineResponse [Job'] ljbprJobs = lens _ljbprJobs (\s a -> s { _ljbprJobs = a }) . _List -- | A value that you use to access the second and subsequent pages of results, -- if any. When the jobs in the specified pipeline fit on one page or when -- you've reached the last page of results, the value of 'NextPageToken' is 'null'. ljbprNextPageToken :: Lens' ListJobsByPipelineResponse (Maybe Text) ljbprNextPageToken = lens _ljbprNextPageToken (\s a -> s { _ljbprNextPageToken = a }) instance ToPath ListJobsByPipeline where toPath ListJobsByPipeline{..} = mconcat [ "/2012-09-25/jobsByPipeline/" , toText _ljbpPipelineId ] instance ToQuery ListJobsByPipeline where toQuery ListJobsByPipeline{..} = mconcat [ "Ascending" =? _ljbpAscending , "PageToken" =? _ljbpPageToken ] instance ToHeaders ListJobsByPipeline instance ToJSON ListJobsByPipeline where toJSON = const (toJSON Empty) instance AWSRequest ListJobsByPipeline where type Sv ListJobsByPipeline = ElasticTranscoder type Rs ListJobsByPipeline = ListJobsByPipelineResponse request = get response = jsonResponse instance FromJSON ListJobsByPipelineResponse where parseJSON = withObject "ListJobsByPipelineResponse" $ \o -> ListJobsByPipelineResponse <$> o .:? "Jobs" .!= mempty <*> o .:? "NextPageToken" instance AWSPager ListJobsByPipeline where page rq rs | stop (rs ^. ljbprNextPageToken) = Nothing | otherwise = (\x -> rq & ljbpPageToken ?~ x) <$> (rs ^. ljbprNextPageToken)
dysinger/amazonka
amazonka-elastictranscoder/gen/Network/AWS/ElasticTranscoder/ListJobsByPipeline.hs
mpl-2.0
5,645
0
12
1,189
751
443
308
80
1
module Kata(tailSwap) where import Data.List.Split tailSwap :: (String, String) -> (String, String) tailSwap (a, b) = let (a1 : (a2 : _)) = splitOn ":" a (b1 : (b2 : _)) = splitOn ":" b in (a1 ++ ":" ++ b2, b1 ++ ":" ++ a2) --
ice1000/OI-codes
codewars/1-100/tail-swap.hs
agpl-3.0
254
0
12
74
129
72
57
6
1
module Network.Haskoin.Wallet.KeyRing ( -- *Database KeyRings initWallet , newKeyRing , keyRings , keyRingSource , getKeyRing -- *Database Accounts , accounts , accountSource , newAccount , addAccountKeys , getAccount , isMultisigAccount , isReadAccount , isCompleteAccount -- *Database Addresses , getAddress , addressSourceAll , addressSource , addressPage , unusedAddresses , addressCount , setAddrLabel , addressPrvKey , useAddress , generateAddrs , setAccountGap , firstAddrTime , getPathRedeem , getPathPubKey -- *Database Bloom Filter , getBloomFilter -- * Helpers , subSelectAddrCount ) where import Control.Monad (unless, when, liftM) import Control.Monad.Trans (MonadIO, liftIO) import Control.Monad.Base (MonadBase) import Control.Monad.Catch (MonadThrow) import Control.Monad.Trans.Resource (MonadResource) import Control.Exception (throwIO, throw) import Data.Text (Text, unpack) import Data.Maybe (mapMaybe, listToMaybe) import Data.Time.Clock (getCurrentTime) import Data.Conduit (Source, mapOutput, await, ($$)) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Data.List (nub) import Data.Word (Word32) import qualified Data.ByteString as BS (ByteString, null) import qualified Database.Persist as P (updateWhere, update , (=.)) import Database.Esqueleto ( Value(..), SqlExpr, SqlQuery , InnerJoin(..), on , select, from, where_, val, sub_select, countRows, count, unValue , orderBy, limit, asc, desc, offset, selectSource, get , max_, not_, isNothing, case_, when_, then_, else_ , (^.), (==.), (&&.), (>.), (-.), (<.) -- Reexports from Database.Persist , SqlPersistT, Entity(..) , getBy, insertUnique, insertMany_, insert_ ) import Network.Haskoin.Crypto import Network.Haskoin.Block import Network.Haskoin.Script import Network.Haskoin.Node import Network.Haskoin.Util import Network.Haskoin.Constants import Network.Haskoin.Node.HeaderTree import Network.Haskoin.Wallet.Types import Network.Haskoin.Wallet.Model {- Initialization -} initWallet :: MonadIO m => Double -> SqlPersistT m () initWallet fpRate = do prevConfigRes <- select $ from $ \c -> return $ count $ c ^. KeyRingConfigId let cnt = maybe 0 unValue $ listToMaybe prevConfigRes if cnt == (0 :: Int) then do time <- liftIO getCurrentTime -- Create an initial bloom filter -- TODO: Compute a random nonce let bloom = bloomCreate (filterLen 0) fpRate 0 BloomUpdateNone insert_ $ KeyRingConfig { keyRingConfigHeight = 0 , keyRingConfigBlock = headerHash genesisHeader , keyRingConfigBloomFilter = bloom , keyRingConfigBloomElems = 0 , keyRingConfigBloomFp = fpRate , keyRingConfigVersion = 1 , keyRingConfigCreated = time } else return () -- Nothing to do {- KeyRing -} -- | Create a new KeyRing from a seed newKeyRing :: MonadIO m => KeyRingName -> BS.ByteString -> SqlPersistT m (Entity KeyRing) newKeyRing name seed | BS.null seed = liftIO . throwIO $ WalletException "The seed is empty" | otherwise = do now <- liftIO getCurrentTime let keyRing = KeyRing { keyRingName = name , keyRingMaster = makeXPrvKey seed , keyRingCreated = now } insertUnique keyRing >>= \resM -> case resM of Just ki -> return (Entity ki keyRing) _ -> liftIO . throwIO $ WalletException $ unwords [ "KeyRing", unpack name, "already exists" ] keyRings :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => SqlPersistT m [KeyRing] keyRings = liftM (map entityVal) $ select $ from return -- | Stream all KeyRings keyRingSource :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Source (SqlPersistT m) KeyRing keyRingSource = mapOutput entityVal $ selectSource $ from return -- Helper functions to get a KeyRing if it exists, or throw an exception -- otherwise. getKeyRing :: MonadIO m => KeyRingName -> SqlPersistT m (Entity KeyRing) getKeyRing name = getBy (UniqueKeyRing name) >>= \resM -> case resM of Just keyRingEnt -> return keyRingEnt _ -> liftIO . throwIO $ WalletException $ unwords [ "KeyRing", unpack name, "does not exist." ] {- Account -} -- | Fetch all the accounts in a keyring accounts :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => KeyRingId -> SqlPersistT m [KeyRingAccount] accounts ki = liftM (map entityVal) $ select $ accountsFrom ki -- | Stream all accounts in a keyring accountSource :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => KeyRingId -> Source (SqlPersistT m) KeyRingAccount accountSource ki = mapOutput entityVal $ selectSource $ accountsFrom ki accountsFrom :: KeyRingId -> SqlQuery (SqlExpr (Entity KeyRingAccount)) accountsFrom ki = from $ \a -> do where_ $ a ^. KeyRingAccountKeyRing ==. val ki return a -- | Create a new account newAccount :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRing -> AccountName -> AccountType -> [XPubKey] -> SqlPersistT m (Entity KeyRingAccount) newAccount (Entity ki keyRing) accountName accountType extraKeys = do unless (validAccountType accountType) $ liftIO . throwIO $ WalletException "Invalid account type" -- Get the next account derivation derivM <- if accountTypeRead accountType then return Nothing else liftM Just $ nextAccountDeriv ki -- Derive the next account key let f d = [ deriveXPubKey (derivePath d $ keyRingMaster keyRing) ] keys = (maybe [] f derivM) ++ extraKeys -- Build the account now <- liftIO getCurrentTime let acc = KeyRingAccount { keyRingAccountKeyRing = ki , keyRingAccountName = accountName , keyRingAccountType = accountType , keyRingAccountDerivation = derivM , keyRingAccountKeys = keys , keyRingAccountGap = 0 , keyRingAccountCreated = now } -- Check if all the keys are valid unless (isValidAccKeys acc) $ liftIO . throwIO $ WalletException "Invalid account keys" -- Insert our account in the database let canSetGap = isCompleteAccount acc newAcc = acc{ keyRingAccountGap = if canSetGap then 10 else 0 } insertUnique newAcc >>= \resM -> case resM of -- The account got created. Just ai -> do let accE = Entity ai newAcc -- If we can set the gap, create the gap addresses when canSetGap $ do _ <- createAddrs accE AddressExternal 20 _ <- createAddrs accE AddressInternal 20 return () return accE -- The account already exists Nothing -> liftIO . throwIO $ WalletException $ unwords [ "Account", unpack accountName, "already exists" ] -- | Add new thirdparty keys to a multisignature account. This function can -- fail if the multisignature account already has all required keys. addAccountKeys :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -- ^ Account Entity -> [XPubKey] -- ^ Thirdparty public keys to add -> SqlPersistT m KeyRingAccount -- ^ Account information addAccountKeys (Entity ai acc) keys -- We can only add keys on incomplete accounts | isCompleteAccount acc = liftIO . throwIO $ WalletException "The account is already complete" | null keys || (not $ isValidAccKeys accKeys) = liftIO . throwIO $ WalletException "Invalid account keys" | otherwise = do let canSetGap = isCompleteAccount accKeys updGap = if canSetGap then [ KeyRingAccountGap P.=. 10 ] else [] newAcc = accKeys{ keyRingAccountGap = if canSetGap then 10 else 0 } -- Update the account with the keys and the new gap if it is complete P.update ai $ (KeyRingAccountKeys P.=. newKeys) : updGap -- If we can set the gap, create the gap addresses when canSetGap $ do let accE = Entity ai newAcc _ <- createAddrs accE AddressExternal 20 _ <- createAddrs accE AddressInternal 20 return () return newAcc where newKeys = keyRingAccountKeys acc ++ keys accKeys = acc{ keyRingAccountKeys = newKeys } isValidAccKeys :: KeyRingAccount -> Bool isValidAccKeys KeyRingAccount{..} = case keyRingAccountType of AccountRegular _ -> length keyRingAccountKeys == 1 -- read-only accounts can have 0 keys. Otherwise 1 key is required. AccountMultisig r _ n -> goMultisig n (if r then 0 else 1) where goMultisig n minLen = length keyRingAccountKeys == length (nub keyRingAccountKeys) && length keyRingAccountKeys <= n && length keyRingAccountKeys >= minLen -- | Compute the next derivation path for a new account nextAccountDeriv :: MonadIO m => KeyRingId -> SqlPersistT m HardPath nextAccountDeriv ki = do lastRes <- select $ from $ \a -> do where_ ( a ^. KeyRingAccountKeyRing ==. val ki &&. not_ (isNothing (a ^. KeyRingAccountDerivation)) ) orderBy [ desc (a ^. KeyRingAccountId) ] limit 1 return $ a ^. KeyRingAccountDerivation return $ case lastRes of (Value (Just (prev :| i)):_) -> prev :| (i + 1) _ -> Deriv :| 0 -- Helper functions to get an Account if it exists, or throw an exception -- otherwise. getAccount :: MonadIO m => KeyRingName -> AccountName -> SqlPersistT m (KeyRing, Entity KeyRingAccount) getAccount keyRingName accountName = do as <- select $ from $ \(k `InnerJoin` a) -> do on $ a ^. KeyRingAccountKeyRing ==. k ^. KeyRingId where_ ( k ^. KeyRingName ==. val keyRingName &&. a ^. KeyRingAccountName ==. val accountName ) return (k, a) case as of ((Entity _ k, accEnt):_) -> return (k, accEnt) _ -> liftIO . throwIO $ WalletException $ unwords [ "Account", unpack accountName, "does not exist" ] {- Addresses -} -- | Get an address if it exists, or throw an exception otherwise. Fetching -- addresses in the hidden gap will also throw an exception. getAddress :: MonadIO m => Entity KeyRingAccount -- ^ Account Entity -> AddressType -- ^ Address type -> KeyIndex -- ^ Derivation index (key) -> SqlPersistT m (Entity KeyRingAddr) -- ^ Address getAddress accE@(Entity ai _) addrType index = do res <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType &&. x ^. KeyRingAddrIndex ==. val index &&. x ^. KeyRingAddrIndex <. subSelectAddrCount accE addrType ) limit 1 return x case res of (addrE:_) -> return addrE _ -> liftIO . throwIO $ WalletException $ unwords [ "Invalid address index", show index ] -- | Stream all addresses in the wallet, including hidden gap addresses. This -- is useful for building a bloom filter. addressSourceAll :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Source (SqlPersistT m) KeyRingAddr addressSourceAll = mapOutput entityVal $ selectSource $ from return -- | Stream all addresses in one account. Hidden gap addresses are not included. addressSource :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -- ^ Account Entity -> AddressType -- ^ Address Type -> Source (SqlPersistT m) KeyRingAddr -- ^ Source of addresses addressSource accE@(Entity ai _) addrType = mapOutput entityVal $ selectSource $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType &&. x ^. KeyRingAddrIndex <. subSelectAddrCount accE addrType ) return x -- | Get addresses by pages. addressPage :: MonadIO m => Entity KeyRingAccount -- ^ Account Entity -> AddressType -- ^ Address type -> PageRequest -- ^ Page request -> SqlPersistT m ([KeyRingAddr], Word32) -- ^ Page result addressPage accE@(Entity ai _) addrType page@PageRequest{..} | validPageRequest page = do cnt <- addressCount accE addrType let (d, m) = cnt `divMod` pageLen maxPage = max 1 $ d + min 1 m when (pageNum > maxPage) $ liftIO . throwIO $ WalletException $ unwords [ "Invalid page number", show pageNum ] if cnt == 0 then return ([], maxPage) else do res <- liftM (map entityVal) $ select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType &&. x ^. KeyRingAddrIndex <. val cnt ) let order = if pageReverse then asc else desc orderBy [ order (x ^. KeyRingAddrIndex) ] limit $ fromIntegral pageLen offset $ fromIntegral $ (pageNum - 1) * pageLen return x -- Flip the order back to ASC if we had it DEC let f = if pageReverse then id else reverse return (f res, maxPage) | otherwise = liftIO . throwIO $ WalletException $ concat [ "Invalid page request" , " (Page: ", show pageNum, ", Page size: ", show pageLen, ")" ] -- | Get a count of all the addresses in an account addressCount :: MonadIO m => Entity KeyRingAccount -- ^ Account Entity -> AddressType -- ^ Address type -> SqlPersistT m Word32 -- ^ Address Count addressCount (Entity ai acc) addrType = do res <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType ) return countRows let cnt = maybe 0 unValue $ listToMaybe res return $ if cnt > keyRingAccountGap acc then cnt - keyRingAccountGap acc else 0 -- | Get a list of all unused addresses. unusedAddresses :: MonadIO m => Entity KeyRingAccount -- ^ Account ID -> AddressType -- ^ Address type -> SqlPersistT m [KeyRingAddr] -- ^ Unused addresses unusedAddresses (Entity ai acc) addrType = do liftM (reverse . map entityVal) $ select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType ) orderBy [ desc $ x ^. KeyRingAddrIndex ] limit $ fromIntegral $ keyRingAccountGap acc offset $ fromIntegral $ keyRingAccountGap acc return x -- | Add a label to an address. setAddrLabel :: MonadIO m => Entity KeyRingAccount -- ^ Account ID -> KeyIndex -- ^ Derivation index -> AddressType -- ^ Address type -> Text -- ^ New label -> SqlPersistT m KeyRingAddr setAddrLabel accE i addrType label = do Entity addrI addr <- getAddress accE addrType i P.update addrI [ KeyRingAddrLabel P.=. label ] return $ addr{ keyRingAddrLabel = label } -- | Returns the private key of an address. addressPrvKey :: MonadIO m => KeyRing -- ^ KeyRing -> Entity KeyRingAccount -- ^ Account Entity -> KeyIndex -- ^ Derivation index of the address -> AddressType -- ^ Address type -> SqlPersistT m PrvKeyC -- ^ Private key addressPrvKey keyRing accE@(Entity ai _) index addrType = do res <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType &&. x ^. KeyRingAddrIndex ==. val index &&. x ^. KeyRingAddrIndex <. subSelectAddrCount accE addrType ) return (x ^. KeyRingAddrFullDerivation) case res of (Value (Just deriv):_) -> return $ xPrvKey $ derivePath deriv $ keyRingMaster keyRing _ -> liftIO . throwIO $ WalletException "Invalid address" -- | Create new addresses in an account and increment the internal bloom filter. -- This is a low-level function that simply creates the desired amount of new -- addresses in an account, disregarding visible and hidden address gaps. You -- should use the function `setAccountGap` if you want to control the gap of an -- account instead. createAddrs :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -> AddressType -> Word32 -> SqlPersistT m [KeyRingAddr] createAddrs (Entity ai acc) addrType n | n == 0 = liftIO . throwIO $ WalletException $ unwords [ "Invalid value", show n ] | not (isCompleteAccount acc) = liftIO . throwIO $ WalletException $ unwords [ "Keys are still missing from the incomplete account" , unpack $ keyRingAccountName acc ] | otherwise = do now <- liftIO getCurrentTime -- Find the next derivation index from the last address lastRes <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType ) return $ max_ (x ^. KeyRingAddrIndex) let nextI = case lastRes of (Value (Just lastI):_) -> lastI + 1 _ -> 0 build (addr, keyM, rdmM, i) = KeyRingAddr { keyRingAddrAccount = ai , keyRingAddrAddress = addr , keyRingAddrIndex = i , keyRingAddrType = addrType , keyRingAddrLabel = "" -- Full derivation from the master key , keyRingAddrFullDerivation = let f d = toMixed d :/ branchType :/ i in f <$> keyRingAccountDerivation acc -- Partial derivation under the account derivation , keyRingAddrDerivation = Deriv :/ branchType :/ i , keyRingAddrRedeem = rdmM , keyRingAddrKey = keyM , keyRingAddrCreated = now } res = map build $ take (fromIntegral n) $ deriveFrom nextI -- Save the addresses and increment the bloom filter insertMany_ res incrementFilter res return res where -- Branch type (external = 0, internal = 1) branchType = addrTypeIndex addrType deriveFrom = case keyRingAccountType acc of AccountMultisig _ m _ -> let f (a, r, i) = (a, Nothing, Just r, i) deriv = Deriv :/ branchType in map f . derivePathMSAddrs (keyRingAccountKeys acc) deriv m AccountRegular _ -> case keyRingAccountKeys acc of (key:_) -> let f (a, k, i) = (a, Just k, Nothing, i) in map f . derivePathAddrs key (Deriv :/ branchType) [] -> throw $ WalletException $ unwords [ "createAddrs: No key available in regular account" , unpack $ keyRingAccountName acc ] -- | Generate all the addresses up to a certain index generateAddrs :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -> AddressType -> KeyIndex -> SqlPersistT m Int generateAddrs accE@(Entity _ _) addrType genIndex = do cnt <- addressCount accE addrType let toGen = (fromIntegral genIndex) - (fromIntegral cnt) + 1 if toGen > 0 then do _ <- createAddrs accE addrType $ fromIntegral toGen return toGen else return 0 -- | Use an address and make sure we have enough gap addresses after it. -- Returns the new addresses that have been created. useAddress :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => KeyRingAddr -> SqlPersistT m [KeyRingAddr] useAddress KeyRingAddr{..} = do res <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val keyRingAddrAccount &&. x ^. KeyRingAddrType ==. val keyRingAddrType &&. x ^. KeyRingAddrIndex >. val keyRingAddrIndex ) return countRows case res of ((Value cnt):_) -> get keyRingAddrAccount >>= \accM -> case accM of Just acc -> do let accE = Entity keyRingAddrAccount acc gap = fromIntegral (keyRingAccountGap acc) :: Int missing = 2*gap - cnt if missing > 0 then createAddrs accE keyRingAddrType $ fromIntegral missing else return [] _ -> return [] -- Should not happen _ -> return [] -- Should not happen -- | Set the address gap of an account to a new value. This will create new -- internal and external addresses as required. The gap can only be increased, -- not decreased in size. setAccountGap :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -- ^ Account Entity -> Word32 -- ^ New gap value -> SqlPersistT m KeyRingAccount setAccountGap accE@(Entity ai acc) gap | not (isCompleteAccount acc) = liftIO . throwIO $ WalletException $ unwords [ "Keys are still missing from the incomplete account" , unpack $ keyRingAccountName acc ] | missing <= 0 = liftIO . throwIO $ WalletException "The gap of an account can only be increased" | otherwise = do _ <- createAddrs accE AddressExternal $ fromInteger $ missing*2 _ <- createAddrs accE AddressInternal $ fromInteger $ missing*2 P.update ai [ KeyRingAccountGap P.=. gap ] return $ acc{ keyRingAccountGap = gap } where missing = toInteger gap - toInteger (keyRingAccountGap acc) -- Return the creation time of the first address in the wallet. firstAddrTime :: MonadIO m => SqlPersistT m (Maybe Timestamp) firstAddrTime = do res <- select $ from $ \x -> do orderBy [ asc (x ^. KeyRingAddrId) ] limit 1 return $ x ^. KeyRingAddrCreated return $ case res of (Value d:_) -> Just $ toPOSIX d _ -> Nothing where toPOSIX = fromInteger . round . utcTimeToPOSIXSeconds {- Bloom filters -} -- | Add the given addresses to the bloom filter. If the number of elements -- becomes too large, a new bloom filter is computed from scratch. incrementFilter :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => [KeyRingAddr] -> SqlPersistT m () incrementFilter addrs = do (bloom, elems, _) <- getBloomFilter let newElems = elems + (length addrs * 2) if filterLen newElems > filterLen elems then computeNewFilter else setBloomFilter (addToFilter bloom addrs) newElems -- | Generate a new bloom filter from the data in the database computeNewFilter :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => SqlPersistT m () computeNewFilter = do (_, _, fpRate) <- getBloomFilter -- Create a new empty bloom filter -- TODO: Choose a random nonce for the bloom filter -- TODO: Check global bloom filter length limits cntRes <- select $ from $ \x -> return $ count $ x ^. KeyRingAddrId let elems = maybe 0 unValue $ listToMaybe cntRes newBloom = bloomCreate (filterLen elems) fpRate 0 BloomUpdateNone bloom <- addressSourceAll $$ bloomSink newBloom setBloomFilter bloom elems where bloomSink bloom = await >>= \addrM -> case addrM of Just addr -> bloomSink $ addToFilter bloom [addr] _ -> return bloom -- Compute the size of a filter given a number of elements. Scale -- the filter length by powers of 2. filterLen :: Int -> Int filterLen = round . pow2 . ceiling . log2 where pow2 x = (2 :: Double) ** fromInteger x log2 x = logBase (2 :: Double) (fromIntegral x) -- | Add elements to a bloom filter addToFilter :: BloomFilter -> [KeyRingAddr] -> BloomFilter addToFilter bloom addrs = bloom3 where pks = mapMaybe keyRingAddrKey addrs rdms = mapMaybe keyRingAddrRedeem addrs -- Add the Hash160 of the addresses f1 b a = bloomInsert b $ encode' $ getAddrHash a bloom1 = foldl f1 bloom $ map keyRingAddrAddress addrs -- Add the redeem scripts f2 b r = bloomInsert b $ encodeOutputBS r bloom2 = foldl f2 bloom1 rdms -- Add the public keys f3 b p = bloomInsert b $ encode' p bloom3 = foldl f3 bloom2 pks -- | Returns a bloom filter containing all the addresses in this wallet. This -- includes internal and external addresses. The bloom filter can be set on a -- peer connection to filter the transactions received by that peer. getBloomFilter :: MonadIO m => SqlPersistT m (BloomFilter, Int, Double) getBloomFilter = do res <- select $ from $ \c -> do limit 1 return ( c ^. KeyRingConfigBloomFilter , c ^. KeyRingConfigBloomElems , c ^. KeyRingConfigBloomFp ) case res of ((Value b, Value n, Value fp):_) -> return (b, n, fp) _ -> liftIO . throwIO $ WalletException "getBloomFilter: Database not initialized" -- | Save a bloom filter and the number of elements it contains setBloomFilter :: MonadIO m => BloomFilter -> Int -> SqlPersistT m () setBloomFilter bloom elems = P.updateWhere [] [ KeyRingConfigBloomFilter P.=. bloom , KeyRingConfigBloomElems P.=. elems ] -- Helper function to compute the redeem script of a given derivation path -- for a given multisig account. getPathRedeem :: KeyRingAccount -> SoftPath -> RedeemScript getPathRedeem acc@KeyRingAccount{..} deriv = case keyRingAccountType of AccountMultisig _ m _ -> if isCompleteAccount acc then sortMulSig $ PayMulSig pubKeys m else throw $ WalletException $ unwords [ "getPathRedeem: Incomplete multisig account" , unpack keyRingAccountName ] _ -> throw $ WalletException $ unwords [ "getPathRedeem: Account", unpack keyRingAccountName , "is not a multisig account" ] where f = toPubKeyG . xPubKey . derivePubPath deriv pubKeys = map f keyRingAccountKeys -- Helper function to compute the public key of a given derivation path for -- a given non-multisig account. getPathPubKey :: KeyRingAccount -> SoftPath -> PubKeyC getPathPubKey acc@KeyRingAccount{..} deriv | isMultisigAccount acc = throw $ WalletException $ unwords [ "getPathPubKey: Account", unpack keyRingAccountName , "is not a regular non-multisig account" ] | otherwise = case keyRingAccountKeys of (key:_) -> xPubKey $ derivePubPath deriv key _ -> throw $ WalletException $ unwords [ "getPathPubKey: No keys are available in account" , unpack keyRingAccountName ] {- Helpers -} subSelectAddrCount :: Entity KeyRingAccount -> AddressType -> SqlExpr (Value KeyIndex) subSelectAddrCount (Entity ai acc) addrType = sub_select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType ) let gap = val $ keyRingAccountGap acc return $ case_ [ when_ (countRows >. gap) then_ (countRows -. gap) ] (else_ $ val 0) validMultisigParams :: Int -> Int -> Bool validMultisigParams m n = n >= 1 && n <= 15 && m >= 1 && m <= n validAccountType :: AccountType -> Bool validAccountType t = case t of AccountRegular _ -> True AccountMultisig _ m n -> validMultisigParams m n isMultisigAccount :: KeyRingAccount -> Bool isMultisigAccount acc = case keyRingAccountType acc of AccountRegular _ -> False AccountMultisig _ _ _ -> True isReadAccount :: KeyRingAccount -> Bool isReadAccount acc = case keyRingAccountType acc of AccountRegular r -> r AccountMultisig r _ _ -> r isCompleteAccount :: KeyRingAccount -> Bool isCompleteAccount acc = case keyRingAccountType acc of AccountRegular _ -> length (keyRingAccountKeys acc) == 1 AccountMultisig _ _ n -> length (keyRingAccountKeys acc) == n
plaprade/haskoin-wallet
Network/Haskoin/Wallet/KeyRing.hs
unlicense
29,202
0
25
8,920
7,250
3,704
3,546
-1
-1
module Triangle (area) where area :: Float -> Float -> Float area b h = b * h
tonilopezmr/Learning-Haskell
Exercises/3/Exercise 1/Triangle.hs
apache-2.0
80
0
6
20
36
20
16
3
1
module KeyBind ( Key (..) , Keyset , updateKeyset , keysetToXY ) where import Data.Complex import Data.Set import Graphics.UI.SDL import Graphics.UI.SDL.Keysym data Key = A | B | C | RB | LB | UB | DB | QUIT deriving (Eq, Ord, Show) type Keyset = Set Key eventToKey :: Event -> Keyset -> Keyset eventToKey Quit = insert QUIT eventToKey (KeyDown k) = normalKey insert k eventToKey (KeyUp k) = normalKey delete k eventToKey _ = id normalKey :: (Key -> Keyset -> Keyset) -> Keysym -> Keyset -> Keyset normalKey f (Keysym {symKey = k}) | k == SDLK_z = f A | k == SDLK_x = f B | k == SDLK_c = f C | k == SDLK_RIGHT = f RB | k == SDLK_LEFT = f LB | k == SDLK_UP = f UB | k == SDLK_DOWN = f DB | k == SDLK_ESCAPE= f QUIT | otherwise = id updateKeyset :: Keyset -> IO Keyset updateKeyset k = do event <- pollEvent case event of NoEvent -> return k some -> updateKeyset (eventToKey some k) keysetToXY :: (RealFloat a) => Keyset -> Complex a keysetToXY k = (right - left) :+ (up - down) where right = b2i $ member RB k left = b2i $ member LB k up = b2i $ member UB k down = b2i $ member DB k b2i False = 0 b2i True = 1
c000/PaperPuppet
src/KeyBind.hs
bsd-3-clause
1,216
0
12
345
532
270
262
42
2
{-# LANGUAGE CPP , DeriveDataTypeable , FlexibleInstances , FlexibleContexts , MultiParamTypeClasses , TypeFamilies , UndecidableInstances #-} {- | Copyright : (c) Andy Sonnenburg 2013 License : BSD3 Maintainer : [email protected] -} module Data.Tuple.IO ( module Data.Tuple.MTuple , IOTuple , ArraySlice , IOUTuple ) where #ifdef MODULE_Control_Monad_ST_Safe import Control.Monad.ST.Safe (RealWorld) #else import Control.Monad.ST (RealWorld) #endif import Data.ByteArraySlice import Data.Tuple.Array import Data.Tuple.ByteArray import Data.Tuple.ITuple import Data.Tuple.MTuple import Data.Typeable (Typeable) newtype IOTuple a = IOTuple { unIOTuple :: ArrayTuple RealWorld a } deriving (Eq, Typeable) instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MTuple IOTuple t IO where thawTuple = fmap IOTuple . thawTuple freezeTuple = freezeTuple . unIOTuple instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MField1 IOTuple t IO where read1 = read1 . unIOTuple write1 = write1 . unIOTuple instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MField2 IOTuple t IO where read2 = read2 . unIOTuple write2 = write2 . unIOTuple instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MField3 IOTuple t IO where read3 = read3 . unIOTuple write3 = write3 . unIOTuple instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MField4 IOTuple t IO where read4 = read4 . unIOTuple write4 = write4 . unIOTuple instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MField5 IOTuple t IO where read5 = read5 . unIOTuple write5 = write5 . unIOTuple instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MField6 IOTuple t IO where read6 = read6 . unIOTuple write6 = write6 . unIOTuple instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MField7 IOTuple t IO where read7 = read7 . unIOTuple write7 = write7 . unIOTuple instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MField8 IOTuple t IO where read8 = read8 . unIOTuple write8 = write8 . unIOTuple instance ( ITuple t , ArraySlice (Tuple (ListRep t)) ) => MField9 IOTuple t IO where read9 = read9 . unIOTuple write9 = write9 . unIOTuple newtype IOUTuple a = IOUTuple { unIOUTuple :: ByteArrayTuple RealWorld a } deriving (Eq, Typeable) instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) ) => MTuple IOUTuple t IO where thawTuple = fmap IOUTuple . thawTuple freezeTuple = freezeTuple . unIOUTuple instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) , ByteArraySlice (Field1 t) ) => MField1 IOUTuple t IO where read1 = read1 . unIOUTuple write1 = write1 . unIOUTuple instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) , ByteArraySlice (Field1 t) , ByteArraySlice (Field2 t) ) => MField2 IOUTuple t IO where read2 = read2 . unIOUTuple write2 = write2 . unIOUTuple instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) , ByteArraySlice (Field1 t) , ByteArraySlice (Field2 t) , ByteArraySlice (Field3 t) ) => MField3 IOUTuple t IO where read3 = read3 . unIOUTuple write3 = write3 . unIOUTuple instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) , ByteArraySlice (Field1 t) , ByteArraySlice (Field2 t) , ByteArraySlice (Field3 t) , ByteArraySlice (Field4 t) ) => MField4 IOUTuple t IO where read4 = read4 . unIOUTuple write4 = write4 . unIOUTuple instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) , ByteArraySlice (Field1 t) , ByteArraySlice (Field2 t) , ByteArraySlice (Field3 t) , ByteArraySlice (Field4 t) , ByteArraySlice (Field5 t) ) => MField5 IOUTuple t IO where read5 = read5 . unIOUTuple write5 = write5 . unIOUTuple instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) , ByteArraySlice (Field1 t) , ByteArraySlice (Field2 t) , ByteArraySlice (Field3 t) , ByteArraySlice (Field4 t) , ByteArraySlice (Field5 t) , ByteArraySlice (Field6 t) ) => MField6 IOUTuple t IO where read6 = read6 . unIOUTuple write6 = write6 . unIOUTuple instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) , ByteArraySlice (Field1 t) , ByteArraySlice (Field2 t) , ByteArraySlice (Field3 t) , ByteArraySlice (Field4 t) , ByteArraySlice (Field5 t) , ByteArraySlice (Field6 t) , ByteArraySlice (Field7 t) ) => MField7 IOUTuple t IO where read7 = read7 . unIOUTuple write7 = write7 . unIOUTuple instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) , ByteArraySlice (Field1 t) , ByteArraySlice (Field2 t) , ByteArraySlice (Field3 t) , ByteArraySlice (Field4 t) , ByteArraySlice (Field5 t) , ByteArraySlice (Field6 t) , ByteArraySlice (Field7 t) , ByteArraySlice (Field8 t) ) => MField8 IOUTuple t IO where read8 = read8 . unIOUTuple write8 = write8 . unIOUTuple instance ( ITuple t , ByteArraySlice (Tuple (ListRep t)) , ByteArraySlice (Field1 t) , ByteArraySlice (Field2 t) , ByteArraySlice (Field3 t) , ByteArraySlice (Field4 t) , ByteArraySlice (Field5 t) , ByteArraySlice (Field6 t) , ByteArraySlice (Field7 t) , ByteArraySlice (Field8 t) , ByteArraySlice (Field9 t) ) => MField9 IOUTuple t IO where read9 = read9 . unIOUTuple write9 = write9 . unIOUTuple
sonyandy/var
src/Data/Tuple/IO.hs
bsd-3-clause
5,909
0
10
1,754
1,827
963
864
171
0
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module Control.ConstraintClasses.Key ( -- * Key classes CKey ) where import Prelude hiding (lookup) import Data.Functor.Identity import Data.Functor.Product import Data.Functor.Sum import Data.Functor.Compose -- vector import qualified Data.Vector as Vector import qualified Data.Vector.Storable as VectorStorable import qualified Data.Vector.Unboxed as VectorUnboxed -------------------------------------------------------------------------------- -- | Equivalent to the @Key@ type family. type family CKey (f :: * -> *) type instance CKey [] = Int type instance CKey Identity = () type instance CKey (Compose f g) = (CKey f, CKey g) type instance CKey (Product f g) = Either (CKey f) (CKey g) type instance CKey (Sum f g) = (CKey f, CKey g) type instance CKey Vector.Vector = Int type instance CKey VectorStorable.Vector = Int type instance CKey VectorUnboxed.Vector = Int
guaraqe/constraint-classes
src/Control/ConstraintClasses/Key.hs
bsd-3-clause
1,028
0
7
155
250
153
97
24
0
module Khronos.AssignModules ( assignModules ) where import Algebra.Graph.AdjacencyIntMap hiding ( empty ) import qualified Data.IntMap.Strict as IntMap import qualified Data.IntSet as Set import qualified Data.List.Extra as List import qualified Data.Map as Map import qualified Data.Set import qualified Data.Text.Extra as T import Data.Vector ( Vector ) import qualified Data.Vector.Extra as V import Data.Version import Polysemy import Polysemy.Input import Polysemy.State import Relude hiding ( State , ask , evalState , execState , get , gets , modify' , put , runState ) import Error import Haskell import Render.Element import Render.SpecInfo import Spec.Types import Data.Char ( isUpper ) import Khronos.Render -- | Assign all render elements a module assignModules :: forall r t . (HasErr r, HasRenderParams r, HasSpecInfo r) => Spec t -> RenderedSpec RenderElement -> Sem r [(ModName, Vector RenderElement)] assignModules spec rs = do let indexed = run . evalState (0 :: Int) $ traverse (\r -> do i <- get @Int modify' @Int succ pure (i, r) ) rs flat = fromList . toList $ indexed lookupRe i = case flat V.!? i of Nothing -> throw "Unable to find element at index" Just (_, e) -> pure e (exporterMap, rel) <- buildRelation (fromList . toList $ indexed) let getExporter n = note ("Unable to find " <> show n <> " in any render element") $ Map.lookup n exporterMap initialState = mempty :: S exports <- execState initialState $ assign (raise . getExporter) rel (closure rel) spec indexed -- -- Check that everything is exported -- unexportedNames <- unexportedNames spec forV_ indexed $ \(i, re) -> case IntMap.lookup i exports of Nothing -> do let exportedNames = exportName <$> toList (reExports re) forV_ (List.nubOrd exportedNames List.\\ unexportedNames) $ \n -> throw $ show n <> " is not exported from any module" Just _ -> pure () let declaredNames = Map.fromListWith (<>) ( IntMap.toList exports <&> \(n, ExportLocation d _) -> (d, Set.singleton n) ) reexportingMap = Map.fromListWith (<>) [ (m, Set.singleton n) | (n, ExportLocation _ ms) <- IntMap.toList exports , m <- toList ms ] forV (Map.toList declaredNames) $ \(modname, is) -> do declaringRenderElements <- traverseV lookupRe (fromList (Set.toList is)) reexportingRenderElements <- case Map.lookup modname reexportingMap of Nothing -> pure mempty Just is -> do res <- filter (getAll . reReexportable) <$> forV (Set.toList is) lookupRe pure $ reexportingRenderElement . Data.Set.fromList . toList . reExports <$> res pure (modname, declaringRenderElements <> fromList reexportingRenderElements) reexportingRenderElement :: Data.Set.Set Export -> RenderElement reexportingRenderElement exports = (emptyRenderElement ("reexporting " <> show exports)) { reReexportedNames = Data.Set.filter ((== Reexportable) . exportReexportable) exports } data ExportLocation = ExportLocation { _elDeclaringModule :: ModName , _elReExportingModules :: [ModName] } type S = IntMap ExportLocation data ReqDeps = ReqDeps { commands :: Vector Int , types :: Vector Int , enumValues :: Vector Int , directExporters :: Vector Int -- ^ The union of all the above } -- The type is put into the first rule that applies, and reexported from any -- subsequent matching rules in that feature. -- -- - For each feature -- - All reachable enums are put under the Feature.Enums module -- - Commands are put into their respective components -- - All types directly used by a command are put into the same module -- -- - For each extension -- - assign :: forall r t . (HasErr r, Member (State S) r, HasRenderParams r) => (HName -> Sem r Int) -> AdjacencyIntMap -> AdjacencyIntMap -> Spec t -> RenderedSpec (Int, RenderElement) -> Sem r () assign getExporter rel closedRel Spec {..} rs@RenderedSpec {..} = do RenderParams {..} <- input let allEnums = IntMap.fromList (toList rsEnums) allHandles = IntMap.fromList (toList rsHandles) allFuncPointers = IntMap.fromList (toList rsFuncPointers) -- Handy for debugging _elemName = let l = toList rs in \i -> reName <$> List.lookup i l -- -- Perform an action over all Features -- forFeatures :: (Feature -> Text -> (Maybe Text -> ModName) -> Sem r a) -> Sem r (Vector a) forFeatures f = forV specFeatures $ \feat@Feature {..} -> do let prefix = modulePrefix <> ".Core" <> foldMap show (versionBranch fVersion) f feat prefix (featureCommentToModuleName prefix) forFeatures_ = void . forFeatures extensionModulePrefix = modulePrefix <> "." <> "Extensions" forExtensionRequires :: (Text -> ModName -> ReqDeps -> Require -> Sem r ()) -> Sem r () forExtensionRequires f = forV_ specExtensions $ \Extension {..} -> forRequires_ exRequires (const $ extensionNameToModuleName extensionModulePrefix exName) $ \modname -> f extensionModulePrefix modname forRequires :: Traversable f => f Require -> (Maybe Text -> ModName) -> (ModName -> ReqDeps -> Require -> Sem r a) -> Sem r [a] forRequires requires commentToModName f = forV (sortOn (isNothing . rComment) . toList $ requires) $ \r -> do commands <- traverseV (getExporter . mkFunName) (rCommandNames r) types <- traverseV (getExporter . mkTyName) (rTypeNames r) enumValues <- traverseV (getExporter . mkPatternName) (rEnumValueNames r) let directExporters = commands <> types <> enumValues f (commentToModName (rComment r)) ReqDeps { .. } r forRequires_ requires commentToModName = void . forRequires requires commentToModName -- -- Perform an action over all 'Require's of all features and elements -- forFeaturesAndExtensions :: (Text -> ModName -> Bool -> ReqDeps -> Require -> Sem r ()) -> Sem r () forFeaturesAndExtensions f = do forFeatures_ $ \feat prefix commentToModName -> forRequires_ (fRequires feat) commentToModName $ \modname -> f prefix modname True forExtensionRequires $ \prefix modname -> f prefix modname False -- -- Export all elements both in world and reachable, optionally from a -- specifically named submodule. -- exportReachable :: Bool -> Text -> IntMap RenderElement -> IntSet -> Sem r () exportReachable namedSubmodule prefix world reachable = do let reachableWorld = world `IntMap.restrictKeys` reachable forV_ (IntMap.toList reachableWorld) $ \(i, re) -> do modName <- if namedSubmodule then do name <- firstTypeName re pure (ModName (prefix <> "." <> name)) else pure (ModName prefix) export modName i allCoreExports <- fmap (Set.unions . concat . toList) . forFeatures $ \Feature {..} _ mkName -> forRequires fRequires mkName $ \_ ReqDeps {..} _ -> let direct = Set.fromList (toList directExporters) in pure $ direct `postIntSets` closedRel ---------------------------------------------------------------- -- Explicit elements ---------------------------------------------------------------- forV_ rs $ \(i, re) -> forV_ (reExplicitModule re) $ \m -> export m i ---------------------------------------------------------------- -- API Constants ---------------------------------------------------------------- constantModule <- mkModuleName ["Core10", "APIConstants"] forV_ rsAPIConstants $ \(i, _) -> export constantModule i ---------------------------------------------------------------- -- Explicit Enums, Handles and FuncPointers for each feature ---------------------------------------------------------------- forFeaturesAndExtensions $ \prefix _ isFeature ReqDeps {..} _ -> do let reachable = Set.unions . toList $ (`postIntSet` closedRel) <$> directExporters ---------------------------------------------------------------- -- Reachable Enums ---------------------------------------------------------------- when isFeature $ exportReachable True (prefix <> ".Enums") allEnums reachable ---------------------------------------------------------------- -- Reachable Handles ---------------------------------------------------------------- exportReachable False (prefix <> ".Handles") allHandles reachable ---------------------------------------------------------------- -- Reachable FuncPointers ---------------------------------------------------------------- when isFeature $ exportReachable False (prefix <> ".FuncPointers") allFuncPointers reachable ---------------------------------------------------------------- -- Explicit exports of all features and extensions ---------------------------------------------------------------- forFeaturesAndExtensions $ \_ modname isFeature ReqDeps {..} _ -> if isFeature then forV_ directExporters $ export modname else let noCore = Set.toList ( Set.fromList (toList directExporters) `Set.difference` allCoreExports ) in forV_ noCore $ export modname ---------------------------------------------------------------- -- Assign aliases to be with their targets if they're not already assigned ---------------------------------------------------------------- forV_ specAliases $ \Alias {..} -> do let mkName = case aType of TypeAlias -> mkTyName TermAlias -> mkFunName -- TODO, terms other than functions? PatternAlias -> mkPatternName i <- getExporter (mkName aName) j <- getExporter (mkName aTarget) gets @S (IntMap.lookup i) >>= \case Just _ -> pure () Nothing -> gets @S (IntMap.lookup j) >>= \case Just (ExportLocation jMod _) -> modify' (IntMap.insert i (ExportLocation jMod [])) Nothing -> pure () ---------------------------------------------------------------- -- Go over the features one by one and close them ---------------------------------------------------------------- forFeatures_ $ \feat _ getModName -> do -- Types directly referred to by the commands and types forRequires_ (fRequires feat) getModName $ \modname ReqDeps {..} _ -> forV_ directExporters $ \i -> exportManyNoReexport modname (i `postIntSet` rel) -- Types indirectly referred to by the commands and types forRequires_ (fRequires feat) getModName $ \modname ReqDeps {..} _ -> forV_ directExporters $ \i -> exportManyNoReexport modname (i `postIntSet` closedRel) ---------------------------------------------------------------- -- Close the extensions ---------------------------------------------------------------- forExtensionRequires $ \_ modname ReqDeps {..} _ -> forV_ directExporters $ \i -> do exportManyNoReexport modname (i `postIntSet` rel) exportMany modname ((i `postIntSet` rel) `Set.difference` allCoreExports) forExtensionRequires $ \_ modname ReqDeps {..} _ -> forV_ directExporters $ \i -> exportMany modname ((i `postIntSet` closedRel) `Set.difference` allCoreExports) -- | This will try to ignore the "Bits" elements of flags and only return them -- if they are the only definition. -- -- The reason is that initially this library exported the "Bits" synonym for -- flags last and the modules were named accordingly. Now they're exported -- first, but we don't want to change the module names firstTypeName :: HasErr r => RenderElement -> Sem r Text firstTypeName re = let ns = mapMaybe getTyConName (V.toList (exportName <$> reExports re)) noBits = filter (("Bits" `T.isSuffixOf`) . stripVendor) ns in case noBits <> ns of [] -> throw "Unable to get type name from RenderElement" x : _ -> pure x export :: Member (State S) r => ModName -> Int -> Sem r () export m i = modify' (IntMap.alter ins i) where ins = \case Nothing -> Just (ExportLocation m []) Just (ExportLocation t rs) -> Just (ExportLocation t (m : rs)) exportMany :: Member (State S) r => ModName -> IntSet -> Sem r () exportMany m is = let newMap = IntMap.fromSet (const (ExportLocation m [])) is in modify' (\s -> IntMap.unionWith ins s newMap) where ins (ExportLocation r rs) (ExportLocation n _) = ExportLocation r (n : rs) exportManyNoReexport :: Member (State S) r => ModName -> IntSet -> Sem r () exportManyNoReexport m is = let newMap = IntMap.fromSet (const (ExportLocation m [])) is in modify' (\s -> IntMap.unionWith ins s newMap) where ins (ExportLocation r rs) (ExportLocation _ _) = ExportLocation r rs ---------------------------------------------------------------- -- Making module names ---------------------------------------------------------------- extensionNameToModuleName :: Text -> Text -> ModName extensionNameToModuleName extensionModulePrefix = ModName . ((extensionModulePrefix <> ".") <>) featureCommentToModuleName :: Text -> Maybe Text -> ModName featureCommentToModuleName prefix = \case Nothing -> ModName prefix Just t -> ModName $ ((prefix <> ".") <>) . mconcat . fmap (T.upperCaseFirst . replaceSymbols) . dropLast "API" . dropLast "commands" . T.words . T.replace "Promoted from" "Promoted_From_" . T.replace "Originally based on" "Originally_Based_On_" . T.takeWhile (/= ',') . removeParens . featureCommentMap $ t featureCommentMap :: Text -> Text featureCommentMap = \case "These types are part of the API and should always be defined, even when no enabled features require them." -> "OtherTypes" "These types are part of the API, though not directly used in API commands or data structures" -> "OtherTypes" "Types not directly used by the API" -> "OtherTypes" "Fundamental types used by many commands and structures" -> "FundamentalTypes" t -> t ---------------------------------------------------------------- -- Utils ---------------------------------------------------------------- buildRelation :: HasErr r => Vector (Int, RenderElement) -> Sem r (Map HName Int, AdjacencyIntMap) buildRelation elements = do let elementExports RenderElement {..} = reInternal <> reExports <> V.concatMap exportWith reExports elementImports = fmap importName . filter (not . importSource) . toList . reLocalImports numbered = elements allNames = sortOn fst [ (n, i) | (i, x) <- toList numbered , n <- fmap exportName . V.toList . elementExports $ x ] nameMap = Map.fromAscList allNames lookup n = case Map.lookup n nameMap of Nothing -> pure 0 -- throw $ "Unable to find " <> show n <> " in any vertex" Just i -> pure i es <- concat <$> forV numbered (\(n, x) -> forV (elementImports x) (fmap (n, ) . lookup)) let relation = vertices (fst <$> toList numbered) `overlay` edges es pure (nameMap, relation) getTyConName :: HName -> Maybe Text getTyConName = \case TyConName n -> Just n _ -> Nothing removeParens :: Text -> Text removeParens t = let (x, y) = T.breakOn "(" t in x <> T.takeWhileEnd (/= ')') y replaceSymbols :: Text -> Text replaceSymbols = \case "+" -> "And" t -> t dropLast :: Eq a => a -> [a] -> [a] dropLast x l = case nonEmpty l of Nothing -> [] Just xs -> if last xs == x then init xs else toList xs postIntSets :: IntSet -> AdjacencyIntMap -> IntSet postIntSets is rel = Set.unions $ (`postIntSet` rel) <$> Set.toList is ---------------------------------------------------------------- -- Ignored unexported names ---------------------------------------------------------------- unexportedNames :: HasRenderParams r => Spec t -> Sem r [HName] unexportedNames Spec {..} = do RenderParams {..} <- input let apiVersions = toList specFeatures <&> \Feature {..} -> let major : minor : _ = versionBranch fVersion in mkTyName (CName $ "VK_API_VERSION_" <> show major <> "_" <> show minor) pure $ [ mkFunName "vkGetSwapchainGrallocUsageANDROID" , mkFunName "vkGetSwapchainGrallocUsage2ANDROID" , mkFunName "vkAcquireImageANDROID" , mkFunName "vkQueueSignalReleaseImageANDROID" , mkTyName "VkSwapchainImageUsageFlagBitsANDROID" , mkTyName "VkSwapchainImageUsageFlagsANDROID" , mkTyName "VkNativeBufferUsage2ANDROID" , mkTyName "VkNativeBufferANDROID" , mkTyName "VkSwapchainImageCreateInfoANDROID" , mkTyName "VkPhysicalDevicePresentationPropertiesANDROID" -- TODO: Export these , mkTyName "VkSemaphoreCreateFlagBits" -- TODO: Export these , mkTyName "InstanceCreateFlagBits" , mkTyName "SessionCreateFlagBits" , mkTyName "SwapchainCreateFlagBits" , mkTyName "ViewStateFlagBits" , mkTyName "CompositionLayerFlagBits" , mkTyName "SpaceLocationFlagBits" , mkTyName "SpaceVelocityFlagBits" , mkTyName "InputSourceLocalizedNameFlagBits" , mkTyName "VulkanInstanceCreateFlagBitsKHR" , mkTyName "VulkanDeviceCreateFlagBitsKHR" , mkTyName "DebugUtilsMessageSeverityFlagBitsEXT" , mkTyName "DebugUtilsMessageTypeFlagBitsEXT" , mkTyName "OverlayMainSessionFlagBitsEXTX" , mkTyName "OverlaySessionCreateFlagBitsEXTX" -- TODO: export these , mkFunName "xrSetInputDeviceActiveEXT" , mkFunName "xrSetInputDeviceStateBoolEXT" , mkFunName "xrSetInputDeviceStateFloatEXT" , mkFunName "xrSetInputDeviceStateVector2fEXT" , mkFunName "xrSetInputDeviceLocationEXT" ] <> apiVersions ---------------------------------------------------------------- -- Utils ---------------------------------------------------------------- stripVendor :: Text -> Text stripVendor = T.dropWhileEnd isUpper
expipiplus1/vulkan
generate-new/khronos-spec/Khronos/AssignModules.hs
bsd-3-clause
19,322
0
25
5,155
4,659
2,389
2,270
-1
-1
{-# LANGUAGE DeriveFunctor, LambdaCase #-} module Data.Boombox.Head where import Data.Boombox.Player import Data.Boombox.Tape import Control.Comonad import Control.Applicative -- | 'Head' is a Store-like comonad which handles seeking. data Head i a = Head !i (Maybe i -> a) deriving Functor instance Comonad (Head i) where extract (Head _ f) = f Nothing extend k (Head i f) = Head i $ \case Nothing -> k $ Head i f Just j -> k $ Head j $ f . Just . maybe j id instance Ord i => Chronological (Head i) where coincidence (Head i f) (Head j g) = case compare i j of EQ -> Simultaneous (Head i (liftA2 (,) f g)) LT -> LeftFirst GT -> RightFirst -- | Seek to an arbitrary position. seeksTape :: Monad m => (i -> Maybe i) -> Tape (Head i) m a -> Tape (Head i) m a seeksTape t (Tape m) = Tape $ m >>= \(_, Head i f) -> unconsTape (f (t i)) -- | Get the current offset. posP :: PlayerT (Head i) s m i posP = control $ \(Head i f) -> (f Nothing, pure i) -- | Apply the given function to the current offset and jump to the resulting offset. seeksP :: (i -> Maybe i) -> PlayerT (Head i) s m () seeksP t = control $ \(Head i f) -> (f (t i), pure ()) -- | Seek to the given offset. seekP :: i -> PlayerT (Head i) s m () seekP i = seeksP (const (Just i))
fumieval/boombox
src/Data/Boombox/Head.hs
bsd-3-clause
1,274
0
14
291
563
287
276
27
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Configuration.Screen where import Lens.Simple ( makeLenses , (^.) ) import Data.Yaml ( FromJSON(..) , (.!=) , (.:?) ) import qualified Data.Yaml as Y data ImprovizScreenConfig = ImprovizScreenConfig { _front :: Float , _back :: Float } deriving (Show) makeLenses ''ImprovizScreenConfig defaultScreenConfig = ImprovizScreenConfig { _front = 0.1, _back = 100 } instance FromJSON ImprovizScreenConfig where parseJSON (Y.Object v) = ImprovizScreenConfig <$> v .:? "front" .!= (defaultScreenConfig ^. front) <*> v .:? "back" .!= (defaultScreenConfig ^. back) parseJSON _ = fail "Expected Object for ScreenConfig value"
rumblesan/proviz
src/Configuration/Screen.hs
bsd-3-clause
1,069
0
11
474
183
108
75
25
1
module Main where import Control.Applicative import Control.Concurrent import Control.Monad import Control.Monad.IO.Class import Data.Aeson import Data.DateTime (DateTime) import Data.Function import Data.Monoid import Data.Text (Text) import Network.API.Builder import Reddit import Reddit.Types.Subreddit import Reddit.Types.Wiki import Text.Read import qualified Data.DateTime as DateTime import qualified Data.Text as Text import qualified System.Environment as System subreddit :: SubredditName subreddit = R "dota2" main :: IO () main = do [user, pass] <- fmap Text.pack <$> System.getArgs go user pass go :: Text -> Text -> IO () go user pass = every 30 $ getSightings >>= \case Left _ -> putStrLn "couldn't get sightings" Right (Sightings (sighting : _)) -> do time <- DateTime.getCurrentTime let status = getYearBeastStatus time sighting void $ runReddit user pass $ do updateBanner status "config/sidebar" updateBanner status "sidebar" Right (Sightings []) -> return () data YearBeastStatus = ArrivingIn Integer | LeavingIn Integer | Missing deriving (Show, Read, Eq) getYearBeastStatus :: DateTime -> Sighting -> YearBeastStatus getYearBeastStatus cur (Sighting _ t d _) = case (cur < DateTime.addSeconds d t, cur < t) of (True, True) -> ArrivingIn $ DateTime.diffSeconds t cur `div` 60 (True, False) -> LeavingIn $ DateTime.diffSeconds (DateTime.addSeconds d t) cur `div` 60 _ -> Missing foo :: Text -> Bool foo = Text.isPrefixOf "#### " updateBanner :: YearBeastStatus -> Text -> Reddit () updateBanner status page = do p <- getWikiPage subreddit page editWikiPage subreddit page (genLink status <> Text.dropWhile (/= '\n') (contentMarkdown p)) "" genLink :: YearBeastStatus -> Text genLink (ArrivingIn 0) = "#### [**The Year Beasts will arrive in less than a minute!**](http://2015.yearbeast.com)" genLink (ArrivingIn 1) = "#### [**The Year Beasts will arrive in 1 minute!**](http://2015.yearbeast.com)" genLink (ArrivingIn n) = "#### [**The Year Beasts will arrive in " <> tshow n <> " minutes!**](http://2015.yearbeast.com)" genLink (LeavingIn 0) = "#### [**The Year Beasts will leave in less than a minute!**](http://2015.yearbeast.com)" genLink (LeavingIn 1) = "#### [**The Year Beasts will leave in 1 minute!**](http://2015.yearbeast.com)" genLink (LeavingIn n) = "#### [**The Year Beasts will leave in " <> tshow n <> " minutes!**](http://2015.yearbeast.com)" genLink Missing = "" tshow :: Show a => a -> Text tshow = Text.pack . show data Sighting = Sighting { sightingID :: Integer , timestamp :: DateTime , duration :: Integer , comment :: Text } deriving (Show, Read, Eq) instance Ord Sighting where compare = compare `on` sightingID instance FromJSON Sighting where parseJSON (Object o) = Sighting <$> (o .: "id" >>= readParse) <*> (DateTime.fromSeconds <$> (o .: "timestamp" >>= readParse)) <*> (o .: "duration" >>= readParse) <*> o .: "comment" parseJSON _ = mempty newtype Sightings = Sightings [Sighting] deriving (Show, Read, Eq) instance FromJSON Sightings where parseJSON x = Sightings <$> parseJSON x instance Receivable Sightings where receive = useFromJSON yearBeast :: Builder yearBeast = basicBuilder "Year Beast" "http://2015.yearbeast.com" sightingsRoute :: Route sightingsRoute = Route [ "history.json" ] [ ] "GET" getSightings :: IO (Either (APIError ()) Sightings) getSightings = execAPI yearBeast () $ runRoute sightingsRoute readParse :: (MonadPlus m, Read a) => String -> m a readParse x = case readMaybe x of Just r -> return r Nothing -> mzero every :: MonadIO m => Int -> m a -> m () every s x = forever $ do _ <- x liftIO $ threadDelay $ s * 1000 * 1000
intolerable/year-beast
src/Main.hs
bsd-3-clause
3,857
0
14
795
1,166
607
559
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Migrate.Internal.Types ( TransferMonad , TransferState(..) , TransactionError(..) , getInformation, get, write, append, modify, getPreviousError , runTransferMonad ) where import ClassyPrelude import Control.Arrow import Control.Exception import Control.Monad import Control.Monad.Trans.Except import Data.Maybe (fromMaybe) import Data.Monoid import Data.Serialize (Serialize) import GHC.Generics data TransactionError = ServiceError String | SystemError String | SerializationError String | Unexpected String deriving (Show, Eq, Ord, Generic) instance Serialize TransactionError where data TransferEnvironment env w = TransferEnvironment { readableEnv :: env , writableRef :: MVar w , prevError :: Maybe TransactionError } newtype TransferMonad environment written return = TransferMonad { unTransferMonad :: ExceptT TransactionError (ReaderT (TransferEnvironment environment written) IO) return } deriving (Monad, Applicative, Functor, MonadIO) runTransferMonad :: r -> MVar w -> Maybe TransactionError -> TransferMonad r w a -> IO (Either TransactionError a) runTransferMonad r mvar exc = flip runReaderT (TransferEnvironment r mvar exc) . runExceptT . unTransferMonad data TransferState initialData dataRead dataWritten = Initializing initialData | Reading initialData dataRead | Writing initialData dataRead dataWritten | Finished initialData dataRead dataWritten deriving (Eq, Ord, Show, Generic) instance (Serialize d, Serialize r, Serialize w) => Serialize (TransferState d r w) where getInformation :: TransferMonad r w r getInformation = TransferMonad (readableEnv <$> lift ask) get :: TransferMonad r w w get = TransferMonad (lift ask >>= readMVar . writableRef) write :: w -> TransferMonad r w () write w = TransferMonad (lift ask >>= void . flip swapMVar w . writableRef) modify :: (w -> w) -> TransferMonad r w w modify f = TransferMonad $ do mvar <- writableRef <$> lift ask modifyMVar mvar (\val -> let x = f val in return (x, x)) append :: Monoid w => w -> TransferMonad r w w append d = modify $ flip mappend d succeed :: a -> TransferMonad r w a succeed = return safeFail :: TransactionError -> TransferMonad r w a safeFail = TransferMonad . throwE getPreviousError :: TransferMonad r w (Maybe TransactionError) getPreviousError = TransferMonad $ prevError <$> lift ask
JustusAdam/bitbucket-github-migrate
src/Migrate/Internal/Types.hs
bsd-3-clause
2,765
0
15
727
747
400
347
61
1
{-# LANGUAGE MagicHash, UnboxedTuples #-} module CasIORef (casIORef) where import GHC.IORef import GHC.STRef import GHC.Exts import GHC.IO casIORef :: IORef a -> a -> a -> IO Bool casIORef (IORef (STRef r#)) old new = IO $ \s -> case casMutVar# r# old new s of (# s', did, val #) -> if did ==# 0# then (# s', True #) else (# s', False #)
mono0926/ParallelConcurrentHaskell
CasIORef.hs
bsd-3-clause
379
0
11
107
135
74
61
12
2
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {- | some internal definitions. To use default persistence, import @Data.TCache.DefaultPersistence@ instead -} module Data.TCache.Defs where import Control.Concurrent import Control.Concurrent.STM (STM, TVar) import Control.Exception as Exception import Control.Monad (when, replicateM) import Control.Monad.Reader (MonadReader, ask, ReaderT(ReaderT), runReaderT) import qualified Data.ByteString.Lazy.Char8 as B import qualified Data.HashTable.IO as H import Data.IORef import Data.List (elemIndices, isInfixOf, stripPrefix) import qualified Data.Map as Map import Data.Maybe (fromJust, catMaybes) import Data.Typeable import System.Directory ( createDirectoryIfMissing , getDirectoryContents , removeFile ) import System.IO ( openFile , IOMode(ReadMode) , hPutStrLn , hClose , hFileSize , stderr ) import System.IO.Unsafe import System.IO.Error import System.Mem.Weak --import Debug.Trace --(!>) = flip trace type AccessTime = Integer type ModifTime = Integer data Status a = NotRead | DoNotExist | Exist a deriving (Typeable) data Elem a = Elem !a !AccessTime !ModifTime deriving (Typeable) type TPVar a = TVar (Status (Elem a)) data DBRef a = DBRef !String !(TPVar a) deriving (Typeable) castErr :: forall a b. (Typeable a, Typeable b) => String -> a -> b castErr s a = case cast a of Just x -> x Nothing -> error $ "Type error: " ++ (show $ typeOf a) ++ " does not match "++ (show $ typeOf (undefined :: b)) ++ "\nThis means that objects of these two types have the same key" ++ "\nor the retrieved object type is not the previously stored one for the same key." ++ "\n" ++ s {- | Indexable is an utility class used to derive instances of IResource Example: @data Person= Person{ pname :: String, cars :: [DBRef Car]} deriving (Show, Read, Typeable) data Car= Car{owner :: DBRef Person , cname:: String} deriving (Show, Read, Eq, Typeable) @ Since Person and Car are instances of 'Read' ans 'Show', by defining the 'Indexable' instance will implicitly define the IResource instance for file persistence: @ instance Indexable Person where key Person{pname=n} = \"Person \" ++ n instance Indexable Car where key Car{cname= n} = \"Car \" ++ n @ -} class Indexable a where key :: a -> String --instance IResource a => Indexable a where -- key x = keyResource x instance Indexable String where key = id instance Indexable Int where key = show instance Indexable Integer where key = show instance Indexable () where key () = "void" {- | Serialize is an alternative to the IResource class for defining persistence in TCache. The deserialization must be as lazy as possible. serialization/deserialization are not performance critical in TCache Read, Show, instances are implicit instances of Serializable > serialize = pack . show > deserialize= read . unpack Since write and read to disk of to/from the cache are not be very frequent The performance of serialization is not critical. -} class Serializable a where serialize :: a -> B.ByteString deserialize :: B.ByteString -> a deserialize = error "No deserialization defined for your data" deserialKey :: String -> B.ByteString -> a deserialKey _ v = deserialize v persist :: Proxy a -> Maybe Persist -- ^ `defaultPersist` if Nothing persist = const Nothing type Key = String type IResource a = (Typeable a, Indexable a, Serializable a) -- there are two references to the DBRef here -- The Maybe one keeps it alive until the cache releases it for *Resources -- calls which does not reference dbrefs explicitly -- The weak reference keeps the dbref alive until is it not referenced elsewere data CacheElem = forall a. (IResource a, Typeable a) => CacheElem (Maybe (DBRef a)) (Weak (DBRef a)) type Ht = H.BasicHashTable String CacheElem type Hts = Map.Map TypeRep Ht -- Contains the hashtable and last sync time. type Cache = IORef (Hts,Integer) data CheckTPVarFlags = AddToHash | NoAddToHash -- | Set the cache. This is useful for hot loaded modules that will update an existing cache. Experimental -- setCache :: Cache -> IO () -- setCache ref = readIORef ref >>= \ch -> writeIORef refcache ch -- | The cache holder. Established by default -- refcache :: Cache -- refcache = unsafePerformIO $ newCache >>= newIORef -- | Creates a new cache. Experimental. newCache :: IO (Hts,Integer) newCache = return (Map.empty,0) data CMTrigger = forall a. (Typeable a) => CMTrigger !((DBRef a) -> Maybe a -> STM ()) -- | A persistence mechanism has to implement these primitives. -- 'filePersist' is the default file persistence. data Persist = Persist { readByKey :: Key -> IO (Maybe B.ByteString) -- ^ read by key. It must be strict. , write :: Key -> B.ByteString -> IO () -- ^ write. It must be strict. , delete :: Key -> IO () -- ^ delete , listByType :: forall t. (Typeable t) => Proxy t -> IO [Key] -- ^ List keys of objects of the given type. , cmtriggers :: IORef [(TypeRep, [CMTrigger])] , cache :: Cache -- ^ Cached values. , persistName :: String -- ^ For showing. } instance Show Persist where show p = persistName p -- | Implements default persistence of objects in files with their keys as filenames, -- inside the given directory. filePersist :: FilePath -> IO Persist filePersist dir = do t <- newIORef [] c <- newCache >>= newIORef createDirectoryIfMissing True dir return $ Persist { readByKey = defaultReadByKey dir , write = defaultWrite dir , delete = defaultDelete dir , listByType = defaultListByType dir , cmtriggers = t , cache = c , persistName = "File persist in " ++ show dir } newtype DB a = DB (ReaderT Persist STM a) deriving (Functor, Applicative, Monad, MonadReader Persist) runDB :: Persist -> DB a -> STM a runDB s (DB h) = runReaderT h s db :: (Persist -> STM a) -> DB a db = DB . ReaderT stm :: STM a -> DB a stm = db . const defaultReadByKey :: FilePath -> String -> IO (Maybe B.ByteString) defaultReadByKey dir k = handle handler $ do s <- readFileStrict $ dir ++ "/" ++ k return $ Just s -- `debug` ("read "++ filename) where handler :: IOError -> IO (Maybe B.ByteString) handler e | isAlreadyInUseError e = defaultReadByKey dir k | isDoesNotExistError e = return Nothing | otherwise = if "invalid" `isInfixOf` ioeGetErrorString e then error $ "defaultReadByKey: " ++ show e ++ " defPath and/or keyResource are not suitable for a file path:\n" ++ k ++ "\"" else defaultReadByKey dir k defaultWrite :: FilePath -> String -> B.ByteString -> IO () defaultWrite dir k x = safeWrite (dir ++ "/" ++ k) x safeWrite filename str = handle handler $ B.writeFile filename str -- !> ("write "++filename) where handler e -- (e :: IOError) | isDoesNotExistError e = do createDirectoryIfMissing True $ take (1 + (last $ elemIndices '/' filename)) filename -- maybe the path does not exist safeWrite filename str | otherwise = if ("invalid" `isInfixOf` ioeGetErrorString e) then error $ "defaultWriteResource: " ++ show e ++ " defPath and/or keyResource are not suitable for a file path: " ++ filename else do hPutStrLn stderr $ "defaultWriteResource: " ++ show e ++ " in file: " ++ filename ++ " retrying" safeWrite filename str defaultDelete :: FilePath -> String -> IO () defaultDelete dir k = handle (handler filename) $ removeFile filename where filename = dir ++ "/" ++ k handler :: String -> IOException -> IO () handler file e | isDoesNotExistError e = return () --`debug` "isDoesNotExistError" | isAlreadyInUseError e = do hPutStrLn stderr $ "defaultDelResource: busy in file: " ++ filename ++ " retrying" -- threadDelay 100000 --`debug`"isAlreadyInUseError" defaultDelete dir k | otherwise = do hPutStrLn stderr $ "defaultDelResource: " ++ show e ++ " in file: " ++ filename ++ " retrying" -- threadDelay 100000 --`debug` ("otherwise " ++ show e) defaultDelete dir k defaultListByType :: forall t. (Typeable t) => FilePath -> Proxy t -> IO [Key] defaultListByType dir _ = do files <- getDirectoryContents dir return . catMaybes . map (stripPrefix $ typeString ++ "-") $ files where typeString = show (typeOf (undefined :: t)) -- | Strict read from file, needed for default file persistence readFileStrict f = openFile f ReadMode >>= \ h -> readIt h `finally` hClose h where readIt h = do s <- hFileSize h let n = fromIntegral s str <- B.hGet h n return str readResourceByKey :: forall t. (Indexable t, Serializable t, Typeable t) => Persist -> Key -> IO (Maybe t) readResourceByKey store k = readByKey store (typedFile pr k) >>= evaluate . fmap (deserialKey k) where pr = Proxy :: Proxy t readResourcesByKey :: forall t. (Indexable t, Serializable t, Typeable t) => Persist -> [Key] -> IO [Maybe t] readResourcesByKey store = mapM (readResourceByKey store) writeResource :: forall t. (Indexable t, Serializable t, Typeable t) => Persist -> t -> IO () writeResource store s = write store (typedFile pr $ key s) $ serialize s where pr = Proxy :: Proxy t delResource :: forall t. (Indexable t, Serializable t, Typeable t) => Persist -> t -> IO () delResource store s = delete store $ typedFile pr (key s) where pr = Proxy :: Proxy t listResources :: forall t. (Serializable t, Indexable t, Typeable t) => Persist -> Proxy t -> IO [Key] listResources = listByType typedFile :: forall t. (Indexable t, Typeable t) => Proxy t -> Key -> FilePath typedFile _ k = typeString ++ "-" ++ k where typeString = show $ typeOf (undefined :: t)
ariep/TCache
src/Data/TCache/Defs.hs
bsd-3-clause
10,379
0
17
2,478
2,523
1,329
1,194
210
2
{-# LANGUAGE CPP #-} -- -- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 -- -------------------------------------------------------------- -- Converting Core to STG Syntax -------------------------------------------------------------- -- And, as we have the info in hand, we may convert some lets to -- let-no-escapes. module CoreToStg ( coreToStg, coreExprToStg ) where #include "HsVersions.h" import CoreSyn import CoreUtils ( exprType, findDefault ) import CoreArity ( manifestArity ) import StgSyn import Type import TyCon import MkId ( coercionTokenId ) import Id import IdInfo import DataCon import CostCentre ( noCCS ) import VarSet import VarEnv import Module import Name ( getOccName, isExternalName, nameOccName ) import OccName ( occNameString, occNameFS ) import BasicTypes ( Arity ) import TysWiredIn ( unboxedUnitDataCon ) import Literal import Outputable import MonadUtils import FastString import Util import DynFlags import ForeignCall import Demand ( isUsedOnce ) import PrimOp ( PrimCall(..) ) import Data.Maybe (isJust) import Control.Monad (liftM, ap) -- Note [Live vs free] -- ~~~~~~~~~~~~~~~~~~~ -- -- The actual Stg datatype is decorated with live variable information, as well -- as free variable information. The two are not the same. Liveness is an -- operational property rather than a semantic one. A variable is live at a -- particular execution point if it can be referred to directly again. In -- particular, a dead variable's stack slot (if it has one): -- -- - should be stubbed to avoid space leaks, and -- - may be reused for something else. -- -- There ought to be a better way to say this. Here are some examples: -- -- let v = [q] \[x] -> e -- in -- ...v... (but no q's) -- -- Just after the `in', v is live, but q is dead. If the whole of that -- let expression was enclosed in a case expression, thus: -- -- case (let v = [q] \[x] -> e in ...v...) of -- alts[...q...] -- -- (ie `alts' mention `q'), then `q' is live even after the `in'; because -- we'll return later to the `alts' and need it. -- -- Let-no-escapes make this a bit more interesting: -- -- let-no-escape v = [q] \ [x] -> e -- in -- ...v... -- -- Here, `q' is still live at the `in', because `v' is represented not by -- a closure but by the current stack state. In other words, if `v' is -- live then so is `q'. Furthermore, if `e' mentions an enclosing -- let-no-escaped variable, then its free variables are also live if `v' is. -- Note [Collecting live CAF info] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- In this pass we also collect information on which CAFs are live for -- constructing SRTs (see SRT.hs). -- -- A top-level Id has CafInfo, which is -- -- - MayHaveCafRefs, if it may refer indirectly to -- one or more CAFs, or -- - NoCafRefs if it definitely doesn't -- -- The CafInfo has already been calculated during the CoreTidy pass. -- -- During CoreToStg, we then pin onto each binding and case expression, a -- list of Ids which represents the "live" CAFs at that point. The meaning -- of "live" here is the same as for live variables, see above (which is -- why it's convenient to collect CAF information here rather than elsewhere). -- -- The later SRT pass takes these lists of Ids and uses them to construct -- the actual nested SRTs, and replaces the lists of Ids with (offset,length) -- pairs. -- Note [Interaction of let-no-escape with SRTs] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Consider -- -- let-no-escape x = ...caf1...caf2... -- in -- ...x...x...x... -- -- where caf1,caf2 are CAFs. Since x doesn't have a closure, we -- build SRTs just as if x's defn was inlined at each call site, and -- that means that x's CAF refs get duplicated in the overall SRT. -- -- This is unlike ordinary lets, in which the CAF refs are not duplicated. -- -- We could fix this loss of (static) sharing by making a sort of pseudo-closure -- for x, solely to put in the SRTs lower down. -- Note [What is a non-escaping let] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- Consider: -- -- let x = fvs \ args -> e -- in -- if ... then x else -- if ... then x else ... -- -- `x' is used twice (so we probably can't unfold it), but when it is -- entered, the stack is deeper than it was when the definition of `x' -- happened. Specifically, if instead of allocating a closure for `x', -- we saved all `x's fvs on the stack, and remembered the stack depth at -- that moment, then whenever we enter `x' we can simply set the stack -- pointer(s) to these remembered (compile-time-fixed) values, and jump -- to the code for `x'. -- -- All of this is provided x is: -- 1. non-updatable - it must have at least one parameter (see Note -- [Join point abstraction]); -- 2. guaranteed to be entered before the stack retreats -- ie x is not -- buried in a heap-allocated closure, or passed as an argument to -- something; -- 3. all the enters have exactly the right number of arguments, -- no more no less; -- 4. all the enters are tail calls; that is, they return to the -- caller enclosing the definition of `x'. -- -- Under these circumstances we say that `x' is non-escaping. -- -- An example of when (4) does not hold: -- -- let x = ... -- in case x of ...alts... -- -- Here, `x' is certainly entered only when the stack is deeper than when -- `x' is defined, but here it must return to ...alts... So we can't just -- adjust the stack down to `x''s recalled points, because that would lost -- alts' context. -- -- Things can get a little more complicated. Consider: -- -- let y = ... -- in let x = fvs \ args -> ...y... -- in ...x... -- -- Now, if `x' is used in a non-escaping way in ...x..., and `y' is used in a -- non-escaping way in ...y..., then `y' is non-escaping. -- -- `x' can even be recursive! Eg: -- -- letrec x = [y] \ [v] -> if v then x True else ... -- in -- ...(x b)... -- -------------------------------------------------------------- -- Setting variable info: top-level, binds, RHSs -- -------------------------------------------------------------- coreToStg :: DynFlags -> Module -> CoreProgram -> IO [StgBinding] coreToStg dflags this_mod pgm = return pgm' where (_, _, pgm') = coreTopBindsToStg dflags this_mod emptyVarEnv pgm coreExprToStg :: CoreExpr -> StgExpr coreExprToStg expr = new_expr where (new_expr,_,_) = initLne emptyVarEnv (coreToStgExpr expr) coreTopBindsToStg :: DynFlags -> Module -> IdEnv HowBound -- environment for the bindings -> CoreProgram -> (IdEnv HowBound, FreeVarsInfo, [StgBinding]) coreTopBindsToStg _ _ env [] = (env, emptyFVInfo, []) coreTopBindsToStg dflags this_mod env (b:bs) = (env2, fvs2, b':bs') where -- Notice the mutually-recursive "knot" here: -- env accumulates down the list of binds, -- fvs accumulates upwards (env1, fvs2, b' ) = coreTopBindToStg dflags this_mod env fvs1 b (env2, fvs1, bs') = coreTopBindsToStg dflags this_mod env1 bs coreTopBindToStg :: DynFlags -> Module -> IdEnv HowBound -> FreeVarsInfo -- Info about the body -> CoreBind -> (IdEnv HowBound, FreeVarsInfo, StgBinding) coreTopBindToStg dflags this_mod env body_fvs (NonRec id rhs) = let env' = extendVarEnv env id how_bound how_bound = LetBound TopLet $! manifestArity rhs (stg_rhs, fvs') = initLne env $ do (stg_rhs, fvs') <- coreToTopStgRhs dflags this_mod body_fvs (id,rhs) return (stg_rhs, fvs') bind = StgNonRec id stg_rhs in ASSERT2(consistentCafInfo id bind, ppr id ) -- NB: previously the assertion printed 'rhs' and 'bind' -- as well as 'id', but that led to a black hole -- where printing the assertion error tripped the -- assertion again! (env', fvs' `unionFVInfo` body_fvs, bind) coreTopBindToStg dflags this_mod env body_fvs (Rec pairs) = ASSERT( not (null pairs) ) let binders = map fst pairs extra_env' = [ (b, LetBound TopLet $! manifestArity rhs) | (b, rhs) <- pairs ] env' = extendVarEnvList env extra_env' (stg_rhss, fvs') = initLne env' $ do (stg_rhss, fvss') <- mapAndUnzipM (coreToTopStgRhs dflags this_mod body_fvs) pairs let fvs' = unionFVInfos fvss' return (stg_rhss, fvs') bind = StgRec (zip binders stg_rhss) in ASSERT2(consistentCafInfo (head binders) bind, ppr binders) (env', fvs' `unionFVInfo` body_fvs, bind) -- Assertion helper: this checks that the CafInfo on the Id matches -- what CoreToStg has figured out about the binding's SRT. The -- CafInfo will be exact in all cases except when CorePrep has -- floated out a binding, in which case it will be approximate. consistentCafInfo :: Id -> GenStgBinding Var Id -> Bool consistentCafInfo id bind = WARN( not (exact || is_sat_thing) , ppr id <+> ppr id_marked_caffy <+> ppr binding_is_caffy ) safe where safe = id_marked_caffy || not binding_is_caffy exact = id_marked_caffy == binding_is_caffy id_marked_caffy = mayHaveCafRefs (idCafInfo id) binding_is_caffy = stgBindHasCafRefs bind is_sat_thing = occNameFS (nameOccName (idName id)) == fsLit "sat" coreToTopStgRhs :: DynFlags -> Module -> FreeVarsInfo -- Free var info for the scope of the binding -> (Id,CoreExpr) -> LneM (StgRhs, FreeVarsInfo) coreToTopStgRhs dflags this_mod scope_fv_info (bndr, rhs) = do { (new_rhs, rhs_fvs, _) <- coreToStgExpr rhs ; lv_info <- freeVarsToLiveVars rhs_fvs ; let stg_rhs = mkTopStgRhs dflags this_mod rhs_fvs (mkSRT lv_info) bndr bndr_info new_rhs stg_arity = stgRhsArity stg_rhs ; return (ASSERT2( arity_ok stg_arity, mk_arity_msg stg_arity) stg_rhs, rhs_fvs) } where bndr_info = lookupFVInfo scope_fv_info bndr -- It's vital that the arity on a top-level Id matches -- the arity of the generated STG binding, else an importing -- module will use the wrong calling convention -- (Trac #2844 was an example where this happened) -- NB1: we can't move the assertion further out without -- blocking the "knot" tied in coreTopBindsToStg -- NB2: the arity check is only needed for Ids with External -- Names, because they are externally visible. The CorePrep -- pass introduces "sat" things with Local Names and does -- not bother to set their Arity info, so don't fail for those arity_ok stg_arity | isExternalName (idName bndr) = id_arity == stg_arity | otherwise = True id_arity = idArity bndr mk_arity_msg stg_arity = vcat [ppr bndr, text "Id arity:" <+> ppr id_arity, text "STG arity:" <+> ppr stg_arity] mkTopStgRhs :: DynFlags -> Module -> FreeVarsInfo -> SRT -> Id -> StgBinderInfo -> StgExpr -> StgRhs mkTopStgRhs dflags this_mod = mkStgRhs' con_updateable -- Dynamic StgConApps are updatable where con_updateable con args = isDllConApp dflags this_mod con args -- --------------------------------------------------------------------------- -- Expressions -- --------------------------------------------------------------------------- coreToStgExpr :: CoreExpr -> LneM (StgExpr, -- Decorated STG expr FreeVarsInfo, -- Its free vars (NB free, not live) EscVarsSet) -- Its escapees, a subset of its free vars; -- also a subset of the domain of the envt -- because we are only interested in the escapees -- for vars which might be turned into -- let-no-escaped ones. -- The second and third components can be derived in a simple bottom up pass, not -- dependent on any decisions about which variables will be let-no-escaped or -- not. The first component, that is, the decorated expression, may then depend -- on these components, but it in turn is not scrutinised as the basis for any -- decisions. Hence no black holes. -- No LitInteger's should be left by the time this is called. CorePrep -- should have converted them all to a real core representation. coreToStgExpr (Lit (LitInteger {})) = panic "coreToStgExpr: LitInteger" coreToStgExpr (Lit l) = return (StgLit l, emptyFVInfo, emptyVarSet) coreToStgExpr (Var v) = coreToStgApp Nothing v [] [] coreToStgExpr (Coercion _) = coreToStgApp Nothing coercionTokenId [] [] coreToStgExpr expr@(App _ _) = coreToStgApp Nothing f args ticks where (f, args, ticks) = myCollectArgs expr coreToStgExpr expr@(Lam _ _) = let (args, body) = myCollectBinders expr args' = filterStgBinders args in extendVarEnvLne [ (a, LambdaBound) | a <- args' ] $ do (body, body_fvs, body_escs) <- coreToStgExpr body let fvs = args' `minusFVBinders` body_fvs escs = body_escs `delVarSetList` args' result_expr | null args' = body | otherwise = StgLam args' body return (result_expr, fvs, escs) coreToStgExpr (Tick tick expr) = do case tick of HpcTick{} -> return () ProfNote{} -> return () SourceNote{} -> return () Breakpoint{} -> panic "coreToStgExpr: breakpoint should not happen" (expr2, fvs, escs) <- coreToStgExpr expr return (StgTick tick expr2, fvs, escs) coreToStgExpr (Cast expr _) = coreToStgExpr expr -- Cases require a little more real work. coreToStgExpr (Case scrut _ _ []) = coreToStgExpr scrut -- See Note [Empty case alternatives] in CoreSyn If the case -- alternatives are empty, the scrutinee must diverge or raise an -- exception, so we can just dive into it. -- -- Of course this may seg-fault if the scrutinee *does* return. A -- belt-and-braces approach would be to move this case into the -- code generator, and put a return point anyway that calls a -- runtime system error function. coreToStgExpr (Case scrut bndr _ alts) = do (alts2, alts_fvs, alts_escs) <- extendVarEnvLne [(bndr, LambdaBound)] $ do (alts2, fvs_s, escs_s) <- mapAndUnzip3M vars_alt alts return ( alts2, unionFVInfos fvs_s, unionVarSets escs_s ) let -- Determine whether the default binder is dead or not -- This helps the code generator to avoid generating an assignment -- for the case binder (is extremely rare cases) ToDo: remove. bndr' | bndr `elementOfFVInfo` alts_fvs = bndr | otherwise = bndr `setIdOccInfo` IAmDead -- Don't consider the default binder as being 'live in alts', -- since this is from the point of view of the case expr, where -- the default binder is not free. alts_fvs_wo_bndr = bndr `minusFVBinder` alts_fvs alts_escs_wo_bndr = alts_escs `delVarSet` bndr alts_lv_info <- freeVarsToLiveVars alts_fvs_wo_bndr -- We tell the scrutinee that everything -- live in the alts is live in it, too. (scrut2, scrut_fvs, _scrut_escs, scrut_lv_info) <- setVarsLiveInCont alts_lv_info $ do (scrut2, scrut_fvs, scrut_escs) <- coreToStgExpr scrut scrut_lv_info <- freeVarsToLiveVars scrut_fvs return (scrut2, scrut_fvs, scrut_escs, scrut_lv_info) return ( StgCase scrut2 (getLiveVars scrut_lv_info) (getLiveVars alts_lv_info) bndr' (mkSRT alts_lv_info) (mkStgAltType bndr alts) alts2, scrut_fvs `unionFVInfo` alts_fvs_wo_bndr, alts_escs_wo_bndr `unionVarSet` getFVSet scrut_fvs -- You might think we should have scrut_escs, not -- (getFVSet scrut_fvs), but actually we can't call, and -- then return from, a let-no-escape thing. ) where vars_alt (con, binders, rhs) | DataAlt c <- con, c == unboxedUnitDataCon = -- This case is a bit smelly. -- See Note [Nullary unboxed tuple] in Type.hs -- where a nullary tuple is mapped to (State# World#) ASSERT( null binders ) do { (rhs2, rhs_fvs, rhs_escs) <- coreToStgExpr rhs ; return ((DEFAULT, [], [], rhs2), rhs_fvs, rhs_escs) } | otherwise = let -- Remove type variables binders' = filterStgBinders binders in extendVarEnvLne [(b, LambdaBound) | b <- binders'] $ do (rhs2, rhs_fvs, rhs_escs) <- coreToStgExpr rhs let -- Records whether each param is used in the RHS good_use_mask = [ b `elementOfFVInfo` rhs_fvs | b <- binders' ] return ( (con, binders', good_use_mask, rhs2), binders' `minusFVBinders` rhs_fvs, rhs_escs `delVarSetList` binders' ) -- ToDo: remove the delVarSet; -- since escs won't include any of these binders -- Lets not only take quite a bit of work, but this is where we convert -- then to let-no-escapes, if we wish. -- (Meanwhile, we don't expect to see let-no-escapes...) coreToStgExpr (Let bind body) = do (new_let, fvs, escs, _) <- mfix (\ ~(_, _, _, no_binder_escapes) -> coreToStgLet no_binder_escapes bind body ) return (new_let, fvs, escs) coreToStgExpr e = pprPanic "coreToStgExpr" (ppr e) mkStgAltType :: Id -> [CoreAlt] -> AltType mkStgAltType bndr alts = case repType (idType bndr) of UnaryRep rep_ty -> case tyConAppTyCon_maybe rep_ty of Just tc | isUnliftedTyCon tc -> PrimAlt tc | isAbstractTyCon tc -> look_for_better_tycon | isAlgTyCon tc -> AlgAlt tc | otherwise -> ASSERT2( _is_poly_alt_tycon tc, ppr tc ) PolyAlt Nothing -> PolyAlt UbxTupleRep rep_tys -> UbxTupAlt (length rep_tys) -- NB Nullary unboxed tuples have UnaryRep, and generate a PrimAlt where _is_poly_alt_tycon tc = isFunTyCon tc || isPrimTyCon tc -- "Any" is lifted but primitive || isFamilyTyCon tc -- Type family; e.g. Any, or arising from strict -- function application where argument has a -- type-family type -- Sometimes, the TyCon is a AbstractTyCon which may not have any -- constructors inside it. Then we may get a better TyCon by -- grabbing the one from a constructor alternative -- if one exists. look_for_better_tycon | ((DataAlt con, _, _) : _) <- data_alts = AlgAlt (dataConTyCon con) | otherwise = ASSERT(null data_alts) PolyAlt where (data_alts, _deflt) = findDefault alts -- --------------------------------------------------------------------------- -- Applications -- --------------------------------------------------------------------------- coreToStgApp :: Maybe UpdateFlag -- Just upd <=> this application is -- the rhs of a thunk binding -- x = [...] \upd [] -> the_app -- with specified update flag -> Id -- Function -> [CoreArg] -- Arguments -> [Tickish Id] -- Debug ticks -> LneM (StgExpr, FreeVarsInfo, EscVarsSet) coreToStgApp _ f args ticks = do (args', args_fvs, ticks') <- coreToStgArgs args how_bound <- lookupVarLne f let n_val_args = valArgCount args not_letrec_bound = not (isLetBound how_bound) fun_fvs = singletonFVInfo f how_bound fun_occ -- e.g. (f :: a -> int) (x :: a) -- Here the free variables are "f", "x" AND the type variable "a" -- coreToStgArgs will deal with the arguments recursively -- Mostly, the arity info of a function is in the fn's IdInfo -- But new bindings introduced by CoreSat may not have no -- arity info; it would do us no good anyway. For example: -- let f = \ab -> e in f -- No point in having correct arity info for f! -- Hence the hasArity stuff below. -- NB: f_arity is only consulted for LetBound things f_arity = stgArity f how_bound saturated = f_arity <= n_val_args fun_occ | not_letrec_bound = noBinderInfo -- Uninteresting variable | f_arity > 0 && saturated = stgSatOcc -- Saturated or over-saturated function call | otherwise = stgUnsatOcc -- Unsaturated function or thunk fun_escs | not_letrec_bound = emptyVarSet -- Only letrec-bound escapees are interesting | f_arity == n_val_args = emptyVarSet -- A function *or thunk* with an exactly -- saturated call doesn't escape -- (let-no-escape applies to 'thunks' too) | otherwise = unitVarSet f -- Inexact application; it does escape -- At the moment of the call: -- either the function is *not* let-no-escaped, in which case -- nothing is live except live_in_cont -- or the function *is* let-no-escaped in which case the -- variables it uses are live, but still the function -- itself is not. PS. In this case, the function's -- live vars should already include those of the -- continuation, but it does no harm to just union the -- two regardless. res_ty = exprType (mkApps (Var f) args) app = case idDetails f of DataConWorkId dc | saturated -> StgConApp dc args' -- Some primitive operator that might be implemented as a library call. PrimOpId op -> ASSERT( saturated ) StgOpApp (StgPrimOp op) args' res_ty -- A call to some primitive Cmm function. FCallId (CCall (CCallSpec (StaticTarget _ lbl (Just pkgId) True) PrimCallConv _)) -> ASSERT( saturated ) StgOpApp (StgPrimCallOp (PrimCall lbl pkgId)) args' res_ty -- A regular foreign call. FCallId call -> ASSERT( saturated ) StgOpApp (StgFCallOp call (idUnique f)) args' res_ty TickBoxOpId {} -> pprPanic "coreToStg TickBox" $ ppr (f,args') _other -> StgApp f args' fvs = fun_fvs `unionFVInfo` args_fvs vars = fun_escs `unionVarSet` (getFVSet args_fvs) -- All the free vars of the args are disqualified -- from being let-no-escaped. tapp = foldr StgTick app (ticks ++ ticks') -- Forcing these fixes a leak in the code generator, noticed while -- profiling for trac #4367 app `seq` fvs `seq` seqVarSet vars `seq` return ( tapp, fvs, vars ) -- --------------------------------------------------------------------------- -- Argument lists -- This is the guy that turns applications into A-normal form -- --------------------------------------------------------------------------- coreToStgArgs :: [CoreArg] -> LneM ([StgArg], FreeVarsInfo, [Tickish Id]) coreToStgArgs [] = return ([], emptyFVInfo, []) coreToStgArgs (Type _ : args) = do -- Type argument (args', fvs, ts) <- coreToStgArgs args return (args', fvs, ts) coreToStgArgs (Coercion _ : args) -- Coercion argument; replace with place holder = do { (args', fvs, ts) <- coreToStgArgs args ; return (StgVarArg coercionTokenId : args', fvs, ts) } coreToStgArgs (Tick t e : args) = ASSERT( not (tickishIsCode t) ) do { (args', fvs, ts) <- coreToStgArgs (e : args) ; return (args', fvs, t:ts) } coreToStgArgs (arg : args) = do -- Non-type argument (stg_args, args_fvs, ticks) <- coreToStgArgs args (arg', arg_fvs, _escs) <- coreToStgExpr arg let fvs = args_fvs `unionFVInfo` arg_fvs (aticks, arg'') = stripStgTicksTop tickishFloatable arg' stg_arg = case arg'' of StgApp v [] -> StgVarArg v StgConApp con [] -> StgVarArg (dataConWorkId con) StgLit lit -> StgLitArg lit _ -> pprPanic "coreToStgArgs" (ppr arg) -- WARNING: what if we have an argument like (v `cast` co) -- where 'co' changes the representation type? -- (This really only happens if co is unsafe.) -- Then all the getArgAmode stuff in CgBindery will set the -- cg_rep of the CgIdInfo based on the type of v, rather -- than the type of 'co'. -- This matters particularly when the function is a primop -- or foreign call. -- Wanted: a better solution than this hacky warning let arg_ty = exprType arg stg_arg_ty = stgArgType stg_arg bad_args = (isUnliftedType arg_ty && not (isUnliftedType stg_arg_ty)) || (map typePrimRep (flattenRepType (repType arg_ty)) /= map typePrimRep (flattenRepType (repType stg_arg_ty))) -- In GHCi we coerce an argument of type BCO# (unlifted) to HValue (lifted), -- and pass it to a function expecting an HValue (arg_ty). This is ok because -- we can treat an unlifted value as lifted. But the other way round -- we complain. -- We also want to check if a pointer is cast to a non-ptr etc WARN( bad_args, text "Dangerous-looking argument. Probable cause: bad unsafeCoerce#" $$ ppr arg ) return (stg_arg : stg_args, fvs, ticks ++ aticks) -- --------------------------------------------------------------------------- -- The magic for lets: -- --------------------------------------------------------------------------- coreToStgLet :: Bool -- True <=> yes, we are let-no-escaping this let -> CoreBind -- bindings -> CoreExpr -- body -> LneM (StgExpr, -- new let FreeVarsInfo, -- variables free in the whole let EscVarsSet, -- variables that escape from the whole let Bool) -- True <=> none of the binders in the bindings -- is among the escaping vars coreToStgLet let_no_escape bind body = do (bind2, bind_fvs, bind_escs, bind_lvs, body2, body_fvs, body_escs, body_lvs) <- mfix $ \ ~(_, _, _, _, _, rec_body_fvs, _, _) -> do -- Do the bindings, setting live_in_cont to empty if -- we ain't in a let-no-escape world live_in_cont <- getVarsLiveInCont ( bind2, bind_fvs, bind_escs, bind_lv_info, env_ext) <- setVarsLiveInCont (if let_no_escape then live_in_cont else emptyLiveInfo) (vars_bind rec_body_fvs bind) -- Do the body extendVarEnvLne env_ext $ do (body2, body_fvs, body_escs) <- coreToStgExpr body body_lv_info <- freeVarsToLiveVars body_fvs return (bind2, bind_fvs, bind_escs, getLiveVars bind_lv_info, body2, body_fvs, body_escs, getLiveVars body_lv_info) -- Compute the new let-expression let new_let | let_no_escape = StgLetNoEscape live_in_whole_let bind_lvs bind2 body2 | otherwise = StgLet bind2 body2 free_in_whole_let = binders `minusFVBinders` (bind_fvs `unionFVInfo` body_fvs) live_in_whole_let = bind_lvs `unionVarSet` (body_lvs `delVarSetList` binders) real_bind_escs = if let_no_escape then bind_escs else getFVSet bind_fvs -- Everything escapes which is free in the bindings let_escs = (real_bind_escs `unionVarSet` body_escs) `delVarSetList` binders all_escs = bind_escs `unionVarSet` body_escs -- Still includes binders of -- this let(rec) no_binder_escapes = isEmptyVarSet (set_of_binders `intersectVarSet` all_escs) -- Debugging code as requested by Andrew Kennedy checked_no_binder_escapes | debugIsOn && not no_binder_escapes && any is_join_var binders = pprTrace "Interesting! A join var that isn't let-no-escaped" (ppr binders) False | otherwise = no_binder_escapes -- Mustn't depend on the passed-in let_no_escape flag, since -- no_binder_escapes is used by the caller to derive the flag! return ( new_let, free_in_whole_let, let_escs, checked_no_binder_escapes ) where set_of_binders = mkVarSet binders binders = bindersOf bind mk_binding bind_lv_info binder rhs = (binder, LetBound (NestedLet live_vars) (manifestArity rhs)) where live_vars | let_no_escape = addLiveVar bind_lv_info binder | otherwise = unitLiveVar binder -- c.f. the invariant on NestedLet vars_bind :: FreeVarsInfo -- Free var info for body of binding -> CoreBind -> LneM (StgBinding, FreeVarsInfo, EscVarsSet, -- free vars; escapee vars LiveInfo, -- Vars and CAFs live in binding [(Id, HowBound)]) -- extension to environment vars_bind body_fvs (NonRec binder rhs) = do (rhs2, bind_fvs, bind_lv_info, escs) <- coreToStgRhs body_fvs [] (binder,rhs) let env_ext_item = mk_binding bind_lv_info binder rhs return (StgNonRec binder rhs2, bind_fvs, escs, bind_lv_info, [env_ext_item]) vars_bind body_fvs (Rec pairs) = mfix $ \ ~(_, rec_rhs_fvs, _, bind_lv_info, _) -> let rec_scope_fvs = unionFVInfo body_fvs rec_rhs_fvs binders = map fst pairs env_ext = [ mk_binding bind_lv_info b rhs | (b,rhs) <- pairs ] in extendVarEnvLne env_ext $ do (rhss2, fvss, lv_infos, escss) <- mapAndUnzip4M (coreToStgRhs rec_scope_fvs binders) pairs let bind_fvs = unionFVInfos fvss bind_lv_info = foldr unionLiveInfo emptyLiveInfo lv_infos escs = unionVarSets escss return (StgRec (binders `zip` rhss2), bind_fvs, escs, bind_lv_info, env_ext) is_join_var :: Id -> Bool -- A hack (used only for compiler debuggging) to tell if -- a variable started life as a join point ($j) is_join_var j = occNameString (getOccName j) == "$j" coreToStgRhs :: FreeVarsInfo -- Free var info for the scope of the binding -> [Id] -> (Id,CoreExpr) -> LneM (StgRhs, FreeVarsInfo, LiveInfo, EscVarsSet) coreToStgRhs scope_fv_info binders (bndr, rhs) = do (new_rhs, rhs_fvs, rhs_escs) <- coreToStgExpr rhs lv_info <- freeVarsToLiveVars (binders `minusFVBinders` rhs_fvs) return (mkStgRhs rhs_fvs (mkSRT lv_info) bndr bndr_info new_rhs, rhs_fvs, lv_info, rhs_escs) where bndr_info = lookupFVInfo scope_fv_info bndr mkStgRhs :: FreeVarsInfo -> SRT -> Id -> StgBinderInfo -> StgExpr -> StgRhs mkStgRhs = mkStgRhs' con_updateable where con_updateable _ _ = False mkStgRhs' :: (DataCon -> [StgArg] -> Bool) -> FreeVarsInfo -> SRT -> Id -> StgBinderInfo -> StgExpr -> StgRhs mkStgRhs' con_updateable rhs_fvs srt bndr binder_info rhs | StgLam bndrs body <- rhs = StgRhsClosure noCCS binder_info (getFVs rhs_fvs) ReEntrant srt bndrs body | StgConApp con args <- unticked_rhs , not (con_updateable con args) = StgRhsCon noCCS con args | otherwise = StgRhsClosure noCCS binder_info (getFVs rhs_fvs) upd_flag srt [] rhs where (_, unticked_rhs) = stripStgTicksTop (not . tickishIsCode) rhs upd_flag | isUsedOnce (idDemandInfo bndr) = SingleEntry | otherwise = Updatable {- SDM: disabled. Eval/Apply can't handle functions with arity zero very well; and making these into simple non-updatable thunks breaks other assumptions (namely that they will be entered only once). upd_flag | isPAP env rhs = ReEntrant | otherwise = Updatable -- Detect thunks which will reduce immediately to PAPs, and make them -- non-updatable. This has several advantages: -- -- - the non-updatable thunk behaves exactly like the PAP, -- -- - the thunk is more efficient to enter, because it is -- specialised to the task. -- -- - we save one update frame, one stg_update_PAP, one update -- and lots of PAP_enters. -- -- - in the case where the thunk is top-level, we save building -- a black hole and futhermore the thunk isn't considered to -- be a CAF any more, so it doesn't appear in any SRTs. -- -- We do it here, because the arity information is accurate, and we need -- to do it before the SRT pass to save the SRT entries associated with -- any top-level PAPs. isPAP env (StgApp f args) = listLengthCmp args arity == LT -- idArity f > length args where arity = stgArity f (lookupBinding env f) isPAP env _ = False -} {- ToDo: upd = if isOnceDem dem then (if isNotTop toplev then SingleEntry -- HA! Paydirt for "dem" else (if debugIsOn then trace "WARNING: SE CAFs unsupported, forcing UPD instead" else id) $ Updatable) else Updatable -- For now we forbid SingleEntry CAFs; they tickle the -- ASSERT in rts/Storage.c line 215 at newCAF() re mut_link, -- and I don't understand why. There's only one SE_CAF (well, -- only one that tickled a great gaping bug in an earlier attempt -- at ClosureInfo.getEntryConvention) in the whole of nofib, -- specifically Main.lvl6 in spectral/cryptarithm2. -- So no great loss. KSW 2000-07. -} -- --------------------------------------------------------------------------- -- A little monad for this let-no-escaping pass -- --------------------------------------------------------------------------- -- There's a lot of stuff to pass around, so we use this LneM monad to -- help. All the stuff here is only passed *down*. newtype LneM a = LneM { unLneM :: IdEnv HowBound -> LiveInfo -- Vars and CAFs live in continuation -> a } type LiveInfo = (StgLiveVars, -- Dynamic live variables; -- i.e. ones with a nested (non-top-level) binding CafSet) -- Static live variables; -- i.e. top-level variables that are CAFs or refer to them type EscVarsSet = IdSet type CafSet = IdSet data HowBound = ImportBound -- Used only as a response to lookupBinding; never -- exists in the range of the (IdEnv HowBound) | LetBound -- A let(rec) in this module LetInfo -- Whether top level or nested Arity -- Its arity (local Ids don't have arity info at this point) | LambdaBound -- Used for both lambda and case data LetInfo = TopLet -- top level things | NestedLet LiveInfo -- For nested things, what is live if this -- thing is live? Invariant: the binder -- itself is always a member of -- the dynamic set of its own LiveInfo isLetBound :: HowBound -> Bool isLetBound (LetBound _ _) = True isLetBound _ = False topLevelBound :: HowBound -> Bool topLevelBound ImportBound = True topLevelBound (LetBound TopLet _) = True topLevelBound _ = False -- For a let(rec)-bound variable, x, we record LiveInfo, the set of -- variables that are live if x is live. This LiveInfo comprises -- (a) dynamic live variables (ones with a non-top-level binding) -- (b) static live variabes (CAFs or things that refer to CAFs) -- -- For "normal" variables (a) is just x alone. If x is a let-no-escaped -- variable then x is represented by a code pointer and a stack pointer -- (well, one for each stack). So all of the variables needed in the -- execution of x are live if x is, and are therefore recorded in the -- LetBound constructor; x itself *is* included. -- -- The set of dynamic live variables is guaranteed ot have no further -- let-no-escaped variables in it. emptyLiveInfo :: LiveInfo emptyLiveInfo = (emptyVarSet,emptyVarSet) unitLiveVar :: Id -> LiveInfo unitLiveVar lv = (unitVarSet lv, emptyVarSet) unitLiveCaf :: Id -> LiveInfo unitLiveCaf caf = (emptyVarSet, unitVarSet caf) addLiveVar :: LiveInfo -> Id -> LiveInfo addLiveVar (lvs, cafs) id = (lvs `extendVarSet` id, cafs) unionLiveInfo :: LiveInfo -> LiveInfo -> LiveInfo unionLiveInfo (lv1,caf1) (lv2,caf2) = (lv1 `unionVarSet` lv2, caf1 `unionVarSet` caf2) mkSRT :: LiveInfo -> SRT mkSRT (_, cafs) = SRTEntries cafs getLiveVars :: LiveInfo -> StgLiveVars getLiveVars (lvs, _) = lvs -- The std monad functions: initLne :: IdEnv HowBound -> LneM a -> a initLne env m = unLneM m env emptyLiveInfo {-# INLINE thenLne #-} {-# INLINE returnLne #-} returnLne :: a -> LneM a returnLne e = LneM $ \_ _ -> e thenLne :: LneM a -> (a -> LneM b) -> LneM b thenLne m k = LneM $ \env lvs_cont -> unLneM (k (unLneM m env lvs_cont)) env lvs_cont instance Functor LneM where fmap = liftM instance Applicative LneM where pure = returnLne (<*>) = ap instance Monad LneM where return = pure (>>=) = thenLne instance MonadFix LneM where mfix expr = LneM $ \env lvs_cont -> let result = unLneM (expr result) env lvs_cont in result -- Functions specific to this monad: getVarsLiveInCont :: LneM LiveInfo getVarsLiveInCont = LneM $ \_env lvs_cont -> lvs_cont setVarsLiveInCont :: LiveInfo -> LneM a -> LneM a setVarsLiveInCont new_lvs_cont expr = LneM $ \env _lvs_cont -> unLneM expr env new_lvs_cont extendVarEnvLne :: [(Id, HowBound)] -> LneM a -> LneM a extendVarEnvLne ids_w_howbound expr = LneM $ \env lvs_cont -> unLneM expr (extendVarEnvList env ids_w_howbound) lvs_cont lookupVarLne :: Id -> LneM HowBound lookupVarLne v = LneM $ \env _lvs_cont -> lookupBinding env v lookupBinding :: IdEnv HowBound -> Id -> HowBound lookupBinding env v = case lookupVarEnv env v of Just xx -> xx Nothing -> ASSERT2( isGlobalId v, ppr v ) ImportBound -- The result of lookupLiveVarsForSet, a set of live variables, is -- only ever tacked onto a decorated expression. It is never used as -- the basis of a control decision, which might give a black hole. freeVarsToLiveVars :: FreeVarsInfo -> LneM LiveInfo freeVarsToLiveVars fvs = LneM freeVarsToLiveVars' where freeVarsToLiveVars' _env live_in_cont = live_info where live_info = foldr unionLiveInfo live_in_cont lvs_from_fvs lvs_from_fvs = map do_one (allFreeIds fvs) do_one (v, how_bound) = case how_bound of ImportBound -> unitLiveCaf v -- Only CAF imports are -- recorded in fvs LetBound TopLet _ | mayHaveCafRefs (idCafInfo v) -> unitLiveCaf v | otherwise -> emptyLiveInfo LetBound (NestedLet lvs) _ -> lvs -- lvs already contains v -- (see the invariant on NestedLet) _lambda_or_case_binding -> unitLiveVar v -- Bound by lambda or case -- --------------------------------------------------------------------------- -- Free variable information -- --------------------------------------------------------------------------- type FreeVarsInfo = VarEnv (Var, HowBound, StgBinderInfo) -- The Var is so we can gather up the free variables -- as a set. -- -- The HowBound info just saves repeated lookups; -- we look up just once when we encounter the occurrence. -- INVARIANT: Any ImportBound Ids are HaveCafRef Ids -- Imported Ids without CAF refs are simply -- not put in the FreeVarsInfo for an expression. -- See singletonFVInfo and freeVarsToLiveVars -- -- StgBinderInfo records how it occurs; notably, we -- are interested in whether it only occurs in saturated -- applications, because then we don't need to build a -- curried version. -- If f is mapped to noBinderInfo, that means -- that f *is* mentioned (else it wouldn't be in the -- IdEnv at all), but perhaps in an unsaturated applications. -- -- All case/lambda-bound things are also mapped to -- noBinderInfo, since we aren't interested in their -- occurrence info. -- -- For ILX we track free var info for type variables too; -- hence VarEnv not IdEnv emptyFVInfo :: FreeVarsInfo emptyFVInfo = emptyVarEnv singletonFVInfo :: Id -> HowBound -> StgBinderInfo -> FreeVarsInfo -- Don't record non-CAF imports at all, to keep free-var sets small singletonFVInfo id ImportBound info | mayHaveCafRefs (idCafInfo id) = unitVarEnv id (id, ImportBound, info) | otherwise = emptyVarEnv singletonFVInfo id how_bound info = unitVarEnv id (id, how_bound, info) unionFVInfo :: FreeVarsInfo -> FreeVarsInfo -> FreeVarsInfo unionFVInfo fv1 fv2 = plusVarEnv_C plusFVInfo fv1 fv2 unionFVInfos :: [FreeVarsInfo] -> FreeVarsInfo unionFVInfos fvs = foldr unionFVInfo emptyFVInfo fvs minusFVBinders :: [Id] -> FreeVarsInfo -> FreeVarsInfo minusFVBinders vs fv = foldr minusFVBinder fv vs minusFVBinder :: Id -> FreeVarsInfo -> FreeVarsInfo minusFVBinder v fv = fv `delVarEnv` v -- When removing a binder, remember to add its type variables -- c.f. CoreFVs.delBinderFV elementOfFVInfo :: Id -> FreeVarsInfo -> Bool elementOfFVInfo id fvs = isJust (lookupVarEnv fvs id) lookupFVInfo :: FreeVarsInfo -> Id -> StgBinderInfo -- Find how the given Id is used. -- Externally visible things may be used any old how lookupFVInfo fvs id | isExternalName (idName id) = noBinderInfo | otherwise = case lookupVarEnv fvs id of Nothing -> noBinderInfo Just (_,_,info) -> info allFreeIds :: FreeVarsInfo -> [(Id,HowBound)] -- Both top level and non-top-level Ids allFreeIds fvs = ASSERT( all (isId . fst) ids ) ids where ids = [(id,how_bound) | (id,how_bound,_) <- varEnvElts fvs] -- Non-top-level things only, both type variables and ids getFVs :: FreeVarsInfo -> [Var] getFVs fvs = [id | (id, how_bound, _) <- varEnvElts fvs, not (topLevelBound how_bound) ] getFVSet :: FreeVarsInfo -> VarSet getFVSet fvs = mkVarSet (getFVs fvs) plusFVInfo :: (Var, HowBound, StgBinderInfo) -> (Var, HowBound, StgBinderInfo) -> (Var, HowBound, StgBinderInfo) plusFVInfo (id1,hb1,info1) (id2,hb2,info2) = ASSERT(id1 == id2 && hb1 `check_eq_how_bound` hb2) (id1, hb1, combineStgBinderInfo info1 info2) -- The HowBound info for a variable in the FVInfo should be consistent check_eq_how_bound :: HowBound -> HowBound -> Bool check_eq_how_bound ImportBound ImportBound = True check_eq_how_bound LambdaBound LambdaBound = True check_eq_how_bound (LetBound li1 ar1) (LetBound li2 ar2) = ar1 == ar2 && check_eq_li li1 li2 check_eq_how_bound _ _ = False check_eq_li :: LetInfo -> LetInfo -> Bool check_eq_li (NestedLet _) (NestedLet _) = True check_eq_li TopLet TopLet = True check_eq_li _ _ = False -- Misc. filterStgBinders :: [Var] -> [Var] filterStgBinders bndrs = filter isId bndrs myCollectBinders :: Expr Var -> ([Var], Expr Var) myCollectBinders expr = go [] expr where go bs (Lam b e) = go (b:bs) e go bs (Cast e _) = go bs e go bs e = (reverse bs, e) myCollectArgs :: CoreExpr -> (Id, [CoreArg], [Tickish Id]) -- We assume that we only have variables -- in the function position by now myCollectArgs expr = go expr [] [] where go (Var v) as ts = (v, as, ts) go (App f a) as ts = go f (a:as) ts go (Tick t e) as ts = ASSERT( all isTypeArg as ) go e as (t:ts) -- ticks can appear in type apps go (Cast e _) as ts = go e as ts go (Lam b e) as ts | isTyVar b = go e as ts -- Note [Collect args] go _ _ _ = pprPanic "CoreToStg.myCollectArgs" (ppr expr) -- Note [Collect args] -- ~~~~~~~~~~~~~~~~~~~ -- -- This big-lambda case occurred following a rather obscure eta expansion. -- It all seems a bit yukky to me. stgArity :: Id -> HowBound -> Arity stgArity _ (LetBound _ arity) = arity stgArity f ImportBound = idArity f stgArity _ LambdaBound = 0
GaloisInc/halvm-ghc
compiler/stgSyn/CoreToStg.hs
bsd-3-clause
46,809
0
21
14,186
7,731
4,211
3,520
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 @Uniques@ are used to distinguish entities in the compiler (@Ids@, @Classes@, etc.) from each other. Thus, @Uniques@ are the basic comparison key in the compiler. If there is any single operation that needs to be fast, it is @Unique@ comparison. Unsurprisingly, there is quite a bit of huff-and-puff directed to that end. Some of the other hair in this code is to be able to use a ``splittable @UniqueSupply@'' if requested/possible (not standard Haskell). -} {-# LANGUAGE CPP, BangPatterns, MagicHash #-} module Unique ( -- * Main data types Unique, Uniquable(..), uNIQUE_BITS, -- ** Constructors, destructors and operations on 'Unique's hasKey, pprUniqueAlways, mkUniqueGrimily, -- Used in UniqSupply only! getKey, -- Used in Var, UniqFM, Name only! mkUnique, unpkUnique, -- Used in GHC.Iface.Binary only eqUnique, ltUnique, incrUnique, newTagUnique, -- Used in CgCase initTyVarUnique, initExitJoinUnique, nonDetCmpUnique, isValidKnownKeyUnique, -- Used in PrelInfo.knownKeyNamesOkay -- ** Making built-in uniques -- now all the built-in Uniques (and functions to make them) -- [the Oh-So-Wonderful Haskell module system wins again...] mkAlphaTyVarUnique, mkPrimOpIdUnique, mkPrimOpWrapperUnique, mkPreludeMiscIdUnique, mkPreludeDataConUnique, mkPreludeTyConUnique, mkPreludeClassUnique, mkCoVarUnique, mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique, mkRegSingleUnique, mkRegPairUnique, mkRegClassUnique, mkRegSubUnique, mkCostCentreUnique, mkBuiltinUnique, mkPseudoUniqueD, mkPseudoUniqueE, mkPseudoUniqueH, -- ** Deriving uniques -- *** From TyCon name uniques tyConRepNameUnique, -- *** From DataCon name uniques dataConWorkerUnique, dataConTyRepNameUnique, -- ** Local uniques -- | These are exposed exclusively for use by 'VarEnv.uniqAway', which -- has rather peculiar needs. See Note [Local uniques]. mkLocalUnique, minLocalUnique, maxLocalUnique ) where #include "HsVersions.h" #include "Unique.h" import GhcPrelude import BasicTypes import FastString import Outputable import Util -- just for implementing a fast [0,61) -> Char function import GHC.Exts (indexCharOffAddr#, Char(..), Int(..)) import Data.Char ( chr, ord ) import Data.Bits {- ************************************************************************ * * \subsection[Unique-type]{@Unique@ type and operations} * * ************************************************************************ The @Chars@ are ``tag letters'' that identify the @UniqueSupply@. Fast comparison is everything on @Uniques@: -} -- | Unique identifier. -- -- The type of unique identifiers that are used in many places in GHC -- for fast ordering and equality tests. You should generate these with -- the functions from the 'UniqSupply' module -- -- These are sometimes also referred to as \"keys\" in comments in GHC. newtype Unique = MkUnique Int {-# INLINE uNIQUE_BITS #-} uNIQUE_BITS :: Int uNIQUE_BITS = finiteBitSize (0 :: Int) - UNIQUE_TAG_BITS {- Now come the functions which construct uniques from their pieces, and vice versa. The stuff about unique *supplies* is handled further down this module. -} unpkUnique :: Unique -> (Char, Int) -- The reverse mkUniqueGrimily :: Int -> Unique -- A trap-door for UniqSupply getKey :: Unique -> Int -- for Var incrUnique :: Unique -> Unique stepUnique :: Unique -> Int -> Unique newTagUnique :: Unique -> Char -> Unique mkUniqueGrimily = MkUnique {-# INLINE getKey #-} getKey (MkUnique x) = x incrUnique (MkUnique i) = MkUnique (i + 1) stepUnique (MkUnique i) n = MkUnique (i + n) mkLocalUnique :: Int -> Unique mkLocalUnique i = mkUnique 'X' i minLocalUnique :: Unique minLocalUnique = mkLocalUnique 0 maxLocalUnique :: Unique maxLocalUnique = mkLocalUnique uniqueMask -- newTagUnique changes the "domain" of a unique to a different char newTagUnique u c = mkUnique c i where (_,i) = unpkUnique u -- | How many bits are devoted to the unique index (as opposed to the class -- character). uniqueMask :: Int uniqueMask = (1 `shiftL` uNIQUE_BITS) - 1 -- pop the Char in the top 8 bits of the Unique(Supply) -- No 64-bit bugs here, as long as we have at least 32 bits. --JSM -- and as long as the Char fits in 8 bits, which we assume anyway! mkUnique :: Char -> Int -> Unique -- Builds a unique from pieces -- NOT EXPORTED, so that we can see all the Chars that -- are used in this one module mkUnique c i = MkUnique (tag .|. bits) where tag = ord c `shiftL` uNIQUE_BITS bits = i .&. uniqueMask unpkUnique (MkUnique u) = let -- as long as the Char may have its eighth bit set, we -- really do need the logical right-shift here! tag = chr (u `shiftR` uNIQUE_BITS) i = u .&. uniqueMask in (tag, i) -- | The interface file symbol-table encoding assumes that known-key uniques fit -- in 30-bits; verify this. -- -- See Note [Symbol table representation of names] in GHC.Iface.Binary for details. isValidKnownKeyUnique :: Unique -> Bool isValidKnownKeyUnique u = case unpkUnique u of (c, x) -> ord c < 0xff && x <= (1 `shiftL` 22) {- ************************************************************************ * * \subsection[Uniquable-class]{The @Uniquable@ class} * * ************************************************************************ -} -- | Class of things that we can obtain a 'Unique' from class Uniquable a where getUnique :: a -> Unique hasKey :: Uniquable a => a -> Unique -> Bool x `hasKey` k = getUnique x == k instance Uniquable FastString where getUnique fs = mkUniqueGrimily (uniqueOfFS fs) instance Uniquable Int where getUnique i = mkUniqueGrimily i {- ************************************************************************ * * \subsection[Unique-instances]{Instance declarations for @Unique@} * * ************************************************************************ And the whole point (besides uniqueness) is fast equality. We don't use `deriving' because we want {\em precise} control of ordering (equality on @Uniques@ is v common). -} -- Note [Unique Determinism] -- ~~~~~~~~~~~~~~~~~~~~~~~~~ -- The order of allocated @Uniques@ is not stable across rebuilds. -- The main reason for that is that typechecking interface files pulls -- @Uniques@ from @UniqSupply@ and the interface file for the module being -- currently compiled can, but doesn't have to exist. -- -- It gets more complicated if you take into account that the interface -- files are loaded lazily and that building multiple files at once has to -- work for any subset of interface files present. When you add parallelism -- this makes @Uniques@ hopelessly random. -- -- As such, to get deterministic builds, the order of the allocated -- @Uniques@ should not affect the final result. -- see also wiki/deterministic-builds -- -- Note [Unique Determinism and code generation] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- The goal of the deterministic builds (wiki/deterministic-builds, #4012) -- is to get ABI compatible binaries given the same inputs and environment. -- The motivation behind that is that if the ABI doesn't change the -- binaries can be safely reused. -- Note that this is weaker than bit-for-bit identical binaries and getting -- bit-for-bit identical binaries is not a goal for now. -- This means that we don't care about nondeterminism that happens after -- the interface files are created, in particular we don't care about -- register allocation and code generation. -- To track progress on bit-for-bit determinism see #12262. eqUnique :: Unique -> Unique -> Bool eqUnique (MkUnique u1) (MkUnique u2) = u1 == u2 ltUnique :: Unique -> Unique -> Bool ltUnique (MkUnique u1) (MkUnique u2) = u1 < u2 -- Provided here to make it explicit at the call-site that it can -- introduce non-determinism. -- See Note [Unique Determinism] -- See Note [No Ord for Unique] nonDetCmpUnique :: Unique -> Unique -> Ordering nonDetCmpUnique (MkUnique u1) (MkUnique u2) = if u1 == u2 then EQ else if u1 < u2 then LT else GT {- Note [No Ord for Unique] ~~~~~~~~~~~~~~~~~~~~~~~~~~ As explained in Note [Unique Determinism] the relative order of Uniques is nondeterministic. To prevent from accidental use the Ord Unique instance has been removed. This makes it easier to maintain deterministic builds, but comes with some drawbacks. The biggest drawback is that Maps keyed by Uniques can't directly be used. The alternatives are: 1) Use UniqFM or UniqDFM, see Note [Deterministic UniqFM] to decide which 2) Create a newtype wrapper based on Unique ordering where nondeterminism is controlled. See Module.ModuleEnv 3) Change the algorithm to use nonDetCmpUnique and document why it's still deterministic 4) Use TrieMap as done in GHC.Cmm.CommonBlockElim.groupByLabel -} instance Eq Unique where a == b = eqUnique a b a /= b = not (eqUnique a b) instance Uniquable Unique where getUnique u = u -- We do sometimes make strings with @Uniques@ in them: showUnique :: Unique -> String showUnique uniq = case unpkUnique uniq of (tag, u) -> finish_show tag u (iToBase62 u) finish_show :: Char -> Int -> String -> String finish_show 't' u _pp_u | u < 26 = -- Special case to make v common tyvars, t1, t2, ... -- come out as a, b, ... (shorter, easier to read) [chr (ord 'a' + u)] finish_show tag _ pp_u = tag : pp_u pprUniqueAlways :: Unique -> SDoc -- The "always" means regardless of -dsuppress-uniques -- It replaces the old pprUnique to remind callers that -- they should consider whether they want to consult -- Opt_SuppressUniques pprUniqueAlways u = text (showUnique u) instance Outputable Unique where ppr = pprUniqueAlways instance Show Unique where show uniq = showUnique uniq {- ************************************************************************ * * \subsection[Utils-base62]{Base-62 numbers} * * ************************************************************************ A character-stingy way to read/write numbers (notably Uniques). The ``62-its'' are \tr{[0-9a-zA-Z]}. We don't handle negative Ints. Code stolen from Lennart. -} iToBase62 :: Int -> String iToBase62 n_ = ASSERT(n_ >= 0) go n_ "" where go n cs | n < 62 = let !c = chooseChar62 n in c : cs | otherwise = go q (c : cs) where (!q, r) = quotRem n 62 !c = chooseChar62 r chooseChar62 :: Int -> Char {-# INLINE chooseChar62 #-} chooseChar62 (I# n) = C# (indexCharOffAddr# chars62 n) chars62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"# {- ************************************************************************ * * \subsection[Uniques-prelude]{@Uniques@ for wired-in Prelude things} * * ************************************************************************ Allocation of unique supply characters: v,t,u : for renumbering value-, type- and usage- vars. B: builtin C-E: pseudo uniques (used in native-code generator) X: uniques from mkLocalUnique _: unifiable tyvars (above) 0-9: prelude things below (no numbers left any more..) :: (prelude) parallel array data constructors other a-z: lower case chars for unique supplies. Used so far: d desugarer f AbsC flattener g SimplStg k constraint tuple tycons m constraint tuple datacons n Native codegen r Hsc name cache s simplifier z anonymous sums -} mkAlphaTyVarUnique :: Int -> Unique mkPreludeClassUnique :: Int -> Unique mkPreludeTyConUnique :: Int -> Unique mkPreludeDataConUnique :: Arity -> Unique mkPrimOpIdUnique :: Int -> Unique -- See Note [Primop wrappers] in PrimOp.hs. mkPrimOpWrapperUnique :: Int -> Unique mkPreludeMiscIdUnique :: Int -> Unique mkCoVarUnique :: Int -> Unique mkAlphaTyVarUnique i = mkUnique '1' i mkCoVarUnique i = mkUnique 'g' i mkPreludeClassUnique i = mkUnique '2' i -------------------------------------------------- -- Wired-in type constructor keys occupy *two* slots: -- * u: the TyCon itself -- * u+1: the TyConRepName of the TyCon mkPreludeTyConUnique i = mkUnique '3' (2*i) tyConRepNameUnique :: Unique -> Unique tyConRepNameUnique u = incrUnique u -- Data constructor keys occupy *two* slots. The first is used for the -- data constructor itself and its wrapper function (the function that -- evaluates arguments as necessary and calls the worker). The second is -- used for the worker function (the function that builds the constructor -- representation). -------------------------------------------------- -- Wired-in data constructor keys occupy *three* slots: -- * u: the DataCon itself -- * u+1: its worker Id -- * u+2: the TyConRepName of the promoted TyCon -- Prelude data constructors are too simple to need wrappers. mkPreludeDataConUnique i = mkUnique '6' (3*i) -- Must be alphabetic -------------------------------------------------- dataConTyRepNameUnique, dataConWorkerUnique :: Unique -> Unique dataConWorkerUnique u = incrUnique u dataConTyRepNameUnique u = stepUnique u 2 -------------------------------------------------- mkPrimOpIdUnique op = mkUnique '9' (2*op) mkPrimOpWrapperUnique op = mkUnique '9' (2*op+1) mkPreludeMiscIdUnique i = mkUnique '0' i -- The "tyvar uniques" print specially nicely: a, b, c, etc. -- See pprUnique for details initTyVarUnique :: Unique initTyVarUnique = mkUnique 't' 0 mkPseudoUniqueD, mkPseudoUniqueE, mkPseudoUniqueH, mkBuiltinUnique :: Int -> Unique mkBuiltinUnique i = mkUnique 'B' i mkPseudoUniqueD i = mkUnique 'D' i -- used in NCG for getUnique on RealRegs mkPseudoUniqueE i = mkUnique 'E' i -- used in NCG spiller to create spill VirtualRegs mkPseudoUniqueH i = mkUnique 'H' i -- used in NCG spiller to create spill VirtualRegs mkRegSingleUnique, mkRegPairUnique, mkRegSubUnique, mkRegClassUnique :: Int -> Unique mkRegSingleUnique = mkUnique 'R' mkRegSubUnique = mkUnique 'S' mkRegPairUnique = mkUnique 'P' mkRegClassUnique = mkUnique 'L' mkCostCentreUnique :: Int -> Unique mkCostCentreUnique = mkUnique 'C' mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique :: FastString -> Unique -- See Note [The Unique of an OccName] in OccName mkVarOccUnique fs = mkUnique 'i' (uniqueOfFS fs) mkDataOccUnique fs = mkUnique 'd' (uniqueOfFS fs) mkTvOccUnique fs = mkUnique 'v' (uniqueOfFS fs) mkTcOccUnique fs = mkUnique 'c' (uniqueOfFS fs) initExitJoinUnique :: Unique initExitJoinUnique = mkUnique 's' 0
sdiehl/ghc
compiler/basicTypes/Unique.hs
bsd-3-clause
15,888
0
12
3,898
1,920
1,077
843
167
3
{-# OPTIONS_GHC -Wall #-} module DFS where import Types import Unify import Control.Monad (forM, liftM) import Control.Monad.Error (strMsg, throwError) import Control.Monad.State (gets) import Data.Maybe (catMaybes) --import Debug.Trace getMatchingRules :: Compound -> Manti [(Rule, Substs)] --getMatchingRules c | trace ("getMatchingRule " ++ show c) False = undefined getMatchingRules (Compound fName args) = do rls <- gets rules let rls' = lookupRules fName (length args) rls rinsts <- mapM instantiate rls' return $ catMaybes $ flip map rinsts $ \r@(Rule (RHead _ rargs) _) -> case unifyArgs nullSubst args rargs of Nothing -> Nothing Just ss -> Just (r, ss) where lookupRules :: Atom -> Int -> [Rule] -> [Rule] lookupRules name arity = filter (\(Rule (RHead fname rargs) _) -> name == fname && length rargs == arity) unifyArgs :: Substs -> [Term] -> [Term] -> Maybe Substs unifyArgs ss [] [] = Just ss unifyArgs ss (t1:t1r) (t2:t2r) = case unify ss (apply ss t1) (apply ss t2) of Left _ -> Nothing Right ss' -> unifyArgs ss' t1r t2r solve :: [Query] -> Manti [Substs] solve [] = return [nullSubst] solve (Query (Compound (Atom "not") [arg]):gs) = case arg of TComp comp -> do ss <- solve [Query comp] --trace ("ss in `not': " ++ show ss) (return ()) if null ss then solve gs else return [] term -> throwError . strMsg $ "not arg is not compound: " ++ show term solve goals = do bs <- branch goals --trace ("bs: " ++ show bs) (return ()) liftM concat $ forM bs $ \(s, goals') -> do solutions <- solve goals' mapM (unionSubsts' s) solutions branch :: [Query] -> Manti [(Substs, [Query])] branch [] = return [] branch (Query c:rest) = do rls <- getMatchingRules c --trace ("matching rules: " ++ show rls) (return ()) --trace ("rest: " ++ show rest) (return ()) return $ flip map rls $ \(Rule _ (RBody conjs), ss) -> (ss, apply ss $ map Query conjs ++ rest)
osa1/MANTI
src/DFS.hs
bsd-3-clause
2,117
0
13
585
766
390
376
44
4
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Data.Text as Text import Graphics.Blank import Paths_blank_canvas_examples (getDataDir) -- A bare-bones demonstration of loading and playing/pausing an audio file. main :: IO () main = do dat <- getDataDir blankCanvas 3000 { events = ["mousedown"], root = dat } $ \context -> -- The Audio data type works with both local files and URLs -- startLoop context "http://upload.wikimedia.org/wikipedia/en/d/df/Florence_Foster_Jenkins_H%C3%B6lle_Rache.ogg" startLoop context "music/sonata.ogg" data Play = Playing | Paused deriving (Eq,Ord,Show) swap :: Play -> Play swap Playing = Paused swap Paused = Playing startLoop context filename = do music <- send context $ newAudio filename loop context music Playing loop :: DeviceContext -> CanvasAudio -> Play -> IO () loop context audio play = do send context $ do let (w,h) = (width context, height context) clearRect (0,0,w,h) lineWidth 1 font "30pt Calibri" -- This music sure is loud, better make it a bit softer. setVolumeAudio(audio,0.9) -- Everyone likes faster music, let's make it twice as fast setPlaybackRateAudio(audio,2.0) -- Play/pause the audio depend in which state it's in if (play == Playing) then do fillText("Click screen to play audio",50,50) pauseAudio audio else do fillText("Click screen to pause audio",50,50) playAudio audio -- display the current time -- TODO: use threading so that the current time can continuously update while -- waiting for a mouse click time <- currentTimeAudio audio fillText(Text.append "Current Time: " (Text.pack $ show time),50,90) -- wait for mouse click event <- wait context case ePageXY event of -- if no mouse location, ignore, and redraw Nothing -> loop context audio play Just (_,_) -> loop context audio (swap play)
ku-fpg/blank-canvas
examples/audio/Main.hs
bsd-3-clause
1,972
0
15
452
474
243
231
40
3
module CF where -- http://rosettacode.org/wiki/Continued_fraction/Arithmetic/G(matrix_NG,_Contined_Fraction_N)#NG -- represents the homographic transform -- a1*z + a -- f(z) --> -------- -- b1*z + b import Data.Natural import Data.List (inits) data NG = NG {a1 :: Natural, a :: Natural, b1 :: Natural, b :: Natural} deriving Show output :: NG -> Bool output (NG _ _ 0 _) = error "b1 == 0" output (NG _ _ _ 0) = error "b == 0" output (NG a1 a b1 b) = div a b == div a1 b1 term :: NG -> Natural term (NG _ _ _ 0) = error "b == 0" term (NG a1 a b1 b) = div a b ingress :: NG -> Natural -> NG ingress (NG a1 a b1 b) t = (NG (a + t * a1) a1 (b + t * b1) b1) inf_ingress :: NG -> NG inf_ingress (NG a1 _ b1 _) = NG a1 a1 b1 b1 egress :: NG -> Natural -> NG egress (NG a1 a b1 b) t | t * b > a = error "t * b > a" | t * b1 > a1 = error "t * b1 > a1" | otherwise = NG b1 b (a1 - t * b1) (a - t * b) type CF = [Natural] ng_apply :: NG -> CF -> CF ng_apply (NG _ _ 0 0) _ = [] ng_apply op@(NG a1 a b1 0) [] = ng_apply (inf_ingress op) [] ng_apply op@(NG a1 a 0 b) [] = ng_apply (inf_ingress op) [] ng_apply op@(NG a1 a b1 b) [] | output op = let t = term op in t : (ng_apply (inf_ingress (egress op t)) []) | otherwise = ng_apply (inf_ingress op) [] ng_apply op@(NG a1 a b1 0) (x : xs) = ng_apply (ingress op x) xs ng_apply op@(NG a1 a 0 b) (x : xs) = ng_apply (ingress op x) xs ng_apply op@(NG a1 a b1 b) (x : xs) | output op = let t = term op in t : (ng_apply (ingress (egress op t) x) xs) | otherwise = ng_apply (ingress op x) xs sqrt2 = 1 : (repeat 2) e_constant = 2 : 1 : (e_pattern 2) where e_pattern n = n : 1 : 1 : (e_pattern (2 + n)) pi_constant :: [Natural] pi_constant = [3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, 1, 84, 2, 1, 1, 15, 3, 13, 1, 4, 2, 6, 6, 99, 1, 2, 2, 6, 3, 5, 1, 1, 6, 8, 1, 7, 1, 2, 3, 7, 1, 2, 1, 1, 12, 1, 1, 1, 3, 1, 1, 8, 1, 1, 2, 1, 6, 1, 1, 5, 2, 2, 3, 1, 2, 4, 4, 16, 1, 161, 45, 1, 22, 1, 2, 2, 1, 4, 1, 2, 24, 1, 2, 1, 3, 1, 2, 1] r2cf :: Natural -> Natural -> CF r2cf _ 0 = [] r2cf n d = q : (r2cf d r) where (q,r) = divMod n d det :: NG -> Int det (NG a1 a b1 b) = (fromIntegral (a1*b)) - (fromIntegral (a*b1)) lau :: NG -> [Natural] -> [NG] lau m xs = (map (foldl ingress m) (inits xs)) phi :: Double phi = 0.5*(1 + sqrt 5) test0 = ng_apply (NG 1 0 0 4) sqrt2 test1 = ng_apply (NG 2 1 0 2) (r2cf 13 11) test2 = ng_apply (NG 1 0 1 2) (1 : tail e_constant) -- (e-1)/(e+1)
rzil/CF-Agda
CF.hs
bsd-3-clause
2,476
0
14
642
1,507
816
691
51
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Network.Hawk.Internal.Types where import Control.Applicative import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as BL import Data.Text (Text) import Data.Time.Clock.POSIX (POSIXTime) import Network.HTTP.Types.Method (Method) import Network.Hawk.Algo -- | Identifies a particular client so that their credentials can be -- looked up. type ClientId = Text -- | Extension data included in verification hash. This can be -- anything or nothing, depending on what the application needs. type ExtData = ByteString -- | Struct for attributes which will be encoded in the Hawk -- @Authorization@ header and included in the verification. The -- terminology (and spelling) come from the original Javascript -- implementation of Hawk. data HeaderArtifacts = HeaderArtifacts { haMethod :: Method -- ^ Signed request method. -- fixme: replace host/port/resource with SplitURL , haHost :: ByteString -- ^ Request host. , haPort :: Maybe Int -- ^ Request port. , haResource :: ByteString -- ^ Request path and query params. , haId :: ClientId -- ^ Client identifier. , haTimestamp :: POSIXTime -- ^ Time of request. , haNonce :: ByteString -- ^ Nonce value. , haMac :: ByteString -- ^ Entire header hash. , haHash :: Maybe ByteString -- ^ Payload hash. , haExt :: Maybe ExtData -- ^ Optional application-specific data. , haApp :: Maybe Text -- ^ Oz application, Iron-encoded. , haDlg :: Maybe Text -- ^ Oz delegated-by application. } deriving (Show, Eq) ---------------------------------------------------------------------------- -- | Value of @Content-Type@ HTTP headers. type ContentType = ByteString -- fixme: CI ByteString -- | Payload data and content type bundled up for convenience. data PayloadInfo = PayloadInfo { payloadContentType :: ContentType , payloadData :: BL.ByteString } deriving Show ---------------------------------------------------------------------------- -- | Authorization attributes for a Hawk message. This is generated by -- 'Network.Hawk.Client.message' and verified by -- 'Network.Hawk.Server.authenticateMessage'. data MessageAuth = MessageAuth { msgId :: ClientId -- ^ User identifier. , msgTimestamp :: POSIXTime -- ^ Message time. , msgNonce :: ByteString -- ^ Nonce string. , msgHash :: ByteString -- ^ Message hash. , msgMac :: ByteString -- ^ Hash of all message parameters. } deriving (Show, Eq) ---------------------------------------------------------------------------- -- | Represents the @WWW-Authenticate@ header which the server uses to -- respond when the client isn't authenticated. data WwwAuthenticateHeader = WwwAuthenticateHeader { wahError :: ByteString -- ^ Error message , wahTs :: Maybe POSIXTime -- ^ Server's timestamp , wahTsm :: Maybe ByteString -- ^ Timestamp mac } deriving (Show, Eq) -- | Represents the @Server-Authorization@ header which the server -- sends back to the client. data ServerAuthorizationHeader = ServerAuthorizationHeader { sahMac :: ByteString -- ^ Hash of all response parameters. , sahHash :: Maybe ByteString -- ^ Optional payload hash. , sahExt :: Maybe ExtData -- ^ Optional application-specific data. } deriving (Show, Eq)
rvl/hsoz
src/Network/Hawk/Internal/Types.hs
bsd-3-clause
3,669
0
9
948
407
267
140
47
0